context-mode 1.0.147 → 1.0.149

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.
package/server.bundle.mjs CHANGED
@@ -1,14 +1,14 @@
1
1
  #!/usr/bin/env node
2
- var WE=Object.create;var Su=Object.defineProperty;var KE=Object.getOwnPropertyDescriptor;var GE=Object.getOwnPropertyNames;var JE=Object.getPrototypeOf,YE=Object.prototype.hasOwnProperty;var ce=(t,e)=>()=>(t&&(e=t(t=0)),e);var R=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ue=(t,e)=>{for(var r in e)Su(t,r,{get:e[r],enumerable:!0})},XE=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GE(e))!YE.call(t,o)&&o!==r&&Su(t,o,{get:()=>e[o],enumerable:!(n=KE(e,o))||n.enumerable});return t};var Fh=(t,e,r)=>(r=t!=null?WE(JE(t)):{},XE(e||!t||!t.__esModule?Su(r,"default",{value:t,enumerable:!0}):r,t));var Hs=R(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Ls=class{};de._CodeOrName=Ls;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Nn=class extends Ls{constructor(e){if(super(),!de.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}}};de.Name=Nn;var Ot=class extends Ls{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Nn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};de._Code=Ot;de.nil=new Ot("");function z_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)op(r,e[n]),r.push(t[++n]);return new Ot(r)}de._=z_;var np=new Ot("+");function L_(t,...e){let r=[Us(t[0])],n=0;for(;n<e.length;)r.push(np),op(r,e[n]),r.push(np,Us(t[++n]));return G0(r),new Ot(r)}de.str=L_;function op(t,e){e instanceof Ot?t.push(...e._items):e instanceof Nn?t.push(e):t.push(X0(e))}de.addCodeArg=op;function G0(t){let e=1;for(;e<t.length-1;){if(t[e]===np){let r=J0(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function J0(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Nn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Nn))return`"${t}${e.slice(1)}`}function Y0(t,e){return e.emptyStr()?t:t.emptyStr()?e:L_`${t}${e}`}de.strConcat=Y0;function X0(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Us(Array.isArray(t)?t.join(","):t)}function Q0(t){return new Ot(Us(t))}de.stringify=Q0;function Us(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Us;function e$(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new Ot(`.${t}`):z_`[${t}]`}de.getProperty=e$;function t$(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new Ot(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=t$;function r$(t){return new Ot(t.toString())}de.regexpCode=r$});var ap=R(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.ValueScope=mt.ValueScopeName=mt.Scope=mt.varKinds=mt.UsedValueState=void 0;var ft=Hs(),sp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},za;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(za||(mt.UsedValueState=za={}));mt.varKinds={const:new ft.Name("const"),let:new ft.Name("let"),var:new ft.Name("var")};var La=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof ft.Name?e:this.name(e)}name(e){return new ft.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}}};mt.Scope=La;var Ua=class extends ft.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,ft._)`.${new ft.Name(r)}[${n}]`}};mt.ValueScopeName=Ua;var n$=(0,ft._)`\n`,ip=class extends La{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?n$:ft.nil}}get(){return this._scope}name(e){return new Ua(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let 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,ft._)`${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=ft.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,za.Started);let l=r(u);if(l){let d=this.opts.es5?mt.varKinds.var:mt.varKinds.const;s=(0,ft._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,ft._)`${s}${l}${this.opts._n}`;else throw new sp(u);c.set(u,za.Completed)})}return s}};mt.ValueScope=ip});var Q=R(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ae=Hs(),Wt=ap(),Wr=Hs();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return Wr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return Wr.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return Wr.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return Wr.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return Wr.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return Wr.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return Wr.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return Wr.Name}});var qa=ap();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return qa.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return qa.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return qa.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return qa.varKinds}});ee.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var Er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},cp=class extends Er{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Wt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ro(this.rhs,e,r)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},Ha=class extends Er{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 ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ro(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return Za(e,this.rhs)}},up=class extends Ha{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},lp=class extends Er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},dp=class extends Er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},pp=class extends Er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},fp=class extends Er{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Ro(this.code,e,r),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},Fs=class extends Er{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)||(o$(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>jn(e,r.names),{})}},wr=class extends Fs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},mp=class extends Fs{},Po=class extends wr{};Po.kind="else";var Dn=class t extends wr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Po(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(U_(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Ro(this.condition,e,r),this}get names(){let e=super.names;return Za(e,this.condition),this.else&&jn(e,this.else.names),e}};Dn.kind="if";var Mn=class extends wr{};Mn.kind="for";var hp=class extends Mn{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Ro(this.iteration,e,r),this}get names(){return jn(super.names,this.iteration.names)}},gp=class extends Mn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Wt.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=Za(super.names,this.from);return Za(e,this.to)}},Fa=class extends Mn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Ro(this.iterable,e,r),this}get names(){return jn(super.names,this.iterable.names)}},Zs=class extends wr{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)}};Zs.kind="func";var qs=class extends Fs{render(e){return"return "+super.render(e)}};qs.kind="return";var yp=class extends wr{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&&jn(e,this.catch.names),this.finally&&jn(e,this.finally.names),e}},Bs=class extends wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Bs.kind="catch";var Vs=class extends wr{render(e){return"finally"+super.render(e)}};Vs.kind="finally";var _p=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
3
- `:""},this._extScope=e,this._scope=new Wt.Scope({parent:e}),this._nodes=[new mp]}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 cp(e,s,n)),s}const(e,r,n){return this._def(Wt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Wt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Wt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Ha(e,r,n))}add(e,r){return this._leafNode(new up(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new fp(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,ae.addCodeArg)(r,o));return r.push("}"),new ae._Code(r)}if(e,r,n){if(this._blockNode(new Dn(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 Dn(e))}else(){return this._elseNode(new Po)}endIf(){return this._endBlockNode(Dn,Po)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new hp(e),r)}forRange(e,r,n,o,s=this.opts.es5?Wt.varKinds.var:Wt.varKinds.let){let i=this._scope.toName(e);return this._for(new gp(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Wt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ae.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(s,(0,ae._)`${i}[${a}]`),n(s)})}return this._for(new Fa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Wt.varKinds.var:Wt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Fa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Mn)}label(e){return this._leafNode(new lp(e))}break(e){return this._leafNode(new dp(e))}return(e){let r=new qs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(qs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new yp;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Bs(s),r(s)}return n&&(this._currNode=o.finally=new Vs,this.code(n)),this._endBlockNode(Bs,Vs)}throw(e){return this._leafNode(new pp(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=ae.nil,n,o){return this._blockNode(new Zs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Zs)}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 Dn))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}};ee.CodeGen=_p;function jn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Za(t,e){return e instanceof ae._CodeOrName?jn(t,e.names):t}function Ro(t,e,r){if(t instanceof ae.Name)return n(t);if(!o(t))return t;return new ae._Code(t._items.reduce((s,i)=>(i instanceof ae.Name&&(i=n(i)),i instanceof ae._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 ae._Code&&s._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function o$(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function U_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${vp(t)}`}ee.not=U_;var s$=H_(ee.operators.AND);function i$(...t){return t.reduce(s$)}ee.and=i$;var a$=H_(ee.operators.OR);function c$(...t){return t.reduce(a$)}ee.or=c$;function H_(t){return(e,r)=>e===ae.nil?r:r===ae.nil?e:(0,ae._)`${vp(e)} ${t} ${vp(r)}`}function vp(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var ue=R(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.checkStrictMode=te.getErrorPath=te.Type=te.useFunc=te.setEvaluated=te.evaluatedPropsToName=te.mergeEvaluated=te.eachItem=te.unescapeJsonPointer=te.escapeJsonPointer=te.escapeFragment=te.unescapeFragment=te.schemaRefOrVal=te.schemaHasRulesButRef=te.schemaHasRules=te.checkUnknownRules=te.alwaysValidSchema=te.toHash=void 0;var ge=Q(),u$=Hs();function l$(t){let e={};for(let r of t)e[r]=!0;return e}te.toHash=l$;function d$(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(q_(t,e),!B_(e,t.self.RULES.all))}te.alwaysValidSchema=d$;function q_(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]||K_(t,`unknown keyword: "${s}"`)}te.checkUnknownRules=q_;function B_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}te.schemaHasRules=B_;function p$(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}te.schemaHasRulesButRef=p$;function f$({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ge._)`${r}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(n)}`}te.schemaRefOrVal=f$;function m$(t){return V_(decodeURIComponent(t))}te.unescapeFragment=m$;function h$(t){return encodeURIComponent(xp(t))}te.escapeFragment=h$;function xp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}te.escapeJsonPointer=xp;function V_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}te.unescapeJsonPointer=V_;function g$(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}te.eachItem=g$;function F_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ge.Name?(s instanceof ge.Name?t(o,s,i):e(o,s,i),i):s instanceof ge.Name?(e(o,i,s),s):r(s,i);return a===ge.Name&&!(c instanceof ge.Name)?n(o,c):c}}te.mergeEvaluated={props:F_({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ge._)`${r} || {}`).code((0,ge._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ge._)`${r} || {}`),Sp(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:W_}),items:F_({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ge._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ge._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function W_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ge._)`{}`);return e!==void 0&&Sp(t,r,e),r}te.evaluatedPropsToName=W_;function Sp(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(n)}`,!0))}te.setEvaluated=Sp;var Z_={};function y$(t,e){return t.scopeValue("func",{ref:e,code:Z_[e.code]||(Z_[e.code]=new u$._Code(e.code))})}te.useFunc=y$;var bp;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(bp||(te.Type=bp={}));function _$(t,e,r){if(t instanceof ge.Name){let n=e===bp.Num;return r?n?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:n?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ge.getProperty)(t).toString():"/"+xp(t)}te.getErrorPath=_$;function K_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}te.checkStrictMode=K_});var Tr=R(kp=>{"use strict";Object.defineProperty(kp,"__esModule",{value:!0});var Ye=Q(),v$={data:new Ye.Name("data"),valCxt:new Ye.Name("valCxt"),instancePath:new Ye.Name("instancePath"),parentData:new Ye.Name("parentData"),parentDataProperty:new Ye.Name("parentDataProperty"),rootData:new Ye.Name("rootData"),dynamicAnchors:new Ye.Name("dynamicAnchors"),vErrors:new Ye.Name("vErrors"),errors:new Ye.Name("errors"),this:new Ye.Name("this"),self:new Ye.Name("self"),scope:new Ye.Name("scope"),json:new Ye.Name("json"),jsonPos:new Ye.Name("jsonPos"),jsonLen:new Ye.Name("jsonLen"),jsonPart:new Ye.Name("jsonPart")};kp.default=v$});var Ws=R(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.extendErrors=Xe.resetErrorsCount=Xe.reportExtraError=Xe.reportError=Xe.keyword$DataError=Xe.keywordError=void 0;var le=Q(),Ba=ue(),nt=Tr();Xe.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};Xe.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function b$(t,e=Xe.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Y_(t,e,r);n??(i||a)?G_(s,c):J_(o,(0,le._)`[${c}]`)}Xe.reportError=b$;function x$(t,e=Xe.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Y_(t,e,r);G_(o,a),s||i||J_(n,nt.default.vErrors)}Xe.reportExtraError=x$;function S$(t,e){t.assign(nt.default.errors,e),t.if((0,le._)`${nt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${nt.default.vErrors}.length`,e),()=>t.assign(nt.default.vErrors,null)))}Xe.resetErrorsCount=S$;function k$({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,nt.default.errors,a=>{t.const(i,(0,le._)`${nt.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(nt.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,r),t.assign((0,le._)`${i}.data`,n))})}Xe.extendErrors=k$;function G_(t,e){let r=t.const("err",e);t.if((0,le._)`${nt.default.vErrors} === null`,()=>t.assign(nt.default.vErrors,(0,le._)`[${r}]`),(0,le._)`${nt.default.vErrors}.push(${r})`),t.code((0,le._)`${nt.default.errors}++`)}function J_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,le._)`new ${t.ValidationError}(${e})`):(r.assign((0,le._)`${n}.errors`,e),r.return(!1))}var zn={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function Y_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,le._)`{}`:E$(t,e,r)}function E$(t,e,r={}){let{gen:n,it:o}=t,s=[w$(o,r),T$(t,r)];return P$(t,e,s),n.object(...s)}function w$({errorPath:t},{instancePath:e}){let r=e?(0,le.str)`${t}${(0,Ba.getErrorPath)(e,Ba.Type.Str)}`:t;return[nt.default.instancePath,(0,le.strConcat)(nt.default.instancePath,r)]}function T$({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,le.str)`${e}/${t}`;return r&&(o=(0,le.str)`${o}${(0,Ba.getErrorPath)(r,Ba.Type.Str)}`),[zn.schemaPath,o]}function P$(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([zn.keyword,o],[zn.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&n.push([zn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([zn.schema,i],[zn.parentSchema,(0,le._)`${l}${d}`],[nt.default.data,s]),u&&n.push([zn.propertyName,u])}});var Q_=R($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0});$o.boolOrEmptySchema=$o.topBoolOrEmptySchema=void 0;var R$=Ws(),$$=Q(),C$=Tr(),O$={message:"boolean schema is false"};function I$(t){let{gen:e,schema:r,validateName:n}=t;r===!1?X_(t,!1):typeof r=="object"&&r.$async===!0?e.return(C$.default.data):(e.assign((0,$$._)`${n}.errors`,null),e.return(!0))}$o.topBoolOrEmptySchema=I$;function A$(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),X_(t)):r.var(e,!0)}$o.boolOrEmptySchema=A$;function X_(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,R$.reportError)(o,O$,void 0,e)}});var Ep=R(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.getRules=Co.isJSONType=void 0;var N$=["string","number","integer","boolean","null","object","array"],D$=new Set(N$);function M$(t){return typeof t=="string"&&D$.has(t)}Co.isJSONType=M$;function j$(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Co.getRules=j$});var wp=R(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.shouldUseRule=Kr.shouldUseGroup=Kr.schemaHasRulesForType=void 0;function z$({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ev(t,n)}Kr.schemaHasRulesForType=z$;function ev(t,e){return e.rules.some(r=>tv(t,r))}Kr.shouldUseGroup=ev;function tv(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))}Kr.shouldUseRule=tv});var Ks=R(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.reportTypeError=Qe.checkDataTypes=Qe.checkDataType=Qe.coerceAndCheckDataType=Qe.getJSONTypes=Qe.getSchemaTypes=Qe.DataType=void 0;var L$=Ep(),U$=wp(),H$=Ws(),Y=Q(),rv=ue(),Oo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Oo||(Qe.DataType=Oo={}));function F$(t){let e=nv(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}Qe.getSchemaTypes=F$;function nv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(L$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Qe.getJSONTypes=nv;function Z$(t,e){let{gen:r,data:n,opts:o}=t,s=q$(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,U$.schemaHasRulesForType)(t,e[0]));if(i){let a=Pp(e,n,o.strictNumbers,Oo.Wrong);r.if(a,()=>{s.length?B$(t,e,s):Rp(t)})}return i}Qe.coerceAndCheckDataType=Z$;var ov=new Set(["string","number","integer","boolean","null"]);function q$(t,e){return e?t.filter(r=>ov.has(r)||e==="array"&&r==="array"):[]}function B$(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,Y._)`typeof ${o}`),a=n.let("coerced",(0,Y._)`undefined`);s.coerceTypes==="array"&&n.if((0,Y._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Y._)`${o}[0]`).assign(i,(0,Y._)`typeof ${o}`).if(Pp(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,Y._)`${a} !== undefined`);for(let u of r)(ov.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Rp(t),n.endIf(),n.if((0,Y._)`${a} !== undefined`,()=>{n.assign(o,a),V$(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":n.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
4
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":n.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
5
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Y._)`+${o}`);return;case"boolean":n.elseIf((0,Y._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,Y._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Y._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
6
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function V$({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${r}]`,n))}function Tp(t,e,r,n=Oo.Correct){let o=n===Oo.Correct?Y.operators.EQ:Y.operators.NEQ,s;switch(t){case"null":return(0,Y._)`${e} ${o} null`;case"array":s=(0,Y._)`Array.isArray(${e})`;break;case"object":s=(0,Y._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,Y._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,Y._)`typeof ${e} ${o} ${t}`}return n===Oo.Correct?s:(0,Y.not)(s);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,r?(0,Y._)`isFinite(${e})`:Y.nil)}}Qe.checkDataType=Tp;function Pp(t,e,r,n){if(t.length===1)return Tp(t[0],e,r,n);let o,s=(0,rv.toHash)(t);if(s.array&&s.object){let i=(0,Y._)`typeof ${e} != "object"`;o=s.null?i:(0,Y._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=Y.nil;s.number&&delete s.integer;for(let i in s)o=(0,Y.and)(o,Tp(i,e,r,n));return o}Qe.checkDataTypes=Pp;var W$={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function Rp(t){let e=K$(t);(0,H$.reportError)(e,W$)}Qe.reportTypeError=Rp;function K$(t){let{gen:e,data:r,schema:n}=t,o=(0,rv.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var iv=R(Va=>{"use strict";Object.defineProperty(Va,"__esModule",{value:!0});Va.assignDefaults=void 0;var Io=Q(),G$=ue();function J$(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)sv(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>sv(t,s,o.default))}Va.assignDefaults=J$;function sv(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Io._)`${s}${(0,Io.getProperty)(e)}`;if(o){(0,G$.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Io._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Io._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Io._)`${a} = ${(0,Io.stringify)(r)}`)}});var It=R(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var Se=Q(),$p=ue(),Gr=Tr(),Y$=ue();function X$(t,e){let{gen:r,data:n,it:o}=t;r.if(Op(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Se._)`${e}`},!0),t.error()})}me.checkReportMissingProp=X$;function Q$({gen:t,data:e,it:{opts:r}},n,o){return(0,Se.or)(...n.map(s=>(0,Se.and)(Op(t,e,s,r.ownProperties),(0,Se._)`${o} = ${s}`)))}me.checkMissingProp=Q$;function eC(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=eC;function av(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Se._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=av;function Cp(t,e,r){return(0,Se._)`${av(t)}.call(${e}, ${r})`}me.isOwnProperty=Cp;function tC(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} !== undefined`;return n?(0,Se._)`${o} && ${Cp(t,e,r)}`:o}me.propertyInData=tC;function Op(t,e,r,n){let o=(0,Se._)`${e}${(0,Se.getProperty)(r)} === undefined`;return n?(0,Se.or)(o,(0,Se.not)(Cp(t,e,r))):o}me.noPropertyInData=Op;function cv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=cv;function rC(t,e){return cv(e).filter(r=>!(0,$p.alwaysValidSchema)(t,e[r]))}me.schemaProperties=rC;function nC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Se._)`${t}, ${e}, ${n}${o}`:e,d=[[Gr.default.instancePath,(0,Se.strConcat)(Gr.default.instancePath,s)],[Gr.default.parentData,i.parentData],[Gr.default.parentDataProperty,i.parentDataProperty],[Gr.default.rootData,Gr.default.rootData]];i.opts.dynamicRef&&d.push([Gr.default.dynamicAnchors,Gr.default.dynamicAnchors]);let f=(0,Se._)`${l}, ${r.object(...d)}`;return c!==Se.nil?(0,Se._)`${a}.call(${c}, ${f})`:(0,Se._)`${a}(${f})`}me.callValidateCode=nC;var oC=(0,Se._)`new RegExp`;function sC({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,Se._)`${o.code==="new RegExp"?oC:(0,Y$.useFunc)(t,o)}(${r}, ${n})`})}me.usePattern=sC;function iC(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,Se._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:$p.Type.Num},s),e.if((0,Se.not)(s),a)})}}me.validateArray=iC;function aC(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,$p.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,Se._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Se.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}me.validateUnion=aC});var dv=R(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.validateKeywordUsage=lr.validSchemaType=lr.funcKeywordCode=lr.macroKeywordCode=void 0;var ot=Q(),Ln=Tr(),cC=It(),uC=Ws();function lC(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=lv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ot.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}lr.macroKeywordCode=lC;function dC(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;fC(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=lv(n,o,u),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)h(),e.modifying&&uv(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&uv(t),g(()=>pC(t,y))}}function m(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,ot._)`await `),v=>n.assign(d,!1).if((0,ot._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,ot._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,ot._)`${l}.errors`;return n.assign(y,null),h(ot.nil),y}function h(y=e.async?(0,ot._)`await `:ot.nil){let v=c.opts.passContext?Ln.default.this:Ln.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,ot._)`${y}${(0,cC.callValidateCode)(t,l,v,_)}`,e.modifying)}function g(y){var v;n.if((0,ot.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}lr.funcKeywordCode=dC;function uv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ot._)`${n.parentData}[${n.parentDataProperty}]`))}function pC(t,e){let{gen:r}=t;r.if((0,ot._)`Array.isArray(${e})`,()=>{r.assign(Ln.default.vErrors,(0,ot._)`${Ln.default.vErrors} === null ? ${e} : ${Ln.default.vErrors}.concat(${e})`).assign(Ln.default.errors,(0,ot._)`${Ln.default.vErrors}.length`),(0,uC.extendErrors)(t)},()=>t.error())}function fC({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function lv(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,ot.stringify)(r)})}function mC(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")}lr.validSchemaType=mC;function hC({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)}}lr.validateKeywordUsage=hC});var fv=R(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.extendSubschemaMode=Jr.extendSubschemaData=Jr.getSubschema=void 0;var dr=Q(),pv=ue();function gC(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,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}${(0,dr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pv.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')}Jr.getSubschema=gC;function yC(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,f=a.let("data",(0,dr._)`${e.data}${(0,dr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,dr.str)`${u}${(0,pv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,dr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof dr.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]}}Jr.extendSubschemaData=yC;function _C(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}Jr.extendSubschemaMode=_C});var Ip=R((PZ,mv)=>{"use strict";mv.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 gv=R((RZ,hv)=>{"use strict";var Yr=hv.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Wa(e,n,o,t,"",t)};Yr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Yr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Yr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Yr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Wa(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in Yr.arrayKeywords)for(var f=0;f<d.length;f++)Wa(t,e,r,d[f],o+"/"+l+"/"+f,s,o,l,n,f)}else if(l in Yr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Wa(t,e,r,d[m],o+"/"+l+"/"+vC(m),s,o,l,n,m)}else(l in Yr.keywords||t.allKeys&&!(l in Yr.skipKeywords))&&Wa(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function vC(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Gs=R(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.getSchemaRefs=ht.resolveUrl=ht.normalizeId=ht._getFullPath=ht.getFullPath=ht.inlineRef=void 0;var bC=ue(),xC=Ip(),SC=gv(),kC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function EC(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ap(t):e?yv(t)<=e:!1}ht.inlineRef=EC;var wC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ap(t){for(let e in t){if(wC.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ap)||typeof r=="object"&&Ap(r))return!0}return!1}function yv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!kC.has(r)&&(typeof t[r]=="object"&&(0,bC.eachItem)(t[r],n=>e+=yv(n)),e===1/0))return 1/0}return e}function _v(t,e="",r){r!==!1&&(e=Ao(e));let n=t.parse(e);return vv(t,n)}ht.getFullPath=_v;function vv(t,e){return t.serialize(e).split("#")[0]+"#"}ht._getFullPath=vv;var TC=/#\/?$/;function Ao(t){return t?t.replace(TC,""):""}ht.normalizeId=Ao;function PC(t,e,r){return r=Ao(r),t.resolve(e,r)}ht.resolveUrl=PC;var RC=/^[a-z_][-a-z0-9._]*$/i;function $C(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ao(t[r]||e),s={"":o},i=_v(n,o,!1),a={},c=new Set;return SC(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=g;function y(_){let S=this.opts.uriResolver.resolve;if(_=Ao(g?S(g,_):_),c.has(_))throw l(_);c.add(_);let T=this.refs[_];return typeof T=="string"&&(T=this.refs[T]),typeof T=="object"?u(d,T.schema,_):_!==Ao(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!RC.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(d,f,m){if(f!==void 0&&!xC(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}ht.getSchemaRefs=$C});var Xs=R(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.getData=Xr.KeywordCxt=Xr.validateFunctionCode=void 0;var Ev=Q_(),bv=Ks(),Dp=wp(),Ka=Ks(),CC=iv(),Ys=dv(),Np=fv(),U=Q(),G=Tr(),OC=Gs(),Pr=ue(),Js=Ws();function IC(t){if(Pv(t)&&(Rv(t),Tv(t))){DC(t);return}wv(t,()=>(0,Ev.topBoolOrEmptySchema)(t))}Xr.validateFunctionCode=IC;function wv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,U._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${xv(r,o)}`),NC(t,o),t.code(s)}):t.func(e,(0,U._)`${G.default.data}, ${AC(o)}`,n.$async,()=>t.code(xv(r,o)).code(s))}function AC(t){return(0,U._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,U._)`, ${G.default.dynamicAnchors}={}`:U.nil}}={}`}function NC(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,U._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,U._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,U._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,U._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,U._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,U._)`""`),t.var(G.default.parentData,(0,U._)`undefined`),t.var(G.default.parentDataProperty,(0,U._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,U._)`{}`)})}function DC(t){let{schema:e,opts:r,gen:n}=t;wv(t,()=>{r.$comment&&e.$comment&&Cv(t),UC(t),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&MC(t),$v(t),ZC(t)})}function MC(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,U._)`${r}.evaluated`),e.if((0,U._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${t.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${t.evaluated}.items`,(0,U._)`undefined`))}function xv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}function jC(t,e){if(Pv(t)&&(Rv(t),Tv(t))){zC(t,e);return}(0,Ev.boolOrEmptySchema)(t,e)}function Tv({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 Pv(t){return typeof t.schema!="boolean"}function zC(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Cv(t),HC(t),FC(t);let s=n.const("_errs",G.default.errors);$v(t,s),n.var(e,(0,U._)`${s} === ${G.default.errors}`)}function Rv(t){(0,Pr.checkUnknownRules)(t),LC(t)}function $v(t,e){if(t.opts.jtd)return Sv(t,[],!1,e);let r=(0,bv.getSchemaTypes)(t.schema),n=(0,bv.coerceAndCheckDataType)(t,r);Sv(t,r,!n,e)}function LC(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Pr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function UC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Pr.checkStrictMode)(t,"default is ignored in the schema root")}function HC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,OC.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function FC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cv({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,U._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,U.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,U._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function ZC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,U._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,U._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,G.default.vErrors),s.unevaluated&&qC(t),e.return((0,U._)`${G.default.errors} === 0`))}function qC({gen:t,evaluated:e,props:r,items:n}){r instanceof U.Name&&t.assign((0,U._)`${e}.props`,r),n instanceof U.Name&&t.assign((0,U._)`${e}.items`,n)}function Sv(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,Pr.schemaHasRulesButRef)(s,l))){o.block(()=>Iv(t,"$ref",l.all.$ref.definition));return}c.jtd||BC(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,Dp.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Ka.checkDataType)(f.type,i,c.strictNumbers)),kv(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,Ka.reportTypeError)(t)),o.endIf()):kv(t,f),a||o.if((0,U._)`${G.default.errors} === ${n||0}`))}}function kv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,CC.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Dp.shouldUseRule)(n,s)&&Iv(t,s.keyword,s.definition,e.type)})}function BC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(VC(t,e),t.opts.allowUnionTypes||WC(t,e),KC(t,t.dataTypes))}function VC(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ov(t.dataTypes,r)||Mp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),JC(t,e)}}function WC(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Mp(t,"use allowUnionTypes to allow union type keyword")}function KC(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Dp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>GC(e,i))&&Mp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function GC(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ov(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JC(t,e){let r=[];for(let n of t.dataTypes)Ov(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Mp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Pr.checkStrictMode)(t,e,t.opts.strictTypes)}var Ga=class{constructor(e,r,n){if((0,Ys.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Pr.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",Av(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ys.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",G.default.errors))}result(e,r,n){this.failResult((0,U.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,U.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,U._)`${r} !== undefined && (${(0,U.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Js.reportExtraError:Js.reportError)(this,this.def.error,r)}$dataError(){(0,Js.reportError)(this,this.def.$dataError||Js.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Js.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=U.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,U.or)((0,U._)`${o} === undefined`,r)),e!==U.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,U.or)(i(),a());function i(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,U._)`${(0,Ka.checkDataTypes)(c,r,s.opts.strictNumbers,Ka.DataType.Wrong)}`}return U.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,U._)`!${c}(${r})`}return U.nil}}subschema(e,r){let n=(0,Np.getSubschema)(this.it,e);(0,Np.extendSubschemaData)(n,this.it,e),(0,Np.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return jC(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Pr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Pr.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,U.Name)),!0}};Xr.KeywordCxt=Ga;function Iv(t,e,r,n){let o=new Ga(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ys.funcKeywordCode)(o,r):"macro"in r?(0,Ys.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ys.funcKeywordCode)(o,r)}var YC=/^\/(?:[^~]|~0|~1)*$/,XC=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Av(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!YC.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=XC.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,U._)`${s}${(0,U.getProperty)((0,Pr.unescapeJsonPointer)(u))}`,i=(0,U._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Xr.getData=Av});var Ja=R(zp=>{"use strict";Object.defineProperty(zp,"__esModule",{value:!0});var jp=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};zp.default=jp});var Qs=R(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var Lp=Gs(),Up=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Lp.resolveUrl)(e,r,n),this.missingSchema=(0,Lp.normalizeId)((0,Lp.getFullPath)(e,this.missingRef))}};Hp.default=Up});var Xa=R(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.resolveSchema=At.getCompilingSchema=At.resolveRef=At.compileSchema=At.SchemaEnv=void 0;var Kt=Q(),QC=Ja(),Un=Tr(),Gt=Gs(),Nv=ue(),eO=Xs(),No=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,Gt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};At.SchemaEnv=No;function Zp(t){let e=Dv.call(this,t);if(e)return e;let r=(0,Gt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Kt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:QC.default,code:(0,Kt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Un.default.data,parentData:Un.default.parentData,parentDataProperty:Un.default.parentDataProperty,dataNames:[Un.default.data],dataPathArr:[Kt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Kt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Kt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Kt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,eO.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Un.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Un.default.self}`,`${Un.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;m.evaluated={props:p instanceof Kt.Name?void 0:p,items:h instanceof Kt.Name?void 0:h,dynamicProps:p instanceof Kt.Name,dynamicItems:h instanceof Kt.Name},m.source&&(m.source.evaluated=(0,Kt.stringify)(m.evaluated))}return t.validate=m,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)}}At.compileSchema=Zp;function tO(t,e,r){var n;r=(0,Gt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=oO.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 No({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=rO.call(this,s)}At.resolveRef=tO;function rO(t){return(0,Gt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Zp.call(this,t)}function Dv(t){for(let e of this._compilations)if(nO(e,t))return e}At.getCompilingSchema=Dv;function nO(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function oO(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Ya.call(this,t,e)}function Ya(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Gt._getFullPath)(this.opts.uriResolver,r),o=(0,Gt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Fp.call(this,r,t);let s=(0,Gt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ya.call(this,t,i);return typeof a?.schema!="object"?void 0:Fp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Zp.call(this,i),s===(0,Gt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Gt.resolveUrl)(this.opts.uriResolver,o,u)),new No({schema:a,schemaId:c,root:t,baseId:o})}return Fp.call(this,r,i)}}At.resolveSchema=Ya;var sO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Fp(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,Nv.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!sO.has(a)&&u&&(e=(0,Gt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Nv.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Gt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Ya.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new No({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Mv=R((NZ,iO)=>{iO.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Bp=R((DZ,Uv)=>{"use strict";var aO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zv=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);function qp(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 cO=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jv(t){return t.length=0,!0}function uO(t,e,r){if(t.length){let n=qp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function lO(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=uO;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=jv}else{o.push(u);continue}}return o.length&&(a===jv?r.zone=o.join(""):i?n.push(o.join("")):n.push(qp(o))),r.address=n.join(""),r}function Lv(t){if(dO(t,":")<2)return{host:t,isIPV6:!1};let e=lO(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 dO(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function pO(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("")}function fO(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function mO(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!zv(r)){let n=Lv(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}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}Uv.exports={nonSimpleDomain:cO,recomposeAuthority:mO,normalizeComponentEncoding:fO,removeDotSegments:pO,isIPv4:zv,isUUID:aO,normalizeIPv6:Lv,stringArrayToHexStripped:qp}});var Bv=R((MZ,qv)=>{"use strict";var{isUUID:hO}=Bp(),gO=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,yO=["http","https","ws","wss","urn","urn:uuid"];function _O(t){return yO.indexOf(t)!==-1}function Vp(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 Hv(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Fv(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 vO(t){return t.secure=Vp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function bO(t){if((t.port===(Vp(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 xO(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(gO);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=Wp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function SO(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=Wp(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 kO(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!hO(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function EO(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Zv={scheme:"http",domainHost:!0,parse:Hv,serialize:Fv},wO={scheme:"https",domainHost:Zv.domainHost,parse:Hv,serialize:Fv},Qa={scheme:"ws",domainHost:!0,parse:vO,serialize:bO},TO={scheme:"wss",domainHost:Qa.domainHost,parse:Qa.parse,serialize:Qa.serialize},PO={scheme:"urn",parse:xO,serialize:SO,skipNormalize:!0},RO={scheme:"urn:uuid",parse:kO,serialize:EO,skipNormalize:!0},ec={http:Zv,https:wO,ws:Qa,wss:TO,urn:PO,"urn:uuid":RO};Object.setPrototypeOf(ec,null);function Wp(t){return t&&(ec[t]||ec[t.toLowerCase()])||void 0}qv.exports={wsIsSecure:Vp,SCHEMES:ec,isValidSchemeName:_O,getSchemeHandler:Wp}});var Kv=R((jZ,rc)=>{"use strict";var{normalizeIPv6:$O,removeDotSegments:ei,recomposeAuthority:CO,normalizeComponentEncoding:tc,isIPv4:OO,nonSimpleDomain:IO}=Bp(),{SCHEMES:AO,getSchemeHandler:Vv}=Bv();function NO(t,e){return typeof t=="string"?t=pr(Rr(t,e),e):typeof t=="object"&&(t=Rr(pr(t,e),e)),t}function DO(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Wv(Rr(t,n),Rr(e,n),n,!0);return n.skipEscape=!0,pr(o,n)}function Wv(t,e,r,n){let o={};return n||(t=Rr(pr(t,r),r),e=Rr(pr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ei(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=ei(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ei(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=ei(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function MO(t,e,r){return typeof t=="string"?(t=unescape(t),t=pr(tc(Rr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=pr(tc(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=pr(tc(Rr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=pr(tc(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function pr(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=Vv(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=CO(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=ei(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var jO=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Rr(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;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(jO);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(OO(n.host)===!1){let c=$O(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=Vv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&IO(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Kp={SCHEMES:AO,normalize:NO,resolve:DO,resolveComponent:Wv,equal:MO,serialize:pr,parse:Rr};rc.exports=Kp;rc.exports.default=Kp;rc.exports.fastUri=Kp});var Jv=R(Gp=>{"use strict";Object.defineProperty(Gp,"__esModule",{value:!0});var Gv=Kv();Gv.code='require("ajv/dist/runtime/uri").default';Gp.default=Gv});var ob=R(Ve=>{"use strict";Object.defineProperty(Ve,"__esModule",{value:!0});Ve.CodeGen=Ve.Name=Ve.nil=Ve.stringify=Ve.str=Ve._=Ve.KeywordCxt=void 0;var zO=Xs();Object.defineProperty(Ve,"KeywordCxt",{enumerable:!0,get:function(){return zO.KeywordCxt}});var Do=Q();Object.defineProperty(Ve,"_",{enumerable:!0,get:function(){return Do._}});Object.defineProperty(Ve,"str",{enumerable:!0,get:function(){return Do.str}});Object.defineProperty(Ve,"stringify",{enumerable:!0,get:function(){return Do.stringify}});Object.defineProperty(Ve,"nil",{enumerable:!0,get:function(){return Do.nil}});Object.defineProperty(Ve,"Name",{enumerable:!0,get:function(){return Do.Name}});Object.defineProperty(Ve,"CodeGen",{enumerable:!0,get:function(){return Do.CodeGen}});var LO=Ja(),tb=Qs(),UO=Ep(),ti=Xa(),HO=Q(),ri=Gs(),nc=Ks(),Yp=ue(),Yv=Mv(),FO=Jv(),rb=(t,e)=>new RegExp(t,e);rb.code="new RegExp";var ZO=["removeAdditional","useDefaults","coerceTypes"],qO=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),BO={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."},VO={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Xv=200;function WO(t){var e,r,n,o,s,i,a,c,u,l,d,f,m,p,h,g,y,v,_,S,T,I,N,O,j;let K=t.strict,k=(e=t.code)===null||e===void 0?void 0:e.optimize,z=k===!0||k===void 0?1:k||0,F=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:rb,ct=(o=t.uriResolver)!==null&&o!==void 0?o:FO.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:K)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:K)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:K)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:K)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:K)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:z,regExp:F}:{optimize:z,regExp:F},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Xv,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Xv,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(T=t.addUsedSchema)!==null&&T!==void 0?T:!0,validateSchema:(I=t.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(N=t.validateFormats)!==null&&N!==void 0?N:!0,unicodeRegExp:(O=t.unicodeRegExp)!==null&&O!==void 0?O:!0,int32range:(j=t.int32range)!==null&&j!==void 0?j:!0,uriResolver:ct}}var ni=class{constructor(e={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...WO(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new HO.ValueScope({scope:{},prefixes:qO,es5:r,lines:n}),this.logger=QO(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,UO.getRules)(),Qv.call(this,BO,e,"NOT SUPPORTED"),Qv.call(this,VO,e,"DEPRECATED","warn"),this._metaOpts=YO.call(this),e.formats&&GO.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&JO.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),KO.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Yv;n==="id"&&(o={...Yv},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 f=this._addSchema(l,d);return f.validate||i.call(this,f)}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 tb.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,ri.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=eb.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ti.SchemaEnv({schema:{},schemaId:n});if(r=ti.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=eb.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ri.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(tI.call(this,n,r),!r)return(0,Yp.eachItem)(n,s=>Jp.call(this,s)),this;nI.call(this,r);let o={...r,type:(0,nc.getJSONTypes)(r.type),schemaType:(0,nc.getJSONTypes)(r.schemaType)};return(0,Yp.eachItem)(n,o.type.length===0?s=>Jp.call(this,s,o):s=>o.type.forEach(i=>Jp.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]=nb(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,ri.normalizeId)(i||n);let u=ri.getSchemaRefs.call(this,e,n);return c=new ti.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:u}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):ti.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{ti.compileSchema.call(this,e)}finally{this.opts=r}}};ni.ValidationError=LO.default;ni.MissingRefError=tb.default;Ve.default=ni;function Qv(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 eb(t){return t=(0,ri.normalizeId)(t),this.schemas[t]||this.refs[t]}function KO(){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 GO(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function JO(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 YO(){let t={...this.opts};for(let e of ZO)delete t[e];return t}var XO={log(){},warn(){},error(){}};function QO(t){if(t===!1)return XO;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 eI=/^[a-z_$][a-z0-9_$:-]*$/i;function tI(t,e){let{RULES:r}=this;if((0,Yp.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!eI.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 Jp(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,nc.getJSONTypes)(e.type),schemaType:(0,nc.getJSONTypes)(e.schemaType)}};e.before?rI.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 rI(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 nI(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=nb(e)),t.validateSchema=this.compile(e,!0))}var oI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function nb(t){return{anyOf:[t,oI]}}});var sb=R(Xp=>{"use strict";Object.defineProperty(Xp,"__esModule",{value:!0});var sI={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Xp.default=sI});var ub=R(Hn=>{"use strict";Object.defineProperty(Hn,"__esModule",{value:!0});Hn.callRef=Hn.getValidate=void 0;var iI=Qs(),ib=It(),gt=Q(),Mo=Tr(),ab=Xa(),oc=ue(),aI={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=ab.resolveRef.call(c,u,o,r);if(l===void 0)throw new iI.default(n.opts.uriResolver,o,r);if(l instanceof ab.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return sc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return sc(t,(0,gt._)`${p}.validate`,u,u.$async)}function f(p){let h=cb(t,p);sc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,gt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:gt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function cb(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,gt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Hn.getValidate=cb;function sc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Mo.default.this:gt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,gt._)`await ${(0,ib.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,gt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,ib.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,gt._)`${p}.errors`;o.assign(Mo.default.vErrors,(0,gt._)`${Mo.default.vErrors} === null ? ${h} : ${Mo.default.vErrors}.concat(${h})`),o.assign(Mo.default.errors,(0,gt._)`${Mo.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=oc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,gt._)`${p}.evaluated.props`);s.props=oc.mergeEvaluated.props(o,y,s.props,gt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=oc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,gt._)`${p}.evaluated.items`);s.items=oc.mergeEvaluated.items(o,y,s.items,gt.Name)}}}Hn.callRef=sc;Hn.default=aI});var lb=R(Qp=>{"use strict";Object.defineProperty(Qp,"__esModule",{value:!0});var cI=sb(),uI=ub(),lI=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cI.default,uI.default];Qp.default=lI});var db=R(ef=>{"use strict";Object.defineProperty(ef,"__esModule",{value:!0});var ic=Q(),Qr=ic.operators,ac={maximum:{okStr:"<=",ok:Qr.LTE,fail:Qr.GT},minimum:{okStr:">=",ok:Qr.GTE,fail:Qr.LT},exclusiveMaximum:{okStr:"<",ok:Qr.LT,fail:Qr.GTE},exclusiveMinimum:{okStr:">",ok:Qr.GT,fail:Qr.LTE}},dI={message:({keyword:t,schemaCode:e})=>(0,ic.str)`must be ${ac[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ic._)`{comparison: ${ac[t].okStr}, limit: ${e}}`},pI={keyword:Object.keys(ac),type:"number",schemaType:"number",$data:!0,error:dI,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ic._)`${r} ${ac[e].fail} ${n} || isNaN(${r})`)}};ef.default=pI});var pb=R(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var oi=Q(),fI={message:({schemaCode:t})=>(0,oi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,oi._)`{multipleOf: ${t}}`},mI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:fI,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,oi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,oi._)`${i} !== parseInt(${i})`;t.fail$data((0,oi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};tf.default=mI});var mb=R(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});function fb(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}rf.default=fb;fb.code='require("ajv/dist/runtime/ucs2length").default'});var hb=R(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var Fn=Q(),hI=ue(),gI=mb(),yI={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Fn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Fn._)`{limit: ${t}}`},_I={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yI,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Fn.operators.GT:Fn.operators.LT,i=o.opts.unicode===!1?(0,Fn._)`${r}.length`:(0,Fn._)`${(0,hI.useFunc)(t.gen,gI.default)}(${r})`;t.fail$data((0,Fn._)`${i} ${s} ${n}`)}};nf.default=_I});var gb=R(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var vI=It(),bI=ue(),jo=Q(),xI={message:({schemaCode:t})=>(0,jo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,jo._)`{pattern: ${t}}`},SI={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:xI,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,jo._)`new RegExp`:(0,bI.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,jo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,jo._)`!${l}`)}else{let c=(0,vI.usePattern)(t,o);t.fail$data((0,jo._)`!${c}.test(${r})`)}}};of.default=SI});var yb=R(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});var si=Q(),kI={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,si.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,si._)`{limit: ${t}}`},EI={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:kI,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?si.operators.GT:si.operators.LT;t.fail$data((0,si._)`Object.keys(${r}).length ${o} ${n}`)}};sf.default=EI});var _b=R(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var ii=It(),ai=Q(),wI=ue(),TI={message:({params:{missingProperty:t}})=>(0,ai.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ai._)`{missingProperty: ${t}}`},PI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:TI,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 m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(m?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,wI.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ai.nil,d);else for(let m of r)(0,ii.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(m,p)),t.ok(p)}else e.if((0,ii.checkMissingProp)(t,r,m)),(0,ii.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,ii.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(p,(0,ii.propertyInData)(e,o,m,a.ownProperties)),e.if((0,ai.not)(p),()=>{t.error(),e.break()})},ai.nil)}}};af.default=PI});var vb=R(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var ci=Q(),RI={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,ci.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,ci._)`{limit: ${t}}`},$I={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:RI,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?ci.operators.GT:ci.operators.LT;t.fail$data((0,ci._)`${r}.length ${o} ${n}`)}};cf.default=$I});var cc=R(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var bb=Ip();bb.code='require("ajv/dist/runtime/equal").default';uf.default=bb});var xb=R(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var lf=Ks(),We=Q(),CI=ue(),OI=cc(),II={message:({params:{i:t,j:e}})=>(0,We.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,We._)`{i: ${t}, j: ${e}}`},AI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:II,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,lf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,We._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,We._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,We._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),y=(0,lf.checkDataTypes)(u,g,a.opts.strictNumbers,lf.DataType.Wrong),v=e.const("indices",(0,We._)`{}`);e.for((0,We._)`;${p}--;`,()=>{e.let(g,(0,We._)`${r}[${p}]`),e.if(y,(0,We._)`continue`),u.length>1&&e.if((0,We._)`typeof ${g} == "string"`,(0,We._)`${g} += "_"`),e.if((0,We._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,We._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,We._)`${v}[${g}] = ${p}`)})}function m(p,h){let g=(0,CI.useFunc)(e,OI.default),y=e.name("outer");e.label(y).for((0,We._)`;${p}--;`,()=>e.for((0,We._)`${h} = ${p}; ${h}--;`,()=>e.if((0,We._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};df.default=AI});var Sb=R(ff=>{"use strict";Object.defineProperty(ff,"__esModule",{value:!0});var pf=Q(),NI=ue(),DI=cc(),MI={message:"must be equal to constant",params:({schemaCode:t})=>(0,pf._)`{allowedValue: ${t}}`},jI={keyword:"const",$data:!0,error:MI,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,pf._)`!${(0,NI.useFunc)(e,DI.default)}(${r}, ${o})`):t.fail((0,pf._)`${s} !== ${r}`)}};ff.default=jI});var kb=R(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var ui=Q(),zI=ue(),LI=cc(),UI={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ui._)`{allowedValues: ${t}}`},HI={keyword:"enum",schemaType:"array",$data:!0,error:UI,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,zI.useFunc)(e,LI.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 m=e.const("vSchema",s);l=(0,ui.or)(...o.map((p,h)=>f(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,ui._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,ui._)`${u()}(${r}, ${m}[${p}])`:(0,ui._)`${r} === ${h}`}}};mf.default=HI});var Eb=R(hf=>{"use strict";Object.defineProperty(hf,"__esModule",{value:!0});var FI=db(),ZI=pb(),qI=hb(),BI=gb(),VI=yb(),WI=_b(),KI=vb(),GI=xb(),JI=Sb(),YI=kb(),XI=[FI.default,ZI.default,qI.default,BI.default,VI.default,WI.default,KI.default,GI.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},JI.default,YI.default];hf.default=XI});var yf=R(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.validateAdditionalItems=void 0;var Zn=Q(),gf=ue(),QI={message:({params:{len:t}})=>(0,Zn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Zn._)`{limit: ${t}}`},eA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:QI,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,gf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}wb(t,n)}};function wb(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Zn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Zn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,gf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Zn._)`${a} <= ${e.length}`);r.if((0,Zn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:gf.Type.Num},u),i.allErrors||r.if((0,Zn.not)(u),()=>r.break())})}}li.validateAdditionalItems=wb;li.default=eA});var _f=R(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.validateTuple=void 0;var Tb=Q(),uc=ue(),tA=It(),rA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Pb(t,"additionalItems",e);r.items=!0,!(0,uc.alwaysValidSchema)(r,e)&&t.ok((0,tA.validateArray)(t))}};function Pb(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=uc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Tb._)`${s}.length`);r.forEach((d,f)=>{(0,uc.alwaysValidSchema)(a,d)||(n.if((0,Tb._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=r.length,h=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,uc.checkStrictMode)(a,g,f.strictTuples)}}}di.validateTuple=Pb;di.default=rA});var Rb=R(vf=>{"use strict";Object.defineProperty(vf,"__esModule",{value:!0});var nA=_f(),oA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,nA.validateTuple)(t,"items")};vf.default=oA});var Cb=R(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var $b=Q(),sA=ue(),iA=It(),aA=yf(),cA={message:({params:{len:t}})=>(0,$b.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$b._)`{limit: ${t}}`},uA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cA,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,sA.alwaysValidSchema)(n,e)&&(o?(0,aA.validateAdditionalItems)(t,o):t.ok((0,iA.validateArray)(t)))}};bf.default=uA});var Ob=R(xf=>{"use strict";Object.defineProperty(xf,"__esModule",{value:!0});var Nt=Q(),lc=ue(),lA={message:({params:{min:t,max:e}})=>e===void 0?(0,Nt.str)`must contain at least ${t} valid item(s)`:(0,Nt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Nt._)`{minContains: ${t}}`:(0,Nt._)`{minContains: ${t}, maxContains: ${e}}`},dA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lA,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,Nt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,lc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,lc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,lc.alwaysValidSchema)(s,r)){let h=(0,Nt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Nt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Nt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>p(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:lc.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Nt._)`${h}++`),a===void 0?e.if((0,Nt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Nt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Nt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};xf.default=dA});var Nb=R(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateSchemaDeps=fr.validatePropertyDeps=fr.error=void 0;var Sf=Q(),pA=ue(),pi=It();fr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Sf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Sf._)`{property: ${t},
2
+ var tw=Object.create;var wu=Object.defineProperty;var rw=Object.getOwnPropertyDescriptor;var nw=Object.getOwnPropertyNames;var ow=Object.getPrototypeOf,sw=Object.prototype.hasOwnProperty;var ce=(t,e)=>()=>(t&&(e=t(t=0)),e);var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Fe=(t,e)=>{for(var r in e)wu(t,r,{get:e[r],enumerable:!0})},iw=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of nw(e))!sw.call(t,o)&&o!==r&&wu(t,o,{get:()=>e[o],enumerable:!(n=rw(e,o))||n.enumerable});return t};var Fh=(t,e,r)=>(r=t!=null?tw(ow(t)):{},iw(e||!t||!t.__esModule?wu(r,"default",{value:t,enumerable:!0}):r,t));var Zs=O(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Hs=class{};de._CodeOrName=Hs;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Dn=class extends Hs{constructor(e){if(super(),!de.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}}};de.Name=Dn;var Ot=class extends Hs{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Dn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};de._Code=Ot;de.nil=new Ot("");function z_(t,...e){let r=[t[0]],n=0;for(;n<e.length;)ap(r,e[n]),r.push(t[++n]);return new Ot(r)}de._=z_;var ip=new Ot("+");function L_(t,...e){let r=[Fs(t[0])],n=0;for(;n<e.length;)r.push(ip),ap(r,e[n]),r.push(ip,Fs(t[++n]));return n$(r),new Ot(r)}de.str=L_;function ap(t,e){e instanceof Ot?t.push(...e._items):e instanceof Dn?t.push(e):t.push(i$(e))}de.addCodeArg=ap;function n$(t){let e=1;for(;e<t.length-1;){if(t[e]===ip){let r=o$(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function o$(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Dn||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Dn))return`"${t}${e.slice(1)}`}function s$(t,e){return e.emptyStr()?t:t.emptyStr()?e:L_`${t}${e}`}de.strConcat=s$;function i$(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Fs(Array.isArray(t)?t.join(","):t)}function a$(t){return new Ot(Fs(t))}de.stringify=a$;function Fs(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=Fs;function c$(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new Ot(`.${t}`):z_`[${t}]`}de.getProperty=c$;function u$(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new Ot(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=u$;function l$(t){return new Ot(t.toString())}de.regexpCode=l$});var lp=O(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.ValueScope=ht.ValueScopeName=ht.Scope=ht.varKinds=ht.UsedValueState=void 0;var mt=Zs(),cp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ua;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ua||(ht.UsedValueState=Ua={}));ht.varKinds={const:new mt.Name("const"),let:new mt.Name("let"),var:new mt.Name("var")};var Ha=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof mt.Name?e:this.name(e)}name(e){return new mt.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}}};ht.Scope=Ha;var Fa=class extends mt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,mt._)`.${new mt.Name(r)}[${n}]`}};ht.ValueScopeName=Fa;var d$=(0,mt._)`\n`,up=class extends Ha{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?d$:mt.nil}}get(){return this._scope}name(e){return new Fa(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let 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,mt._)`${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=mt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,Ua.Started);let l=r(u);if(l){let d=this.opts.es5?ht.varKinds.var:ht.varKinds.const;s=(0,mt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,mt._)`${s}${l}${this.opts._n}`;else throw new cp(u);c.set(u,Ua.Completed)})}return s}};ht.ValueScope=up});var Q=O(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ae=Zs(),Kt=lp(),Kr=Zs();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return Kr._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return Kr.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return Kr.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return Kr.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return Kr.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return Kr.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return Kr.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return Kr.Name}});var Va=lp();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return Va.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return Va.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return Va.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return Va.varKinds}});ee.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var Er=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},dp=class extends Er{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Kt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=$o(this.rhs,e,r)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},Za=class extends Er{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 ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=$o(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return Ba(e,this.rhs)}},pp=class extends Za{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},fp=class extends Er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},mp=class extends Er{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},hp=class extends Er{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},gp=class extends Er{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=$o(this.code,e,r),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},qs=class extends Er{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)||(p$(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>zn(e,r.names),{})}},wr=class extends qs{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},yp=class extends qs{},Po=class extends wr{};Po.kind="else";var Mn=class t extends wr{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Po(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(U_(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=$o(this.condition,e,r),this}get names(){let e=super.names;return Ba(e,this.condition),this.else&&zn(e,this.else.names),e}};Mn.kind="if";var jn=class extends wr{};jn.kind="for";var _p=class extends jn{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=$o(this.iteration,e,r),this}get names(){return zn(super.names,this.iteration.names)}},vp=class extends jn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Kt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=Ba(super.names,this.from);return Ba(e,this.to)}},qa=class extends jn{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=$o(this.iterable,e,r),this}get names(){return zn(super.names,this.iterable.names)}},Bs=class extends wr{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)}};Bs.kind="func";var Vs=class extends qs{render(e){return"return "+super.render(e)}};Vs.kind="return";var xp=class extends wr{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&&zn(e,this.catch.names),this.finally&&zn(e,this.finally.names),e}},Ws=class extends wr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ws.kind="catch";var Ks=class extends wr{render(e){return"finally"+super.render(e)}};Ks.kind="finally";var bp=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
3
+ `:""},this._extScope=e,this._scope=new Kt.Scope({parent:e}),this._nodes=[new yp]}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 dp(e,s,n)),s}const(e,r,n){return this._def(Kt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Kt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Kt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Za(e,r,n))}add(e,r){return this._leafNode(new pp(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new gp(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,ae.addCodeArg)(r,o));return r.push("}"),new ae._Code(r)}if(e,r,n){if(this._blockNode(new Mn(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 Mn(e))}else(){return this._elseNode(new Po)}endIf(){return this._endBlockNode(Mn,Po)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new _p(e),r)}forRange(e,r,n,o,s=this.opts.es5?Kt.varKinds.var:Kt.varKinds.let){let i=this._scope.toName(e);return this._for(new vp(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Kt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ae.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(s,(0,ae._)`${i}[${a}]`),n(s)})}return this._for(new qa("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Kt.varKinds.var:Kt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new qa("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(jn)}label(e){return this._leafNode(new fp(e))}break(e){return this._leafNode(new mp(e))}return(e){let r=new Vs;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Vs)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new xp;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Ws(s),r(s)}return n&&(this._currNode=o.finally=new Ks,this.code(n)),this._endBlockNode(Ws,Ks)}throw(e){return this._leafNode(new hp(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=ae.nil,n,o){return this._blockNode(new Bs(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(Bs)}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 Mn))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}};ee.CodeGen=bp;function zn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Ba(t,e){return e instanceof ae._CodeOrName?zn(t,e.names):t}function $o(t,e,r){if(t instanceof ae.Name)return n(t);if(!o(t))return t;return new ae._Code(t._items.reduce((s,i)=>(i instanceof ae.Name&&(i=n(i)),i instanceof ae._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 ae._Code&&s._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function p$(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function U_(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${Sp(t)}`}ee.not=U_;var f$=H_(ee.operators.AND);function m$(...t){return t.reduce(f$)}ee.and=m$;var h$=H_(ee.operators.OR);function g$(...t){return t.reduce(h$)}ee.or=g$;function H_(t){return(e,r)=>e===ae.nil?r:r===ae.nil?e:(0,ae._)`${Sp(e)} ${t} ${Sp(r)}`}function Sp(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var ue=O(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.checkStrictMode=te.getErrorPath=te.Type=te.useFunc=te.setEvaluated=te.evaluatedPropsToName=te.mergeEvaluated=te.eachItem=te.unescapeJsonPointer=te.escapeJsonPointer=te.escapeFragment=te.unescapeFragment=te.schemaRefOrVal=te.schemaHasRulesButRef=te.schemaHasRules=te.checkUnknownRules=te.alwaysValidSchema=te.toHash=void 0;var ge=Q(),y$=Zs();function _$(t){let e={};for(let r of t)e[r]=!0;return e}te.toHash=_$;function v$(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(q_(t,e),!B_(e,t.self.RULES.all))}te.alwaysValidSchema=v$;function q_(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]||K_(t,`unknown keyword: "${s}"`)}te.checkUnknownRules=q_;function B_(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}te.schemaHasRules=B_;function x$(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}te.schemaHasRulesButRef=x$;function b$({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ge._)`${r}`}return(0,ge._)`${t}${e}${(0,ge.getProperty)(n)}`}te.schemaRefOrVal=b$;function S$(t){return V_(decodeURIComponent(t))}te.unescapeFragment=S$;function k$(t){return encodeURIComponent(Ep(t))}te.escapeFragment=k$;function Ep(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}te.escapeJsonPointer=Ep;function V_(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}te.unescapeJsonPointer=V_;function E$(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}te.eachItem=E$;function F_({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ge.Name?(s instanceof ge.Name?t(o,s,i):e(o,s,i),i):s instanceof ge.Name?(e(o,i,s),s):r(s,i);return a===ge.Name&&!(c instanceof ge.Name)?n(o,c):c}}te.mergeEvaluated={props:F_({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ge._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ge._)`${r} || {}`).code((0,ge._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ge._)`${r} || {}`),wp(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:W_}),items:F_({mergeNames:(t,e,r)=>t.if((0,ge._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ge._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ge._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ge._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function W_(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ge._)`{}`);return e!==void 0&&wp(t,r,e),r}te.evaluatedPropsToName=W_;function wp(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ge._)`${e}${(0,ge.getProperty)(n)}`,!0))}te.setEvaluated=wp;var Z_={};function w$(t,e){return t.scopeValue("func",{ref:e,code:Z_[e.code]||(Z_[e.code]=new y$._Code(e.code))})}te.useFunc=w$;var kp;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(kp||(te.Type=kp={}));function T$(t,e,r){if(t instanceof ge.Name){let n=e===kp.Num;return r?n?(0,ge._)`"[" + ${t} + "]"`:(0,ge._)`"['" + ${t} + "']"`:n?(0,ge._)`"/" + ${t}`:(0,ge._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ge.getProperty)(t).toString():"/"+Ep(t)}te.getErrorPath=T$;function K_(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}te.checkStrictMode=K_});var Tr=O(Tp=>{"use strict";Object.defineProperty(Tp,"__esModule",{value:!0});var tt=Q(),R$={data:new tt.Name("data"),valCxt:new tt.Name("valCxt"),instancePath:new tt.Name("instancePath"),parentData:new tt.Name("parentData"),parentDataProperty:new tt.Name("parentDataProperty"),rootData:new tt.Name("rootData"),dynamicAnchors:new tt.Name("dynamicAnchors"),vErrors:new tt.Name("vErrors"),errors:new tt.Name("errors"),this:new tt.Name("this"),self:new tt.Name("self"),scope:new tt.Name("scope"),json:new tt.Name("json"),jsonPos:new tt.Name("jsonPos"),jsonLen:new tt.Name("jsonLen"),jsonPart:new tt.Name("jsonPart")};Tp.default=R$});var Gs=O(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.extendErrors=rt.resetErrorsCount=rt.reportExtraError=rt.reportError=rt.keyword$DataError=rt.keywordError=void 0;var le=Q(),Wa=ue(),it=Tr();rt.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};rt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function P$(t,e=rt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=X_(t,e,r);n??(i||a)?G_(s,c):J_(o,(0,le._)`[${c}]`)}rt.reportError=P$;function $$(t,e=rt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=X_(t,e,r);G_(o,a),s||i||J_(n,it.default.vErrors)}rt.reportExtraError=$$;function C$(t,e){t.assign(it.default.errors,e),t.if((0,le._)`${it.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${it.default.vErrors}.length`,e),()=>t.assign(it.default.vErrors,null)))}rt.resetErrorsCount=C$;function O$({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,it.default.errors,a=>{t.const(i,(0,le._)`${it.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(it.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,r),t.assign((0,le._)`${i}.data`,n))})}rt.extendErrors=O$;function G_(t,e){let r=t.const("err",e);t.if((0,le._)`${it.default.vErrors} === null`,()=>t.assign(it.default.vErrors,(0,le._)`[${r}]`),(0,le._)`${it.default.vErrors}.push(${r})`),t.code((0,le._)`${it.default.errors}++`)}function J_(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,le._)`new ${t.ValidationError}(${e})`):(r.assign((0,le._)`${n}.errors`,e),r.return(!1))}var Ln={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function X_(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,le._)`{}`:I$(t,e,r)}function I$(t,e,r={}){let{gen:n,it:o}=t,s=[A$(o,r),N$(t,r)];return D$(t,e,s),n.object(...s)}function A$({errorPath:t},{instancePath:e}){let r=e?(0,le.str)`${t}${(0,Wa.getErrorPath)(e,Wa.Type.Str)}`:t;return[it.default.instancePath,(0,le.strConcat)(it.default.instancePath,r)]}function N$({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,le.str)`${e}/${t}`;return r&&(o=(0,le.str)`${o}${(0,Wa.getErrorPath)(r,Wa.Type.Str)}`),[Ln.schemaPath,o]}function D$(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([Ln.keyword,o],[Ln.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&n.push([Ln.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Ln.schema,i],[Ln.parentSchema,(0,le._)`${l}${d}`],[it.default.data,s]),u&&n.push([Ln.propertyName,u])}});var Q_=O(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.boolOrEmptySchema=Co.topBoolOrEmptySchema=void 0;var M$=Gs(),j$=Q(),z$=Tr(),L$={message:"boolean schema is false"};function U$(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Y_(t,!1):typeof r=="object"&&r.$async===!0?e.return(z$.default.data):(e.assign((0,j$._)`${n}.errors`,null),e.return(!0))}Co.topBoolOrEmptySchema=U$;function H$(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Y_(t)):r.var(e,!0)}Co.boolOrEmptySchema=H$;function Y_(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,M$.reportError)(o,L$,void 0,e)}});var Rp=O(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.getRules=Oo.isJSONType=void 0;var F$=["string","number","integer","boolean","null","object","array"],Z$=new Set(F$);function q$(t){return typeof t=="string"&&Z$.has(t)}Oo.isJSONType=q$;function B$(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Oo.getRules=B$});var Pp=O(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.shouldUseRule=Gr.shouldUseGroup=Gr.schemaHasRulesForType=void 0;function V$({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&ev(t,n)}Gr.schemaHasRulesForType=V$;function ev(t,e){return e.rules.some(r=>tv(t,r))}Gr.shouldUseGroup=ev;function tv(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))}Gr.shouldUseRule=tv});var Js=O(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.reportTypeError=nt.checkDataTypes=nt.checkDataType=nt.coerceAndCheckDataType=nt.getJSONTypes=nt.getSchemaTypes=nt.DataType=void 0;var W$=Rp(),K$=Pp(),G$=Gs(),X=Q(),rv=ue(),Io;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Io||(nt.DataType=Io={}));function J$(t){let e=nv(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}nt.getSchemaTypes=J$;function nv(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(W$.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}nt.getJSONTypes=nv;function X$(t,e){let{gen:r,data:n,opts:o}=t,s=Y$(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,K$.schemaHasRulesForType)(t,e[0]));if(i){let a=Cp(e,n,o.strictNumbers,Io.Wrong);r.if(a,()=>{s.length?Q$(t,e,s):Op(t)})}return i}nt.coerceAndCheckDataType=X$;var ov=new Set(["string","number","integer","boolean","null"]);function Y$(t,e){return e?t.filter(r=>ov.has(r)||e==="array"&&r==="array"):[]}function Q$(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,X._)`typeof ${o}`),a=n.let("coerced",(0,X._)`undefined`);s.coerceTypes==="array"&&n.if((0,X._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,X._)`${o}[0]`).assign(i,(0,X._)`typeof ${o}`).if(Cp(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,X._)`${a} !== undefined`);for(let u of r)(ov.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),Op(t),n.endIf(),n.if((0,X._)`${a} !== undefined`,()=>{n.assign(o,a),eC(t,a)});function c(u){switch(u){case"string":n.elseIf((0,X._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,X._)`"" + ${o}`).elseIf((0,X._)`${o} === null`).assign(a,(0,X._)`""`);return;case"number":n.elseIf((0,X._)`${i} == "boolean" || ${o} === null
4
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,X._)`+${o}`);return;case"integer":n.elseIf((0,X._)`${i} === "boolean" || ${o} === null
5
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,X._)`+${o}`);return;case"boolean":n.elseIf((0,X._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,X._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,X._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,X._)`${i} === "string" || ${i} === "number"
6
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,X._)`[${o}]`)}}}function eC({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,X._)`${e} !== undefined`,()=>t.assign((0,X._)`${e}[${r}]`,n))}function $p(t,e,r,n=Io.Correct){let o=n===Io.Correct?X.operators.EQ:X.operators.NEQ,s;switch(t){case"null":return(0,X._)`${e} ${o} null`;case"array":s=(0,X._)`Array.isArray(${e})`;break;case"object":s=(0,X._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,X._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,X._)`typeof ${e} ${o} ${t}`}return n===Io.Correct?s:(0,X.not)(s);function i(a=X.nil){return(0,X.and)((0,X._)`typeof ${e} == "number"`,a,r?(0,X._)`isFinite(${e})`:X.nil)}}nt.checkDataType=$p;function Cp(t,e,r,n){if(t.length===1)return $p(t[0],e,r,n);let o,s=(0,rv.toHash)(t);if(s.array&&s.object){let i=(0,X._)`typeof ${e} != "object"`;o=s.null?i:(0,X._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=X.nil;s.number&&delete s.integer;for(let i in s)o=(0,X.and)(o,$p(i,e,r,n));return o}nt.checkDataTypes=Cp;var tC={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,X._)`{type: ${t}}`:(0,X._)`{type: ${e}}`};function Op(t){let e=rC(t);(0,G$.reportError)(e,tC)}nt.reportTypeError=Op;function rC(t){let{gen:e,data:r,schema:n}=t,o=(0,rv.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var iv=O(Ka=>{"use strict";Object.defineProperty(Ka,"__esModule",{value:!0});Ka.assignDefaults=void 0;var Ao=Q(),nC=ue();function oC(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)sv(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>sv(t,s,o.default))}Ka.assignDefaults=oC;function sv(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Ao._)`${s}${(0,Ao.getProperty)(e)}`;if(o){(0,nC.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ao._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ao._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Ao._)`${a} = ${(0,Ao.stringify)(r)}`)}});var It=O(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.validateUnion=me.validateArray=me.usePattern=me.callValidateCode=me.schemaProperties=me.allSchemaProperties=me.noPropertyInData=me.propertyInData=me.isOwnProperty=me.hasPropFunc=me.reportMissingProp=me.checkMissingProp=me.checkReportMissingProp=void 0;var ke=Q(),Ip=ue(),Jr=Tr(),sC=ue();function iC(t,e){let{gen:r,data:n,it:o}=t;r.if(Np(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ke._)`${e}`},!0),t.error()})}me.checkReportMissingProp=iC;function aC({gen:t,data:e,it:{opts:r}},n,o){return(0,ke.or)(...n.map(s=>(0,ke.and)(Np(t,e,s,r.ownProperties),(0,ke._)`${o} = ${s}`)))}me.checkMissingProp=aC;function cC(t,e){t.setParams({missingProperty:e},!0),t.error()}me.reportMissingProp=cC;function av(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ke._)`Object.prototype.hasOwnProperty`})}me.hasPropFunc=av;function Ap(t,e,r){return(0,ke._)`${av(t)}.call(${e}, ${r})`}me.isOwnProperty=Ap;function uC(t,e,r,n){let o=(0,ke._)`${e}${(0,ke.getProperty)(r)} !== undefined`;return n?(0,ke._)`${o} && ${Ap(t,e,r)}`:o}me.propertyInData=uC;function Np(t,e,r,n){let o=(0,ke._)`${e}${(0,ke.getProperty)(r)} === undefined`;return n?(0,ke.or)(o,(0,ke.not)(Ap(t,e,r))):o}me.noPropertyInData=Np;function cv(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}me.allSchemaProperties=cv;function lC(t,e){return cv(e).filter(r=>!(0,Ip.alwaysValidSchema)(t,e[r]))}me.schemaProperties=lC;function dC({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ke._)`${t}, ${e}, ${n}${o}`:e,d=[[Jr.default.instancePath,(0,ke.strConcat)(Jr.default.instancePath,s)],[Jr.default.parentData,i.parentData],[Jr.default.parentDataProperty,i.parentDataProperty],[Jr.default.rootData,Jr.default.rootData]];i.opts.dynamicRef&&d.push([Jr.default.dynamicAnchors,Jr.default.dynamicAnchors]);let f=(0,ke._)`${l}, ${r.object(...d)}`;return c!==ke.nil?(0,ke._)`${a}.call(${c}, ${f})`:(0,ke._)`${a}(${f})`}me.callValidateCode=dC;var pC=(0,ke._)`new RegExp`;function fC({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,ke._)`${o.code==="new RegExp"?pC:(0,sC.useFunc)(t,o)}(${r}, ${n})`})}me.usePattern=fC;function mC(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,ke._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Ip.Type.Num},s),e.if((0,ke.not)(s),a)})}}me.validateArray=mC;function hC(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Ip.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,ke._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ke.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}me.validateUnion=hC});var dv=O(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.validateKeywordUsage=lr.validSchemaType=lr.funcKeywordCode=lr.macroKeywordCode=void 0;var at=Q(),Un=Tr(),gC=It(),yC=Gs();function _C(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=lv(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:at.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}lr.macroKeywordCode=_C;function vC(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;bC(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=lv(n,o,u),d=n.let("valid");t.block$data(d,f),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function f(){if(e.errors===!1)h(),e.modifying&&uv(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&uv(t),g(()=>xC(t,y))}}function m(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,at._)`await `),v=>n.assign(d,!1).if((0,at._)`${v} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,at._)`${v}.errors`),()=>n.throw(v))),y}function p(){let y=(0,at._)`${l}.errors`;return n.assign(y,null),h(at.nil),y}function h(y=e.async?(0,at._)`await `:at.nil){let v=c.opts.passContext?Un.default.this:Un.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,at._)`${y}${(0,gC.callValidateCode)(t,l,v,_)}`,e.modifying)}function g(y){var v;n.if((0,at.not)((v=e.valid)!==null&&v!==void 0?v:d),y)}}lr.funcKeywordCode=vC;function uv(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,at._)`${n.parentData}[${n.parentDataProperty}]`))}function xC(t,e){let{gen:r}=t;r.if((0,at._)`Array.isArray(${e})`,()=>{r.assign(Un.default.vErrors,(0,at._)`${Un.default.vErrors} === null ? ${e} : ${Un.default.vErrors}.concat(${e})`).assign(Un.default.errors,(0,at._)`${Un.default.vErrors}.length`),(0,yC.extendErrors)(t)},()=>t.error())}function bC({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function lv(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,at.stringify)(r)})}function SC(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")}lr.validSchemaType=SC;function kC({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)}}lr.validateKeywordUsage=kC});var fv=O(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.extendSubschemaMode=Xr.extendSubschemaData=Xr.getSubschema=void 0;var dr=Q(),pv=ue();function EC(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,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,dr._)`${t.schemaPath}${(0,dr.getProperty)(e)}${(0,dr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,pv.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')}Xr.getSubschema=EC;function wC(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,f=a.let("data",(0,dr._)`${e.data}${(0,dr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,dr.str)`${u}${(0,pv.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,dr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof dr.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]}}Xr.extendSubschemaData=wC;function TC(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}Xr.extendSubschemaMode=TC});var Dp=O((QZ,mv)=>{"use strict";mv.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 gv=O((eq,hv)=>{"use strict";var Yr=hv.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(){};Ga(e,n,o,t,"",t)};Yr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Yr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Yr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Yr.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 Ga(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 Yr.arrayKeywords)for(var f=0;f<d.length;f++)Ga(t,e,r,d[f],o+"/"+l+"/"+f,s,o,l,n,f)}else if(l in Yr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Ga(t,e,r,d[m],o+"/"+l+"/"+RC(m),s,o,l,n,m)}else(l in Yr.keywords||t.allKeys&&!(l in Yr.skipKeywords))&&Ga(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function RC(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Xs=O(gt=>{"use strict";Object.defineProperty(gt,"__esModule",{value:!0});gt.getSchemaRefs=gt.resolveUrl=gt.normalizeId=gt._getFullPath=gt.getFullPath=gt.inlineRef=void 0;var PC=ue(),$C=Dp(),CC=gv(),OC=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function IC(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Mp(t):e?yv(t)<=e:!1}gt.inlineRef=IC;var AC=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Mp(t){for(let e in t){if(AC.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Mp)||typeof r=="object"&&Mp(r))return!0}return!1}function yv(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!OC.has(r)&&(typeof t[r]=="object"&&(0,PC.eachItem)(t[r],n=>e+=yv(n)),e===1/0))return 1/0}return e}function _v(t,e="",r){r!==!1&&(e=No(e));let n=t.parse(e);return vv(t,n)}gt.getFullPath=_v;function vv(t,e){return t.serialize(e).split("#")[0]+"#"}gt._getFullPath=vv;var NC=/#\/?$/;function No(t){return t?t.replace(NC,""):""}gt.normalizeId=No;function DC(t,e,r){return r=No(r),t.resolve(e,r)}gt.resolveUrl=DC;var MC=/^[a-z_][-a-z0-9._]*$/i;function jC(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=No(t[r]||e),s={"":o},i=_v(n,o,!1),a={},c=new Set;return CC(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[r]=="string"&&(g=y.call(this,d[r])),v.call(this,d.$anchor),v.call(this,d.$dynamicAnchor),s[f]=g;function y(_){let b=this.opts.uriResolver.resolve;if(_=No(g?b(g,_):_),c.has(_))throw l(_);c.add(_);let E=this.refs[_];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,_):_!==No(h)&&(_[0]==="#"?(u(d,a[_],_),a[_]=d):this.refs[_]=h),_}function v(_){if(typeof _=="string"){if(!MC.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(d,f,m){if(f!==void 0&&!$C(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}gt.getSchemaRefs=jC});var ei=O(Qr=>{"use strict";Object.defineProperty(Qr,"__esModule",{value:!0});Qr.getData=Qr.KeywordCxt=Qr.validateFunctionCode=void 0;var Ev=Q_(),xv=Js(),zp=Pp(),Ja=Js(),zC=iv(),Qs=dv(),jp=fv(),H=Q(),G=Tr(),LC=Xs(),Rr=ue(),Ys=Gs();function UC(t){if(Rv(t)&&(Pv(t),Tv(t))){ZC(t);return}wv(t,()=>(0,Ev.topBoolOrEmptySchema)(t))}Qr.validateFunctionCode=UC;function wv({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,H._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{t.code((0,H._)`"use strict"; ${bv(r,o)}`),FC(t,o),t.code(s)}):t.func(e,(0,H._)`${G.default.data}, ${HC(o)}`,n.$async,()=>t.code(bv(r,o)).code(s))}function HC(t){return(0,H._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,H._)`, ${G.default.dynamicAnchors}={}`:H.nil}}={}`}function FC(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,H._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,H._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,H._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,H._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,H._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,H._)`""`),t.var(G.default.parentData,(0,H._)`undefined`),t.var(G.default.parentDataProperty,(0,H._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,H._)`{}`)})}function ZC(t){let{schema:e,opts:r,gen:n}=t;wv(t,()=>{r.$comment&&e.$comment&&Cv(t),KC(t),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&qC(t),$v(t),XC(t)})}function qC(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,H._)`${r}.evaluated`),e.if((0,H._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,H._)`${t.evaluated}.props`,(0,H._)`undefined`)),e.if((0,H._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,H._)`${t.evaluated}.items`,(0,H._)`undefined`))}function bv(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,H._)`/*# sourceURL=${r} */`:H.nil}function BC(t,e){if(Rv(t)&&(Pv(t),Tv(t))){VC(t,e);return}(0,Ev.boolOrEmptySchema)(t,e)}function Tv({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 Rv(t){return typeof t.schema!="boolean"}function VC(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Cv(t),GC(t),JC(t);let s=n.const("_errs",G.default.errors);$v(t,s),n.var(e,(0,H._)`${s} === ${G.default.errors}`)}function Pv(t){(0,Rr.checkUnknownRules)(t),WC(t)}function $v(t,e){if(t.opts.jtd)return Sv(t,[],!1,e);let r=(0,xv.getSchemaTypes)(t.schema),n=(0,xv.coerceAndCheckDataType)(t,r);Sv(t,r,!n,e)}function WC(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Rr.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function KC(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Rr.checkStrictMode)(t,"default is ignored in the schema root")}function GC(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,LC.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function JC(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Cv({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,H._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,H.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,H._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function XC(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,H._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,H._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,H._)`${n}.errors`,G.default.vErrors),s.unevaluated&&YC(t),e.return((0,H._)`${G.default.errors} === 0`))}function YC({gen:t,evaluated:e,props:r,items:n}){r instanceof H.Name&&t.assign((0,H._)`${e}.props`,r),n instanceof H.Name&&t.assign((0,H._)`${e}.items`,n)}function Sv(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,Rr.schemaHasRulesButRef)(s,l))){o.block(()=>Iv(t,"$ref",l.all.$ref.definition));return}c.jtd||QC(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,zp.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Ja.checkDataType)(f.type,i,c.strictNumbers)),kv(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,Ja.reportTypeError)(t)),o.endIf()):kv(t,f),a||o.if((0,H._)`${G.default.errors} === ${n||0}`))}}function kv(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,zC.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,zp.shouldUseRule)(n,s)&&Iv(t,s.keyword,s.definition,e.type)})}function QC(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(eO(t,e),t.opts.allowUnionTypes||tO(t,e),rO(t,t.dataTypes))}function eO(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Ov(t.dataTypes,r)||Lp(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),oO(t,e)}}function tO(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Lp(t,"use allowUnionTypes to allow union type keyword")}function rO(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,zp.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>nO(e,i))&&Lp(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function nO(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Ov(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function oO(t,e){let r=[];for(let n of t.dataTypes)Ov(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Lp(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Rr.checkStrictMode)(t,e,t.opts.strictTypes)}var Xa=class{constructor(e,r,n){if((0,Qs.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,Rr.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",Av(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Qs.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",G.default.errors))}result(e,r,n){this.failResult((0,H.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,H.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,H._)`${r} !== undefined && (${(0,H.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?Ys.reportExtraError:Ys.reportError)(this,this.def.error,r)}$dataError(){(0,Ys.reportError)(this,this.def.$dataError||Ys.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ys.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=H.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=H.nil,r=H.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,H.or)((0,H._)`${o} === undefined`,r)),e!==H.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==H.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,H.or)(i(),a());function i(){if(n.length){if(!(r instanceof H.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,H._)`${(0,Ja.checkDataTypes)(c,r,s.opts.strictNumbers,Ja.DataType.Wrong)}`}return H.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,H._)`!${c}(${r})`}return H.nil}}subschema(e,r){let n=(0,jp.getSubschema)(this.it,e);(0,jp.extendSubschemaData)(n,this.it,e),(0,jp.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return BC(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Rr.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Rr.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,H.Name)),!0}};Qr.KeywordCxt=Xa;function Iv(t,e,r,n){let o=new Xa(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Qs.funcKeywordCode)(o,r):"macro"in r?(0,Qs.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Qs.funcKeywordCode)(o,r)}var sO=/^\/(?:[^~]|~0|~1)*$/,iO=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Av(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!sO.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=iO.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,H._)`${s}${(0,H.getProperty)((0,Rr.unescapeJsonPointer)(u))}`,i=(0,H._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}Qr.getData=Av});var Ya=O(Hp=>{"use strict";Object.defineProperty(Hp,"__esModule",{value:!0});var Up=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Hp.default=Up});var ti=O(qp=>{"use strict";Object.defineProperty(qp,"__esModule",{value:!0});var Fp=Xs(),Zp=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Fp.resolveUrl)(e,r,n),this.missingSchema=(0,Fp.normalizeId)((0,Fp.getFullPath)(e,this.missingRef))}};qp.default=Zp});var ec=O(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.resolveSchema=At.getCompilingSchema=At.resolveRef=At.compileSchema=At.SchemaEnv=void 0;var Gt=Q(),aO=Ya(),Hn=Tr(),Jt=Xs(),Nv=ue(),cO=ei(),Do=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,Jt.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};At.SchemaEnv=Do;function Vp(t){let e=Dv.call(this,t);if(e)return e;let r=(0,Jt.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Gt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:aO.default,code:(0,Gt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Hn.default.data,parentData:Hn.default.parentData,parentDataProperty:Hn.default.parentDataProperty,dataNames:[Hn.default.data],dataPathArr:[Gt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Gt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Gt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Gt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,cO.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Hn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Hn.default.self}`,`${Hn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:m}),m.errors=null,m.schema=t.schema,m.schemaEnv=t,t.$async&&(m.$async=!0),this.opts.code.source===!0&&(m.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;m.evaluated={props:p instanceof Gt.Name?void 0:p,items:h instanceof Gt.Name?void 0:h,dynamicProps:p instanceof Gt.Name,dynamicItems:h instanceof Gt.Name},m.source&&(m.source.evaluated=(0,Gt.stringify)(m.evaluated))}return t.validate=m,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)}}At.compileSchema=Vp;function uO(t,e,r){var n;r=(0,Jt.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=pO.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 Do({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=lO.call(this,s)}At.resolveRef=uO;function lO(t){return(0,Jt.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Vp.call(this,t)}function Dv(t){for(let e of this._compilations)if(dO(e,t))return e}At.getCompilingSchema=Dv;function dO(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function pO(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Qa.call(this,t,e)}function Qa(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Jt._getFullPath)(this.opts.uriResolver,r),o=(0,Jt.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Bp.call(this,r,t);let s=(0,Jt.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Qa.call(this,t,i);return typeof a?.schema!="object"?void 0:Bp.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Vp.call(this,i),s===(0,Jt.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,Jt.resolveUrl)(this.opts.uriResolver,o,u)),new Do({schema:a,schemaId:c,root:t,baseId:o})}return Bp.call(this,r,i)}}At.resolveSchema=Qa;var fO=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Bp(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,Nv.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!fO.has(a)&&u&&(e=(0,Jt.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Nv.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Jt.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Qa.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Do({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Mv=O((iq,mO)=>{mO.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Kp=O((aq,Uv)=>{"use strict";var hO=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zv=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);function Wp(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var gO=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jv(t){return t.length=0,!0}function yO(t,e,r){if(t.length){let n=Wp(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function _O(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=yO;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=jv}else{o.push(u);continue}}return o.length&&(a===jv?r.zone=o.join(""):i?n.push(o.join("")):n.push(Wp(o))),r.address=n.join(""),r}function Lv(t){if(vO(t,":")<2)return{host:t,isIPV6:!1};let e=_O(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 vO(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function xO(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("")}function bO(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function SO(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!zv(r)){let n=Lv(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}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}Uv.exports={nonSimpleDomain:gO,recomposeAuthority:SO,normalizeComponentEncoding:bO,removeDotSegments:xO,isIPv4:zv,isUUID:hO,normalizeIPv6:Lv,stringArrayToHexStripped:Wp}});var Bv=O((cq,qv)=>{"use strict";var{isUUID:kO}=Kp(),EO=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,wO=["http","https","ws","wss","urn","urn:uuid"];function TO(t){return wO.indexOf(t)!==-1}function Gp(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 Hv(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Fv(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 RO(t){return t.secure=Gp(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function PO(t){if((t.port===(Gp(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 $O(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(EO);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=Jp(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function CO(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=Jp(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 OO(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!kO(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function IO(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Zv={scheme:"http",domainHost:!0,parse:Hv,serialize:Fv},AO={scheme:"https",domainHost:Zv.domainHost,parse:Hv,serialize:Fv},tc={scheme:"ws",domainHost:!0,parse:RO,serialize:PO},NO={scheme:"wss",domainHost:tc.domainHost,parse:tc.parse,serialize:tc.serialize},DO={scheme:"urn",parse:$O,serialize:CO,skipNormalize:!0},MO={scheme:"urn:uuid",parse:OO,serialize:IO,skipNormalize:!0},rc={http:Zv,https:AO,ws:tc,wss:NO,urn:DO,"urn:uuid":MO};Object.setPrototypeOf(rc,null);function Jp(t){return t&&(rc[t]||rc[t.toLowerCase()])||void 0}qv.exports={wsIsSecure:Gp,SCHEMES:rc,isValidSchemeName:TO,getSchemeHandler:Jp}});var Kv=O((uq,oc)=>{"use strict";var{normalizeIPv6:jO,removeDotSegments:ri,recomposeAuthority:zO,normalizeComponentEncoding:nc,isIPv4:LO,nonSimpleDomain:UO}=Kp(),{SCHEMES:HO,getSchemeHandler:Vv}=Bv();function FO(t,e){return typeof t=="string"?t=pr(Pr(t,e),e):typeof t=="object"&&(t=Pr(pr(t,e),e)),t}function ZO(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=Wv(Pr(t,n),Pr(e,n),n,!0);return n.skipEscape=!0,pr(o,n)}function Wv(t,e,r,n){let o={};return n||(t=Pr(pr(t,r),r),e=Pr(pr(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=ri(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=ri(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=ri(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=ri(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 qO(t,e,r){return typeof t=="string"?(t=unescape(t),t=pr(nc(Pr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=pr(nc(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=pr(nc(Pr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=pr(nc(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function pr(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=Vv(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=zO(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=ri(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 BO=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Pr(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;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(BO);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(LO(n.host)===!1){let c=jO(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=Vv(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&UO(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var Xp={SCHEMES:HO,normalize:FO,resolve:ZO,resolveComponent:Wv,equal:qO,serialize:pr,parse:Pr};oc.exports=Xp;oc.exports.default=Xp;oc.exports.fastUri=Xp});var Jv=O(Yp=>{"use strict";Object.defineProperty(Yp,"__esModule",{value:!0});var Gv=Kv();Gv.code='require("ajv/dist/runtime/uri").default';Yp.default=Gv});var ox=O(Ge=>{"use strict";Object.defineProperty(Ge,"__esModule",{value:!0});Ge.CodeGen=Ge.Name=Ge.nil=Ge.stringify=Ge.str=Ge._=Ge.KeywordCxt=void 0;var VO=ei();Object.defineProperty(Ge,"KeywordCxt",{enumerable:!0,get:function(){return VO.KeywordCxt}});var Mo=Q();Object.defineProperty(Ge,"_",{enumerable:!0,get:function(){return Mo._}});Object.defineProperty(Ge,"str",{enumerable:!0,get:function(){return Mo.str}});Object.defineProperty(Ge,"stringify",{enumerable:!0,get:function(){return Mo.stringify}});Object.defineProperty(Ge,"nil",{enumerable:!0,get:function(){return Mo.nil}});Object.defineProperty(Ge,"Name",{enumerable:!0,get:function(){return Mo.Name}});Object.defineProperty(Ge,"CodeGen",{enumerable:!0,get:function(){return Mo.CodeGen}});var WO=Ya(),tx=ti(),KO=Rp(),ni=ec(),GO=Q(),oi=Xs(),sc=Js(),ef=ue(),Xv=Mv(),JO=Jv(),rx=(t,e)=>new RegExp(t,e);rx.code="new RegExp";var XO=["removeAdditional","useDefaults","coerceTypes"],YO=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),QO={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."},eI={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Yv=200;function tI(t){var e,r,n,o,s,i,a,c,u,l,d,f,m,p,h,g,y,v,_,b,E,R,N,C,M;let W=t.strict,k=(e=t.code)===null||e===void 0?void 0:e.optimize,D=k===!0||k===void 0?1:k||0,L=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:rx,qe=(o=t.uriResolver)!==null&&o!==void 0?o:JO.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:W)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:W)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:W)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:W)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:W)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:D,regExp:L}:{optimize:D,regExp:L},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:Yv,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:Yv,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(v=t.messages)!==null&&v!==void 0?v:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:(N=t.validateFormats)!==null&&N!==void 0?N:!0,unicodeRegExp:(C=t.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(M=t.int32range)!==null&&M!==void 0?M:!0,uriResolver:qe}}var si=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,...tI(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new GO.ValueScope({scope:{},prefixes:YO,es5:r,lines:n}),this.logger=aI(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,KO.getRules)(),Qv.call(this,QO,e,"NOT SUPPORTED"),Qv.call(this,eI,e,"DEPRECATED","warn"),this._metaOpts=sI.call(this),e.formats&&nI.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&oI.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),rI.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=Xv;n==="id"&&(o={...Xv},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 f=this._addSchema(l,d);return f.validate||i.call(this,f)}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 tx.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,oi.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=ex.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new ni.SchemaEnv({schema:{},schemaId:n});if(r=ni.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=ex.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,oi.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(uI.call(this,n,r),!r)return(0,ef.eachItem)(n,s=>Qp.call(this,s)),this;dI.call(this,r);let o={...r,type:(0,sc.getJSONTypes)(r.type),schemaType:(0,sc.getJSONTypes)(r.schemaType)};return(0,ef.eachItem)(n,o.type.length===0?s=>Qp.call(this,s,o):s=>o.type.forEach(i=>Qp.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]=nx(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,oi.normalizeId)(i||n);let u=oi.getSchemaRefs.call(this,e,n);return c=new ni.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):ni.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{ni.compileSchema.call(this,e)}finally{this.opts=r}}};si.ValidationError=WO.default;si.MissingRefError=tx.default;Ge.default=si;function Qv(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 ex(t){return t=(0,oi.normalizeId)(t),this.schemas[t]||this.refs[t]}function rI(){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 nI(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function oI(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 sI(){let t={...this.opts};for(let e of XO)delete t[e];return t}var iI={log(){},warn(){},error(){}};function aI(t){if(t===!1)return iI;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 cI=/^[a-z_$][a-z0-9_$:-]*$/i;function uI(t,e){let{RULES:r}=this;if((0,ef.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!cI.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 Qp(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,sc.getJSONTypes)(e.type),schemaType:(0,sc.getJSONTypes)(e.schemaType)}};e.before?lI.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 lI(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 dI(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=nx(e)),t.validateSchema=this.compile(e,!0))}var pI={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function nx(t){return{anyOf:[t,pI]}}});var sx=O(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var fI={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};tf.default=fI});var ux=O(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.callRef=Fn.getValidate=void 0;var mI=ti(),ix=It(),yt=Q(),jo=Tr(),ax=ec(),ic=ue(),hI={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=ax.resolveRef.call(c,u,o,r);if(l===void 0)throw new mI.default(n.opts.uriResolver,o,r);if(l instanceof ax.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return ac(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return ac(t,(0,yt._)`${p}.validate`,u,u.$async)}function f(p){let h=cx(t,p);ac(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,yt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:yt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function cx(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,yt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Fn.getValidate=cx;function ac(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?jo.default.this:yt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=o.let("valid");o.try(()=>{o.code((0,yt._)`await ${(0,ix.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,yt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,ix.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,yt._)`${p}.errors`;o.assign(jo.default.vErrors,(0,yt._)`${jo.default.vErrors} === null ? ${h} : ${jo.default.vErrors}.concat(${h})`),o.assign(jo.default.errors,(0,yt._)`${jo.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=ic.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,yt._)`${p}.evaluated.props`);s.props=ic.mergeEvaluated.props(o,y,s.props,yt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=ic.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,yt._)`${p}.evaluated.items`);s.items=ic.mergeEvaluated.items(o,y,s.items,yt.Name)}}}Fn.callRef=ac;Fn.default=hI});var lx=O(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var gI=sx(),yI=ux(),_I=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",gI.default,yI.default];rf.default=_I});var dx=O(nf=>{"use strict";Object.defineProperty(nf,"__esModule",{value:!0});var cc=Q(),en=cc.operators,uc={maximum:{okStr:"<=",ok:en.LTE,fail:en.GT},minimum:{okStr:">=",ok:en.GTE,fail:en.LT},exclusiveMaximum:{okStr:"<",ok:en.LT,fail:en.GTE},exclusiveMinimum:{okStr:">",ok:en.GT,fail:en.LTE}},vI={message:({keyword:t,schemaCode:e})=>(0,cc.str)`must be ${uc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,cc._)`{comparison: ${uc[t].okStr}, limit: ${e}}`},xI={keyword:Object.keys(uc),type:"number",schemaType:"number",$data:!0,error:vI,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,cc._)`${r} ${uc[e].fail} ${n} || isNaN(${r})`)}};nf.default=xI});var px=O(of=>{"use strict";Object.defineProperty(of,"__esModule",{value:!0});var ii=Q(),bI={message:({schemaCode:t})=>(0,ii.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ii._)`{multipleOf: ${t}}`},SI={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:bI,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ii._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ii._)`${i} !== parseInt(${i})`;t.fail$data((0,ii._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};of.default=SI});var mx=O(sf=>{"use strict";Object.defineProperty(sf,"__esModule",{value:!0});function fx(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}sf.default=fx;fx.code='require("ajv/dist/runtime/ucs2length").default'});var hx=O(af=>{"use strict";Object.defineProperty(af,"__esModule",{value:!0});var Zn=Q(),kI=ue(),EI=mx(),wI={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Zn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Zn._)`{limit: ${t}}`},TI={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wI,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Zn.operators.GT:Zn.operators.LT,i=o.opts.unicode===!1?(0,Zn._)`${r}.length`:(0,Zn._)`${(0,kI.useFunc)(t.gen,EI.default)}(${r})`;t.fail$data((0,Zn._)`${i} ${s} ${n}`)}};af.default=TI});var gx=O(cf=>{"use strict";Object.defineProperty(cf,"__esModule",{value:!0});var RI=It(),PI=ue(),zo=Q(),$I={message:({schemaCode:t})=>(0,zo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,zo._)`{pattern: ${t}}`},CI={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:$I,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,zo._)`new RegExp`:(0,PI.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,zo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,zo._)`!${l}`)}else{let c=(0,RI.usePattern)(t,o);t.fail$data((0,zo._)`!${c}.test(${r})`)}}};cf.default=CI});var yx=O(uf=>{"use strict";Object.defineProperty(uf,"__esModule",{value:!0});var ai=Q(),OI={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,ai.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,ai._)`{limit: ${t}}`},II={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:OI,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?ai.operators.GT:ai.operators.LT;t.fail$data((0,ai._)`Object.keys(${r}).length ${o} ${n}`)}};uf.default=II});var _x=O(lf=>{"use strict";Object.defineProperty(lf,"__esModule",{value:!0});var ci=It(),ui=Q(),AI=ue(),NI={message:({params:{missingProperty:t}})=>(0,ui.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ui._)`{missingProperty: ${t}}`},DI={keyword:"required",type:"object",schemaType:"array",$data:!0,error:NI,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 m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(m?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,AI.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(ui.nil,d);else for(let m of r)(0,ci.checkReportMissingProp)(t,m)}function l(){let m=e.let("missing");if(c||s){let p=e.let("valid",!0);t.block$data(p,()=>f(m,p)),t.ok(p)}else e.if((0,ci.checkMissingProp)(t,r,m)),(0,ci.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",n,m=>{t.setParams({missingProperty:m}),e.if((0,ci.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,n,()=>{e.assign(p,(0,ci.propertyInData)(e,o,m,a.ownProperties)),e.if((0,ui.not)(p),()=>{t.error(),e.break()})},ui.nil)}}};lf.default=DI});var vx=O(df=>{"use strict";Object.defineProperty(df,"__esModule",{value:!0});var li=Q(),MI={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,li.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,li._)`{limit: ${t}}`},jI={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:MI,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?li.operators.GT:li.operators.LT;t.fail$data((0,li._)`${r}.length ${o} ${n}`)}};df.default=jI});var lc=O(pf=>{"use strict";Object.defineProperty(pf,"__esModule",{value:!0});var xx=Dp();xx.code='require("ajv/dist/runtime/equal").default';pf.default=xx});var bx=O(mf=>{"use strict";Object.defineProperty(mf,"__esModule",{value:!0});var ff=Js(),Je=Q(),zI=ue(),LI=lc(),UI={message:({params:{i:t,j:e}})=>(0,Je.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Je._)`{i: ${t}, j: ${e}}`},HI={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:UI,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,ff.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Je._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Je._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Je._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),y=(0,ff.checkDataTypes)(u,g,a.opts.strictNumbers,ff.DataType.Wrong),v=e.const("indices",(0,Je._)`{}`);e.for((0,Je._)`;${p}--;`,()=>{e.let(g,(0,Je._)`${r}[${p}]`),e.if(y,(0,Je._)`continue`),u.length>1&&e.if((0,Je._)`typeof ${g} == "string"`,(0,Je._)`${g} += "_"`),e.if((0,Je._)`typeof ${v}[${g}] == "number"`,()=>{e.assign(h,(0,Je._)`${v}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Je._)`${v}[${g}] = ${p}`)})}function m(p,h){let g=(0,zI.useFunc)(e,LI.default),y=e.name("outer");e.label(y).for((0,Je._)`;${p}--;`,()=>e.for((0,Je._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Je._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};mf.default=HI});var Sx=O(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var hf=Q(),FI=ue(),ZI=lc(),qI={message:"must be equal to constant",params:({schemaCode:t})=>(0,hf._)`{allowedValue: ${t}}`},BI={keyword:"const",$data:!0,error:qI,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,hf._)`!${(0,FI.useFunc)(e,ZI.default)}(${r}, ${o})`):t.fail((0,hf._)`${s} !== ${r}`)}};gf.default=BI});var kx=O(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var di=Q(),VI=ue(),WI=lc(),KI={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,di._)`{allowedValues: ${t}}`},GI={keyword:"enum",schemaType:"array",$data:!0,error:KI,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,VI.useFunc)(e,WI.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 m=e.const("vSchema",s);l=(0,di.or)(...o.map((p,h)=>f(m,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,m=>e.if((0,di._)`${u()}(${r}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,di._)`${u()}(${r}, ${m}[${p}])`:(0,di._)`${r} === ${h}`}}};yf.default=GI});var Ex=O(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var JI=dx(),XI=px(),YI=hx(),QI=gx(),eA=yx(),tA=_x(),rA=vx(),nA=bx(),oA=Sx(),sA=kx(),iA=[JI.default,XI.default,YI.default,QI.default,eA.default,tA.default,rA.default,nA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},oA.default,sA.default];_f.default=iA});var xf=O(pi=>{"use strict";Object.defineProperty(pi,"__esModule",{value:!0});pi.validateAdditionalItems=void 0;var qn=Q(),vf=ue(),aA={message:({params:{len:t}})=>(0,qn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,qn._)`{limit: ${t}}`},cA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:aA,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,vf.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}wx(t,n)}};function wx(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,qn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,qn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,vf.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,qn._)`${a} <= ${e.length}`);r.if((0,qn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:vf.Type.Num},u),i.allErrors||r.if((0,qn.not)(u),()=>r.break())})}}pi.validateAdditionalItems=wx;pi.default=cA});var bf=O(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.validateTuple=void 0;var Tx=Q(),dc=ue(),uA=It(),lA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return Rx(t,"additionalItems",e);r.items=!0,!(0,dc.alwaysValidSchema)(r,e)&&t.ok((0,uA.validateArray)(t))}};function Rx(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=dc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,Tx._)`${s}.length`);r.forEach((d,f)=>{(0,dc.alwaysValidSchema)(a,d)||(n.if((0,Tx._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=r.length,h=p===d.minItems&&(p===d.maxItems||d[e]===!1);if(f.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${m}"`;(0,dc.checkStrictMode)(a,g,f.strictTuples)}}}fi.validateTuple=Rx;fi.default=lA});var Px=O(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var dA=bf(),pA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,dA.validateTuple)(t,"items")};Sf.default=pA});var Cx=O(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var $x=Q(),fA=ue(),mA=It(),hA=xf(),gA={message:({params:{len:t}})=>(0,$x.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,$x._)`{limit: ${t}}`},yA={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:gA,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,fA.alwaysValidSchema)(n,e)&&(o?(0,hA.validateAdditionalItems)(t,o):t.ok((0,mA.validateArray)(t)))}};kf.default=yA});var Ox=O(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var Nt=Q(),pc=ue(),_A={message:({params:{min:t,max:e}})=>e===void 0?(0,Nt.str)`must contain at least ${t} valid item(s)`:(0,Nt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Nt._)`{minContains: ${t}}`:(0,Nt._)`{minContains: ${t}, maxContains: ${e}}`},vA={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:_A,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,Nt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,pc.alwaysValidSchema)(s,r)){let h=(0,Nt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Nt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?m(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Nt._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>p(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:pc.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Nt._)`${h}++`),a===void 0?e.if((0,Nt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Nt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Nt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Ef.default=vA});var Nx=O(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateSchemaDeps=fr.validatePropertyDeps=fr.error=void 0;var wf=Q(),xA=ue(),mi=It();fr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,wf.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,wf._)`{property: ${t},
7
7
  missingProperty: ${n},
8
8
  depsCount: ${e},
9
- deps: ${r}}`};var fA={keyword:"dependencies",type:"object",schemaType:"object",error:fr.error,code(t){let[e,r]=mA(t);Ib(t,e),Ab(t,r)}};function mA({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 Ib(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,pi.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,pi.checkReportMissingProp)(t,u)}):(r.if((0,Sf._)`${c} && (${(0,pi.checkMissingProp)(t,a,s)})`),(0,pi.reportMissingProp)(t,s),r.else())}}fr.validatePropertyDeps=Ib;function Ab(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,pA.alwaysValidSchema)(s,e[a])||(r.if((0,pi.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))}fr.validateSchemaDeps=Ab;fr.default=fA});var Mb=R(kf=>{"use strict";Object.defineProperty(kf,"__esModule",{value:!0});var Db=Q(),hA=ue(),gA={message:"property name must be valid",params:({params:t})=>(0,Db._)`{propertyName: ${t.propertyName}}`},yA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:gA,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,hA.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,Db.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};kf.default=yA});var wf=R(Ef=>{"use strict";Object.defineProperty(Ef,"__esModule",{value:!0});var dc=It(),Jt=Q(),_A=Tr(),pc=ue(),vA={message:"must NOT have additional properties",params:({params:t})=>(0,Jt._)`{additionalProperty: ${t.additionalProperty}}`},bA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:vA,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,pc.alwaysValidSchema)(i,r))return;let u=(0,dc.allSchemaProperties)(n.properties),l=(0,dc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Jt._)`${s} === ${_A.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let y;if(u.length>8){let v=(0,pc.schemaRefOrVal)(i,n.properties,"properties");y=(0,dc.isOwnProperty)(e,v,g)}else u.length?y=(0,Jt.or)(...u.map(v=>(0,Jt._)`${g} === ${v}`)):y=Jt.nil;return l.length&&(y=(0,Jt.or)(y,...l.map(v=>(0,Jt._)`${(0,dc.usePattern)(t,v)}.test(${g})`))),(0,Jt.not)(y)}function m(g){e.code((0,Jt._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,pc.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Jt.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,Jt.not)(y),()=>e.break()))}}function h(g,y,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:pc.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};Ef.default=bA});var Lb=R(Pf=>{"use strict";Object.defineProperty(Pf,"__esModule",{value:!0});var xA=Xs(),jb=It(),Tf=ue(),zb=wf(),SA={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&&zb.default.code(new xA.KeywordCxt(s,zb.default,"additionalProperties"));let i=(0,jb.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Tf.mergeEvaluated.props(e,(0,Tf.toHash)(i),s.props));let a=i.filter(d=>!(0,Tf.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,jb.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)}}};Pf.default=SA});var Zb=R(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var Ub=It(),fc=Q(),Hb=ue(),Fb=ue(),kA={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,Ub.allSchemaProperties)(r),c=a.filter(h=>(0,Hb.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 fc.Name)&&(s.props=(0,Fb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Hb.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,fc._)`${(0,Ub.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Fb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,fc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,fc.not)(l),()=>e.break())})})}}};Rf.default=kA});var qb=R($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var EA=ue(),wA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,EA.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"}};$f.default=wA});var Bb=R(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var TA=It(),PA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:TA.validateUnion,error:{message:"must match a schema in anyOf"}};Cf.default=PA});var Vb=R(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var mc=Q(),RA=ue(),$A={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,mc._)`{passingSchemas: ${t.passing}}`},CA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$A,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 f;(0,RA.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,mc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,mc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,mc.Name)})})}}};Of.default=CA});var Wb=R(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var OA=ue(),IA={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,OA.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};If.default=IA});var Jb=R(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var hc=Q(),Gb=ue(),AA={message:({params:t})=>(0,hc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,hc._)`{failingKeyword: ${t.ifClause}}`},NA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:AA,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Gb.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Kb(n,"then"),s=Kb(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,hc.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 f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,hc._)`${l}`):t.setParams({ifClause:l})}}}};function Kb(t,e){let r=t.schema[e];return r!==void 0&&!(0,Gb.alwaysValidSchema)(t,r)}Af.default=NA});var Yb=R(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var DA=ue(),MA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,DA.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Nf.default=MA});var Xb=R(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var jA=yf(),zA=Rb(),LA=_f(),UA=Cb(),HA=Ob(),FA=Nb(),ZA=Mb(),qA=wf(),BA=Lb(),VA=Zb(),WA=qb(),KA=Bb(),GA=Vb(),JA=Wb(),YA=Jb(),XA=Yb();function QA(t=!1){let e=[WA.default,KA.default,GA.default,JA.default,YA.default,XA.default,ZA.default,qA.default,FA.default,BA.default,VA.default];return t?e.push(zA.default,UA.default):e.push(jA.default,LA.default),e.push(HA.default),e}Df.default=QA});var Qb=R(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Me=Q(),eN={message:({schemaCode:t})=>(0,Me.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Me._)`{format: ${t}}`},tN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:eN,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?f():m();function f(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Me._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Me._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Me._)`${h}.type || "string"`).assign(y,(0,Me._)`${h}.validate`),()=>r.assign(g,(0,Me._)`"string"`).assign(y,h)),t.fail$data((0,Me.or)(v(),_()));function v(){return c.strictSchema===!1?Me.nil:(0,Me._)`${i} && !${y}`}function _(){let S=l.$async?(0,Me._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Me._)`${y}(${n})`,T=(0,Me._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${n}))`;return(0,Me._)`${y} && ${y} !== true && ${g} === ${e} && !${T}`}}function m(){let p=d.formats[s];if(!p){v();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(S());function v(){if(c.strictSchema===!1){d.logger.warn(T());return}throw new Error(T());function T(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(T){let I=T instanceof RegExp?(0,Me.regexpCode)(T):c.code.formats?(0,Me._)`${c.code.formats}${(0,Me.getProperty)(s)}`:void 0,N=r.scopeValue("formats",{key:s,ref:T,code:I});return typeof T=="object"&&!(T instanceof RegExp)?[T.type||"string",T.validate,(0,Me._)`${N}.validate`]:["string",T,N]}function S(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Me._)`await ${y}(${n})`}return typeof g=="function"?(0,Me._)`${y}(${n})`:(0,Me._)`${y}.test(${n})`}}}};Mf.default=tN});var ex=R(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var rN=Qb(),nN=[rN.default];jf.default=nN});var tx=R(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.contentVocabulary=zo.metadataVocabulary=void 0;zo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];zo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nx=R(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var oN=lb(),sN=Eb(),iN=Xb(),aN=ex(),rx=tx(),cN=[oN.default,sN.default,(0,iN.default)(),aN.default,rx.metadataVocabulary,rx.contentVocabulary];zf.default=cN});var sx=R(gc=>{"use strict";Object.defineProperty(gc,"__esModule",{value:!0});gc.DiscrError=void 0;var ox;(function(t){t.Tag="tag",t.Mapping="mapping"})(ox||(gc.DiscrError=ox={}))});var ax=R(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Lo=Q(),Lf=sx(),ix=Xa(),uN=Qs(),lN=ue(),dN={message:({params:{discrError:t,tagName:e}})=>t===Lf.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Lo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},pN={keyword:"discriminator",type:"object",schemaType:"object",error:dN,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Lo._)`${r}${(0,Lo.getProperty)(a)}`);e.if((0,Lo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Lf.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=f();e.if(!1);for(let p in m)e.elseIf((0,Lo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:Lf.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},p);return t.mergeEvaluated(h,Lo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let S=0;S<i.length;S++){let T=i[S];if(T?.$ref&&!(0,lN.schemaHasRulesButRef)(T,s.self.RULES)){let N=T.$ref;if(T=ix.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,N),T instanceof ix.SchemaEnv&&(T=T.schema),T===void 0)throw new uN.default(s.opts.uriResolver,s.baseId,N)}let I=(m=T?.properties)===null||m===void 0?void 0:m[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(T)),v(I,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function v(S,T){if(S.const)_(S.const,T);else if(S.enum)for(let I of S.enum)_(I,T);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(S,T){if(typeof S!="string"||S in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[S]=T}}}};Uf.default=pN});var cx=R((wq,fN)=>{fN.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 Ff=R((ke,Hf)=>{"use strict";Object.defineProperty(ke,"__esModule",{value:!0});ke.MissingRefError=ke.ValidationError=ke.CodeGen=ke.Name=ke.nil=ke.stringify=ke.str=ke._=ke.KeywordCxt=ke.Ajv=void 0;var mN=ob(),hN=nx(),gN=ax(),ux=cx(),yN=["/properties"],yc="http://json-schema.org/draft-07/schema",Uo=class extends mN.default{_addVocabularies(){super._addVocabularies(),hN.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(gN.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ux,yN):ux;this.addMetaSchema(e,yc,!1),this.refs["http://json-schema.org/schema"]=yc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(yc)?yc:void 0)}};ke.Ajv=Uo;Hf.exports=ke=Uo;Hf.exports.Ajv=Uo;Object.defineProperty(ke,"__esModule",{value:!0});ke.default=Uo;var _N=Xs();Object.defineProperty(ke,"KeywordCxt",{enumerable:!0,get:function(){return _N.KeywordCxt}});var Ho=Q();Object.defineProperty(ke,"_",{enumerable:!0,get:function(){return Ho._}});Object.defineProperty(ke,"str",{enumerable:!0,get:function(){return Ho.str}});Object.defineProperty(ke,"stringify",{enumerable:!0,get:function(){return Ho.stringify}});Object.defineProperty(ke,"nil",{enumerable:!0,get:function(){return Ho.nil}});Object.defineProperty(ke,"Name",{enumerable:!0,get:function(){return Ho.Name}});Object.defineProperty(ke,"CodeGen",{enumerable:!0,get:function(){return Ho.CodeGen}});var vN=Ja();Object.defineProperty(ke,"ValidationError",{enumerable:!0,get:function(){return vN.default}});var bN=Qs();Object.defineProperty(ke,"MissingRefError",{enumerable:!0,get:function(){return bN.default}})});var yx=R(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatNames=hr.fastFormats=hr.fullFormats=void 0;function mr(t,e){return{validate:t,compare:e}}hr.fullFormats={date:mr(fx,Vf),time:mr(qf(!0),Wf),"date-time":mr(lx(!0),hx),"iso-time":mr(qf(),mx),"iso-date-time":mr(lx(),gx),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:TN,"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:AN,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:PN,int32:{type:"number",validate:CN},int64:{type:"number",validate:ON},float:{type:"number",validate:px},double:{type:"number",validate:px},password:!0,binary:!0};hr.fastFormats={...hr.fullFormats,date:mr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vf),time:mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wf),"date-time":mr(/^\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,hx),"iso-time":mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mx),"iso-date-time":mr(/^\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,gx),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};hr.formatNames=Object.keys(hr.fullFormats);function xN(t){return t%4===0&&(t%100!==0||t%400===0)}var SN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,kN=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fx(t){let e=SN.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&&xN(r)?29:kN[n])}function Vf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Zf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function qf(t){return function(r){let n=Zf.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,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function Wf(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 mx(t,e){if(!(t&&e))return;let r=Zf.exec(t),n=Zf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Bf=/t|\s/i;function lx(t){let e=qf(t);return function(n){let o=n.split(Bf);return o.length===2&&fx(o[0])&&e(o[1])}}function hx(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function gx(t,e){if(!(t&&e))return;let[r,n]=t.split(Bf),[o,s]=e.split(Bf),i=Vf(r,o);if(i!==void 0)return i||Wf(n,s)}var EN=/\/|:/,wN=/^(?:[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 TN(t){return EN.test(t)&&wN.test(t)}var dx=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function PN(t){return dx.lastIndex=0,dx.test(t)}var RN=-(2**31),$N=2**31-1;function CN(t){return Number.isInteger(t)&&t<=$N&&t>=RN}function ON(t){return Number.isInteger(t)}function px(){return!0}var IN=/[^\\]\\Z/;function AN(t){if(IN.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _x=R(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.formatLimitDefinition=void 0;var NN=Ff(),Yt=Q(),en=Yt.operators,_c={formatMaximum:{okStr:"<=",ok:en.LTE,fail:en.GT},formatMinimum:{okStr:">=",ok:en.GTE,fail:en.LT},formatExclusiveMaximum:{okStr:"<",ok:en.LT,fail:en.GTE},formatExclusiveMinimum:{okStr:">",ok:en.GT,fail:en.LTE}},DN={message:({keyword:t,schemaCode:e})=>(0,Yt.str)`should be ${_c[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Yt._)`{comparison: ${_c[t].okStr}, limit: ${e}}`};Fo.formatLimitDefinition={keyword:Object.keys(_c),type:"string",schemaType:"string",$data:!0,error:DN,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 NN.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,Yt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Yt.or)((0,Yt._)`typeof ${m} != "object"`,(0,Yt._)`${m} instanceof RegExp`,(0,Yt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,Yt._)`${i.code.formats}${(0,Yt.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,Yt._)`${f}.compare(${r}, ${n}) ${_c[o].fail} 0`}},dependencies:["format"]};var MN=t=>(t.addKeyword(Fo.formatLimitDefinition),t);Fo.default=MN});var Sx=R((fi,xx)=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});var Zo=yx(),jN=_x(),Kf=Q(),vx=new Kf.Name("fullFormats"),zN=new Kf.Name("fastFormats"),Gf=(t,e={keywords:!0})=>{if(Array.isArray(e))return bx(t,e,Zo.fullFormats,vx),t;let[r,n]=e.mode==="fast"?[Zo.fastFormats,zN]:[Zo.fullFormats,vx],o=e.formats||Zo.formatNames;return bx(t,o,r,n),e.keywords&&(0,jN.default)(t),t};Gf.get=(t,e="full")=>{let n=(e==="fast"?Zo.fastFormats:Zo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function bx(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Kf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}xx.exports=fi=Gf;Object.defineProperty(fi,"__esModule",{value:!0});fi.default=Gf});import{createRequire as iD}from"node:module";import{existsSync as aD,unlinkSync as Gx,renameSync as cD}from"node:fs";import{tmpdir as uD}from"node:os";import{join as lD}from"node:path";function dD(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function pD(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function et(){if(!qo){let t=iD(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;qo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new om(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(pD()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&dD(e)?qo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new sm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:qo=t("better-sqlite3")}else qo=t("better-sqlite3")}return qo}function vi(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function bi(t){if(!aD(t))for(let e of["-wal","-shm"])try{Gx(t+e)}catch{}}function im(t){for(let e of["","-wal","-shm"])try{Gx(t+e)}catch{}}function xi(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Jx(t="context-mode"){return lD(uD(),`${t}-${process.pid}.db`)}function qn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function am(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function fD(t){let e=Date.now();for(let r of["","-wal","-shm"])try{cD(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var om,sm,qo,_i,nm,Cc,Bo=ce(()=>{"use strict";om=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},sm=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},qo=null;_i=Symbol.for("__context_mode_live_dbs_v3__"),nm=(()=>{let t=globalThis;return t[_i]||(t[_i]=new Set,process.on("exit",()=>{for(let e of t[_i])xi(e);t[_i].clear()})),t[_i]})(),Cc=class{#e;#t;constructor(e){let r=et();this.#e=e,bi(e);let n;try{n=new r(e,{timeout:3e4}),vi(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(am(s)){fD(e),bi(e);try{n=new r(e,{timeout:3e4}),vi(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,nm.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){nm.delete(this.#t),xi(this.#t)}withRetry(e){return qn(e)}cleanup(){nm.delete(this.#t),xi(this.#t),im(this.#e)}}});var iS,aS=ce(()=>{"use strict";iS={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{createHash as ki}from"node:crypto";import{execFileSync as xD}from"node:child_process";import{accessSync as SD,constants as kD,existsSync as Nc,mkdirSync as ED,realpathSync as wD,renameSync as hm}from"node:fs";import{homedir as fS}from"node:os";import{dirname as TD,isAbsolute as mS,join as rn,resolve as Wo}from"node:path";function gm(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):rn(PD(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function PD(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?uS(n.trim()):uS(t,fS())}function uS(t,e){return t.startsWith("~")?Wo(fS(),t.replace(/^~[/\\]?/,"")):mS(t)?Wo(t):e?Wo(e,t):Wo(t)}function RD(t,e,r){return new nn(t,e,gr,void 0,[`Invalid ${gr} for context-mode ${t} directory: ${r}`,vS()].join(`
10
- `))}function gS(t){let e=process.env[gr];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:gr,ignoredReason:"empty"};if(!mS(r))throw RD(t,r,`${gr} must be an absolute path.`);return{kind:"override",root:Wo(r)}}function $D(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function yS(t,e){let r=gS(t);return r.kind!=="override"?null:{kind:t,path:rn(r.root,e),envVar:gr,source:"override"}}function CD(t,e,r){return{kind:t,path:Wo(e()),envVar:null,source:"default",...r}}function Ei(t){let e=gS("session");return e.kind==="override"?{kind:"session",path:rn(e.root,hS),envVar:gr,source:"override"}:CD("session",t,$D(e))}function ym(t){let e=yS("content",cS);if(e)return e;let r=Ei(t);return{kind:"content",path:rn(TD(r.path),cS),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function _m(t){let e=yS("stats",hS);if(e)return e;let r=Ei(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function _S(t){return t.message}function Dc(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function Mc(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=mm.get(e);if(r instanceof nn)throw r;if(r===t.path)return r;try{return ED(t.path,{recursive:!0}),SD(t.path,kD.W_OK),mm.set(e,t.path),t.path}catch(n){let o=new nn(t.kind,AD(n)??t.path,gr,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw mm.set(e,o),o}}function OD(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,ID(r),vS()].filter(Boolean).join(`
11
- `)}function ID(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function vS(){return`Set ${gr} to a writable absolute path.`}function AD(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function wi(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function lS(t){let e=t;try{e=wD.native(t)}catch{}let r=wi(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function bS(t,e){return xD("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function ND(t){let e=bS(t,["rev-parse","--show-toplevel"]);return e.length>0?wi(e):null}function DD(t){let e=bS(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?wi(e):null}function jc(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Si&&Si.projectDir===t&&Si.envSuffix===e)return Si.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=ND(t),o=DD(t);if(n&&o){let s=lS(n),i=lS(o);s!==i&&(r=`__${ki("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return Si={projectDir:t,envSuffix:e,suffix:r},r}function $r(t){return ki("sha256").update(wi(t)).digest("hex").slice(0,16)}function st(t){let e=wi(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return ki("sha256").update(r).digest("hex").slice(0,16)}function xS(t){let{projectDir:e,contentDir:r}=t,n=st(e),o=rn(r,`${n}.db`);if(Nc(o))return o;let s=$r(e);if(s===n)return o;let i=rn(r,`${s}.db`);if(Nc(i))try{hm(i,o);for(let a of["-wal","-shm"])try{hm(i+a,o+a)}catch{}}catch{}return o}function Ti(t){return MD({...t,ext:".db"})}function MD(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??jc(e),s=st(e),i=rn(r,`${s}${o}${n}`);if(Nc(i))return i;let a=$r(e);if(a===s)return i;let c=rn(r,`${a}${o}${n}`);if(Nc(c))try{hm(c,i)}catch{}return i}function Ac(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var gr,hS,cS,nn,mm,Si,dS,pS,H,Xt,on=ce(()=>{"use strict";Bo();gr="CONTEXT_MODE_DIR",hS="sessions",cS="content",nn=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=gr,o,s,i={}){super(s??OD(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},mm=new Map;dS=1e3,pS=5;H={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},Xt=class extends Cc{constructor(e){super(e?.dbPath??Jx("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
9
+ deps: ${r}}`};var bA={keyword:"dependencies",type:"object",schemaType:"object",error:fr.error,code(t){let[e,r]=SA(t);Ix(t,e),Ax(t,r)}};function SA({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 Ix(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,mi.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,mi.checkReportMissingProp)(t,u)}):(r.if((0,wf._)`${c} && (${(0,mi.checkMissingProp)(t,a,s)})`),(0,mi.reportMissingProp)(t,s),r.else())}}fr.validatePropertyDeps=Ix;function Ax(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,xA.alwaysValidSchema)(s,e[a])||(r.if((0,mi.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))}fr.validateSchemaDeps=Ax;fr.default=bA});var Mx=O(Tf=>{"use strict";Object.defineProperty(Tf,"__esModule",{value:!0});var Dx=Q(),kA=ue(),EA={message:"property name must be valid",params:({params:t})=>(0,Dx._)`{propertyName: ${t.propertyName}}`},wA={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:EA,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,kA.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,Dx.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Tf.default=wA});var Pf=O(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var fc=It(),Xt=Q(),TA=Tr(),mc=ue(),RA={message:"must NOT have additional properties",params:({params:t})=>(0,Xt._)`{additionalProperty: ${t.additionalProperty}}`},PA={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:RA,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,mc.alwaysValidSchema)(i,r))return;let u=(0,fc.allSchemaProperties)(n.properties),l=(0,fc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,Xt._)`${s} === ${TA.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?p(g):e.if(f(g),()=>p(g))})}function f(g){let y;if(u.length>8){let v=(0,mc.schemaRefOrVal)(i,n.properties,"properties");y=(0,fc.isOwnProperty)(e,v,g)}else u.length?y=(0,Xt.or)(...u.map(v=>(0,Xt._)`${g} === ${v}`)):y=Xt.nil;return l.length&&(y=(0,Xt.or)(y,...l.map(v=>(0,Xt._)`${(0,fc.usePattern)(t,v)}.test(${g})`))),(0,Xt.not)(y)}function m(g){e.code((0,Xt._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){m(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,mc.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,Xt.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,Xt.not)(y),()=>e.break()))}}function h(g,y,v){let _={keyword:"additionalProperties",dataProp:g,dataPropType:mc.Type.Str};v===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};Rf.default=PA});var Lx=O(Cf=>{"use strict";Object.defineProperty(Cf,"__esModule",{value:!0});var $A=ei(),jx=It(),$f=ue(),zx=Pf(),CA={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&&zx.default.code(new $A.KeywordCxt(s,zx.default,"additionalProperties"));let i=(0,jx.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=$f.mergeEvaluated.props(e,(0,$f.toHash)(i),s.props));let a=i.filter(d=>!(0,$f.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,jx.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)}}};Cf.default=CA});var Zx=O(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var Ux=It(),hc=Q(),Hx=ue(),Fx=ue(),OA={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,Ux.allSchemaProperties)(r),c=a.filter(h=>(0,Hx.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 hc.Name)&&(s.props=(0,Fx.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Hx.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,hc._)`${(0,Ux.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Fx.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,hc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,hc.not)(l),()=>e.break())})})}}};Of.default=OA});var qx=O(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var IA=ue(),AA={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,IA.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"}};If.default=AA});var Bx=O(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var NA=It(),DA={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:NA.validateUnion,error:{message:"must match a schema in anyOf"}};Af.default=DA});var Vx=O(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var gc=Q(),MA=ue(),jA={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,gc._)`{passingSchemas: ${t.passing}}`},zA={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jA,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 f;(0,MA.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,gc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,gc.Name)})})}}};Nf.default=zA});var Wx=O(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var LA=ue(),UA={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,LA.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Df.default=UA});var Jx=O(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var yc=Q(),Gx=ue(),HA={message:({params:t})=>(0,yc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,yc._)`{failingKeyword: ${t.ifClause}}`},FA={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:HA,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Gx.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=Kx(n,"then"),s=Kx(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,yc.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 f=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(f,i),d?e.assign(d,(0,yc._)`${l}`):t.setParams({ifClause:l})}}}};function Kx(t,e){let r=t.schema[e];return r!==void 0&&!(0,Gx.alwaysValidSchema)(t,r)}Mf.default=FA});var Xx=O(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var ZA=ue(),qA={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,ZA.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};jf.default=qA});var Yx=O(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var BA=xf(),VA=Px(),WA=bf(),KA=Cx(),GA=Ox(),JA=Nx(),XA=Mx(),YA=Pf(),QA=Lx(),eN=Zx(),tN=qx(),rN=Bx(),nN=Vx(),oN=Wx(),sN=Jx(),iN=Xx();function aN(t=!1){let e=[tN.default,rN.default,nN.default,oN.default,sN.default,iN.default,XA.default,YA.default,JA.default,QA.default,eN.default];return t?e.push(VA.default,KA.default):e.push(BA.default,WA.default),e.push(GA.default),e}zf.default=aN});var Qx=O(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Me=Q(),cN={message:({schemaCode:t})=>(0,Me.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Me._)`{format: ${t}}`},uN={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:cN,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?f():m();function f(){let p=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Me._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Me._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Me._)`${h}.type || "string"`).assign(y,(0,Me._)`${h}.validate`),()=>r.assign(g,(0,Me._)`"string"`).assign(y,h)),t.fail$data((0,Me.or)(v(),_()));function v(){return c.strictSchema===!1?Me.nil:(0,Me._)`${i} && !${y}`}function _(){let b=l.$async?(0,Me._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Me._)`${y}(${n})`,E=(0,Me._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${n}))`;return(0,Me._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function m(){let p=d.formats[s];if(!p){v();return}if(p===!0)return;let[h,g,y]=_(p);h===e&&t.pass(b());function v(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function _(E){let R=E instanceof RegExp?(0,Me.regexpCode)(E):c.code.formats?(0,Me._)`${c.code.formats}${(0,Me.getProperty)(s)}`:void 0,N=r.scopeValue("formats",{key:s,ref:E,code:R});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Me._)`${N}.validate`]:["string",E,N]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Me._)`await ${y}(${n})`}return typeof g=="function"?(0,Me._)`${y}(${n})`:(0,Me._)`${y}.test(${n})`}}}};Lf.default=uN});var eb=O(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var lN=Qx(),dN=[lN.default];Uf.default=dN});var tb=O(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.contentVocabulary=Lo.metadataVocabulary=void 0;Lo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Lo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var nb=O(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var pN=lx(),fN=Ex(),mN=Yx(),hN=eb(),rb=tb(),gN=[pN.default,fN.default,(0,mN.default)(),hN.default,rb.metadataVocabulary,rb.contentVocabulary];Hf.default=gN});var sb=O(_c=>{"use strict";Object.defineProperty(_c,"__esModule",{value:!0});_c.DiscrError=void 0;var ob;(function(t){t.Tag="tag",t.Mapping="mapping"})(ob||(_c.DiscrError=ob={}))});var ab=O(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Uo=Q(),Ff=sb(),ib=ec(),yN=ti(),_N=ue(),vN={message:({params:{discrError:t,tagName:e}})=>t===Ff.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Uo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xN={keyword:"discriminator",type:"object",schemaType:"object",error:vN,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,Uo._)`${r}${(0,Uo.getProperty)(a)}`);e.if((0,Uo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Ff.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let m=f();e.if(!1);for(let p in m)e.elseIf((0,Uo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:Ff.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(m){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:m},p);return t.mergeEvaluated(h,Uo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let E=i[b];if(E?.$ref&&!(0,_N.schemaHasRulesButRef)(E,s.self.RULES)){let N=E.$ref;if(E=ib.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,N),E instanceof ib.SchemaEnv&&(E=E.schema),E===void 0)throw new yN.default(s.opts.uriResolver,s.baseId,N)}let R=(m=E?.properties)===null||m===void 0?void 0:m[a];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(E)),v(R,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function v(b,E){if(b.const)_(b.const,E);else if(b.enum)for(let R of b.enum)_(R,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(b,E){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=E}}}};Zf.default=xN});var cb=O((Xq,bN)=>{bN.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 Bf=O((Ee,qf)=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.MissingRefError=Ee.ValidationError=Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=Ee.Ajv=void 0;var SN=ox(),kN=nb(),EN=ab(),ub=cb(),wN=["/properties"],vc="http://json-schema.org/draft-07/schema",Ho=class extends SN.default{_addVocabularies(){super._addVocabularies(),kN.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(EN.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(ub,wN):ub;this.addMetaSchema(e,vc,!1),this.refs["http://json-schema.org/schema"]=vc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(vc)?vc:void 0)}};Ee.Ajv=Ho;qf.exports=Ee=Ho;qf.exports.Ajv=Ho;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Ho;var TN=ei();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:function(){return TN.KeywordCxt}});var Fo=Q();Object.defineProperty(Ee,"_",{enumerable:!0,get:function(){return Fo._}});Object.defineProperty(Ee,"str",{enumerable:!0,get:function(){return Fo.str}});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:function(){return Fo.stringify}});Object.defineProperty(Ee,"nil",{enumerable:!0,get:function(){return Fo.nil}});Object.defineProperty(Ee,"Name",{enumerable:!0,get:function(){return Fo.Name}});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:function(){return Fo.CodeGen}});var RN=Ya();Object.defineProperty(Ee,"ValidationError",{enumerable:!0,get:function(){return RN.default}});var PN=ti();Object.defineProperty(Ee,"MissingRefError",{enumerable:!0,get:function(){return PN.default}})});var yb=O(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.formatNames=hr.fastFormats=hr.fullFormats=void 0;function mr(t,e){return{validate:t,compare:e}}hr.fullFormats={date:mr(fb,Gf),time:mr(Wf(!0),Jf),"date-time":mr(lb(!0),hb),"iso-time":mr(Wf(),mb),"iso-date-time":mr(lb(),gb),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:NN,"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:HN,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:DN,int32:{type:"number",validate:zN},int64:{type:"number",validate:LN},float:{type:"number",validate:pb},double:{type:"number",validate:pb},password:!0,binary:!0};hr.fastFormats={...hr.fullFormats,date:mr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Gf),time:mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Jf),"date-time":mr(/^\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,hb),"iso-time":mr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mb),"iso-date-time":mr(/^\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,gb),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};hr.formatNames=Object.keys(hr.fullFormats);function $N(t){return t%4===0&&(t%100!==0||t%400===0)}var CN=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ON=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fb(t){let e=CN.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&&$N(r)?29:ON[n])}function Gf(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Vf=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Wf(t){return function(r){let n=Vf.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,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function Jf(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 mb(t,e){if(!(t&&e))return;let r=Vf.exec(t),n=Vf.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var Kf=/t|\s/i;function lb(t){let e=Wf(t);return function(n){let o=n.split(Kf);return o.length===2&&fb(o[0])&&e(o[1])}}function hb(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function gb(t,e){if(!(t&&e))return;let[r,n]=t.split(Kf),[o,s]=e.split(Kf),i=Gf(r,o);if(i!==void 0)return i||Jf(n,s)}var IN=/\/|:/,AN=/^(?:[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 NN(t){return IN.test(t)&&AN.test(t)}var db=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function DN(t){return db.lastIndex=0,db.test(t)}var MN=-(2**31),jN=2**31-1;function zN(t){return Number.isInteger(t)&&t<=jN&&t>=MN}function LN(t){return Number.isInteger(t)}function pb(){return!0}var UN=/[^\\]\\Z/;function HN(t){if(UN.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _b=O(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.formatLimitDefinition=void 0;var FN=Bf(),Yt=Q(),tn=Yt.operators,xc={formatMaximum:{okStr:"<=",ok:tn.LTE,fail:tn.GT},formatMinimum:{okStr:">=",ok:tn.GTE,fail:tn.LT},formatExclusiveMaximum:{okStr:"<",ok:tn.LT,fail:tn.GTE},formatExclusiveMinimum:{okStr:">",ok:tn.GT,fail:tn.LTE}},ZN={message:({keyword:t,schemaCode:e})=>(0,Yt.str)`should be ${xc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Yt._)`{comparison: ${xc[t].okStr}, limit: ${e}}`};Zo.formatLimitDefinition={keyword:Object.keys(xc),type:"string",schemaType:"string",$data:!0,error:ZN,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 FN.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),m=e.const("fmt",(0,Yt._)`${f}[${c.schemaCode}]`);t.fail$data((0,Yt.or)((0,Yt._)`typeof ${m} != "object"`,(0,Yt._)`${m} instanceof RegExp`,(0,Yt._)`typeof ${m}.compare != "function"`,d(m)))}function l(){let f=c.schema,m=a.formats[f];if(!m||m===!0)return;if(typeof m!="object"||m instanceof RegExp||typeof m.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let p=e.scopeValue("formats",{key:f,ref:m,code:i.code.formats?(0,Yt._)`${i.code.formats}${(0,Yt.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,Yt._)`${f}.compare(${r}, ${n}) ${xc[o].fail} 0`}},dependencies:["format"]};var qN=t=>(t.addKeyword(Zo.formatLimitDefinition),t);Zo.default=qN});var Sb=O((hi,bb)=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});var qo=yb(),BN=_b(),Xf=Q(),vb=new Xf.Name("fullFormats"),VN=new Xf.Name("fastFormats"),Yf=(t,e={keywords:!0})=>{if(Array.isArray(e))return xb(t,e,qo.fullFormats,vb),t;let[r,n]=e.mode==="fast"?[qo.fastFormats,VN]:[qo.fullFormats,vb],o=e.formats||qo.formatNames;return xb(t,o,r,n),e.keywords&&(0,BN.default)(t),t};Yf.get=(t,e="full")=>{let n=(e==="fast"?qo.fastFormats:qo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function xb(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Xf._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}bb.exports=hi=Yf;Object.defineProperty(hi,"__esModule",{value:!0});hi.default=Yf});import{createRequire as mD}from"node:module";import{existsSync as hD,unlinkSync as Gb,renameSync as gD}from"node:fs";import{tmpdir as yD}from"node:os";import{join as _D}from"node:path";function vD(t){let e=null;try{return e=new t(":memory:"),e.exec("CREATE VIRTUAL TABLE __fts5_probe USING fts5(x)"),!0}catch{return!1}finally{try{e?.close()}catch{}}}function xD(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[o,s]=(n.node??"0.0.0").split("."),i=Number(o),a=Number(s);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function Ye(){if(!Bo){let t=mD(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Bo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new am(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(xD()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&vD(e)?Bo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1}),i=new cm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:Bo=t("better-sqlite3")}else Bo=t("better-sqlite3")}return Bo}function bi(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Si(t){if(!hD(t))for(let e of["-wal","-shm"])try{Gb(t+e)}catch{}}function um(t){for(let e of["","-wal","-shm"])try{Gb(t+e)}catch{}}function ki(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Jb(t="context-mode"){return _D(yD(),`${t}-${process.pid}.db`)}function Bn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function lm(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function bD(t){let e=Date.now();for(let r of["","-wal","-shm"])try{gD(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var am,cm,Bo,xi,im,Ic,Vo=ce(()=>{"use strict";am=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},cm=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Bo=null;xi=Symbol.for("__context_mode_live_dbs_v3__"),im=(()=>{let t=globalThis;return t[xi]||(t[xi]=new Set,process.on("exit",()=>{for(let e of t[xi])ki(e);t[xi].clear()})),t[xi]})(),Ic=class{#e;#t;constructor(e){let r=Ye();this.#e=e,Si(e);let n;try{n=new r(e,{timeout:3e4}),bi(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(lm(s)){bD(e),Si(e);try{n=new r(e,{timeout:3e4}),bi(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,im.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){im.delete(this.#t),ki(this.#t)}withRetry(e){return Bn(e)}cleanup(){im.delete(this.#t),ki(this.#t),um(this.#e)}}});var dS,pS=ce(()=>{"use strict";dS={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","JetBrains Client":"jetbrains-copilot","IntelliJ IDEA":"jetbrains-copilot",PyCharm:"jetbrains-copilot",Codex:"codex","codex-mcp-client":"codex","Kilo Code":"kilo","Kiro CLI":"kiro","Pi CLI":"pi","Pi Coding Agent":"pi","omp-coding-agent":"omp",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{createHash as wi}from"node:crypto";import{execFileSync as qD}from"node:child_process";import{accessSync as BD,constants as VD,existsSync as Mc,mkdirSync as WD,realpathSync as KD,renameSync as _m}from"node:fs";import{homedir as _S}from"node:os";import{dirname as GD,isAbsolute as vS,join as nn,resolve as Ko}from"node:path";function vm(t){let e=t.env??process.env,r=t.legacySessionDirEnv,n=r?e[r]?.trim():void 0;return n&&r?(t.onLegacySessionDir?.(r,n),n):nn(JD(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function JD(t,e,r){let n=e?r[e]:void 0;return n&&n.trim()!==""?mS(n.trim()):mS(t,_S())}function mS(t,e){return t.startsWith("~")?Ko(_S(),t.replace(/^~[/\\]?/,"")):vS(t)?Ko(t):e?Ko(e,t):Ko(t)}function XD(t,e,r){return new on(t,e,gr,void 0,[`Invalid ${gr} for context-mode ${t} directory: ${r}`,ES()].join(`
10
+ `))}function bS(t){let e=process.env[gr];if(e===void 0)return{kind:"unset"};let r=e.trim();if(!r)return{kind:"ignored-empty",ignoredEnvVar:gr,ignoredReason:"empty"};if(!vS(r))throw XD(t,r,`${gr} must be an absolute path.`);return{kind:"override",root:Ko(r)}}function YD(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function SS(t,e){let r=bS(t);return r.kind!=="override"?null:{kind:t,path:nn(r.root,e),envVar:gr,source:"override"}}function QD(t,e,r){return{kind:t,path:Ko(e()),envVar:null,source:"default",...r}}function Ti(t){let e=bS("session");return e.kind==="override"?{kind:"session",path:nn(e.root,xS),envVar:gr,source:"override"}:QD("session",t,YD(e))}function xm(t){let e=SS("content",fS);if(e)return e;let r=Ti(t);return{kind:"content",path:nn(GD(r.path),fS),envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function bm(t){let e=SS("stats",xS);if(e)return e;let r=Ti(t);return{kind:"stats",path:r.path,envVar:r.envVar,source:r.source,ignoredEnvVar:r.ignoredEnvVar,ignoredReason:r.ignoredReason}}function kS(t){return t.message}function jc(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function zc(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),r=ym.get(e);if(r instanceof on)throw r;if(r===t.path)return r;try{return WD(t.path,{recursive:!0}),BD(t.path,VD.W_OK),ym.set(e,t.path),t.path}catch(n){let o=new on(t.kind,rM(n)??t.path,gr,n,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw ym.set(e,o),o}}function eM(t,e,r={}){return[`context-mode ${t} directory is not writable: ${e}`,tM(r),ES()].filter(Boolean).join(`
11
+ `)}function tM(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function ES(){return`Set ${gr} to a writable absolute path.`}function rM(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function Ri(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function hS(t){let e=t;try{e=KD.native(t)}catch{}let r=Ri(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function wS(t,e){return qD("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function nM(t){let e=wS(t,["rev-parse","--show-toplevel"]);return e.length>0?Ri(e):null}function oM(t){let e=wS(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Ri(e):null}function Lc(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Ei&&Ei.projectDir===t&&Ei.envSuffix===e)return Ei.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=nM(t),o=oM(t);if(n&&o){let s=hS(n),i=hS(o);s!==i&&(r=`__${wi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return Ei={projectDir:t,envSuffix:e,suffix:r},r}function $r(t){return wi("sha256").update(Ri(t)).digest("hex").slice(0,16)}function ct(t){let e=Ri(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return wi("sha256").update(r).digest("hex").slice(0,16)}function TS(t){let{projectDir:e,contentDir:r}=t,n=ct(e),o=nn(r,`${n}.db`);if(Mc(o))return o;let s=$r(e);if(s===n)return o;let i=nn(r,`${s}.db`);if(Mc(i))try{_m(i,o);for(let a of["-wal","-shm"])try{_m(i+a,o+a)}catch{}}catch{}return o}function Pi(t){return sM({...t,ext:".db"})}function sM(t){let{projectDir:e,sessionsDir:r,ext:n}=t,o=t.suffix??Lc(e),s=ct(e),i=nn(r,`${s}${o}${n}`);if(Mc(i))return i;let a=$r(e);if(a===s)return i;let c=nn(r,`${a}${o}${n}`);if(Mc(c))try{_m(c,i)}catch{}return i}function Dc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function RS(t){let e=t.pragma("table_xinfo(session_events)"),r=new Set(e.map(o=>o.name)),n=!1;for(let[o,s]of iM)r.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),n=!0);return n&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),n}function PS(t,e){let r=null;try{r=new e(t),RS(r)}catch{}finally{try{r?.close()}catch{}}}var gr,xS,fS,on,ym,Ei,gS,yS,F,iM,Qt,Cr=ce(()=>{"use strict";Vo();gr="CONTEXT_MODE_DIR",xS="sessions",fS="content",on=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,r,n=gr,o,s,i={}){super(s??eM(e,r,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=r,this.overrideEnvVar=n,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},ym=new Map;gS=1e3,yS=5;F={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},iM=[["project_dir","TEXT NOT NULL DEFAULT ''"],["attribution_source","TEXT NOT NULL DEFAULT 'unknown'"],["attribution_confidence","REAL NOT NULL DEFAULT 0"],["bytes_avoided","INTEGER NOT NULL DEFAULT 0"],["bytes_returned","INTEGER NOT NULL DEFAULT 0"]];Qt=class extends Ic{constructor(e){super(e?.dbPath??Jb("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
12
12
  CREATE TABLE IF NOT EXISTS session_events (
13
13
  id INTEGER PRIMARY KEY AUTOINCREMENT,
14
14
  session_id TEXT NOT NULL,
@@ -58,50 +58,50 @@ var WE=Object.create;var Su=Object.defineProperty;var KE=Object.getOwnPropertyDe
58
58
  );
59
59
 
60
60
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
61
- `);try{let e=this.db.pragma("table_xinfo(session_events)"),r=new Set(e.map(n=>n.name));r.has("project_dir")||this.db.exec("ALTER TABLE session_events ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''"),r.has("attribution_source")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_source TEXT NOT NULL DEFAULT 'unknown'"),r.has("attribution_confidence")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_confidence REAL NOT NULL DEFAULT 0"),r.has("bytes_avoided")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_avoided INTEGER NOT NULL DEFAULT 0"),r.has("bytes_returned")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_returned INTEGER NOT NULL DEFAULT 0"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)")}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(H.insertEvent,`INSERT INTO session_events (
61
+ `);try{RS(this.db)}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(F.insertEvent,`INSERT INTO session_events (
62
62
  session_id, type, category, priority, data,
63
63
  project_dir, attribution_source, attribution_confidence,
64
64
  bytes_avoided, bytes_returned,
65
65
  source_hook, data_hash
66
66
  )
67
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(H.getEvents,`SELECT id, session_id, type, category, priority, data,
67
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(F.getEvents,`SELECT id, session_id, type, category, priority, data,
68
68
  project_dir, attribution_source, attribution_confidence,
69
69
  bytes_avoided, bytes_returned,
70
70
  source_hook, created_at, data_hash
71
- FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(H.getEventsByType,`SELECT id, session_id, type, category, priority, data,
71
+ FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(F.getEventsByType,`SELECT id, session_id, type, category, priority, data,
72
72
  project_dir, attribution_source, attribution_confidence,
73
73
  bytes_avoided, bytes_returned,
74
74
  source_hook, created_at, data_hash
75
- FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(H.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
75
+ FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(F.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
76
76
  project_dir, attribution_source, attribution_confidence,
77
77
  bytes_avoided, bytes_returned,
78
78
  source_hook, created_at, data_hash
79
- FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(H.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
79
+ FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(F.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
80
80
  project_dir, attribution_source, attribution_confidence,
81
81
  bytes_avoided, bytes_returned,
82
82
  source_hook, created_at, data_hash
83
- FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(H.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(H.getLatestAttributedProject,`SELECT project_dir
83
+ FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(F.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(F.getLatestAttributedProject,`SELECT project_dir
84
84
  FROM session_events
85
85
  WHERE session_id = ? AND project_dir != ''
86
86
  ORDER BY id DESC
87
- LIMIT 1`),e(H.checkDuplicate,`SELECT 1 FROM (
87
+ LIMIT 1`),e(F.checkDuplicate,`SELECT 1 FROM (
88
88
  SELECT type, data_hash FROM session_events
89
89
  WHERE session_id = ? ORDER BY id DESC LIMIT ?
90
90
  ) AS recent
91
91
  WHERE recent.type = ? AND recent.data_hash = ?
92
- LIMIT 1`),e(H.evictLowestPriority,`DELETE FROM session_events WHERE id = (
92
+ LIMIT 1`),e(F.evictLowestPriority,`DELETE FROM session_events WHERE id = (
93
93
  SELECT id FROM session_events WHERE session_id = ?
94
94
  ORDER BY priority ASC, id ASC LIMIT 1
95
- )`),e(H.updateMetaLastEvent,`UPDATE session_meta
95
+ )`),e(F.updateMetaLastEvent,`UPDATE session_meta
96
96
  SET last_event_at = datetime('now'), event_count = event_count + 1
97
- WHERE session_id = ?`),e(H.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(H.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
98
- FROM session_meta WHERE session_id = ?`),e(H.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(H.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
97
+ WHERE session_id = ?`),e(F.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(F.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
98
+ FROM session_meta WHERE session_id = ?`),e(F.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(F.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
99
99
  VALUES (?, ?, ?)
100
100
  ON CONFLICT(session_id) DO UPDATE SET
101
101
  snapshot = excluded.snapshot,
102
102
  event_count = excluded.event_count,
103
103
  created_at = datetime('now'),
104
- consumed = 0`),e(H.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(H.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(H.claimLatestUnconsumedResume,`UPDATE session_resume
104
+ consumed = 0`),e(F.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(F.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(F.claimLatestUnconsumedResume,`UPDATE session_resume
105
105
  SET consumed = 1
106
106
  WHERE id = (
107
107
  SELECT id FROM session_resume
@@ -110,88 +110,88 @@ var WE=Object.create;var Su=Object.defineProperty;var KE=Object.getOwnPropertyDe
110
110
  ORDER BY created_at DESC, id DESC
111
111
  LIMIT 1
112
112
  )
113
- RETURNING session_id, snapshot`),e(H.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(H.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(H.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(H.searchEvents,`SELECT id, session_id, category, type, data, created_at
113
+ RETURNING session_id, snapshot`),e(F.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(F.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(F.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(F.searchEvents,`SELECT id, session_id, category, type, data, created_at
114
114
  FROM session_events
115
115
  WHERE (project_dir = ? OR project_dir = '')
116
116
  AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
117
117
  AND (? IS NULL OR category = ?)
118
118
  ORDER BY id ASC
119
- LIMIT ?`),e(H.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(H.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
119
+ LIMIT ?`),e(F.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(F.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
120
120
  VALUES (?, ?, 1, ?)
121
121
  ON CONFLICT(session_id, tool) DO UPDATE SET
122
122
  calls = calls + 1,
123
123
  bytes_returned = bytes_returned + excluded.bytes_returned,
124
- updated_at = datetime('now')`),e(H.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
124
+ updated_at = datetime('now')`),e(F.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
125
125
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
126
- FROM tool_calls WHERE session_id = ?`),e(H.getToolCallByTool,`SELECT tool, calls, bytes_returned
127
- FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(H.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
126
+ FROM tool_calls WHERE session_id = ?`),e(F.getToolCallByTool,`SELECT tool, calls, bytes_returned
127
+ FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(F.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
128
128
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
129
- FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=ki("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=Ac(s?.bytesAvoided),f=Ac(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(H.checkDuplicate).get(e,pS,r.type,i))return;this.stmt(H.getEventCount).get(e).cnt>=dS&&this.stmt(H.evictLowestPriority).run(e),this.stmt(H.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,l,d,f,n,i),this.stmt(H.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let l=ki("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],f=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),m=String(d?.source??c.attribution_source??"unknown"),p=Number(d?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=s?.[u],y=Ac(g?.bytesAvoided),v=Ac(g?.bytesReturned);return{event:c,dataHash:l,projectDir:f,attributionSource:m,attributionConfidence:h,bytesAvoided:y,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(H.getEventCount).get(e).cnt;for(let u of i)this.stmt(H.checkDuplicate).get(e,pS,u.event.type,u.dataHash)||(c>=dS?this.stmt(H.evictLowestPriority).run(e):c++,this.stmt(H.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(H.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(H.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(H.getEventsByType).all(e,o,n):s!==void 0?this.stmt(H.getEventsByPriority).all(e,s,n):this.stmt(H.getEvents).all(e,n)}getEventCount(e){return this.stmt(H.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(H.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(H.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(H.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(H.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(H.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(H.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(H.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(H.getResume).get(e)??null}markResumeConsumed(e){this.stmt(H.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(H.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(H.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(H.getToolCallTotals).get(e),n=this.stmt(H.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(H.deleteEvents).run(e),this.stmt(H.deleteResume).run(e),this.stmt(H.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(H.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}}});import{join as Ko,resolve as SS}from"node:path";import{accessSync as jD,copyFileSync as zD,constants as LD,mkdirSync as UD}from"node:fs";import{homedir as vm}from"node:os";function Qt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?SS(vm(),e.replace(/^~[/\\]?/,"")):SS(e)}var be,it=ce(()=>{"use strict";on();be=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=Qt(),r=e?Ko(e,"context-mode","sessions"):Ko(vm(),...this.sessionDirSegments,"context-mode","sessions");return UD(r,{recursive:!0}),r}getConfigDir(e){return Ko(vm(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=Qt(),n=r?Ko(r,"context-mode","memory"):Ko(this.getConfigDir(),"memory");return e?Ko(n,st(e)):n}backupSettings(){let e=this.getSettingsPath();try{jD(e,LD.R_OK);let r=e+".bak";return zD(e,r),r}catch{return null}}}});var Go,bm=ce(()=>{"use strict";it();Go=class extends be{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});async function HD(){if(Jo)return Jo;if(Pi)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Jo=n,Jo}catch(n){e=n}return Pi=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return Pi=t instanceof Error?t.message:String(t),null}}function kS(t){if(Jo){let e=Jo.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}return Pi?{status:"FAIL",detail:`integrity helper unavailable: ${Pi}`}:{status:"FAIL",detail:"integrity helper not yet loaded"}}var Jo,Pi,ES=ce(()=>{"use strict";Jo=null,Pi=null;HD()});function Ie(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function zc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}var sn=ce(()=>{"use strict"});function Ri(t,e){let r=Bn[e],n=Sm(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Sm(t,e){if(e){let r=Bn[t];return Ie(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function km(t){let e=zc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function PS(t){let e=Object.values(Bn);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var er,FD,xm,wS,ZD,KB,Bn,TS,GB,RS=ce(()=>{"use strict";sn();er={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},FD="mcp__",xm=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",FD],wS=xm.join("|"),ZD=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],KB=ZD.join("|"),Bn={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},TS=[er.PRE_TOOL_USE,er.SESSION_START],GB=[er.POST_TOOL_USE,er.PRE_COMPACT,er.USER_PROMPT_SUBMIT]});var wm={};Ue(wm,{ClaudeCodeAdapter:()=>Em});import{readFileSync as Lc,writeFileSync as $S,existsSync as CS,readdirSync as qD,chmodSync as BD,accessSync as VD,mkdirSync as WD,constants as KD}from"node:fs";import{resolve as Uc,join as an}from"node:path";import{homedir as OS}from"node:os";var Em,Tm=ce(()=>{"use strict";bm();it();Vn();ES();sn();RS();Em=class extends Go{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return St()}getSessionDir(){let e=Qt(),r=e?an(e,"context-mode","sessions"):an(this.getConfigDir(),"context-mode","sessions");return WD(r,{recursive:!0}),r}getSettingsPath(){return an(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Ie(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...xm].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Lc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){$S(this.getSettingsPath(),JSON.stringify(e,null,2)+`
130
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,er.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,er.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(Bn).map(([o,s])=>{let i=an(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>CS(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>kS(e)};return[...r,n]}readPluginHooks(e){let r=[an(e,"hooks","hooks.json"),an(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=Lc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>Ri(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>Ri(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=an(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Lc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),St(),Uc(OS(),".claude"),Uc(OS(),".config","claude")]));for(let r of e){let n=Uc(r,"plugins","cache","context-mode","context-mode");try{let s=qD(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(d=>{let f=d;if(!PS(f))return!0;let m=f.hooks??[];return m.every(h=>!h.command||!km(h.command))?!0:m.every(h=>{let g=h.command?km(h.command):null;return g?CS(g):!0})}),l=c.length-u.length;l>0&&(n[a]=u,o.push(`Removed ${l} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&TS.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(Bn),u=l=>l!=null&&(c.some(d=>l.includes(d))||l.includes("context-mode hook"));for(let l of Object.keys(n)){let d=n[l];if(!Array.isArray(d))continue;let f=0;for(let p of d){let h=p,g=h.hooks??[],y=g.length;h.hooks=g.filter(v=>!u(v.command)),f+=y-h.hooks.length}let m=d.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(f>0||m.length!==d.length)&&(n[l]=m,f>0&&o.push(`Removed ${f} duplicate ${l} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[er.PRE_TOOL_USE,er.SESSION_START];for(let a of i){let c=Sm(a,e);if(a===er.PRE_TOOL_USE){let u={matcher:wS,hooks:[{type:"command",command:c}]},l=n.PreToolUse;if(l&&Array.isArray(l)){let d=l.findIndex(f=>Ri(f,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=l}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},l=n[a];if(l&&Array.isArray(l)){let d=l.findIndex(f=>Ri(f,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n[a]=l}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Bn)){let o=Uc(e,"hooks",n);try{VD(o,KD.R_OK),BD(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=an(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Lc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();$S(n,JSON.stringify(o,null,2)+`
131
- `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Wn(t,e){let r=Pm[t];return e&&r?Ie(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Ee,IS,Pm,a2,c2,AS=ce(()=>{"use strict";sn();Ee={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},IS="mcp__(?!.*context-mode)",Pm={[Ee.BEFORE_AGENT]:"beforeagent.mjs",[Ee.BEFORE_TOOL]:"beforetool.mjs",[Ee.AFTER_TOOL]:"aftertool.mjs",[Ee.PRE_COMPRESS]:"precompress.mjs",[Ee.SESSION_START]:"sessionstart.mjs"},a2=[Ee.BEFORE_TOOL,Ee.SESSION_START],c2=[Ee.AFTER_TOOL,Ee.PRE_COMPRESS]});var DS={};Ue(DS,{GeminiCLIAdapter:()=>$m});import{readFileSync as Rm,writeFileSync as NS,mkdirSync as GD,accessSync as JD,chmodSync as YD,constants as XD}from"node:fs";import{resolve as $i,join as QD}from"node:path";import{homedir as Hc}from"node:os";var $m,MS=ce(()=>{"use strict";it();AS();$m=class extends be{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return $i(Hc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Ee.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Wn(Ee.BEFORE_AGENT,e)}]}],[Ee.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${IS}`,hooks:[{type:"command",command:Wn(Ee.BEFORE_TOOL,e)}]}],[Ee.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Wn(Ee.AFTER_TOOL,e)}]}],[Ee.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Wn(Ee.PRE_COMPRESS,e)}]}],[Ee.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Wn(Ee.SESSION_START,e)}]}]}}readSettings(){try{let e=Rm(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=$i(Hc(),".gemini");GD(r,{recursive:!0}),NS(this.getSettingsPath(),JSON.stringify(e,null,2)+`
132
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[Ee.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[Ee.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=$i(Hc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Rm(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:Ee.BEFORE_AGENT},{name:Ee.BEFORE_TOOL},{name:Ee.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Wn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(m=>m.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=QD(e,"hooks","gemini-cli");for(let o of Object.values(Pm)){let s=$i(n,o);try{JD(s,XD.R_OK),YD(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=$i(Hc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Rm(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),NS(n,JSON.stringify(o,null,2)+`
133
- `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var Kn,g2,y2,jS=ce(()=>{"use strict";Kn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},g2=[Kn.BEFORE,Kn.AFTER],y2=[Kn.COMPACTING]});var LS={};Ue(LS,{OpenCodeAdapter:()=>Cm});import{readFileSync as zS,writeFileSync as tM,mkdirSync as rM,copyFileSync as nM,accessSync as oM,constants as sM}from"node:fs";import{resolve as jt,join as Cr}from"node:path";import{homedir as cn}from"node:os";function eM(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Cm,US=ce(()=>{"use strict";it();jS();Cm=class extends be{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??jt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[jt("kilo.json"),jt("kilo.jsonc"),jt(".kilo","kilo.json"),jt(".kilo","kilo.jsonc"),jt(".kilocode","kilo.json"),jt(".kilocode","kilo.jsonc"),Cr(cn(),".config","kilo","kilo.json"),Cr(cn(),".config","kilo","kilo.jsonc")]:[jt("opencode.json"),jt("opencode.jsonc"),jt(".opencode","opencode.json"),jt(".opencode","opencode.jsonc"),Cr(cn(),".config","opencode","opencode.json"),Cr(cn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Qt(),r=e?Cr(e,"context-mode","sessions"):Cr(this.getConfigDir(),"context-mode","sessions");return rM(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Cr(cn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Cr(cn(),".config"),Cr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Kn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Kn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Kn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(cn()))),n=null,o;for(let s of e)try{let i=zS(s,"utf-8"),a=s.endsWith(".jsonc")?eM(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){tM(this.getSettingsPath(),JSON.stringify(e,null,2)+`
134
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=jt(cn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(zS(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{oM(this.settingsPath,sM.R_OK);let r=this.settingsPath+".bak";return nM(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Gn,E2,w2,HS=ce(()=>{"use strict";Gn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},E2=[Gn.TOOL_CALL_BEFORE,Gn.TOOL_CALL_AFTER],w2=[Gn.COMMAND_NEW]});var FS={};Ue(FS,{OpenClawAdapter:()=>Nm});import{readFileSync as Om,writeFileSync as iM,copyFileSync as aM,accessSync as cM,constants as uM}from"node:fs";import{resolve as Or,join as Im}from"node:path";import{homedir as Am}from"node:os";var Nm,ZS=ce(()=>{"use strict";it();HS();Nm=class extends be{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Or("openclaw.json")}getConfigDir(e){return Or(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Im(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[Gn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Im(Am(),".openclaw","openclaw.json")];for(let r of e)try{let n=Om(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Or("openclaw.json");iM(r,JSON.stringify(e,null,2)+`
135
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Or(Am(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Om(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Or("node_modules","context-mode","package.json"),r=JSON.parse(Om(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Or("openclaw.json"),Or(".openclaw","openclaw.json"),Im(Am(),".openclaw","openclaw.json")];for(let r of e)try{cM(r,uM.R_OK);let n=r+".bak";return aM(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as qS}from"node:os";import{resolve as Dm}from"node:path";function BS(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Dm(qS(),t.replace(/^~[/\\]?/,"")):Dm(t):Dm(qS(),".codex")}var VS=ce(()=>{"use strict"});var JS={};Ue(JS,{CodexAdapter:()=>zm});import{readFileSync as Yo,writeFileSync as WS,accessSync as lM,copyFileSync as dM,constants as pM,mkdirSync as Mm}from"node:fs";import{resolve as fM,dirname as jm,join as Jn}from"node:path";import{fileURLToPath as mM}from"node:url";function KS(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
136
- `):null}function GS(t){let e=KS(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function yM(t){let e=KS(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function _M(t){if(GS(t))return{text:t,changed:!1};let e=t.includes(`\r
129
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",o,s){let i=wi("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??r.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??r.attribution_source??"unknown"),u=Number(o?.confidence??r.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=Dc(s?.bytesAvoided),f=Dc(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(F.checkDuplicate).get(e,yS,r.type,i))return;this.stmt(F.getEventCount).get(e).cnt>=gS&&this.stmt(F.evictLowestPriority).run(e),this.stmt(F.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,l,d,f,n,i),this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,r,n="PostToolUse",o,s){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0],s?.[0]);return}let i=r.map((c,u)=>{let l=wi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),d=o?.[u],f=String(d?.projectDir??c.project_dir??this._getSessionProjectDir(e)??"").trim(),m=String(d?.source??c.attribution_source??"unknown"),p=Number(d?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=s?.[u],y=Dc(g?.bytesAvoided),v=Dc(g?.bytesReturned);return{event:c,dataHash:l,projectDir:f,attributionSource:m,attributionConfidence:h,bytesAvoided:y,bytesReturned:v}}),a=this.db.transaction(()=>{let c=this.stmt(F.getEventCount).get(e).cnt;for(let u of i)this.stmt(F.checkDuplicate).get(e,yS,u.event.type,u.dataHash)||(c>=gS?this.stmt(F.evictLowestPriority).run(e):c++,this.stmt(F.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(F.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(F.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(F.getEventsByType).all(e,o,n):s!==void 0?this.stmt(F.getEventsByPriority).all(e,s,n):this.stmt(F.getEvents).all(e,n)}getEventCount(e){return this.stmt(F.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(F.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(F.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(F.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(F.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(F.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(F.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(F.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(F.getResume).get(e)??null}markResumeConsumed(e){this.stmt(F.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(F.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(F.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(F.getToolCallTotals).get(e),n=this.stmt(F.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(F.deleteEvents).run(e),this.stmt(F.deleteResume).run(e),this.stmt(F.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(F.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}}});import{join as Go,resolve as $S}from"node:path";import{accessSync as aM,copyFileSync as cM,constants as uM,mkdirSync as lM}from"node:fs";import{homedir as Sm}from"node:os";function er(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?$S(Sm(),e.replace(/^~[/\\]?/,"")):$S(e)}var xe,ut=ce(()=>{"use strict";Cr();xe=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=er(),r=e?Go(e,"context-mode","sessions"):Go(Sm(),...this.sessionDirSegments,"context-mode","sessions");return lM(r,{recursive:!0}),r}getConfigDir(e){return Go(Sm(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let r=er(),n=r?Go(r,"context-mode","memory"):Go(this.getConfigDir(),"memory");return e?Go(n,ct(e)):n}backupSettings(){let e=this.getSettingsPath();try{aM(e,uM.R_OK);let r=e+".bak";return cM(e,r),r}catch{return null}}}});var Jo,km=ce(()=>{"use strict";ut();Jo=class extends xe{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});async function dM(){if(Xo)return Xo;if($i)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Xo=n,Xo}catch(n){e=n}return $i=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return $i=t instanceof Error?t.message:String(t),null}}function CS(t){if(Xo){let e=Xo.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}return $i?{status:"FAIL",detail:`integrity helper unavailable: ${$i}`}:{status:"FAIL",detail:"integrity helper not yet loaded"}}var Xo,$i,OS=ce(()=>{"use strict";Xo=null,$i=null;dM()});function Ie(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function Uc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}var sn=ce(()=>{"use strict"});function Ci(t,e){let r=Vn[e],n=wm(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function wm(t,e){if(e){let r=Vn[t];return Ie(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Tm(t){let e=Uc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function NS(t){let e=Object.values(Vn);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var tr,pM,Em,IS,fM,E2,Vn,AS,w2,DS=ce(()=>{"use strict";sn();tr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},pM="mcp__",Em=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",pM],IS=Em.join("|"),fM=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],E2=fM.join("|"),Vn={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},AS=[tr.PRE_TOOL_USE,tr.SESSION_START],w2=[tr.POST_TOOL_USE,tr.PRE_COMPACT,tr.USER_PROMPT_SUBMIT]});var Pm={};Fe(Pm,{ClaudeCodeAdapter:()=>Rm});import{readFileSync as Hc,writeFileSync as MS,existsSync as jS,readdirSync as mM,chmodSync as hM,accessSync as gM,mkdirSync as yM,constants as _M}from"node:fs";import{resolve as Fc,join as an}from"node:path";import{homedir as zS}from"node:os";var Rm,$m=ce(()=>{"use strict";km();ut();Wn();OS();sn();DS();Rm=class extends Jo{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return St()}getSessionDir(){let e=er(),r=e?an(e,"context-mode","sessions"):an(this.getConfigDir(),"context-mode","sessions");return yM(r,{recursive:!0}),r}getSettingsPath(){return an(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=Ie(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Em].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Hc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){MS(this.getSettingsPath(),JSON.stringify(e,null,2)+`
130
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,tr.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,tr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(Vn).map(([o,s])=>{let i=an(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>jS(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>CS(e)};return[...r,n]}readPluginHooks(e){let r=[an(e,"hooks","hooks.json"),an(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=Hc(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>Ci(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>Ci(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=an(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Hc(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=Array.from(new Set([this.getConfigDir(),St(),Fc(zS(),".claude"),Fc(zS(),".config","claude")]));for(let r of e){let n=Fc(r,"plugins","cache","context-mode","context-mode");try{let s=mM(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(d=>{let f=d;if(!NS(f))return!0;let m=f.hooks??[];return m.every(h=>!h.command||!Tm(h.command))?!0:m.every(h=>{let g=h.command?Tm(h.command):null;return g?jS(g):!0})}),l=c.length-u.length;l>0&&(n[a]=u,o.push(`Removed ${l} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&AS.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(Vn),u=l=>l!=null&&(c.some(d=>l.includes(d))||l.includes("context-mode hook"));for(let l of Object.keys(n)){let d=n[l];if(!Array.isArray(d))continue;let f=0;for(let p of d){let h=p,g=h.hooks??[],y=g.length;h.hooks=g.filter(v=>!u(v.command)),f+=y-h.hooks.length}let m=d.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(f>0||m.length!==d.length)&&(n[l]=m,f>0&&o.push(`Removed ${f} duplicate ${l} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[tr.PRE_TOOL_USE,tr.SESSION_START];for(let a of i){let c=wm(a,e);if(a===tr.PRE_TOOL_USE){let u={matcher:IS,hooks:[{type:"command",command:c}]},l=n.PreToolUse;if(l&&Array.isArray(l)){let d=l.findIndex(f=>Ci(f,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=l}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},l=n[a];if(l&&Array.isArray(l)){let d=l.findIndex(f=>Ci(f,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n[a]=l}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(Vn)){let o=Fc(e,"hooks",n);try{gM(o,_M.R_OK),hM(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=an(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(Hc(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();MS(n,JSON.stringify(o,null,2)+`
131
+ `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function Kn(t,e){let r=Cm[t];return e&&r?Ie(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var we,LS,Cm,j2,z2,US=ce(()=>{"use strict";sn();we={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},LS="mcp__(?!.*context-mode)",Cm={[we.BEFORE_AGENT]:"beforeagent.mjs",[we.BEFORE_TOOL]:"beforetool.mjs",[we.AFTER_TOOL]:"aftertool.mjs",[we.PRE_COMPRESS]:"precompress.mjs",[we.SESSION_START]:"sessionstart.mjs"},j2=[we.BEFORE_TOOL,we.SESSION_START],z2=[we.AFTER_TOOL,we.PRE_COMPRESS]});var FS={};Fe(FS,{GeminiCLIAdapter:()=>Im});import{readFileSync as Om,writeFileSync as HS,mkdirSync as vM,accessSync as xM,chmodSync as bM,constants as SM}from"node:fs";import{resolve as Oi,join as kM}from"node:path";import{homedir as Zc}from"node:os";var Im,ZS=ce(()=>{"use strict";ut();US();Im=class extends xe{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Oi(Zc(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[we.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Kn(we.BEFORE_AGENT,e)}]}],[we.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${LS}`,hooks:[{type:"command",command:Kn(we.BEFORE_TOOL,e)}]}],[we.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Kn(we.AFTER_TOOL,e)}]}],[we.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Kn(we.PRE_COMPRESS,e)}]}],[we.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Kn(we.SESSION_START,e)}]}]}}readSettings(){try{let e=Om(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Oi(Zc(),".gemini");vM(r,{recursive:!0}),HS(this.getSettingsPath(),JSON.stringify(e,null,2)+`
132
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[we.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[we.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Oi(Zc(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Om(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:we.BEFORE_AGENT},{name:we.BEFORE_TOOL},{name:we.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:Kn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(m=>m.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=kM(e,"hooks","gemini-cli");for(let o of Object.values(Cm)){let s=Oi(n,o);try{xM(s,SM.R_OK),bM(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Oi(Zc(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Om(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),HS(n,JSON.stringify(o,null,2)+`
133
+ `,"utf-8")}catch{}}getProjectDir(e){return e.cwd??process.env.GEMINI_PROJECT_DIR??process.env.CLAUDE_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});var Gn,V2,W2,qS=ce(()=>{"use strict";Gn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},V2=[Gn.BEFORE,Gn.AFTER],W2=[Gn.COMPACTING]});var VS={};Fe(VS,{OpenCodeAdapter:()=>Am});import{readFileSync as BS,writeFileSync as wM,mkdirSync as TM,copyFileSync as RM,accessSync as PM,constants as $M}from"node:fs";import{resolve as jt,join as Or}from"node:path";import{homedir as cn}from"node:os";function EM(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Am,WS=ce(()=>{"use strict";ut();qS();Am=class extends xe{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??jt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[jt("kilo.json"),jt("kilo.jsonc"),jt(".kilo","kilo.json"),jt(".kilo","kilo.jsonc"),jt(".kilocode","kilo.json"),jt(".kilocode","kilo.jsonc"),Or(cn(),".config","kilo","kilo.json"),Or(cn(),".config","kilo","kilo.jsonc")]:[jt("opencode.json"),jt("opencode.jsonc"),jt(".opencode","opencode.json"),jt(".opencode","opencode.jsonc"),Or(cn(),".config","opencode","opencode.json"),Or(cn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=er(),r=e?Or(e,"context-mode","sessions"):Or(this.getConfigDir(),"context-mode","sessions");return TM(r,{recursive:!0}),r}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Or(cn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Or(cn(),".config"),Or(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Gn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Gn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(cn()))),n=null,o;for(let s of e)try{let i=BS(s,"utf-8"),a=s.endsWith(".jsonc")?EM(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){wM(this.getSettingsPath(),JSON.stringify(e,null,2)+`
134
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),r;let o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),this.hasLegacyContextModeMcp(n)&&r.push({check:"Legacy MCP registration",status:"warn",message:"mcp.context-mode is redundant: ctx_* tools are now provided by the plugin",fix:"context-mode upgrade (removes only mcp.context-mode; preserves other MCP servers)"}),r.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),r}checkPluginRegistration(){let e=this.readSettings();return e?this.hasContextModePlugin(e)?{check:"Plugin registration",status:"pass",message:"context-mode found in plugin array"}:{check:"Plugin registration",status:"fail",message:`context-mode not found in ${this.platform}.json plugin array`,fix:"context-mode upgrade"}:{check:"Plugin registration",status:"warn",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`}}getInstalledVersion(){try{let e=jt(cn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(BS(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];o.some(i=>i.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o;let s=r.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],n.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).length===0&&delete r.mcp}return this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{PM(this.settingsPath,$M.R_OK);let r=this.settingsPath+".bak";return RM(this.settingsPath,r),r}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}hasContextModePlugin(e){let r=e.plugin;return Array.isArray(r)&&r.some(n=>typeof n=="string"&&n.includes("context-mode"))}hasLegacyContextModeMcp(e){let r=e.mcp;return!!(r&&typeof r=="object"&&!Array.isArray(r)&&Object.prototype.hasOwnProperty.call(r,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var Jn,e4,t4,KS=ce(()=>{"use strict";Jn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},e4=[Jn.TOOL_CALL_BEFORE,Jn.TOOL_CALL_AFTER],t4=[Jn.COMMAND_NEW]});var GS={};Fe(GS,{OpenClawAdapter:()=>jm});import{readFileSync as Nm,writeFileSync as CM,copyFileSync as OM,accessSync as IM,constants as AM}from"node:fs";import{resolve as Ir,join as Dm}from"node:path";import{homedir as Mm}from"node:os";var jm,JS=ce(()=>{"use strict";ut();KS();jm=class extends xe{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ir("openclaw.json")}getConfigDir(e){return Ir(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Dm(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[Jn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Jn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Jn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Ir("openclaw.json"),Ir(".openclaw","openclaw.json"),Dm(Mm(),".openclaw","openclaw.json")];for(let r of e)try{let n=Nm(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Ir("openclaw.json");CM(r,JSON.stringify(e,null,2)+`
135
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),r;let o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=Ir(Mm(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Nm(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Ir("node_modules","context-mode","package.json"),r=JSON.parse(Nm(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[Ir("openclaw.json"),Ir(".openclaw","openclaw.json"),Dm(Mm(),".openclaw","openclaw.json")];for(let r of e)try{IM(r,AM.R_OK);let n=r+".bak";return OM(r,n),n}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getProjectDir(e){return e.cwd??process.env.OPENCLAW_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.sessionId?e.sessionId:`pid-${process.ppid}`}}});import{homedir as XS}from"node:os";import{resolve as zm}from"node:path";function YS(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?zm(XS(),t.replace(/^~[/\\]?/,"")):zm(t):zm(XS(),".codex")}var QS=ce(()=>{"use strict"});var ok={};Fe(ok,{CodexAdapter:()=>Hm,probeCodexCliVersion:()=>tk});import{execFileSync as NM}from"node:child_process";import{readFileSync as Yo,writeFileSync as ek,accessSync as DM,copyFileSync as MM,constants as jM,mkdirSync as Lm}from"node:fs";import{resolve as zM,dirname as Um,join as Xn}from"node:path";import{fileURLToPath as LM}from"node:url";function tk(t=NM){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","codex --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("codex",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),r=String(e).trim();return r.length>0?r:"available (version output empty)"}catch{return null}}function rk(t,e){let r=t.split(/\r?\n/),n=!1,o=[];for(let s of r){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(n)break;n=i[1]?.trim()===e;continue}n&&o.push(s)}return n?o.join(`
136
+ `):null}function nk(t){let e=rk(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function FM(t){let e=rk(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function ZM(t){if(nk(t))return{text:t,changed:!1};let e=t.includes(`\r
137
137
  `)?`\r
138
138
  `:`
139
139
  `,r=t.split(/\r?\n/),n=r.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(n===-1){let s=t.length>0&&!t.endsWith(`
140
- `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var hM,Yn,gM,zm,YS=ce(()=>{"use strict";it();on();VS();hM="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Yn={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},gM={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};zm=class extends be{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return BS()}getSettingsPath(){return Jn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Qt(),r=e?Jn(e,"context-mode","sessions"):Jn(this.getConfigDir(),"context-mode","sessions");return Mm(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=Qt(),n=r?Jn(r,"context-mode","memories"):Jn(this.getConfigDir(),"memories");return e?Jn(n,st(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:hM,hooks:[{type:"command",command:Yn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Yn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Yn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Yn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Yn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Yn.Stop}]}]}}readSettings(){try{return{_raw_toml:Yo(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let a=Yo(this.getSettingsPath(),"utf-8"),c=GS(a),u=!c&&yM(a);r.push({check:"Codex hooks feature flag",status:c?"pass":"fail",message:c?`[features].hooks enabled in ${this.getSettingsPath()}`:u?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...c?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let n=this.readHooksConfig();if(!n.ok)return n.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):n.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${n.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${n.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!n.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let o=this.generateHookConfig(""),s=Object.entries(o).map(([a,c])=>{let u=n.config.hooks?.[a],l=c[0],d=Array.isArray(u)&&u.some(m=>this.isExpectedHookEntry(a,m,l)),f=a==="PreCompact"?"warn":"fail";return{check:`${a} hook`,status:d?"pass":f,message:d?`${a} hook configured in ${this.getHooksPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:d?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),i=[];for(let a of Object.keys(o)){let c=n.config.hooks?.[a];if(!Array.isArray(c))continue;let u=c.filter(l=>this.isManagedContextModeEntry(a,l)).length;u>1&&i.push({check:`${a} duplicates`,status:"warn",message:`${u} context-mode entries found for ${a} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r.concat(s,i)}checkPluginRegistration(){try{let e=Yo(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o;if(r.ok)o=r.config;else if(r.reason==="missing")o={hooks:{}};else if(r.reason==="invalid_json"){let l=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${l}`),o={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let s=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:{},i=this.generateHookConfig(e);for(let[l,d]of Object.entries(i))this.upsertManagedHookEntry(s,l,d[0],n);n.length>0&&(o.hooks=s,this.writeHooksConfig(o),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=Yo(a,"utf-8")}catch{c=""}let u=_M(c);if(u.changed){let l=u.text.includes(`\r
140
+ `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=r.length;for(let s=n+1;s<r.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(r[s]??"")){o=s;break}for(let s=n+1;s<o;s++)if(/^\s*hooks\s*=/.test(r[s]??""))return r[s]="hooks = true",{text:r.join(e),changed:!0};return r.splice(n+1,0,"hooks = true"),{text:r.join(e),changed:!0}}var UM,Yn,HM,Hm,sk=ce(()=>{"use strict";ut();Cr();QS();UM="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Yn={PreToolUse:"context-mode hook codex pretooluse",PostToolUse:"context-mode hook codex posttooluse",SessionStart:"context-mode hook codex sessionstart",PreCompact:"context-mode hook codex precompact",UserPromptSubmit:"context-mode hook codex userpromptsubmit",Stop:"context-mode hook codex stop"},HM={PreToolUse:["hooks/pretooluse.mjs","hooks/codex/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/codex/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/codex/sessionstart.mjs"],PreCompact:["hooks/precompact.mjs","hooks/codex/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/codex/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/codex/stop.mjs"]};Hm=class extends xe{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return YS()}getSettingsPath(){return Xn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=er(),r=e?Xn(e,"context-mode","sessions"):Xn(this.getConfigDir(),"context-mode","sessions");return Lm(r,{recursive:!0}),r}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let r=er(),n=r?Xn(r,"context-mode","memories"):Xn(this.getConfigDir(),"memories");return e?Xn(n,ct(e)):n}generateHookConfig(e){return{PreToolUse:[{matcher:UM,hooks:[{type:"command",command:Yn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Yn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Yn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Yn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Yn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Yn.Stop}]}]}}readSettings(){try{return{_raw_toml:Yo(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[],n=tk();r.push({check:"Codex CLI binary",status:n?"pass":"warn",message:n?`codex --version resolved to ${n}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...n?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{let c=Yo(this.getSettingsPath(),"utf-8"),u=nk(c),l=!u&&FM(c);r.push({check:"Codex hooks feature flag",status:u?"pass":"fail",message:u?`[features].hooks enabled in ${this.getSettingsPath()}`:l?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...u?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let o=this.readHooksConfig();if(!o.ok)return o.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):o.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${o.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${o.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!o.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig(""),i=Object.entries(s).map(([c,u])=>{let l=o.config.hooks?.[c],d=u[0],f=Array.isArray(l)&&l.some(p=>this.isExpectedHookEntry(c,p,d)),m=c==="PreCompact"?"warn":"fail";return{check:`${c} hook`,status:f?"pass":m,message:f?`${c} hook configured in ${this.getHooksPath()}`:c==="PreCompact"?`${c} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${c} hook missing or not pointing to context-mode`,fix:f?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),a=[];for(let c of Object.keys(s)){let u=o.config.hooks?.[c];if(!Array.isArray(u))continue;let l=u.filter(d=>this.isManagedContextModeEntry(c,d)).length;l>1&&a.push({check:`${c} duplicates`,status:"warn",message:`${l} context-mode entries found for ${c} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return r.concat(i,a)}checkPluginRegistration(){try{let e=Yo(this.getSettingsPath(),"utf-8"),r=e.includes("context-mode"),n=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return r&&n?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:n?{check:"MCP registration",status:"fail",message:"[mcp_servers] section exists but context-mode not found",fix:`Add context-mode to [mcp_servers] in ${this.getSettingsPath()}`}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:`Add [mcp_servers.context-mode] to ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let r=this.readHooksConfig(),n=[],o;if(r.ok)o=r.config;else if(r.reason==="missing")o={hooks:{}};else if(r.reason==="invalid_json"){let l=this.backupFile(this.getHooksPath(),".broken");n.push(`Backed up malformed Codex hooks to ${l}`),o={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${r.error}`);let s=o.hooks&&typeof o.hooks=="object"&&!Array.isArray(o.hooks)?o.hooks:{},i=this.generateHookConfig(e);for(let[l,d]of Object.entries(i))this.upsertManagedHookEntry(s,l,d[0],n);n.length>0&&(o.hooks=s,this.writeHooksConfig(o),n.push(`Wrote native Codex hooks to ${this.getHooksPath()}`));let a=this.getSettingsPath(),c="";try{c=Yo(a,"utf-8")}catch{c=""}let u=ZM(c);if(u.changed){let l=u.text.includes(`\r
141
141
  `)?`\r
142
142
  `:`
143
143
  `,d=u.text.endsWith(`
144
- `)?u.text:`${u.text}${l}`;Mm(jm(a),{recursive:!0}),WS(a,d,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{lM(r,pM.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=fM(jm(mM(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Yo(e,"utf-8")}catch{return`# context-mode
144
+ `)?u.text:`${u.text}${l}`;Lm(Um(a),{recursive:!0}),ek(a,d,"utf-8"),n.push("Enabled Codex hooks feature flag")}return n}backupSettings(){let e=null;for(let r of[this.getHooksPath(),this.getSettingsPath()])try{DM(r,jM.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=zM(Um(LM(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Yo(e,"utf-8")}catch{return`# context-mode
145
145
 
146
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Jn(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return dM(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Yo(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();Mm(jm(r),{recursive:!0}),WS(r,JSON.stringify(e,null,2)+`
147
- `,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(Yn[e]??""),s=gM[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as XS,writeFileSync as vM,mkdirSync as bM,accessSync as xM,chmodSync as SM,constants as kM}from"node:fs";import{resolve as Fc,join as EM}from"node:path";var Xo,Lm=ce(()=>{"use strict";it();Xo=class extends be{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return Fc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=XS(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=XS(Fc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();bM(Fc(".github","hooks"),{recursive:!0}),vM(r,JSON.stringify(e,null,2)+`
148
- `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=EM(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Fc(n,o);try{xM(s,kM.R_OK),SM(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function QS(t,e){if(!Um[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var zt,Um,B2,V2,ek=ce(()=>{"use strict";zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Um={[zt.PRE_TOOL_USE]:"pretooluse.mjs",[zt.POST_TOOL_USE]:"posttooluse.mjs",[zt.PRE_COMPACT]:"precompact.mjs",[zt.SESSION_START]:"sessionstart.mjs"},B2=[zt.PRE_TOOL_USE,zt.SESSION_START],V2=[zt.POST_TOOL_USE,zt.PRE_COMPACT]});var rk={};Ue(rk,{VSCodeCopilotAdapter:()=>Zm});import{readFileSync as Hm,mkdirSync as tk,accessSync as wM,existsSync as TM,constants as PM}from"node:fs";import{resolve as Qo,join as Ci}from"node:path";import{homedir as Fm}from"node:os";var Zm,nk=ce(()=>{"use strict";Lm();it();ek();Zm=class extends Xo{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:zt,HOOK_SCRIPTS:Um,buildHookCommand:QS};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.cwd()}getSessionDir(){let e=Qt();if(e){let s=Ci(e,"context-mode","sessions");return tk(s,{recursive:!0}),s}let r=Qo(".github","context-mode","sessions"),n=Ci(Fm(),".vscode","context-mode","sessions"),o=TM(Qo(".github"))?r:n;return tk(o,{recursive:!0}),o}getConfigDir(e){return Qo(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=Qo(".github","hooks");try{wM(n,PM.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=Qo(n,"context-mode.json");try{let s=Hm(o,"utf-8"),a=JSON.parse(s).hooks;a?.[zt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[zt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=Qo(".vscode","mcp.json"),r=Hm(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ci(Fm(),".vscode","extensions"),Ci(Fm(),".vscode-insiders","extensions")];for(let r of e)try{let n=Hm(Ci(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function ok(t,e){if(!qm[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Lt,qm,e4,t4,sk=ce(()=>{"use strict";Lt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},qm={[Lt.PRE_TOOL_USE]:"pretooluse.mjs",[Lt.POST_TOOL_USE]:"posttooluse.mjs",[Lt.PRE_COMPACT]:"precompact.mjs",[Lt.SESSION_START]:"sessionstart.mjs"},e4=[Lt.PRE_TOOL_USE,Lt.SESSION_START],t4=[Lt.POST_TOOL_USE,Lt.PRE_COMPACT]});var ik={};Ue(ik,{JetBrainsCopilotAdapter:()=>Bm});import{readFileSync as RM}from"node:fs";import{resolve as $M}from"node:path";var Bm,ak=ce(()=>{"use strict";Lm();sk();Bm=class extends Xo{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Lt,HOOK_SCRIPTS:qm,buildHookCommand:ok};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return $M(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=RM(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Lt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Lt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Oi(t,e){let r=Vm[e],n=Ut(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ut(t){return`context-mode hook cursor ${t.toLowerCase()}`}var he,Vm,CM,OM,Wm,ck,uk,lk=ce(()=>{"use strict";he={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Vm={[he.PRE_TOOL_USE]:"pretooluse.mjs",[he.POST_TOOL_USE]:"posttooluse.mjs",[he.SESSION_START]:"sessionstart.mjs",[he.STOP]:"stop.mjs",[he.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},CM="MCP:(?!ctx_)",OM=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",CM],Wm=OM.join("|"),ck=[he.PRE_TOOL_USE],uk=[he.POST_TOOL_USE]});var hk={};Ue(hk,{CursorAdapter:()=>Km});import{readFileSync as Zc,writeFileSync as IM,mkdirSync as AM,accessSync as dk,chmodSync as NM,constants as pk,existsSync as fk,readdirSync as DM}from"node:fs";import{execSync as MM}from"node:child_process";import{resolve as Xn,join as Qn}from"node:path";import{homedir as qc}from"node:os";var mk,Km,gk=ce(()=>{"use strict";it();Vn();lk();mk="/Library/Application Support/Cursor/hooks.json",Km=class extends be{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Xn(".cursor","hooks.json")}getConfigDir(e){return Xn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[he.PRE_TOOL_USE]:[{type:"command",command:Ut(he.PRE_TOOL_USE),matcher:Wm,loop_limit:null,failClosed:!1}],[he.POST_TOOL_USE]:[{type:"command",command:Ut(he.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[he.SESSION_START]:[{type:"command",command:Ut(he.SESSION_START),loop_limit:null,failClosed:!1}],[he.STOP]:[{type:"command",command:Ut(he.STOP),loop_limit:null,failClosed:!1}],[he.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ut(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Zc(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();AM(Xn(".cursor"),{recursive:!0}),IM(r,JSON.stringify(e,null,2)+`
149
- `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of ck){let a=s[i],c=Array.isArray(a)&&a.some(u=>Oi(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of uk){let a=s[i],c=Array.isArray(a)&&a.some(u=>Oi(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}fk(mk)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Oi(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[Qn(qc(),".cursor","plugins","local"),Qn(qc(),".cursor","plugins","cache")],r=[];for(let n of e){try{dk(n,pk.F_OK)}catch{continue}let o=[];try{o=DM(n)}catch{continue}for(let s of o){let i=Qn(n,s,".cursor-plugin","plugin.json");try{let a=Zc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Xn(".cursor","mcp.json"),Qn(qc(),".cursor","mcp.json")];for(let n of e)try{let o=Zc(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return MM("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,he.PRE_TOOL_USE,{type:"command",command:Ut(he.PRE_TOOL_USE),matcher:Wm,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.POST_TOOL_USE,{type:"command",command:Ut(he.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.SESSION_START,{type:"command",command:Ut(he.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.STOP,{type:"command",command:Ut(he.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.AFTER_AGENT_RESPONSE,{type:"command",command:Ut(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=Qn(e,"hooks","cursor");for(let o of Object.values(Vm)){let s=Xn(n,o);try{dk(s,pk.R_OK),NM(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Qn(qc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(mk),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Zc(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Xn(".claude","settings.json"),Xn(".claude","settings.local.json"),Qn(St(),"settings.json")].some(r=>fk(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Oi(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var _k={};Ue(_k,{AntigravityAdapter:()=>Jm});import{readFileSync as Bc,writeFileSync as jM,mkdirSync as zM}from"node:fs";import{resolve as Vc,dirname as yk}from"node:path";import{fileURLToPath as LM}from"node:url";import{homedir as Gm}from"node:os";var Jm,vk=ce(()=>{"use strict";it();Jm=class extends be{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Vc(Gm(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Vc(Gm(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Bc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();zM(yk(r),{recursive:!0}),jM(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Bc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Vc(Gm(),".gemini","extensions","context-mode","package.json");return JSON.parse(Bc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Vc(yk(LM(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Bc(e,"utf-8")}catch{return`# context-mode
146
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}getProjectDir(e){return e.cwd??process.env.CODEX_PROJECT_DIR??process.cwd()}getHooksPath(){return Xn(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return MM(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Yo(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();Lm(Um(r),{recursive:!0}),ek(r,JSON.stringify(e,null,2)+`
147
+ `,"utf-8")}upsertManagedHookEntry(e,r,n,o){let s=Array.isArray(e[r])?[...e[r]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(r,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(n),e[r]=s,o.push(`Added ${r} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(n)&&(s[a]=n,o.push(`Updated ${r} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${r} context-mode hook`);e[r]=s}isExpectedHookEntry(e,r,n){return!r||typeof r!="object"||e==="PreToolUse"&&r.matcher!==n.matcher?!1:this.entryContainsManagedCommand(e,r)}isManagedContextModeEntry(e,r){return!r||typeof r!="object"?!1:this.entryContainsManagedCommand(e,r)}entryContainsManagedCommand(e,r){let n=(Array.isArray(r.hooks)?r.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(Yn[e]??""),s=HM[e]??[];return n.some(i=>i.includes(o)||s.some(a=>i.includes(a)))}normalizeCommand(e){return(e??"").replace(/\\/g,"/")}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as ik,writeFileSync as qM,mkdirSync as BM,accessSync as VM,chmodSync as WM,constants as KM}from"node:fs";import{resolve as qc,join as GM}from"node:path";var Qo,Fm=ce(()=>{"use strict";ut();Qo=class extends xe{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(e){return qc(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:r,buildHookCommand:n}=this.hookModule;return{[r.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_TOOL_USE,e)}]}],[r.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:n(r.POST_TOOL_USE,e)}]}],[r.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:n(r.PRE_COMPACT,e)}]}],[r.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:n(r.SESSION_START,e)}]}]}}readSettings(){try{let e=ik(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=ik(qc(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();BM(qc(".github","hooks"),{recursive:!0}),qM(r,JSON.stringify(e,null,2)+`
148
+ `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=GM(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=qc(n,o);try{VM(s,KM.R_OK),WM(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function ak(t,e){if(!Zm[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var zt,Zm,S4,k4,ck=ce(()=>{"use strict";zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Zm={[zt.PRE_TOOL_USE]:"pretooluse.mjs",[zt.POST_TOOL_USE]:"posttooluse.mjs",[zt.PRE_COMPACT]:"precompact.mjs",[zt.SESSION_START]:"sessionstart.mjs"},S4=[zt.PRE_TOOL_USE,zt.SESSION_START],k4=[zt.POST_TOOL_USE,zt.PRE_COMPACT]});var lk={};Fe(lk,{VSCodeCopilotAdapter:()=>Vm});import{readFileSync as qm,mkdirSync as uk,accessSync as JM,existsSync as XM,constants as YM}from"node:fs";import{resolve as es,join as Ii}from"node:path";import{homedir as Bm}from"node:os";var Vm,dk=ce(()=>{"use strict";Fm();ut();ck();Vm=class extends Qo{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:zt,HOOK_SCRIPTS:Zm,buildHookCommand:ak};hookSubdir="vscode-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.VSCODE_PID?`vscode-${process.env.VSCODE_PID}`:`pid-${process.ppid}`}getProjectDir(){return process.env.CLAUDE_PROJECT_DIR||process.cwd()}getSessionDir(){let e=er();if(e){let s=Ii(e,"context-mode","sessions");return uk(s,{recursive:!0}),s}let r=es(".github","context-mode","sessions"),n=Ii(Bm(),".vscode","context-mode","sessions"),o=XM(es(".github"))?r:n;return uk(o,{recursive:!0}),o}getConfigDir(e){return es(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=es(".github","hooks");try{JM(n,YM.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=es(n,"context-mode.json");try{let s=qm(o,"utf-8"),a=JSON.parse(s).hooks;a?.[zt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[zt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),r.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),r}checkPluginRegistration(){try{let e=es(".vscode","mcp.json"),r=qm(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[Ii(Bm(),".vscode","extensions"),Ii(Bm(),".vscode-insiders","extensions")];for(let r of e)try{let n=qm(Ii(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function pk(t,e){if(!Wm[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Lt,Wm,O4,I4,fk=ce(()=>{"use strict";Lt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Wm={[Lt.PRE_TOOL_USE]:"pretooluse.mjs",[Lt.POST_TOOL_USE]:"posttooluse.mjs",[Lt.PRE_COMPACT]:"precompact.mjs",[Lt.SESSION_START]:"sessionstart.mjs"},O4=[Lt.PRE_TOOL_USE,Lt.SESSION_START],I4=[Lt.POST_TOOL_USE,Lt.PRE_COMPACT]});var mk={};Fe(mk,{JetBrainsCopilotAdapter:()=>Km});import{readFileSync as QM}from"node:fs";import{resolve as ej}from"node:path";var Km,hk=ce(()=>{"use strict";Fm();fk();Km=class extends Qo{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Lt,HOOK_SCRIPTS:Wm,buildHookCommand:pk};hookSubdir="jetbrains-copilot";extractSessionId(e){return e.sessionId?e.sessionId:process.env.JETBRAINS_CLIENT_ID?`jetbrains-${process.env.JETBRAINS_CLIENT_ID}`:process.env.IDEA_HOME?`idea-${process.pid}`:`pid-${process.ppid}`}getProjectDir(){return process.env.IDEA_INITIAL_DIRECTORY||process.env.CLAUDE_PROJECT_DIR||process.cwd()}getConfigDir(e){return ej(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=QM(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Lt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Lt.SESSION_START]?r.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):r.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{r.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return r.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),r}checkPluginRegistration(){return{check:"MCP registration",status:"warn",message:"JetBrains stores MCP config via Settings UI \u2014 not CLI-inspectable",fix:"Verify in IDE: Settings > Tools > GitHub Copilot > MCP > ensure a context-mode server entry exists"}}getInstalledVersion(){let r=this.readSettings()?.hooks;return r&&Object.keys(r).length>0?"configured":"unknown"}}});function Ai(t,e){let r=Gm[e],n=Ut(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ut(t){return`context-mode hook cursor ${t.toLowerCase()}`}var he,Gm,tj,rj,Jm,gk,yk,_k=ce(()=>{"use strict";he={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Gm={[he.PRE_TOOL_USE]:"pretooluse.mjs",[he.POST_TOOL_USE]:"posttooluse.mjs",[he.SESSION_START]:"sessionstart.mjs",[he.STOP]:"stop.mjs",[he.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},tj="MCP:(?!ctx_)",rj=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",tj],Jm=rj.join("|"),gk=[he.PRE_TOOL_USE],yk=[he.POST_TOOL_USE]});var kk={};Fe(kk,{CursorAdapter:()=>Xm});import{readFileSync as Bc,writeFileSync as nj,mkdirSync as oj,accessSync as vk,chmodSync as sj,constants as xk,existsSync as bk,readdirSync as ij}from"node:fs";import{execSync as aj}from"node:child_process";import{resolve as Qn,join as eo}from"node:path";import{homedir as Vc}from"node:os";var Sk,Xm,Ek=ce(()=>{"use strict";ut();Wn();_k();Sk="/Library/Application Support/Cursor/hooks.json",Xm=class extends xe{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return Qn(".cursor","hooks.json")}getConfigDir(e){return Qn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[he.PRE_TOOL_USE]:[{type:"command",command:Ut(he.PRE_TOOL_USE),matcher:Jm,loop_limit:null,failClosed:!1}],[he.POST_TOOL_USE]:[{type:"command",command:Ut(he.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[he.SESSION_START]:[{type:"command",command:Ut(he.SESSION_START),loop_limit:null,failClosed:!1}],[he.STOP]:[{type:"command",command:Ut(he.STOP),loop_limit:null,failClosed:!1}],[he.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ut(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Bc(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();oj(Qn(".cursor"),{recursive:!0}),nj(r,JSON.stringify(e,null,2)+`
149
+ `,"utf-8")}validateHooks(e){let r=[],n=this.loadNativeHookConfig();if(!n)r.push({check:"Native hook config",status:"fail",message:"No readable native Cursor hook config found in .cursor/hooks.json or ~/.cursor/hooks.json",fix:"context-mode upgrade"});else{let s=n.config.hooks??{};r.push({check:"Native hook config",status:"pass",message:`Loaded ${n.path}`});for(let i of gk){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ai(u,i));r.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${n.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of yk){let a=s[i],c=Array.isArray(a)&&a.some(u=>Ai(u,i));r.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}bk(Sk)&&r.push({check:"Enterprise hook config",status:"warn",message:"Enterprise Cursor hook config detected at /Library/Application Support/Cursor/hooks.json (read-only informational layer)"}),this.hasClaudeCompatibilityHooks()&&r.push({check:"Claude compatibility",status:"warn",message:"Claude-compatible hooks detected; native Cursor hooks are the supported configuration"});let o=this.detectPluginInstalls();return o.length>0&&((n?Object.entries(n.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>Ai(c,i))):!1)&&n?r.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${n.path} \u2014 each event will fire twice. Remove one configuration to avoid duplicate routing.`,fix:"Remove the native .cursor/hooks.json entries OR uninstall the plugin"}):r.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),r}detectPluginInstalls(){let e=[eo(Vc(),".cursor","plugins","local"),eo(Vc(),".cursor","plugins","cache")],r=[];for(let n of e){try{vk(n,xk.F_OK)}catch{continue}let o=[];try{o=ij(n)}catch{continue}for(let s of o){let i=eo(n,s,".cursor-plugin","plugin.json");try{let a=Bc(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Qn(".cursor","mcp.json"),eo(Vc(),".cursor","mcp.json")];for(let n of e)try{let o=Bc(n,"utf-8"),s=JSON.parse(o),i=s.mcpServers??s.servers;if(!i)continue;if(Object.entries(i).some(([c,u])=>c.includes("context-mode")?!0:!u||typeof u!="object"?!1:u.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${n}`}}catch{continue}let r=this.detectPluginInstalls();return r.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${r[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return aj("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,he.PRE_TOOL_USE,{type:"command",command:Ut(he.PRE_TOOL_USE),matcher:Jm,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.POST_TOOL_USE,{type:"command",command:Ut(he.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.SESSION_START,{type:"command",command:Ut(he.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.STOP,{type:"command",command:Ut(he.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.AFTER_AGENT_RESPONSE,{type:"command",command:Ut(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=eo(e,"hooks","cursor");for(let o of Object.values(Gm)){let s=Qn(n,o);try{vk(s,xk.R_OK),sj(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),eo(Vc(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Sk),e}getProjectDir(e){return e.cwd||e.workspace_roots?.[0]||process.env.CURSOR_CWD||process.cwd()}extractSessionId(e){return e.conversation_id?e.conversation_id:e.session_id?e.session_id:process.env.CURSOR_SESSION_ID?process.env.CURSOR_SESSION_ID:process.env.CURSOR_TRACE_ID?process.env.CURSOR_TRACE_ID:`pid-${process.ppid}`}loadNativeHookConfig(){for(let e of this.getCandidateHookConfigPaths())try{let r=Bc(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Qn(".claude","settings.json"),Qn(".claude","settings.local.json"),eo(St(),"settings.json")].some(r=>bk(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Ai(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var Tk={};Fe(Tk,{AntigravityAdapter:()=>Qm});import{readFileSync as Wc,writeFileSync as cj,mkdirSync as uj}from"node:fs";import{resolve as Kc,dirname as wk}from"node:path";import{fileURLToPath as lj}from"node:url";import{homedir as Ym}from"node:os";var Qm,Rk=ce(()=>{"use strict";ut();Qm=class extends xe{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Kc(Ym(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Kc(Ym(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Wc(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();uj(wk(r),{recursive:!0}),cj(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Antigravity does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Wc(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.gemini/antigravity/mcp_config.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.gemini/antigravity/mcp_config.json"}}}getInstalledVersion(){try{let e=Kc(Ym(),".gemini","extensions","context-mode","package.json");return JSON.parse(Wc(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Kc(wk(lj(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Wc(e,"utf-8")}catch{return`# context-mode
150
150
 
151
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Wc(t,e){let r=bk[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function es(t,e){let r=bk[t];return e&&r?Ie(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ae,bk,UM,HM,Ym,S4,k4,xk=ce(()=>{"use strict";sn();Ae={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},bk={[Ae.PRE_TOOL_USE]:"pretooluse.mjs",[Ae.POST_TOOL_USE]:"posttooluse.mjs",[Ae.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ae.AGENT_SPAWN]:"agentspawn.mjs"},UM="@(?!context-mode/)",HM=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",UM],Ym=HM.join("|"),S4=[Ae.PRE_TOOL_USE,Ae.AGENT_SPAWN],k4=[Ae.POST_TOOL_USE,Ae.USER_PROMPT_SUBMIT]});var wk={};Ue(wk,{KiroAdapter:()=>Xm});import{readFileSync as ts,writeFileSync as Sk,mkdirSync as kk}from"node:fs";import{resolve as eo,dirname as Ek}from"node:path";import{fileURLToPath as FM}from"node:url";import{homedir as Kc}from"node:os";var Xm,Tk=ce(()=>{"use strict";it();xk();Xm=class extends be{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return eo(Kc(),".kiro","settings","mcp.json")}getConfigDir(e){return eo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ae.PRE_TOOL_USE]:[{matcher:Ym,hooks:[{type:"command",command:es(Ae.PRE_TOOL_USE,e)}]}],[Ae.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:es(Ae.POST_TOOL_USE,e)}]}],[Ae.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:es(Ae.AGENT_SPAWN,e)}]}],[Ae.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:es(Ae.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ts(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();kk(Ek(r),{recursive:!0}),Sk(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=eo(Kc(),".kiro","agents","default.json");try{let s=JSON.parse(ts(n,"utf-8")).hooks??{};for(let i of[Ae.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Wc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Ae.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Wc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=ts(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=eo(Kc(),".kiro","extensions","context-mode","package.json");return JSON.parse(ts(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=eo(Kc(),".kiro","agents"),o=eo(n,"default.json");try{kk(n,{recursive:!0});let s={};try{s=JSON.parse(ts(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ae.PRE_TOOL_USE,Ym],[Ae.POST_TOOL_USE,"*"],[Ae.AGENT_SPAWN,"*"],[Ae.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Wc(d,c))||(l.push({matcher:u,command:es(c,e)}),i[c]=l,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,Sk(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=eo(Ek(FM(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ts(e,"utf-8")}catch{return`# context-mode
151
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});function Gc(t,e){let r=Pk[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function ts(t,e){let r=Pk[t];return e&&r?Ie(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ae,Pk,dj,pj,eh,Q4,e9,$k=ce(()=>{"use strict";sn();Ae={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Pk={[Ae.PRE_TOOL_USE]:"pretooluse.mjs",[Ae.POST_TOOL_USE]:"posttooluse.mjs",[Ae.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ae.AGENT_SPAWN]:"agentspawn.mjs"},dj="@(?!context-mode/)",pj=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",dj],eh=pj.join("|"),Q4=[Ae.PRE_TOOL_USE,Ae.AGENT_SPAWN],e9=[Ae.POST_TOOL_USE,Ae.USER_PROMPT_SUBMIT]});var Ak={};Fe(Ak,{KiroAdapter:()=>th});import{readFileSync as rs,writeFileSync as Ck,mkdirSync as Ok}from"node:fs";import{resolve as to,dirname as Ik}from"node:path";import{fileURLToPath as fj}from"node:url";import{homedir as Jc}from"node:os";var th,Nk=ce(()=>{"use strict";ut();$k();th=class extends xe{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return to(Jc(),".kiro","settings","mcp.json")}getConfigDir(e){return to(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ae.PRE_TOOL_USE]:[{matcher:eh,hooks:[{type:"command",command:ts(Ae.PRE_TOOL_USE,e)}]}],[Ae.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ts(Ae.POST_TOOL_USE,e)}]}],[Ae.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ts(Ae.AGENT_SPAWN,e)}]}],[Ae.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ts(Ae.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=rs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();Ok(Ik(r),{recursive:!0}),Ck(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=to(Jc(),".kiro","agents","default.json");try{let s=JSON.parse(rs(n,"utf-8")).hooks??{};for(let i of[Ae.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Gc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Ae.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Gc(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=rs(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=to(Jc(),".kiro","extensions","context-mode","package.json");return JSON.parse(rs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=to(Jc(),".kiro","agents"),o=to(n,"default.json");try{Ok(n,{recursive:!0});let s={};try{s=JSON.parse(rs(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ae.PRE_TOOL_USE,eh],[Ae.POST_TOOL_USE,"*"],[Ae.AGENT_SPAWN,"*"],[Ae.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Gc(d,c))||(l.push({matcher:u,command:ts(c,e)}),i[c]=l,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,Ck(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=to(Ik(fj(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return rs(e,"utf-8")}catch{return`# context-mode
152
152
 
153
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var $k={};Ue($k,{ZedAdapter:()=>eh});import{readFileSync as Qm,writeFileSync as ZM,mkdirSync as qM}from"node:fs";import{resolve as Pk,dirname as Rk}from"node:path";import{fileURLToPath as BM}from"node:url";import{homedir as VM}from"node:os";var eh,Ck=ce(()=>{"use strict";it();eh=class extends be{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Pk(VM(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Qm(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();qM(Rk(r),{recursive:!0}),ZM(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=Qm(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Pk(Rk(BM(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Qm(e,"utf-8")}catch{return`# context-mode
153
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}}});var jk={};Fe(jk,{ZedAdapter:()=>nh});import{readFileSync as rh,writeFileSync as mj,mkdirSync as hj}from"node:fs";import{resolve as Dk,dirname as Mk}from"node:path";import{fileURLToPath as gj}from"node:url";import{homedir as yj}from"node:os";var nh,zk=ce(()=>{"use strict";ut();nh=class extends xe{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Dk(yj(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=rh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();hj(Mk(r),{recursive:!0}),mj(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"Zed does not support hooks. Only MCP integration is available."}]}checkPluginRegistration(){try{let e=rh(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Dk(Mk(gj(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return rh(e,"utf-8")}catch{return`# context-mode
154
154
 
155
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var th,Ok=ce(()=>{"use strict";th="mcp__(?!.*context-mode)"});var Nk={};Ue(Nk,{QwenCodeAdapter:()=>rh});import{readFileSync as WM,writeFileSync as KM,existsSync as GM}from"node:fs";import{resolve as Ik,join as JM}from"node:path";import{homedir as Ak}from"node:os";var rh,Dk=ce(()=>{"use strict";bm();Ok();sn();rh=class extends Go{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return Ik(Ak(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",th].join("|"),hooks:[{type:"command",command:Ie(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Ie(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=WM(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){KM(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let f=l.hooks??[];return f.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?f.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?GM(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",th].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Ie(`${e}/hooks/${a}`)}]},l=n[i];if(l&&Array.isArray(l)){let d=l.findIndex(f=>f.hooks?.some(p=>p.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),n[i]=l}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:Ik(JM(Ak(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var Mk={};Ue(Mk,{OMPAdapter:()=>sh});import{readFileSync as nh,writeFileSync as YM,mkdirSync as XM}from"node:fs";import{resolve as oh,dirname as QM}from"node:path";import{homedir as ej}from"node:os";var sh,jk=ce(()=>{"use strict";it();sh=class extends be{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??oh(ej(),".omp","agent")}getSettingsPath(){return oh(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=nh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();XM(QM(r),{recursive:!0}),YM(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=nh(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=oh(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(nh(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
155
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var oh,Lk=ce(()=>{"use strict";oh="mcp__(?!.*context-mode)"});var Fk={};Fe(Fk,{QwenCodeAdapter:()=>sh});import{readFileSync as _j,writeFileSync as vj,existsSync as xj}from"node:fs";import{resolve as Uk,join as bj}from"node:path";import{homedir as Hk}from"node:os";var sh,Zk=ce(()=>{"use strict";km();Lk();sn();sh=class extends Jo{constructor(){super([".qwen"])}name="Qwen Code";paradigm="json-stdio";projectDirEnvVar="QWEN_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getSettingsPath(){return Uk(Hk(),".qwen","settings.json")}getInstructionFiles(){return["QWEN.md"]}generateHookConfig(e){return{PreToolUse:[{matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",oh].join("|"),hooks:[{type:"command",command:Ie(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Ie(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Ie(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=_j(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){vj(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let f=l.hooks??[];return f.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?f.every(p=>{if(!p.command)return!0;let h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?xj(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",oh].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Ie(`${e}/hooks/${a}`)}]},l=n[i];if(l&&Array.isArray(l)){let d=l.findIndex(f=>f.hooks?.some(p=>p.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),n[i]=l}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:Uk(bj(Hk(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let r=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var qk={};Fe(qk,{OMPAdapter:()=>ch});import{readFileSync as ih,writeFileSync as Sj,mkdirSync as kj}from"node:fs";import{resolve as ah,dirname as Ej}from"node:path";import{homedir as wj}from"node:os";var ch,Bk=ce(()=>{"use strict";ut();ch=class extends xe{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??ah(wj(),".omp","agent")}getSettingsPath(){return ah(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=ih(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();kj(Ej(r),{recursive:!0}),Sj(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"warn",message:"context-mode delivers via MCP for OMP. Native OMP pre/post tool-call hooks are not yet wired by this adapter."}]}checkPluginRegistration(){try{let e=ih(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:`Add context-mode to mcpServers in ${this.getSettingsPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getSettingsPath()}`}}}getInstalledVersion(){try{let e=ah(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(ih(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
156
156
 
157
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var zk={};Ue(zk,{PiAdapter:()=>uh});import{readFileSync as ih,writeFileSync as tj,mkdirSync as rj}from"node:fs";import{resolve as ah,dirname as nj}from"node:path";import{homedir as ch}from"node:os";var uh,Lk=ce(()=>{"use strict";it();uh=class extends be{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return ah(ch(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=ih(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();rj(nj(r),{recursive:!0}),tj(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=ah(ch(),".pi","extensions","context-mode","package.json");try{return JSON.parse(ih(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=ah(ch(),".pi","extensions","context-mode","package.json");return JSON.parse(ih(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
157
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of run_command/view_file for data-heavy operations.`}}});var Vk={};Fe(Vk,{PiAdapter:()=>ph});import{readFileSync as uh,writeFileSync as Tj,mkdirSync as Rj}from"node:fs";import{resolve as lh,dirname as Pj}from"node:path";import{homedir as dh}from"node:os";var ph,Wk=ce(()=>{"use strict";ut();ph=class extends xe{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return lh(dh(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=uh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();Rj(Pj(r),{recursive:!0}),Tj(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Pi hooks are wired via the context-mode Pi extension (~/.pi/extensions/context-mode/), not via JSON-stdio."}]}checkPluginRegistration(){let e=lh(dh(),".pi","extensions","context-mode","package.json");try{return JSON.parse(uh(e,"utf-8"))?.name==="context-mode"?{check:"Pi extension registration",status:"pass",message:`context-mode extension installed at ${e}`}:{check:"Pi extension registration",status:"warn",message:`Unexpected package at ${e}`}}catch{return{check:"Pi extension registration",status:"fail",message:`context-mode not found at ${e}`,fix:"Run: context-mode upgrade"}}}getInstalledVersion(){try{let e=lh(dh(),".pi","extensions","context-mode","package.json");return JSON.parse(uh(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
158
158
 
159
- Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});var Gc={};Ue(Gc,{PLATFORM_ENV_VARS:()=>rs,__resetClaudeCodePluginCacheForTests:()=>ij,__seedClaudeCodePluginCacheMissForTests:()=>aj,detectPlatform:()=>Ir,foreignIdentificationEnv:()=>dj,foreignWorkspaceEnv:()=>lj,getAdapter:()=>pj,getEnvVarNames:()=>uj,getSessionDirSegments:()=>Ii,workspaceEnvVarsFor:()=>lh});import{existsSync as kt,readFileSync as oj}from"node:fs";import{resolve as yt}from"node:path";import{homedir as Uk}from"node:os";function sj(){if(to!==null)return to!=="miss"&&to.hasCM;try{let t=yt(Uk(),".claude","plugins","installed_plugins.json"),e=oj(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return to={hasCM:o},o}catch{return to="miss",!1}}function ij(){to=null}function aj(){to="miss"}function uj(t){return(rs.get(t)??[]).map(e=>e.name)}function lh(t){return(rs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function lj(t){let e=new Set;for(let[r,n]of rs)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function dj(t){let e=new Set;for(let[r,n]of rs)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Ii(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Ir(t){if(t?.name){let n=iS[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of rs)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&sj()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Uk();return kt(yt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:kt(yt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:kt(yt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:kt(yt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:kt(yt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:kt(yt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:kt(yt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:kt(yt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:kt(yt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:kt(yt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:kt(yt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:kt(yt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:kt(yt(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function pj(t){let e=t??Ir().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Tm(),wm));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(MS(),DS));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(US(),LS));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(ZS(),FS));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(YS(),JS));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(nk(),rk));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(ak(),ik));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(gk(),hk));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(vk(),_k));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(Tk(),wk));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(Ck(),$k));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Dk(),Nk));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(jk(),Mk));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Lk(),zk));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Tm(),wm));return new r}}}var to,cj,rs,ro=ce(()=>{"use strict";aS();to=null;cj=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],rs=new Map(cj)});import{resolve as Ai}from"node:path";import{homedir as dh}from"node:os";function St(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ai(dh(),e.replace(/^~[/\\]?/,"")):Ai(e):Ai(dh(),".claude")}function fj(t=process.env){return Ai(St(t),"settings.json")}function ph(t=process.env){let e=[],r=Ir();if(r.platform!=="claude-code"){let o=Ii(r.platform);o&&o.length>0&&e.push(Ai(dh(),...o,"settings.json"))}let n=fj(t);return e.includes(n)||e.push(n),e}var Vn=ce(()=>{"use strict";ro()});var A={};Ue(A,{BRAND:()=>Ew,DIRTY:()=>dn,EMPTY_PATH:()=>rw,INVALID:()=>B,NEVER:()=>aT,OK:()=>Je,ParseStatus:()=>Fe,Schema:()=>X,ZodAny:()=>Lr,ZodArray:()=>Sr,ZodBigInt:()=>fn,ZodBoolean:()=>mn,ZodBranded:()=>ps,ZodCatch:()=>wn,ZodDate:()=>hn,ZodDefault:()=>En,ZodDiscriminatedUnion:()=>qi,ZodEffects:()=>Pt,ZodEnum:()=>Sn,ZodError:()=>ut,ZodFirstPartyTypeKind:()=>w,ZodFunction:()=>Vi,ZodIntersection:()=>vn,ZodIssueCode:()=>E,ZodLazy:()=>bn,ZodLiteral:()=>xn,ZodMap:()=>lo,ZodNaN:()=>fo,ZodNativeEnum:()=>kn,ZodNever:()=>Zt,ZodNull:()=>yn,ZodNullable:()=>cr,ZodNumber:()=>pn,ZodObject:()=>dt,ZodOptional:()=>lt,ZodParsedType:()=>$,ZodPipeline:()=>fs,ZodPromise:()=>Ur,ZodReadonly:()=>Tn,ZodRecord:()=>Bi,ZodSchema:()=>X,ZodSet:()=>po,ZodString:()=>zr,ZodSymbol:()=>co,ZodTransformer:()=>Pt,ZodTuple:()=>ar,ZodType:()=>X,ZodUndefined:()=>gn,ZodUnion:()=>_n,ZodUnknown:()=>xr,ZodVoid:()=>uo,addIssueToContext:()=>P,any:()=>Aw,array:()=>jw,bigint:()=>Rw,boolean:()=>Qh,coerce:()=>iT,custom:()=>Jh,date:()=>$w,datetimeRegex:()=>Kh,defaultErrorMap:()=>vr,discriminatedUnion:()=>Uw,effect:()=>Xw,enum:()=>Gw,function:()=>Vw,getErrorMap:()=>so,getParsedType:()=>ir,instanceof:()=>Tw,intersection:()=>Hw,isAborted:()=>Fi,isAsync:()=>io,isDirty:()=>Zi,isValid:()=>jr,late:()=>ww,lazy:()=>Ww,literal:()=>Kw,makeIssue:()=>ds,map:()=>qw,nan:()=>Pw,nativeEnum:()=>Jw,never:()=>Dw,null:()=>Iw,nullable:()=>eT,number:()=>Xh,object:()=>Tu,objectUtil:()=>ku,oboolean:()=>sT,onumber:()=>oT,optional:()=>Qw,ostring:()=>nT,pipeline:()=>rT,preprocess:()=>tT,promise:()=>Yw,quotelessJson:()=>QE,record:()=>Zw,set:()=>Bw,setErrorMap:()=>tw,strictObject:()=>zw,string:()=>Yh,symbol:()=>Cw,transformer:()=>Xw,tuple:()=>Fw,undefined:()=>Ow,union:()=>Lw,unknown:()=>Nw,util:()=>ne,void:()=>Mw});var ne;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ne||(ne={}));var ku;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(ku||(ku={}));var $=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ir=t=>{switch(typeof t){case"undefined":return $.undefined;case"string":return $.string;case"number":return Number.isNaN(t)?$.nan:$.number;case"boolean":return $.boolean;case"function":return $.function;case"bigint":return $.bigint;case"symbol":return $.symbol;case"object":return Array.isArray(t)?$.array:t===null?$.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?$.promise:typeof Map<"u"&&t instanceof Map?$.map:typeof Set<"u"&&t instanceof Set?$.set:typeof Date<"u"&&t instanceof Date?$.date:$.object;default:return $.unknown}};var E=ne.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),QE=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ut=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};ut.create=t=>new ut(t);var ew=(t,e)=>{let r;switch(t.code){case E.invalid_type:t.received===$.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:r=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case E.invalid_union:r="Invalid input";break;case E.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case E.invalid_enum_value:r=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:r="Invalid function arguments";break;case E.invalid_return_type:r="Invalid function return type";break;case E.invalid_date:r="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ne.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case E.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case E.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case E.custom:r="Invalid input";break;case E.invalid_intersection_types:r="Intersection results could not be merged";break;case E.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:r="Number must be finite";break;default:r=e.defaultError,ne.assertNever(t)}return{message:r}},vr=ew;var Zh=vr;function tw(t){Zh=t}function so(){return Zh}var ds=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},rw=[];function P(t,e){let r=so(),n=ds({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===vr?void 0:vr].filter(o=>!!o)});t.common.issues.push(n)}var Fe=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return B;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return B;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:"aborted"}),dn=t=>({status:"dirty",value:t}),Je=t=>({status:"valid",value:t}),Fi=t=>t.status==="aborted",Zi=t=>t.status==="dirty",jr=t=>t.status==="valid",io=t=>typeof Promise<"u"&&t instanceof Promise;var D;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(D||(D={}));var Tt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},qh=(t,e)=>{if(jr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new ut(t.common.issues);return this._error=r,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var X=class{get description(){return this._def.description}_getType(e){return ir(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Fe,ctx:{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(io(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)},o=this._parseSync({data:e,path:n.path,parent:n});return qh(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return jr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>jr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(io(o)?o:Promise.resolve(o));return qh(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Pt({schema:this,typeName:w.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return lt.create(this,this._def)}nullable(){return cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Sr.create(this)}promise(){return Ur.create(this,this._def)}or(e){return _n.create([this,e],this._def)}and(e){return vn.create(this,e,this._def)}transform(e){return new Pt({...J(this._def),schema:this,typeName:w.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new En({...J(this._def),innerType:this,defaultValue:r,typeName:w.ZodDefault})}brand(){return new ps({typeName:w.ZodBranded,type:this,...J(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new wn({...J(this._def),innerType:this,catchValue:r,typeName:w.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return fs.create(this,e)}readonly(){return Tn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nw=/^c[^\s-]{8,}$/i,ow=/^[0-9a-z]+$/,sw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,aw=/^[a-z0-9_-]{21}$/i,cw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,lw=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Eu,pw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,fw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,mw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,hw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gw=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yw=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",_w=new RegExp(`^${Vh}$`);function Wh(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function vw(t){return new RegExp(`^${Wh(t)}$`)}function Kh(t){let e=`${Vh}T${Wh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function bw(t,e){return!!((e==="v4"||!e)&&pw.test(t)||(e==="v6"||!e)&&mw.test(t))}function xw(t,e){if(!cw.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Sw(t,e){return!!((e==="v4"||!e)&&fw.test(t)||(e==="v6"||!e)&&hw.test(t))}var zr=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==$.string){let s=this._getOrReturnCtx(e);return P(s,{code:E.invalid_type,expected:$.string,received:s.parsedType}),B}let n=new Fe,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?P(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&P(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")lw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"email",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Eu||(Eu=new RegExp(dw,"u")),Eu.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"emoji",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")iw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"uuid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")aw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")nw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cuid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")ow.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")sw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"ulid",code:E.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),P(o,{validation:"url",code:E.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"regex",code:E.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Kh(s).test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?_w.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?vw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:E.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?uw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"duration",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?bw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"ip",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?xw(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"jwt",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Sw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cidr",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?gw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"base64",code:E.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?yw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"base64url",code:E.invalid_string,message:s.message}),n.dirty()):ne.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:E.invalid_string,...D.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...D.errToObj(e)})}url(e){return this._addCheck({kind:"url",...D.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...D.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...D.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...D.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...D.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...D.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...D.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...D.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...D.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...D.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...D.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...D.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...D.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...D.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...D.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...D.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...D.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...D.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...D.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...D.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...D.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...D.errToObj(r)})}nonempty(e){return this.min(1,D.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};zr.create=t=>new zr({checks:[],typeName:w.ZodString,coerce:t?.coerce??!1,...J(t)});function kw(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var pn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==$.number){let s=this._getOrReturnCtx(e);return P(s,{code:E.invalid_type,expected:$.number,received:s.parsedType}),B}let n,o=new Fe;for(let s of this._def.checks)s.kind==="int"?ne.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:E.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?kw(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_finite,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:D.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:D.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};pn.create=t=>new pn({checks:[],typeName:w.ZodNumber,coerce:t?.coerce||!1,...J(t)});var fn=class t extends X{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==$.bigint)return this._getInvalidInput(e);let n,o=new Fe;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),P(n,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return P(r,{code:E.invalid_type,expected:$.bigint,received:r.parsedType}),B}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};fn.create=t=>new fn({checks:[],typeName:w.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var mn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==$.boolean){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.boolean,received:n.parsedType}),B}return Je(e.data)}};mn.create=t=>new mn({typeName:w.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var hn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==$.date){let s=this._getOrReturnCtx(e);return P(s,{code:E.invalid_type,expected:$.date,received:s.parsedType}),B}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return P(s,{code:E.invalid_date}),B}let n=new Fe,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ne.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:D.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:D.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};hn.create=t=>new hn({checks:[],coerce:t?.coerce||!1,typeName:w.ZodDate,...J(t)});var co=class extends X{_parse(e){if(this._getType(e)!==$.symbol){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.symbol,received:n.parsedType}),B}return Je(e.data)}};co.create=t=>new co({typeName:w.ZodSymbol,...J(t)});var gn=class extends X{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.undefined,received:n.parsedType}),B}return Je(e.data)}};gn.create=t=>new gn({typeName:w.ZodUndefined,...J(t)});var yn=class extends X{_parse(e){if(this._getType(e)!==$.null){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.null,received:n.parsedType}),B}return Je(e.data)}};yn.create=t=>new yn({typeName:w.ZodNull,...J(t)});var Lr=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return Je(e.data)}};Lr.create=t=>new Lr({typeName:w.ZodAny,...J(t)});var xr=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Je(e.data)}};xr.create=t=>new xr({typeName:w.ZodUnknown,...J(t)});var Zt=class extends X{_parse(e){let r=this._getOrReturnCtx(e);return P(r,{code:E.invalid_type,expected:$.never,received:r.parsedType}),B}};Zt.create=t=>new Zt({typeName:w.ZodNever,...J(t)});var uo=class extends X{_parse(e){if(this._getType(e)!==$.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.void,received:n.parsedType}),B}return Je(e.data)}};uo.create=t=>new uo({typeName:w.ZodVoid,...J(t)});var Sr=class t extends X{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==$.array)return P(r,{code:E.invalid_type,expected:$.array,received:r.parsedType}),B;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(P(r,{code:i?E.too_big:E.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(P(r,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(P(r,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Tt(r,i,r.path,a)))).then(i=>Fe.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Tt(r,i,r.path,a)));return Fe.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:D.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:D.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:D.toString(r)}})}nonempty(e){return this.min(1,e)}};Sr.create=(t,e)=>new Sr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:w.ZodArray,...J(e)});function ao(t){if(t instanceof dt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=lt.create(ao(n))}return new dt({...t._def,shape:()=>e})}else return t instanceof Sr?new Sr({...t._def,type:ao(t.element)}):t instanceof lt?lt.create(ao(t.unwrap())):t instanceof cr?cr.create(ao(t.unwrap())):t instanceof ar?ar.create(t.items.map(e=>ao(e))):t}var dt=class t extends X{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ne.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==$.object){let u=this._getOrReturnCtx(e);return P(u,{code:E.invalid_type,expected:$.object,received:u.parsedType}),B}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Zt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Tt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Zt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(P(o,{code:E.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Tt(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Fe.mergeObjectSync(n,u)):Fe.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return D.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:D.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:w.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ne.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ne.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ao(this)}partial(e){let r={};for(let n of ne.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ne.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof lt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Gh(ne.objectKeys(this.shape))}};dt.create=(t,e)=>new dt({shape:()=>t,unknownKeys:"strip",catchall:Zt.create(),typeName:w.ZodObject,...J(e)});dt.strictCreate=(t,e)=>new dt({shape:()=>t,unknownKeys:"strict",catchall:Zt.create(),typeName:w.ZodObject,...J(e)});dt.lazycreate=(t,e)=>new dt({shape:t,unknownKeys:"strip",catchall:Zt.create(),typeName:w.ZodObject,...J(e)});var _n=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new ut(a.ctx.common.issues));return P(r,{code:E.invalid_union,unionErrors:i}),B}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new ut(c));return P(r,{code:E.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};_n.create=(t,e)=>new _n({options:t,typeName:w.ZodUnion,...J(e)});var br=t=>t instanceof bn?br(t.schema):t instanceof Pt?br(t.innerType()):t instanceof xn?[t.value]:t instanceof Sn?t.options:t instanceof kn?ne.objectValues(t.enum):t instanceof En?br(t._def.innerType):t instanceof gn?[void 0]:t instanceof yn?[null]:t instanceof lt?[void 0,...br(t.unwrap())]:t instanceof cr?[null,...br(t.unwrap())]:t instanceof ps||t instanceof Tn?br(t.unwrap()):t instanceof wn?br(t._def.innerType):[],qi=class t extends X{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.object)return P(r,{code:E.invalid_type,expected:$.object,received:r.parsedType}),B;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(P(r,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=br(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:w.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...J(n)})}};function wu(t,e){let r=ir(t),n=ir(e);if(t===e)return{valid:!0,data:t};if(r===$.object&&n===$.object){let o=ne.objectKeys(e),s=ne.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=wu(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===$.array&&n===$.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=wu(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===$.date&&n===$.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var vn=class extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Fi(s)||Fi(i))return B;let a=wu(s.value,i.value);return a.valid?((Zi(s)||Zi(i))&&r.dirty(),{status:r.value,value:a.data}):(P(n,{code:E.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};vn.create=(t,e,r)=>new vn({left:t,right:e,typeName:w.ZodIntersection,...J(r)});var ar=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.array)return P(n,{code:E.invalid_type,expected:$.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return P(n,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Tt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Fe.mergeArray(r,i)):Fe.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ar.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ar({items:t,typeName:w.ZodTuple,rest:null,...J(e)})};var Bi=class t extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.object)return P(n,{code:E.invalid_type,expected:$.object,received:n.parsedType}),B;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Tt(n,a,n.path,a)),value:i._parse(new Tt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Fe.mergeObjectAsync(r,o):Fe.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof X?new t({keyType:e,valueType:r,typeName:w.ZodRecord,...J(n)}):new t({keyType:zr.create(),valueType:e,typeName:w.ZodRecord,...J(r)})}},lo=class extends X{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.map)return P(n,{code:E.invalid_type,expected:$.map,received:n.parsedType}),B;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Tt(n,a,n.path,[u,"key"])),value:s._parse(new Tt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};lo.create=(t,e,r)=>new lo({valueType:e,keyType:t,typeName:w.ZodMap,...J(r)});var po=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==$.set)return P(n,{code:E.invalid_type,expected:$.set,received:n.parsedType}),B;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(P(n,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(P(n,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return B;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Tt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:D.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:D.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};po.create=(t,e)=>new po({valueType:t,minSize:null,maxSize:null,typeName:w.ZodSet,...J(e)});var Vi=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.function)return P(r,{code:E.invalid_type,expected:$.function,received:r.parsedType}),B;function n(a,c){return ds({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,so(),vr].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return ds({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,so(),vr].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Ur){let a=this;return Je(async function(...c){let u=new ut([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return Je(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new ut([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new ut([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ar.create(e).rest(xr.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ar.create([]).rest(xr.create()),returns:r||xr.create(),typeName:w.ZodFunction,...J(n)})}},bn=class extends X{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};bn.create=(t,e)=>new bn({getter:t,typeName:w.ZodLazy,...J(e)});var xn=class extends X{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return P(r,{received:r.data,code:E.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};xn.create=(t,e)=>new xn({value:t,typeName:w.ZodLiteral,...J(e)});function Gh(t,e){return new Sn({values:t,typeName:w.ZodEnum,...J(e)})}var Sn=class t extends X{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{expected:ne.joinValues(n),received:r.parsedType,code:E.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{received:r.data,code:E.invalid_enum_value,options:n}),B}return Je(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Sn.create=Gh;var kn=class extends X{_parse(e){let r=ne.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==$.string&&n.parsedType!==$.number){let o=ne.objectValues(r);return P(n,{expected:ne.joinValues(o),received:n.parsedType,code:E.invalid_type}),B}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ne.objectValues(r);return P(n,{received:n.data,code:E.invalid_enum_value,options:o}),B}return Je(e.data)}get enum(){return this._def.values}};kn.create=(t,e)=>new kn({values:t,typeName:w.ZodNativeEnum,...J(e)});var Ur=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==$.promise&&r.common.async===!1)return P(r,{code:E.invalid_type,expected:$.promise,received:r.parsedType}),B;let n=r.parsedType===$.promise?r.data:Promise.resolve(r.data);return Je(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ur.create=(t,e)=>new Ur({type:t,typeName:w.ZodPromise,...J(e)});var Pt=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===w.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{P(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return B;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?B:c.status==="dirty"?dn(c.value):r.value==="dirty"?dn(c.value):c});{if(r.value==="aborted")return B;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?B:a.status==="dirty"?dn(a.value):r.value==="dirty"?dn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!jr(i))return B;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>jr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):B);ne.assertNever(o)}};Pt.create=(t,e,r)=>new Pt({schema:t,typeName:w.ZodEffects,effect:e,...J(r)});Pt.createWithPreprocess=(t,e,r)=>new Pt({schema:e,effect:{type:"preprocess",transform:t},typeName:w.ZodEffects,...J(r)});var lt=class extends X{_parse(e){return this._getType(e)===$.undefined?Je(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};lt.create=(t,e)=>new lt({innerType:t,typeName:w.ZodOptional,...J(e)});var cr=class extends X{_parse(e){return this._getType(e)===$.null?Je(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};cr.create=(t,e)=>new cr({innerType:t,typeName:w.ZodNullable,...J(e)});var En=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===$.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};En.create=(t,e)=>new En({innerType:t,typeName:w.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var wn=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return io(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ut(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ut(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:w.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var fo=class extends X{_parse(e){if(this._getType(e)!==$.nan){let n=this._getOrReturnCtx(e);return P(n,{code:E.invalid_type,expected:$.nan,received:n.parsedType}),B}return{status:"valid",value:e.data}}};fo.create=t=>new fo({typeName:w.ZodNaN,...J(t)});var Ew=Symbol("zod_brand"),ps=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},fs=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?B:s.status==="dirty"?(r.dirty(),dn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?B:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:w.ZodPipeline})}},Tn=class extends X{_parse(e){let r=this._def.innerType._parse(e),n=o=>(jr(o)&&(o.value=Object.freeze(o.value)),o);return io(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Tn.create=(t,e)=>new Tn({innerType:t,typeName:w.ZodReadonly,...J(e)});function Bh(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Jh(t,e={},r){return t?Lr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Bh(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Bh(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Lr.create()}var ww={object:dt.lazycreate},w;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(w||(w={}));var Tw=(t,e={message:`Input not instance of ${t.name}`})=>Jh(r=>r instanceof t,e),Yh=zr.create,Xh=pn.create,Pw=fo.create,Rw=fn.create,Qh=mn.create,$w=hn.create,Cw=co.create,Ow=gn.create,Iw=yn.create,Aw=Lr.create,Nw=xr.create,Dw=Zt.create,Mw=uo.create,jw=Sr.create,Tu=dt.create,zw=dt.strictCreate,Lw=_n.create,Uw=qi.create,Hw=vn.create,Fw=ar.create,Zw=Bi.create,qw=lo.create,Bw=po.create,Vw=Vi.create,Ww=bn.create,Kw=xn.create,Gw=Sn.create,Jw=kn.create,Yw=Ur.create,Xw=Pt.create,Qw=lt.create,eT=cr.create,tT=Pt.createWithPreprocess,rT=fs.create,nT=()=>Yh().optional(),oT=()=>Xh().optional(),sT=()=>Qh().optional(),iT={string:(t=>zr.create({...t,coerce:!0})),number:(t=>pn.create({...t,coerce:!0})),boolean:(t=>mn.create({...t,coerce:!0})),bigint:(t=>fn.create({...t,coerce:!0})),date:(t=>hn.create({...t,coerce:!0}))};var aT=B;var cT=Object.freeze({status:"aborted"});function x(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Wi={};function vt(t){return t&&Object.assign(Wi,t),Wi}var oe={};Ue(oe,{BIGINT_FORMAT_RANGES:()=>tg,Class:()=>Ru,NUMBER_FORMAT_RANGES:()=>Du,aborted:()=>Rn,allowsEval:()=>Iu,assert:()=>fT,assertEqual:()=>uT,assertIs:()=>dT,assertNever:()=>pT,assertNotEqual:()=>lT,assignProp:()=>Ou,cached:()=>gs,captureStackTrace:()=>Gi,cleanEnum:()=>TT,cleanRegex:()=>_s,clone:()=>bt,createTransparentProxy:()=>vT,defineLazy:()=>ye,esc:()=>Pn,escapeRegex:()=>Hr,extend:()=>ST,finalizeIssue:()=>qt,floatSafeRemainder:()=>Cu,getElementAtPath:()=>mT,getEnumValues:()=>hs,getLengthableOrigin:()=>vs,getParsedType:()=>_T,getSizableOrigin:()=>rg,isObject:()=>mo,isPlainObject:()=>ho,issue:()=>Mu,joinValues:()=>Ki,jsonStringifyReplacer:()=>$u,merge:()=>kT,normalizeParams:()=>V,nullish:()=>ys,numKeys:()=>yT,omit:()=>xT,optionalKeys:()=>Nu,partial:()=>ET,pick:()=>bT,prefixIssues:()=>ur,primitiveTypes:()=>eg,promiseAllObject:()=>hT,propertyKeyTypes:()=>Au,randomString:()=>gT,required:()=>wT,stringifyPrimitive:()=>Ji,unwrapMessage:()=>ms});function uT(t){return t}function lT(t){return t}function dT(t){}function pT(t){throw new Error}function fT(t){}function hs(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ki(t,e="|"){return t.map(r=>Ji(r)).join(e)}function $u(t,e){return typeof e=="bigint"?e.toString():e}function gs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ys(t){return t==null}function _s(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Cu(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ye(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Ou(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function mT(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function hT(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function gT(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Pn(t){return JSON.stringify(t)}var Gi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function mo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Iu=gs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function ho(t){if(mo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(mo(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yT(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var _T=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Au=new Set(["string","number","symbol"]),eg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Hr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function V(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function vT(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Ji(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Nu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Du={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function bT(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return bt(t,{...t._zod.def,shape:r,checks:[]})}function xT(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return bt(t,{...t._zod.def,shape:r,checks:[]})}function ST(t,e){if(!ho(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Ou(this,"shape",n),n},checks:[]};return bt(t,r)}function kT(t,e){return bt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ou(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function ET(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return bt(e,{...e._zod.def,shape:o,checks:[]})}function wT(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return bt(e,{...e._zod.def,shape:o,checks:[]})}function Rn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ur(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ms(t){return typeof t=="string"?t:t?.message}function qt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ms(t.inst?._zod.def?.error?.(t))??ms(e?.error?.(t))??ms(r.customError?.(t))??ms(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function rg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function vs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Mu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function TT(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ru=class{constructor(...e){}};var ng=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,$u,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Yi=x("$ZodError",ng),bs=x("$ZodError",ng,{Parent:Error});function ju(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function zu(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Lu=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>qt(c,s,vt())));throw Gi(a,o?.callee),a}return i.value},Uu=Lu(bs),Hu=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>qt(c,s,vt())));throw Gi(a,o?.callee),a}return i.value},Fu=Hu(bs),Zu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new kr;return s.issues.length?{success:!1,error:new(t??Yi)(s.issues.map(i=>qt(i,o,vt())))}:{success:!0,data:s.value}},$n=Zu(bs),qu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>qt(i,o,vt())))}:{success:!0,data:s.value}},Cn=qu(bs);var og=/^[cC][^\s-]{8,}$/,sg=/^[0-9a-z]+$/,ig=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ag=/^[0-9a-vA-V]{20}$/,cg=/^[A-Za-z0-9]{27}$/,ug=/^[a-zA-Z0-9_-]{21}$/,lg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var dg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Bu=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var pg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var RT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fg(){return new RegExp(RT,"u")}var mg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,hg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,gg=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_g=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Vu=/^[A-Za-z0-9_-]*$/,vg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var bg=/^\+(?:[0-9]){6,14}[0-9]$/,xg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Sg=new RegExp(`^${xg}$`);function kg(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eg(t){return new RegExp(`^${kg(t)}$`)}function wg(t){let e=kg({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${xg}T(?:${n})$`)}var Tg=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Pg=/^\d+$/,Rg=/^-?\d+(?:\.\d+)?/i,$g=/true|false/i,Cg=/null/i;var Og=/^[^A-Z]*$/,Ig=/^[^a-z]*$/;var Ze=x("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ag={number:"number",bigint:"bigint",object:"date"},Wu=x("$ZodCheckLessThan",(t,e)=>{Ze.init(t,e);let r=Ag[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ku=x("$ZodCheckGreaterThan",(t,e)=>{Ze.init(t,e);let r=Ag[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ng=x("$ZodCheckMultipleOf",(t,e)=>{Ze.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Cu(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Dg=x("$ZodCheckNumberFormat",(t,e)=>{Ze.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Du[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Pg)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Mg=x("$ZodCheckMaxLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=vs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),jg=x("$ZodCheckMinLength",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=vs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),zg=x("$ZodCheckLengthEquals",(t,e)=>{var r;Ze.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!ys(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=vs(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),xs=x("$ZodCheckStringFormat",(t,e)=>{var r,n;Ze.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Lg=x("$ZodCheckRegex",(t,e)=>{xs.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ug=x("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Og),xs.init(t,e)}),Hg=x("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ig),xs.init(t,e)}),Fg=x("$ZodCheckIncludes",(t,e)=>{Ze.init(t,e);let r=Hr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Zg=x("$ZodCheckStartsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`^${Hr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),qg=x("$ZodCheckEndsWith",(t,e)=>{Ze.init(t,e);let r=new RegExp(`.*${Hr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Bg=x("$ZodCheckOverwrite",(t,e)=>{Ze.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var Qi=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
159
+ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ctx_fetch_and_index, ctx_search) instead of inline shell/HTTP calls for data-heavy operations.`}}});var Xc={};Fe(Xc,{PLATFORM_ENV_VARS:()=>ns,__resetClaudeCodePluginCacheForTests:()=>Oj,__seedClaudeCodePluginCacheMissForTests:()=>Ij,detectPlatform:()=>Ar,foreignIdentificationEnv:()=>Mj,foreignWorkspaceEnv:()=>Dj,getAdapter:()=>jj,getEnvVarNames:()=>Nj,getSessionDirSegments:()=>Ni,workspaceEnvVarsFor:()=>fh});import{existsSync as kt,readFileSync as $j}from"node:fs";import{resolve as _t}from"node:path";import{homedir as Kk}from"node:os";function Cj(){if(ro!==null)return ro!=="miss"&&ro.hasCM;try{let t=_t(Kk(),".claude","plugins","installed_plugins.json"),e=$j(t,"utf-8"),r=JSON.parse(e),o=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(s=>s.includes("context-mode"));return ro={hasCM:o},o}catch{return ro="miss",!1}}function Oj(){ro=null}function Ij(){ro="miss"}function Nj(t){return(ns.get(t)??[]).map(e=>e.name)}function fh(t){return(ns.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function Dj(t){let e=new Set;for(let[r,n]of ns)if(r!==t)for(let o of n)o.role==="workspace"&&e.add(o.name);return e}function Mj(t){let e=new Set;for(let[r,n]of ns)if(r!==t)for(let o of n)o.role==="identification"&&e.add(o.name);return e}function Ni(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kilo":return[".config","kilo"];case"opencode":return[".config","opencode"];case"zed":return[".config","zed"];case"jetbrains-copilot":return[".config","JetBrains"];default:return null}}function Ar(t){if(t?.name){let n=dS[t.name];if(n)return{platform:n,confidence:"high",reason:`MCP clientInfo.name="${t.name}"`};if(t.name.startsWith("qwen-cli-mcp-client"))return{platform:"qwen-code",confidence:"high",reason:`MCP clientInfo.name="${t.name}" (qwen-cli pattern)`}}let e=process.env.CONTEXT_MODE_PLATFORM;if(e&&["claude-code","gemini-cli","kilo","opencode","codex","vscode-copilot","jetbrains-copilot","cursor","antigravity","kiro","pi","omp","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of ns)if(o.some(s=>s.detect!==!1&&process.env[s.name]))return n==="vscode-copilot"&&Cj()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:n,confidence:"high",reason:`${o.filter(s=>s.detect!==!1).map(s=>s.name).join(" or ")} env var set`};let r=Kk();return kt(_t(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:kt(_t(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:kt(_t(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:kt(_t(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:kt(_t(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:kt(_t(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:kt(_t(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:kt(_t(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:kt(_t(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:kt(_t(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:kt(_t(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:kt(_t(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:kt(_t(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function jj(t){let e=t??Ar().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>($m(),Pm));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(ZS(),FS));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(WS(),VS));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(JS(),GS));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(sk(),ok));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(dk(),lk));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(hk(),mk));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Ek(),kk));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Rk(),Tk));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(Nk(),Ak));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(zk(),jk));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Zk(),Fk));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Bk(),qk));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Wk(),Vk));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>($m(),Pm));return new r}}}var ro,Aj,ns,no=ce(()=>{"use strict";pS();ro=null;Aj=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],ns=new Map(Aj)});import{resolve as Di}from"node:path";import{homedir as mh}from"node:os";function St(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Di(mh(),e.replace(/^~[/\\]?/,"")):Di(e):Di(mh(),".claude")}function zj(t=process.env){return Di(St(t),"settings.json")}function hh(t=process.env){let e=[],r=Ar();if(r.platform!=="claude-code"){let o=Ni(r.platform);o&&o.length>0&&e.push(Di(mh(),...o,"settings.json"))}let n=zj(t);return e.includes(n)||e.push(n),e}var Wn=ce(()=>{"use strict";no()});var $={};Fe($,{BRAND:()=>Iw,DIRTY:()=>pn,EMPTY_PATH:()=>lw,INVALID:()=>B,NEVER:()=>hT,OK:()=>et,ParseStatus:()=>Be,Schema:()=>Y,ZodAny:()=>Ur,ZodArray:()=>Sr,ZodBigInt:()=>mn,ZodBoolean:()=>hn,ZodBranded:()=>ms,ZodCatch:()=>Tn,ZodDate:()=>gn,ZodDefault:()=>wn,ZodDiscriminatedUnion:()=>Vi,ZodEffects:()=>Rt,ZodEnum:()=>kn,ZodError:()=>lt,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Ki,ZodIntersection:()=>xn,ZodIssueCode:()=>w,ZodLazy:()=>bn,ZodLiteral:()=>Sn,ZodMap:()=>po,ZodNaN:()=>mo,ZodNativeEnum:()=>En,ZodNever:()=>qt,ZodNull:()=>_n,ZodNullable:()=>cr,ZodNumber:()=>fn,ZodObject:()=>pt,ZodOptional:()=>dt,ZodParsedType:()=>I,ZodPipeline:()=>hs,ZodPromise:()=>Hr,ZodReadonly:()=>Rn,ZodRecord:()=>Wi,ZodSchema:()=>Y,ZodSet:()=>fo,ZodString:()=>Lr,ZodSymbol:()=>uo,ZodTransformer:()=>Rt,ZodTuple:()=>ar,ZodType:()=>Y,ZodUndefined:()=>yn,ZodUnion:()=>vn,ZodUnknown:()=>br,ZodVoid:()=>lo,addIssueToContext:()=>P,any:()=>Hw,array:()=>Bw,bigint:()=>Mw,boolean:()=>Qh,coerce:()=>mT,custom:()=>Jh,date:()=>jw,datetimeRegex:()=>Kh,defaultErrorMap:()=>vr,discriminatedUnion:()=>Kw,effect:()=>iT,enum:()=>nT,function:()=>eT,getErrorMap:()=>io,getParsedType:()=>ir,instanceof:()=>Nw,intersection:()=>Gw,isAborted:()=>qi,isAsync:()=>ao,isDirty:()=>Bi,isValid:()=>zr,late:()=>Aw,lazy:()=>tT,literal:()=>rT,makeIssue:()=>fs,map:()=>Yw,nan:()=>Dw,nativeEnum:()=>oT,never:()=>Zw,null:()=>Uw,nullable:()=>cT,number:()=>Yh,object:()=>$u,objectUtil:()=>Tu,oboolean:()=>fT,onumber:()=>pT,optional:()=>aT,ostring:()=>dT,pipeline:()=>lT,preprocess:()=>uT,promise:()=>sT,quotelessJson:()=>aw,record:()=>Xw,set:()=>Qw,setErrorMap:()=>uw,strictObject:()=>Vw,string:()=>Xh,symbol:()=>zw,transformer:()=>iT,tuple:()=>Jw,undefined:()=>Lw,union:()=>Ww,unknown:()=>Fw,util:()=>ne,void:()=>qw});var ne;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ne||(ne={}));var Tu;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Tu||(Tu={}));var I=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ir=t=>{switch(typeof t){case"undefined":return I.undefined;case"string":return I.string;case"number":return Number.isNaN(t)?I.nan:I.number;case"boolean":return I.boolean;case"function":return I.function;case"bigint":return I.bigint;case"symbol":return I.symbol;case"object":return Array.isArray(t)?I.array:t===null?I.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?I.promise:typeof Map<"u"&&t instanceof Map?I.map:typeof Set<"u"&&t instanceof Set?I.set:typeof Date<"u"&&t instanceof Date?I.date:I.object;default:return I.unknown}};var w=ne.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),aw=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),lt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};lt.create=t=>new lt(t);var cw=(t,e)=>{let r;switch(t.code){case w.invalid_type:t.received===I.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case w.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case w.unrecognized_keys:r=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case w.invalid_union:r="Invalid input";break;case w.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case w.invalid_enum_value:r=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case w.invalid_arguments:r="Invalid function arguments";break;case w.invalid_return_type:r="Invalid function return type";break;case w.invalid_date:r="Invalid date";break;case w.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:ne.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case w.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case w.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case w.custom:r="Invalid input";break;case w.invalid_intersection_types:r="Intersection results could not be merged";break;case w.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case w.not_finite:r="Number must be finite";break;default:r=e.defaultError,ne.assertNever(t)}return{message:r}},vr=cw;var Zh=vr;function uw(t){Zh=t}function io(){return Zh}var fs=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},lw=[];function P(t,e){let r=io(),n=fs({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===vr?void 0:vr].filter(o=>!!o)});t.common.issues.push(n)}var Be=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return B;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return B;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},B=Object.freeze({status:"aborted"}),pn=t=>({status:"dirty",value:t}),et=t=>({status:"valid",value:t}),qi=t=>t.status==="aborted",Bi=t=>t.status==="dirty",zr=t=>t.status==="valid",ao=t=>typeof Promise<"u"&&t instanceof Promise;var j;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}));var Tt=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},qh=(t,e)=>{if(zr(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new lt(t.common.issues);return this._error=r,this._error}}};function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}var Y=class{get description(){return this._def.description}_getType(e){return ir(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Be,ctx:{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ao(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)},o=this._parseSync({data:e,path:n.path,parent:n});return qh(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return zr(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>zr(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ao(o)?o:Promise.resolve(o));return qh(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:w.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Rt({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return dt.create(this,this._def)}nullable(){return cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Sr.create(this)}promise(){return Hr.create(this,this._def)}or(e){return vn.create([this,e],this._def)}and(e){return xn.create(this,e,this._def)}transform(e){return new Rt({...J(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new wn({...J(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new ms({typeName:T.ZodBranded,type:this,...J(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Tn({...J(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return hs.create(this,e)}readonly(){return Rn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},dw=/^c[^\s-]{8,}$/i,pw=/^[0-9a-z]+$/,fw=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mw=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,hw=/^[a-z0-9_-]{21}$/i,gw=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,yw=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,_w=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vw="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Ru,xw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,bw=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Sw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,kw=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ew=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ww=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Vh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Tw=new RegExp(`^${Vh}$`);function Wh(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Rw(t){return new RegExp(`^${Wh(t)}$`)}function Kh(t){let e=`${Vh}T${Wh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Pw(t,e){return!!((e==="v4"||!e)&&xw.test(t)||(e==="v6"||!e)&&Sw.test(t))}function $w(t,e){if(!gw.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function Cw(t,e){return!!((e==="v4"||!e)&&bw.test(t)||(e==="v6"||!e)&&kw.test(t))}var Lr=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==I.string){let s=this._getOrReturnCtx(e);return P(s,{code:w.invalid_type,expected:I.string,received:s.parsedType}),B}let n=new Be,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?P(o,{code:w.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&P(o,{code:w.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")_w.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"email",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Ru||(Ru=new RegExp(vw,"u")),Ru.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"emoji",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")mw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"uuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")hw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"nanoid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")dw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cuid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")pw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cuid2",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")fw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"ulid",code:w.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),P(o,{validation:"url",code:w.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"regex",code:w.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?Kh(s).test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?Tw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?Rw(s).test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{code:w.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?yw.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"duration",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Pw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"ip",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?$w(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"jwt",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?Cw(e.data,s.version)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"cidr",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?Ew.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"base64",code:w.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?ww.test(e.data)||(o=this._getOrReturnCtx(e,o),P(o,{validation:"base64url",code:w.invalid_string,message:s.message}),n.dirty()):ne.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:w.invalid_string,...j.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...j.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...j.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...j.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...j.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...j.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...j.errToObj(r)})}nonempty(e){return this.min(1,j.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Lr.create=t=>new Lr({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...J(t)});function Ow(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var fn=class t extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==I.number){let s=this._getOrReturnCtx(e);return P(s,{code:w.invalid_type,expected:I.number,received:s.parsedType}),B}let n,o=new Be;for(let s of this._def.checks)s.kind==="int"?ne.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:w.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?Ow(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),P(n,{code:w.not_finite,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,j.toString(r))}gt(e,r){return this.setLimit("min",e,!1,j.toString(r))}lte(e,r){return this.setLimit("max",e,!0,j.toString(r))}lt(e,r){return this.setLimit("max",e,!1,j.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ne.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};fn.create=t=>new fn({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...J(t)});var mn=class t extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==I.bigint)return this._getInvalidInput(e);let n,o=new Be;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),P(n,{code:w.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return P(r,{code:w.invalid_type,expected:I.bigint,received:r.parsedType}),B}gte(e,r){return this.setLimit("min",e,!0,j.toString(r))}gt(e,r){return this.setLimit("min",e,!1,j.toString(r))}lte(e,r){return this.setLimit("max",e,!0,j.toString(r))}lt(e,r){return this.setLimit("max",e,!1,j.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};mn.create=t=>new mn({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var hn=class extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==I.boolean){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.boolean,received:n.parsedType}),B}return et(e.data)}};hn.create=t=>new hn({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var gn=class t extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==I.date){let s=this._getOrReturnCtx(e);return P(s,{code:w.invalid_type,expected:I.date,received:s.parsedType}),B}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return P(s,{code:w.invalid_date}),B}let n=new Be,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:w.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),P(o,{code:w.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ne.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:j.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};gn.create=t=>new gn({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...J(t)});var uo=class extends Y{_parse(e){if(this._getType(e)!==I.symbol){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.symbol,received:n.parsedType}),B}return et(e.data)}};uo.create=t=>new uo({typeName:T.ZodSymbol,...J(t)});var yn=class extends Y{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.undefined,received:n.parsedType}),B}return et(e.data)}};yn.create=t=>new yn({typeName:T.ZodUndefined,...J(t)});var _n=class extends Y{_parse(e){if(this._getType(e)!==I.null){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.null,received:n.parsedType}),B}return et(e.data)}};_n.create=t=>new _n({typeName:T.ZodNull,...J(t)});var Ur=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return et(e.data)}};Ur.create=t=>new Ur({typeName:T.ZodAny,...J(t)});var br=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return et(e.data)}};br.create=t=>new br({typeName:T.ZodUnknown,...J(t)});var qt=class extends Y{_parse(e){let r=this._getOrReturnCtx(e);return P(r,{code:w.invalid_type,expected:I.never,received:r.parsedType}),B}};qt.create=t=>new qt({typeName:T.ZodNever,...J(t)});var lo=class extends Y{_parse(e){if(this._getType(e)!==I.undefined){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.void,received:n.parsedType}),B}return et(e.data)}};lo.create=t=>new lo({typeName:T.ZodVoid,...J(t)});var Sr=class t extends Y{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==I.array)return P(r,{code:w.invalid_type,expected:I.array,received:r.parsedType}),B;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(P(r,{code:i?w.too_big:w.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(P(r,{code:w.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(P(r,{code:w.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new Tt(r,i,r.path,a)))).then(i=>Be.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new Tt(r,i,r.path,a)));return Be.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:j.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:j.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:j.toString(r)}})}nonempty(e){return this.min(1,e)}};Sr.create=(t,e)=>new Sr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...J(e)});function co(t){if(t instanceof pt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=dt.create(co(n))}return new pt({...t._def,shape:()=>e})}else return t instanceof Sr?new Sr({...t._def,type:co(t.element)}):t instanceof dt?dt.create(co(t.unwrap())):t instanceof cr?cr.create(co(t.unwrap())):t instanceof ar?ar.create(t.items.map(e=>co(e))):t}var pt=class t extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ne.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==I.object){let u=this._getOrReturnCtx(e);return P(u,{code:w.invalid_type,expected:I.object,received:u.parsedType}),B}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof qt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new Tt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof qt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(P(o,{code:w.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new Tt(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,f=await l.value;u.push({key:d,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>Be.mergeObjectSync(n,u)):Be.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:j.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:T.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of ne.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of ne.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return co(this)}partial(e){let r={};for(let n of ne.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ne.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof dt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return Gh(ne.objectKeys(this.shape))}};pt.create=(t,e)=>new pt({shape:()=>t,unknownKeys:"strip",catchall:qt.create(),typeName:T.ZodObject,...J(e)});pt.strictCreate=(t,e)=>new pt({shape:()=>t,unknownKeys:"strict",catchall:qt.create(),typeName:T.ZodObject,...J(e)});pt.lazycreate=(t,e)=>new pt({shape:t,unknownKeys:"strip",catchall:qt.create(),typeName:T.ZodObject,...J(e)});var vn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new lt(a.ctx.common.issues));return P(r,{code:w.invalid_union,unionErrors:i}),B}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new lt(c));return P(r,{code:w.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};vn.create=(t,e)=>new vn({options:t,typeName:T.ZodUnion,...J(e)});var xr=t=>t instanceof bn?xr(t.schema):t instanceof Rt?xr(t.innerType()):t instanceof Sn?[t.value]:t instanceof kn?t.options:t instanceof En?ne.objectValues(t.enum):t instanceof wn?xr(t._def.innerType):t instanceof yn?[void 0]:t instanceof _n?[null]:t instanceof dt?[void 0,...xr(t.unwrap())]:t instanceof cr?[null,...xr(t.unwrap())]:t instanceof ms||t instanceof Rn?xr(t.unwrap()):t instanceof Tn?xr(t._def.innerType):[],Vi=class t extends Y{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.object)return P(r,{code:w.invalid_type,expected:I.object,received:r.parsedType}),B;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(P(r,{code:w.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),B)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=xr(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:T.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...J(n)})}};function Pu(t,e){let r=ir(t),n=ir(e);if(t===e)return{valid:!0,data:t};if(r===I.object&&n===I.object){let o=ne.objectKeys(e),s=ne.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Pu(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===I.array&&n===I.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Pu(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===I.date&&n===I.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var xn=class extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(qi(s)||qi(i))return B;let a=Pu(s.value,i.value);return a.valid?((Bi(s)||Bi(i))&&r.dirty(),{status:r.value,value:a.data}):(P(n,{code:w.invalid_intersection_types}),B)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};xn.create=(t,e,r)=>new xn({left:t,right:e,typeName:T.ZodIntersection,...J(r)});var ar=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.array)return P(n,{code:w.invalid_type,expected:I.array,received:n.parsedType}),B;if(n.data.length<this._def.items.length)return P(n,{code:w.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),B;!this._def.rest&&n.data.length>this._def.items.length&&(P(n,{code:w.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new Tt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>Be.mergeArray(r,i)):Be.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ar.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ar({items:t,typeName:T.ZodTuple,rest:null,...J(e)})};var Wi=class t extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.object)return P(n,{code:w.invalid_type,expected:I.object,received:n.parsedType}),B;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new Tt(n,a,n.path,a)),value:i._parse(new Tt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Be.mergeObjectAsync(r,o):Be.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Y?new t({keyType:e,valueType:r,typeName:T.ZodRecord,...J(n)}):new t({keyType:Lr.create(),valueType:e,typeName:T.ZodRecord,...J(r)})}},po=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.map)return P(n,{code:w.invalid_type,expected:I.map,received:n.parsedType}),B;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new Tt(n,a,n.path,[u,"key"])),value:s._parse(new Tt(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return B;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};po.create=(t,e,r)=>new po({valueType:e,keyType:t,typeName:T.ZodMap,...J(r)});var fo=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==I.set)return P(n,{code:w.invalid_type,expected:I.set,received:n.parsedType}),B;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(P(n,{code:w.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(P(n,{code:w.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return B;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new Tt(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:j.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:j.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};fo.create=(t,e)=>new fo({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...J(e)});var Ki=class t extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.function)return P(r,{code:w.invalid_type,expected:I.function,received:r.parsedType}),B;function n(a,c){return fs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,io(),vr].filter(u=>!!u),issueData:{code:w.invalid_arguments,argumentsError:c}})}function o(a,c){return fs({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,io(),vr].filter(u=>!!u),issueData:{code:w.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Hr){let a=this;return et(async function(...c){let u=new lt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(n(c,m)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(o(d,m)),u})})}else{let a=this;return et(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new lt([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new lt([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ar.create(e).rest(br.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||ar.create([]).rest(br.create()),returns:r||br.create(),typeName:T.ZodFunction,...J(n)})}},bn=class extends Y{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};bn.create=(t,e)=>new bn({getter:t,typeName:T.ZodLazy,...J(e)});var Sn=class extends Y{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return P(r,{received:r.data,code:w.invalid_literal,expected:this._def.value}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};Sn.create=(t,e)=>new Sn({value:t,typeName:T.ZodLiteral,...J(e)});function Gh(t,e){return new kn({values:t,typeName:T.ZodEnum,...J(e)})}var kn=class t extends Y{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{expected:ne.joinValues(n),received:r.parsedType,code:w.invalid_type}),B}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return P(r,{received:r.data,code:w.invalid_enum_value,options:n}),B}return et(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};kn.create=Gh;var En=class extends Y{_parse(e){let r=ne.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==I.string&&n.parsedType!==I.number){let o=ne.objectValues(r);return P(n,{expected:ne.joinValues(o),received:n.parsedType,code:w.invalid_type}),B}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ne.objectValues(r);return P(n,{received:n.data,code:w.invalid_enum_value,options:o}),B}return et(e.data)}get enum(){return this._def.values}};En.create=(t,e)=>new En({values:t,typeName:T.ZodNativeEnum,...J(e)});var Hr=class extends Y{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==I.promise&&r.common.async===!1)return P(r,{code:w.invalid_type,expected:I.promise,received:r.parsedType}),B;let n=r.parsedType===I.promise?r.data:Promise.resolve(r.data);return et(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Hr.create=(t,e)=>new Hr({type:t,typeName:T.ZodPromise,...J(e)});var Rt=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{P(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return B;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?B:c.status==="dirty"?pn(c.value):r.value==="dirty"?pn(c.value):c});{if(r.value==="aborted")return B;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?B:a.status==="dirty"?pn(a.value):r.value==="dirty"?pn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?B:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!zr(i))return B;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>zr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):B);ne.assertNever(o)}};Rt.create=(t,e,r)=>new Rt({schema:t,typeName:T.ZodEffects,effect:e,...J(r)});Rt.createWithPreprocess=(t,e,r)=>new Rt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...J(r)});var dt=class extends Y{_parse(e){return this._getType(e)===I.undefined?et(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};dt.create=(t,e)=>new dt({innerType:t,typeName:T.ZodOptional,...J(e)});var cr=class extends Y{_parse(e){return this._getType(e)===I.null?et(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};cr.create=(t,e)=>new cr({innerType:t,typeName:T.ZodNullable,...J(e)});var wn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===I.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};wn.create=(t,e)=>new wn({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Tn=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ao(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new lt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new lt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Tn.create=(t,e)=>new Tn({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var mo=class extends Y{_parse(e){if(this._getType(e)!==I.nan){let n=this._getOrReturnCtx(e);return P(n,{code:w.invalid_type,expected:I.nan,received:n.parsedType}),B}return{status:"valid",value:e.data}}};mo.create=t=>new mo({typeName:T.ZodNaN,...J(t)});var Iw=Symbol("zod_brand"),ms=class extends Y{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},hs=class t extends Y{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?B:s.status==="dirty"?(r.dirty(),pn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?B:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:T.ZodPipeline})}},Rn=class extends Y{_parse(e){let r=this._def.innerType._parse(e),n=o=>(zr(o)&&(o.value=Object.freeze(o.value)),o);return ao(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Rn.create=(t,e)=>new Rn({innerType:t,typeName:T.ZodReadonly,...J(e)});function Bh(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function Jh(t,e={},r){return t?Ur.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Bh(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=Bh(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Ur.create()}var Aw={object:pt.lazycreate},T;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(T||(T={}));var Nw=(t,e={message:`Input not instance of ${t.name}`})=>Jh(r=>r instanceof t,e),Xh=Lr.create,Yh=fn.create,Dw=mo.create,Mw=mn.create,Qh=hn.create,jw=gn.create,zw=uo.create,Lw=yn.create,Uw=_n.create,Hw=Ur.create,Fw=br.create,Zw=qt.create,qw=lo.create,Bw=Sr.create,$u=pt.create,Vw=pt.strictCreate,Ww=vn.create,Kw=Vi.create,Gw=xn.create,Jw=ar.create,Xw=Wi.create,Yw=po.create,Qw=fo.create,eT=Ki.create,tT=bn.create,rT=Sn.create,nT=kn.create,oT=En.create,sT=Hr.create,iT=Rt.create,aT=dt.create,cT=cr.create,uT=Rt.createWithPreprocess,lT=hs.create,dT=()=>Xh().optional(),pT=()=>Yh().optional(),fT=()=>Qh().optional(),mT={string:(t=>Lr.create({...t,coerce:!0})),number:(t=>fn.create({...t,coerce:!0})),boolean:(t=>hn.create({...t,coerce:!0})),bigint:(t=>mn.create({...t,coerce:!0})),date:(t=>gn.create({...t,coerce:!0}))};var hT=B;var gT=Object.freeze({status:"aborted"});function S(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var kr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Gi={};function vt(t){return t&&Object.assign(Gi,t),Gi}var oe={};Fe(oe,{BIGINT_FORMAT_RANGES:()=>tg,Class:()=>Ou,NUMBER_FORMAT_RANGES:()=>zu,aborted:()=>$n,allowsEval:()=>Du,assert:()=>bT,assertEqual:()=>yT,assertIs:()=>vT,assertNever:()=>xT,assertNotEqual:()=>_T,assignProp:()=>Nu,cached:()=>_s,captureStackTrace:()=>Xi,cleanEnum:()=>NT,cleanRegex:()=>xs,clone:()=>xt,createTransparentProxy:()=>RT,defineLazy:()=>ye,esc:()=>Pn,escapeRegex:()=>Fr,extend:()=>CT,finalizeIssue:()=>Bt,floatSafeRemainder:()=>Au,getElementAtPath:()=>ST,getEnumValues:()=>ys,getLengthableOrigin:()=>bs,getParsedType:()=>TT,getSizableOrigin:()=>rg,isObject:()=>ho,isPlainObject:()=>go,issue:()=>Lu,joinValues:()=>Ji,jsonStringifyReplacer:()=>Iu,merge:()=>OT,normalizeParams:()=>V,nullish:()=>vs,numKeys:()=>wT,omit:()=>$T,optionalKeys:()=>ju,partial:()=>IT,pick:()=>PT,prefixIssues:()=>ur,primitiveTypes:()=>eg,promiseAllObject:()=>kT,propertyKeyTypes:()=>Mu,randomString:()=>ET,required:()=>AT,stringifyPrimitive:()=>Yi,unwrapMessage:()=>gs});function yT(t){return t}function _T(t){return t}function vT(t){}function xT(t){throw new Error}function bT(t){}function ys(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ji(t,e="|"){return t.map(r=>Yi(r)).join(e)}function Iu(t,e){return typeof e=="bigint"?e.toString():e}function _s(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function vs(t){return t==null}function xs(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Au(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function ye(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Nu(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ST(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function kT(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function ET(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Pn(t){return JSON.stringify(t)}var Xi=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function ho(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Du=_s(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function go(t){if(ho(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ho(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function wT(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}var TT=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Mu=new Set(["string","number","symbol"]),eg=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Fr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function V(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function RT(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Yi(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ju(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var zu={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},tg={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function PT(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return xt(t,{...t._zod.def,shape:r,checks:[]})}function $T(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return xt(t,{...t._zod.def,shape:r,checks:[]})}function CT(t,e){if(!go(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Nu(this,"shape",n),n},checks:[]};return xt(t,r)}function OT(t,e){return xt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Nu(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function IT(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return xt(e,{...e._zod.def,shape:o,checks:[]})}function AT(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return xt(e,{...e._zod.def,shape:o,checks:[]})}function $n(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ur(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function gs(t){return typeof t=="string"?t:t?.message}function Bt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=gs(t.inst?._zod.def?.error?.(t))??gs(e?.error?.(t))??gs(r.customError?.(t))??gs(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function rg(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function bs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Lu(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function NT(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ou=class{constructor(...e){}};var ng=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Iu,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Qi=S("$ZodError",ng),Ss=S("$ZodError",ng,{Parent:Error});function Uu(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Hu(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var Fu=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new kr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Bt(c,s,vt())));throw Xi(a,o?.callee),a}return i.value},Zu=Fu(Ss),qu=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Bt(c,s,vt())));throw Xi(a,o?.callee),a}return i.value},Bu=qu(Ss),Vu=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new kr;return s.issues.length?{success:!1,error:new(t??Qi)(s.issues.map(i=>Bt(i,o,vt())))}:{success:!0,data:s.value}},Cn=Vu(Ss),Wu=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Bt(i,o,vt())))}:{success:!0,data:s.value}},On=Wu(Ss);var og=/^[cC][^\s-]{8,}$/,sg=/^[0-9a-z]+$/,ig=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,ag=/^[0-9a-vA-V]{20}$/,cg=/^[A-Za-z0-9]{27}$/,ug=/^[a-zA-Z0-9_-]{21}$/,lg=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var dg=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ku=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/;var pg=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var MT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function fg(){return new RegExp(MT,"u")}var mg=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,hg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,gg=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,yg=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,_g=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Gu=/^[A-Za-z0-9_-]*$/,vg=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var xg=/^\+(?:[0-9]){6,14}[0-9]$/,bg="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Sg=new RegExp(`^${bg}$`);function kg(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Eg(t){return new RegExp(`^${kg(t)}$`)}function wg(t){let e=kg({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${bg}T(?:${n})$`)}var Tg=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Rg=/^\d+$/,Pg=/^-?\d+(?:\.\d+)?/i,$g=/true|false/i,Cg=/null/i;var Og=/^[^A-Z]*$/,Ig=/^[^a-z]*$/;var Ve=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Ag={number:"number",bigint:"bigint",object:"date"},Ju=S("$ZodCheckLessThan",(t,e)=>{Ve.init(t,e);let r=Ag[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Xu=S("$ZodCheckGreaterThan",(t,e)=>{Ve.init(t,e);let r=Ag[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Ng=S("$ZodCheckMultipleOf",(t,e)=>{Ve.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Au(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Dg=S("$ZodCheckNumberFormat",(t,e)=>{Ve.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=zu[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Rg)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}});var Mg=S("$ZodCheckMaxLength",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=bs(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),jg=S("$ZodCheckMinLength",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=bs(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),zg=S("$ZodCheckLengthEquals",(t,e)=>{var r;Ve.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!vs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=bs(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),ks=S("$ZodCheckStringFormat",(t,e)=>{var r,n;Ve.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),Lg=S("$ZodCheckRegex",(t,e)=>{ks.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Ug=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Og),ks.init(t,e)}),Hg=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Ig),ks.init(t,e)}),Fg=S("$ZodCheckIncludes",(t,e)=>{Ve.init(t,e);let r=Fr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),Zg=S("$ZodCheckStartsWith",(t,e)=>{Ve.init(t,e);let r=new RegExp(`^${Fr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),qg=S("$ZodCheckEndsWith",(t,e)=>{Ve.init(t,e);let r=new RegExp(`.*${Fr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});var Bg=S("$ZodCheckOverwrite",(t,e)=>{Ve.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}});var ta=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
160
160
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
161
- `))}};var Wg={major:4,minor:0,patch:0};var fe=x("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Wg;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Rn(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new kr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Rn(s,d)))});else{if(s.issues.length===d)continue;c||(c=Rn(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=$n(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Cn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Ss=x("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Tg(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),_e=x("$ZodStringFormat",(t,e)=>{xs.init(t,e),Ss.init(t,e)}),Ju=x("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=dg),_e.init(t,e)}),Yu=x("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Bu(n))}else e.pattern??(e.pattern=Bu());_e.init(t,e)}),Xu=x("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=pg),_e.init(t,e)}),Qu=x("$ZodURL",(t,e)=>{_e.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:vg.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),el=x("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=fg()),_e.init(t,e)}),tl=x("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ug),_e.init(t,e)}),rl=x("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=og),_e.init(t,e)}),nl=x("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sg),_e.init(t,e)}),ol=x("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ig),_e.init(t,e)}),sl=x("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ag),_e.init(t,e)}),il=x("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=cg),_e.init(t,e)}),ny=x("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=wg(e)),_e.init(t,e)}),oy=x("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sg),_e.init(t,e)}),sy=x("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Eg(e)),_e.init(t,e)}),iy=x("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=lg),_e.init(t,e)}),al=x("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=mg),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),cl=x("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=hg),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),ul=x("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=gg),_e.init(t,e)}),ll=x("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=yg),_e.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function ay(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var dl=x("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=_g),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{ay(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function $T(t){if(!Vu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return ay(r)}var pl=x("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Vu),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{$T(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),fl=x("$ZodE164",(t,e)=>{e.pattern??(e.pattern=bg),_e.init(t,e)});function CT(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var ml=x("$ZodJWT",(t,e)=>{_e.init(t,e),t._zod.check=r=>{CT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var ta=x("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Rg,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),hl=x("$ZodNumber",(t,e)=>{Dg.init(t,e),ta.init(t,e)}),gl=x("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=$g,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var yl=x("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=Cg,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var _l=x("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),vl=x("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Kg(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}var bl=x("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Kg(u,r,i))):Kg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ea(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function Gg(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ur(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var ra=x("$ZodObject",(t,e)=>{fe.init(t,e);let r=gs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof fe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=Nu(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});ye(t._zod,"propValues",()=>{let d=e.shape,f={};for(let m in d){let p=d[m]._zod;if(p.values){f[m]??(f[m]=new Set);for(let h of p.values)f[m].add(h)}}return f});let n=d=>{let f=new Qi(["shape","payload","ctx"]),m=r.value,p=v=>{let _=Pn(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of m.keys)h[v]=`key_${g++}`;f.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let _=h[v];f.write(`const ${_} = ${p(v)};`);let S=Pn(v);f.write(`
161
+ `))}};var Wg={major:4,minor:0,patch:0};var fe=S("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Wg;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=$n(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,f=l._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new kr;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=$n(s,d)))});else{if(s.issues.length===d)continue;c||(c=$n(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new kr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=Cn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return On(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Es=S("$ZodString",(t,e)=>{fe.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Tg(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),_e=S("$ZodStringFormat",(t,e)=>{ks.init(t,e),Es.init(t,e)}),Qu=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=dg),_e.init(t,e)}),el=S("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Ku(n))}else e.pattern??(e.pattern=Ku());_e.init(t,e)}),tl=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=pg),_e.init(t,e)}),rl=S("$ZodURL",(t,e)=>{_e.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:vg.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),nl=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=fg()),_e.init(t,e)}),ol=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=ug),_e.init(t,e)}),sl=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=og),_e.init(t,e)}),il=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=sg),_e.init(t,e)}),al=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=ig),_e.init(t,e)}),cl=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=ag),_e.init(t,e)}),ul=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=cg),_e.init(t,e)}),ny=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=wg(e)),_e.init(t,e)}),oy=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Sg),_e.init(t,e)}),sy=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Eg(e)),_e.init(t,e)}),iy=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=lg),_e.init(t,e)}),ll=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=mg),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),dl=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=hg),_e.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),pl=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=gg),_e.init(t,e)}),fl=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=yg),_e.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});function ay(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ml=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=_g),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{ay(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});function jT(t){if(!Gu.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return ay(r)}var hl=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Gu),_e.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{jT(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),gl=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=xg),_e.init(t,e)});function zT(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var yl=S("$ZodJWT",(t,e)=>{_e.init(t,e),t._zod.check=r=>{zT(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}});var na=S("$ZodNumber",(t,e)=>{fe.init(t,e),t._zod.pattern=t._zod.bag.pattern??Pg,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),_l=S("$ZodNumber",(t,e)=>{Dg.init(t,e),na.init(t,e)}),vl=S("$ZodBoolean",(t,e)=>{fe.init(t,e),t._zod.pattern=$g,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}});var xl=S("$ZodNull",(t,e)=>{fe.init(t,e),t._zod.pattern=Cg,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}});var bl=S("$ZodUnknown",(t,e)=>{fe.init(t,e),t._zod.parse=r=>r}),Sl=S("$ZodNever",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});function Kg(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}var kl=S("$ZodArray",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>Kg(u,r,i))):Kg(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});function ra(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function Gg(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...ur(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}var oa=S("$ZodObject",(t,e)=>{fe.init(t,e);let r=_s(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof fe))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=ju(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});ye(t._zod,"propValues",()=>{let d=e.shape,f={};for(let m in d){let p=d[m]._zod;if(p.values){f[m]??(f[m]=new Set);for(let h of p.values)f[m].add(h)}}return f});let n=d=>{let f=new ta(["shape","payload","ctx"]),m=r.value,p=v=>{let _=Pn(v);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let v of m.keys)h[v]=`key_${g++}`;f.write("const newResult = {}");for(let v of m.keys)if(m.optionalKeys.has(v)){let _=h[v];f.write(`const ${_} = ${p(v)};`);let b=Pn(v);f.write(`
162
162
  if (${_}.issues.length) {
163
- if (input[${S}] === undefined) {
164
- if (${S} in input) {
165
- newResult[${S}] = undefined;
163
+ if (input[${b}] === undefined) {
164
+ if (${b} in input) {
165
+ newResult[${b}] = undefined;
166
166
  }
167
167
  } else {
168
168
  payload.issues = payload.issues.concat(
169
169
  ${_}.issues.map((iss) => ({
170
170
  ...iss,
171
- path: iss.path ? [${S}, ...iss.path] : [${S}],
171
+ path: iss.path ? [${b}, ...iss.path] : [${b}],
172
172
  }))
173
173
  );
174
174
  }
175
175
  } else if (${_}.value === undefined) {
176
- if (${S} in input) newResult[${S}] = undefined;
176
+ if (${b} in input) newResult[${b}] = undefined;
177
177
  } else {
178
- newResult[${S}] = ${_}.value;
178
+ newResult[${b}] = ${_}.value;
179
179
  }
180
180
  `)}else{let _=h[v];f.write(`const ${_} = ${p(v)};`),f.write(`
181
181
  if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
182
182
  ...iss,
183
183
  path: iss.path ? [${Pn(v)}, ...iss.path] : [${Pn(v)}]
184
- })));`),f.write(`newResult[${Pn(v)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(v,_)=>y(d,v,_)},o,s=mo,i=!Wi.jitless,c=i&&Iu.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let _=l.shape;for(let S of l.keys){let T=_[S],I=T._zod.run({value:m[S],issues:[]},f),N=T._zod.optin==="optional"&&T._zod.optout==="optional";I instanceof Promise?p.push(I.then(O=>N?Gg(O,d,S,m):ea(O,d,S))):N?Gg(I,d,S,m):ea(I,d,S)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,v=y.def.type;for(let _ of Object.keys(m)){if(g.has(_))continue;if(v==="never"){h.push(_);continue}let S=y.run({value:m[_],issues:[]},f);S instanceof Promise?p.push(S.then(T=>ea(T,d,_))):ea(S,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Jg(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>qt(s,n,vt())))}),e}var na=x("$ZodUnion",(t,e)=>{fe.init(t,e),ye(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ye(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ye(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ye(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>_s(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Jg(i,r,t,n)):Jg(s,r,t,n)}}),xl=x("$ZodDiscriminatedUnion",(t,e)=>{na.init(t,e);let r=t._zod.parse;ye(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=gs(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!mo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Sl=x("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Yg(r,c,u)):Yg(r,s,i)}});function Gu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(ho(t)&&ho(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Gu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Gu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Yg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),Rn(t))return t;let n=Gu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var kl=x("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ho(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ur(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ur(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>qt(u,n,vt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ur(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ur(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var El=x("$ZodEnum",(t,e)=>{fe.init(t,e);let r=hs(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Au.has(typeof n)).map(n=>typeof n=="string"?Hr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),wl=x("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Hr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var Tl=x("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new kr;return r.value=o,r}}),Pl=x("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ye(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ye(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${_s(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Rl=x("$ZodNullable",(t,e)=>{fe.init(t,e),ye(t._zod,"optin",()=>e.innerType._zod.optin),ye(t._zod,"optout",()=>e.innerType._zod.optout),ye(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${_s(r.source)}|null)$`):void 0}),ye(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),$l=x("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Xg(s,e)):Xg(o,e)}});function Xg(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Cl=x("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Ol=x("$ZodNonOptional",(t,e)=>{fe.init(t,e),ye(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Qg(s,t)):Qg(o,t)}});function Qg(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Il=x("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"optout",()=>e.innerType._zod.optout),ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>qt(i,n,vt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>qt(s,n,vt()))},input:r.value}),r.issues=[]),r)}});var Al=x("$ZodPipe",(t,e)=>{fe.init(t,e),ye(t._zod,"values",()=>e.in._zod.values),ye(t._zod,"optin",()=>e.in._zod.optin),ye(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ey(s,e,n)):ey(o,e,n)}});function ey(t,e,r){return Rn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var Nl=x("$ZodReadonly",(t,e)=>{fe.init(t,e),ye(t._zod,"propValues",()=>e.innerType._zod.propValues),ye(t._zod,"values",()=>e.innerType._zod.values),ye(t._zod,"optin",()=>e.innerType._zod.optin),ye(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ty):ty(o)}});function ty(t){return t.value=Object.freeze(t.value),t}var Dl=x("$ZodCustom",(t,e)=>{Ze.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>ry(s,r,n,t));ry(o,r,n,t)}});function ry(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Mu(o))}}var OT=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},IT=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${OT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Ji(n.values[0])}`:`Invalid option: expected one of ${Ki(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ki(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function cy(){return{localeError:IT()}}var ks=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function uy(){return new ks}var Fr=uy();function Ml(t,e){return new t({type:"string",...V(e)})}function jl(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...V(e)})}function oa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...V(e)})}function zl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...V(e)})}function Ll(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...V(e)})}function Ul(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...V(e)})}function Hl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...V(e)})}function Fl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...V(e)})}function Zl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...V(e)})}function ql(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...V(e)})}function Bl(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...V(e)})}function Vl(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...V(e)})}function Wl(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...V(e)})}function Kl(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...V(e)})}function Gl(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...V(e)})}function Jl(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...V(e)})}function Yl(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...V(e)})}function Xl(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...V(e)})}function Ql(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...V(e)})}function ed(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...V(e)})}function td(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...V(e)})}function rd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...V(e)})}function nd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...V(e)})}function ly(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...V(e)})}function dy(t,e){return new t({type:"string",format:"date",check:"string_format",...V(e)})}function py(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...V(e)})}function fy(t,e){return new t({type:"string",format:"duration",check:"string_format",...V(e)})}function od(t,e){return new t({type:"number",checks:[],...V(e)})}function sd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...V(e)})}function id(t,e){return new t({type:"boolean",...V(e)})}function ad(t,e){return new t({type:"null",...V(e)})}function cd(t){return new t({type:"unknown"})}function ud(t,e){return new t({type:"never",...V(e)})}function sa(t,e){return new Wu({check:"less_than",...V(e),value:t,inclusive:!1})}function Es(t,e){return new Wu({check:"less_than",...V(e),value:t,inclusive:!0})}function ia(t,e){return new Ku({check:"greater_than",...V(e),value:t,inclusive:!1})}function ws(t,e){return new Ku({check:"greater_than",...V(e),value:t,inclusive:!0})}function aa(t,e){return new Ng({check:"multiple_of",...V(e),value:t})}function ca(t,e){return new Mg({check:"max_length",...V(e),maximum:t})}function go(t,e){return new jg({check:"min_length",...V(e),minimum:t})}function ua(t,e){return new zg({check:"length_equals",...V(e),length:t})}function ld(t,e){return new Lg({check:"string_format",format:"regex",...V(e),pattern:t})}function dd(t){return new Ug({check:"string_format",format:"lowercase",...V(t)})}function pd(t){return new Hg({check:"string_format",format:"uppercase",...V(t)})}function fd(t,e){return new Fg({check:"string_format",format:"includes",...V(e),includes:t})}function md(t,e){return new Zg({check:"string_format",format:"starts_with",...V(e),prefix:t})}function hd(t,e){return new qg({check:"string_format",format:"ends_with",...V(e),suffix:t})}function On(t){return new Bg({check:"overwrite",tx:t})}function gd(t){return On(e=>e.normalize(t))}function yd(){return On(t=>t.trim())}function _d(){return On(t=>t.toLowerCase())}function vd(){return On(t=>t.toUpperCase())}function my(t,e,r){return new t({type:"array",element:e,...V(r)})}function bd(t,e,r){let n=V(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function xd(t,e,r){return new t({type:"custom",check:"custom",fn:e,...V(r)})}var la=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Fr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let p=m;p.type="string";let{minimum:h,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){let S=[...v];S.length===1?p.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(T=>({...this.target==="draft-7"?{type:"string"}:{},pattern:T.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof S=="number"&&(p.exclusiveMinimum=S),typeof h=="number"&&(p.minimum=h,typeof S=="number"&&(S>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let h=o.shape;for(let v in h)p.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(v=>{let _=o.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((v,_)=>this.process(v,{...d,path:[...d.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=m;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,h=hs(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&ze(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:m+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let p=d.schema;for(let h in p)delete p[h];p.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
184
+ })));`),f.write(`newResult[${Pn(v)}] = ${_}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(v,_)=>y(d,v,_)},o,s=ho,i=!Gi.jitless,c=i&&Du.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=r.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),d=o(d,f);else{d.value={};let _=l.shape;for(let b of l.keys){let E=_[b],R=E._zod.run({value:m[b],issues:[]},f),N=E._zod.optin==="optional"&&E._zod.optout==="optional";R instanceof Promise?p.push(R.then(C=>N?Gg(C,d,b,m):ra(C,d,b))):N?Gg(R,d,b,m):ra(R,d,b)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,v=y.def.type;for(let _ of Object.keys(m)){if(g.has(_))continue;if(v==="never"){h.push(_);continue}let b=y.run({value:m[_],issues:[]},f);b instanceof Promise?p.push(b.then(E=>ra(E,d,_))):ra(b,d,_)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Jg(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Bt(s,n,vt())))}),e}var sa=S("$ZodUnion",(t,e)=>{fe.init(t,e),ye(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ye(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ye(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ye(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>xs(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>Jg(i,r,t,n)):Jg(s,r,t,n)}}),El=S("$ZodDiscriminatedUnion",(t,e)=>{sa.init(t,e);let r=t._zod.parse;ye(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=_s(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!ho(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),wl=S("$ZodIntersection",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>Xg(r,c,u)):Xg(r,s,i)}});function Yu(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(go(t)&&go(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Yu(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Yu(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Xg(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),$n(t))return t;let n=Yu(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}var Tl=S("$ZodRecord",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!go(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ur(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ur(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Bt(u,n,vt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ur(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ur(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}});var Rl=S("$ZodEnum",(t,e)=>{fe.init(t,e);let r=ys(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Mu.has(typeof n)).map(n=>typeof n=="string"?Fr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Pl=S("$ZodLiteral",(t,e)=>{fe.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Fr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}});var $l=S("$ZodTransform",(t,e)=>{fe.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new kr;return r.value=o,r}}),Cl=S("$ZodOptional",(t,e)=>{fe.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ye(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ye(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${xs(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Ol=S("$ZodNullable",(t,e)=>{fe.init(t,e),ye(t._zod,"optin",()=>e.innerType._zod.optin),ye(t._zod,"optout",()=>e.innerType._zod.optout),ye(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${xs(r.source)}|null)$`):void 0}),ye(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Il=S("$ZodDefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Yg(s,e)):Yg(o,e)}});function Yg(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Al=S("$ZodPrefault",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Nl=S("$ZodNonOptional",(t,e)=>{fe.init(t,e),ye(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>Qg(s,t)):Qg(o,t)}});function Qg(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}var Dl=S("$ZodCatch",(t,e)=>{fe.init(t,e),t._zod.optin="optional",ye(t._zod,"optout",()=>e.innerType._zod.optout),ye(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Bt(i,n,vt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Bt(s,n,vt()))},input:r.value}),r.issues=[]),r)}});var Ml=S("$ZodPipe",(t,e)=>{fe.init(t,e),ye(t._zod,"values",()=>e.in._zod.values),ye(t._zod,"optin",()=>e.in._zod.optin),ye(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>ey(s,e,n)):ey(o,e,n)}});function ey(t,e,r){return $n(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}var jl=S("$ZodReadonly",(t,e)=>{fe.init(t,e),ye(t._zod,"propValues",()=>e.innerType._zod.propValues),ye(t._zod,"values",()=>e.innerType._zod.values),ye(t._zod,"optin",()=>e.innerType._zod.optin),ye(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(ty):ty(o)}});function ty(t){return t.value=Object.freeze(t.value),t}var zl=S("$ZodCustom",(t,e)=>{Ve.init(t,e),fe.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>ry(s,r,n,t));ry(o,r,n,t)}});function ry(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Lu(o))}}var LT=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},UT=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${LT(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Yi(n.values[0])}`:`Invalid option: expected one of ${Ji(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ji(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}};function cy(){return{localeError:UT()}}var ws=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function uy(){return new ws}var Zr=uy();function Ll(t,e){return new t({type:"string",...V(e)})}function Ul(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...V(e)})}function ia(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...V(e)})}function Hl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...V(e)})}function Fl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...V(e)})}function Zl(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...V(e)})}function ql(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...V(e)})}function Bl(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...V(e)})}function Vl(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...V(e)})}function Wl(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...V(e)})}function Kl(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...V(e)})}function Gl(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...V(e)})}function Jl(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...V(e)})}function Xl(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...V(e)})}function Yl(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...V(e)})}function Ql(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...V(e)})}function ed(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...V(e)})}function td(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...V(e)})}function rd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...V(e)})}function nd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...V(e)})}function od(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...V(e)})}function sd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...V(e)})}function id(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...V(e)})}function ly(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...V(e)})}function dy(t,e){return new t({type:"string",format:"date",check:"string_format",...V(e)})}function py(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...V(e)})}function fy(t,e){return new t({type:"string",format:"duration",check:"string_format",...V(e)})}function ad(t,e){return new t({type:"number",checks:[],...V(e)})}function cd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...V(e)})}function ud(t,e){return new t({type:"boolean",...V(e)})}function ld(t,e){return new t({type:"null",...V(e)})}function dd(t){return new t({type:"unknown"})}function pd(t,e){return new t({type:"never",...V(e)})}function aa(t,e){return new Ju({check:"less_than",...V(e),value:t,inclusive:!1})}function Ts(t,e){return new Ju({check:"less_than",...V(e),value:t,inclusive:!0})}function ca(t,e){return new Xu({check:"greater_than",...V(e),value:t,inclusive:!1})}function Rs(t,e){return new Xu({check:"greater_than",...V(e),value:t,inclusive:!0})}function ua(t,e){return new Ng({check:"multiple_of",...V(e),value:t})}function la(t,e){return new Mg({check:"max_length",...V(e),maximum:t})}function yo(t,e){return new jg({check:"min_length",...V(e),minimum:t})}function da(t,e){return new zg({check:"length_equals",...V(e),length:t})}function fd(t,e){return new Lg({check:"string_format",format:"regex",...V(e),pattern:t})}function md(t){return new Ug({check:"string_format",format:"lowercase",...V(t)})}function hd(t){return new Hg({check:"string_format",format:"uppercase",...V(t)})}function gd(t,e){return new Fg({check:"string_format",format:"includes",...V(e),includes:t})}function yd(t,e){return new Zg({check:"string_format",format:"starts_with",...V(e),prefix:t})}function _d(t,e){return new qg({check:"string_format",format:"ends_with",...V(e),suffix:t})}function In(t){return new Bg({check:"overwrite",tx:t})}function vd(t){return In(e=>e.normalize(t))}function xd(){return In(t=>t.trim())}function bd(){return In(t=>t.toLowerCase())}function Sd(){return In(t=>t.toUpperCase())}function my(t,e,r){return new t({type:"array",element:e,...V(r)})}function kd(t,e,r){let n=V(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Ed(t,e,r){return new t({type:"custom",check:"custom",fn:e,...V(r)})}var pa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Zr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let p=m;p.type="string";let{minimum:h,maximum:g,format:y,patterns:v,contentEncoding:_}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),v&&v.size>0){let b=[...v];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:v,exclusiveMaximum:_,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof v=="number"&&(p.multipleOf=v);break}case"boolean":{let p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let h=o.shape;for(let v in h)p.properties[v]=this.process(h[v],{...d,path:[...d.path,"properties",v]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(v=>{let _=o.shape[v]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,v=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=v;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((v,_)=>this.process(v,{...d,path:[...d.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let v=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=v:p.additionalItems=v}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=m;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,h=ys(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:v}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),v?v.length===1?(h.contentMediaType=v[0],Object.assign(p,h)):p.anyOf=v.map(_=>({...h,contentMediaType:_})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&Le(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(v=>v);if(h)return{ref:g(h)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let m=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:m+p}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:f,defId:m}=s(l);d.def={...d.schema},m&&(d.defId=m);let p=d.schema;for(let h in p)delete p[h];p.$ref=f};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
185
185
 
186
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),m=f.def??f.schema,p={...m};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,p))}f.isParent||this.override({zodSchema:l,jsonSchema:m,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function Sd(t,e){if(t instanceof ks){let n=new la(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new la(e);return r.process(t),r.emit(t,e)}function ze(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ze(o.element,r);case"object":{for(let s in o.shape)if(ze(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(ze(s,r))return!0;return!1}case"intersection":return ze(o.left,r)||ze(o.right,r);case"tuple":{for(let s of o.items)if(ze(s,r))return!0;return!!(o.rest&&ze(o.rest,r))}case"record":return ze(o.keyType,r)||ze(o.valueType,r);case"map":return ze(o.keyType,r)||ze(o.valueType,r);case"set":return ze(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ze(o.innerType,r);case"lazy":return ze(o.getter(),r);case"default":return ze(o.innerType,r);case"prefault":return ze(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return ze(o.in,r)||ze(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var fP=x("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");fe.init(t,e),t.def=e,t.parse=(r,n)=>Uu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>$n(t,r,n),t.parseAsync=async(r,n)=>Fu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Cn(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>bt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var mP=x("ZodMiniObject",(t,e)=>{ra.init(t,e),fP.init(t,e),oe.defineLazy(t,"shape",()=>e.shape)});function kd(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new mP(r)}function Rt(t){return!!t._zod}function An(t){let e=Object.values(t);if(e.length===0)return kd({});let r=e.every(Rt),n=e.every(o=>!Rt(o));if(r)return kd(t);if(n)return Tu(t);throw new Error("Mixed Zod versions detected in object shape.")}function Zr(t,e){return Rt(t)?$n(t,e):t.safeParse(e)}async function da(t,e){return Rt(t)?await Cn(t,e):await t.safeParseAsync(e)}function qr(t){if(!t)return;let e;if(Rt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function yo(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return An(t)}}if(Rt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function pa(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function gy(t){return t.description}function yy(t){if(Rt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function fa(t){if(Rt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ts={};Ue(Ts,{ZodISODate:()=>vy,ZodISODateTime:()=>_y,ZodISODuration:()=>xy,ZodISOTime:()=>by,date:()=>wd,datetime:()=>Ed,duration:()=>Pd,time:()=>Td});var _y=x("ZodISODateTime",(t,e)=>{ny.init(t,e),Te.init(t,e)});function Ed(t){return ly(_y,t)}var vy=x("ZodISODate",(t,e)=>{oy.init(t,e),Te.init(t,e)});function wd(t){return dy(vy,t)}var by=x("ZodISOTime",(t,e)=>{sy.init(t,e),Te.init(t,e)});function Td(t){return py(by,t)}var xy=x("ZodISODuration",(t,e)=>{iy.init(t,e),Te.init(t,e)});function Pd(t){return fy(xy,t)}var Sy=(t,e)=>{Yi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>zu(t,r)},flatten:{value:r=>ju(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},H1=x("ZodError",Sy),Ps=x("ZodError",Sy,{Parent:Error});var ky=Lu(Ps),Ey=Hu(Ps),wy=Zu(Ps),Ty=qu(Ps);var Oe=x("ZodType",(t,e)=>(fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>bt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>ky(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>wy(t,r,n),t.parseAsync=async(r,n)=>Ey(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ty(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(dR(r,n)),t.superRefine=r=>t.check(pR(r)),t.overwrite=r=>t.check(On(r)),t.optional=()=>Re(t),t.nullable=()=>$y(t),t.nullish=()=>Re($y(t)),t.nonoptional=r=>oR(t,r),t.array=()=>se(t),t.or=r=>xe([t,r]),t.and=r=>ha(t,r),t.transform=r=>$d(t,Dy(r)),t.default=r=>tR(t,r),t.prefault=r=>nR(t,r),t.catch=r=>iR(t,r),t.pipe=r=>$d(t,r),t.readonly=()=>uR(t),t.describe=r=>{let n=t.clone();return Fr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Fr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Fr.get(t);let n=t.clone();return Fr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cy=x("_ZodString",(t,e)=>{Ss.init(t,e),Oe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(ld(...n)),t.includes=(...n)=>t.check(fd(...n)),t.startsWith=(...n)=>t.check(md(...n)),t.endsWith=(...n)=>t.check(hd(...n)),t.min=(...n)=>t.check(go(...n)),t.max=(...n)=>t.check(ca(...n)),t.length=(...n)=>t.check(ua(...n)),t.nonempty=(...n)=>t.check(go(1,...n)),t.lowercase=n=>t.check(dd(n)),t.uppercase=n=>t.check(pd(n)),t.trim=()=>t.check(yd()),t.normalize=(...n)=>t.check(gd(...n)),t.toLowerCase=()=>t.check(_d()),t.toUpperCase=()=>t.check(vd())}),kP=x("ZodString",(t,e)=>{Ss.init(t,e),Cy.init(t,e),t.email=r=>t.check(jl(EP,r)),t.url=r=>t.check(Fl(wP,r)),t.jwt=r=>t.check(nd(UP,r)),t.emoji=r=>t.check(Zl(TP,r)),t.guid=r=>t.check(oa(Py,r)),t.uuid=r=>t.check(zl(ma,r)),t.uuidv4=r=>t.check(Ll(ma,r)),t.uuidv6=r=>t.check(Ul(ma,r)),t.uuidv7=r=>t.check(Hl(ma,r)),t.nanoid=r=>t.check(ql(PP,r)),t.guid=r=>t.check(oa(Py,r)),t.cuid=r=>t.check(Bl(RP,r)),t.cuid2=r=>t.check(Vl($P,r)),t.ulid=r=>t.check(Wl(CP,r)),t.base64=r=>t.check(ed(jP,r)),t.base64url=r=>t.check(td(zP,r)),t.xid=r=>t.check(Kl(OP,r)),t.ksuid=r=>t.check(Gl(IP,r)),t.ipv4=r=>t.check(Jl(AP,r)),t.ipv6=r=>t.check(Yl(NP,r)),t.cidrv4=r=>t.check(Xl(DP,r)),t.cidrv6=r=>t.check(Ql(MP,r)),t.e164=r=>t.check(rd(LP,r)),t.datetime=r=>t.check(Ed(r)),t.date=r=>t.check(wd(r)),t.time=r=>t.check(Td(r)),t.duration=r=>t.check(Pd(r))});function b(t){return Ml(kP,t)}var Te=x("ZodStringFormat",(t,e)=>{_e.init(t,e),Cy.init(t,e)}),EP=x("ZodEmail",(t,e)=>{Xu.init(t,e),Te.init(t,e)});var Py=x("ZodGUID",(t,e)=>{Ju.init(t,e),Te.init(t,e)});var ma=x("ZodUUID",(t,e)=>{Yu.init(t,e),Te.init(t,e)});var wP=x("ZodURL",(t,e)=>{Qu.init(t,e),Te.init(t,e)});var TP=x("ZodEmoji",(t,e)=>{el.init(t,e),Te.init(t,e)});var PP=x("ZodNanoID",(t,e)=>{tl.init(t,e),Te.init(t,e)});var RP=x("ZodCUID",(t,e)=>{rl.init(t,e),Te.init(t,e)});var $P=x("ZodCUID2",(t,e)=>{nl.init(t,e),Te.init(t,e)});var CP=x("ZodULID",(t,e)=>{ol.init(t,e),Te.init(t,e)});var OP=x("ZodXID",(t,e)=>{sl.init(t,e),Te.init(t,e)});var IP=x("ZodKSUID",(t,e)=>{il.init(t,e),Te.init(t,e)});var AP=x("ZodIPv4",(t,e)=>{al.init(t,e),Te.init(t,e)});var NP=x("ZodIPv6",(t,e)=>{cl.init(t,e),Te.init(t,e)});var DP=x("ZodCIDRv4",(t,e)=>{ul.init(t,e),Te.init(t,e)});var MP=x("ZodCIDRv6",(t,e)=>{ll.init(t,e),Te.init(t,e)});var jP=x("ZodBase64",(t,e)=>{dl.init(t,e),Te.init(t,e)});var zP=x("ZodBase64URL",(t,e)=>{pl.init(t,e),Te.init(t,e)});var LP=x("ZodE164",(t,e)=>{fl.init(t,e),Te.init(t,e)});var UP=x("ZodJWT",(t,e)=>{ml.init(t,e),Te.init(t,e)});var Oy=x("ZodNumber",(t,e)=>{ta.init(t,e),Oe.init(t,e),t.gt=(n,o)=>t.check(ia(n,o)),t.gte=(n,o)=>t.check(ws(n,o)),t.min=(n,o)=>t.check(ws(n,o)),t.lt=(n,o)=>t.check(sa(n,o)),t.lte=(n,o)=>t.check(Es(n,o)),t.max=(n,o)=>t.check(Es(n,o)),t.int=n=>t.check(Ry(n)),t.safe=n=>t.check(Ry(n)),t.positive=n=>t.check(ia(0,n)),t.nonnegative=n=>t.check(ws(0,n)),t.negative=n=>t.check(sa(0,n)),t.nonpositive=n=>t.check(Es(0,n)),t.multipleOf=(n,o)=>t.check(aa(n,o)),t.step=(n,o)=>t.check(aa(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function pe(t){return od(Oy,t)}var HP=x("ZodNumberFormat",(t,e)=>{hl.init(t,e),Oy.init(t,e)});function Ry(t){return sd(HP,t)}var FP=x("ZodBoolean",(t,e)=>{gl.init(t,e),Oe.init(t,e)});function He(t){return id(FP,t)}var ZP=x("ZodNull",(t,e)=>{yl.init(t,e),Oe.init(t,e)});function Iy(t){return ad(ZP,t)}var qP=x("ZodUnknown",(t,e)=>{_l.init(t,e),Oe.init(t,e)});function Pe(){return cd(qP)}var BP=x("ZodNever",(t,e)=>{vl.init(t,e),Oe.init(t,e)});function VP(t){return ud(BP,t)}var WP=x("ZodArray",(t,e)=>{bl.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(go(r,n)),t.nonempty=r=>t.check(go(1,r)),t.max=(r,n)=>t.check(ca(r,n)),t.length=(r,n)=>t.check(ua(r,n)),t.unwrap=()=>t.element});function se(t,e){return my(WP,t,e)}var Ay=x("ZodObject",(t,e)=>{ra.init(t,e),Oe.init(t,e),oe.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>pt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:VP()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>oe.extend(t,r),t.merge=r=>oe.merge(t,r),t.pick=r=>oe.pick(t,r),t.omit=r=>oe.omit(t,r),t.partial=(...r)=>oe.partial(My,t,r[0]),t.required=(...r)=>oe.required(jy,t,r[0])});function C(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new Ay(r)}function tt(t,e){return new Ay({type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},catchall:Pe(),...oe.normalizeParams(e)})}var Ny=x("ZodUnion",(t,e)=>{na.init(t,e),Oe.init(t,e),t.options=e.options});function xe(t,e){return new Ny({type:"union",options:t,...oe.normalizeParams(e)})}var KP=x("ZodDiscriminatedUnion",(t,e)=>{Ny.init(t,e),xl.init(t,e)});function Cd(t,e,r){return new KP({type:"union",options:e,discriminator:t,...oe.normalizeParams(r)})}var GP=x("ZodIntersection",(t,e)=>{Sl.init(t,e),Oe.init(t,e)});function ha(t,e){return new GP({type:"intersection",left:t,right:e})}var JP=x("ZodRecord",(t,e)=>{kl.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ve(t,e,r){return new JP({type:"record",keyType:t,valueType:e,...oe.normalizeParams(r)})}var Rd=x("ZodEnum",(t,e)=>{El.init(t,e),Oe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Rd({...e,checks:[],...oe.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Rd({...e,checks:[],...oe.normalizeParams(o),entries:s})}});function pt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Rd({type:"enum",entries:r,...oe.normalizeParams(e)})}var YP=x("ZodLiteral",(t,e)=>{wl.init(t,e),Oe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function L(t,e){return new YP({type:"literal",values:Array.isArray(t)?t:[t],...oe.normalizeParams(e)})}var XP=x("ZodTransform",(t,e)=>{Tl.init(t,e),Oe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(oe.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(oe.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Dy(t){return new XP({type:"transform",transform:t})}var My=x("ZodOptional",(t,e)=>{Pl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Re(t){return new My({type:"optional",innerType:t})}var QP=x("ZodNullable",(t,e)=>{Rl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $y(t){return new QP({type:"nullable",innerType:t})}var eR=x("ZodDefault",(t,e)=>{$l.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function tR(t,e){return new eR({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var rR=x("ZodPrefault",(t,e)=>{Cl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function nR(t,e){return new rR({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var jy=x("ZodNonOptional",(t,e)=>{Ol.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function oR(t,e){return new jy({type:"nonoptional",innerType:t,...oe.normalizeParams(e)})}var sR=x("ZodCatch",(t,e)=>{Il.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function iR(t,e){return new sR({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var aR=x("ZodPipe",(t,e)=>{Al.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function $d(t,e){return new aR({type:"pipe",in:t,out:e})}var cR=x("ZodReadonly",(t,e)=>{Nl.init(t,e),Oe.init(t,e)});function uR(t){return new cR({type:"readonly",innerType:t})}var zy=x("ZodCustom",(t,e)=>{Dl.init(t,e),Oe.init(t,e)});function lR(t){let e=new Ze({check:"custom"});return e._zod.check=t,e}function Ly(t,e){return bd(zy,t??(()=>!0),e)}function dR(t,e={}){return xd(zy,t,e)}function pR(t){let e=lR(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(oe.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(oe.issue(o))}},t(r.value,r)));return e}function Od(t,e){return $d(Dy(t),e)}vt(cy());var Ad="2025-11-25";var Uy=[Ad,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Br="io.modelcontextprotocol/related-task",ya="2.0",Le=Ly(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hy=xe([b(),pe().int()]),Fy=b(),tU=tt({ttl:pe().optional(),pollInterval:pe().optional()}),fR=C({ttl:pe().optional()}),mR=C({taskId:b()}),Nd=tt({progressToken:Hy.optional(),[Br]:mR.optional()}),xt=C({_meta:Nd.optional()}),Rs=xt.extend({task:fR.optional()}),Zy=t=>Rs.safeParse(t).success,qe=C({method:b(),params:xt.loose().optional()}),$t=C({_meta:Nd.optional()}),Ct=C({method:b(),params:$t.loose().optional()}),Be=tt({_meta:Nd.optional()}),_a=xe([b(),pe().int()]),qy=C({jsonrpc:L(ya),id:_a,...qe.shape}).strict(),Dd=t=>qy.safeParse(t).success,By=C({jsonrpc:L(ya),...Ct.shape}).strict(),Vy=t=>By.safeParse(t).success,Md=C({jsonrpc:L(ya),id:_a,result:Be}).strict(),$s=t=>Md.safeParse(t).success;var Z;(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"})(Z||(Z={}));var jd=C({jsonrpc:L(ya),id:_a.optional(),error:C({code:pe().int(),message:b(),data:Pe().optional()})}).strict();var Wy=t=>jd.safeParse(t).success;var Ky=xe([qy,By,Md,jd]),rU=xe([Md,jd]),va=Be.strict(),hR=$t.extend({requestId:_a.optional(),reason:b().optional()}),ba=Ct.extend({method:L("notifications/cancelled"),params:hR}),gR=C({src:b(),mimeType:b().optional(),sizes:se(b()).optional(),theme:pt(["light","dark"]).optional()}),Cs=C({icons:se(gR).optional()}),_o=C({name:b(),title:b().optional()}),Gy=_o.extend({..._o.shape,...Cs.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),yR=ha(C({applyDefaults:He().optional()}),ve(b(),Pe())),_R=Od(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ha(C({form:yR.optional(),url:Le.optional()}),ve(b(),Pe()).optional())),vR=tt({list:Le.optional(),cancel:Le.optional(),requests:tt({sampling:tt({createMessage:Le.optional()}).optional(),elicitation:tt({create:Le.optional()}).optional()}).optional()}),bR=tt({list:Le.optional(),cancel:Le.optional(),requests:tt({tools:tt({call:Le.optional()}).optional()}).optional()}),xR=C({experimental:ve(b(),Le).optional(),sampling:C({context:Le.optional(),tools:Le.optional()}).optional(),elicitation:_R.optional(),roots:C({listChanged:He().optional()}).optional(),tasks:vR.optional(),extensions:ve(b(),Le).optional()}),SR=xt.extend({protocolVersion:b(),capabilities:xR,clientInfo:Gy}),zd=qe.extend({method:L("initialize"),params:SR});var kR=C({experimental:ve(b(),Le).optional(),logging:Le.optional(),completions:Le.optional(),prompts:C({listChanged:He().optional()}).optional(),resources:C({subscribe:He().optional(),listChanged:He().optional()}).optional(),tools:C({listChanged:He().optional()}).optional(),tasks:bR.optional(),extensions:ve(b(),Le).optional()}),ER=Be.extend({protocolVersion:b(),capabilities:kR,serverInfo:Gy,instructions:b().optional()}),Ld=Ct.extend({method:L("notifications/initialized"),params:$t.optional()});var xa=qe.extend({method:L("ping"),params:xt.optional()}),wR=C({progress:pe(),total:Re(pe()),message:Re(b())}),TR=C({...$t.shape,...wR.shape,progressToken:Hy}),Sa=Ct.extend({method:L("notifications/progress"),params:TR}),PR=xt.extend({cursor:Fy.optional()}),Os=qe.extend({params:PR.optional()}),Is=Be.extend({nextCursor:Fy.optional()}),RR=pt(["working","input_required","completed","failed","cancelled"]),As=C({taskId:b(),status:RR,ttl:xe([pe(),Iy()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:Re(pe()),statusMessage:Re(b())}),vo=Be.extend({task:As}),$R=$t.merge(As),Ns=Ct.extend({method:L("notifications/tasks/status"),params:$R}),ka=qe.extend({method:L("tasks/get"),params:xt.extend({taskId:b()})}),Ea=Be.merge(As),wa=qe.extend({method:L("tasks/result"),params:xt.extend({taskId:b()})}),nU=Be.loose(),Ta=Os.extend({method:L("tasks/list")}),Pa=Is.extend({tasks:se(As)}),Ra=qe.extend({method:L("tasks/cancel"),params:xt.extend({taskId:b()})}),Jy=Be.merge(As),Yy=C({uri:b(),mimeType:Re(b()),_meta:ve(b(),Pe()).optional()}),Xy=Yy.extend({text:b()}),Ud=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Qy=Yy.extend({blob:Ud}),Ds=pt(["user","assistant"]),bo=C({audience:se(Ds).optional(),priority:pe().min(0).max(1).optional(),lastModified:Ts.datetime({offset:!0}).optional()}),e_=C({..._o.shape,...Cs.shape,uri:b(),description:Re(b()),mimeType:Re(b()),size:Re(pe()),annotations:bo.optional(),_meta:Re(tt({}))}),CR=C({..._o.shape,...Cs.shape,uriTemplate:b(),description:Re(b()),mimeType:Re(b()),annotations:bo.optional(),_meta:Re(tt({}))}),xo=Os.extend({method:L("resources/list")}),OR=Is.extend({resources:se(e_)}),So=Os.extend({method:L("resources/templates/list")}),IR=Is.extend({resourceTemplates:se(CR)}),Hd=xt.extend({uri:b()}),AR=Hd,$a=qe.extend({method:L("resources/read"),params:AR}),NR=Be.extend({contents:se(xe([Xy,Qy]))}),DR=Ct.extend({method:L("notifications/resources/list_changed"),params:$t.optional()}),MR=Hd,jR=qe.extend({method:L("resources/subscribe"),params:MR}),zR=Hd,LR=qe.extend({method:L("resources/unsubscribe"),params:zR}),UR=$t.extend({uri:b()}),HR=Ct.extend({method:L("notifications/resources/updated"),params:UR}),FR=C({name:b(),description:Re(b()),required:Re(He())}),ZR=C({..._o.shape,...Cs.shape,description:Re(b()),arguments:Re(se(FR)),_meta:Re(tt({}))}),ko=Os.extend({method:L("prompts/list")}),qR=Is.extend({prompts:se(ZR)}),BR=xt.extend({name:b(),arguments:ve(b(),b()).optional()}),Ca=qe.extend({method:L("prompts/get"),params:BR}),Fd=C({type:L("text"),text:b(),annotations:bo.optional(),_meta:ve(b(),Pe()).optional()}),Zd=C({type:L("image"),data:Ud,mimeType:b(),annotations:bo.optional(),_meta:ve(b(),Pe()).optional()}),qd=C({type:L("audio"),data:Ud,mimeType:b(),annotations:bo.optional(),_meta:ve(b(),Pe()).optional()}),VR=C({type:L("tool_use"),name:b(),id:b(),input:ve(b(),Pe()),_meta:ve(b(),Pe()).optional()}),WR=C({type:L("resource"),resource:xe([Xy,Qy]),annotations:bo.optional(),_meta:ve(b(),Pe()).optional()}),KR=e_.extend({type:L("resource_link")}),Bd=xe([Fd,Zd,qd,KR,WR]),GR=C({role:Ds,content:Bd}),JR=Be.extend({description:b().optional(),messages:se(GR)}),YR=Ct.extend({method:L("notifications/prompts/list_changed"),params:$t.optional()}),XR=C({title:b().optional(),readOnlyHint:He().optional(),destructiveHint:He().optional(),idempotentHint:He().optional(),openWorldHint:He().optional()}),QR=C({taskSupport:pt(["required","optional","forbidden"]).optional()}),t_=C({..._o.shape,...Cs.shape,description:b().optional(),inputSchema:C({type:L("object"),properties:ve(b(),Le).optional(),required:se(b()).optional()}).catchall(Pe()),outputSchema:C({type:L("object"),properties:ve(b(),Le).optional(),required:se(b()).optional()}).catchall(Pe()).optional(),annotations:XR.optional(),execution:QR.optional(),_meta:ve(b(),Pe()).optional()}),Eo=Os.extend({method:L("tools/list")}),e0=Is.extend({tools:se(t_)}),Oa=Be.extend({content:se(Bd).default([]),structuredContent:ve(b(),Pe()).optional(),isError:He().optional()}),oU=Oa.or(Be.extend({toolResult:Pe()})),t0=Rs.extend({name:b(),arguments:ve(b(),Pe()).optional()}),wo=qe.extend({method:L("tools/call"),params:t0}),r0=Ct.extend({method:L("notifications/tools/list_changed"),params:$t.optional()}),sU=C({autoRefresh:He().default(!0),debounceMs:pe().int().nonnegative().default(300)}),Ms=pt(["debug","info","notice","warning","error","critical","alert","emergency"]),n0=xt.extend({level:Ms}),Vd=qe.extend({method:L("logging/setLevel"),params:n0}),o0=$t.extend({level:Ms,logger:b().optional(),data:Pe()}),s0=Ct.extend({method:L("notifications/message"),params:o0}),i0=C({name:b().optional()}),a0=C({hints:se(i0).optional(),costPriority:pe().min(0).max(1).optional(),speedPriority:pe().min(0).max(1).optional(),intelligencePriority:pe().min(0).max(1).optional()}),c0=C({mode:pt(["auto","required","none"]).optional()}),u0=C({type:L("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:se(Bd).default([]),structuredContent:C({}).loose().optional(),isError:He().optional(),_meta:ve(b(),Pe()).optional()}),l0=Cd("type",[Fd,Zd,qd]),ga=Cd("type",[Fd,Zd,qd,VR,u0]),d0=C({role:Ds,content:xe([ga,se(ga)]),_meta:ve(b(),Pe()).optional()}),p0=Rs.extend({messages:se(d0),modelPreferences:a0.optional(),systemPrompt:b().optional(),includeContext:pt(["none","thisServer","allServers"]).optional(),temperature:pe().optional(),maxTokens:pe().int(),stopSequences:se(b()).optional(),metadata:Le.optional(),tools:se(t_).optional(),toolChoice:c0.optional()}),f0=qe.extend({method:L("sampling/createMessage"),params:p0}),js=Be.extend({model:b(),stopReason:Re(pt(["endTurn","stopSequence","maxTokens"]).or(b())),role:Ds,content:l0}),Wd=Be.extend({model:b(),stopReason:Re(pt(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Ds,content:xe([ga,se(ga)])}),m0=C({type:L("boolean"),title:b().optional(),description:b().optional(),default:He().optional()}),h0=C({type:L("string"),title:b().optional(),description:b().optional(),minLength:pe().optional(),maxLength:pe().optional(),format:pt(["email","uri","date","date-time"]).optional(),default:b().optional()}),g0=C({type:pt(["number","integer"]),title:b().optional(),description:b().optional(),minimum:pe().optional(),maximum:pe().optional(),default:pe().optional()}),y0=C({type:L("string"),title:b().optional(),description:b().optional(),enum:se(b()),default:b().optional()}),_0=C({type:L("string"),title:b().optional(),description:b().optional(),oneOf:se(C({const:b(),title:b()})),default:b().optional()}),v0=C({type:L("string"),title:b().optional(),description:b().optional(),enum:se(b()),enumNames:se(b()).optional(),default:b().optional()}),b0=xe([y0,_0]),x0=C({type:L("array"),title:b().optional(),description:b().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:C({type:L("string"),enum:se(b())}),default:se(b()).optional()}),S0=C({type:L("array"),title:b().optional(),description:b().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:C({anyOf:se(C({const:b(),title:b()}))}),default:se(b()).optional()}),k0=xe([x0,S0]),E0=xe([v0,b0,k0]),w0=xe([E0,m0,h0,g0]),T0=Rs.extend({mode:L("form").optional(),message:b(),requestedSchema:C({type:L("object"),properties:ve(b(),w0),required:se(b()).optional()})}),P0=Rs.extend({mode:L("url"),message:b(),elicitationId:b(),url:b().url()}),R0=xe([T0,P0]),$0=qe.extend({method:L("elicitation/create"),params:R0}),C0=$t.extend({elicitationId:b()}),O0=Ct.extend({method:L("notifications/elicitation/complete"),params:C0}),To=Be.extend({action:pt(["accept","decline","cancel"]),content:Od(t=>t===null?void 0:t,ve(b(),xe([b(),pe(),He(),se(b())])).optional())}),I0=C({type:L("ref/resource"),uri:b()});var A0=C({type:L("ref/prompt"),name:b()}),N0=xt.extend({ref:xe([A0,I0]),argument:C({name:b(),value:b()}),context:C({arguments:ve(b(),b()).optional()}).optional()}),Ia=qe.extend({method:L("completion/complete"),params:N0});function r_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function n_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var D0=Be.extend({completion:tt({values:se(b()).max(100),total:Re(pe().int()),hasMore:Re(He())})}),M0=C({uri:b().startsWith("file://"),name:b().optional(),_meta:ve(b(),Pe()).optional()}),j0=qe.extend({method:L("roots/list"),params:xt.optional()}),Kd=Be.extend({roots:se(M0)}),z0=Ct.extend({method:L("notifications/roots/list_changed"),params:$t.optional()}),iU=xe([xa,zd,Ia,Vd,Ca,ko,xo,So,$a,jR,LR,wo,Eo,ka,wa,Ta,Ra]),aU=xe([ba,Sa,Ld,z0,Ns]),cU=xe([va,js,Wd,To,Kd,Ea,Pa,vo]),uU=xe([xa,f0,$0,j0,ka,wa,Ta,Ra]),lU=xe([ba,Sa,s0,HR,DR,r0,YR,Ns,O0]),dU=xe([va,ER,D0,JR,qR,OR,IR,NR,Oa,e0,Ea,Pa,vo]),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===Z.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Id(o.elicitations,r)}return new t(e,r,n)}},Id=class extends M{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Vr(t){return t==="completed"||t==="failed"||t==="cancelled"}var s_=Symbol("Let zodToJsonSchema decide on which parser to use");var o_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},i_=t=>typeof t=="string"?{...o_,name:t}:{...o_,...t};var a_=t=>{let e=i_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Gd(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ie(t,e,r,n,o){t[e]=r,Gd(t,e,n,o)}var Aa=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function $e(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Aa(e,t.currentPath):e.join("/")}}function c_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==w.ZodAny&&(r.items=W(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(r,"minItems",t.exactLength.value,t.exactLength.message,e),ie(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function u_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function l_(){return{type:"boolean"}}function Na(t,e){return W(t.type._def,e)}var d_=(t,e)=>W(t.innerType._def,e);function Jd(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Jd(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return L0(t,e)}}var L0=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ie(r,"minimum",n.value,n.message,e);break;case"max":ie(r,"maximum",n.value,n.message,e);break}return r};function p_(t,e){return{...W(t.innerType._def,e),default:t.defaultValue()}}function f_(t,e){return e.effectStrategy==="input"?W(t.schema._def,e):$e(e)}function m_(t){return{type:"string",enum:Array.from(t.values)}}var U0=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function h_(t,e){let r=[W(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),W(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(U0(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function g_(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Yd,Bt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Yd===void 0&&(Yd=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Yd),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Da(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Vt(r,"email",n.message,e);break;case"format:idn-email":Vt(r,"idn-email",n.message,e);break;case"pattern:zod":rt(r,Bt.email,n.message,e);break}break;case"url":Vt(r,"uri",n.message,e);break;case"uuid":Vt(r,"uuid",n.message,e);break;case"regex":rt(r,n.regex,n.message,e);break;case"cuid":rt(r,Bt.cuid,n.message,e);break;case"cuid2":rt(r,Bt.cuid2,n.message,e);break;case"startsWith":rt(r,RegExp(`^${Xd(n.value,e)}`),n.message,e);break;case"endsWith":rt(r,RegExp(`${Xd(n.value,e)}$`),n.message,e);break;case"datetime":Vt(r,"date-time",n.message,e);break;case"date":Vt(r,"date",n.message,e);break;case"time":Vt(r,"time",n.message,e);break;case"duration":Vt(r,"duration",n.message,e);break;case"length":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{rt(r,RegExp(Xd(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Vt(r,"ipv4",n.message,e),n.version!=="v4"&&Vt(r,"ipv6",n.message,e);break}case"base64url":rt(r,Bt.base64url,n.message,e);break;case"jwt":rt(r,Bt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&rt(r,Bt.ipv4Cidr,n.message,e),n.version!=="v4"&&rt(r,Bt.ipv6Cidr,n.message,e);break}case"emoji":rt(r,Bt.emoji(),n.message,e);break;case"ulid":{rt(r,Bt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Vt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ie(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{rt(r,Bt.base64,n.message,e);break}}break}case"nanoid":rt(r,Bt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Xd(t,e){return e.patternStrategy==="escape"?F0(t):t}var H0=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function F0(t){let e="";for(let r=0;r<t.length;r++)H0.has(t[r])||(e+="\\"),e+=t[r];return e}function Vt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ie(t,"format",e,r,n)}function rt(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:y_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ie(t,"pattern",y_(e,n),r,n)}function y_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
186
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let m=n.external.registry.get(l[0])?.id;if(e!==l[0]&&m){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let f=this.seen.get(l),m=f.def??f.schema,p={...m};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(m.allOf=m.allOf??[],m.allOf.push(g)):(Object.assign(m,g),Object.assign(m,p))}f.isParent||this.override({zodSchema:l,jsonSchema:m,path:f.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}};function wd(t,e){if(t instanceof ws){let n=new pa(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new pa(e);return r.process(t),r.emit(t,e)}function Le(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return Le(o.element,r);case"object":{for(let s in o.shape)if(Le(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(Le(s,r))return!0;return!1}case"intersection":return Le(o.left,r)||Le(o.right,r);case"tuple":{for(let s of o.items)if(Le(s,r))return!0;return!!(o.rest&&Le(o.rest,r))}case"record":return Le(o.keyType,r)||Le(o.valueType,r);case"map":return Le(o.keyType,r)||Le(o.valueType,r);case"set":return Le(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Le(o.innerType,r);case"lazy":return Le(o.getter(),r);case"default":return Le(o.innerType,r);case"prefault":return Le(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Le(o.in,r)||Le(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var b0=S("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");fe.init(t,e),t.def=e,t.parse=(r,n)=>Zu(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Cn(t,r,n),t.parseAsync=async(r,n)=>Bu(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>On(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>xt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))});var S0=S("ZodMiniObject",(t,e)=>{oa.init(t,e),b0.init(t,e),oe.defineLazy(t,"shape",()=>e.shape)});function Td(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new S0(r)}function Pt(t){return!!t._zod}function Nn(t){let e=Object.values(t);if(e.length===0)return Td({});let r=e.every(Pt),n=e.every(o=>!Pt(o));if(r)return Td(t);if(n)return $u(t);throw new Error("Mixed Zod versions detected in object shape.")}function qr(t,e){return Pt(t)?Cn(t,e):t.safeParse(e)}async function fa(t,e){return Pt(t)?await On(t,e):await t.safeParseAsync(e)}function Br(t){if(!t)return;let e;if(Pt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function _o(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Nn(t)}}if(Pt(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ma(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function gy(t){return t.description}function yy(t){if(Pt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ha(t){if(Pt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ps={};Fe(Ps,{ZodISODate:()=>vy,ZodISODateTime:()=>_y,ZodISODuration:()=>by,ZodISOTime:()=>xy,date:()=>Pd,datetime:()=>Rd,duration:()=>Cd,time:()=>$d});var _y=S("ZodISODateTime",(t,e)=>{ny.init(t,e),Re.init(t,e)});function Rd(t){return ly(_y,t)}var vy=S("ZodISODate",(t,e)=>{oy.init(t,e),Re.init(t,e)});function Pd(t){return dy(vy,t)}var xy=S("ZodISOTime",(t,e)=>{sy.init(t,e),Re.init(t,e)});function $d(t){return py(xy,t)}var by=S("ZodISODuration",(t,e)=>{iy.init(t,e),Re.init(t,e)});function Cd(t){return fy(by,t)}var Sy=(t,e)=>{Qi.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Hu(t,r)},flatten:{value:r=>Uu(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},fU=S("ZodError",Sy),$s=S("ZodError",Sy,{Parent:Error});var ky=Fu($s),Ey=qu($s),wy=Vu($s),Ty=Wu($s);var Oe=S("ZodType",(t,e)=>(fe.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>xt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>ky(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>wy(t,r,n),t.parseAsync=async(r,n)=>Ey(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Ty(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(vR(r,n)),t.superRefine=r=>t.check(xR(r)),t.overwrite=r=>t.check(In(r)),t.optional=()=>$e(t),t.nullable=()=>$y(t),t.nullish=()=>$e($y(t)),t.nonoptional=r=>pR(t,r),t.array=()=>se(t),t.or=r=>Se([t,r]),t.and=r=>ya(t,r),t.transform=r=>Id(t,Dy(r)),t.default=r=>uR(t,r),t.prefault=r=>dR(t,r),t.catch=r=>mR(t,r),t.pipe=r=>Id(t,r),t.readonly=()=>yR(t),t.describe=r=>{let n=t.clone();return Zr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Zr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Zr.get(t);let n=t.clone();return Zr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),Cy=S("_ZodString",(t,e)=>{Es.init(t,e),Oe.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(fd(...n)),t.includes=(...n)=>t.check(gd(...n)),t.startsWith=(...n)=>t.check(yd(...n)),t.endsWith=(...n)=>t.check(_d(...n)),t.min=(...n)=>t.check(yo(...n)),t.max=(...n)=>t.check(la(...n)),t.length=(...n)=>t.check(da(...n)),t.nonempty=(...n)=>t.check(yo(1,...n)),t.lowercase=n=>t.check(md(n)),t.uppercase=n=>t.check(hd(n)),t.trim=()=>t.check(xd()),t.normalize=(...n)=>t.check(vd(...n)),t.toLowerCase=()=>t.check(bd()),t.toUpperCase=()=>t.check(Sd())}),O0=S("ZodString",(t,e)=>{Es.init(t,e),Cy.init(t,e),t.email=r=>t.check(Ul(I0,r)),t.url=r=>t.check(Bl(A0,r)),t.jwt=r=>t.check(id(K0,r)),t.emoji=r=>t.check(Vl(N0,r)),t.guid=r=>t.check(ia(Ry,r)),t.uuid=r=>t.check(Hl(ga,r)),t.uuidv4=r=>t.check(Fl(ga,r)),t.uuidv6=r=>t.check(Zl(ga,r)),t.uuidv7=r=>t.check(ql(ga,r)),t.nanoid=r=>t.check(Wl(D0,r)),t.guid=r=>t.check(ia(Ry,r)),t.cuid=r=>t.check(Kl(M0,r)),t.cuid2=r=>t.check(Gl(j0,r)),t.ulid=r=>t.check(Jl(z0,r)),t.base64=r=>t.check(nd(B0,r)),t.base64url=r=>t.check(od(V0,r)),t.xid=r=>t.check(Xl(L0,r)),t.ksuid=r=>t.check(Yl(U0,r)),t.ipv4=r=>t.check(Ql(H0,r)),t.ipv6=r=>t.check(ed(F0,r)),t.cidrv4=r=>t.check(td(Z0,r)),t.cidrv6=r=>t.check(rd(q0,r)),t.e164=r=>t.check(sd(W0,r)),t.datetime=r=>t.check(Rd(r)),t.date=r=>t.check(Pd(r)),t.time=r=>t.check($d(r)),t.duration=r=>t.check(Cd(r))});function x(t){return Ll(O0,t)}var Re=S("ZodStringFormat",(t,e)=>{_e.init(t,e),Cy.init(t,e)}),I0=S("ZodEmail",(t,e)=>{tl.init(t,e),Re.init(t,e)});var Ry=S("ZodGUID",(t,e)=>{Qu.init(t,e),Re.init(t,e)});var ga=S("ZodUUID",(t,e)=>{el.init(t,e),Re.init(t,e)});var A0=S("ZodURL",(t,e)=>{rl.init(t,e),Re.init(t,e)});var N0=S("ZodEmoji",(t,e)=>{nl.init(t,e),Re.init(t,e)});var D0=S("ZodNanoID",(t,e)=>{ol.init(t,e),Re.init(t,e)});var M0=S("ZodCUID",(t,e)=>{sl.init(t,e),Re.init(t,e)});var j0=S("ZodCUID2",(t,e)=>{il.init(t,e),Re.init(t,e)});var z0=S("ZodULID",(t,e)=>{al.init(t,e),Re.init(t,e)});var L0=S("ZodXID",(t,e)=>{cl.init(t,e),Re.init(t,e)});var U0=S("ZodKSUID",(t,e)=>{ul.init(t,e),Re.init(t,e)});var H0=S("ZodIPv4",(t,e)=>{ll.init(t,e),Re.init(t,e)});var F0=S("ZodIPv6",(t,e)=>{dl.init(t,e),Re.init(t,e)});var Z0=S("ZodCIDRv4",(t,e)=>{pl.init(t,e),Re.init(t,e)});var q0=S("ZodCIDRv6",(t,e)=>{fl.init(t,e),Re.init(t,e)});var B0=S("ZodBase64",(t,e)=>{ml.init(t,e),Re.init(t,e)});var V0=S("ZodBase64URL",(t,e)=>{hl.init(t,e),Re.init(t,e)});var W0=S("ZodE164",(t,e)=>{gl.init(t,e),Re.init(t,e)});var K0=S("ZodJWT",(t,e)=>{yl.init(t,e),Re.init(t,e)});var Oy=S("ZodNumber",(t,e)=>{na.init(t,e),Oe.init(t,e),t.gt=(n,o)=>t.check(ca(n,o)),t.gte=(n,o)=>t.check(Rs(n,o)),t.min=(n,o)=>t.check(Rs(n,o)),t.lt=(n,o)=>t.check(aa(n,o)),t.lte=(n,o)=>t.check(Ts(n,o)),t.max=(n,o)=>t.check(Ts(n,o)),t.int=n=>t.check(Py(n)),t.safe=n=>t.check(Py(n)),t.positive=n=>t.check(ca(0,n)),t.nonnegative=n=>t.check(Rs(0,n)),t.negative=n=>t.check(aa(0,n)),t.nonpositive=n=>t.check(Ts(0,n)),t.multipleOf=(n,o)=>t.check(ua(n,o)),t.step=(n,o)=>t.check(ua(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});function pe(t){return ad(Oy,t)}var G0=S("ZodNumberFormat",(t,e)=>{_l.init(t,e),Oy.init(t,e)});function Py(t){return cd(G0,t)}var J0=S("ZodBoolean",(t,e)=>{vl.init(t,e),Oe.init(t,e)});function Ze(t){return ud(J0,t)}var X0=S("ZodNull",(t,e)=>{xl.init(t,e),Oe.init(t,e)});function Iy(t){return ld(X0,t)}var Y0=S("ZodUnknown",(t,e)=>{bl.init(t,e),Oe.init(t,e)});function Pe(){return dd(Y0)}var Q0=S("ZodNever",(t,e)=>{Sl.init(t,e),Oe.init(t,e)});function eR(t){return pd(Q0,t)}var tR=S("ZodArray",(t,e)=>{kl.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(yo(r,n)),t.nonempty=r=>t.check(yo(1,r)),t.max=(r,n)=>t.check(la(r,n)),t.length=(r,n)=>t.check(da(r,n)),t.unwrap=()=>t.element});function se(t,e){return my(tR,t,e)}var Ay=S("ZodObject",(t,e)=>{oa.init(t,e),Oe.init(t,e),oe.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>ft(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:eR()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>oe.extend(t,r),t.merge=r=>oe.merge(t,r),t.pick=r=>oe.pick(t,r),t.omit=r=>oe.omit(t,r),t.partial=(...r)=>oe.partial(My,t,r[0]),t.required=(...r)=>oe.required(jy,t,r[0])});function A(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new Ay(r)}function ot(t,e){return new Ay({type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},catchall:Pe(),...oe.normalizeParams(e)})}var Ny=S("ZodUnion",(t,e)=>{sa.init(t,e),Oe.init(t,e),t.options=e.options});function Se(t,e){return new Ny({type:"union",options:t,...oe.normalizeParams(e)})}var rR=S("ZodDiscriminatedUnion",(t,e)=>{Ny.init(t,e),El.init(t,e)});function Ad(t,e,r){return new rR({type:"union",options:e,discriminator:t,...oe.normalizeParams(r)})}var nR=S("ZodIntersection",(t,e)=>{wl.init(t,e),Oe.init(t,e)});function ya(t,e){return new nR({type:"intersection",left:t,right:e})}var oR=S("ZodRecord",(t,e)=>{Tl.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ve(t,e,r){return new oR({type:"record",keyType:t,valueType:e,...oe.normalizeParams(r)})}var Od=S("ZodEnum",(t,e)=>{Rl.init(t,e),Oe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Od({...e,checks:[],...oe.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Od({...e,checks:[],...oe.normalizeParams(o),entries:s})}});function ft(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Od({type:"enum",entries:r,...oe.normalizeParams(e)})}var sR=S("ZodLiteral",(t,e)=>{Pl.init(t,e),Oe.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function U(t,e){return new sR({type:"literal",values:Array.isArray(t)?t:[t],...oe.normalizeParams(e)})}var iR=S("ZodTransform",(t,e)=>{$l.init(t,e),Oe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(oe.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(oe.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});function Dy(t){return new iR({type:"transform",transform:t})}var My=S("ZodOptional",(t,e)=>{Cl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $e(t){return new My({type:"optional",innerType:t})}var aR=S("ZodNullable",(t,e)=>{Ol.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function $y(t){return new aR({type:"nullable",innerType:t})}var cR=S("ZodDefault",(t,e)=>{Il.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function uR(t,e){return new cR({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var lR=S("ZodPrefault",(t,e)=>{Al.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function dR(t,e){return new lR({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var jy=S("ZodNonOptional",(t,e)=>{Nl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function pR(t,e){return new jy({type:"nonoptional",innerType:t,...oe.normalizeParams(e)})}var fR=S("ZodCatch",(t,e)=>{Dl.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function mR(t,e){return new fR({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var hR=S("ZodPipe",(t,e)=>{Ml.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function Id(t,e){return new hR({type:"pipe",in:t,out:e})}var gR=S("ZodReadonly",(t,e)=>{jl.init(t,e),Oe.init(t,e)});function yR(t){return new gR({type:"readonly",innerType:t})}var zy=S("ZodCustom",(t,e)=>{zl.init(t,e),Oe.init(t,e)});function _R(t){let e=new Ve({check:"custom"});return e._zod.check=t,e}function Ly(t,e){return kd(zy,t??(()=>!0),e)}function vR(t,e={}){return Ed(zy,t,e)}function xR(t){let e=_R(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(oe.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(oe.issue(o))}},t(r.value,r)));return e}function Nd(t,e){return Id(Dy(t),e)}vt(cy());var Md="2025-11-25";var Uy=[Md,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Vr="io.modelcontextprotocol/related-task",va="2.0",Ue=Ly(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Hy=Se([x(),pe().int()]),Fy=x(),RU=ot({ttl:pe().optional(),pollInterval:pe().optional()}),bR=A({ttl:pe().optional()}),SR=A({taskId:x()}),jd=ot({progressToken:Hy.optional(),[Vr]:SR.optional()}),bt=A({_meta:jd.optional()}),Cs=bt.extend({task:bR.optional()}),Zy=t=>Cs.safeParse(t).success,We=A({method:x(),params:bt.loose().optional()}),$t=A({_meta:jd.optional()}),Ct=A({method:x(),params:$t.loose().optional()}),Ke=ot({_meta:jd.optional()}),xa=Se([x(),pe().int()]),qy=A({jsonrpc:U(va),id:xa,...We.shape}).strict(),zd=t=>qy.safeParse(t).success,By=A({jsonrpc:U(va),...Ct.shape}).strict(),Vy=t=>By.safeParse(t).success,Ld=A({jsonrpc:U(va),id:xa,result:Ke}).strict(),Os=t=>Ld.safeParse(t).success;var Z;(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"})(Z||(Z={}));var Ud=A({jsonrpc:U(va),id:xa.optional(),error:A({code:pe().int(),message:x(),data:Pe().optional()})}).strict();var Wy=t=>Ud.safeParse(t).success;var Ky=Se([qy,By,Ld,Ud]),PU=Se([Ld,Ud]),ba=Ke.strict(),kR=$t.extend({requestId:xa.optional(),reason:x().optional()}),Sa=Ct.extend({method:U("notifications/cancelled"),params:kR}),ER=A({src:x(),mimeType:x().optional(),sizes:se(x()).optional(),theme:ft(["light","dark"]).optional()}),Is=A({icons:se(ER).optional()}),vo=A({name:x(),title:x().optional()}),Gy=vo.extend({...vo.shape,...Is.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),wR=ya(A({applyDefaults:Ze().optional()}),ve(x(),Pe())),TR=Nd(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ya(A({form:wR.optional(),url:Ue.optional()}),ve(x(),Pe()).optional())),RR=ot({list:Ue.optional(),cancel:Ue.optional(),requests:ot({sampling:ot({createMessage:Ue.optional()}).optional(),elicitation:ot({create:Ue.optional()}).optional()}).optional()}),PR=ot({list:Ue.optional(),cancel:Ue.optional(),requests:ot({tools:ot({call:Ue.optional()}).optional()}).optional()}),$R=A({experimental:ve(x(),Ue).optional(),sampling:A({context:Ue.optional(),tools:Ue.optional()}).optional(),elicitation:TR.optional(),roots:A({listChanged:Ze().optional()}).optional(),tasks:RR.optional(),extensions:ve(x(),Ue).optional()}),CR=bt.extend({protocolVersion:x(),capabilities:$R,clientInfo:Gy}),Hd=We.extend({method:U("initialize"),params:CR});var OR=A({experimental:ve(x(),Ue).optional(),logging:Ue.optional(),completions:Ue.optional(),prompts:A({listChanged:Ze().optional()}).optional(),resources:A({subscribe:Ze().optional(),listChanged:Ze().optional()}).optional(),tools:A({listChanged:Ze().optional()}).optional(),tasks:PR.optional(),extensions:ve(x(),Ue).optional()}),IR=Ke.extend({protocolVersion:x(),capabilities:OR,serverInfo:Gy,instructions:x().optional()}),Fd=Ct.extend({method:U("notifications/initialized"),params:$t.optional()});var ka=We.extend({method:U("ping"),params:bt.optional()}),AR=A({progress:pe(),total:$e(pe()),message:$e(x())}),NR=A({...$t.shape,...AR.shape,progressToken:Hy}),Ea=Ct.extend({method:U("notifications/progress"),params:NR}),DR=bt.extend({cursor:Fy.optional()}),As=We.extend({params:DR.optional()}),Ns=Ke.extend({nextCursor:Fy.optional()}),MR=ft(["working","input_required","completed","failed","cancelled"]),Ds=A({taskId:x(),status:MR,ttl:Se([pe(),Iy()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:$e(pe()),statusMessage:$e(x())}),xo=Ke.extend({task:Ds}),jR=$t.merge(Ds),Ms=Ct.extend({method:U("notifications/tasks/status"),params:jR}),wa=We.extend({method:U("tasks/get"),params:bt.extend({taskId:x()})}),Ta=Ke.merge(Ds),Ra=We.extend({method:U("tasks/result"),params:bt.extend({taskId:x()})}),$U=Ke.loose(),Pa=As.extend({method:U("tasks/list")}),$a=Ns.extend({tasks:se(Ds)}),Ca=We.extend({method:U("tasks/cancel"),params:bt.extend({taskId:x()})}),Jy=Ke.merge(Ds),Xy=A({uri:x(),mimeType:$e(x()),_meta:ve(x(),Pe()).optional()}),Yy=Xy.extend({text:x()}),Zd=x().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Qy=Xy.extend({blob:Zd}),js=ft(["user","assistant"]),bo=A({audience:se(js).optional(),priority:pe().min(0).max(1).optional(),lastModified:Ps.datetime({offset:!0}).optional()}),e_=A({...vo.shape,...Is.shape,uri:x(),description:$e(x()),mimeType:$e(x()),size:$e(pe()),annotations:bo.optional(),_meta:$e(ot({}))}),zR=A({...vo.shape,...Is.shape,uriTemplate:x(),description:$e(x()),mimeType:$e(x()),annotations:bo.optional(),_meta:$e(ot({}))}),So=As.extend({method:U("resources/list")}),LR=Ns.extend({resources:se(e_)}),ko=As.extend({method:U("resources/templates/list")}),UR=Ns.extend({resourceTemplates:se(zR)}),qd=bt.extend({uri:x()}),HR=qd,Oa=We.extend({method:U("resources/read"),params:HR}),FR=Ke.extend({contents:se(Se([Yy,Qy]))}),ZR=Ct.extend({method:U("notifications/resources/list_changed"),params:$t.optional()}),qR=qd,BR=We.extend({method:U("resources/subscribe"),params:qR}),VR=qd,WR=We.extend({method:U("resources/unsubscribe"),params:VR}),KR=$t.extend({uri:x()}),GR=Ct.extend({method:U("notifications/resources/updated"),params:KR}),JR=A({name:x(),description:$e(x()),required:$e(Ze())}),XR=A({...vo.shape,...Is.shape,description:$e(x()),arguments:$e(se(JR)),_meta:$e(ot({}))}),Eo=As.extend({method:U("prompts/list")}),YR=Ns.extend({prompts:se(XR)}),QR=bt.extend({name:x(),arguments:ve(x(),x()).optional()}),Ia=We.extend({method:U("prompts/get"),params:QR}),Bd=A({type:U("text"),text:x(),annotations:bo.optional(),_meta:ve(x(),Pe()).optional()}),Vd=A({type:U("image"),data:Zd,mimeType:x(),annotations:bo.optional(),_meta:ve(x(),Pe()).optional()}),Wd=A({type:U("audio"),data:Zd,mimeType:x(),annotations:bo.optional(),_meta:ve(x(),Pe()).optional()}),eP=A({type:U("tool_use"),name:x(),id:x(),input:ve(x(),Pe()),_meta:ve(x(),Pe()).optional()}),tP=A({type:U("resource"),resource:Se([Yy,Qy]),annotations:bo.optional(),_meta:ve(x(),Pe()).optional()}),rP=e_.extend({type:U("resource_link")}),Kd=Se([Bd,Vd,Wd,rP,tP]),nP=A({role:js,content:Kd}),oP=Ke.extend({description:x().optional(),messages:se(nP)}),sP=Ct.extend({method:U("notifications/prompts/list_changed"),params:$t.optional()}),iP=A({title:x().optional(),readOnlyHint:Ze().optional(),destructiveHint:Ze().optional(),idempotentHint:Ze().optional(),openWorldHint:Ze().optional()}),aP=A({taskSupport:ft(["required","optional","forbidden"]).optional()}),t_=A({...vo.shape,...Is.shape,description:x().optional(),inputSchema:A({type:U("object"),properties:ve(x(),Ue).optional(),required:se(x()).optional()}).catchall(Pe()),outputSchema:A({type:U("object"),properties:ve(x(),Ue).optional(),required:se(x()).optional()}).catchall(Pe()).optional(),annotations:iP.optional(),execution:aP.optional(),_meta:ve(x(),Pe()).optional()}),wo=As.extend({method:U("tools/list")}),cP=Ns.extend({tools:se(t_)}),Aa=Ke.extend({content:se(Kd).default([]),structuredContent:ve(x(),Pe()).optional(),isError:Ze().optional()}),CU=Aa.or(Ke.extend({toolResult:Pe()})),uP=Cs.extend({name:x(),arguments:ve(x(),Pe()).optional()}),To=We.extend({method:U("tools/call"),params:uP}),lP=Ct.extend({method:U("notifications/tools/list_changed"),params:$t.optional()}),OU=A({autoRefresh:Ze().default(!0),debounceMs:pe().int().nonnegative().default(300)}),zs=ft(["debug","info","notice","warning","error","critical","alert","emergency"]),dP=bt.extend({level:zs}),Gd=We.extend({method:U("logging/setLevel"),params:dP}),pP=$t.extend({level:zs,logger:x().optional(),data:Pe()}),fP=Ct.extend({method:U("notifications/message"),params:pP}),mP=A({name:x().optional()}),hP=A({hints:se(mP).optional(),costPriority:pe().min(0).max(1).optional(),speedPriority:pe().min(0).max(1).optional(),intelligencePriority:pe().min(0).max(1).optional()}),gP=A({mode:ft(["auto","required","none"]).optional()}),yP=A({type:U("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:se(Kd).default([]),structuredContent:A({}).loose().optional(),isError:Ze().optional(),_meta:ve(x(),Pe()).optional()}),_P=Ad("type",[Bd,Vd,Wd]),_a=Ad("type",[Bd,Vd,Wd,eP,yP]),vP=A({role:js,content:Se([_a,se(_a)]),_meta:ve(x(),Pe()).optional()}),xP=Cs.extend({messages:se(vP),modelPreferences:hP.optional(),systemPrompt:x().optional(),includeContext:ft(["none","thisServer","allServers"]).optional(),temperature:pe().optional(),maxTokens:pe().int(),stopSequences:se(x()).optional(),metadata:Ue.optional(),tools:se(t_).optional(),toolChoice:gP.optional()}),bP=We.extend({method:U("sampling/createMessage"),params:xP}),Ls=Ke.extend({model:x(),stopReason:$e(ft(["endTurn","stopSequence","maxTokens"]).or(x())),role:js,content:_P}),Jd=Ke.extend({model:x(),stopReason:$e(ft(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:js,content:Se([_a,se(_a)])}),SP=A({type:U("boolean"),title:x().optional(),description:x().optional(),default:Ze().optional()}),kP=A({type:U("string"),title:x().optional(),description:x().optional(),minLength:pe().optional(),maxLength:pe().optional(),format:ft(["email","uri","date","date-time"]).optional(),default:x().optional()}),EP=A({type:ft(["number","integer"]),title:x().optional(),description:x().optional(),minimum:pe().optional(),maximum:pe().optional(),default:pe().optional()}),wP=A({type:U("string"),title:x().optional(),description:x().optional(),enum:se(x()),default:x().optional()}),TP=A({type:U("string"),title:x().optional(),description:x().optional(),oneOf:se(A({const:x(),title:x()})),default:x().optional()}),RP=A({type:U("string"),title:x().optional(),description:x().optional(),enum:se(x()),enumNames:se(x()).optional(),default:x().optional()}),PP=Se([wP,TP]),$P=A({type:U("array"),title:x().optional(),description:x().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:A({type:U("string"),enum:se(x())}),default:se(x()).optional()}),CP=A({type:U("array"),title:x().optional(),description:x().optional(),minItems:pe().optional(),maxItems:pe().optional(),items:A({anyOf:se(A({const:x(),title:x()}))}),default:se(x()).optional()}),OP=Se([$P,CP]),IP=Se([RP,PP,OP]),AP=Se([IP,SP,kP,EP]),NP=Cs.extend({mode:U("form").optional(),message:x(),requestedSchema:A({type:U("object"),properties:ve(x(),AP),required:se(x()).optional()})}),DP=Cs.extend({mode:U("url"),message:x(),elicitationId:x(),url:x().url()}),MP=Se([NP,DP]),jP=We.extend({method:U("elicitation/create"),params:MP}),zP=$t.extend({elicitationId:x()}),LP=Ct.extend({method:U("notifications/elicitation/complete"),params:zP}),Ro=Ke.extend({action:ft(["accept","decline","cancel"]),content:Nd(t=>t===null?void 0:t,ve(x(),Se([x(),pe(),Ze(),se(x())])).optional())}),UP=A({type:U("ref/resource"),uri:x()});var HP=A({type:U("ref/prompt"),name:x()}),FP=bt.extend({ref:Se([HP,UP]),argument:A({name:x(),value:x()}),context:A({arguments:ve(x(),x()).optional()}).optional()}),Na=We.extend({method:U("completion/complete"),params:FP});function r_(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function n_(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var ZP=Ke.extend({completion:ot({values:se(x()).max(100),total:$e(pe().int()),hasMore:$e(Ze())})}),qP=A({uri:x().startsWith("file://"),name:x().optional(),_meta:ve(x(),Pe()).optional()}),BP=We.extend({method:U("roots/list"),params:bt.optional()}),Xd=Ke.extend({roots:se(qP)}),VP=Ct.extend({method:U("notifications/roots/list_changed"),params:$t.optional()}),IU=Se([ka,Hd,Na,Gd,Ia,Eo,So,ko,Oa,BR,WR,To,wo,wa,Ra,Pa,Ca]),AU=Se([Sa,Ea,Fd,VP,Ms]),NU=Se([ba,Ls,Jd,Ro,Xd,Ta,$a,xo]),DU=Se([ka,bP,jP,BP,wa,Ra,Pa,Ca]),MU=Se([Sa,Ea,fP,GR,ZR,lP,sP,Ms,LP]),jU=Se([ba,IR,ZP,oP,YR,LR,UR,FR,Aa,cP,Ta,$a,xo]),z=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===Z.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Dd(o.elicitations,r)}return new t(e,r,n)}},Dd=class extends z{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function Wr(t){return t==="completed"||t==="failed"||t==="cancelled"}var s_=Symbol("Let zodToJsonSchema decide on which parser to use");var o_={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},i_=t=>typeof t=="string"?{...o_,name:t}:{...o_,...t};var a_=t=>{let e=i_(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}};function Yd(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ie(t,e,r,n,o){t[e]=r,Yd(t,e,n,o)}var Da=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")};function Ce(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Da(e,t.currentPath):e.join("/")}}function c_(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(r.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(r,"minItems",t.exactLength.value,t.exactLength.message,e),ie(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}function u_(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function l_(){return{type:"boolean"}}function Ma(t,e){return K(t.type._def,e)}var d_=(t,e)=>K(t.innerType._def,e);function Qd(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Qd(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return WP(t,e)}}var WP=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":ie(r,"minimum",n.value,n.message,e);break;case"max":ie(r,"maximum",n.value,n.message,e);break}return r};function p_(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function f_(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):Ce(e)}function m_(t){return{type:"string",enum:Array.from(t.values)}}var KP=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function h_(t,e){let r=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(KP(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}function g_(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var ep,Vt={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ep===void 0&&(ep=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ep),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function ja(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Wt(r,"email",n.message,e);break;case"format:idn-email":Wt(r,"idn-email",n.message,e);break;case"pattern:zod":st(r,Vt.email,n.message,e);break}break;case"url":Wt(r,"uri",n.message,e);break;case"uuid":Wt(r,"uuid",n.message,e);break;case"regex":st(r,n.regex,n.message,e);break;case"cuid":st(r,Vt.cuid,n.message,e);break;case"cuid2":st(r,Vt.cuid2,n.message,e);break;case"startsWith":st(r,RegExp(`^${tp(n.value,e)}`),n.message,e);break;case"endsWith":st(r,RegExp(`${tp(n.value,e)}$`),n.message,e);break;case"datetime":Wt(r,"date-time",n.message,e);break;case"date":Wt(r,"date",n.message,e);break;case"time":Wt(r,"time",n.message,e);break;case"duration":Wt(r,"duration",n.message,e);break;case"length":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{st(r,RegExp(tp(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Wt(r,"ipv4",n.message,e),n.version!=="v4"&&Wt(r,"ipv6",n.message,e);break}case"base64url":st(r,Vt.base64url,n.message,e);break;case"jwt":st(r,Vt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&st(r,Vt.ipv4Cidr,n.message,e),n.version!=="v4"&&st(r,Vt.ipv6Cidr,n.message,e);break}case"emoji":st(r,Vt.emoji(),n.message,e);break;case"ulid":{st(r,Vt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Wt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ie(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{st(r,Vt.base64,n.message,e);break}}break}case"nanoid":st(r,Vt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function tp(t,e){return e.patternStrategy==="escape"?JP(t):t}var GP=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function JP(t){let e="";for(let r=0;r<t.length;r++)GP.has(t[r])||(e+="\\"),e+=t[r];return e}function Wt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ie(t,"format",e,r,n)}function st(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:y_(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ie(t,"pattern",y_(e,n),r,n)}function y_(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
187
187
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
188
188
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
189
189
  `:`[${n[c]}\r
190
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function Ma(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===w.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Da(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Na(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function __(t,e){if(e.mapStrategy==="record")return Ma(t,e);let r=W(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),n=W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function v_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function b_(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function x_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function k_(t,e){if(e.target==="openApi3")return S_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in zs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=zs[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return S_(t,e)}var S_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>W(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function E_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:zs[t.innerType._def.typeName],nullable:!0}:{type:[zs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=W(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function w_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Gd(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function T_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=q0(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=W(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=Z0(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Z0(t,e){if(t.catchall._def.typeName!=="ZodNever")return W(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function q0(t){try{return t.isOptional()}catch{return!0}}var P_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return W(t.innerType._def,e);let r=W(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:$e(e)},r]}:$e(e)};var R_=(t,e)=>{if(e.pipeStrategy==="input")return W(t.in._def,e);if(e.pipeStrategy==="output")return W(t.out._def,e);let r=W(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=W(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function $_(t,e){return W(t.type._def,e)}function C_(t,e){let n={type:"array",uniqueItems:!0,items:W(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function O_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>W(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:W(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>W(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function I_(t){return{not:$e(t)}}function A_(t){return $e(t)}var N_=(t,e)=>W(t.innerType._def,e);var D_=(t,e,r)=>{switch(e){case w.ZodString:return Da(t,r);case w.ZodNumber:return w_(t,r);case w.ZodObject:return T_(t,r);case w.ZodBigInt:return u_(t,r);case w.ZodBoolean:return l_();case w.ZodDate:return Jd(t,r);case w.ZodUndefined:return I_(r);case w.ZodNull:return x_(r);case w.ZodArray:return c_(t,r);case w.ZodUnion:case w.ZodDiscriminatedUnion:return k_(t,r);case w.ZodIntersection:return h_(t,r);case w.ZodTuple:return O_(t,r);case w.ZodRecord:return Ma(t,r);case w.ZodLiteral:return g_(t,r);case w.ZodEnum:return m_(t);case w.ZodNativeEnum:return v_(t);case w.ZodNullable:return E_(t,r);case w.ZodOptional:return P_(t,r);case w.ZodMap:return __(t,r);case w.ZodSet:return C_(t,r);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return $_(t,r);case w.ZodNaN:case w.ZodNever:return b_(r);case w.ZodEffects:return f_(t,r);case w.ZodAny:return $e(r);case w.ZodUnknown:return A_(r);case w.ZodDefault:return p_(t,r);case w.ZodBranded:return Na(t,r);case w.ZodReadonly:return N_(t,r);case w.ZodCatch:return d_(t,r);case w.ZodPipeline:return R_(t,r);case w.ZodFunction:case w.ZodVoid:case w.ZodSymbol:return;default:return(n=>{})(e)}};function W(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==s_)return a}if(n&&!r){let a=B0(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=D_(t,t.typeName,e),i=typeof s=="function"?W(s(),e):s;if(i&&V0(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var B0=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Aa(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},V0=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Qd=(t,e)=>{let r=a_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:W(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??$e(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=W(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??$e(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function W0(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ep(t,e){return Rt(t)?Sd(t,{target:W0(e?.target),io:e?.pipeStrategy??"input"}):Qd(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function tp(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function rp(t,e){let r=Zr(t,e);if(!r.success)throw r.error;return r.data}var K0=6e4,ja=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(ba,r=>{this._oncancel(r)}),this.setNotificationHandler(Sa,r=>{this._onprogress(r)}),this.setRequestHandler(xa,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ka,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(wa,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,f=new M(d.error.code,d.error.message,d.error.data);l(f)}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(Z.InvalidParams,`Task not found: ${s}`);if(!Vr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Vr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Br]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ta,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(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ra,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new M(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Vr(o.status))throw new M(Z.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(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof M?o:new M(Z.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(Z.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),$s(s)||Wy(s)?this._onresponse(s):Dd(s)?this._onrequest(s,i):Vy(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(Z.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?.[Br]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.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=Zy(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,f)=>{if(i.signal.aborted)throw new M(Z.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let p=m.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},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:Z.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),$s(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($s(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),$s(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(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,vo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new M(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Vr(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(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new M(Z.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(Z.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=v=>{l(v)};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(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Br]:c}});let p=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let _=v instanceof M?v:new M(Z.RequestTimeout,String(v));l(_)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let _=Zr(r,v.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??K0,g=()=>p(M.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=_=>{let S=this._responseHandlers.get(f);S?S(_):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(f),l(_)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(f),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ea,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},Pa,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Jy,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||{},[Br]: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||{},[Br]: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||{},[Br]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=tp(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=rp(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=tp(e);this._notificationHandlers.set(n,o=>{let s=rp(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"&&Dd(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new M(Z.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(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new M(Z.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(Z.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=Ns.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Vr(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(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Vr(a.status))throw new M(Z.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=Ns.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Vr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function M_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function j_(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];M_(i)&&M_(s)?r[o]={...i,...s}:r[o]=s}return r}var kx=Fh(Ff(),1),Ex=Fh(Sx(),1);function LN(){let t=new kx.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ex.default)(t),t}var vc=class{constructor(e){this._ajv=e??LN()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}};var bc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},js,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},To,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function wx(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 Tx(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}}var xc=class extends ja{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Ms.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new vc,this.setRequestHandler(zd,n=>this._oninitialize(n)),this.setNotificationHandler(Ld,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Vd,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Ms.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new bc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=j_(this._capabilities,e)}setRequestHandler(e,r){let o=qr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Rt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Zr(wo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new M(Z.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let p=Zr(vo,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new M(Z.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=Zr(Oa,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new M(Z.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Tx(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&wx(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Uy.includes(r)?r:Ad,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},va)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Wd,r):this.request({method:"sampling/createMessage",params:e},js,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},To,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},To,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new M(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof M?i:new M(Z.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Kd,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Rx=Symbol.for("mcp.completable");function Jf(t){return!!t&&typeof t=="object"&&Rx in t}function $x(t){return t[Rx]?.complete}var Px;(function(t){t.Completable="McpCompletable"})(Px||(Px={}));var UN=/^[A-Za-z0-9._-]{1,128}$/;function HN(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!UN.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function FN(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Yf(t){let e=HN(t);return FN(t,e.warnings),e.isValid}var Sc=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var kc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new xc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Sc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(Eo)),this.server.assertCanSetRequestHandler(tn(wo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Eo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=yo(r.inputSchema);return o?ep(o,{strictUnions:!0,pipeStrategy:"input"}):ZN})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=yo(r.outputSchema);o&&(n.outputSchema=ep(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(wo,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new M(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new M(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new M(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new M(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof M&&n.code===Z.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=yo(e.inputSchema)??e.inputSchema,i=await da(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=pa(a);throw new M(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new M(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=yo(e.outputSchema),s=await da(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=pa(i);throw new M(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new M(Z.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(tn(Ia)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ia,async e=>{switch(e.params.ref.type){case"ref/prompt":return r_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return n_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new M(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new M(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new M(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return mi;let s=qr(n.argsSchema)?.[e.params.argument.name];if(!Jf(s))return mi;let i=$x(s);if(!i)return mi;let a=await i(e.params.argument.value,e.params.context);return Ox(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return mi;throw new M(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return mi;let s=await o(e.params.argument.value,e.params.context);return Ox(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(xo)),this.server.assertCanSetRequestHandler(tn(So)),this.server.assertCanSetRequestHandler(tn($a)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(xo,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(So,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler($a,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new M(Z.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new M(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(tn(ko)),this.server.assertCanSetRequestHandler(tn(Ca)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(ko,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?qN(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ca,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new M(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new M(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=yo(n.argsSchema),s=await da(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=pa(c);throw new M(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:An(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=An(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof lt?c._def?.innerType:c;return Jf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Yf(e);let l={title:r,description:n,inputSchema:Cx(o),outputSchema:Cx(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Yf(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=An(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=An(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Xf(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Xf(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var ZN={type:"object",properties:{}};function Ix(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Ax(t){return"_def"in t||"_zod"in t||Ix(t)}function Xf(t){return typeof t!="object"||t===null||Ax(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ix)}function Cx(t){if(t){if(Xf(t))return An(t);if(!Ax(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function qN(t){let e=qr(t);return e?Object.entries(e).map(([r,n])=>{let o=gy(n),s=yy(n);return{name:r,description:o,required:!s}}):[]}function tn(t){let r=qr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=fa(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ox(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var mi={completion:{values:[],hasMore:!1}};import Dx from"node:process";var Ec=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
191
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),BN(r)}clear(){this._buffer=void 0}};function BN(t){return Ky.parse(JSON.parse(t))}function Nx(t){return JSON.stringify(t)+`
192
- `}var wc=class{constructor(e=Dx.stdin,r=Dx.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ec,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Nx(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{createRequire as $E}from"node:module";import{existsSync as we,unlinkSync as cs,readdirSync as rz,readFileSync as hu,writeFileSync as Ih,renameSync as nz,rmSync as uu,mkdirSync as CE,cpSync as oz,statSync as yE,symlinkSync as sz,lstatSync as iz}from"node:fs";import{execSync as _E,spawnSync as OE}from"node:child_process";import{join as Ce,dirname as nr,resolve as je,sep as az,isAbsolute as cz}from"node:path";import{fileURLToPath as uz}from"node:url";import{homedir as zi,tmpdir as Ah,cpus as lz}from"node:os";import{request as dz}from"node:https";import{AsyncLocalStorage as pz}from"node:async_hooks";import{spawn as Zx,execSync as JN,execFileSync as Wx}from"node:child_process";import{mkdtempSync as YN,writeFileSync as qx,rmSync as Bx,existsSync as Vx}from"node:fs";import{join as $c,resolve as Kx}from"node:path";import{tmpdir as XN}from"node:os";import{execFileSync as jx,execSync as hi}from"node:child_process";import{existsSync as Tc}from"node:fs";var VN=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Mx=/^bun(\.exe)?$/i;function em(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function WN(t){return VN.test(em(t))}var gi=process.platform==="win32";function Ke(t){try{let e=gi?`where ${t}`:`command -v ${t}`;return hi(e,{stdio:"pipe"}),!0}catch{return!1}}function Qf(t){if(gi)try{let r=hi(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ke(t))return!1;try{return gi?hi(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):jx(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function zx(){if(Ke("bun"))return!0;for(let t of Lx())if(Tc(t))return!0;return!1}function KN(){for(let e of Lx())if(Tc(e))return e;if(Ke("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return gi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Lx(){let t=process.env.HOME??process.env.USERPROFILE??"";if(gi){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function GN(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(Tc(e))return e;try{let r=hi("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Dt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return hi(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return jx(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Pc(){let e=zx()?KN():null,r=process.env.SHELL,n=r&&Tc(r)&&WN(r)?r:null,o=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(Ke("tsx")?"tsx":Ke("ts-node")?"ts-node":null),python:Qf("python3")?"python3":Qf("python")?"python":Qf("py")?"py":null,shell:n??(o?GN()??(Ke("sh")?"sh":Ke("powershell")?"powershell":"cmd.exe"):Ke("bash")?"bash":"sh"),ruby:Ke("ruby")?"ruby":null,go:Ke("go")?"go":null,rust:Ke("rustc")?"rustc":null,php:Ke("php")?"php":null,perl:Ke("perl")?"perl":null,r:Ke("Rscript")?"Rscript":Ke("r")?"r":null,elixir:Ke("elixir")?"elixir":null,csharp:Ke("dotnet-script")?"dotnet-script":null}}function Rc(){return zx()}function Ux(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Dt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Dt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Dt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Dt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Dt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Dt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Dt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Dt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Dt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Dt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Dt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Dt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
193
- `)}function Hx(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function Fx(t,e,r){switch(e){case"javascript":return Mx.test(em(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Mx.test(em(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let s=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${s}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var Mt=process.platform==="win32",QN={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};function eD(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${QN[t]}`}function tD(t){return{windowsHide:t==="win32"}}function rD(t){return`'${t.replace(/'/g,"'\\''")}'`}function nD(t,e,r){return r==="win32"||!e?t:`export PATH=${rD(e)}
194
- ${t}`}var oD=(()=>{if(Mt)return process.env.TEMP??process.env.TMP??XN();try{let t=Wx(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:Kx(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function tm(t){if(Mt&&t.pid)try{JN(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var yi=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??Pc()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(Mt?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1}=e,i=YN($c(oD,".ctx-mode-"));try{let a=this.#a(i,n,r),c=Fx(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,o);let u=r==="shell"?this.#o:i,l=await this.#i(c,u,i,o,s);if(!l.backgrounded)try{Bx(i,{recursive:!0,force:!0})}catch{}return l}catch(a){try{Bx(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=Kx(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
190
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}function za(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ce(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=ja(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Ma(t.keyType._def,e);return{...r,propertyNames:o}}}return r}function __(t,e){if(e.mapStrategy==="record")return za(t,e);let r=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ce(e),n=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ce(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}function v_(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}function x_(t){return t.target==="openAi"?void 0:{not:Ce({...t,currentPath:[...t.currentPath,"not"]})}}function b_(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Us={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function k_(t,e){if(e.target==="openApi3")return S_(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Us&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Us[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return S_(t,e)}var S_=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>K(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0};function E_(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Us[t.innerType._def.typeName],nullable:!0}:{type:[Us[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function w_(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Yd(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}function T_(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=YP(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=K(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=XP(t,e);return i!==void 0&&(n.additionalProperties=i),n}function XP(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function YP(t){try{return t.isOptional()}catch{return!0}}var R_=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ce(e)},r]}:Ce(e)};var P_=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let r=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}};function $_(t,e){return K(t.type._def,e)}function C_(t,e){let n={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function O_(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}function I_(t){return{not:Ce(t)}}function A_(t){return Ce(t)}var N_=(t,e)=>K(t.innerType._def,e);var D_=(t,e,r)=>{switch(e){case T.ZodString:return ja(t,r);case T.ZodNumber:return w_(t,r);case T.ZodObject:return T_(t,r);case T.ZodBigInt:return u_(t,r);case T.ZodBoolean:return l_();case T.ZodDate:return Qd(t,r);case T.ZodUndefined:return I_(r);case T.ZodNull:return b_(r);case T.ZodArray:return c_(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return k_(t,r);case T.ZodIntersection:return h_(t,r);case T.ZodTuple:return O_(t,r);case T.ZodRecord:return za(t,r);case T.ZodLiteral:return g_(t,r);case T.ZodEnum:return m_(t);case T.ZodNativeEnum:return v_(t);case T.ZodNullable:return E_(t,r);case T.ZodOptional:return R_(t,r);case T.ZodMap:return __(t,r);case T.ZodSet:return C_(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return $_(t,r);case T.ZodNaN:case T.ZodNever:return x_(r);case T.ZodEffects:return f_(t,r);case T.ZodAny:return Ce(r);case T.ZodUnknown:return A_(r);case T.ZodDefault:return p_(t,r);case T.ZodBranded:return Ma(t,r);case T.ZodReadonly:return N_(t,r);case T.ZodCatch:return d_(t,r);case T.ZodPipeline:return P_(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(e)}};function K(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==s_)return a}if(n&&!r){let a=QP(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=D_(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&e$(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var QP=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Da(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ce(e)):e.$refStrategy==="seen"?Ce(e):void 0}},e$=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var rp=(t,e)=>{let r=a_(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:K(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ce(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=K(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ce(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function t$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function np(t,e){return Pt(t)?wd(t,{target:t$(e?.target),io:e?.pipeStrategy??"input"}):rp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function op(t){let r=Br(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ha(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function sp(t,e){let r=qr(t,e);if(!r.success)throw r.error;return r.data}var r$=6e4,La=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(Sa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ea,r=>{this._onprogress(r)}),this.setRequestHandler(ka,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wa,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ra,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,f=new z(d.error.code,d.error.message,d.error.data);l(f)}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 z(Z.InvalidParams,`Task not found: ${s}`);if(!Wr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Wr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Vr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Pa,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 z(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Ca,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new z(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Wr(o.status))throw new z(Z.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 z(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(Z.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),z.fromError(Z.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),Os(s)||Wy(s)?this._onresponse(s):zd(s)?this._onrequest(s,i):Vy(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=z.fromError(Z.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?.[Vr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.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=Zy(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,f)=>{if(i.signal.aborted)throw new z(Z.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let p=m.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},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:Z.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),Os(e))n(e);else{let i=new z(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(Os(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),Os(e))o(e);else{let i=z.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 z?i:new z(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,xo,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Wr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new z(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(Z.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 z?i:new z(Z.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=v=>{l(v)};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(v){d(v);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),m.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(m.params={...m.params,task:a}),c&&(m.params={...m.params,_meta:{...m.params?._meta||{},[Vr]:c}});let p=v=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(v)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let _=v instanceof z?v:new z(Z.RequestTimeout,String(v));l(_)};this._responseHandlers.set(f,v=>{if(!n?.signal?.aborted){if(v instanceof Error)return l(v);try{let _=qr(r,v.result);_.success?u(_.data):l(_.error)}catch(_){l(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??r$,g=()=>p(z.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let v=_=>{let b=this._responseHandlers.get(f);b?b(_):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,v),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(f),l(_)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(v=>{this._cleanupTimeout(f),l(v)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ta,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},$a,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Jy,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||{},[Vr]: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||{},[Vr]: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||{},[Vr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=op(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=sp(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=op(e);this._notificationHandlers.set(n,o=>{let s=sp(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"&&zd(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(Z.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 z(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new z(Z.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 z(Z.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=Ms.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Wr(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 z(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Wr(a.status))throw new z(Z.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=Ms.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Wr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}};function M_(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function j_(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];M_(i)&&M_(s)?r[o]={...i,...s}:r[o]=s}return r}var kb=Fh(Bf(),1),Eb=Fh(Sb(),1);function WN(){let t=new kb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Eb.default)(t),t}var bc=class{constructor(e){this._ajv=e??WN()}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 Sc=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(f=>f.type==="tool_use").map(f=>f.id)),d=new Set(s.filter(f=>f.type==="tool_result").map(f=>f.toolUseId));if(l.size!==d.size||![...l].every(f=>d.has(f)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ls,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},Ro,r)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}};function wb(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 Tb(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}}var kc=class extends La{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(zs.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new bc,this.setRequestHandler(Hd,n=>this._oninitialize(n)),this.setNotificationHandler(Fd,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Gd,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=zs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Sc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=j_(this._capabilities,e)}setRequestHandler(e,r){let o=Br(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Pt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=qr(To,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new z(Z.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(r(c,u));if(d.task){let p=qr(xo,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new z(Z.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=qr(Aa,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new z(Z.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){Tb(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&wb(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Uy.includes(r)?r:Md,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ba)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Jd,r):this.request({method:"sampling/createMessage",params:e},Ls,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},Ro,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},Ro,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new z(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(Z.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Xd,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var Pb=Symbol.for("mcp.completable");function Qf(t){return!!t&&typeof t=="object"&&Pb in t}function $b(t){return t[Pb]?.complete}var Rb;(function(t){t.Completable="McpCompletable"})(Rb||(Rb={}));var KN=/^[A-Za-z0-9._-]{1,128}$/;function GN(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!KN.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function JN(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function em(t){let e=GN(t);return JN(t,e.warnings),e.isValid}var Ec=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}};var wc=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new kc(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ec(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(wo)),this.server.assertCanSetRequestHandler(rn(To)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(wo,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=_o(r.inputSchema);return o?np(o,{strictUnions:!0,pipeStrategy:"input"}):XN})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=_o(r.outputSchema);o&&(n.outputSchema=np(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(To,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new z(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new z(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new z(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof z&&n.code===Z.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=_o(e.inputSchema)??e.inputSchema,i=await fa(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ma(a);throw new z(Z.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new z(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=_o(e.outputSchema),s=await fa(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ma(i);throw new z(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(f=>setTimeout(f,l));let d=await n.taskStore.getTask(c);if(!d)throw new z(Z.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(rn(Na)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Na,async e=>{switch(e.params.ref.type){case"ref/prompt":return r_(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return n_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new z(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new z(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return gi;let s=Br(n.argsSchema)?.[e.params.argument.name];if(!Qf(s))return gi;let i=$b(s);if(!i)return gi;let a=await i(e.params.argument.value,e.params.context);return Ob(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return gi;throw new z(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return gi;let s=await o(e.params.argument.value,e.params.context);return Ob(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(So)),this.server.assertCanSetRequestHandler(rn(ko)),this.server.assertCanSetRequestHandler(rn(Oa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(So,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(ko,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Oa,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new z(Z.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new z(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(rn(Eo)),this.server.assertCanSetRequestHandler(rn(Ia)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Eo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?YN(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ia,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new z(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new z(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=_o(n.argsSchema),s=await fa(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=ma(c);throw new z(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Nn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Nn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof dt?c._def?.innerType:c;return Qf(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){em(e);let l={title:r,description:n,inputSchema:Cb(o),outputSchema:Cb(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&em(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Nn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Nn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(tm(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!tm(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var XN={type:"object",properties:{}};function Ib(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Ab(t){return"_def"in t||"_zod"in t||Ib(t)}function tm(t){return typeof t!="object"||t===null||Ab(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ib)}function Cb(t){if(t){if(tm(t))return Nn(t);if(!Ab(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function YN(t){let e=Br(t);return e?Object.entries(e).map(([r,n])=>{let o=gy(n),s=yy(n);return{name:r,description:o,required:!s}}):[]}function rn(t){let r=Br(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ha(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Ob(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var gi={completion:{values:[],hasMore:!1}};import Db from"node:process";var Tc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
191
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),QN(r)}clear(){this._buffer=void 0}};function QN(t){return Ky.parse(JSON.parse(t))}function Nb(t){return JSON.stringify(t)+`
192
+ `}var Rc=class{constructor(e=Db.stdin,r=Db.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Tc,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=Nb(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}};import{createRequire as jE}from"node:module";import{existsSync as be,unlinkSync as ls,readdirSync as Pz,readFileSync as xu,writeFileSync as Oh,renameSync as $z,rmSync as mu,mkdirSync as zE,cpSync as Cz,statSync as Ph,symlinkSync as Oz,lstatSync as Iz}from"node:fs";import{execSync as TE,spawnSync as LE}from"node:child_process";import{join as Te,dirname as or,resolve as ze,sep as Az,isAbsolute as Nz}from"node:path";import{fileURLToPath as Dz}from"node:url";import{homedir as ds,tmpdir as Ih,cpus as Mz}from"node:os";import{request as jz}from"node:https";import{AsyncLocalStorage as zz}from"node:async_hooks";import{spawn as Zb,execSync as oD,execFileSync as Wb}from"node:child_process";import{mkdtempSync as sD,writeFileSync as qb,rmSync as Bb,existsSync as Vb}from"node:fs";import{join as Oc,resolve as Kb}from"node:path";import{tmpdir as iD}from"node:os";import{execFileSync as jb,execSync as yi}from"node:child_process";import{existsSync as Pc}from"node:fs";var eD=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Mb=/^bun(\.exe)?$/i;function nm(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function tD(t){return eD.test(nm(t))}var _i=process.platform==="win32";function Xe(t){try{let e=_i?`where ${t}`:`command -v ${t}`;return yi(e,{stdio:"pipe"}),!0}catch{return!1}}function rm(t){if(_i)try{let r=yi(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0||r.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Xe(t))return!1;try{return _i?yi(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):jb(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function zb(){if(Xe("bun"))return!0;for(let t of Lb())if(Pc(t))return!0;return!1}function rD(){for(let e of Lb())if(Pc(e))return e;if(Xe("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return _i?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Lb(){let t=process.env.HOME??process.env.USERPROFILE??"";if(_i){let e=process.env.LOCALAPPDATA??"",r=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...r?[`${r}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function nD(){let t=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];for(let e of t)if(Pc(e))return e;try{let r=yi("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Dt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return yi(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return jb(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function $c(){let e=zb()?rD():null,r=process.env.SHELL,n=r&&Pc(r)&&tD(r)?r:null,o=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(Xe("tsx")?"tsx":Xe("ts-node")?"ts-node":null),python:rm("python3")?"python3":rm("python")?"python":rm("py")?"py":null,shell:n??(o?nD()??(Xe("sh")?"sh":Xe("powershell")?"powershell":"cmd.exe"):Xe("bash")?"bash":"sh"),ruby:Xe("ruby")?"ruby":null,go:Xe("go")?"go":null,rust:Xe("rustc")?"rustc":null,php:Xe("php")?"php":null,perl:Xe("perl")?"perl":null,r:Xe("Rscript")?"Rscript":Xe("r")?"r":null,elixir:Xe("elixir")?"elixir":null,csharp:Xe("dotnet-script")?"dotnet-script":null}}function Cc(){return zb()}function Ub(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Dt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Dt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Dt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Dt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Dt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Dt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Dt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Dt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Dt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Dt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Dt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Dt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
193
+ `)}function Hb(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function Fb(t,e,r){switch(e){case"javascript":return Mb.test(nm(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return Mb.test(nm(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let s=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${s}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var Mt=process.platform==="win32",aD={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};function cD(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${aD[t]}`}function uD(t){return{windowsHide:t==="win32"}}function lD(t){return`'${t.replace(/'/g,"'\\''")}'`}function dD(t,e,r){return r==="win32"||!e?t:`export PATH=${lD(e)}
194
+ ${t}`}var pD=(()=>{if(Mt)return process.env.TEMP??process.env.TMP??iD();try{let t=Wb(process.platform==="darwin"?"getconf":"mktemp",process.platform==="darwin"?["DARWIN_USER_TEMP_DIR"]:["-u","-d"],{env:{...process.env,TMPDIR:void 0},encoding:"utf-8"}).trim(),e=process.platform==="darwin"?t:Kb(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function om(t){if(Mt&&t.pid)try{oD(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var vi=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??$c()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(Mt?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1,cwd:i}=e,a=sD(Oc(pD,".ctx-mode-"));try{let c=this.#a(a,n,r),u=Fb(this.#n,r,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=r==="shell"?i??this.#o:a,d=await this.#i(u,l,a,o,s);if(!d.backgrounded)try{Bb(a,{recursive:!0,force:!0})}catch{}return d}catch(c){try{Bb(a,{recursive:!0,force:!0})}catch{}throw c}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=Kb(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
195
195
 
196
196
  import "fmt"
197
197
 
@@ -199,12 +199,12 @@ func main() {
199
199
  ${r}
200
200
  }
201
201
  `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
202
- ${r}`),n==="elixir"&&Vx($c(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify($c(this.#o,"_build/dev/lib"))}, "*/ebin"))
202
+ ${r}`),n==="elixir"&&Vb(Oc(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Oc(this.#o,"_build/dev/lib"))}, "*/ebin"))
203
203
  |> Enum.each(&Code.prepend_path/1)
204
204
 
205
- ${r}`);let o=$c(e,eD(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?qx(o,nD(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):qx(o,r,"utf-8"),o}async#c(e,r,n){let o=Mt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{Wx("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
206
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=Mt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Mt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Mt?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let l={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!Mt,...tD(process.platform)},d;if(a){let _=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");d=Zx(_,[],{...l,shell:!0})}else d=Zx(c,u,{...l,shell:!1});let f=!1,m=!1,p=o===void 0?void 0:setTimeout(()=>{if(f=!0,s){m=!0,d.pid&&this.#s.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let _=Buffer.concat(h).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else tm(d)},o),h=[],g=[],y=0,v=!1;d.stdout.on("data",_=>{y+=_.length,y<=this.#e?h.push(_):v||(v=!0,tm(d))}),d.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):v||(v=!0,tm(d))}),d.on("close",_=>{if(clearTimeout(p),m)return;let S=Buffer.concat(h).toString("utf-8"),T=Buffer.concat(g).toString("utf-8");v&&(T+=`
207
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:T,exitCode:f?1:_??1,timedOut:f})}),d.on("error",_=>{clearTimeout(p),!m&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Mt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Mt?"":"/usr/local/bin:/usr/bin:/bin"),Mt){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=Mt?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(Vx(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
205
+ ${r}`);let o=Oc(e,cD(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?qb(o,dD(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):qb(o,r,"utf-8"),o}async#c(e,r,n){let o=Mt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{Wb("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
206
+ ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=Mt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Mt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Mt?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let l={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!Mt,...uD(process.platform)},d;if(a){let _=[c,...u].map(b=>/\s/.test(b)?JSON.stringify(b):b).join(" ");d=Zb(_,[],{...l,shell:!0})}else d=Zb(c,u,{...l,shell:!1});let f=!1,m=!1,p=o===void 0?void 0:setTimeout(()=>{if(f=!0,s){m=!0,d.pid&&this.#s.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let _=Buffer.concat(h).toString("utf-8"),b=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:b,exitCode:0,timedOut:!0,backgrounded:!0})}else om(d)},o),h=[],g=[],y=0,v=!1;d.stdout.on("data",_=>{y+=_.length,y<=this.#e?h.push(_):v||(v=!0,om(d))}),d.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):v||(v=!0,om(d))}),d.on("close",_=>{if(clearTimeout(p),m)return;let b=Buffer.concat(h).toString("utf-8"),E=Buffer.concat(g).toString("utf-8");v&&(E+=`
207
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:E,exitCode:f?1:_??1,timedOut:f})}),d.on("error",_=>{clearTimeout(p),!m&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Mt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Mt?"":"/usr/local/bin:/usr/bin:/bin"),Mt){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=Mt?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(Vb(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
208
208
  const file_path = FILE_CONTENT_PATH;
209
209
  const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
210
210
  ${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
@@ -262,7 +262,7 @@ file_content = File.read!(file_content_path)
262
262
  ${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
263
263
  var file_path = FILE_CONTENT_PATH;
264
264
  var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
265
- ${n}`}}};import{cpus as sD}from"node:os";async function rm(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,sD().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let m=l++;if(m>=t.length)return;try{let p=await t[m].run();u[m]={status:"fulfilled",value:p}}catch(p){u[m]={status:"rejected",reason:p}}o?.(m,u[m])}}let f=[];for(let m=0;m<a;m++)f.push(d());return await Promise.allSettled(f),{settled:u,effectiveConcurrency:a,capped:c}}Bo();import{readFileSync as Yx,readdirSync as nS,unlinkSync as um,existsSync as cm,statSync as Oc,openSync as Xx,fstatSync as Qx,closeSync as eS}from"node:fs";import{createHash as tS}from"node:crypto";import{tmpdir as oS}from"node:os";import{join as lm}from"node:path";var Vo=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);function sS(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function mD(t,e="AND"){let r=sS(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!Vo.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function hD(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=sS(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!Vo.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function gD(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function yD(t){return t<=4?1:t<=12?2:3}var rS=4096;function dm(){let t=oS(),e=0;try{let r=nS(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=lm(t,n);for(let a of["","-wal","-shm"])try{um(i+a)}catch{}e++}}}catch{}return e}function pm(t,e){let r=0;try{if(!cm(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=nS(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=lm(t,s),c=Oc(i).mtimeMs<n;if(!c){let u=i+"-wal";if(cm(u))try{let l=Oc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{um(i+u)}catch{}r++}}catch{}}catch{}return r}function _D(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function vD(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,f=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(n++,u++)}}return n}function bD(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var Ic=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#f;#m;#h;#g;#y;#_;#v;#b;#x;#S;#k;#E;#w;#T;#P;#R;#$;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=et();this.#t=e??lm(oS(),`context-mode-${process.pid}.db`),bi(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),vi(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(am(s)){im(this.#t),bi(this.#t);try{n=new r(this.#t,{timeout:3e4}),vi(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#F(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{um(this.#t+e)}catch{}}#F(){this.#e.exec(`
265
+ ${n}`}}};import{cpus as fD}from"node:os";async function sm(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,fD().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let m=l++;if(m>=t.length)return;try{let p=await t[m].run();u[m]={status:"fulfilled",value:p}}catch(p){u[m]={status:"rejected",reason:p}}o?.(m,u[m])}}let f=[];for(let m=0;m<a;m++)f.push(d());return await Promise.allSettled(f),{settled:u,effectiveConcurrency:a,capped:c}}Vo();import{readFileSync as rS,readdirSync as cS,unlinkSync as pm,existsSync as dm,statSync as Ac,openSync as nS,fstatSync as oS,closeSync as sS}from"node:fs";import{createHash as iS}from"node:crypto";import{tmpdir as uS}from"node:os";import{join as fm}from"node:path";import{readdirSync as SD,statSync as kD,lstatSync as ED,realpathSync as Xb,existsSync as wD,readFileSync as TD}from"node:fs";import{join as Qb,extname as RD,relative as eS,sep as PD,resolve as $D}from"node:path";var CD=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],OD=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],ID=5,AD=200;function ND(t){let e="";for(let r=0;r<t.length;r++){let n=t[r];n==="*"?t[r+1]==="*"?(e+=".*",r++):e+="[^/]*":n==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(n)?e+="\\"+n:e+=n}return new RegExp(`^${e}$`)}function Yb(t,e){if(e.length===0)return!1;let r=t.split("/").pop()??t;for(let n of e){if(!n.includes("/")&&!n.includes("*")){if(r===n||t.split("/").includes(n))return!0;continue}let o=ND(n);if(o.test(t)||o.test(r))return!0}return!1}function DD(t){let e=Qb(t,".gitignore");if(!wD(e))return[];try{return TD(e,"utf-8").split(/\r?\n/).map(n=>n.trim()).filter(n=>n.length>0&&!n.startsWith("#")&&!n.startsWith("!")).map(n=>n.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function MD(t,e){return eS(t,e).split(PD).join("/")}function tS(t,e={}){let{include:r,exclude:n,maxDepth:o=ID,maxFiles:s=AD,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Xb(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:OD).map(v=>(v.startsWith(".")?v:"."+v).toLowerCase()),d=[...CD,...n??[],...a?DD(u):[]],f=r??[],m=[],p=new Set([u]),h=0,g=!1;function y(v,_){if(g||_>o)return;let b;try{b=SD(v,{withFileTypes:!0})}catch{return}for(let E of b){if(g)return;let R=Qb(v,E.name),N=MD(u,R);if(Yb(N,d))continue;let C=E.isDirectory(),M=E.isFile(),W=!1;try{W=ED(R).isSymbolicLink()}catch{continue}if(W){if(!c)continue;let D;try{D=Xb(R)}catch{continue}let L=eS(u,D);if((L.startsWith("..")||$D(L)===D)&&L.startsWith("..")||p.has(D))continue;p.add(D);try{let qe=kD(D);C=qe.isDirectory(),M=qe.isFile()}catch{continue}}if(C){y(R,_+1);continue}if(!M)continue;let k=RD(R).toLowerCase();if(l.includes(k)&&!(f.length>0&&!Yb(N,f))){if(h++,m.length>=s){g=!0;return}m.push(R)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var Wo=new Set(["the","and","for","are","but","not","you","all","can","had","her","was","one","our","out","has","his","how","its","may","new","now","old","see","way","who","did","get","got","let","say","she","too","use","will","with","this","that","from","they","been","have","many","some","them","than","each","make","like","just","over","such","take","into","year","your","good","could","would","about","which","their","there","other","after","should","through","also","more","most","only","very","when","what","then","these","those","being","does","done","both","same","still","while","where","here","were","much","update","updates","updated","deps","dev","tests","test","add","added","fix","fixed","run","running","using"]);function lS(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function jD(t,e="AND"){let r=lS(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!Wo.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function zD(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=lS(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!Wo.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function LD(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function UD(t){return t<=4?1:t<=12?2:3}var aS=4096;function mm(){let t=uS(),e=0;try{let r=cS(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=fm(t,n);for(let a of["","-wal","-shm"])try{pm(i+a)}catch{}e++}}}catch{}return e}function hm(t,e){let r=0;try{if(!dm(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=cS(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=fm(t,s),c=Ac(i).mtimeMs<n;if(!c){let u=i+"-wal";if(dm(u))try{let l=Ac(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{pm(i+u)}catch{}r++}}catch{}}catch{}return r}function HD(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function FD(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,f=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(n++,u++)}}return n}function ZD(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var Nc=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#f;#m;#h;#g;#y;#_;#v;#x;#b;#S;#k;#E;#w;#T;#R;#P;#$;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Ye();this.#t=e??fm(uS(),`context-mode-${process.pid}.db`),Si(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),bi(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(lm(s)){um(this.#t),Si(this.#t);try{n=new r(this.#t,{timeout:3e4}),bi(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#F(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{pm(this.#t+e)}catch{}}#F(){this.#e.exec(`
266
266
  CREATE TABLE IF NOT EXISTS sources (
267
267
  id INTEGER PRIMARY KEY AUTOINCREMENT,
268
268
  label TEXT NOT NULL,
@@ -409,7 +409,7 @@ ${n}`}}};import{cpus as sD}from"node:os";async function rm(t,e){let{concurrency:
409
409
  WHERE chunks_trigram MATCH ? AND sources.label = ?
410
410
  ORDER BY rank
411
411
  LIMIT ?
412
- `),this.#x=this.#e.prepare(`
412
+ `),this.#b=this.#e.prepare(`
413
413
  SELECT
414
414
  chunks.title,
415
415
  chunks.content,
@@ -493,7 +493,7 @@ ${n}`}}};import{cpus as sD}from"node:os";async function rm(t,e){let{concurrency:
493
493
  WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
494
494
  ORDER BY rank
495
495
  LIMIT ?
496
- `),this.#b=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#R=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
496
+ `),this.#x=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#R=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
497
497
  FROM chunks c
498
498
  JOIN sources s ON s.id = c.source_id
499
499
  WHERE c.source_id = ?
@@ -502,74 +502,86 @@ ${n}`}}};import{cpus as sD}from"node:os";async function rm(t,e){let{concurrency:
502
502
  (SELECT COUNT(*) FROM sources) AS sources,
503
503
  (SELECT COUNT(*) FROM chunks) AS chunks,
504
504
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
505
- `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let f=Xx(n,"r");try{if(!Qx(f).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=Yx(f,"utf-8")}finally{eS(f)}}let c=o??n??"untitled",u=this.#V(a),l=n??void 0,d=l?tS("sha256").update(a).digest("hex"):void 0;return qn(()=>this.#d(u,c,a,l,d,s))}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#W(e,n);return qn(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=rS,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#H(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):qn(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(f=>f.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#f.run(r),e.length===0){let h=this.#s.run(r,o??null,s??null);return Number(h.lastInsertRowid)}let f=this.#o.run(r,e.length,a,o??null,s??null),m=Number(f.lastInsertRowid),p=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,m,g,null,c,u,p),this.#c.run(h.title,h.content,m,g,null,c,u,p)}return m})();return n&&this.#B(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=mD(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#x,u=[a,s,r]):(c=this.#m,u=[a,r]),qn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=hD(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#T:this.#w,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#v:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#E,u=[a,s,r]):(c=this.#y,u=[a,r]),qn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=yD(r.length),o=this.#b.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let l=gD(r,u);l<i&&(i=l,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=f=>`${f.source}::${f.title}`;for(let[f,m]of c.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}for(let[f,m]of u.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}return Array.from(l.values()).sort((f,m)=>m.score-f.score).slice(0,r).map(({result:f,score:m})=>({...f,rank:-m}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!Vo.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(m=>a.includes(m)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,f=0;if(s.length>=2){let m=i.content.toLowerCase(),p=s.map(h=>_D(m,h));if(!p.some(h=>h.length===0)){d=1/(1+bD(p)/Math.max(m.length,1));let g=vD(p,s);f=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+f}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like"){this.#q();let i=this.#z(e,r,n,o,s);if(i.length>0)return this.#L(i,e).map(f=>({...f,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(d=>d.length>=3&&!Vo.has(d)),c=a.join(" "),l=a.map(d=>this.fuzzyCorrect(d)??d).join(" ");if(l!==c){let d=this.#z(l,r,n,o,s);if(d.length>0)return this.#L(d,l).map(m=>({...m,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#q(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!cm(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Oc(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=Xx(r.file_path,"r"),i;try{if(!Qx(s).isFile())continue;i=Yx(s,"utf-8")}finally{eS(s)}if(tS("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#P.all()}getChunksBySource(e){return this.#R.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#$.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#C.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!Vo.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let f=Math.log(o/d),m=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:f+m+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return Oc(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),xi(this.#e)}#B(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Vo.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#V(e,r=rS){let n=[],o=e.split(`
505
+ `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:o,attribution:s}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let f=nS(n,"r");try{if(!oS(f).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=rS(f,"utf-8")}finally{sS(f)}}let c=o??n??"untitled",u=this.#V(a),l=n??void 0,d=l?iS("sha256").update(a).digest("hex"):void 0;return Bn(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:r,source:n,attribution:o,perFileDeny:s,...i}=e,a=tS(r,i),c=0,u=0,l=0,d=0;for(let f of a.files){if(s&&s(f)){l++;continue}try{let m=n?`${n}:${f}`:f,p=this.index({path:f,source:m,attribution:o});c++,u+=p.totalChunks}catch{d++}}return{filesIndexed:c,totalChunks:u,capped:a.capped,totalSeen:a.totalSeen,denied:l,failed:d,label:n??r}}indexPlainText(e,r,n=20,o){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,o);let s=this.#W(e,n);return Bn(()=>this.#d(s.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,o))}indexJSON(e,r,n=aS,o){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,o);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,o)}let i=[];return this.#H(s,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,o):Bn(()=>this.#d(i,r,e,void 0,void 0,o))}#d(e,r,n,o,s,i){let a=e.filter(f=>f.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",d=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#f.run(r),e.length===0){let h=this.#s.run(r,o??null,s??null);return Number(h.lastInsertRowid)}let f=this.#o.run(r,e.length,a,o??null,s??null),m=Number(f.lastInsertRowid),p=new Date().toISOString();for(let h of e){let g=h.hasCode?"code":"prose";this.#a.run(h.title,h.content,m,g,null,c,u,p),this.#c.run(h.title,h.content,m,g,null,c,u,p)}return m})();return n&&this.#B(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,r=3,n,o="AND",s,i="like"){let a=jD(e,o),c,u;return n&&s?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):s?(c=this.#b,u=[a,s,r]):(c=this.#m,u=[a,r]),Bn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=zD(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#T:this.#w,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#v:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#E,u=[a,s,r]):(c=this.#y,u=[a,r]),Bn(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=UD(r.length),o=this.#x.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let l=LD(r,u);l<i&&(i=l,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#z(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=f=>`${f.source}::${f.title}`;for(let[f,m]of c.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}for(let[f,m]of u.entries()){let p=d(m),h=l.get(p);h?h.score+=1/(60+f+1):l.set(p,{result:m,score:1/(60+f+1)})}return Array.from(l.values()).sort((f,m)=>m.score-f.score).slice(0,r).map(({result:f,score:m})=>({...f,rank:-m}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!Wo.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(m=>a.includes(m)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,f=0;if(s.length>=2){let m=i.content.toLowerCase(),p=s.map(h=>HD(m,h));if(!p.some(h=>h.length===0)){d=1/(1+ZD(p)/Math.max(m.length,1));let g=FD(p,s);f=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+f}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like"){this.#q();let i=this.#z(e,r,n,o,s);if(i.length>0)return this.#L(i,e).map(f=>({...f,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(d=>d.length>=3&&!Wo.has(d)),c=a.join(" "),l=a.map(d=>this.fuzzyCorrect(d)??d).join(" ");if(l!==c){let d=this.#z(l,r,n,o,s);if(d.length>0)return this.#L(d,l).map(m=>({...m,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#q(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!dm(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Ac(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=nS(r.file_path,"r"),i;try{if(!oS(s).isFile())continue;i=rS(s,"utf-8")}finally{sS(s)}if(iS("sha256").update(i).digest("hex")===r.content_hash)continue;this.index({content:i,path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#I.get(e);return r?{label:r.label,chunkCount:r.chunk_count,codeChunkCount:r.code_chunk_count,indexedAt:r.indexed_at,filePath:r.file_path??null,contentHash:r.content_hash??null}:null}listSources(){return this.#R.all()}getChunksBySource(e){return this.#P.all(e).map(n=>({title:n.title,content:n.content,source:n.label,rank:0,contentType:n.content_type}))}getDistinctiveTerms(e,r=40){let n=this.#$.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#C.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!Wo.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let f=Math.log(o/d),m=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:f+m+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#A.run(o),this.#N.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return Ac(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),ki(this.#e)}#B(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!Wo.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#V(e,r=aS){let n=[],o=e.split(`
506
506
  `),s=[],i=[],a="",c=()=>{let l=i.join(`
507
- `).trim();if(l.length===0)return;let d=this.#Y(s,a),f=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:f}),i=[];return}let m=l.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
507
+ `).trim();if(l.length===0)return;let d=this.#X(s,a),f=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:f}),i=[];return}let m=l.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
508
508
 
509
509
  `).trim();if(y.length===0)return;let v=m.length>1?`${d} (${h})`:d;h++,n.push({title:v,content:y,hasCode:y.includes("```")}),p=[]};for(let y of m){p.push(y);let v=p.join(`
510
510
 
511
511
  `);Buffer.byteLength(v)>r&&p.length>1&&(p.pop(),g(),p=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let m=d[1].length,p=d[2].trim();for(;s.length>0&&s[s.length-1].level>=m;)s.pop();s.push({level:m,text:p}),a=p,i.push(l),u++;continue}let f=l.match(/^(`{3,})(.*)?$/);if(f){let m=f[1],p=[l];for(u++;u<o.length;){if(p.push(o[u]),o[u].startsWith(m)&&o[u].trim()===m){u++;break}u++}i.push(...p);continue}i.push(l),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
512
512
  `)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
513
513
  `);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),f=u[0]?.trim().slice(0,80);s.push({title:f||`Lines ${l}-${d}`,content:u.join(`
514
- `)})}return s}#H(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#H(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#K(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#G(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#J(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#K(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#G(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}};function fm(t,e){return t===void 0?e:`${t}::${e}`}Vn();import{readFileSync as Fk,realpathSync as mj}from"node:fs";import{resolve as Ni}from"node:path";function Zk(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function hj(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function gj(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Hk(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function yj(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=gj(o),a=Hk(s);r=`^${i}(\\s${a})?$`}else r=`^${Hk(t)}$`;return new RegExp(r,e?"i":"")}function _j(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function vj(t,e,r=!1){for(let n of e){let o=Zk(n);if(o&&yj(o,r).test(t))return n}return null}function bj(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function fh(t){let e;try{e=Fk(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Zk(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function mh(t,e){let r=[];if(t){let o=Ni(t,".claude","settings.local.json"),s=fh(o);s&&r.push(s);let i=Ni(t,".claude","settings.json"),a=fh(i);a&&r.push(a)}let n=e!==void 0?[e]:ph();for(let o of n){let s=fh(o);s&&r.push(s)}return r}function hh(t,e,r){let n=[],o=i=>{let a;try{a=Fk(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let f=hj(d);f&&f.tool===t&&l.push(f.glob)}return l};if(e){let i=o(Ni(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Ni(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:ph();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function gh(t,e,r=process.platform==="win32"){let n=bj(t);for(let o of n)for(let s of e){let i=vj(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function yh(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Ni(n,t);s.add(o(i));try{s.add(o(mj(i)))}catch{}}for(let i of e)for(let a of i){let c=_j(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}var xj={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]};function Sj(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function qk(t,e){let r=xj[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...Sj(t)),n}function _h(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
514
+ `)})}return s}#H(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#H(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#K(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#G(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#J(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#K(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#G(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#X(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}};function gm(t,e){return t===void 0?e:`${t}::${e}`}Wn();import{readFileSync as Jk,realpathSync as Lj}from"node:fs";import{resolve as Mi}from"node:path";function Xk(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function Uj(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function Hj(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Gk(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function Fj(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=Hj(o),a=Gk(s);r=`^${i}(\\s${a})?$`}else r=`^${Gk(t)}$`;return new RegExp(r,e?"i":"")}function Zj(t,e=!1){let r="",n=0;for(;n<t.length;)t[n]==="*"&&t[n+1]==="*"?n+2<t.length&&t[n+2]==="/"?(r+="(.*/)?",n+=3):(r+=".*",n+=2):t[n]==="*"?(r+="[^/]*",n++):t[n]==="?"?(r+="[^/]",n++):(r+=t[n].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),n++);return new RegExp(`^${r}$`,e?"i":"")}function qj(t,e,r=!1){for(let n of e){let o=Xk(n);if(o&&Fj(o,r).test(t))return n}return null}function Bj(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function gh(t){let e;try{e=Jk(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&Xk(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function yh(t,e){let r=[];if(t){let o=Mi(t,".claude","settings.local.json"),s=gh(o);s&&r.push(s);let i=Mi(t,".claude","settings.json"),a=gh(i);a&&r.push(a)}let n=e!==void 0?[e]:hh();for(let o of n){let s=gh(o);s&&r.push(s)}return r}function Yc(t,e,r){let n=[],o=i=>{let a;try{a=Jk(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let l=[];for(let d of u){if(typeof d!="string")continue;let f=Uj(d);f&&f.tool===t&&l.push(f.glob)}return l};if(e){let i=o(Mi(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=o(Mi(e,".claude","settings.json"));a!==null&&n.push(a)}let s=r!==void 0?[r]:hh();for(let i of s){let a=o(i);a!==null&&n.push(a)}return n}function _h(t,e,r=process.platform==="win32"){let n=Bj(t);for(let o of n)for(let s of e){let i=qj(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Qc(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Mi(n,t);s.add(o(i));try{s.add(o(Lj(i)))}catch{}}for(let i of e)for(let a of i){let c=Zj(o(a),r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}var Vj={python:[/os\.system\(\s*(['"])(.*?)\1\s*\)/g,/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*(['"])(.*?)\1/g],javascript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],typescript:[/exec(?:Sync|File|FileSync)?\(\s*(['"`])(.*?)\1/g,/spawn(?:Sync)?\(\s*(['"`])(.*?)\1/g],ruby:[/system\(\s*(['"])(.*?)\1/g,/`(.*?)`/g],go:[/exec\.Command\(\s*(['"`])(.*?)\1/g],php:[/shell_exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])exec\(\s*(['"`])(.*?)\1/g,/(?:^|[^.])system\(\s*(['"`])(.*?)\1/g,/passthru\(\s*(['"`])(.*?)\1/g,/proc_open\(\s*(['"`])(.*?)\1/g],rust:[/Command::new\(\s*(['"`])(.*?)\1/g]};function Wj(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function Yk(t,e){let r=Vj[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...Wj(t)),n}function vh(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
515
515
 
516
516
  stdout:
517
517
  ${n}
518
518
 
519
519
  stderr:
520
- ${o}`}}import{execFileSync as kj}from"node:child_process";function Ej(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=kj("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function wj(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??Ej,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}var Tj=wj();function Pj(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function Bk(t){let e=t.checkIntervalMs??Pj(),r=t.isParentAlive??Tj,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}function Vk(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}on();Bo();on();import{existsSync as vh,unlinkSync as Rj}from"node:fs";import{join as Di}from"node:path";var $j=["","-wal","-shm"];function bh(t,e){try{return Rj(t),e.push(t),!0}catch{return!1}}function Jc(t,e){let r=!1;for(let n of $j)bh(`${t}${n}`,e)&&n===""&&(r=!0);return r}function Wk(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let _=jc(e),S=st(e),T=$r(e),I=S===T?[S]:[S,T],N=!1;for(let K of I){let k=Di(r,`${K}${_}.db`);if(!vh(k))continue;let z=null;try{z=new Xt({dbPath:k});let F=z.getEvents(a).length;z.deleteSession(a),F>0&&(N=!0)}catch{}finally{try{z?.close()}catch{}}}N&&u.push(`session rows for ${a}`);let O=[];if(n&&vh(n)&&O.push(n),o){let K=st(e),k=$r(e),z=K===k?[K]:[K,k];for(let F of z){let ct=Di(o,`${F}.db`);vh(ct)&&!O.includes(ct)&&O.push(ct)}}let j=!1;for(let K of O)try{let k=et(),z=new k(K,{timeout:3e4});try{let F=z.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;z.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),z.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),F>0&&(j=!0)}finally{try{z.close()}catch{}}}catch{}return j&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(n&&Jc(n,l)&&(f=!0),o){let _=st(e),S=$r(e),T=_===S?[_]:[_,S];for(let I of T){let N=Di(o,`${I}.db`);Jc(N,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=Di(s,`${i}.db`);Jc(_,l)}let m=jc(e),p=st(e),h=$r(e),g=p===h?[p]:[p,h],y=!1,v=!1;for(let _ of g){let S=Di(r,`${_}${m}`);Jc(`${S}.db`,l)&&(y=!0),bh(`${S}-events.md`,l)&&(v=!0),bh(`${S}.cleanup`,l)}return y&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}on();import{existsSync as Cj}from"node:fs";function xh(t,e){try{if(!Cj(t))return;let r=new Xt({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function Kk(t){xh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function Gk(t){xh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function Jk(t){xh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}on();import{existsSync as Yk}from"node:fs";function Xk(t,e,r){try{if(!Yk(t))return;let n=new Xt({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function Qk(t){try{if(!Yk(t))return null;let e=new Xt({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}Vn();on();import{existsSync as Sh,readFileSync as Oj,readdirSync as Ij,statSync as Aj}from"node:fs";import{join as ns,isAbsolute as Nj}from"node:path";var eE=process.env.DEBUG?.includes("context-mode");function rE(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?tE(r,a):null)??n??St(),l=o?.getMemoryDir(r),d=ns(u,"memory"),f=r?ns(d,st(r)):d,m=l?tE(r,l):f,p=[];if(r)for(let h of i){let g=ns(r,h);Sh(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let g=ns(u,h);Sh(g)&&p.push({path:g,label:`user/${h}`})}if(m&&Sh(m))try{let h=Ij(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:ns(m,g),label:`memory/${g}`})}catch(h){eE&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
521
- `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=Aj(h.path),g.size>1e6)continue}catch{continue}let y=Oj(h.path,"utf-8"),v=y.toLowerCase();for(let _ of t){if(s.length>=e)break;let T=_.toLowerCase().split(/\s+/).filter(N=>N.length>=3);if(T.some(N=>{try{return new RegExp(`\\b${N.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return v.includes(N)}})){let N=T.reduce((F,ct)=>{let yr=v.indexOf(ct);return yr>=0&&(F<0||yr<F)?yr:F},-1),O=Math.max(0,N-200),j=Math.min(y.length,N+500),K=y.lastIndexOf(`
522
-
523
- `,O),k=y.indexOf(`
524
-
525
- `,j);K>=0&&(O=K+2),k>=0&&(j=k);let z=y.slice(O,j).trim();s.push({title:`[auto-memory] ${h.label}`,content:z,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){eE&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
526
- `)}}return s.slice(0,e)}function tE(t,e){return e?Nj(e)||!t?e:ns(t,e):t??""}var kh=process.env.DEBUG?.includes("context-mode");function nE(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l}=t,d=[],f=new Date().toISOString();try{let m=n.searchWithFallback(e,r,s,i);d.push(...m.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||f,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(m){kh&&process.stderr.write(`[ctx] ContentStore search failed: ${m}
527
- `)}if(o==="timeline"){try{if(a){let m=a.searchEvents(e,r,c||"",s);d.push(...m.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(m){kh&&process.stderr.write(`[ctx] SessionDB search failed: ${m}
528
- `)}try{let m=rE([e],r,c,u,l);d.push(...m)}catch(m){kh&&process.stderr.write(`[ctx] auto-memory search failed: ${m}
529
- `)}}for(let m of d)m.timestamp&&!m.timestamp.includes("T")&&(m.timestamp=m.timestamp.replace(" ","T")+"Z");return o==="timeline"&&d.sort((m,p)=>(m.timestamp||"").localeCompare(p.timestamp||"")),d.slice(0,r)}sn();ro();sn();function Dj(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function Mj(t){let e=zc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function oE(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of Dj(s)){let a=Mj(i);a&&r.add(a)}return[...r]}Vn();ro();import*as _t from"node:fs";import*as wh from"node:path";var jj=["CONTEXT_MODE_PROJECT_DIR"],zj=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Eh(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function Lj(t){if(!_t.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of _t.readdirSync(t.projectsRoot)){let o=wh.join(t.projectsRoot,n),s;try{s=_t.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=_t.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=wh.join(o,a);try{let u=_t.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=_t.openSync(e,"r");try{let o=Buffer.alloc(8192),s=_t.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
530
- `).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{_t.closeSync(n)}}catch{}}function sE(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a}=t,c=a?[...lh(a),...jj]:zj;for(let u of c){let l=e[u];if(l&&!Eh(l))return l}if(o){let u=Lj({projectsRoot:o,maxAgeMs:s,nowMs:i});if(u&&!Eh(u))return u}return n&&!Eh(n)?n:r}Bo();Bo();Vn();import{execFileSync as Uj}from"node:child_process";import{existsSync as Ar,readdirSync as os,statSync as Hj}from"node:fs";import{homedir as tu}from"node:os";import{join as Et,sep as Fj}from"node:path";function fE(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}var Xc={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},Zj={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},ss=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){let c=[...s.concurrencies].sort((l,d)=>l-d),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((k,z)=>k+z,0),s=Object.values(e.calls).reduce((k,z)=>k+z,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(k=>({tool:k,calls:e.calls[k]||0,context_kb:Math.round((e.bytesReturned[k]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[k]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let k=a+e.cacheBytesSaved,z=k/Math.max(o,1),F=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:F,total_with_cache:k,total_savings_ratio:z}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),S=_?!_.consumed:!1,T=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),I=new Map;for(let k of T){I.has(k.category)||I.set(k.category,new Set);let z=I.get(k.category);if(z.size<5){let F=k.data;k.category==="file"?F=k.data.split("/").pop()||k.data:(k.category==="prompt"||k.category==="user-prompt")&&(F=F.length>50?F.slice(0,47)+"...":F),F.length>40&&(F=F.slice(0,37)+"..."),z.add(F)}}let N=g.map(k=>({category:k.category,count:k.cnt,label:Xc[k.category]||k.category,preview:I.get(k.category)?Array.from(I.get(k.category)).join(", "):"",why:Zj[k.category]||"Survives context resets"})),O=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),K=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(k=>k.cnt>0).map(k=>({category:k.category,count:k.cnt,label:Xc[k.category]||k.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:m},continuity:{total_events:h,by_category:N,compact_count:v,resume_ready:S},projectMemory:{total_events:O.cnt,session_count:O.sessions,by_category:K}}}};function qj(t){let e=t?.home??tu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Et(e,...o,"context-mode");return{name:n,sessionsDir:Et(s,"sessions"),contentDir:Et(s,"content")}})}function Bj(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Mi(t){let e=St(),r=t?.sessionsDir??Et(e,"context-mode","sessions"),n=t?.memoryRoot??Et(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Ar(r)){let m=[];try{m=os(r).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():et()}catch{}if(p)for(let h of m){let g=Et(r,h);try{let y=new p(g,{readonly:!0});try{let v=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=v?.cnt??0,s+=_?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let T of S)T.category&&(u[T.category]=(u[T.category]??0)+(T.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let T=S.t.endsWith("Z")?S.t:S.t+"Z",I=Date.parse(T);Number.isFinite(I)&&I<a&&(a=I)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let T of S)T.p&&c.add(T.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Ar(n)){let m=[];try{m=os(n).filter(p=>{try{return Hj(Et(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Et(n,p,"memory");if(!Ar(h))continue;let g=[];try{g=os(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let v=Bj(y);f[v]=(f[v]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:f,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function mE(t){let e=t.sessionsDir??Et(tu(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Ar(e))return n;let o=[];try{o=os(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():et()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=_=>Math.floor(_/864e5)*864e5;for(let _ of o){let S=Et(e,_),T=!1;try{let I=new s(S,{readonly:!0});try{let N=I.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let j of N)j.category&&(i[j.category]=(i[j.category]??0)+(j.cnt??0),a+=j.cnt??0,T=!0);let O=I.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(O?.mn){let j=Date.parse(O.mn+(O.mn.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j<d&&(d=j)}if(O?.mx){let j=Date.parse(O.mx+(O.mx.endsWith("Z")?"":"Z"));Number.isFinite(j)&&j>f&&(f=j)}try{let j=I.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let K of j){if(!K.sec)continue;let k=parseInt(K.sec,10)*1e3;if(!Number.isFinite(k))continue;let z=h(k),F=p.get(z)??{count:0,rescueBytes:0};F.count+=K.cnt??0,p.set(z,F)}}catch{}try{let j=I.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(j?.bytes&&(u+=j.bytes),j?.n&&(l+=j.n),j?.lastSec){let K=parseInt(j.lastSec,10)*1e3;if(Number.isFinite(K)&&K>m&&(m=K),Number.isFinite(K)&&(j?.bytes??0)>0){let k=h(K),z=p.get(k)??{count:0,rescueBytes:0};z.rescueBytes=Math.max(z.rescueBytes,j.bytes),p.set(k,z)}}}catch{}}finally{I.close()}}catch{}T&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,S])=>({category:_,count:S,label:Xc[_]||_})).sort((_,S)=>S.count-_.count),v=[...p.entries()].sort((_,S)=>_[0]-S[0]).map(([_,S])=>({ms:_,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:m>0?m:void 0,byDay:v}}function Vj(t,e,r){if(!t||!e||!Ar(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():et()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
531
- FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function hE(t,e){if(!t||!Ar(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():et()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
532
- FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Th(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Et(tu(),".claude","context-mode","sessions");if(!Ar(r))return e;let n=[];try{n=os(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():et()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of n){let f=Et(r,d);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
520
+ ${o}`}}import{execFileSync as Kj}from"node:child_process";function Gj(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=Kj("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function Jj(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??Gj,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}var Xj=Jj();function Yj(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<=0?3e4:1e3}function Qk(t){let e=t.checkIntervalMs??Yj(),r=t.isParentAlive??Xj,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}function eE(t,e){if(e<=0)return"";if(t.length<=e)return t;let r=e,n=t.charCodeAt(r-1);return n>=55296&&n<=56319&&(r-=1),t.slice(0,r)}Cr();Vo();Cr();import{existsSync as xh,unlinkSync as Qj}from"node:fs";import{join as ji}from"node:path";var ez=["","-wal","-shm"];function bh(t,e){try{return Qj(t),e.push(t),!0}catch{return!1}}function eu(t,e){let r=!1;for(let n of ez)bh(`${t}${n}`,e)&&n===""&&(r=!0);return r}function tE(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let _=Lc(e),b=ct(e),E=$r(e),R=b===E?[b]:[b,E],N=!1;for(let W of R){let k=ji(r,`${W}${_}.db`);if(!xh(k))continue;let D=null;try{D=new Qt({dbPath:k});let L=D.getEvents(a).length;D.deleteSession(a),L>0&&(N=!0)}catch{}finally{try{D?.close()}catch{}}}N&&u.push(`session rows for ${a}`);let C=[];if(n&&xh(n)&&C.push(n),o){let W=ct(e),k=$r(e),D=W===k?[W]:[W,k];for(let L of D){let qe=ji(o,`${L}.db`);xh(qe)&&!C.includes(qe)&&C.push(qe)}}let M=!1;for(let W of C)try{let k=Ye(),D=new k(W,{timeout:3e4});try{let L=D.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;D.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),D.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),L>0&&(M=!0)}finally{try{D.close()}catch{}}}catch{}return M&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(n&&eu(n,l)&&(f=!0),o){let _=ct(e),b=$r(e),E=_===b?[_]:[_,b];for(let R of E){let N=ji(o,`${R}.db`);eu(N,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=ji(s,`${i}.db`);eu(_,l)}let m=Lc(e),p=ct(e),h=$r(e),g=p===h?[p]:[p,h],y=!1,v=!1;for(let _ of g){let b=ji(r,`${_}${m}`);eu(`${b}.db`,l)&&(y=!0),bh(`${b}-events.md`,l)&&(v=!0),bh(`${b}.cleanup`,l)}return y&&u.push("session events DB"),v&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}Cr();import{existsSync as tz}from"node:fs";function Sh(t,e){try{if(!tz(t))return;let r=new Qt({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function rE(t){Sh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"sandbox-execute",category:"sandbox",priority:1,data:t.toolName,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesReturned:t.bytesReturned})})}function nE(t){Sh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"index-write",category:"sandbox",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}function oE(t){Sh(t.sessionDbPath,(e,r)=>{e.insertEvent(r,{type:"cache-hit",category:"cache",priority:1,data:t.source,project_dir:"",attribution_source:"server",attribution_confidence:1},"ctx-server",void 0,{bytesAvoided:t.bytesAvoided})})}Cr();import{existsSync as sE}from"node:fs";function iE(t,e,r){try{if(!sE(t))return;let n=new Qt({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function aE(t){try{if(!sE(t))return null;let e=new Qt({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}Wn();Cr();import{existsSync as kh,readFileSync as rz,readdirSync as nz,statSync as oz}from"node:fs";import{join as os,isAbsolute as sz}from"node:path";var cE=process.env.DEBUG?.includes("context-mode");function lE(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?uE(r,a):null)??n??St(),l=o?.getMemoryDir(r),d=os(u,"memory"),f=r?os(d,ct(r)):d,m=l?uE(r,l):f,p=[];if(r)for(let h of i){let g=os(r,h);kh(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let g=os(u,h);kh(g)&&p.push({path:g,label:`user/${h}`})}if(m&&kh(m))try{let h=nz(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:os(m,g),label:`memory/${g}`})}catch(h){cE&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
521
+ `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=oz(h.path),g.size>1e6)continue}catch{continue}let y=rz(h.path,"utf-8"),v=y.toLowerCase();for(let _ of t){if(s.length>=e)break;let E=_.toLowerCase().split(/\s+/).filter(N=>N.length>=3);if(E.some(N=>{try{return new RegExp(`\\b${N.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return v.includes(N)}})){let N=E.reduce((L,qe)=>{let yr=v.indexOf(qe);return yr>=0&&(L<0||yr<L)?yr:L},-1),C=Math.max(0,N-200),M=Math.min(y.length,N+500),W=y.lastIndexOf(`
522
+
523
+ `,C),k=y.indexOf(`
524
+
525
+ `,M);W>=0&&(C=W+2),k>=0&&(M=k);let D=y.slice(C,M).trim();s.push({title:`[auto-memory] ${h.label}`,content:D,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){cE&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
526
+ `)}}return s.slice(0,e)}function uE(t,e){return e?sz(e)||!t?e:os(t,e):t??""}var Eh=process.env.DEBUG?.includes("context-mode");function dE(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l}=t,d=[],f=new Date().toISOString();try{let m=n.searchWithFallback(e,r,s,i);d.push(...m.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||f,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(m){Eh&&process.stderr.write(`[ctx] ContentStore search failed: ${m}
527
+ `)}if(o==="timeline"){try{if(a){let m=a.searchEvents(e,r,c||"",s);d.push(...m.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(m){Eh&&process.stderr.write(`[ctx] SessionDB search failed: ${m}
528
+ `)}try{let m=lE([e],r,c,u,l);d.push(...m)}catch(m){Eh&&process.stderr.write(`[ctx] auto-memory search failed: ${m}
529
+ `)}}for(let m of d)m.timestamp&&!m.timestamp.includes("T")&&(m.timestamp=m.timestamp.replace(" ","T")+"Z");return o==="timeline"&&d.sort((m,p)=>(m.timestamp||"").localeCompare(p.timestamp||"")),d.slice(0,r)}sn();no();sn();function iz(t){let e=[];if(t&&typeof t=="object"){let r=t.command;typeof r=="string"&&e.push(r);let n=t.hooks;if(Array.isArray(n)){for(let o of n)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function az(t){let e=Uc(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function pE(t,e){let r=new Set,n=t.generateHookConfig(e);for(let o of Object.values(n))if(Array.isArray(o))for(let s of o)for(let i of iz(s)){let a=az(i);a&&r.add(a)}return[...r]}Wn();no();import*as je from"node:fs";import*as fE from"node:os";import*as ss from"node:path";var cz=["CONTEXT_MODE_PROJECT_DIR"],uz=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function tu(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function lz(t){if(!je.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of je.readdirSync(t.projectsRoot)){let o=ss.join(t.projectsRoot,n),s;try{s=je.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=je.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=ss.join(o,a);try{let u=je.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=je.openSync(e,"r");try{let o=Buffer.alloc(8192),s=je.readSync(n,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
530
+ `).slice(0,10))if(a.trim())try{let c=JSON.parse(a);if(typeof c.cwd=="string"&&c.cwd.length>0)return c.cwd}catch{}}finally{je.closeSync(n)}}catch{}}function dz(t){let e=t?.codexHome??process.env.CODEX_HOME??ss.join(fE.homedir(),".codex"),r=ss.join(e,"sessions");if(!je.existsSync(r))return null;let n,o=0;try{for(let s of je.readdirSync(r)){if(!s.endsWith(".jsonl"))continue;let i=ss.join(r,s);try{let a=je.statSync(i).mtimeMs;a>o&&(o=a,n=i)}catch{}}}catch{return null}if(!n||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-o>t.transcriptMaxAgeMs)return null;try{let s=je.openSync(n,"r");try{let i=Buffer.alloc(8192),a=je.readSync(s,i,0,i.length,0),u=i.subarray(0,a).toString("utf-8").split(`
531
+ `,1)[0];if(!u||!u.trim())return null;try{let d=JSON.parse(u)?.meta?.cwd;return typeof d!="string"||d.length===0||tu(d)?null:d}catch{return null}}finally{je.closeSync(s)}}catch{return null}}function mE(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...fh(a),...cz]:uz;for(let l of u){let d=e[l];if(d&&!tu(d))return d}if(o){let l=lz({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!tu(l))return l}if(a==="codex"){let l=dz({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return n&&!tu(n)?n:r}Vo();Vo();Cr();Wn();import{execFileSync as pz}from"node:child_process";import{existsSync as Nr,readdirSync as is,statSync as fz}from"node:fs";import{homedir as iu}from"node:os";import{join as Et,sep as mz}from"node:path";function SE(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}var nu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session goal",role:"Behavior rules",constraint:"Constraints you set",mcp:"MCP tools called",skill:"Skills used",subagent:"Delegated work",decision:"Your decisions","agent-finding":"Agent insights kept","rejected-approach":"Approaches you rejected","external-ref":"External docs indexed",data:"Data references",git:"Git operations",env:"Environment setup",task:"Tasks in progress",error:"Errors caught",compact:"Compactions weathered",resume:"Sessions resumed cleanly",snapshot:"Snapshots restored",cache:"Cache hits saved",latency:"Slow tools recorded","user-prompt":"Your messages remembered",plan:"Plans drafted","blocked-on":"Blockers logged"},hz={file:"Restored after compact \u2014 no need to re-read",rule:"Your project instructions survive context resets",prompt:"Continues exactly where you left off",decision:"Applied automatically \u2014 won\u2019t ask again",task:"Picks up from where it stopped",error:"Tracked and monitored across compacts",git:"Branch, commit, and repo state preserved",env:"Runtime config carried forward",mcp:"Tool usage patterns remembered",subagent:"Delegation history preserved",skill:"Skill invocations tracked"},as=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){let c=[...s.concurrencies].sort((l,d)=>l-d),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((k,D)=>k+D,0),s=Object.values(e.calls).reduce((k,D)=>k+D,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(k=>({tool:k,calls:e.calls[k]||0,context_kb:Math.round((e.bytesReturned[k]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[k]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let k=a+e.cacheBytesSaved,D=k/Math.max(o,1),L=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:L,total_with_cache:k,total_savings_ratio:D}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),v=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),b=_?!_.consumed:!1,E=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),R=new Map;for(let k of E){R.has(k.category)||R.set(k.category,new Set);let D=R.get(k.category);if(D.size<5){let L=k.data;k.category==="file"?L=k.data.split("/").pop()||k.data:(k.category==="prompt"||k.category==="user-prompt")&&(L=L.length>50?L.slice(0,47)+"...":L),L.length>40&&(L=L.slice(0,37)+"..."),D.add(L)}}let N=g.map(k=>({category:k.category,count:k.cnt,label:nu[k.category]||k.category,preview:R.get(k.category)?Array.from(R.get(k.category)).join(", "):"",why:hz[k.category]||"Survives context resets"})),C=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),W=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(k=>k.cnt>0).map(k=>({category:k.category,count:k.cnt,label:nu[k.category]||k.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:p,session:{id:n,uptime_min:m},continuity:{total_events:h,by_category:N,compact_count:v,resume_ready:b},projectMemory:{total_events:C.cnt,session_count:C.sessions,by_category:W}}}};function gz(t){let e=t?.home??iu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([n,o])=>{let s=Et(e,...o,"context-mode");return{name:n,sessionsDir:Et(s,"sessions"),contentDir:Et(s,"content")}})}function yz(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function zi(t){let e=St(),r=t?.sessionsDir??Et(e,"context-mode","sessions"),n=t?.memoryRoot??Et(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Nr(r)){let m=[];try{m=is(r).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Ye()}catch{}if(p)for(let h of m){let g=Et(r,h);try{let y=new p(g,{readonly:!0});try{let v=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=v?.cnt??0,s+=_?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let E of b)E.category&&(u[E.category]=(u[E.category]??0)+(E.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let E=b.t.endsWith("Z")?b.t:b.t+"Z",R=Date.parse(E);Number.isFinite(R)&&R<a&&(a=R)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let E of b)E.p&&c.add(E.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Nr(n)){let m=[];try{m=is(n).filter(p=>{try{return fz(Et(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Et(n,p,"memory");if(!Nr(h))continue;let g=[];try{g=is(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let v=yz(y);f[v]=(f[v]??0)+1}}}}return{totalEvents:o,totalSessions:s,autoMemoryCount:l,autoMemoryProjects:d,autoMemoryByPrefix:f,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function kE(t){let e=t.sessionsDir??Et(iu(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Nr(e))return n;let o=[];try{o=is(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(o.length===0)return n;let s=null;try{s=t.loadDatabase?t.loadDatabase():Ye()}catch{return n}if(!s)return n;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=_=>Math.floor(_/864e5)*864e5;for(let _ of o){let b=Et(e,_),E=!1;try{let R=new s(b,{readonly:!0});try{let N=R.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let M of N)M.category&&(i[M.category]=(i[M.category]??0)+(M.cnt??0),a+=M.cnt??0,E=!0);let C=R.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(C?.mn){let M=Date.parse(C.mn+(C.mn.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M<d&&(d=M)}if(C?.mx){let M=Date.parse(C.mx+(C.mx.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M>f&&(f=M)}try{let M=R.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let W of M){if(!W.sec)continue;let k=parseInt(W.sec,10)*1e3;if(!Number.isFinite(k))continue;let D=h(k),L=p.get(D)??{count:0,rescueBytes:0};L.count+=W.cnt??0,p.set(D,L)}}catch{}try{let M=R.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(M?.bytes&&(u+=M.bytes),M?.n&&(l+=M.n),M?.lastSec){let W=parseInt(M.lastSec,10)*1e3;if(Number.isFinite(W)&&W>m&&(m=W),Number.isFinite(W)&&(M?.bytes??0)>0){let k=h(W),D=p.get(k)??{count:0,rescueBytes:0};D.rescueBytes=Math.max(D.rescueBytes,M.bytes),p.set(k,D)}}}catch{}}finally{R.close()}}catch{}E&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,b])=>({category:_,count:b,label:nu[_]||_})).sort((_,b)=>b.count-_.count),v=[...p.entries()].sort((_,b)=>_[0]-b[0]).map(([_,b])=>({ms:_,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:m>0?m:void 0,byDay:v}}function _z(t,e,r){if(!t||!e||!Nr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():Ye()}catch{return 0}if(!n)return 0;try{let o=new n(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
532
+ FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function EE(t,e){if(!t||!Nr(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():Ye()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let o=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
533
+ FROM chunks`).get();return Number(o?.bytes??0)}finally{n.close()}}catch{return 0}}function Li(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Et(iu(),".claude","context-mode","sessions");if(!Nr(r))return e;let n=[];try{n=is(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():Ye()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of n){let f=Et(r,d);PS(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
533
534
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
534
535
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
535
536
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
536
- FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}}else{let p=m.prepare(`SELECT
537
+ FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}}else if(t.projectDir){let p=m.prepare(`SELECT
537
538
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
538
539
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
539
540
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
540
- FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=Vj(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}var Wj={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function Kj(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!Ar(t.sessionsDir))return n;let o=[];try{o=os(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Et(t.sessionsDir,l);try{let f=new s(d,{readonly:!0});try{let m=f.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();m&&(n.eventCount+=Number(m.cnt??0),n.dataBytes+=Number(m.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=f.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=f.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=f.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=f.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{f.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function ru(t){let e=qj({home:t?.home}),r=t?.loadDatabase??et,n={...Wj,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Ar(c.sessionsDir))continue;let u=Kj(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var gE={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},Gj={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};function Qc(t){return Gj[t]??t}function Ge(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function Jj(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function Yc(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function Yj(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Yc(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=Uj("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!Yc(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!Yc(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return Yc(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function iE(t){let e=tu();return e?t===e?"~":t.startsWith(e+Fj)?"~"+t.slice(e.length):t:t}function Xj(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,o=(h,g=2)=>h.toFixed(g),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),m=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${Ge(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function Qj(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*dE,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*dE,v=Math.round((r?.rescueBytes??0)/4),_=y+v,S=o?.lifetime?.totalSavedTokens??0,T=Math.max(_,S),I=o?.lifetime?.bytesReturned??0,N=o?.lifetime?.bytesAvoided??0,O=I+N>0?Math.max(1,Math.floor(I/4)):Math.max(1,Math.round(T*.02)),j=n?.totalBytes&&n.totalBytes>0?n.totalBytes:T*4,K=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,k=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,z=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,F=z>0?Math.max(1,Math.round((c-z)/864e5)):0,ct=n?.totalSessions??r?.totalSessions??1,yr=n?.perAdapter.filter(De=>De.isReal).length??0,ls;if(n&&yr>=2)ls=`across ${yr} AI tools`;else if(n&&yr===1){let De=n.perAdapter.find(Ht=>Ht.isReal);ls=`in ${De?Qc(De.name):"Claude Code"}`}else ls="in Claude Code";F>0?d.push(` Across ${F} days you ran ${tr(ct)} conversations ${ls}.`):d.push(` You ran ${tr(ct)} conversations ${ls}.`);let LE=F>0?j/F:0;d.push(` context-mode kept ${Ge(j)} out of your context window \u2014 about ${Ge(LE)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let jh=e.firstEventMs&&e.firstEventMs>0?aE(e.firstEventMs,i,a):"";if(jh?d.push(` This conversation started ${jh} in ${iE(s)}.`):d.push(` This conversation lives in ${iE(s)}.`),d.push(` ${k}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let De=e.lastRescueMs&&e.lastRescueMs>0?aE(e.lastRescueMs,i,a):"",Ht=Math.round(e.snapshotBytes/1024);De?d.push(` On ${De}, /compact fired \u2014 ${Ht} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Ht} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let _u=o?.conversation,zh=_u?.bytesAvoided??0,vu=_u?.bytesReturned??0,bu=_u?.eventDataBytes??0;if(zh+vu+bu>0){let De=zh+vu+bu,Ht=Math.max(1,vu+bu),Ft=Math.max(1,Math.floor(De/4)),_r=Math.max(1,Math.floor(Ht/4)),xu=un(Ft,Ft,32),qE=un(_r,Ft,32),BE=(1-_r/Ft)*100,VE=Math.max(1,Math.round(Ft/_r));d.push(` Without context-mode ${Ge(De).padStart(8)} ${xu} ${tr(Ft).padStart(7)} tokens`),d.push(` With context-mode ${Ge(Ht).padStart(8)} ${qE} ${tr(_r).padStart(7)} tokens`),d.push(` ${BE.toFixed(0)}% kept out of context \xB7 your AI ran ${VE}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let De=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${Ge(K)} built up \u2014 ${De} days, ${e.byDay.length} active:`),d.push(""),d.push(...tz(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let UE=e.byCategory.reduce((De,Ht)=>De+Ht.count,0).toLocaleString(i);d.push(` ${UE} things \u2014 files, errors, decisions, agent runs:`),d.push("");let HE=e.byCategory[0]?.count??1;for(let De of e.byCategory)d.push(` ${De.label.padEnd(26)} ${String(De.count).padStart(5)} ${un(De.count,HE,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Lh=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Uh=z>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(z)):"",Hh=r?.distinctProjects??0,FE=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${Ge(K)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Lh?` \xB7 started ${Lh}`:""}.`),d.push(` All your work: ${Ge(j)} kept out \xB7 ${FE.toLocaleString(i)} captures across ${Hh} project${Hh===1?"":"s"}${Uh?` \xB7 since ${Uh}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...Xj(j,T,F)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let De=Object.entries(r.autoMemoryByPrefix).sort((Ft,_r)=>_r[1]-Ft[1]),Ht=De.length>0?De[0][1]:1;for(let[Ft,_r]of De){let xu=gE[Ft]??Ft;d.push(` ${xu.padEnd(26)} ${String(_r).padStart(2)} ${un(_r,Ht,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let ZE=u?`v${u}`:"context-mode";return d.push(` ${ZE}`),u&&l&&l!=="unknown"&&fE(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),ez(d)}function ez(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function tz(t,e,r){if(t.length===0)return[];let n=[...t].sort((f,m)=>f.ms-m.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let f of n)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of n){let m=Math.round((f.ms-o.ms)/i*(c-1)),p="\u25CF";f===a&&(p="\u2588"),(f.rescueBytes??0)>0&&(p="\u25C6"),u[m]=p}let l=f=>{let m=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(f)),p=(m.find(g=>g.type==="month")?.value??"").toLowerCase(),h=m.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let f of n){let m=l(f.ms).padEnd(7),p=`${f.count} captures`,h=f===a?" \u2190 peak":"",g=(f.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((f.rescueBytes??0)/1024)} KB`:"";d.push(` ${m} ${p}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function aE(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(f=>f.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function tr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}var nu=15/1e6;function eu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*nu).toFixed(2)}`}function un(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function cE(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${tr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${tr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${tr(h)} sessions`,y=a*256+r;o.push(` ${tr(a)} events \xB7 ${g} \xB7 ~${eu(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:Xc[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let f=d.slice(0,n),m=f.length>0?f[0].count:1;for(let h of f)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${un(h.count,m,30)}`);let p=Math.max(0,d.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function uE(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=gE[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${un(s,n,20)}`)}return e}function lE(t,e){let r=[],n=eu(t),o=(e?.totalEvents??0)*256+t,s=eu(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}var dE=256;function pE(t){if(!t)return[];let e=t.perAdapter.filter(o=>o.isReal),r=t.perAdapter.filter(o=>!o.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?tr(u.eventCount):"\u2014",f=Ge(u.dataBytes),m=Ge(l);n.push(` ${Qc(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${m.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>Qc(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function ou(t,e,r,n){let o=[],s=Jj(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(I=>I.isReal).length??0;if(l&&d>0){let I=l.totalSessions||i?.totalSessions||0,N=i?.firstEventMs??0,O=N>0?Math.max(1,Math.round((Date.now()-N)/864e5)):0,j=O>0?`Across ${O} day${O===1?"":"s"} `:"",K=I>0?`you ran ${tr(I)} conversation${I===1?"":"s"} `:"you ran ",k;if(d>=2)k=`across ${d} AI tools`;else{let z=l.perAdapter.find(F=>F.isReal);k=`in ${z?Qc(z.name):"Claude Code"}`}o.push(`${j}${K}${k}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let I=Yj(),N=n?.cwd??process.cwd(),O=n?.now??Date.now(),j=n?.locale??I.locale,K=n?.tz??I.tz;return o.push(...Qj({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:N,locale:j,tz:K,now:O,version:e,latestVersion:r})),o.join(`
541
- `)}let f=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),m=t.savings.total_bytes_returned,p=t.savings.total_calls,h=f+m,g=h>0?f/h*100:0,y=Math.round(f/4),v=m>0?Math.max(1,Math.round(h/Math.max(m,1))):0;if(f===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${Ge(m)} entered context | 0 tokens saved`),o.push(...cE(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...pE(l)),o.push(...uE(i)),o.push(...lE(0,i)),o.push("");let I=e?`v${e}`:"context-mode";return o.push(I),e&&r&&r!=="unknown"&&fE(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
542
- `)}o.push(`${tr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${eu(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${un(h,h)}| ${Ge(h)}`),o.push(`With context-mode |${un(m,h)}| ${Ge(m)}`),o.push(""),v>=2?o.push(`${Ge(f)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):o.push(`${Ge(f)} kept out of your conversation. Never entered context.`),o.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${Ge(t.cache.bytes_saved)})`),o.push(_.join(" \xB7 "));let S=t.savings.by_tool.filter(I=>I.calls>0);if(S.length>=2){o.push("");let I=S.map(N=>{let O=N.context_kb*1024,j=g<100?O/(1-g/100):O,K=Math.max(0,j-O);return{...N,returnedBytes:O,estimatedSaved:K}}).sort((N,O)=>O.estimatedSaved-N.estimatedSaved);for(let N of I){let O=N.tool.length>22?N.tool.slice(0,19)+"...":N.tool;o.push(` ${O.padEnd(22)} ${String(N.calls).padStart(4)} calls ${Ge(N.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let I=a.filter(N=>N.median_concurrency!=null&&(N.max_concurrency??1)>1);if(I.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let N of I){let O=N.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${O.padEnd(22)} ${N.calls} batches \xB7 ${N.median_concurrency} typical, ${N.max_concurrency} peak`)}}}o.push(...cE(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...pE(l)),o.push(...uE(i)),o.push(...lE(y,i)),o.push("");let T=e?`v${e}`:"context-mode";return o.push(T),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
543
- `)}var wt=nr(uz(import.meta.url)),Dr=(()=>{for(let t of["../package.json","./package.json"]){let e=je(wt,t);if(we(e))try{return JSON.parse(hu(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
541
+ FROM session_events
542
+ WHERE session_id IN (
543
+ SELECT session_id FROM session_meta WHERE project_dir = ?
544
+ )`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
545
+ FROM session_resume
546
+ WHERE session_id IN (
547
+ SELECT session_id FROM session_meta WHERE project_dir = ?
548
+ )`).get(t.projectDir);h?.bytes&&(c+=Number(h.bytes))}catch{}}else{let p=m.prepare(`SELECT
549
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
550
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
551
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
552
+ FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=_z(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let l=Math.floor((s+i+c)/4);return{eventDataBytes:s,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:l}}var vz={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function xz(t,e,r){let n={name:t.name,eventCount:0,sessionCount:0,dataBytes:0,rescueBytes:0,contentBytes:0,uuidConvs:0,projectDirs:[],firstMs:Number.POSITIVE_INFINITY,lastMs:0,isReal:!1};if(!Nr(t.sessionsDir))return n;let o=[];try{o=is(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return n}if(o.length===0)return n;let s=null;try{s=e()}catch{return n}if(!s)return n;let i=new Set,a=new Set;for(let l of o){let d=Et(t.sessionsDir,l);try{let f=new s(d,{readonly:!0});try{let m=f.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();m&&(n.eventCount+=Number(m.cnt??0),n.dataBytes+=Number(m.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=f.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=f.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=f.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=f.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{f.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function au(t){let e=gz({home:t?.home}),r=t?.loadDatabase??Ye,n={...vz,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Nr(c.sessionsDir))continue;let u=xz(c,r,n);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var wE={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},bz={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};function ou(t){return bz[t]??t}function Qe(t){if(!Number.isFinite(t)||t<=0)return"0 B";if(t<1024)return`${Math.round(t)} B`;let e=t/1024;if(e<1024)return e<100?`${e.toFixed(1)} KB`:`${Math.round(e)} KB`;let r=e/1024;if(r<1024)return r<100?`${r.toFixed(1)} MB`:`${Math.round(r)} MB`;let n=r/1024;return n<100?`${n.toFixed(2)} GB`:`${n.toFixed(1)} GB`}function Sz(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let r=Math.floor(e/60),n=Math.round(e%60);return n>0?`${r}h ${n}m`:`${r}h`}function ru(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function kz(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!ru(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=pz("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!ru(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!ru(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return ru(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function hE(t){let e=iu();return e?t===e?"~":t.startsWith(e+mz)?"~"+t.slice(e.length):t:t}function Ez(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,o=(h,g=2)=>h.toFixed(g),s=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),m=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${o(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${Qe(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function wz(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*xE,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*xE,v=Math.round((r?.rescueBytes??0)/4),_=y+v,b=o?.lifetime?.totalSavedTokens??0,E=Math.max(_,b),R=o?.lifetime?.bytesReturned??0,N=o?.lifetime?.bytesAvoided??0,C=R+N>0?Math.max(1,Math.floor(R/4)):Math.max(1,Math.round(E*.02)),M=n?.totalBytes&&n.totalBytes>0?n.totalBytes:E*4,W=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,k=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,D=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,L=D>0?Math.max(1,Math.round((c-D)/864e5)):0,qe=n?.totalSessions??r?.totalSessions??1,yr=n?.perAdapter.filter(De=>De.isReal).length??0,ps;if(n&&yr>=2)ps=`across ${yr} AI tools`;else if(n&&yr===1){let De=n.perAdapter.find(Ft=>Ft.isReal);ps=`in ${De?ou(De.name):"Claude Code"}`}else ps="in Claude Code";L>0?d.push(` Across ${L} days you ran ${rr(qe)} conversations ${ps}.`):d.push(` You ran ${rr(qe)} conversations ${ps}.`);let WE=L>0?M/L:0;d.push(` context-mode kept ${Qe(M)} out of your context window \u2014 about ${Qe(WE)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Mh=e.firstEventMs&&e.firstEventMs>0?gE(e.firstEventMs,i,a):"";if(Mh?d.push(` This conversation started ${Mh} in ${hE(s)}.`):d.push(` This conversation lives in ${hE(s)}.`),d.push(` ${k}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let De=e.lastRescueMs&&e.lastRescueMs>0?gE(e.lastRescueMs,i,a):"",Ft=Math.round(e.snapshotBytes/1024);De?d.push(` On ${De}, /compact fired \u2014 ${Ft} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Ft} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let jh=o?.conversation,zh=jh?.bytesAvoided??0,ku=jh?.bytesReturned??0;if(zh+ku===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let De=zh+ku,Ft=Math.max(1,ku),Zt=Math.max(1,Math.floor(De/4)),_r=Math.max(1,Math.floor(Ft/4)),Eu=un(Zt,Zt,32),YE=un(_r,Zt,32),QE=(1-_r/Zt)*100,ew=Math.max(1,Math.round(Zt/_r));d.push(` Without context-mode ${Qe(De).padStart(8)} ${Eu} ${rr(Zt).padStart(7)} tokens`),d.push(` With context-mode ${Qe(Ft).padStart(8)} ${YE} ${rr(_r).padStart(7)} tokens`),d.push(` ${QE.toFixed(0)}% kept out of context \xB7 your AI ran ${ew}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let De=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${Qe(W)} built up \u2014 ${De} days, ${e.byDay.length} active:`),d.push(""),d.push(...Rz(e.byDay,i,a))}d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 2. What this chat captured (used when you --continue or /resume here) \u2500\u2500\u2500"),d.push("");let KE=e.byCategory.reduce((De,Ft)=>De+Ft.count,0).toLocaleString(i);d.push(` ${KE} things \u2014 files, errors, decisions, agent runs:`),d.push("");let GE=e.byCategory[0]?.count??1;for(let De of e.byCategory)d.push(` ${De.label.padEnd(26)} ${String(De.count).padStart(5)} ${un(De.count,GE,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Lh=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Uh=D>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(D)):"",Hh=r?.distinctProjects??0,JE=r?.totalEvents??n?.totalEvents??0;if(d.push(` This chat: ${Qe(W)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Lh?` \xB7 started ${Lh}`:""}.`),d.push(` All your work: ${Qe(M)} kept out \xB7 ${JE.toLocaleString(i)} captures across ${Hh} project${Hh===1?"":"s"}${Uh?` \xB7 since ${Uh}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...Ez(M,E,L)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),r&&r.autoMemoryCount>0){d.push(` ${r.autoMemoryCount} preferences picked up across ${r.autoMemoryProjects} project${r.autoMemoryProjects===1?"":"s"}:`);let De=Object.entries(r.autoMemoryByPrefix).sort((Zt,_r)=>_r[1]-Zt[1]),Ft=De.length>0?De[0][1]:1;for(let[Zt,_r]of De){let Eu=wE[Zt]??Zt;d.push(` ${Eu.padEnd(26)} ${String(_r).padStart(2)} ${un(_r,Ft,20)}`)}}else d.push(" No preferences learned yet \u2014 context-mode picks them up automatically.");d.push(""),d.push(""),d.push(" Your AI talks less, remembers more, costs less."),d.push(` Locale ${i} \xB7 timezone ${a} \xB7 pricing examples for illustration only.`),d.push("");let XE=u?`v${u}`:"context-mode";return d.push(` ${XE}`),u&&l&&l!=="unknown"&&SE(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),Tz(d)}function Tz(t){let e=[],r=0;for(let n of t)n===""?(r++,r<=2&&e.push(n)):(r=0,e.push(n));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function Rz(t,e,r){if(t.length===0)return[];let n=[...t].sort((f,m)=>f.ms-m.ms),o=n[0],s=n[n.length-1],i=Math.max(1,s.ms-o.ms),a=n[0];for(let f of n)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of n){let m=Math.round((f.ms-o.ms)/i*(c-1)),p="\u25CF";f===a&&(p="\u2588"),(f.rescueBytes??0)>0&&(p="\u25C6"),u[m]=p}let l=f=>{let m=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(f)),p=(m.find(g=>g.type==="month")?.value??"").toLowerCase(),h=m.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},d=[];d.push(` ${l(o.ms)} ${u.join("")} ${l(s.ms)}`),d.push("");for(let f of n){let m=l(f.ms).padEnd(7),p=`${f.count} captures`,h=f===a?" \u2190 peak":"",g=(f.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((f.rescueBytes??0)/1024)} KB`:"";d.push(` ${m} ${p}${h}${g}`)}return d.push(""),d.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),d}function gE(t,e,r){if(!Number.isFinite(t)||t<=0)return"";let n=new Date(t);if(Number.isNaN(n.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:r,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(n),s=d=>o.find(f=>f.type===d)?.value??"",i=s("day"),a=s("month"),c=s("year"),u=s("hour"),l=s("minute");return u==="24"&&(u="00"),`${i} ${a} ${c} at ${u}:${l} (${r})`}function rr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}var cu=15/1e6;function su(t){return`$${((Number.isFinite(t)&&t>0?t:0)*cu).toFixed(2)}`}function un(t,e,r=40){if(e<=0)return"\u2591".repeat(r);let n=Math.max(1,Math.round(t/e*r));return"\u2588".repeat(Math.min(n,r))+"\u2591".repeat(Math.max(0,r-n))}function yE(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,o=[];o.push("");let s=e?.multiAdapter,i=s?.perAdapter.filter(h=>h.isReal).length??0,a=s?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=s?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";o.push(` All your work${h} \xB7 ${rr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${rr(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${rr(h)} sessions`,y=a*256+r;o.push(` ${rr(a)} events \xB7 ${g} \xB7 ~${su(y)} saved lifetime`)}o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:nu[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let f=d.slice(0,n),m=f.length>0?f[0].count:1;for(let h of f)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${un(h.count,m,30)}`);let p=Math.max(0,d.length-n);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function _E(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(` Preferences learned \xB7 ${t.autoMemoryCount} across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r){let i=wE[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${un(s,n,20)}`)}return e}function vE(t,e){let r=[],n=su(t),o=(e?.totalEvents??0)*256+t,s=su(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}var xE=256;function bE(t){if(!t)return[];let e=t.perAdapter.filter(o=>o.isReal),r=t.perAdapter.filter(o=>!o.isReal);if(e.length===0&&r.length===0)return[];let n=[];if(e.length>0){n.push(""),n.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),n.push("");let o=16,s=10,i=10,a=16;n.push(` ${"Tool".padEnd(o)}${"Captures".padStart(s)}${"Indexed".padStart(i)}${"Total kept out".padStart(a)}`);let c=[...e].sort((u,l)=>l.dataBytes+l.rescueBytes-(u.dataBytes+u.rescueBytes));for(let u of c){let l=u.dataBytes+u.rescueBytes,d=u.eventCount>0?rr(u.eventCount):"\u2014",f=Qe(u.dataBytes),m=Qe(l);n.push(` ${ou(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${m.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let o=r.map(s=>ou(s.name)).join(", ");n.push(` Skipped (${r.length}): ${o}`),n.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),n.push(" or detection probes \u2014 no real chat activity.")}return n}function uu(t,e,r,n){let o=[],s=Sz(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,l=n?.multiAdapter,d=l?.perAdapter.filter(R=>R.isReal).length??0;if(l&&d>0){let R=l.totalSessions||i?.totalSessions||0,N=i?.firstEventMs??0,C=N>0?Math.max(1,Math.round((Date.now()-N)/864e5)):0,M=C>0?`Across ${C} day${C===1?"":"s"} `:"",W=R>0?`you ran ${rr(R)} conversation${R===1?"":"s"} `:"you ran ",k;if(d>=2)k=`across ${d} AI tools`;else{let D=l.perAdapter.find(L=>L.isReal);k=`in ${D?ou(D.name):"Claude Code"}`}o.push(`${M}${W}${k}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let R=kz(),N=n?.cwd??process.cwd(),C=n?.now??Date.now(),M=n?.locale??R.locale,W=n?.tz??R.tz;return o.push(...wz({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:N,locale:M,tz:W,now:C,version:e,latestVersion:r})),o.join(`
553
+ `)}let f=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),m=t.savings.total_bytes_returned,p=t.savings.total_calls,h=f+m,g=h>0?f/h*100:0,y=Math.round(f/4),v=m>0?Math.max(1,Math.round(h/Math.max(m,1))):0;if(f===0){o.push(`context-mode ${s} ${p} calls`),o.push(""),p===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${Qe(m)} entered context | 0 tokens saved`),o.push(...yE(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...bE(l)),o.push(..._E(i)),o.push(...vE(0,i)),o.push("");let R=e?`v${e}`:"context-mode";return o.push(R),e&&r&&r!=="unknown"&&SE(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
554
+ `)}o.push(`${rr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${su(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${un(h,h)}| ${Qe(h)}`),o.push(`With context-mode |${un(m,h)}| ${Qe(m)}`),o.push(""),v>=2?o.push(`${Qe(f)} kept out of your conversation \u2014 ${v}\xD7 longer sessions before compact.`):o.push(`${Qe(f)} kept out of your conversation. Never entered context.`),o.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${Qe(t.cache.bytes_saved)})`),o.push(_.join(" \xB7 "));let b=t.savings.by_tool.filter(R=>R.calls>0);if(b.length>=2){o.push("");let R=b.map(N=>{let C=N.context_kb*1024,M=g<100?C/(1-g/100):C,W=Math.max(0,M-C);return{...N,returnedBytes:C,estimatedSaved:W}}).sort((N,C)=>C.estimatedSaved-N.estimatedSaved);for(let N of R){let C=N.tool.length>22?N.tool.slice(0,19)+"...":N.tool;o.push(` ${C.padEnd(22)} ${String(N.calls).padStart(4)} calls ${Qe(N.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let R=a.filter(N=>N.median_concurrency!=null&&(N.max_concurrency??1)>1);if(R.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let N of R){let C=N.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${C.padEnd(22)} ${N.calls} batches \xB7 ${N.median_concurrency} typical, ${N.max_concurrency} peak`)}}}o.push(...yE(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...bE(l)),o.push(..._E(i)),o.push(...vE(y,i)),o.push("");let E=e?`v${e}`:"context-mode";return o.push(E),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
555
+ `)}var wt=or(Dz(import.meta.url)),Mr=(()=>{for(let t of["../package.json","./package.json"]){let e=ze(wt,t);if(be(e))try{return JSON.parse(xu(e,"utf8")).version}catch{}}return"unknown"})();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
544
556
  `)}),process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
545
- `)}));var Ui=Pc(),cu=Hx(Ui),Ne=new kc({name:"context-mode",version:Dr}),fz=[];function mz(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??Ir().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??gz(r);return yz(n)&&_z(n)}function hz(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
557
+ `)}));var Fi=$c(),fu=Hb(Fi),Ne=new wc({name:"context-mode",version:Mr}),Lz=[];function Uz(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let r=t.platform??Ar().platform;if(r!=="opencode"&&r!=="kilo")return!1;let n=t.settings??Fz(r);return Zz(n)&&qz(n)}function Hz(t){let e="",r=!1,n=!1,o=!1;for(let s=0;s<t.length;s++){let i=t[s],a=t[s+1];if(o){i==="*"&&a==="/"&&(o=!1,s++);continue}if(n){e+=i,n=!1;continue}if(i==="\\"){e+=i,n=r;continue}if(i==='"'){r=!r,e+=i;continue}if(!r&&i==="/"&&a==="/"){for(;s<t.length&&t[s]!==`
546
558
  `;)s++;s<t.length&&(e+=`
547
- `);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function gz(t){let e=t==="kilo"?"kilo":"opencode",r=[je(`${e}.json`),je(`${e}.jsonc`),je(`.${e}`,`${e}.json`),je(`.${e}`,`${e}.jsonc`),Ce(zi(),".config",e,`${e}.json`),Ce(zi(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!we(n))continue;return JSON.parse(hz(hu(n,"utf8")))}catch{}return null}function yz(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function _z(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var IE=mz(),Ch=!1;function vz(t={}){if(Ch)return;Ch=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
548
- `)}function SV(){Ch=!1}function bz(t=Ne){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Eo,async()=>({tools:[]}))}var xz=Ne.registerTool.bind(Ne);Ne.registerTool=(...t)=>{let[e,r,n]=t;if(IE){vz();return}let o=Sz(e,n);return fz.push({name:e,config:r,handler:o}),t[2]=o,xz(...t)};function Sz(t,e){return async r=>{try{return await e(r)}catch(n){let o=Rz(n);if(o)try{return q(t,o)}catch(s){if(s instanceof nn)return o;throw s}throw n}}}IE&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&bz(Ne);var Nh=new pz;async function kV(t,e){let r=typeof t=="string"?{projectDir:t}:t;return Nh.run(r,e)}Ne.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ne.server.setRequestHandler(ko,async()=>({prompts:[]}));Ne.server.setRequestHandler(xo,async()=>({resources:[]}));Ne.server.setRequestHandler(So,async()=>({resourceTemplates:[]}));var Hi=new yi({runtimes:Ui,projectRoot:()=>sr()}),gu=Ce(Ah(),`cm-fs-preload-${process.pid}.js`);Ih(gu,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
549
- `);process.on("exit",()=>{try{cs(gu)}catch{}});var rr=null;function us(){let t=Nh.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??kz();if(e)return{sessionId:e}}var su;function kz(t){let e=Date.now();if(!t?.bypassCache&&su&&e-su.checkedAt<2e3)return su.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??at(),o=Ti({projectDir:r,sessionsDir:n});if(!we(o))return;let s=et(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(su={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function Ez(t){try{let e=at();if(!we(e))return;let r=rz(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=Ce(e,n);try{t.index({path:o,source:"session-events",attribution:us()}),cs(o)}catch{}}}catch{}}var ln=null,Nr=null;async function wz(){if(ln)return ln;try{let{getAdapter:t}=await Promise.resolve().then(()=>(ro(),Gc)),e=Ir();return await t(e.platform)}catch{return null}}function is(){if(ln)return ln.getSessionDir();try{let t=Ir(),e=Ii(t.platform);if(e)return gm({configDir:Ce(...e),configDirEnv:Tz(e)})}catch{}return gm({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function Tz(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function at(){return Mc(Ei(is))}function sr(){let t=Nh.getStore();if(t)return t.projectDir;let e,r;try{let n=Ir().platform;r=n,n==="claude-code"&&(e=Ce(zi(),".claude","projects"))}catch{}return sE({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r})}function Pz(t){return cz(t)?t:je(sr(),t)}function Li(){return Ti({projectDir:sr(),sessionsDir:at()})}function lu(){let t=Mc(ym(is));return xS({projectDir:sr(),contentDir:t})}function oo(){if(!rr){let t=lu();rr=new Ic(t),rr.setDenyChecker(e=>{try{let r=sr(),n=hh("Read",r);return yh(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=nr(lu());pm(e,14),rr.cleanupStaleSources(14);let r=Ce(zi(),".context-mode","content");we(r)&&pm(r,0)}catch{}dm()}return Ez(rr),rr}var re={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()};function Rz(t){return t instanceof nn?{content:[{type:"text",text:_S(t)}],isError:!0}:null}var Mr=null,iu=0,vE=0,$z=3,Cz=3600*1e3;async function bE(){return new Promise(t=>{let e=dz("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function Oz(){let t=ln?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function Iz(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function Az(){return!Mr||Mr==="unknown"?!1:Iz(Mr,Dr)}function Nz(){if(!Az())return!1;let t=Date.now();if(iu>=$z){if(t-vE<Cz)return!1;iu=0}return iu===0&&(vE=t),iu++,!0}var xE=!1;function Dz(){if(!xE){xE=!0;try{let t=St(),e=je(t,"plugins","installed_plugins.json");if(!we(e))return;let r=JSON.parse(hu(e,"utf-8")),n=je(t,"plugins","cache"),o=we(je(wt,"package.json"))?wt:nr(wt);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||we(c)||!je(c).startsWith(n+az))continue;try{iz(c).isSymbolicLink()&&cs(c)}catch{}let u=nr(c);we(u)||CE(u,{recursive:!0}),we(o)&&sz(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function q(t,e){if(Dz(),Nz()&&e.content.length>0){let n=Oz();e.content[0].text=`\u26A0\uFE0F context-mode v${Dr} outdated \u2192 v${Mr} available. Upgrade: ${n}
559
+ `);continue}if(!r&&i==="/"&&a==="*"){o=!0,s++;continue}e+=i}return e.replace(/,(\s*[}\]])/g,"$1")}function Fz(t){let e=t==="kilo"?"kilo":"opencode",r=[ze(`${e}.json`),ze(`${e}.jsonc`),ze(`.${e}`,`${e}.json`),ze(`.${e}`,`${e}.jsonc`),Te(ds(),".config",e,`${e}.json`),Te(ds(),".config",e,`${e}.jsonc`)];for(let n of r)try{if(!be(n))continue;return JSON.parse(Hz(xu(n,"utf8")))}catch{}return null}function Zz(t){let e=t?.plugin;return Array.isArray(e)&&e.some(r=>typeof r=="string"&&r.includes("context-mode"))}function qz(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var UE=Uz(),$h=!1;function Bz(t={}){if($h)return;$h=!0;let e=t.write??(n=>{process.stderr.write(n)}),r=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["context-mode"] in ${r}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
560
+ `)}function eW(){$h=!1}function Vz(t=Ne){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(wo,async()=>({tools:[]}))}var Wz=Ne.registerTool.bind(Ne);Ne.registerTool=(...t)=>{let[e,r,n]=t;if(UE){Bz();return}let o=Kz(e,n);return Lz.push({name:e,config:r,handler:o}),t[2]=o,Wz(...t)};function Kz(t,e){return async r=>{try{return await e(r)}catch(n){let o=eL(n);if(o)try{return q(t,o)}catch(s){if(s instanceof on)return o;throw s}throw n}}}UE&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&Vz(Ne);var Ah=new zz;async function tW(t,e){let r=typeof t=="string"?{projectDir:t}:t;return Ah.run(r,e)}Ne.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ne.server.setRequestHandler(Eo,async()=>({prompts:[]}));Ne.server.setRequestHandler(So,async()=>({resources:[]}));Ne.server.setRequestHandler(ko,async()=>({resourceTemplates:[]}));var Zi=new vi({runtimes:Fi,projectRoot:()=>Ht()}),bu=Te(Ih(),`cm-fs-preload-${process.pid}.js`);Oh(bu,`(function(){var __cm_fs=0;process.on('exit',function(){if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch(e){}});try{var f=require('fs');var ors=f.readFileSync;f.readFileSync=function(){var r=ors.apply(this,arguments);if(Buffer.isBuffer(r))__cm_fs+=r.length;else if(typeof r==='string')__cm_fs+=Buffer.byteLength(r);return r;};}catch(e){}})();
561
+ `);process.on("exit",()=>{try{ls(bu)}catch{}});var nr=null;function so(){let t=Ah.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??Gz();if(e)return{sessionId:e}}var lu;function Gz(t){let e=Date.now();if(!t?.bypassCache&&lu&&e-lu.checkedAt<2e3)return lu.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??He(),o=Pi({projectDir:r,sessionsDir:n});if(!be(o))return;let s=Ye(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(lu={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function Jz(t){try{let e=He();if(!be(e))return;let r=Pz(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=Te(e,n);try{t.index({path:o,source:"session-events",attribution:so()}),ls(o)}catch{}}}catch{}}var ln=null,Dr=null;async function Xz(){if(ln)return ln;try{let{getAdapter:t}=await Promise.resolve().then(()=>(no(),Xc)),e=Ar();return await t(e.platform)}catch{return null}}function cs(){if(ln)return ln.getSessionDir();try{let t=Ar(),e=Ni(t.platform);if(e)return vm({configDir:Te(...e),configDirEnv:Yz(e)})}catch{}return vm({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function Yz(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function He(){return zc(Ti(cs))}function Ht(){let t=Ah.getStore();if(t)return t.projectDir;let e,r,n;try{let o=Ar().platform;r=o,o==="claude-code"&&(e=Te(ds(),".claude","projects")),o==="codex"&&(n=process.env.CODEX_HOME??Te(ds(),".codex"))}catch{}return mE({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:r,codexHome:n})}function Qz(t){return Nz(t)?t:ze(Ht(),t)}function Hi(){return Pi({projectDir:Ht(),sessionsDir:He()})}function hu(){let t=zc(xm(cs));return TS({projectDir:Ht(),contentDir:t})}function dn(){if(!nr){let t=hu();nr=new Nc(t),nr.setDenyChecker(e=>{try{let r=Ht(),n=Yc("Read",r);return Qc(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=or(hu());hm(e,14),nr.cleanupStaleSources(14);let r=Te(ds(),".context-mode","content");be(r)&&hm(r,0)}catch{}mm()}return Jz(nr),nr}var re={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()};function eL(t){return t instanceof on?{content:[{type:"text",text:kS(t)}],isError:!0}:null}var jr=null,du=0,RE=0,tL=3,rL=3600*1e3;async function PE(){return new Promise(t=>{let e=jz("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function nL(){let t=ln?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function oL(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function sL(){return!jr||jr==="unknown"?!1:oL(jr,Mr)}function iL(){if(!sL())return!1;let t=Date.now();if(du>=tL){if(t-RE<rL)return!1;du=0}return du===0&&(RE=t),du++,!0}var $E=!1;function aL(){if(!$E){$E=!0;try{let t=St(),e=ze(t,"plugins","installed_plugins.json");if(!be(e))return;let r=JSON.parse(xu(e,"utf-8")),n=ze(t,"plugins","cache"),o=be(ze(wt,"package.json"))?wt:or(wt);for(let[s,i]of Object.entries(r.plugins??{}))if(s==="context-mode@context-mode")for(let a of i){let c=a.installPath;if(!c||be(c)||!ze(c).startsWith(n+Az))continue;try{Iz(c).isSymbolicLink()&&ls(c)}catch{}let u=or(c);be(u)||zE(u,{recursive:!0}),be(o)&&Oz(o,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function q(t,e){if(aL(),iL()&&e.content.length>0){let n=nL();e.content[0].text=`\u26A0\uFE0F context-mode v${Mr} outdated \u2192 v${jr} available. Upgrade: ${n}
550
562
 
551
- `+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return re.calls[t]=(re.calls[t]||0)+1,re.bytesReturned[t]=(re.bytesReturned[t]||0)+r,du(),setImmediate(()=>Xk(Li(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>Kk({sessionDbPath:Li(),toolName:t,bytesReturned:r})),e}function or(t,e="unknown"){re.bytesIndexed+=t,du(),t>0&&setImmediate(()=>Gk({sessionDbPath:Li(),source:e,bytesAvoided:t}))}var Mz=500,jz=2,zz=3e4,Lz=256,Oh=0,au;function AE(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=Mc(_m(is));return Ce(e,`stats-${t}.json`)}function du(){let t=Date.now();if(!(t-Oh<Mz)){Oh=t;try{let e=Object.values(re.bytesReturned).reduce((d,f)=>d+f,0),r=Object.values(re.calls).reduce((d,f)=>d+f,0),n=re.bytesIndexed+re.bytesSandboxed+re.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=au?.tokens??0;if(!au||t-au.computedAt>zz)try{a=(Mi({sessionsDir:at()})?.totalEvents??0)*Lz,au={tokens:a,computedAt:t}}catch{}let c={schemaVersion:jz,version:Dr,updated_at:t,session_start:re.sessionStart,uptime_ms:t-re.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:re.bytesIndexed,bytes_sandboxed:re.bytesSandboxed,cache_hits:re.cacheHits,cache_bytes_saved:re.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*nu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*nu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...re.calls,...re.bytesReturned}).map(d=>[d,{calls:re.calls[d]||0,bytes:re.bytesReturned[d]||0}]))},u=AE(),l=`${u}.tmp`;Ih(l,JSON.stringify(c)),nz(l,u)}catch{}}}function Dh(t,e){try{let r=mh(process.env.CLAUDE_PROJECT_DIR),n=gh(t,r);if(n.decision==="deny")return q(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function NE(t,e,r){try{let n=qk(t,e);if(n.length===0)return null;let o=mh(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=gh(s,o);if(i.decision==="deny")return q(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function DE(t,e){try{let r=sr(),n=hh("Read",r),o=yh(t,n,process.platform==="win32",r);if(o.denied)return q(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}var Uz=cu.join(", "),Hz=Rc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",Fz="",Zz="";function qz(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===Fz){for(e.push(r),n++;n<t.length&&t[n]!==Zz;)r++,n++;n<t.length&&n++}else r++,n++;return e}function ME(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of qz(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let f=l.indexOf(d);for(;f!==-1;)o.push(f),f=l.indexOf(d,f+1)}}if(o.length===0)return t.slice(0,r)+`
563
+ `+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return re.calls[t]=(re.calls[t]||0)+1,re.bytesReturned[t]=(re.bytesReturned[t]||0)+r,gu(),setImmediate(()=>iE(Hi(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>rE({sessionDbPath:Hi(),toolName:t,bytesReturned:r})),e}function sr(t,e="unknown"){re.bytesIndexed+=t,gu(),t>0&&setImmediate(()=>nE({sessionDbPath:Hi(),source:e,bytesAvoided:t}))}var cL=500,uL=2,lL=3e4,dL=256,Ch=0,pu;function HE(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=zc(bm(cs));return Te(e,`stats-${t}.json`)}function gu(){let t=Date.now();if(!(t-Ch<cL)){Ch=t;try{let e=Object.values(re.bytesReturned).reduce((d,f)=>d+f,0),r=Object.values(re.calls).reduce((d,f)=>d+f,0),n=re.bytesIndexed+re.bytesSandboxed+re.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=pu?.tokens??0;if(!pu||t-pu.computedAt>lL)try{a=(zi({sessionsDir:He()})?.totalEvents??0)*dL,pu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:uL,version:Mr,updated_at:t,session_start:re.sessionStart,uptime_ms:t-re.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:re.bytesIndexed,bytes_sandboxed:re.bytesSandboxed,cache_hits:re.cacheHits,cache_bytes_saved:re.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*cu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*cu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...re.calls,...re.bytesReturned}).map(d=>[d,{calls:re.calls[d]||0,bytes:re.bytesReturned[d]||0}]))},u=HE(),l=`${u}.tmp`;Oh(l,JSON.stringify(c)),$z(l,u)}catch{}}}function Nh(t,e){try{let r=yh(process.env.CLAUDE_PROJECT_DIR),n=_h(t,r);if(n.decision==="deny")return q(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function FE(t,e,r){try{let n=Yk(t,e);if(n.length===0)return null;let o=yh(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=_h(s,o);if(i.decision==="deny")return q(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function ZE(t,e){try{let r=Ht(),n=Yc("Read",r),o=Qc(t,n,process.platform==="win32",r);if(o.denied)return q(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}var pL=fu.join(", "),fL=Cc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",mL="",hL="";function gL(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===mL){for(e.push(r),n++;n<t.length&&t[n]!==hL;)r++,n++;n<t.length&&n++}else r++,n++;return e}function qE(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of gL(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let f=l.indexOf(d);for(;f!==-1;)o.push(f),f=l.indexOf(d,f+1)}}if(o.length===0)return t.slice(0,r)+`
552
564
  \u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=r)break;let d=t.slice(u,Math.min(l,u+(r-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
553
565
 
554
- `)}function Bz(t,e,r,n=80*1024){let o=[],s=0;for(let i of e){if(s>n){o.push(`## ${i}
566
+ `)}function yL(t,e,r,n=80*1024){let o=[],s=0;for(let i of e){if(s>n){o.push(`## ${i}
555
567
  (output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
556
- `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(o.push(`## ${i}`),o.push(""),a.length>0){for(let c of a){let u=ME(c.content,i,3e3,c.highlighted);o.push(`### ${c.title}`),o.push(u),o.push(""),s+=u.length+c.title.length}continue}o.push("No matching sections found."),o.push("")}return o.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),o}function Vz(t){return`'${t.replace(/'/g,"'\\''")}'`}function Wz(t){return`'${t.replace(/'/g,"''")}'`}function Kz(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${Wz(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${Vz(r)} `}function SE(t,e,r){let n=e||"(no output)",o=n.matchAll(/__CM_FS__:(\d+)/g),s=0;for(let i of o)s+=parseInt(i[1]);return s>0&&(r?.(s),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
568
+ `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(o.push(`## ${i}`),o.push(""),a.length>0){for(let c of a){let u=qE(c.content,i,3e3,c.highlighted);o.push(`### ${c.title}`),o.push(u),o.push(""),s+=u.length+c.title.length}continue}o.push("No matching sections found."),o.push("")}return o.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),o}function _L(t){return`'${t.replace(/'/g,"'\\''")}'`}function vL(t){return`'${t.replace(/'/g,"''")}'`}function xL(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${vL(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${_L(r)} `}function CE(t,e,r){let n=e||"(no output)",o=n.matchAll(/__CM_FS__:(\d+)/g),s=0;for(let i of o)s+=parseInt(i[1]);return s>0&&(r?.(s),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
557
569
 
558
570
  ${n}
559
- `}function kE(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
571
+ `}function OE(t){let e=t.stdout||"",r=t.stderr||"";return r?e?`${e}${e.endsWith(`
560
572
  `)?"":`
561
- `}${r}`:r:e}async function Gz(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let d=[],f=Date.now(),m=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let v=Date.now()-f,_=n-v;if(_<=0){d.push(`# ${h.label}
573
+ `}${r}`:r:e}async function bL(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let d=[],f=Date.now(),m=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let v=Date.now()-f,_=n-v;if(_<=0){d.push(`# ${h.label}
562
574
 
563
575
  (skipped \u2014 batch timeout exceeded)
564
- `),m=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${s}${h.command}`,timeout:g});if(d.push(SE(h.label,kE(y),i)),y.timedOut){m=!0;for(let v=p+1;v<t.length;v++)d.push(`# ${t[v].label}
576
+ `),m=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${s}${h.command}`,timeout:g});if(d.push(CE(h.label,OE(y),i)),y.timedOut){m=!0;for(let v=p+1;v<t.length;v++)d.push(`# ${t[v].label}
565
577
 
566
578
  (skipped \u2014 batch timeout exceeded)
567
- `);break}}return{outputs:d,timedOut:m}}let a=t.map(d=>({run:async()=>{let f=await r.execute({language:"shell",code:`${s}${d.command}`,timeout:n}),m=SE(d.label,kE(f),i);return{output:f.timedOut?m.replace(/\n$/,"")+`
579
+ `);break}}return{outputs:d,timedOut:m}}let a=t.map(d=>({run:async()=>{let f=await r.execute({language:"shell",code:`${s}${d.command}`,timeout:n}),m=CE(d.label,OE(f),i);return{output:f.timedOut?m.replace(/\n$/,"")+`
568
580
  (timed out after ${n??"?"}ms)
569
- `:m,timedOut:!!f.timedOut}}})),{settled:c}=await rm(a,{concurrency:o}),u=new Array(t.length),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(f.status==="fulfilled")u[d]=f.value.output,f.value.timedOut&&(l=!0);else{let m=f.reason instanceof Error?f.reason.message:String(f.reason);u[d]=`# ${t[d].label}
581
+ `:m,timedOut:!!f.timedOut}}})),{settled:c}=await sm(a,{concurrency:o}),u=new Array(t.length),l=!1;for(let d=0;d<c.length;d++){let f=c[d];if(f.status==="fulfilled")u[d]=f.value.output,f.value.timedOut&&(l=!0);else{let m=f.reason instanceof Error?f.reason.message:String(f.reason);u[d]=`# ${t[d].label}
570
582
 
571
583
  (executor error: ${m})
572
- `}}return{outputs:u,timedOut:l}}Ne.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${Hz} Languages: ${Uz}.
584
+ `}}return{outputs:u,timedOut:l}}Ne.registerTool("ctx_execute",{title:"Execute Code",description:`Run code in a sandboxed subprocess.${fL} Languages: ${pL}.
573
585
 
574
586
  Think-in-Code \u2014 the core philosophy: the bytes your code processes never enter your conversation memory; only what you console.log() does. Reading a 700 KB log directly means 700 KB of your remaining reasoning capacity gets spent on raw bytes. Running code over that same log in this sandbox and printing a 3 KB summary leaves you with 697 KB of capacity for the actual work.
575
587
 
@@ -600,9 +612,9 @@ RETURNS:
600
612
  Only what your code prints. Wrap risky calls in try/catch \u2014 uncaught errors go to stderr and may leak more than intended. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout; use ctx_search(queries: [...]) to drill into specific sections.
601
613
 
602
614
  EXAMPLE: ctx_execute(language: "shell", code: "npm test 2>&1 | grep -E '(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))' | head -60")
603
- EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:A.object({language:A.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:A.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:A.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:A.preprocess(Mh,A.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:A.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
615
+ EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('gh issue list --json number,title --limit 100', {encoding:'utf8'}); const hooks = JSON.parse(out).filter(i => /hook|routing/i.test(i.title)); console.log(\`\${hooks.length} hook-related issues\`)")`,inputSchema:$.object({language:$.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:$.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), IO.puts (Elixir), or Console.WriteLine (C#) to output a summary to context."),timeout:$.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:$.preprocess(Dh,$.boolean()).optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:$.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
604
616
 
605
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=Dh(e,"execute");if(s)return s}else{let s=NE(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
617
+ TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=Nh(e,"execute");if(s)return s}else{let s=FE(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
606
618
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
607
619
  let __cm_fs=0;
608
620
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -661,16 +673,16 @@ ${e}
661
673
  }
662
674
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
663
675
  setInterval(()=>{},2147483647);`:""}
664
- })(typeof require!=='undefined'?require:null);`);let i=await Hi.execute({language:t,code:s,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(re.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(re.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let l=i.stdout?.trim();return i.backgrounded&&l?q("ctx_execute",{content:[{type:"text",text:`${l}
676
+ })(typeof require!=='undefined'?require:null);`);let i=await Zi.execute({language:t,code:s,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(re.bytesSandboxed+=parseInt(a[1]),i.stderr=i.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let c=i.stderr?.match(/__CM_FS__:(\d+)/);if(c&&(re.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let l=i.stdout?.trim();return i.backgrounded&&l?q("ctx_execute",{content:[{type:"text",text:`${l}
665
677
 
666
678
  _(process backgrounded after ${r}ms \u2014 still running)_`}]}):l?q("ctx_execute",{content:[{type:"text",text:`${l}
667
679
 
668
680
  _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):q("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
669
681
 
670
682
  stderr:
671
- ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:l,output:d}=_h({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(d)>pu?(or(Buffer.byteLength(d)),q("ctx_execute",{content:[{type:"text",text:as(d,o,l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):Buffer.byteLength(d)>fu?(or(Buffer.byteLength(d)),q("ctx_execute",{content:[{type:"text",text:as(d,"errors failures exceptions",l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):q("ctx_execute",{content:[{type:"text",text:d}],isError:l})}let u=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(u)>pu?(or(Buffer.byteLength(u)),q("ctx_execute",{content:[{type:"text",text:as(u,o,`execute:${t}`)}]})):Buffer.byteLength(u)>fu?q("ctx_execute",jE(u,`execute:${t}`)):q("ctx_execute",{content:[{type:"text",text:u}]})}catch(s){let i=s instanceof Error?s.message:String(s);return q("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});function jE(t,e){let r=oo();or(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:us()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
672
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}var pu=5e3,fu=102400;function as(t,e,r,n=5){let o=t.split(`
673
- `).length,s=Buffer.byteLength(t),i=oo(),a=i.indexPlainText(t,r,void 0,us()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
683
+ ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:l,output:d}=vh({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(d)>yu?(sr(Buffer.byteLength(d)),q("ctx_execute",{content:[{type:"text",text:us(d,o,l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):Buffer.byteLength(d)>_u?(sr(Buffer.byteLength(d)),q("ctx_execute",{content:[{type:"text",text:us(d,"errors failures exceptions",l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):q("ctx_execute",{content:[{type:"text",text:d}],isError:l})}let u=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(u)>yu?(sr(Buffer.byteLength(u)),q("ctx_execute",{content:[{type:"text",text:us(u,o,`execute:${t}`)}]})):Buffer.byteLength(u)>_u?q("ctx_execute",BE(u,`execute:${t}`)):q("ctx_execute",{content:[{type:"text",text:u}]})}catch(s){let i=s instanceof Error?s.message:String(s);return q("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});function BE(t,e){let r=dn();sr(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:so()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
684
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}var yu=5e3,_u=102400;function us(t,e,r,n=5){let o=t.split(`
685
+ `).length,s=Buffer.byteLength(t),i=dn(),a=i.indexPlainText(t,r,void 0,so()),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
674
686
  `)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let f=d.content.split(`
675
687
  `)[0].slice(0,120);l.push(` - ${d.title}: ${f}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
676
688
  `)}Ne.registerTool("ctx_execute_file",{title:"Execute File Processing",description:`Read a file into a sandboxed FILE_CONTENT variable and run code over it. Only what you console.log() enters your conversation \u2014 the file bytes stay in the sandbox.
@@ -692,7 +704,7 @@ RETURNS:
692
704
  Only what your code prints. The FILE_CONTENT variable holds the raw bytes inside the sandbox; nothing else leaves. When \`intent\` is set and output exceeds the auto-index threshold, the response carries searchable section titles + previews instead of the raw stdout.
693
705
 
694
706
  EXAMPLE: ctx_execute_file(path: "huge.log", language: "javascript", code: "const errs = FILE_CONTENT.split('\\\\n').filter(l => /ERROR|FATAL/.test(l)); console.log(\`\${errs.length} error lines\`); console.log(errs.slice(-5).join('\\\\n'))")
695
- EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:A.object({path:A.string().describe("Absolute file path or relative to project root"),language:A.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:A.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:A.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:A.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=DE(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=Dh(r,"execute_file");if(i)return i}else{let i=NE(r,e,"execute_file");if(i)return i}try{let i=await Hi.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return q("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=_h({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(u)>pu?(or(Buffer.byteLength(u)),q("ctx_execute_file",{content:[{type:"text",text:as(u,o,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>fu?(or(Buffer.byteLength(u)),q("ctx_execute_file",{content:[{type:"text",text:as(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):q("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(a)>pu?(or(Buffer.byteLength(a)),q("ctx_execute_file",{content:[{type:"text",text:as(a,o,`file:${t}`)}]})):Buffer.byteLength(a)>fu?q("ctx_execute_file",jE(a,`file:${t}`)):q("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return q("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ne.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
707
+ EXAMPLE: ctx_execute_file(path: "data.csv", language: "javascript", code: "const rows = FILE_CONTENT.split('\\\\n'); console.log(\`rows: \${rows.length - 1}, header: \${rows[0]}\`)")`,inputSchema:$.object({path:$.string().describe("Absolute file path or relative to project root"),language:$.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir","csharp"]).describe("Runtime language"),code:$.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts/Console.WriteLine."),timeout:$.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:$.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=ZE(t,"ctx_execute_file");if(s)return s;if(e==="shell"){let i=Nh(r,"execute_file");if(i)return i}else{let i=FE(r,e,"execute_file");if(i)return i}try{let i=await Zi.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return q("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=vh({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(u)>yu?(sr(Buffer.byteLength(u)),q("ctx_execute_file",{content:[{type:"text",text:us(u,o,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>_u?(sr(Buffer.byteLength(u)),q("ctx_execute_file",{content:[{type:"text",text:us(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):q("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(a)>yu?(sr(Buffer.byteLength(a)),q("ctx_execute_file",{content:[{type:"text",text:us(a,o,`file:${t}`)}]})):Buffer.byteLength(a)>_u?q("ctx_execute_file",BE(a,`file:${t}`)):q("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return q("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ne.registerTool("ctx_index",{title:"Index Content",description:`Store content in a searchable knowledge base (BM25 over FTS5). Splits markdown by headings, keeps code blocks intact, and persists the raw chunks. The full content stays in storage \u2014 retrieve any section on-demand via ctx_search; nothing is summarized or truncated.
696
708
 
697
709
  WHEN:
698
710
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -710,21 +722,22 @@ RETURNS:
710
722
  Indexing metadata: chunk counts (total, code-bearing), source label, and the exact ctx_search call shape to query the indexed content. Raw content is NOT echoed back \u2014 it lives in storage, retrievable via ctx_search(source: "<label>"). When \`path\` is provided, a content hash is stored so ctx_search results auto-flag staleness on future calls.
711
723
 
712
724
  EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
713
- EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:A.object({content:A.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:A.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:A.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return q("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=DE(e,"ctx_index");if(n)return n}try{let n=e?Pz(e):void 0;if(t)or(Buffer.byteLength(t));else if(n)try{let i=await import("fs");or(i.readFileSync(n).byteLength)}catch{}let s=oo().index({content:t,path:n,source:r??n,attribution:us()});return q("ctx_index",{content:[{type:"text",text:`Indexed ${s.totalChunks} sections (${s.codeChunks} with code) from: ${s.label}
714
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${s.label}" to scope results.`}]})}catch(n){let o=n instanceof Error?n.message:String(n);return q("ctx_index",{content:[{type:"text",text:`Index error: ${o}`}],isError:!0})}});var no=0,Ph=Date.now(),Jz=6e4,EE=3,wE=8;function yu(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function Mh(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function Yz(t){let e=yu(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}Ne.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:A.object({queries:A.preprocess(yu,A.array(A.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:A.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:A.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:A.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:A.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=oo(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return q("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
725
+ EXAMPLE: ctx_index(path: "/path/to/large-spec.md", source: "openapi-v2-spec")`,inputSchema:$.object({content:$.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:$.string().optional().describe("File OR directory path to read and index (content never enters context). Provide this OR content. Directory paths trigger a bounded recursive walk (#687)."),source:$.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')"),include:$.array($.string()).optional().describe("Directory-only: glob patterns to include (default: all matching extensions)."),exclude:$.array($.string()).optional().describe("Directory-only: glob patterns to exclude. Merged with defaults (node_modules, .git, dist, build, .next, coverage, .venv, __pycache__, .DS_Store)."),maxDepth:$.number().int().min(0).optional().describe("Directory-only: max recursion depth from root (default: 5)."),maxFiles:$.number().int().min(1).optional().describe("Directory-only: hard cap on files indexed (default: 200) \u2014 FTS5 blow-up guard."),extensions:$.array($.string()).optional().describe("Directory-only: allowed file extensions (default: .md .mdx .txt .json .yaml .yml .ts .tsx .js .jsx .py .rs .go .sh)."),respectGitignore:$.boolean().optional().describe("Directory-only: apply nearest .gitignore (default: true)."),followSymlinks:$.boolean().optional().describe("Directory-only: follow directory symlinks (default: false \u2014 cycle hazard + escape risk).")})},async({content:t,path:e,source:r,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return q("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=ZE(e,"ctx_index");if(l)return l}try{let l=e?Qz(e):void 0;if(l&&be(l)&&Ph(l).isDirectory()){let m=dn(),p=Ht(),h=Yc("Read",p),g=process.platform==="win32",y=R=>{try{return Qc(R,h,g,p).denied}catch{return!1}},v=m.indexDirectory({path:l,source:r??l,attribution:so(),perFileDeny:y,include:n,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),_=v.capped?` (cap reached \u2014 only first ${v.filesIndexed} of ${v.totalSeen}+ files; raise maxFiles to index more)`:"",b=v.denied>0?` (${v.denied} file${v.denied===1?"":"s"} blocked by Read deny policy)`:"",E=v.failed>0?` (${v.failed} file${v.failed===1?"":"s"} failed to read)`:"";return q("ctx_index",{content:[{type:"text",text:`Indexed ${v.filesIndexed} file${v.filesIndexed===1?"":"s"} (${v.totalChunks} sections) from directory: ${v.label}${_}${b}${E}
726
+ Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)sr(Buffer.byteLength(t));else if(l)try{let m=await import("fs");sr(m.readFileSync(l).byteLength)}catch{}let f=dn().index({content:t,path:l,source:r??l,attribution:so()});return q("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
727
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${f.label}" to scope results.`}]})}catch(l){let d=l instanceof Error?l.message:String(l);return q("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});var oo=0,wh=Date.now(),SL=6e4,IE=3,AE=8;function Su(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let r=JSON.parse(t);if(Array.isArray(r))return r}catch{}return[t]}return t}function Dh(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function kL(t){let e=Su(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}Ne.registerTool("ctx_search",{title:"Search Indexed Content",description:'Search a unified knowledge base with a multi-strategy ranking pipeline. Two parallel matchers run on every query: a Porter-stemming matcher ("caching" finds "cached", "caches", "cach") and a trigram-substring matcher ("useEff" finds "useEffect"). Their ranked lists are merged via Reciprocal Rank Fusion, so a document that ranks well in both surfaces above one that wins only on a single strategy. Multi-term queries get an additional proximity-rerank pass that boosts passages where the query terms appear close together. Typos are corrected via Levenshtein distance and re-searched. Result snippets are window-extracted around the matched terms, not blindly truncated.\n\nThe knowledge base is unified: queries reach indexed content you stored (ctx_index, ctx_fetch_and_index, ctx_batch_execute output) AND auto-captured session memory written by hooks (decisions, errors, blockers, plans, user prompts, rejected approaches, tool failures, compaction guides \u2014 26 event categories). File-backed sources carry a content hash and auto-flag staleness when the source file changes.\n\nWHEN:\n - You want to recall something that exists in storage (recently indexed content, prior session events, auto-memory) instead of re-reading raw sources\n - You have multiple related questions about the same body of knowledge \u2014 batch every question into one call (the ranking pipeline runs per-query but the round-trip cost is paid once)\n - You want to scope the query to one labelled source (pass `source` \u2014 partial match is fine)\n - You want a chronological view across current session + prior sessions + persistent auto-memory (pass `sort: "timeline"` \u2014 the default `relevance` mode only ranks within the current session)\n - You want to filter ranked results by content shape (pass `contentType: "code"` to surface implementation snippets or `contentType: "prose"` to surface explanations)\n\nWHEN NOT:\n - The data you want to query has never been stored in the knowledge base AND no session memory has accumulated around it \u2014 capture first (run a gather-and-index call), then come back here to query\n - You have one ad-hoc question against data that is not in the knowledge base \u2014 answer it inline by running code in the sandbox tool; one round-trip instead of capture-then-query\n\nRETURNS:\n Per-query ranked sections with window-extracted snippets. Use 2-4 specific technical terms per query. Common session-memory source labels: `decision` (user corrections / preferences), `error` and `error-resolution` (past failures + their fixes), `blocker`, `plan`, `user-prompt`, `rejected-approach`, `compaction` (post-compact session guide). See ctx_stats for live category counts.\n\nEXAMPLE: ctx_search(queries: ["root cause", "proposed fix", "test coverage"], source: "issue-#683")\nEXAMPLE: ctx_search(queries: ["what did we decide about caching"], source: "decision", sort: "timeline")\nEXAMPLE: ctx_search(queries: ["useEffect cleanup pattern"], source: "react-docs", contentType: "code", limit: 5)\nEXAMPLE: ctx_search(queries: ["last user prompt", "active skills", "open blockers"], sort: "timeline")',inputSchema:$.object({queries:$.preprocess(Su,$.array($.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:$.coerce.number().optional().default(3).describe("Results per query (default: 3)"),source:$.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:$.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:$.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=dn(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return q("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
715
728
 
716
729
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
717
730
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
718
731
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
719
732
  \u2022 ctx_index(content, source) \u2014 manually index text content
720
733
 
721
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return q("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a}=t,c=Date.now();if(c-Ph>Jz&&(no=0,Ph=c),no++,no>wE)return q("ctx_search",{content:[{type:"text",text:`BLOCKED: ${no} search calls in ${Math.round((c-Ph)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let u=no>EE?1:Math.min(s,2),l=40*1024,d=0,f=[],m=null;if(r==="timeline")try{let g=at(),y=sr(),v=Ti({projectDir:y,sessionsDir:g});we(v)&&(m=new Xt({dbPath:v}))}catch{}let p=ln?.getConfigDir()??St();try{for(let g of o){if(d>l){f.push(`## ${g}
734
+ After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return q("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a}=t,c=Date.now();if(c-wh>SL&&(oo=0,wh=c),oo++,oo>AE)return q("ctx_search",{content:[{type:"text",text:`BLOCKED: ${oo} search calls in ${Math.round((c-wh)/1e3)}s. You're flooding context. STOP making individual search calls. Use ctx_batch_execute(commands, queries) for your next research step.`}],isError:!0});let u=oo>IE?1:Math.min(s,2),l=40*1024,d=0,f=[],m=null;if(r==="timeline")try{let g=He(),y=Ht(),v=Pi({projectDir:y,sessionsDir:g});be(v)&&(m=new Qt({dbPath:v}))}catch{}let p=ln?.getConfigDir()??St();try{for(let g of o){if(d>l){f.push(`## ${g}
722
735
  (output cap reached)
723
- `);continue}let y;if(r==="timeline"?y=nE({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:m,projectDir:sr(),configDir:p,adapter:ln??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){f.push(`## ${g}
724
- No results found.`);continue}let v=y.map((_,S)=>{let T=_.origin||"current-session",I=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",N=`--- [${T}${I?" | "+I:""} | ${_.source}] ---`,O=`### ${_.title}`,j=ME(_.content,g,1500,_.highlighted);return`${N}
725
- ${O}
736
+ `);continue}let y;if(r==="timeline"?y=dE({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:m,projectDir:Ht(),configDir:p,adapter:ln??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){f.push(`## ${g}
737
+ No results found.`);continue}let v=y.map((_,b)=>{let E=_.origin||"current-session",R=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",N=`--- [${E}${R?" | "+R:""} | ${_.source}] ---`,C=`### ${_.title}`,M=qE(_.content,g,1500,_.highlighted);return`${N}
738
+ ${C}
726
739
 
727
- ${j}`}).join(`
740
+ ${M}`}).join(`
728
741
 
729
742
  `);f.push(`## ${g}
730
743
 
@@ -734,10 +747,10 @@ ${v}`),d+=v.length}}finally{try{m?.close()}catch{}}let h=f.join(`
734
747
 
735
748
  `);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
736
749
 
737
- `+h),no>=EE&&(h+=`
750
+ `+h),oo>=IE&&(h+=`
738
751
 
739
- \u26A0 search call #${no}/${wE} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
740
- Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return q("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return q("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return q("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});var Rh=null,$h=null;function Xz(){return Rh||(Rh=$E(import.meta.url).resolve("turndown")),Rh}function Qz(){return $h||($h=$E(import.meta.url).resolve("turndown-plugin-gfm")),$h}function eL(t,e){let r=JSON.stringify(Xz()),n=JSON.stringify(Qz()),o=JSON.stringify(e),s=mu.toString(),i=mu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
752
+ \u26A0 search call #${oo}/${AE} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
753
+ Indexed sources: ${g.map(v=>`"${v.label}" (${v.chunkCount} sections)`).join(", ")}`:"";return q("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return q("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return q("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});var Th=null,Rh=null;function EL(){return Th||(Th=jE(import.meta.url).resolve("turndown")),Th}function wL(){return Rh||(Rh=jE(import.meta.url).resolve("turndown-plugin-gfm")),Rh}function TL(t,e){let r=JSON.stringify(EL()),n=JSON.stringify(wL()),o=JSON.stringify(e),s=vu.toString(),i=vu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
741
754
  var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
742
755
  const TurndownService = require(${r});
743
756
  const { gfm } = require(${n});
@@ -963,7 +976,7 @@ async function main() {
963
976
  emit('text', text);
964
977
  }
965
978
  main();
966
- `}var tL=1440*60*1e3,TE=3072;function rL(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function nL(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=mu(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function mu(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?mu(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function oL(t,e,r,n){let o=await nL(t);if(o)return o;if(!r&&n!==0){let i=oo(),a=fm(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=n??tL;if(l<d){let f=Math.floor(l/36e5),m=Math.floor(l/(60*1e3)),p=f>0?`${f}h ago`:m>0?`${m}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:p,ttlStr:rL(d)}}}}let s=Ce(Ah(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=eL(t,s),a=await Hi.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",f=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${f}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{u=hu(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{uu(s)}catch{}}}function sL(t){let e=oo(),r=fm(t.source,t.url),n=us(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),or(Buffer.byteLength(t.markdown));let s=t.markdown.length>TE?Vk(t.markdown,TE)+`
979
+ `}var RL=1440*60*1e3,NE=3072;function PL(t){if(t===0)return"0ms";let e=1440*60*1e3,r=3600*1e3,n=60*1e3;return t%e===0?`${t/e}d`:t%r===0?`${t/r}h`:t%n===0?`${t/n}m`:`${t}ms`}async function $L(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=vu(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){let o=n?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=n instanceof Error?n.message:String(n),a=s?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`DNS lookup failed for "${e.hostname}": ${i}${a}`,reason:"exit"}}return null}function vu(t){let e=t.indexOf("%"),r=e===-1?t:t.slice(0,e),n=r.toLowerCase();if(n.includes(":")){let a=n.match(/^::ffff:([\d.]+)$/);return a?vu(a[1]):n==="::"||n.startsWith("fe8")||n.startsWith("fe9")||n.startsWith("fea")||n.startsWith("feb")||n.startsWith("ff")?"block":n==="::1"||n.startsWith("fc")||n.startsWith("fd")?"private":"public"}if(!r.includes("."))return"block";let o=r.split(".").map(a=>parseInt(a,10));if(o.length!==4||o.some(a=>isNaN(a)||a<0||a>255))return"block";let[s,i]=o;return s===169&&i===254||s===0||s>=224?"block":s===127||s===10||s===172&&i>=16&&i<=31||s===192&&i===168?"private":"public"}async function CL(t,e,r,n){let o=await $L(t);if(o)return o;if(!r&&n!==0){let i=dn(),a=gm(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=n??RL;if(l<d){let f=Math.floor(l/36e5),m=Math.floor(l/(60*1e3)),p=f>0?`${f}h ago`:m>0?`${m}m ago`:"just now",h=c.chunkCount*1600;return{kind:"cached",label:c.label,chunkCount:c.chunkCount,estimatedBytes:h,ageStr:p,ttlStr:PL(d)}}}}let s=Te(Ih(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=TL(t,s),a=await Zi.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",f=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${f}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{u=xu(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{mu(s)}catch{}}}function OL(t){let e=dn(),r=gm(t.source,t.url),n=so(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,r,void 0,n):o=e.index({content:t.markdown,source:r,attribution:n}),sr(Buffer.byteLength(t.markdown));let s=t.markdown.length>NE?eE(t.markdown,NE)+`
967
980
 
968
981
  \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}Ne.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",description:`Fetches URL content, converts HTML to markdown (JSON is chunked by key paths, plain text indexed directly), persists it in a searchable knowledge base, and returns a small preview window per source. The raw page bytes never enter your conversation \u2014 they live in storage and you retrieve any section on-demand via ctx_search.
969
982
 
@@ -985,15 +998,15 @@ RETURNS:
985
998
  EXAMPLE: ctx_fetch_and_index(
986
999
  requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
987
1000
  concurrency: 5
988
- )`,inputSchema:A.object({url:A.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:A.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:A.preprocess(yu,A.array(A.object({url:A.string().describe("URL to fetch"),source:A.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:A.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:A.preprocess(Mh,A.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:A.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return q("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(k=>({run:()=>oL(k.url,k.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await rm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let k=0;k<l.length;k++){let z=l[k];if(z.status==="rejected"){let ct=z.reason instanceof Error?z.reason.message:String(z.reason);m.push({kind:"job_error",url:i[k].url,error:ct});continue}let F=z.value;if(F.kind==="cached"){re.cacheHits++,re.cacheBytesSaved+=F.estimatedBytes;let ct=F.estimatedBytes,yr=F.label;setImmediate(()=>Jk({sessionDbPath:Li(),source:yr,bytesAvoided:ct})),m.push({kind:"cached",label:F.label,chunkCount:F.chunkCount,ageStr:F.ageStr,ttlStr:F.ttlStr})}else F.kind==="fetch_error"?m.push({kind:"fetch_error",url:F.url,error:F.error,reason:F.reason}):m.push({kind:"fetched",indexed:sL(F)})}if(a){let k=m[0];if(k.kind==="cached")return q("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${k.label}** \u2014 ${k.chunkCount} sections, indexed ${k.ageStr} (fresh, TTL: ${k.ttlStr}).
1001
+ )`,inputSchema:$.object({url:$.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:$.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:$.preprocess(Su,$.array($.object({url:$.string().describe("URL to fetch"),source:$.string().optional().describe("Label for this URL's indexed content")})).min(1)).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:$.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:$.preprocess(Dh,$.boolean()).optional().describe("Skip cache and re-fetch even if content was recently indexed"),ttl:$.coerce.number().int().min(0).optional().describe("Override the cache freshness window for this call, in milliseconds. `ttl: 0` bypasses the cache like `force: true`; omit to use the default 24h TTL.")})},async({url:t,source:e,requests:r,concurrency:n,force:o,ttl:s})=>{let i=r||(t?[{url:t,source:e}]:[]);if(i.length===0)return q("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let a=!r&&i.length===1,c=n??1,u=i.map(k=>({run:()=>CL(k.url,k.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await sm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let k=0;k<l.length;k++){let D=l[k];if(D.status==="rejected"){let qe=D.reason instanceof Error?D.reason.message:String(D.reason);m.push({kind:"job_error",url:i[k].url,error:qe});continue}let L=D.value;if(L.kind==="cached"){re.cacheHits++,re.cacheBytesSaved+=L.estimatedBytes;let qe=L.estimatedBytes,yr=L.label;setImmediate(()=>oE({sessionDbPath:Hi(),source:yr,bytesAvoided:qe})),m.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr,ttlStr:L.ttlStr})}else L.kind==="fetch_error"?m.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):m.push({kind:"fetched",indexed:OL(L)})}if(a){let k=m[0];if(k.kind==="cached")return q("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${k.label}** \u2014 ${k.chunkCount} sections, indexed ${k.ageStr} (fresh, TTL: ${k.ttlStr}).
989
1002
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
990
1003
 
991
1004
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
992
- Use: ctx_search(queries: [...], source: "${k.label}")`}]});if(k.kind==="fetched"){let z=(k.indexed.totalBytes/1024).toFixed(1),F=[`Fetched and indexed **${k.indexed.totalChunks} sections** (${z}KB) from: ${k.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${k.indexed.label}") for specific lookups.`,"","---","",k.indexed.preview].join(`
993
- `);return q("ctx_fetch_and_index",{content:[{type:"text",text:F}]})}if(k.kind==="fetch_error"){let z=k.reason==="empty"?`Fetched ${k.url} but got empty content`:k.reason==="read"?`Fetched ${k.url} but could not read subprocess output`:k.reason==="exit"?`Failed to fetch ${k.url}: ${k.error}`:`Fetch error: ${k.error}`;return q("ctx_fetch_and_index",{content:[{type:"text",text:z}],isError:!0})}return q("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${k.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,v=0,_=0,S=0,T=[];for(let k of m)if(k.kind==="cached")v++,h.push(`- [cache] ${k.label} \u2014 ${k.chunkCount} sections (${k.ageStr}, TTL: ${k.ttlStr})`);else if(k.kind==="fetched"){_++,g+=k.indexed.totalChunks,y+=k.indexed.totalBytes;let z=(k.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${k.indexed.label} \u2014 ${k.indexed.totalChunks} sections (${z}KB)`);let F=k.indexed.preview.length>p?k.indexed.preview.slice(0,p).trimEnd()+"\u2026":k.indexed.preview;T.push(`### ${k.indexed.label}
1005
+ Use: ctx_search(queries: [...], source: "${k.label}")`}]});if(k.kind==="fetched"){let D=(k.indexed.totalBytes/1024).toFixed(1),L=[`Fetched and indexed **${k.indexed.totalChunks} sections** (${D}KB) from: ${k.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${k.indexed.label}") for specific lookups.`,"","---","",k.indexed.preview].join(`
1006
+ `);return q("ctx_fetch_and_index",{content:[{type:"text",text:L}]})}if(k.kind==="fetch_error"){let D=k.reason==="empty"?`Fetched ${k.url} but got empty content`:k.reason==="read"?`Fetched ${k.url} but could not read subprocess output`:k.reason==="exit"?`Failed to fetch ${k.url}: ${k.error}`:`Fetch error: ${k.error}`;return q("ctx_fetch_and_index",{content:[{type:"text",text:D}],isError:!0})}return q("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${k.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,v=0,_=0,b=0,E=[];for(let k of m)if(k.kind==="cached")v++,h.push(`- [cache] ${k.label} \u2014 ${k.chunkCount} sections (${k.ageStr}, TTL: ${k.ttlStr})`);else if(k.kind==="fetched"){_++,g+=k.indexed.totalChunks,y+=k.indexed.totalBytes;let D=(k.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${k.indexed.label} \u2014 ${k.indexed.totalChunks} sections (${D}KB)`);let L=k.indexed.preview.length>p?k.indexed.preview.slice(0,p).trimEnd()+"\u2026":k.indexed.preview;E.push(`### ${k.indexed.label}
994
1007
 
995
- ${F}`)}else S++,h.push(`- [err] ${k.url}: ${k.error}`);let I=(y/1024).toFixed(1),N=f?` cap=${d}/${lz().length}cpu`:"",O=(k,z,F)=>`${k} ${k===1?z:F}`,K=[`fetched ${i.length} c=${d}${N}. ok=${_} cache=${v} err=${S}. ${O(g,"section","sections")} ${I}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...T.length>0?["","---","",...T]:[]].join(`
996
- `);return q("ctx_fetch_and_index",{content:[{type:"text",text:K}],isError:S===i.length})});Ne.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
1008
+ ${L}`)}else b++,h.push(`- [err] ${k.url}: ${k.error}`);let R=(y/1024).toFixed(1),N=f?` cap=${d}/${Mz().length}cpu`:"",C=(k,D,L)=>`${k} ${k===1?D:L}`,W=[`fetched ${i.length} c=${d}${N}. ok=${_} cache=${v} err=${b}. ${C(g,"section","sections")} ${R}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...E.length>0?["","---","",...E]:[]].join(`
1009
+ `);return q("ctx_fetch_and_index",{content:[{type:"text",text:W}],isError:b===i.length})});Ne.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
997
1010
 
998
1011
  Concurrency parallelizes the FETCH phase (run-the-commands). The DERIVATION phase \u2014 turning raw output into an answer \u2014 still belongs in code: add a processing command that consumes the indexed output and prints only the answer, so the raw bytes never enter your conversation (Think-in-Code, same principle as the sandbox tool).
999
1012
 
@@ -1018,13 +1031,13 @@ EXAMPLE: ctx_batch_execute(
1018
1031
  ],
1019
1032
  queries: ["root cause", "proposed fix"],
1020
1033
  concurrency: 2
1021
- )`,inputSchema:A.object({commands:A.preprocess(Yz,A.array(A.object({label:A.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:A.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:A.preprocess(yu,A.array(A.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:A.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:A.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let o of t){let s=Dh(o.command,"batch_execute");if(s)return s}try{let o=Kz(Ui.shell,gu),{outputs:s,timedOut:i}=await Gz(t,{timeout:r,concurrency:n,nodeOptsPrefix:o,onFsBytes:_=>{re.bytesSandboxed+=_}},Hi),a=s.join(`
1034
+ )`,inputSchema:$.object({commands:$.preprocess(kL,$.array($.object({label:$.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:$.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:$.preprocess(Su,$.array($.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:$.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:$.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let o of t){let s=Nh(o.command,"batch_execute");if(s)return s}try{let o=xL(Fi.shell,bu),{outputs:s,timedOut:i}=await bL(t,{timeout:r,concurrency:n,nodeOptsPrefix:o,onFsBytes:_=>{re.bytesSandboxed+=_}},Zi),a=s.join(`
1022
1035
  `),c=Buffer.byteLength(a),u=a.split(`
1023
- `).length;if(i&&s.length===0)return q("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});or(c);let l=oo(),d=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,f=l.index({content:a,source:d,attribution:us()}),m=l.getChunksBySource(f.sourceId),p=["## Indexed Sections",""],h=[];for(let _ of m){let S=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(S/1024).toFixed(1)}KB)`),h.push(_.title)}let g=Bz(l,e,d),y=l.getDistinctiveTerms?l.getDistinctiveTerms(f.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${f.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
1036
+ `).length;if(i&&s.length===0)return q("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});sr(c);let l=dn(),d=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,f=l.index({content:a,source:d,attribution:so()}),m=l.getChunksBySource(f.sourceId),p=["## Indexed Sections",""],h=[];for(let _ of m){let b=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(b/1024).toFixed(1)}KB)`),h.push(_.title)}let g=yL(l,e,d),y=l.getDistinctiveTerms?l.getDistinctiveTerms(f.sourceId):[],v=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${f.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
1024
1037
  Searchable terms for follow-up: ${y.join(", ")}`:""].join(`
1025
- `);return q("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(o){let s=o instanceof Error?o.message:String(o);return q("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${s}`}],isError:!0})}});function PE(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Ne.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:A.object({})},async()=>{let t;try{let e=sr(),r=st(e),n=Ti({projectDir:e,sessionsDir:at()});if(we(n)){let o=et(),s=new o(n,{readonly:!0});try{let i=new ss(s),a=i.queryAll(re),c=i.getMcpToolUsage(),u=Mi({sessionsDir:at()}),l;try{l=ru()}catch{}let d,f;try{let m=process.env.CLAUDE_SESSION_ID;if(m||(m=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),m){d=mE({sessionId:m,sessionsDir:at(),worktreeHash:r});let p=lu(),h=Th({sessionId:m,sessionsDir:at(),worktreeHash:r,contentDbPath:p}),g=Th({sessionsDir:at()}),y=hE(p),v={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};f={conversation:h,lifetime:v}}}catch{}t=ou(a,Dr,Mr,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,cwd:e})}finally{s.close()}}else{let s=new ss(PE()).queryAll(re),i=Mi({sessionsDir:at()}),a;try{a=ru()}catch{}t=ou(s,Dr,Mr,{lifetime:i,multiAdapter:a})}}catch{let r=new ss(PE()).queryAll(re),n;try{n=Mi({sessionsDir:at()})}catch{}let o;try{o=ru()}catch{}t=ou(r,Dr,Mr,n||o?{lifetime:n,multiAdapter:o}:void 0)}return q("ctx_stats",{content:[{type:"text",text:t}]})});Ne.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:A.object({})},async()=>{let t=["context-mode doctor",""],e=we(je(wt,"package.json"))?wt:nr(wt),r=11,n=(cu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${cu.length}/${r} (${n}%) \u2014 ${cu.join(", ")}`),Rc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=Ei(is),s=ym(is),i=_m(is);t.push(`[OK] Storage sessions: ${o.path} (${Dc(o)})`),t.push(`[OK] Storage content: ${s.path} (${Dc(s)})`),t.push(`[OK] Storage stats: ${i.path} (${Dc(i)})`);{let c=new yi({runtimes:Ui});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let l=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${l}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=et();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let l=c.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();l&&l.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await wz();if(a){for(let u of a.validateHooks(e)){let l=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",d=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${l} ${u.check}: ${u.message}${d}`)}let c=oE(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let l=je(e,u);we(l)?t.push(`[OK] Hook script: PASS \u2014 ${l}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${l}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Dr}`),q("ctx_doctor",{content:[{type:"text",text:t.join(`
1026
- `)}]})});Ne.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:A.object({})},async()=>{let t=we(je(wt,"package.json"))?wt:nr(wt),e=je(t,"cli.bundle.mjs"),r=je(t,"build","cli.js");try{let i=at(),a=Ce(nr(i),"insight-cache");we(a)&&(zE(4747),uu(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(ro(),Gc)),a=Ne.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let o;if(we(e))o=`${Ie(e)} upgrade${n}`;else if(we(r))o=`${Ie(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
1027
- `),c=je(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),o=Ie(c)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",o,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
1038
+ `);return q("ctx_batch_execute",{content:[{type:"text",text:v}]})}catch(o){let s=o instanceof Error?o.message:String(o);return q("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${s}`}],isError:!0})}});function DE(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Ne.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:$.object({})},async()=>{let t;try{let e=Ht(),r=ct(e),n=Pi({projectDir:e,sessionsDir:He()});if(be(n)){let o=Ye(),s=new o(n,{readonly:!0});try{let i=new as(s),a=i.queryAll(re),c=i.getMcpToolUsage(),u=zi({sessionsDir:He()}),l;try{l=au()}catch{}let d,f;try{let m=process.env.CLAUDE_SESSION_ID;if(m||(m=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),m){d=kE({sessionId:m,sessionsDir:He(),worktreeHash:r});let p=hu(),h;try{let _=Ye(),b=(await import("node:fs")).readdirSync(He()).filter(R=>R.endsWith(".db")&&(!r||R.startsWith(r))),E;for(let R of b)try{let N=new _((await import("node:path")).join(He(),R),{readonly:!0});try{let C=N.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(m);if(C?.project_dir){E=C.project_dir;break}}finally{N.close()}}catch{}h=E?Li({projectDir:E,sessionsDir:He(),worktreeHash:r,contentDbPath:p}):Li({sessionId:m,sessionsDir:He(),worktreeHash:r,contentDbPath:p})}catch{h=Li({sessionId:m,sessionsDir:He(),worktreeHash:r,contentDbPath:p})}let g=Li({sessionsDir:He()}),y=EE(p),v={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};f={conversation:h,lifetime:v}}}catch{}t=uu(a,Mr,jr,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,cwd:e})}finally{s.close()}}else{let s=new as(DE()).queryAll(re),i=zi({sessionsDir:He()}),a;try{a=au()}catch{}t=uu(s,Mr,jr,{lifetime:i,multiAdapter:a})}}catch{let r=new as(DE()).queryAll(re),n;try{n=zi({sessionsDir:He()})}catch{}let o;try{o=au()}catch{}t=uu(r,Mr,jr,n||o?{lifetime:n,multiAdapter:o}:void 0)}return q("ctx_stats",{content:[{type:"text",text:t}]})});Ne.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:$.object({})},async()=>{let t=["context-mode doctor",""],e=be(ze(wt,"package.json"))?wt:or(wt),r=11,n=(fu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${fu.length}/${r} (${n}%) \u2014 ${fu.join(", ")}`),Cc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let o=Ti(cs),s=xm(cs),i=bm(cs);t.push(`[OK] Storage sessions: ${o.path} (${jc(o)})`),t.push(`[OK] Storage content: ${s.path} (${jc(s)})`),t.push(`[OK] Storage stats: ${i.path} (${jc(i)})`);{let c=new vi({runtimes:Fi});try{let u=await c.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(u.exitCode===0&&u.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let l=u.stderr?.trim()?` (${u.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${u.exitCode}${l}`)}}catch(u){t.push(`[FAIL] Server test: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{c.cleanupBackgrounded()}}{let c;try{let u=Ye();c=new u(":memory:"),c.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),c.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let l=c.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();l&&l.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(u){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${u instanceof Error?u.message:u}`)}finally{try{c?.close()}catch{}}}let a=await Xz();if(a){for(let u of a.validateHooks(e)){let l=u.status==="pass"?"[OK]":u.status==="warn"?"[WARN]":"[FAIL]",d=u.fix?` \u2014 fix: ${u.fix}`:"";t.push(`${l} ${u.check}: ${u.message}${d}`)}let c=pE(a,e);c.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let u of c){let l=ze(e,u);be(l)?t.push(`[OK] Hook script: PASS \u2014 ${l}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${l}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Mr}`),q("ctx_doctor",{content:[{type:"text",text:t.join(`
1039
+ `)}]})});Ne.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:$.object({})},async()=>{let t=be(ze(wt,"package.json"))?wt:or(wt),e=ze(t,"cli.bundle.mjs"),r=ze(t,"build","cli.js");try{let i=He(),a=Te(or(i),"insight-cache");be(a)&&(VE(4747),mu(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(no(),Xc)),a=Ne.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let o;if(be(e))o=`${Ie(e)} upgrade${n}`;else if(be(r))o=`${Ie(r)} upgrade${n}`;else{let a=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync}from"node:fs";','import{join}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(t)};`,'const T=mkdtempSync(join(tmpdir(),"ctx-upgrade-"));',"try{",'console.log("- [x] Starting inline upgrade (no CLI found)");','execFileSync("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"for(const item of items){const from=join(T,item);const to=join(P,item);if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true});}}",'console.log("- [x] Copied package files");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install","--production"],{cwd:P,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Installed production dependencies");','console.log("## context-mode upgrade complete");',"}catch(e){",'console.error("- [ ] Upgrade failed:",e.message);',"process.exit(1);","}finally{","try{rmSync(T,{recursive:true,force:true})}catch{}","}"].join(`
1040
+ `),c=ze(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),o=Ie(c)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",o,"```","","After the command completes, display results as a markdown checklist:","- `[x]` for success, `[ ]` for failure","- Example format:"," ```"," ## context-mode upgrade"," - [x] Pulled latest from GitHub"," - [x] Built and installed v0.9.24"," - [x] npm global updated"," - [x] Hooks configured"," - [x] Doctor: all checks PASS"," ```","- Tell the user to restart their session to pick up the new version."].join(`
1028
1041
  `);return q("ctx_upgrade",{content:[{type:"text",text:s}]})});Ne.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
1029
1042
 
1030
1043
  WHEN:
@@ -1049,14 +1062,14 @@ RETURNS:
1049
1062
  A summary of removed rows + the resolved scope.
1050
1063
 
1051
1064
  EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
1052
- EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:A.object({confirm:A.preprocess(Mh,A.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:A.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:A.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return q("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return q("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=lu()}catch{}if(rr){try{rr.cleanup()}catch{}rr=null}let s=o?nr(o):void 0,{deleted:i}=Wk({projectDir:sr(),sessionsDir:at(),storePath:o,contentDir:s,legacyContentDir:Ce(zi(),".context-mode","content"),contentHash:$r(sr()),scope:n,sessionId:e});if(n==="project"){re.calls={},re.bytesReturned={},re.bytesIndexed=0,re.bytesSandboxed=0,re.cacheHits=0,re.cacheBytesSaved=0,re.sessionStart=Date.now(),i.push("session stats");try{let c=AE();we(c)&&cs(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return q("ctx_purge",{content:[{type:"text",text:a}]})});var ji=5e3;function iL(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function RE(t,e=process.platform,r=OE){let n=iL(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:ji});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function zE(t,e=process.platform,r=OE){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ji});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],f=u[2],m=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(f!=="0.0.0.0:0"&&f!=="[::]:0"||/^\d+$/.test(m)&&i.add(m))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ji});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:ji});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:ji});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}Ne.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:A.object({port:A.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:A.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:A.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:A.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:A.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=we(je(wt,"package.json"))?wt:nr(wt),u=je(c,"insight"),l=i?je(i):at(),d=a?je(a):Ce(nr(l),"content"),f=Ce(nr(l),"insight-cache");if(!we(Ce(u,"server.mjs")))return q("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let m=[],p=!1;CE(f,{recursive:!0});let h=yE(Ce(u,"server.mjs")).mtimeMs,g=we(Ce(f,"server.mjs"))?yE(Ce(f,"server.mjs")).mtimeMs:0;if(h>g&&(m.push("Copying source files..."),oz(u,f,{recursive:!0,force:!0}),m.push("Source files copied."),p=!0),!we(Ce(f,"node_modules"))||p){m.push("Installing dependencies (first run, ~30s)...");try{_E(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:f,stdio:"pipe",timeout:3e5})}catch{try{uu(Ce(f,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!we(Ce(f,"node_modules","vite"))||!we(Ce(f,"node_modules","better-sqlite3")))throw uu(Ce(f,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");m.push("Dependencies installed.")}m.push("Building dashboard..."),_E("npx vite build",{cwd:f,stdio:"pipe",timeout:6e4}),m.push("Build complete.");let v=!1;try{let{request:O}=await import("node:http");await new Promise((j,K)=>{let k=O(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},z=>{z.resume(),j()});k.on("error",()=>K()),k.on("timeout",()=>{k.destroy(),K()}),k.end()}),v=!0}catch{}if(v&&p){m.push("Killing stale dashboard server (source updated)...");let O=zE(s);if(O.attemptedPids.length>0&&O.killedPids.length===0)return q("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${O.attemptedPids.join(", ")}: ${O.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(O.errors.length>0&&O.attemptedPids.length===0)return q("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${O.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(j=>setTimeout(j,500)),m.push(`Stale server killed (${O.killedPids.length} pid${O.killedPids.length===1?"":"s"}).`)}else if(v){m.push("Dashboard already running.");let O=`http://localhost:${s}`,j=RE(O),K=j.ok?"":` (auto-open failed: ${j.reason}; navigate manually)`;return q("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${O}${K}`}]})}if(Nr&&Nr.pid&&!Nr.killed)try{Nr.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),S=_("node",[Ce(f,"server.mjs")],{cwd:f,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:l,INSIGHT_CONTENT_DIR:d,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});S.on("error",()=>{}),S.unref(),Nr=S,await new Promise(O=>setTimeout(O,1500));try{let{request:O}=await import("node:http");await new Promise((j,K)=>{let k=O(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},z=>{j(),z.resume()});k.on("error",K),k.on("timeout",()=>{k.destroy(),K(new Error("timeout"))}),k.end()})}catch{return q("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
1065
+ EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(Dh,$.boolean()).describe("MUST be true. Destructive operation; false returns 'purge cancelled'."),sessionId:$.string().optional().describe("UUID of a single session. Pairs with confirm:true to wipe only that session's events + per-session FTS5 chunks. Sibling sessions and the stats file are preserved. MUST NOT be combined with scope:'project'."),scope:$.enum(["session","project"]).optional().describe("Explicit scope selector. 'session' REQUIRES sessionId. 'project' wipes the entire project (FTS5 + every session + stats). Omit only for the deprecated bare-{confirm:true} back-compat path.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return q("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return q("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let o;try{o=hu()}catch{}if(nr){try{nr.cleanup()}catch{}nr=null}let s=o?or(o):void 0,{deleted:i}=tE({projectDir:Ht(),sessionsDir:He(),storePath:o,contentDir:s,legacyContentDir:Te(ds(),".context-mode","content"),contentHash:$r(Ht()),scope:n,sessionId:e});if(n==="project"){re.calls={},re.bytesReturned={},re.bytesIndexed=0,re.bytesSandboxed=0,re.cacheHits=0,re.cacheBytesSaved=0,re.sessionStart=Date.now(),i.push("session stats");try{let c=HE();be(c)&&ls(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return q("ctx_purge",{content:[{type:"text",text:a}]})});var Ui=5e3;function IL(t,e){return e==="darwin"?[{cmd:"open",args:[t]}]:e==="win32"?[{cmd:"cmd",args:["/c","start","",t]}]:[{cmd:"xdg-open",args:[t]},{cmd:"sensible-browser",args:[t]}]}function ME(t,e=process.platform,r=LE){let n=IL(t,e),o=[];for(let{cmd:s,args:i}of n)try{let a=r(s,i,{stdio:"ignore",timeout:Ui});if(!a.error&&a.status===0)return{ok:!0,method:s};let c=a.error?.message??`status=${a.status===null?"signaled":a.status}`;o.push(`${s}: ${c}`)}catch(a){o.push(`${s}: ${a instanceof Error?a.message:String(a)}`)}return{ok:!1,method:"none",reason:o.join("; ")}}function VE(t,e=process.platform,r=LE){let n={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return n.errors.push(`invalid port: ${t}`),n;try{if(e==="win32"){let o=r("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ui});if(o.error)return n.errors.push(`netstat: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=`:${t}`,i=new Set;for(let a of o.stdout.split(/\r?\n/)){let c=a.trim();if(!c)continue;let u=c.split(/\s+/);if(u.length<5)continue;let l=u[0],d=u[1],f=u[2],m=u[u.length-1];l==="TCP"&&d.endsWith(s)&&(f!=="0.0.0.0:0"&&f!=="[::]:0"||/^\d+$/.test(m)&&i.add(m))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Ui});c.error||c.status!==0?n.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):n.killedPids.push(a)}catch(c){n.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=r("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:Ui});if(o.error)return n.errors.push(`lsof: ${o.error.message}`),n;if(o.status!==0||typeof o.stdout!="string")return n;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){n.attemptedPids.push(i);try{let a=r("kill",[i],{stdio:"ignore",timeout:Ui});a.error||a.status!==0?n.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):n.killedPids.push(i)}catch(a){n.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){n.errors.push(o instanceof Error?o.message:String(o))}return n}Ne.registerTool("ctx_insight",{title:"Open Insight Dashboard",description:"Opens the context-mode Insight dashboard in the browser. Shows personal analytics: session activity, tool usage, error rate, parallel work patterns, project focus, and actionable insights. First run installs dependencies (~30s). Subsequent runs open instantly. Defaults to port 4747; pass `port` to override. `sessionDir` and `contentDir` override the session/content storage roots (env aliases INSIGHT_SESSION_DIR / INSIGHT_CONTENT_DIR) for diagnosing multi-install setups or pointing at a sibling project's data.",inputSchema:$.object({port:$.coerce.number().int().min(1).max(65535).optional().describe("Port to serve on (default: 4747)"),sessionDir:$.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:$.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:$.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:$.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=be(ze(wt,"package.json"))?wt:or(wt),u=ze(c,"insight"),l=i?ze(i):He(),d=a?ze(a):Te(or(l),"content"),f=Te(or(l),"insight-cache");if(!be(Te(u,"server.mjs")))return q("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let m=[],p=!1;zE(f,{recursive:!0});let h=Ph(Te(u,"server.mjs")).mtimeMs,g=be(Te(f,"server.mjs"))?Ph(Te(f,"server.mjs")).mtimeMs:0;if(h>g&&(m.push("Copying source files..."),Cz(u,f,{recursive:!0,force:!0}),m.push("Source files copied."),p=!0),!be(Te(f,"node_modules"))||p){m.push("Installing dependencies (first run, ~30s)...");try{TE(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:f,stdio:"pipe",timeout:3e5})}catch{try{mu(Te(f,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!be(Te(f,"node_modules","vite"))||!be(Te(f,"node_modules","better-sqlite3")))throw mu(Te(f,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");m.push("Dependencies installed.")}m.push("Building dashboard..."),TE("npx vite build",{cwd:f,stdio:"pipe",timeout:6e4}),m.push("Build complete.");let v=!1;try{let{request:C}=await import("node:http");await new Promise((M,W)=>{let k=C(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},D=>{D.resume(),M()});k.on("error",()=>W()),k.on("timeout",()=>{k.destroy(),W()}),k.end()}),v=!0}catch{}if(v&&p){m.push("Killing stale dashboard server (source updated)...");let C=VE(s);if(C.attemptedPids.length>0&&C.killedPids.length===0)return q("ctx_insight",{content:[{type:"text",text:`Could not free port ${s} (kill failed for ${C.attemptedPids.join(", ")}: ${C.errors.join("; ")}). Try ctx_insight({ port: ${s+1} }) or stop the process manually.`}]});if(C.errors.length>0&&C.attemptedPids.length===0)return q("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${s}: ${C.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(M=>setTimeout(M,500)),m.push(`Stale server killed (${C.killedPids.length} pid${C.killedPids.length===1?"":"s"}).`)}else if(v){m.push("Dashboard already running.");let C=`http://localhost:${s}`,M=ME(C),W=M.ok?"":` (auto-open failed: ${M.reason}; navigate manually)`;return q("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${C}${W}`}]})}if(Dr&&Dr.pid&&!Dr.killed)try{Dr.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),b=_("node",[Te(f,"server.mjs")],{cwd:f,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:l,INSIGHT_CONTENT_DIR:d,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});b.on("error",()=>{}),b.unref(),Dr=b,await new Promise(C=>setTimeout(C,1500));try{let{request:C}=await import("node:http");await new Promise((M,W)=>{let k=C(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},D=>{M(),D.resume()});k.on("error",W),k.on("timeout",()=>{k.destroy(),W(new Error("timeout"))}),k.end()})}catch{return q("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
1053
1066
 
1054
1067
  To fix:
1055
1068
  - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${s}`:`lsof -ti:${s} | xargs kill`}
1056
- - Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let T=`http://localhost:${s}`,I=RE(T),N=I.ok?"":` (auto-open failed: ${I.reason}; navigate manually)`;return m.push(`Dashboard running at ${T}${N}`),q("ctx_insight",{content:[{type:"text",text:m.map(O=>`- ${O}`).join(`
1069
+ - Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let E=`http://localhost:${s}`,R=ME(E),N=R.ok?"":` (auto-open failed: ${R.reason}; navigate manually)`;return m.push(`Dashboard running at ${E}${N}`),q("ctx_insight",{content:[{type:"text",text:m.map(C=>`- ${C}`).join(`
1057
1070
  `)+`
1058
1071
 
1059
- Open: ${T}
1060
- PID: ${S.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${S.pid} /F`:`kill ${S.pid}`}`}]})}catch(m){let p=m instanceof Error?m.message:String(m);return q("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});async function aL(){let t=dm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Ah():"/tmp",r=Ce(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{Hi.cleanupBackgrounded(),rr&&rr.close();try{cs(gu)}catch{}try{cs(r)}catch{}if(Nr&&Nr.pid&&!Nr.killed)try{Nr.kill("SIGTERM")}catch{}},o=async()=>{try{Oh=0,du()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),Bk({onShutdown:()=>o()});let s=new wc;await Ne.connect(s);try{Ih(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(ro(),Gc)),c=Ne.server.getClientVersion(),u=i(c??void 0);ln=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=Qk(Li());if(i){for(let[a,c]of Object.entries(i.calls))re.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))re.bytesReturned[a]=c;i.sessionStart>0&&(re.sessionStart=i.sessionStart)}}catch{}bE().then(i=>{i!=="unknown"&&(Mr=i)}),setInterval(()=>{bE().then(i=>{i!=="unknown"&&(Mr=i)})},3600*1e3).unref(),setInterval(()=>du(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Dr} running on stdio`),console.error(`Detected runtimes:
1061
- ${Ux(Ui)}`),Rc()||(console.error(`
1062
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&aL().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{fz as REGISTERED_CTX_TOOLS,SV as __resetSuppressionDiagnosticForTests,iL as browserOpenArgv,Kz as buildBatchNodeOptionsPrefix,eL as buildFetchCode,mu as classifyIp,us as currentAttribution,vz as emitSuppressionDiagnostic,ME as extractSnippet,Bz as formatBatchQueryResults,zE as killProcessOnPort,RE as openBrowserSync,qz as positionsFromHighlight,bz as registerEmptyToolsListHandler,kz as resolveSessionIdFromSessionDB,Gz as runBatchCommands,Ne as server,mz as shouldSuppressMcpToolsForNativePluginHost,kV as withProjectDirOverride};
1072
+ Open: ${E}
1073
+ PID: ${b.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${b.pid} /F`:`kill ${b.pid}`}`}]})}catch(m){let p=m instanceof Error?m.message:String(m);return q("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});async function AL(){let t=mm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Ih():"/tmp",r=Te(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{Zi.cleanupBackgrounded(),nr&&nr.close();try{ls(bu)}catch{}try{ls(r)}catch{}if(Dr&&Dr.pid&&!Dr.killed)try{Dr.kill("SIGTERM")}catch{}},o=async()=>{try{Ch=0,gu()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),Qk({onShutdown:()=>o()});let s=new Rc;await Ne.connect(s);try{Oh(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(no(),Xc)),c=Ne.server.getClientVersion(),u=i(c??void 0);ln=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=aE(Hi());if(i){for(let[a,c]of Object.entries(i.calls))re.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))re.bytesReturned[a]=c;i.sessionStart>0&&(re.sessionStart=i.sessionStart)}}catch{}PE().then(i=>{i!=="unknown"&&(jr=i)}),setInterval(()=>{PE().then(i=>{i!=="unknown"&&(jr=i)})},3600*1e3).unref(),setInterval(()=>gu(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Mr} running on stdio`),console.error(`Detected runtimes:
1074
+ ${Ub(Fi)}`),Cc()||(console.error(`
1075
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&AL().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{Lz as REGISTERED_CTX_TOOLS,eW as __resetSuppressionDiagnosticForTests,IL as browserOpenArgv,xL as buildBatchNodeOptionsPrefix,TL as buildFetchCode,vu as classifyIp,so as currentAttribution,Bz as emitSuppressionDiagnostic,qE as extractSnippet,yL as formatBatchQueryResults,Ht as getProjectDir,VE as killProcessOnPort,ME as openBrowserSync,gL as positionsFromHighlight,Vz as registerEmptyToolsListHandler,Gz as resolveSessionIdFromSessionDB,bL as runBatchCommands,Ne as server,Uz as shouldSuppressMcpToolsForNativePluginHost,tW as withProjectDirOverride};