@mxalbert/context-mode 2.0.2 → 2.0.3

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,16 +1,16 @@
1
1
  #!/usr/bin/env node
2
- var VP=Object.create;var gl=Object.defineProperty;var WP=Object.getOwnPropertyDescriptor;var KP=Object.getOwnPropertyNames;var GP=Object.getPrototypeOf,JP=Object.prototype.hasOwnProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Me=(t,e)=>{for(var n in e)gl(t,n,{get:e[n],enumerable:!0})},XP=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of KP(e))!JP.call(t,o)&&o!==n&&gl(t,o,{get:()=>e[o],enumerable:!(r=WP(e,o))||r.enumerable});return t};var yy=(t,e,n)=>(n=t!=null?VP(GP(t)):{},XP(e||!t||!t.__esModule?gl(n,"default",{value:t,enumerable:!0}):n,t));var li=I(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.regexpCode=pe.getEsmExportName=pe.getProperty=pe.safeStringify=pe.stringify=pe.strConcat=pe.addCodeArg=pe.str=pe._=pe.nil=pe._Code=pe.Name=pe.IDENTIFIER=pe._CodeOrName=void 0;var ci=class{};pe._CodeOrName=ci;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Gr=class extends ci{constructor(e){if(super(),!pe.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}}};pe.Name=Gr;var Ut=class extends ci{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Gr&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=Ut;pe.nil=new Ut("");function fb(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Yp(n,e[r]),n.push(t[++r]);return new Ut(n)}pe._=fb;var Xp=new Ut("+");function mb(t,...e){let n=[ui(t[0])],r=0;for(;r<e.length;)n.push(Xp),Yp(n,e[r]),n.push(Xp,ui(t[++r]));return GO(n),new Ut(n)}pe.str=mb;function Yp(t,e){e instanceof Ut?t.push(...e._items):e instanceof Gr?t.push(e):t.push(YO(e))}pe.addCodeArg=Yp;function GO(t){let e=1;for(;e<t.length-1;){if(t[e]===Xp){let n=JO(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function JO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Gr||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 Gr))return`"${t}${e.slice(1)}`}function XO(t,e){return e.emptyStr()?t:t.emptyStr()?e:mb`${t}${e}`}pe.strConcat=XO;function YO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ui(Array.isArray(t)?t.join(","):t)}function QO(t){return new Ut(ui(t))}pe.stringify=QO;function ui(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=ui;function eI(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new Ut(`.${t}`):fb`[${t}]`}pe.getProperty=eI;function tI(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=tI;function nI(t){return new Ut(t.toString())}pe.regexpCode=nI});var tf=I(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var vt=li(),Qp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},pc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(pc||(Et.UsedValueState=pc={}));Et.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var fc=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Et.Scope=fc;var mc=class extends vt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(n)}[${r}]`}};Et.ValueScopeName=mc;var rI=(0,vt._)`\n`,ef=class extends fc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?rI:vt.nil}}get(){return this._scope}name(e){return new mc(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,vt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,pc.Started);let l=n(u);if(l){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,vt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,vt._)`${s}${l}${this.opts._n}`;else throw new Qp(u);c.set(u,pc.Completed)})}return s}};Et.ValueScope=ef});var ee=I(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var ue=li(),on=tf(),ir=li();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return ir._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return ir.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return ir.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return ir.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return ir.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return ir.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return ir.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return ir.Name}});var _c=tf();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return _c.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return _c.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return _c.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return _c.varKinds}});te.operators={GT:new ue._Code(">"),GTE:new ue._Code(">="),LT:new ue._Code("<"),LTE:new ue._Code("<="),EQ:new ue._Code("==="),NEQ:new ue._Code("!=="),NOT:new ue._Code("!"),OR:new ue._Code("||"),AND:new ue._Code("&&"),ADD:new ue._Code("+")};var jn=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},nf=class extends jn{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?on.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=Wo(this.rhs,e,n)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},hc=class extends jn{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ue.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Wo(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return yc(e,this.rhs)}},rf=class extends hc{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},of=class extends jn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sf=class extends jn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},af=class extends jn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},cf=class extends jn{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=Wo(this.code,e,n),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},di=class extends jn{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(oI(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Yr(e,n.names),{})}},Ln=class extends di{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},uf=class extends di{},Vo=class extends Ln{};Vo.kind="else";var Jr=class t extends Ln{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Vo(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(hb(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=Wo(this.condition,e,n),this}get names(){let e=super.names;return yc(e,this.condition),this.else&&Yr(e,this.else.names),e}};Jr.kind="if";var Xr=class extends Ln{};Xr.kind="for";var lf=class extends Xr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=Wo(this.iteration,e,n),this}get names(){return Yr(super.names,this.iteration.names)}},df=class extends Xr{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?on.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=yc(super.names,this.from);return yc(e,this.to)}},gc=class extends Xr{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=Wo(this.iterable,e,n),this}get names(){return Yr(super.names,this.iterable.names)}},pi=class extends Ln{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};pi.kind="func";var fi=class extends di{render(e){return"return "+super.render(e)}};fi.kind="return";var pf=class extends Ln{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Yr(e,this.catch.names),this.finally&&Yr(e,this.finally.names),e}},mi=class extends Ln{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};mi.kind="catch";var hi=class extends Ln{render(e){return"finally"+super.render(e)}};hi.kind="finally";var ff=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
3
- `:""},this._extScope=e,this._scope=new on.Scope({parent:e}),this._nodes=[new uf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new nf(e,s,r)),s}const(e,n,r){return this._def(on.varKinds.const,e,n,r)}let(e,n,r){return this._def(on.varKinds.let,e,n,r)}var(e,n,r){return this._def(on.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new hc(e,n,r))}add(e,n){return this._leafNode(new rf(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new cf(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,ue.addCodeArg)(n,o));return n.push("}"),new ue._Code(n)}if(e,n,r){if(this._blockNode(new Jr(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Jr(e))}else(){return this._elseNode(new Vo)}endIf(){return this._endBlockNode(Jr,Vo)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new lf(e),n)}forRange(e,n,r,o,s=this.opts.es5?on.varKinds.var:on.varKinds.let){let i=this._scope.toName(e);return this._for(new df(s,i,n,r),()=>o(i))}forOf(e,n,r,o=on.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ue.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ue._)`${i}.length`,a=>{this.var(s,(0,ue._)`${i}[${a}]`),r(s)})}return this._for(new gc("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?on.varKinds.var:on.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ue._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new gc("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Xr)}label(e){return this._leafNode(new of(e))}break(e){return this._leafNode(new sf(e))}return(e){let n=new fi;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fi)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new pf;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new mi(s),n(s)}return r&&(this._currNode=o.finally=new hi,this.code(r)),this._endBlockNode(mi,hi)}throw(e){return this._leafNode(new af(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ue.nil,r,o){return this._blockNode(new pi(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(pi)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Jr))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};te.CodeGen=ff;function Yr(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function yc(t,e){return e instanceof ue._CodeOrName?Yr(t,e.names):t}function Wo(t,e,n){if(t instanceof ue.Name)return r(t);if(!o(t))return t;return new ue._Code(t._items.reduce((s,i)=>(i instanceof ue.Name&&(i=r(i)),i instanceof ue._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ue._Code&&s._items.some(i=>i instanceof ue.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function oI(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function hb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${mf(t)}`}te.not=hb;var sI=gb(te.operators.AND);function iI(...t){return t.reduce(sI)}te.and=iI;var aI=gb(te.operators.OR);function cI(...t){return t.reduce(aI)}te.or=cI;function gb(t){return(e,n)=>e===ue.nil?n:n===ue.nil?e:(0,ue._)`${mf(e)} ${t} ${mf(n)}`}function mf(t){return t instanceof ue.Name?t:(0,ue._)`(${t})`}});var le=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var xe=ee(),uI=li();function lI(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=lI;function dI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(xb(t,e),!bb(e,t.self.RULES.all))}re.alwaysValidSchema=dI;function xb(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||vb(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=xb;function bb(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=bb;function pI(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}re.schemaHasRulesButRef=pI;function fI({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,xe._)`${n}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(r)}`}re.schemaRefOrVal=fI;function mI(t){return Sb(decodeURIComponent(t))}re.unescapeFragment=mI;function hI(t){return encodeURIComponent(gf(t))}re.escapeFragment=hI;function gf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=gf;function Sb(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=Sb;function gI(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=gI;function yb({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):n(s,i);return a===xe.Name&&!(c instanceof xe.Name)?r(o,c):c}}re.mergeEvaluated={props:yb({mergeNames:(t,e,n)=>t.if((0,xe._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,xe._)`${n} || {}`).code((0,xe._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,xe._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,xe._)`${n} || {}`),yf(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:kb}),items:yb({mergeNames:(t,e,n)=>t.if((0,xe._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,xe._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,xe._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,xe._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function kb(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,xe._)`{}`);return e!==void 0&&yf(t,n,e),n}re.evaluatedPropsToName=kb;function yf(t,e,n){Object.keys(n).forEach(r=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(r)}`,!0))}re.setEvaluated=yf;var _b={};function yI(t,e){return t.scopeValue("func",{ref:e,code:_b[e.code]||(_b[e.code]=new uI._Code(e.code))})}re.useFunc=yI;var hf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(hf||(re.Type=hf={}));function _I(t,e,n){if(t instanceof xe.Name){let r=e===hf.Num;return n?r?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:r?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,xe.getProperty)(t).toString():"/"+gf(t)}re.getErrorPath=_I;function vb(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=vb});var zn=I(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var it=ee(),xI={data:new it.Name("data"),valCxt:new it.Name("valCxt"),instancePath:new it.Name("instancePath"),parentData:new it.Name("parentData"),parentDataProperty:new it.Name("parentDataProperty"),rootData:new it.Name("rootData"),dynamicAnchors:new it.Name("dynamicAnchors"),vErrors:new it.Name("vErrors"),errors:new it.Name("errors"),this:new it.Name("this"),self:new it.Name("self"),scope:new it.Name("scope"),json:new it.Name("json"),jsonPos:new it.Name("jsonPos"),jsonLen:new it.Name("jsonLen"),jsonPart:new it.Name("jsonPart")};_f.default=xI});var gi=I(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.extendErrors=at.resetErrorsCount=at.reportExtraError=at.reportError=at.keyword$DataError=at.keywordError=void 0;var de=ee(),xc=le(),ft=zn();at.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};at.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,de.str)`"${t}" keyword must be ${e} ($data)`:(0,de.str)`"${t}" keyword is invalid ($data)`};function bI(t,e=at.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Tb(t,e,n);r??(i||a)?Eb(s,c):wb(o,(0,de._)`[${c}]`)}at.reportError=bI;function SI(t,e=at.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=Tb(t,e,n);Eb(o,a),s||i||wb(r,ft.default.vErrors)}at.reportExtraError=SI;function kI(t,e){t.assign(ft.default.errors,e),t.if((0,de._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}at.resetErrorsCount=kI;function vI({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ft.default.errors,a=>{t.const(i,(0,de._)`${ft.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(ft.default.instancePath,s.errorPath))),t.assign((0,de._)`${i}.schemaPath`,(0,de.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,de._)`${i}.schema`,n),t.assign((0,de._)`${i}.data`,r))})}at.extendErrors=vI;function Eb(t,e){let n=t.const("err",e);t.if((0,de._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,de._)`[${n}]`),(0,de._)`${ft.default.vErrors}.push(${n})`),t.code((0,de._)`${ft.default.errors}++`)}function wb(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,de._)`new ${t.ValidationError}(${e})`):(n.assign((0,de._)`${r}.errors`,e),n.return(!1))}var Qr={keyword:new de.Name("keyword"),schemaPath:new de.Name("schemaPath"),params:new de.Name("params"),propertyName:new de.Name("propertyName"),message:new de.Name("message"),schema:new de.Name("schema"),parentSchema:new de.Name("parentSchema")};function Tb(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,de._)`{}`:EI(t,e,n)}function EI(t,e,n={}){let{gen:r,it:o}=t,s=[wI(o,n),TI(t,n)];return PI(t,e,s),r.object(...s)}function wI({errorPath:t},{instancePath:e}){let n=e?(0,de.str)`${t}${(0,xc.getErrorPath)(e,xc.Type.Str)}`:t;return[ft.default.instancePath,(0,de.strConcat)(ft.default.instancePath,n)]}function TI({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,de.str)`${e}/${t}`;return n&&(o=(0,de.str)`${o}${(0,xc.getErrorPath)(n,xc.Type.Str)}`),[Qr.schemaPath,o]}function PI(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Qr.keyword,o],[Qr.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&r.push([Qr.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Qr.schema,i],[Qr.parentSchema,(0,de._)`${l}${d}`],[ft.default.data,s]),u&&r.push([Qr.propertyName,u])}});var Rb=I(Ko=>{"use strict";Object.defineProperty(Ko,"__esModule",{value:!0});Ko.boolOrEmptySchema=Ko.topBoolOrEmptySchema=void 0;var RI=gi(),CI=ee(),$I=zn(),OI={message:"boolean schema is false"};function II(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Pb(t,!1):typeof n=="object"&&n.$async===!0?e.return($I.default.data):(e.assign((0,CI._)`${r}.errors`,null),e.return(!0))}Ko.topBoolOrEmptySchema=II;function AI(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Pb(t)):n.var(e,!0)}Ko.boolOrEmptySchema=AI;function Pb(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,RI.reportError)(o,OI,void 0,e)}});var xf=I(Go=>{"use strict";Object.defineProperty(Go,"__esModule",{value:!0});Go.getRules=Go.isJSONType=void 0;var NI=["string","number","integer","boolean","null","object","array"],DI=new Set(NI);function MI(t){return typeof t=="string"&&DI.has(t)}Go.isJSONType=MI;function jI(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Go.getRules=jI});var bf=I(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.shouldUseRule=ar.shouldUseGroup=ar.schemaHasRulesForType=void 0;function LI({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Cb(t,r)}ar.schemaHasRulesForType=LI;function Cb(t,e){return e.rules.some(n=>$b(t,n))}ar.shouldUseGroup=Cb;function $b(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}ar.shouldUseRule=$b});var yi=I(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.reportTypeError=ct.checkDataTypes=ct.checkDataType=ct.coerceAndCheckDataType=ct.getJSONTypes=ct.getSchemaTypes=ct.DataType=void 0;var zI=xf(),HI=bf(),UI=gi(),Y=ee(),Ob=le(),Jo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Jo||(ct.DataType=Jo={}));function FI(t){let e=Ib(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}ct.getSchemaTypes=FI;function Ib(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ct.getJSONTypes=Ib;function BI(t,e){let{gen:n,data:r,opts:o}=t,s=ZI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,HI.schemaHasRulesForType)(t,e[0]));if(i){let a=kf(e,r,o.strictNumbers,Jo.Wrong);n.if(a,()=>{s.length?qI(t,e,s):vf(t)})}return i}ct.coerceAndCheckDataType=BI;var Ab=new Set(["string","number","integer","boolean","null"]);function ZI(t,e){return e?t.filter(n=>Ab.has(n)||e==="array"&&n==="array"):[]}function qI(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,Y._)`typeof ${o}`),a=r.let("coerced",(0,Y._)`undefined`);s.coerceTypes==="array"&&r.if((0,Y._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,Y._)`${o}[0]`).assign(i,(0,Y._)`typeof ${o}`).if(kf(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,Y._)`${a} !== undefined`);for(let u of n)(Ab.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),vf(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(o,a),VI(t,a)});function c(u){switch(u){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
2
+ var WP=Object.create;var gl=Object.defineProperty;var KP=Object.getOwnPropertyDescriptor;var GP=Object.getOwnPropertyNames;var JP=Object.getPrototypeOf,XP=Object.prototype.hasOwnProperty;var J=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),je=(t,e)=>{for(var n in e)gl(t,n,{get:e[n],enumerable:!0})},YP=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GP(e))!XP.call(t,o)&&o!==n&&gl(t,o,{get:()=>e[o],enumerable:!(r=KP(e,o))||r.enumerable});return t};var gy=(t,e,n)=>(n=t!=null?WP(JP(t)):{},YP(e||!t||!t.__esModule?gl(n,"default",{value:t,enumerable:!0}):n,t));var li=I(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.regexpCode=pe.getEsmExportName=pe.getProperty=pe.safeStringify=pe.stringify=pe.strConcat=pe.addCodeArg=pe.str=pe._=pe.nil=pe._Code=pe.Name=pe.IDENTIFIER=pe._CodeOrName=void 0;var ci=class{};pe._CodeOrName=ci;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Kr=class extends ci{constructor(e){if(super(),!pe.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}}};pe.Name=Kr;var Ut=class extends ci{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((n,r)=>`${n}${r}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((n,r)=>(r instanceof Kr&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=Ut;pe.nil=new Ut("");function pb(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Yp(n,e[r]),n.push(t[++r]);return new Ut(n)}pe._=pb;var Xp=new Ut("+");function fb(t,...e){let n=[ui(t[0])],r=0;for(;r<e.length;)n.push(Xp),Yp(n,e[r]),n.push(Xp,ui(t[++r]));return JO(n),new Ut(n)}pe.str=fb;function Yp(t,e){e instanceof Ut?t.push(...e._items):e instanceof Kr?t.push(e):t.push(QO(e))}pe.addCodeArg=Yp;function JO(t){let e=1;for(;e<t.length-1;){if(t[e]===Xp){let n=XO(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function XO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Kr||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 Kr))return`"${t}${e.slice(1)}`}function YO(t,e){return e.emptyStr()?t:t.emptyStr()?e:fb`${t}${e}`}pe.strConcat=YO;function QO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ui(Array.isArray(t)?t.join(","):t)}function eI(t){return new Ut(ui(t))}pe.stringify=eI;function ui(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=ui;function tI(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new Ut(`.${t}`):pb`[${t}]`}pe.getProperty=tI;function nI(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new Ut(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=nI;function rI(t){return new Ut(t.toString())}pe.regexpCode=rI});var tf=I(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.ValueScope=Et.ValueScopeName=Et.Scope=Et.varKinds=Et.UsedValueState=void 0;var vt=li(),Qp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},dc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(dc||(Et.UsedValueState=dc={}));Et.varKinds={const:new vt.Name("const"),let:new vt.Name("let"),var:new vt.Name("var")};var pc=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof vt.Name?e:this.name(e)}name(e){return new vt.Name(this._newName(e))}_newName(e){let n=this._names[e]||this._nameGroup(e);return`${e}${n.index++}`}_nameGroup(e){var n,r;if(!((r=(n=this._parent)===null||n===void 0?void 0:n._prefixes)===null||r===void 0)&&r.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}}};Et.Scope=pc;var fc=class extends vt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,vt._)`.${new vt.Name(n)}[${r}]`}};Et.ValueScopeName=fc;var oI=(0,vt._)`\n`,ef=class extends pc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?oI:vt.nil}}get(){return this._scope}name(e){return new fc(e,this._newName(e))}value(e,n){var r;if(n.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(r=n.key)!==null&&r!==void 0?r:n.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]=n.ref,o.setValue(n,{property:s,itemIndex:u}),o}getValue(e,n){let r=this._values[e];if(r)return r.get(n)}scopeRefs(e,n=this._values){return this._reduceValues(n,r=>{if(r.scopePath===void 0)throw new Error(`CodeGen: name "${r}" has no value`);return(0,vt._)`${e}${r.scopePath}`})}scopeCode(e=this._values,n,r){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},n,r)}_reduceValues(e,n,r={},o){let s=vt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=r[i]=r[i]||new Map;a.forEach(u=>{if(c.has(u))return;c.set(u,dc.Started);let l=n(u);if(l){let d=this.opts.es5?Et.varKinds.var:Et.varKinds.const;s=(0,vt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,vt._)`${s}${l}${this.opts._n}`;else throw new Qp(u);c.set(u,dc.Completed)})}return s}};Et.ValueScope=ef});var ee=I(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.or=te.and=te.not=te.CodeGen=te.operators=te.varKinds=te.ValueScopeName=te.ValueScope=te.Scope=te.Name=te.regexpCode=te.stringify=te.getProperty=te.nil=te.strConcat=te.str=te._=void 0;var ue=li(),on=tf(),sr=li();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return sr._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return sr.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return sr.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return sr.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return sr.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return sr.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return sr.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return sr.Name}});var yc=tf();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return yc.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return yc.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return yc.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return yc.varKinds}});te.operators={GT:new ue._Code(">"),GTE:new ue._Code(">="),LT:new ue._Code("<"),LTE:new ue._Code("<="),EQ:new ue._Code("==="),NEQ:new ue._Code("!=="),NOT:new ue._Code("!"),OR:new ue._Code("||"),AND:new ue._Code("&&"),ADD:new ue._Code("+")};var Mn=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},nf=class extends Mn{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?on.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${r} ${this.name}${o};`+n}optimizeNames(e,n){if(e[this.name.str])return this.rhs&&(this.rhs=qo(this.rhs,e,n)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},mc=class extends Mn{constructor(e,n,r){super(),this.lhs=e,this.rhs=n,this.sideEffects=r}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof ue.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=qo(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return gc(e,this.rhs)}},rf=class extends mc{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},of=class extends Mn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},sf=class extends Mn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},af=class extends Mn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},cf=class extends Mn{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,n){return this.code=qo(this.code,e,n),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},di=class extends Mn{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((n,r)=>n+r.render(e),"")}optimizeNodes(){let{nodes:e}=this,n=e.length;for(;n--;){let r=e[n].optimizeNodes();Array.isArray(r)?e.splice(n,1,...r):r?e[n]=r:e.splice(n,1)}return e.length>0?this:void 0}optimizeNames(e,n){let{nodes:r}=this,o=r.length;for(;o--;){let s=r[o];s.optimizeNames(e,n)||(sI(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Xr(e,n.names),{})}},jn=class extends di{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},uf=class extends di{},Zo=class extends jn{};Zo.kind="else";var Gr=class t extends jn{constructor(e,n){super(n),this.condition=e}render(e){let n=`if(${this.condition})`+super.render(e);return this.else&&(n+="else "+this.else.render(e)),n}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let n=this.else;if(n){let r=n.optimizeNodes();n=this.else=Array.isArray(r)?new Zo(r):r}if(n)return e===!1?n instanceof t?n:n.nodes:this.nodes.length?this:new t(mb(e),n instanceof t?[n]:n.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,n){var r;if(this.else=(r=this.else)===null||r===void 0?void 0:r.optimizeNames(e,n),!!(super.optimizeNames(e,n)||this.else))return this.condition=qo(this.condition,e,n),this}get names(){let e=super.names;return gc(e,this.condition),this.else&&Xr(e,this.else.names),e}};Gr.kind="if";var Jr=class extends jn{};Jr.kind="for";var lf=class extends Jr{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iteration=qo(this.iteration,e,n),this}get names(){return Xr(super.names,this.iteration.names)}},df=class extends Jr{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?on.varKinds.var:this.varKind,{name:r,from:o,to:s}=this;return`for(${n} ${r}=${o}; ${r}<${s}; ${r}++)`+super.render(e)}get names(){let e=gc(super.names,this.from);return gc(e,this.to)}},hc=class extends Jr{constructor(e,n,r,o){super(),this.loop=e,this.varKind=n,this.name=r,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,n){if(super.optimizeNames(e,n))return this.iterable=qo(this.iterable,e,n),this}get names(){return Xr(super.names,this.iterable.names)}},pi=class extends jn{constructor(e,n,r){super(),this.name=e,this.args=n,this.async=r}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};pi.kind="func";var fi=class extends di{render(e){return"return "+super.render(e)}};fi.kind="return";var pf=class extends jn{render(e){let n="try"+super.render(e);return this.catch&&(n+=this.catch.render(e)),this.finally&&(n+=this.finally.render(e)),n}optimizeNodes(){var e,n;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(n=this.finally)===null||n===void 0||n.optimizeNodes(),this}optimizeNames(e,n){var r,o;return super.optimizeNames(e,n),(r=this.catch)===null||r===void 0||r.optimizeNames(e,n),(o=this.finally)===null||o===void 0||o.optimizeNames(e,n),this}get names(){let e=super.names;return this.catch&&Xr(e,this.catch.names),this.finally&&Xr(e,this.finally.names),e}},mi=class extends jn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};mi.kind="catch";var hi=class extends jn{render(e){return"finally"+super.render(e)}};hi.kind="finally";var ff=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
3
+ `:""},this._extScope=e,this._scope=new on.Scope({parent:e}),this._nodes=[new uf]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,n){let r=this._extScope.value(e,n);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(e,n){return this._extScope.getValue(e,n)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,n,r,o){let s=this._scope.toName(n);return r!==void 0&&o&&(this._constants[s.str]=r),this._leafNode(new nf(e,s,r)),s}const(e,n,r){return this._def(on.varKinds.const,e,n,r)}let(e,n,r){return this._def(on.varKinds.let,e,n,r)}var(e,n,r){return this._def(on.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new mc(e,n,r))}add(e,n){return this._leafNode(new rf(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new cf(e)),this}object(...e){let n=["{"];for(let[r,o]of e)n.length>1&&n.push(","),n.push(r),(r!==o||this.opts.es5)&&(n.push(":"),(0,ue.addCodeArg)(n,o));return n.push("}"),new ue._Code(n)}if(e,n,r){if(this._blockNode(new Gr(e)),n&&r)this.code(n).else().code(r).endIf();else if(n)this.code(n).endIf();else if(r)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Gr(e))}else(){return this._elseNode(new Zo)}endIf(){return this._endBlockNode(Gr,Zo)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new lf(e),n)}forRange(e,n,r,o,s=this.opts.es5?on.varKinds.var:on.varKinds.let){let i=this._scope.toName(e);return this._for(new df(s,i,n,r),()=>o(i))}forOf(e,n,r,o=on.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=n instanceof ue.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ue._)`${i}.length`,a=>{this.var(s,(0,ue._)`${i}[${a}]`),r(s)})}return this._for(new hc("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?on.varKinds.var:on.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ue._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new hc("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Jr)}label(e){return this._leafNode(new of(e))}break(e){return this._leafNode(new sf(e))}return(e){let n=new fi;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fi)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new pf;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new mi(s),n(s)}return r&&(this._currNode=o.finally=new hi,this.code(r)),this._endBlockNode(mi,hi)}throw(e){return this._leafNode(new af(e))}block(e,n){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(n),this}endBlock(e){let n=this._blockStarts.pop();if(n===void 0)throw new Error("CodeGen: not in self-balancing block");let r=this._nodes.length-n;if(r<0||e!==void 0&&r!==e)throw new Error(`CodeGen: wrong number of nodes: ${r} vs ${e} expected`);return this._nodes.length=n,this}func(e,n=ue.nil,r,o){return this._blockNode(new pi(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(pi)}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,n){let r=this._currNode;if(r instanceof e||n&&r instanceof n)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${n?`${e.kind}/${n.kind}`:e.kind}"`)}_elseNode(e){let n=this._currNode;if(!(n instanceof Gr))throw new Error('CodeGen: "else" without "if"');return this._currNode=n.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let n=this._nodes;n[n.length-1]=e}};te.CodeGen=ff;function Xr(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function gc(t,e){return e instanceof ue._CodeOrName?Xr(t,e.names):t}function qo(t,e,n){if(t instanceof ue.Name)return r(t);if(!o(t))return t;return new ue._Code(t._items.reduce((s,i)=>(i instanceof ue.Name&&(i=r(i)),i instanceof ue._Code?s.push(...i._items):s.push(i),s),[]));function r(s){let i=n[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ue._Code&&s._items.some(i=>i instanceof ue.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function sI(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function mb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${mf(t)}`}te.not=mb;var iI=hb(te.operators.AND);function aI(...t){return t.reduce(iI)}te.and=aI;var cI=hb(te.operators.OR);function uI(...t){return t.reduce(cI)}te.or=uI;function hb(t){return(e,n)=>e===ue.nil?n:n===ue.nil?e:(0,ue._)`${mf(e)} ${t} ${mf(n)}`}function mf(t){return t instanceof ue.Name?t:(0,ue._)`(${t})`}});var le=I(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.checkStrictMode=re.getErrorPath=re.Type=re.useFunc=re.setEvaluated=re.evaluatedPropsToName=re.mergeEvaluated=re.eachItem=re.unescapeJsonPointer=re.escapeJsonPointer=re.escapeFragment=re.unescapeFragment=re.schemaRefOrVal=re.schemaHasRulesButRef=re.schemaHasRules=re.checkUnknownRules=re.alwaysValidSchema=re.toHash=void 0;var xe=ee(),lI=li();function dI(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=dI;function pI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(_b(t,e),!xb(e,t.self.RULES.all))}re.alwaysValidSchema=pI;function _b(t,e=t.schema){let{opts:n,self:r}=t;if(!n.strictSchema||typeof e=="boolean")return;let o=r.RULES.keywords;for(let s in e)o[s]||kb(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=_b;function xb(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=xb;function fI(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(n!=="$ref"&&e.all[n])return!0;return!1}re.schemaHasRulesButRef=fI;function mI({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,xe._)`${n}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(r)}`}re.schemaRefOrVal=mI;function hI(t){return bb(decodeURIComponent(t))}re.unescapeFragment=hI;function gI(t){return encodeURIComponent(gf(t))}re.escapeFragment=gI;function gf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=gf;function bb(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=bb;function yI(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=yI;function gb({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):n(s,i);return a===xe.Name&&!(c instanceof xe.Name)?r(o,c):c}}re.mergeEvaluated={props:gb({mergeNames:(t,e,n)=>t.if((0,xe._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,xe._)`${n} || {}`).code((0,xe._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,xe._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,xe._)`${n} || {}`),yf(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Sb}),items:gb({mergeNames:(t,e,n)=>t.if((0,xe._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,xe._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,xe._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,xe._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Sb(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,xe._)`{}`);return e!==void 0&&yf(t,n,e),n}re.evaluatedPropsToName=Sb;function yf(t,e,n){Object.keys(n).forEach(r=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(r)}`,!0))}re.setEvaluated=yf;var yb={};function _I(t,e){return t.scopeValue("func",{ref:e,code:yb[e.code]||(yb[e.code]=new lI._Code(e.code))})}re.useFunc=_I;var hf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(hf||(re.Type=hf={}));function xI(t,e,n){if(t instanceof xe.Name){let r=e===hf.Num;return n?r?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:r?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,xe.getProperty)(t).toString():"/"+gf(t)}re.getErrorPath=xI;function kb(t,e,n=t.opts.strictSchema){if(n){if(e=`strict mode: ${e}`,n===!0)throw new Error(e);t.self.logger.warn(e)}}re.checkStrictMode=kb});var Ln=I(_f=>{"use strict";Object.defineProperty(_f,"__esModule",{value:!0});var it=ee(),bI={data:new it.Name("data"),valCxt:new it.Name("valCxt"),instancePath:new it.Name("instancePath"),parentData:new it.Name("parentData"),parentDataProperty:new it.Name("parentDataProperty"),rootData:new it.Name("rootData"),dynamicAnchors:new it.Name("dynamicAnchors"),vErrors:new it.Name("vErrors"),errors:new it.Name("errors"),this:new it.Name("this"),self:new it.Name("self"),scope:new it.Name("scope"),json:new it.Name("json"),jsonPos:new it.Name("jsonPos"),jsonLen:new it.Name("jsonLen"),jsonPart:new it.Name("jsonPart")};_f.default=bI});var gi=I(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.extendErrors=at.resetErrorsCount=at.reportExtraError=at.reportError=at.keyword$DataError=at.keywordError=void 0;var de=ee(),_c=le(),ft=Ln();at.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};at.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,de.str)`"${t}" keyword must be ${e} ($data)`:(0,de.str)`"${t}" keyword is invalid ($data)`};function SI(t,e=at.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=wb(t,e,n);r??(i||a)?vb(s,c):Eb(o,(0,de._)`[${c}]`)}at.reportError=SI;function kI(t,e=at.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=wb(t,e,n);vb(o,a),s||i||Eb(r,ft.default.vErrors)}at.reportExtraError=kI;function vI(t,e){t.assign(ft.default.errors,e),t.if((0,de._)`${ft.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${ft.default.vErrors}.length`,e),()=>t.assign(ft.default.vErrors,null)))}at.resetErrorsCount=vI;function EI({gen:t,keyword:e,schemaValue:n,data:r,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ft.default.errors,a=>{t.const(i,(0,de._)`${ft.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(ft.default.instancePath,s.errorPath))),t.assign((0,de._)`${i}.schemaPath`,(0,de.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,de._)`${i}.schema`,n),t.assign((0,de._)`${i}.data`,r))})}at.extendErrors=EI;function vb(t,e){let n=t.const("err",e);t.if((0,de._)`${ft.default.vErrors} === null`,()=>t.assign(ft.default.vErrors,(0,de._)`[${n}]`),(0,de._)`${ft.default.vErrors}.push(${n})`),t.code((0,de._)`${ft.default.errors}++`)}function Eb(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,de._)`new ${t.ValidationError}(${e})`):(n.assign((0,de._)`${r}.errors`,e),n.return(!1))}var Yr={keyword:new de.Name("keyword"),schemaPath:new de.Name("schemaPath"),params:new de.Name("params"),propertyName:new de.Name("propertyName"),message:new de.Name("message"),schema:new de.Name("schema"),parentSchema:new de.Name("parentSchema")};function wb(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,de._)`{}`:wI(t,e,n)}function wI(t,e,n={}){let{gen:r,it:o}=t,s=[TI(o,n),PI(t,n)];return RI(t,e,s),r.object(...s)}function TI({errorPath:t},{instancePath:e}){let n=e?(0,de.str)`${t}${(0,_c.getErrorPath)(e,_c.Type.Str)}`:t;return[ft.default.instancePath,(0,de.strConcat)(ft.default.instancePath,n)]}function PI({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,de.str)`${e}/${t}`;return n&&(o=(0,de.str)`${o}${(0,_c.getErrorPath)(n,_c.Type.Str)}`),[Yr.schemaPath,o]}function RI(t,{params:e,message:n},r){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;r.push([Yr.keyword,o],[Yr.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&r.push([Yr.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Yr.schema,i],[Yr.parentSchema,(0,de._)`${l}${d}`],[ft.default.data,s]),u&&r.push([Yr.propertyName,u])}});var Pb=I(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.boolOrEmptySchema=Vo.topBoolOrEmptySchema=void 0;var CI=gi(),$I=ee(),OI=Ln(),II={message:"boolean schema is false"};function AI(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Tb(t,!1):typeof n=="object"&&n.$async===!0?e.return(OI.default.data):(e.assign((0,$I._)`${r}.errors`,null),e.return(!0))}Vo.topBoolOrEmptySchema=AI;function NI(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Tb(t)):n.var(e,!0)}Vo.boolOrEmptySchema=NI;function Tb(t,e){let{gen:n,data:r}=t,o={gen:n,keyword:"false schema",data:r,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,CI.reportError)(o,II,void 0,e)}});var xf=I(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.getRules=Wo.isJSONType=void 0;var DI=["string","number","integer","boolean","null","object","array"],MI=new Set(DI);function jI(t){return typeof t=="string"&&MI.has(t)}Wo.isJSONType=jI;function LI(){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:{}}}Wo.getRules=LI});var bf=I(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.shouldUseRule=ir.shouldUseGroup=ir.schemaHasRulesForType=void 0;function zI({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&Rb(t,r)}ir.schemaHasRulesForType=zI;function Rb(t,e){return e.rules.some(n=>Cb(t,n))}ir.shouldUseGroup=Rb;function Cb(t,e){var n;return t[e.keyword]!==void 0||((n=e.definition.implements)===null||n===void 0?void 0:n.some(r=>t[r]!==void 0))}ir.shouldUseRule=Cb});var yi=I(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.reportTypeError=ct.checkDataTypes=ct.checkDataType=ct.coerceAndCheckDataType=ct.getJSONTypes=ct.getSchemaTypes=ct.DataType=void 0;var HI=xf(),UI=bf(),FI=gi(),Y=ee(),$b=le(),Ko;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ko||(ct.DataType=Ko={}));function BI(t){let e=Ob(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}ct.getSchemaTypes=BI;function Ob(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(HI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}ct.getJSONTypes=Ob;function ZI(t,e){let{gen:n,data:r,opts:o}=t,s=qI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,UI.schemaHasRulesForType)(t,e[0]));if(i){let a=kf(e,r,o.strictNumbers,Ko.Wrong);n.if(a,()=>{s.length?VI(t,e,s):vf(t)})}return i}ct.coerceAndCheckDataType=ZI;var Ib=new Set(["string","number","integer","boolean","null"]);function qI(t,e){return e?t.filter(n=>Ib.has(n)||e==="array"&&n==="array"):[]}function VI(t,e,n){let{gen:r,data:o,opts:s}=t,i=r.let("dataType",(0,Y._)`typeof ${o}`),a=r.let("coerced",(0,Y._)`undefined`);s.coerceTypes==="array"&&r.if((0,Y._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>r.assign(o,(0,Y._)`${o}[0]`).assign(i,(0,Y._)`typeof ${o}`).if(kf(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,Y._)`${a} !== undefined`);for(let u of n)(Ib.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),vf(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(o,a),WI(t,a)});function c(u){switch(u){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
4
4
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":r.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
5
5
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Y._)`+${o}`);return;case"boolean":r.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":r.elseIf((0,Y._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
6
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function VI({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function Sf(t,e,n,r=Jo.Correct){let o=r===Jo.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 r===Jo.Correct?s:(0,Y.not)(s);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,n?(0,Y._)`isFinite(${e})`:Y.nil)}}ct.checkDataType=Sf;function kf(t,e,n,r){if(t.length===1)return Sf(t[0],e,n,r);let o,s=(0,Ob.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,Sf(i,e,n,r));return o}ct.checkDataTypes=kf;var WI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function vf(t){let e=KI(t);(0,UI.reportError)(e,WI)}ct.reportTypeError=vf;function KI(t){let{gen:e,data:n,schema:r}=t,o=(0,Ob.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var Db=I(bc=>{"use strict";Object.defineProperty(bc,"__esModule",{value:!0});bc.assignDefaults=void 0;var Xo=ee(),GI=le();function JI(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)Nb(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Nb(t,s,o.default))}bc.assignDefaults=JI;function Nb(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Xo._)`${s}${(0,Xo.getProperty)(e)}`;if(o){(0,GI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Xo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Xo._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Xo._)`${a} = ${(0,Xo.stringify)(n)}`)}});var Ft=I(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.validateUnion=ge.validateArray=ge.usePattern=ge.callValidateCode=ge.schemaProperties=ge.allSchemaProperties=ge.noPropertyInData=ge.propertyInData=ge.isOwnProperty=ge.hasPropFunc=ge.reportMissingProp=ge.checkMissingProp=ge.checkReportMissingProp=void 0;var Ee=ee(),Ef=le(),cr=zn(),XI=le();function YI(t,e){let{gen:n,data:r,it:o}=t;n.if(Tf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ee._)`${e}`},!0),t.error()})}ge.checkReportMissingProp=YI;function QI({gen:t,data:e,it:{opts:n}},r,o){return(0,Ee.or)(...r.map(s=>(0,Ee.and)(Tf(t,e,s,n.ownProperties),(0,Ee._)`${o} = ${s}`)))}ge.checkMissingProp=QI;function eA(t,e){t.setParams({missingProperty:e},!0),t.error()}ge.reportMissingProp=eA;function Mb(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ee._)`Object.prototype.hasOwnProperty`})}ge.hasPropFunc=Mb;function wf(t,e,n){return(0,Ee._)`${Mb(t)}.call(${e}, ${n})`}ge.isOwnProperty=wf;function tA(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} !== undefined`;return r?(0,Ee._)`${o} && ${wf(t,e,n)}`:o}ge.propertyInData=tA;function Tf(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} === undefined`;return r?(0,Ee.or)(o,(0,Ee.not)(wf(t,e,n))):o}ge.noPropertyInData=Tf;function jb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ge.allSchemaProperties=jb;function nA(t,e){return jb(e).filter(n=>!(0,Ef.alwaysValidSchema)(t,e[n]))}ge.schemaProperties=nA;function rA({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ee._)`${t}, ${e}, ${r}${o}`:e,d=[[cr.default.instancePath,(0,Ee.strConcat)(cr.default.instancePath,s)],[cr.default.parentData,i.parentData],[cr.default.parentDataProperty,i.parentDataProperty],[cr.default.rootData,cr.default.rootData]];i.opts.dynamicRef&&d.push([cr.default.dynamicAnchors,cr.default.dynamicAnchors]);let f=(0,Ee._)`${l}, ${n.object(...d)}`;return c!==Ee.nil?(0,Ee._)`${a}.call(${c}, ${f})`:(0,Ee._)`${a}(${f})`}ge.callValidateCode=rA;var oA=(0,Ee._)`new RegExp`;function sA({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ee._)`${o.code==="new RegExp"?oA:(0,XI.useFunc)(t,o)}(${n}, ${r})`})}ge.usePattern=sA;function iA(t){let{gen:e,data:n,keyword:r,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,Ee._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Ef.Type.Num},s),e.if((0,Ee.not)(s),a)})}}ge.validateArray=iA;function aA(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ef.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ee._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ee.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ge.validateUnion=aA});var Hb=I(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.validateKeywordUsage=Sn.validSchemaType=Sn.funcKeywordCode=Sn.macroKeywordCode=void 0;var mt=ee(),eo=zn(),cA=Ft(),uA=gi();function lA(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=zb(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:mt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Sn.macroKeywordCode=lA;function dA(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;fA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=zb(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)h(),e.modifying&&Lb(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&Lb(t),g(()=>pA(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,mt._)`await `),_=>r.assign(d,!1).if((0,mt._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,mt._)`${_}.errors`),()=>r.throw(_))),y}function p(){let y=(0,mt._)`${l}.errors`;return r.assign(y,null),h(mt.nil),y}function h(y=e.async?(0,mt._)`await `:mt.nil){let _=c.opts.passContext?eo.default.this:eo.default.self,x=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,mt._)`${y}${(0,cA.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;r.if((0,mt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}Sn.funcKeywordCode=dA;function Lb(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,mt._)`${r.parentData}[${r.parentDataProperty}]`))}function pA(t,e){let{gen:n}=t;n.if((0,mt._)`Array.isArray(${e})`,()=>{n.assign(eo.default.vErrors,(0,mt._)`${eo.default.vErrors} === null ? ${e} : ${eo.default.vErrors}.concat(${e})`).assign(eo.default.errors,(0,mt._)`${eo.default.vErrors}.length`),(0,uA.extendErrors)(t)},()=>t.error())}function fA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function zb(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,mt.stringify)(n)})}function mA(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}Sn.validSchemaType=mA;function hA({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}Sn.validateKeywordUsage=hA});var Fb=I(ur=>{"use strict";Object.defineProperty(ur,"__esModule",{value:!0});ur.extendSubschemaMode=ur.extendSubschemaData=ur.getSubschema=void 0;var kn=ee(),Ub=le();function gA(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,kn._)`${t.schemaPath}${(0,kn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,kn._)`${t.schemaPath}${(0,kn.getProperty)(e)}${(0,kn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ub.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}ur.getSubschema=gA;function yA(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,kn._)`${e.data}${(0,kn.getProperty)(n)}`,!0);c(f),t.errorPath=(0,kn.str)`${u}${(0,Ub.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,kn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof kn.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]}}ur.extendSubschemaData=yA;function _A(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}ur.extendSubschemaMode=_A});var Pf=I(($9,Bb)=>{"use strict";Bb.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var qb=I((O9,Zb)=>{"use strict";var lr=Zb.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};Sc(e,r,o,t,"",t)};lr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};lr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};lr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};lr.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function Sc(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in lr.arrayKeywords)for(var f=0;f<d.length;f++)Sc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in lr.propsKeywords){if(d&&typeof d=="object")for(var m in d)Sc(t,e,n,d[m],o+"/"+l+"/"+xA(m),s,o,l,r,m)}else(l in lr.keywords||t.allKeys&&!(l in lr.skipKeywords))&&Sc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function xA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var _i=I(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.getSchemaRefs=wt.resolveUrl=wt.normalizeId=wt._getFullPath=wt.getFullPath=wt.inlineRef=void 0;var bA=le(),SA=Pf(),kA=qb(),vA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function EA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Rf(t):e?Vb(t)<=e:!1}wt.inlineRef=EA;var wA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Rf(t){for(let e in t){if(wA.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Rf)||typeof n=="object"&&Rf(n))return!0}return!1}function Vb(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!vA.has(n)&&(typeof t[n]=="object"&&(0,bA.eachItem)(t[n],r=>e+=Vb(r)),e===1/0))return 1/0}return e}function Wb(t,e="",n){n!==!1&&(e=Yo(e));let r=t.parse(e);return Kb(t,r)}wt.getFullPath=Wb;function Kb(t,e){return t.serialize(e).split("#")[0]+"#"}wt._getFullPath=Kb;var TA=/#\/?$/;function Yo(t){return t?t.replace(TA,""):""}wt.normalizeId=Yo;function PA(t,e,n){return n=Yo(n),t.resolve(e,n)}wt.resolveUrl=PA;var RA=/^[a-z_][-a-z0-9._]*$/i;function CA(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Yo(t[n]||e),s={"":o},i=Wb(r,o,!1),a={},c=new Set;return kA(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(x){let b=this.opts.uriResolver.resolve;if(x=Yo(g?b(g,x):x),c.has(x))throw l(x);c.add(x);let v=this.refs[x];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,x):x!==Yo(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!RA.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,f,m){if(f!==void 0&&!SA(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}wt.getSchemaRefs=CA});var Si=I(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.getData=dr.KeywordCxt=dr.validateFunctionCode=void 0;var Qb=Rb(),Gb=yi(),$f=bf(),kc=yi(),$A=Db(),bi=Hb(),Cf=Fb(),F=ee(),G=zn(),OA=_i(),Hn=le(),xi=gi();function IA(t){if(nS(t)&&(rS(t),tS(t))){DA(t);return}eS(t,()=>(0,Qb.topBoolOrEmptySchema)(t))}dr.validateFunctionCode=IA;function eS({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,F._)`${G.default.data}, ${G.default.valCxt}`,r.$async,()=>{t.code((0,F._)`"use strict"; ${Jb(n,o)}`),NA(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${AA(o)}`,r.$async,()=>t.code(Jb(n,o)).code(s))}function AA(t){return(0,F._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,F._)`, ${G.default.dynamicAnchors}={}`:F.nil}}={}`}function NA(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,F._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,F._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,F._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,F._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,F._)`""`),t.var(G.default.parentData,(0,F._)`undefined`),t.var(G.default.parentDataProperty,(0,F._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`{}`)})}function DA(t){let{schema:e,opts:n,gen:r}=t;eS(t,()=>{n.$comment&&e.$comment&&sS(t),HA(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&MA(t),oS(t),BA(t)})}function MA(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,F._)`${n}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function Jb(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${n} */`:F.nil}function jA(t,e){if(nS(t)&&(rS(t),tS(t))){LA(t,e);return}(0,Qb.boolOrEmptySchema)(t,e)}function tS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function nS(t){return typeof t.schema!="boolean"}function LA(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&sS(t),UA(t),FA(t);let s=r.const("_errs",G.default.errors);oS(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function rS(t){(0,Hn.checkUnknownRules)(t),zA(t)}function oS(t,e){if(t.opts.jtd)return Xb(t,[],!1,e);let n=(0,Gb.getSchemaTypes)(t.schema),r=(0,Gb.coerceAndCheckDataType)(t,n);Xb(t,n,!r,e)}function zA(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Hn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function HA(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Hn.checkStrictMode)(t,"default is ignored in the schema root")}function UA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,OA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function FA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function sS({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,F._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function BA(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,F._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,F._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,F._)`${r}.errors`,G.default.vErrors),s.unevaluated&&ZA(t),e.return((0,F._)`${G.default.errors} === 0`))}function ZA({gen:t,evaluated:e,props:n,items:r}){n instanceof F.Name&&t.assign((0,F._)`${e}.props`,n),r instanceof F.Name&&t.assign((0,F._)`${e}.items`,r)}function Xb(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Hn.schemaHasRulesButRef)(s,l))){o.block(()=>aS(t,"$ref",l.all.$ref.definition));return}c.jtd||qA(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,$f.shouldUseGroup)(s,f)&&(f.type?(o.if((0,kc.checkDataType)(f.type,i,c.strictNumbers)),Yb(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,kc.reportTypeError)(t)),o.endIf()):Yb(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function Yb(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,$A.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,$f.shouldUseRule)(r,s)&&aS(t,s.keyword,s.definition,e.type)})}function qA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(VA(t,e),t.opts.allowUnionTypes||WA(t,e),KA(t,t.dataTypes))}function VA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{iS(t.dataTypes,n)||Of(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),JA(t,e)}}function WA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Of(t,"use allowUnionTypes to allow union type keyword")}function KA(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,$f.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>GA(e,i))&&Of(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function GA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function iS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JA(t,e){let n=[];for(let r of t.dataTypes)iS(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Of(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Hn.checkStrictMode)(t,e,t.opts.strictTypes)}var vc=class{constructor(e,n,r){if((0,bi.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Hn.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",cS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,bi.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",G.default.errors))}result(e,n,r){this.failResult((0,F.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,F.not)(e),void 0,n)}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:n}=this;this.fail((0,F._)`${n} !== undefined && (${(0,F.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?xi.reportExtraError:xi.reportError)(this,this.def.error,n)}$dataError(){(0,xi.reportError)(this,this.def.$dataError||xi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,xi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=F.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=F.nil,n=F.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,F.or)((0,F._)`${o} === undefined`,n)),e!==F.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(r.length){if(!(n instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,F._)`${(0,kc.checkDataTypes)(c,n,s.opts.strictNumbers,kc.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${c}(${n})`}return F.nil}}subschema(e,n){let r=(0,Cf.getSubschema)(this.it,e);(0,Cf.extendSubschemaData)(r,this.it,e),(0,Cf.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return jA(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Hn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Hn.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,F.Name)),!0}};dr.KeywordCxt=vc;function aS(t,e,n,r){let o=new vc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,bi.funcKeywordCode)(o,n):"macro"in n?(0,bi.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,bi.funcKeywordCode)(o,n)}var XA=/^\/(?:[^~]|~0|~1)*$/,YA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function cS(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!XA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=YA.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,Hn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}dr.getData=cS});var Ec=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var If=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Af.default=If});var ki=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Nf=_i(),Df=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Nf.resolveUrl)(e,n,r),this.missingSchema=(0,Nf.normalizeId)((0,Nf.getFullPath)(e,this.missingRef))}};Mf.default=Df});var Tc=I(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.resolveSchema=Bt.getCompilingSchema=Bt.resolveRef=Bt.compileSchema=Bt.SchemaEnv=void 0;var sn=ee(),QA=Ec(),to=zn(),an=_i(),uS=le(),eN=Si(),Qo=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,an.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Bt.SchemaEnv=Qo;function Lf(t){let e=lS.call(this,t);if(e)return e;let n=(0,an.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new sn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:QA.default,code:(0,sn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:to.default.data,parentData:to.default.parentData,parentDataProperty:to.default.parentDataProperty,dataNames:[to.default.data],dataPathArr:[sn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,sn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:sn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,sn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,eN.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(to.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${to.default.self}`,`${to.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 sn.Name?void 0:p,items:h instanceof sn.Name?void 0:h,dynamicProps:p instanceof sn.Name,dynamicItems:h instanceof sn.Name},m.source&&(m.source.evaluated=(0,sn.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)}}Bt.compileSchema=Lf;function tN(t,e,n){var r;n=(0,an.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=oN.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Qo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=nN.call(this,s)}Bt.resolveRef=tN;function nN(t){return(0,an.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Lf.call(this,t)}function lS(t){for(let e of this._compilations)if(rN(e,t))return e}Bt.getCompilingSchema=lS;function rN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function oN(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||wc.call(this,t,e)}function wc(t,e){let n=this.opts.uriResolver.parse(e),r=(0,an._getFullPath)(this.opts.uriResolver,n),o=(0,an.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return jf.call(this,n,t);let s=(0,an.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=wc.call(this,t,i);return typeof a?.schema!="object"?void 0:jf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Lf.call(this,i),s===(0,an.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,an.resolveUrl)(this.opts.uriResolver,o,u)),new Qo({schema:a,schemaId:c,root:t,baseId:o})}return jf.call(this,n,i)}}Bt.resolveSchema=wc;var sN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function jf(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,uS.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!sN.has(a)&&u&&(e=(0,an.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,uS.schemaHasRulesButRef)(n,this.RULES)){let a=(0,an.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=wc.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Qo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var dS=I((j9,iN)=>{iN.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Zf=I((L9,_S)=>{"use strict";var aN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hf=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),cN=RegExp.prototype.test.bind(/^\d*$/u),no=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Uf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),fS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Ff=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),uN=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Tt[e]="%"+t[e>>4]+t[e&15]}function ut(t){return t<2048?Tt[192|t>>6]+Tt[128|t&63]:t<65536?Tt[224|t>>12]+Tt[128|t>>6&63]+Tt[128|t&63]:Tt[240|t>>18]+Tt[128|t>>12&63]+Tt[128|t>>6&63]+Tt[128|t&63]}function lN(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var dN=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),pN=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),fN=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),mN=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function hN(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!fN(t[e])){if(t[e]==="%"&&e+2<t.length&&no(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function pS(t){let e=-1,n=0,r=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(r===-1&&(r=a),o++,o>n&&(n=o,e=r)):(r=-1,o=0);if(n<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+n).join(":");return s+"::"+i}function gN(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let n=e===-1?t.split(":"):t.slice(0,e).split(":"),r=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(n.length===1&&n[0]===""&&(n.length=0),r.length===1&&r[0]===""&&(r.length=0));let o=n.concat(r),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&r.length===0||!Hf(c))return;s+=2;continue}if(!dN(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:pS(o);if(s>=8)return;let i=o.slice(0,n.length);for(let a=s;a<8;a++)i.push("0");for(let a=n.length;a<o.length;a++)i.push(o[a]);return pS(i)}function zf(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let r=e?t.slice(1,-1):t;if(e&&pN(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(yN(r,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=r.indexOf("%");if(s!==-1){let a=r.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=r.slice(s+a),!hN(o))return{host:t,isIPV6:!1,error:!0};r=r.slice(0,s)}let i=gN(r);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function yN(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function _N(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var xN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},bN=/[@/?#:]/g,SN=/[@/?#]/g;function mS(t,e){let n=e?SN:bN;return n.lastIndex=0,t.replace(n,r=>xN[r])}function hS(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(no(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Uf(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function kN(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(no(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Uf(i)?e+=i:e+="%"+s,n+=2;continue}}if(fS(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=yS(o)?r:Tt[o];else if(o<55296||o>57343)e+=ut(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=ut(65536+(o-55296<<10)+(s-56320)),n++):e+=ut(65533)}else e+=ut(65533)}}return e}function vN(t,e=!1){let n="",r=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(no(i)){n+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(r=!1),fS(s)&&(s!==":"||!r))n+=s;else{let i=t.charCodeAt(o);if(i<128)n+=Tt[i];else if(i<55296||i>57343)n+=ut(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(n+=ut(65536+(i-55296<<10)+(a-56320)),o++):n+=ut(65533)}else n+=ut(65533)}}return n}function Bf(t,e){let n="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(no(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(e(o))n+=o;else{let s=t.charCodeAt(r);if(s<128)n+=Tt[s];else if(s<55296||s>57343)n+=ut(s);else if(s<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(n+=ut(65536+(s-55296<<10)+(i-56320)),r++):n+=ut(65533)}else n+=ut(65533)}}return n}function gS(t){return Bf(t,uN)}function EN(t){return Bf(t,Ff)}function wN(t){return Bf(t,Ff)}function yS(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function TN(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(no(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Uf(i)?e+=i:e+="%"+s,n+=2;continue}}if(Ff(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=yS(o)?r:Tt[o];else if(o<55296||o>57343)e+=ut(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=ut(65536+(o-55296<<10)+(s-56320)),n++):e+=ut(65533)}else e+=ut(65533)}}return e}function PN(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(no(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function RN(t){let e=[];if(t.userinfo!==void 0&&(e.push(gS(t.userinfo)),e.push("@")),t.host!==void 0){let n=t.host;if(!Hf(n)){let r=zf(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=hS(n,!0),r=zf(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=mS(n,!1)}e.push(n)}if(typeof t.port=="number"||typeof t.port=="string"){let n=String(t.port);if(!cN(n))throw new TypeError("URI port is malformed.");e.push(":"),e.push(n)}return e.length?e.join(""):void 0}_S.exports={nonSimpleDomain:mN,recomposeAuthority:RN,reescapeHostDelimiters:mS,normalizePercentEncoding:hS,normalizePathEncoding:kN,serializePathEncoding:vN,normalizeQueryFragmentEncoding:TN,encodeUserinfo:gS,encodeQuery:EN,encodeFragment:wN,escapePreservingEscapes:PN,removeDotSegments:_N,isIPv4:Hf,isUUID:aN,normalizeIPv6:zf,stringArrayToHexStripped:lN}});var vS=I((z9,kS)=>{"use strict";var{isUUID:CN}=Zf(),$N=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,ON=["http","https","ws","wss","urn","urn:uuid"];function IN(t){return ON.indexOf(t)!==-1}function qf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function xS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function bS(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 AN(t){return t.secure=qf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function NN(t){if((t.port===(qf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),n=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=n&&n!=="/"?n:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function DN(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match($N);if(n&&n[0]===t.path){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Vf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function MN(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Vf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function jN(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!CN(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function LN(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var SS={scheme:"http",domainHost:!0,parse:xS,serialize:bS},zN={scheme:"https",domainHost:SS.domainHost,parse:xS,serialize:bS},Pc={scheme:"ws",domainHost:!0,parse:AN,serialize:NN},HN={scheme:"wss",domainHost:Pc.domainHost,parse:Pc.parse,serialize:Pc.serialize},UN={scheme:"urn",parse:DN,serialize:MN,skipNormalize:!0},FN={scheme:"urn:uuid",parse:jN,serialize:LN,skipNormalize:!0},Rc={http:SS,https:zN,ws:Pc,wss:HN,urn:UN,"urn:uuid":FN};Object.setPrototypeOf(Rc,null);function Vf(t){return t&&(Rc[t]||Rc[t.toLowerCase()])||void 0}kS.exports={wsIsSecure:qf,SCHEMES:Rc,isValidSchemeName:IN,getSchemeHandler:Vf}});var jS=I((H9,Oc)=>{"use strict";var{normalizeIPv6:RS,removeDotSegments:Ei,recomposeAuthority:BN,normalizePercentEncoding:CS,normalizePathEncoding:ZN,serializePathEncoding:ES,normalizeQueryFragmentEncoding:wS,encodeQuery:qN,encodeFragment:VN,reescapeHostDelimiters:WN,isIPv4:$S,nonSimpleDomain:KN}=Zf(),{SCHEMES:OS,getSchemeHandler:Wf}=vS(),IS=/^[A-Za-z][A-Za-z0-9+.-]*$/u,AS="URI scheme is malformed.";function TS(t){let e=unescape(String(t));if(!IS.test(e))throw new TypeError(AS);return e}function GN(t,e){return typeof t=="string"?t=rD(t,e):typeof t=="object"&&(t=$c(ro(t,e),e)),t}function JN(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Cc(t,r),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:m,malformedHost:p,malformedScheme:h}=Cc(e,r);if(s||d||i||f||a||m||c||p||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=NS(o,l,r,!0),y=Wf(n&&n.scheme||g.scheme),_=g.host,x=_!==void 0&&_!==""&&($S(_)||RS(_).isIPV6);DS(g,n||{},y,x);let b=_&&_.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(_);if(g.error&&!b)throw new Error(g.error);return r.skipEscape=!0,ro(g,r)}function NS(t,e,n,r){let o={};return r||(t=$c(ro(t,n),n),e=$c(ro(e,n),n)),n=n||{},!n.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 XN(t,e,n){let r=PS(t,n),o=PS(e,n);return r!==void 0&&o!==void 0&&r===o}function ro(t,e){let n={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:""},r=Object.assign({},e),o=[];n.scheme&&(n.scheme=TS(n.scheme));let s=Wf(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r);let i=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,a=!r.skipEscape&&n.scheme===void 0&&!i;n.path!==void 0&&(r.skipEscape?n.path=CS(n.path):n.path=ES(n.path,a)),r.reference!=="suffix"&&n.scheme&&(n.scheme=TS(n.scheme),o.push(n.scheme,":"));let c=BN(n);if(c!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(c),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let u=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(u=Ei(u)),a&&(u=ES(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return n.query!==void 0&&o.push("?",qN(n.query)),n.fragment!==void 0&&o.push("#",VN(n.fragment)),o.join("")}var YN=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,QN=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,eD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function tD(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function vi(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function Kf(t){return t[0]==="["&&t[t.length-1]==="]"}function nD(t){let e=t[4];return vi(t[3])||e!==void 0&&!Kf(e)&&vi(e)||vi(t[6])||vi(t[7])||vi(t[8])}function DS(t,e,n,r){if(!e.unicodeSupport&&(!n||!n.unicodeSupport)&&t.host&&!Kf(t.host)&&(e.domainHost||n&&n.domainHost)&&r===!1&&KN(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Cc(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let d=t.match(QN);d!==null&&d[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);let f=t.match(eD);if(f!==null){let p=f[1],h=p.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",o=!0):p.length!==h.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(YN);if(m){if(r.scheme=m[1],r.userinfo=m[3],r.host=m[4],r.port=parseInt(m[5],10),r.path=m[6]||"",r.query=m[7],r.fragment=m[8],r.scheme!==void 0){let g=unescape(r.scheme);IS.test(g)?r.scheme=g.toLowerCase():(r.error=r.error||AS,u=!0)}s=nD(m),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=m[5]);let p=tD(r,m);if(p!==void 0&&(r.error=r.error||p,o=!0),r.host)if($S(r.host)===!1){let y=Kf(r.host),_=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,x=RS(r.host);l=x.isIPV6||x.isIPVFuture===!0,c=_&&(!y||x.error===!0),r.host=l?x.host:x.host.toLowerCase(),c&&(r.error=r.error||"URI host is malformed.",o=!0)}else l=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let h=Wf(n.scheme||r.scheme);if(c||(a=DS(r,n,h,l)),!h||h&&!h.skipNormalize){if(t.indexOf("%")!==-1&&r.host!==void 0&&!c){let g=l?r.host:CS(r.host,!0);r.host=WN(g,l)}r.path&&(r.path=ZN(r.path)),r.query&&(r.query=wS(r.query)),r.fragment&&(r.fragment=wS(r.fragment))}h&&h.parse&&(h.parse(r,n),h===OS.urn&&r.nid===void 0&&(i=!0))}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function $c(t,e){return Cc(t,e).parsed}function rD(t,e){return MS(t,e).normalized}function MS(t,e){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Cc(t,e);return{normalized:r||o||s||i||a?t:ro(n,e),malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function PS(t,e){if(typeof t!="string"&&typeof t!="object")return;let n;try{n=typeof t=="string"?t:ro(t,e)}catch{return}let{normalized:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=MS(n,e);return o||s||i||a||c?void 0:r}var Gf={SCHEMES:OS,normalize:GN,resolve:JN,resolveComponent:NS,equal:XN,serialize:ro,parse:$c};Oc.exports=Gf;Oc.exports.default=Gf;Oc.exports.fastUri=Gf});var zS=I(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var LS=jS();LS.code='require("ajv/dist/runtime/uri").default';Jf.default=LS});var WS=I(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.CodeGen=Qe.Name=Qe.nil=Qe.stringify=Qe.str=Qe._=Qe.KeywordCxt=void 0;var oD=Si();Object.defineProperty(Qe,"KeywordCxt",{enumerable:!0,get:function(){return oD.KeywordCxt}});var es=ee();Object.defineProperty(Qe,"_",{enumerable:!0,get:function(){return es._}});Object.defineProperty(Qe,"str",{enumerable:!0,get:function(){return es.str}});Object.defineProperty(Qe,"stringify",{enumerable:!0,get:function(){return es.stringify}});Object.defineProperty(Qe,"nil",{enumerable:!0,get:function(){return es.nil}});Object.defineProperty(Qe,"Name",{enumerable:!0,get:function(){return es.Name}});Object.defineProperty(Qe,"CodeGen",{enumerable:!0,get:function(){return es.CodeGen}});var sD=Ec(),ZS=ki(),iD=xf(),wi=Tc(),aD=ee(),Ti=_i(),Ic=yi(),Yf=le(),HS=dS(),cD=zS(),qS=(t,e)=>new RegExp(t,e);qS.code="new RegExp";var uD=["removeAdditional","useDefaults","coerceTypes"],lD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),dD={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."},pD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},US=200;function fD(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,x,b,v,O,R,j,M;let V=t.strict,w=(e=t.code)===null||e===void 0?void 0:e.optimize,P=w===!0||w===void 0?1:w||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:qS,se=(o=t.uriResolver)!==null&&o!==void 0?o:cD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:V)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:V)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:V)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:P,regExp:H}:{optimize:P,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:US,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:US,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(j=t.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(M=t.int32range)!==null&&M!==void 0?M:!0,uriResolver:se}}var Pi=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,...fD(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new aD.ValueScope({scope:{},prefixes:lD,es5:n,lines:r}),this.logger=xD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,iD.getRules)(),FS.call(this,dD,e,"NOT SUPPORTED"),FS.call(this,pD,e,"DEPRECATED","warn"),this._metaOpts=yD.call(this),e.formats&&hD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&gD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),mD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=HS;r==="id"&&(o={...HS},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);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 ZS.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ti.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=BS.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new wi.SchemaEnv({schema:{},schemaId:r});if(n=wi.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=BS.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ti.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(SD.call(this,r,n),!n)return(0,Yf.eachItem)(r,s=>Xf.call(this,s)),this;vD.call(this,n);let o={...n,type:(0,Ic.getJSONTypes)(n.type),schemaType:(0,Ic.getJSONTypes)(n.schemaType)};return(0,Yf.eachItem)(r,o.type.length===0?s=>Xf.call(this,s,o):s=>o.type.forEach(i=>Xf.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=VS(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ti.normalizeId)(i||r);let u=Ti.getSchemaRefs.call(this,e,r);return c=new wi.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):wi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{wi.compileSchema.call(this,e)}finally{this.opts=n}}};Pi.ValidationError=sD.default;Pi.MissingRefError=ZS.default;Qe.default=Pi;function FS(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function BS(t){return t=(0,Ti.normalizeId)(t),this.schemas[t]||this.refs[t]}function mD(){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 hD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function gD(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function yD(){let t={...this.opts};for(let e of uD)delete t[e];return t}var _D={log(){},warn(){},error(){}};function xD(t){if(t===!1)return _D;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 bD=/^[a-z_$][a-z0-9_$:-]*$/i;function SD(t,e){let{RULES:n}=this;if((0,Yf.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!bD.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xf(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Ic.getJSONTypes)(e.type),schemaType:(0,Ic.getJSONTypes)(e.schemaType)}};e.before?kD.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function kD(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function vD(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=VS(e)),t.validateSchema=this.compile(e,!0))}var ED={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function VS(t){return{anyOf:[t,ED]}}});var KS=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var wD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qf.default=wD});var YS=I(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.callRef=oo.getValidate=void 0;var TD=ki(),GS=Ft(),Pt=ee(),ts=zn(),JS=Tc(),Ac=le(),PD={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=JS.resolveRef.call(c,u,o,n);if(l===void 0)throw new TD.default(r.opts.uriResolver,o,n);if(l instanceof JS.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return Nc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return Nc(t,(0,Pt._)`${p}.validate`,u,u.$async)}function f(p){let h=XS(t,p);Nc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Pt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function XS(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}oo.getValidate=XS;function Nc(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?ts.default.this:Pt.nil;r?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,Pt._)`await ${(0,GS.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,Pt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,GS.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,Pt._)`${p}.errors`;o.assign(ts.default.vErrors,(0,Pt._)`${ts.default.vErrors} === null ? ${h} : ${ts.default.vErrors}.concat(${h})`),o.assign(ts.default.errors,(0,Pt._)`${ts.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=n?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Ac.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,Pt._)`${p}.evaluated.props`);s.props=Ac.mergeEvaluated.props(o,y,s.props,Pt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Ac.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,Pt._)`${p}.evaluated.items`);s.items=Ac.mergeEvaluated.items(o,y,s.items,Pt.Name)}}}oo.callRef=Nc;oo.default=PD});var QS=I(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var RD=KS(),CD=YS(),$D=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",RD.default,CD.default];em.default=$D});var ek=I(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Dc=ee(),pr=Dc.operators,Mc={maximum:{okStr:"<=",ok:pr.LTE,fail:pr.GT},minimum:{okStr:">=",ok:pr.GTE,fail:pr.LT},exclusiveMaximum:{okStr:"<",ok:pr.LT,fail:pr.GTE},exclusiveMinimum:{okStr:">",ok:pr.GT,fail:pr.LTE}},OD={message:({keyword:t,schemaCode:e})=>(0,Dc.str)`must be ${Mc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Dc._)`{comparison: ${Mc[t].okStr}, limit: ${e}}`},ID={keyword:Object.keys(Mc),type:"number",schemaType:"number",$data:!0,error:OD,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Dc._)`${n} ${Mc[e].fail} ${r} || isNaN(${n})`)}};tm.default=ID});var tk=I(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Ri=ee(),AD={message:({schemaCode:t})=>(0,Ri.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ri._)`{multipleOf: ${t}}`},ND={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:AD,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ri._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ri._)`${i} !== parseInt(${i})`;t.fail$data((0,Ri._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};nm.default=ND});var rk=I(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});function nk(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}rm.default=nk;nk.code='require("ajv/dist/runtime/ucs2length").default'});var ok=I(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var so=ee(),DD=le(),MD=rk(),jD={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,so.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,so._)`{limit: ${t}}`},LD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:jD,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?so.operators.GT:so.operators.LT,i=o.opts.unicode===!1?(0,so._)`${n}.length`:(0,so._)`${(0,DD.useFunc)(t.gen,MD.default)}(${n})`;t.fail$data((0,so._)`${i} ${s} ${r}`)}};om.default=LD});var sk=I(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var zD=Ft(),HD=le(),ns=ee(),UD={message:({schemaCode:t})=>(0,ns.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ns._)`{pattern: ${t}}`},FD={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:UD,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,ns._)`new RegExp`:(0,HD.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,ns._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,ns._)`!${l}`)}else{let c=(0,zD.usePattern)(t,o);t.fail$data((0,ns._)`!${c}.test(${n})`)}}};sm.default=FD});var ik=I(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Ci=ee(),BD={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ci.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ci._)`{limit: ${t}}`},ZD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:BD,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ci.operators.GT:Ci.operators.LT;t.fail$data((0,Ci._)`Object.keys(${n}).length ${o} ${r}`)}};im.default=ZD});var ak=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var $i=Ft(),Oi=ee(),qD=le(),VD={message:({params:{missingProperty:t}})=>(0,Oi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Oi._)`{missingProperty: ${t}}`},WD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:VD,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of n)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,qD.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Oi.nil,d);else for(let m of n)(0,$i.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,$i.checkMissingProp)(t,n,m)),(0,$i.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,$i.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,$i.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Oi.not)(p),()=>{t.error(),e.break()})},Oi.nil)}}};am.default=WD});var ck=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var Ii=ee(),KD={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ii.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ii._)`{limit: ${t}}`},GD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:KD,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ii.operators.GT:Ii.operators.LT;t.fail$data((0,Ii._)`${n}.length ${o} ${r}`)}};cm.default=GD});var jc=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var uk=Pf();uk.code='require("ajv/dist/runtime/equal").default';um.default=uk});var lk=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var lm=yi(),et=ee(),JD=le(),XD=jc(),YD={message:({params:{i:t,j:e}})=>(0,et.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,et._)`{i: ${t}, j: ${e}}`},QD={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:YD,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,lm.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,et._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,et._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,et._)`${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,lm.checkDataTypes)(u,g,a.opts.strictNumbers,lm.DataType.Wrong),_=e.const("indices",(0,et._)`{}`);e.for((0,et._)`;${p}--;`,()=>{e.let(g,(0,et._)`${n}[${p}]`),e.if(y,(0,et._)`continue`),u.length>1&&e.if((0,et._)`typeof ${g} == "string"`,(0,et._)`${g} += "_"`),e.if((0,et._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,et._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,et._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,JD.useFunc)(e,XD.default),y=e.name("outer");e.label(y).for((0,et._)`;${p}--;`,()=>e.for((0,et._)`${h} = ${p}; ${h}--;`,()=>e.if((0,et._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};dm.default=QD});var dk=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var pm=ee(),eM=le(),tM=jc(),nM={message:"must be equal to constant",params:({schemaCode:t})=>(0,pm._)`{allowedValue: ${t}}`},rM={keyword:"const",$data:!0,error:nM,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,pm._)`!${(0,eM.useFunc)(e,tM.default)}(${n}, ${o})`):t.fail((0,pm._)`${s} !== ${n}`)}};fm.default=rM});var pk=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Ai=ee(),oM=le(),sM=jc(),iM={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ai._)`{allowedValues: ${t}}`},aM={keyword:"enum",schemaType:"array",$data:!0,error:iM,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,oM.useFunc)(e,sM.default)),l;if(a||r)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,Ai.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,Ai._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,Ai._)`${u()}(${n}, ${m}[${p}])`:(0,Ai._)`${n} === ${h}`}}};mm.default=aM});var fk=I(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var cM=ek(),uM=tk(),lM=ok(),dM=sk(),pM=ik(),fM=ak(),mM=ck(),hM=lk(),gM=dk(),yM=pk(),_M=[cM.default,uM.default,lM.default,dM.default,pM.default,fM.default,mM.default,hM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},gM.default,yM.default];hm.default=_M});var ym=I(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.validateAdditionalItems=void 0;var io=ee(),gm=le(),xM={message:({params:{len:t}})=>(0,io.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,io._)`{limit: ${t}}`},bM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:xM,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,gm.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}mk(t,r)}};function mk(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,io._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,io._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,gm.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,io._)`${a} <= ${e.length}`);n.if((0,io.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:gm.Type.Num},u),i.allErrors||n.if((0,io.not)(u),()=>n.break())})}}Ni.validateAdditionalItems=mk;Ni.default=bM});var _m=I(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.validateTuple=void 0;var hk=ee(),Lc=le(),SM=Ft(),kM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return gk(t,"additionalItems",e);n.items=!0,!(0,Lc.alwaysValidSchema)(n,e)&&t.ok((0,SM.validateArray)(t))}};function gk(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=Lc.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,hk._)`${s}.length`);n.forEach((d,f)=>{(0,Lc.alwaysValidSchema)(a,d)||(r.if((0,hk._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=n.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,Lc.checkStrictMode)(a,g,f.strictTuples)}}}Di.validateTuple=gk;Di.default=kM});var yk=I(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var vM=_m(),EM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,vM.validateTuple)(t,"items")};xm.default=EM});var xk=I(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var _k=ee(),wM=le(),TM=Ft(),PM=ym(),RM={message:({params:{len:t}})=>(0,_k.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,_k._)`{limit: ${t}}`},CM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:RM,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,wM.alwaysValidSchema)(r,e)&&(o?(0,PM.validateAdditionalItems)(t,o):t.ok((0,TM.validateArray)(t)))}};bm.default=CM});var bk=I(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var Zt=ee(),zc=le(),$M={message:({params:{min:t,max:e}})=>e===void 0?(0,Zt.str)`must contain at least ${t} valid item(s)`:(0,Zt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Zt._)`{minContains: ${t}}`:(0,Zt._)`{minContains: ${t}, maxContains: ${e}}`},OM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:$M,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Zt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,zc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,zc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,zc.alwaysValidSchema)(s,n)){let h=(0,Zt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Zt._)`${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,Zt._)`${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:zc.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Zt._)`${h}++`),a===void 0?e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Zt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Sm.default=OM});var vk=I(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.validateSchemaDeps=vn.validatePropertyDeps=vn.error=void 0;var km=ee(),IM=le(),Mi=Ft();vn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,km.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,km._)`{property: ${t},
6
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function WI({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function Sf(t,e,n,r=Ko.Correct){let o=r===Ko.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 r===Ko.Correct?s:(0,Y.not)(s);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,n?(0,Y._)`isFinite(${e})`:Y.nil)}}ct.checkDataType=Sf;function kf(t,e,n,r){if(t.length===1)return Sf(t[0],e,n,r);let o,s=(0,$b.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,Sf(i,e,n,r));return o}ct.checkDataTypes=kf;var KI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function vf(t){let e=GI(t);(0,FI.reportError)(e,KI)}ct.reportTypeError=vf;function GI(t){let{gen:e,data:n,schema:r}=t,o=(0,$b.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var Nb=I(xc=>{"use strict";Object.defineProperty(xc,"__esModule",{value:!0});xc.assignDefaults=void 0;var Go=ee(),JI=le();function XI(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)Ab(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>Ab(t,s,o.default))}xc.assignDefaults=XI;function Ab(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Go._)`${s}${(0,Go.getProperty)(e)}`;if(o){(0,JI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Go._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Go._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Go._)`${a} = ${(0,Go.stringify)(n)}`)}});var Ft=I(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.validateUnion=ge.validateArray=ge.usePattern=ge.callValidateCode=ge.schemaProperties=ge.allSchemaProperties=ge.noPropertyInData=ge.propertyInData=ge.isOwnProperty=ge.hasPropFunc=ge.reportMissingProp=ge.checkMissingProp=ge.checkReportMissingProp=void 0;var Ee=ee(),Ef=le(),ar=Ln(),YI=le();function QI(t,e){let{gen:n,data:r,it:o}=t;n.if(Tf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ee._)`${e}`},!0),t.error()})}ge.checkReportMissingProp=QI;function eA({gen:t,data:e,it:{opts:n}},r,o){return(0,Ee.or)(...r.map(s=>(0,Ee.and)(Tf(t,e,s,n.ownProperties),(0,Ee._)`${o} = ${s}`)))}ge.checkMissingProp=eA;function tA(t,e){t.setParams({missingProperty:e},!0),t.error()}ge.reportMissingProp=tA;function Db(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ee._)`Object.prototype.hasOwnProperty`})}ge.hasPropFunc=Db;function wf(t,e,n){return(0,Ee._)`${Db(t)}.call(${e}, ${n})`}ge.isOwnProperty=wf;function nA(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} !== undefined`;return r?(0,Ee._)`${o} && ${wf(t,e,n)}`:o}ge.propertyInData=nA;function Tf(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} === undefined`;return r?(0,Ee.or)(o,(0,Ee.not)(wf(t,e,n))):o}ge.noPropertyInData=Tf;function Mb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ge.allSchemaProperties=Mb;function rA(t,e){return Mb(e).filter(n=>!(0,Ef.alwaysValidSchema)(t,e[n]))}ge.schemaProperties=rA;function oA({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ee._)`${t}, ${e}, ${r}${o}`:e,d=[[ar.default.instancePath,(0,Ee.strConcat)(ar.default.instancePath,s)],[ar.default.parentData,i.parentData],[ar.default.parentDataProperty,i.parentDataProperty],[ar.default.rootData,ar.default.rootData]];i.opts.dynamicRef&&d.push([ar.default.dynamicAnchors,ar.default.dynamicAnchors]);let f=(0,Ee._)`${l}, ${n.object(...d)}`;return c!==Ee.nil?(0,Ee._)`${a}.call(${c}, ${f})`:(0,Ee._)`${a}(${f})`}ge.callValidateCode=oA;var sA=(0,Ee._)`new RegExp`;function iA({gen:t,it:{opts:e}},n){let r=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(n,r);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ee._)`${o.code==="new RegExp"?sA:(0,YI.useFunc)(t,o)}(${n}, ${r})`})}ge.usePattern=iA;function aA(t){let{gen:e,data:n,keyword:r,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,Ee._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:Ef.Type.Num},s),e.if((0,Ee.not)(s),a)})}}ge.validateArray=aA;function cA(t){let{gen:e,schema:n,keyword:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(n.some(c=>(0,Ef.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>n.forEach((c,u)=>{let l=t.subschema({keyword:r,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ee._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ee.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ge.validateUnion=cA});var zb=I(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.validateKeywordUsage=bn.validSchemaType=bn.funcKeywordCode=bn.macroKeywordCode=void 0;var mt=ee(),Qr=Ln(),uA=Ft(),lA=gi();function dA(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Lb(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:mt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}bn.macroKeywordCode=dA;function pA(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;mA(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Lb(r,o,u),d=r.let("valid");t.block$data(d,f),t.ok((n=e.valid)!==null&&n!==void 0?n:d);function f(){if(e.errors===!1)h(),e.modifying&&jb(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&jb(t),g(()=>fA(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,mt._)`await `),_=>r.assign(d,!1).if((0,mt._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,mt._)`${_}.errors`),()=>r.throw(_))),y}function p(){let y=(0,mt._)`${l}.errors`;return r.assign(y,null),h(mt.nil),y}function h(y=e.async?(0,mt._)`await `:mt.nil){let _=c.opts.passContext?Qr.default.this:Qr.default.self,x=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,mt._)`${y}${(0,uA.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;r.if((0,mt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}bn.funcKeywordCode=pA;function jb(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,mt._)`${r.parentData}[${r.parentDataProperty}]`))}function fA(t,e){let{gen:n}=t;n.if((0,mt._)`Array.isArray(${e})`,()=>{n.assign(Qr.default.vErrors,(0,mt._)`${Qr.default.vErrors} === null ? ${e} : ${Qr.default.vErrors}.concat(${e})`).assign(Qr.default.errors,(0,mt._)`${Qr.default.vErrors}.length`),(0,lA.extendErrors)(t)},()=>t.error())}function mA({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Lb(t,e,n){if(n===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof n=="function"?{ref:n}:{ref:n,code:(0,mt.stringify)(n)})}function hA(t,e,n=!1){return!e.length||e.some(r=>r==="array"?Array.isArray(t):r==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==r||n&&typeof t>"u")}bn.validSchemaType=hA;function gA({schema:t,opts:e,self:n,errSchemaPath:r},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 "${r}": `+n.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")n.logger.error(c);else throw new Error(c)}}bn.validateKeywordUsage=gA});var Ub=I(cr=>{"use strict";Object.defineProperty(cr,"__esModule",{value:!0});cr.extendSubschemaMode=cr.extendSubschemaData=cr.getSubschema=void 0;var Sn=ee(),Hb=le();function yA(t,{keyword:e,schemaProp:n,schema:r,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&r!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return n===void 0?{schema:a,schemaPath:(0,Sn._)`${t.schemaPath}${(0,Sn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,Sn._)`${t.schemaPath}${(0,Sn.getProperty)(e)}${(0,Sn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Hb.escapeFragment)(n)}`}}if(r!==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:r,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}cr.getSubschema=yA;function _A(t,e,{dataProp:n,dataPropType:r,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&n!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(n!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,f=a.let("data",(0,Sn._)`${e.data}${(0,Sn.getProperty)(n)}`,!0);c(f),t.errorPath=(0,Sn.str)`${u}${(0,Hb.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,Sn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof Sn.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]}}cr.extendSubschemaData=_A;function xA(t,{jtdDiscriminator:e,jtdMetadata:n,compositeRule:r,createErrors:o,allErrors:s}){r!==void 0&&(t.compositeRule=r),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=n}cr.extendSubschemaMode=xA});var Pf=I((O9,Fb)=>{"use strict";Fb.exports=function t(e,n){if(e===n)return!0;if(e&&n&&typeof e=="object"&&typeof n=="object"){if(e.constructor!==n.constructor)return!1;var r,o,s;if(Array.isArray(e)){if(r=e.length,r!=n.length)return!1;for(o=r;o--!==0;)if(!t(e[o],n[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===n.source&&e.flags===n.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===n.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===n.toString();if(s=Object.keys(e),r=s.length,r!==Object.keys(n).length)return!1;for(o=r;o--!==0;)if(!Object.prototype.hasOwnProperty.call(n,s[o]))return!1;for(o=r;o--!==0;){var i=s[o];if(!t(e[i],n[i]))return!1}return!0}return e!==e&&n!==n}});var Zb=I((I9,Bb)=>{"use strict";var ur=Bb.exports=function(t,e,n){typeof e=="function"&&(n=e,e={}),n=e.cb||n;var r=typeof n=="function"?n:n.pre||function(){},o=n.post||function(){};bc(e,r,o,t,"",t)};ur.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ur.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ur.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ur.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function bc(t,e,n,r,o,s,i,a,c,u){if(r&&typeof r=="object"&&!Array.isArray(r)){e(r,o,s,i,a,c,u);for(var l in r){var d=r[l];if(Array.isArray(d)){if(l in ur.arrayKeywords)for(var f=0;f<d.length;f++)bc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in ur.propsKeywords){if(d&&typeof d=="object")for(var m in d)bc(t,e,n,d[m],o+"/"+l+"/"+bA(m),s,o,l,r,m)}else(l in ur.keywords||t.allKeys&&!(l in ur.skipKeywords))&&bc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function bA(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var _i=I(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.getSchemaRefs=wt.resolveUrl=wt.normalizeId=wt._getFullPath=wt.getFullPath=wt.inlineRef=void 0;var SA=le(),kA=Pf(),vA=Zb(),EA=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wA(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Rf(t):e?qb(t)<=e:!1}wt.inlineRef=wA;var TA=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Rf(t){for(let e in t){if(TA.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(Rf)||typeof n=="object"&&Rf(n))return!0}return!1}function qb(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!EA.has(n)&&(typeof t[n]=="object"&&(0,SA.eachItem)(t[n],r=>e+=qb(r)),e===1/0))return 1/0}return e}function Vb(t,e="",n){n!==!1&&(e=Jo(e));let r=t.parse(e);return Wb(t,r)}wt.getFullPath=Vb;function Wb(t,e){return t.serialize(e).split("#")[0]+"#"}wt._getFullPath=Wb;var PA=/#\/?$/;function Jo(t){return t?t.replace(PA,""):""}wt.normalizeId=Jo;function RA(t,e,n){return n=Jo(n),t.resolve(e,n)}wt.resolveUrl=RA;var CA=/^[a-z_][-a-z0-9._]*$/i;function $A(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Jo(t[n]||e),s={"":o},i=Vb(r,o,!1),a={},c=new Set;return vA(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(x){let b=this.opts.uriResolver.resolve;if(x=Jo(g?b(g,x):x),c.has(x))throw l(x);c.add(x);let v=this.refs[x];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,x):x!==Jo(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!CA.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,f,m){if(f!==void 0&&!kA(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}wt.getSchemaRefs=$A});var Si=I(lr=>{"use strict";Object.defineProperty(lr,"__esModule",{value:!0});lr.getData=lr.KeywordCxt=lr.validateFunctionCode=void 0;var Yb=Pb(),Kb=yi(),$f=bf(),Sc=yi(),OA=Nb(),bi=zb(),Cf=Ub(),F=ee(),G=Ln(),IA=_i(),zn=le(),xi=gi();function AA(t){if(tS(t)&&(nS(t),eS(t))){MA(t);return}Qb(t,()=>(0,Yb.topBoolOrEmptySchema)(t))}lr.validateFunctionCode=AA;function Qb({gen:t,validateName:e,schema:n,schemaEnv:r,opts:o},s){o.code.es5?t.func(e,(0,F._)`${G.default.data}, ${G.default.valCxt}`,r.$async,()=>{t.code((0,F._)`"use strict"; ${Gb(n,o)}`),DA(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${NA(o)}`,r.$async,()=>t.code(Gb(n,o)).code(s))}function NA(t){return(0,F._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,F._)`, ${G.default.dynamicAnchors}={}`:F.nil}}={}`}function DA(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,F._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,F._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,F._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,F._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,F._)`""`),t.var(G.default.parentData,(0,F._)`undefined`),t.var(G.default.parentDataProperty,(0,F._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`{}`)})}function MA(t){let{schema:e,opts:n,gen:r}=t;Qb(t,()=>{n.$comment&&e.$comment&&oS(t),UA(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&jA(t),rS(t),ZA(t)})}function jA(t){let{gen:e,validateName:n}=t;t.evaluated=e.const("evaluated",(0,F._)`${n}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function Gb(t,e){let n=typeof t=="object"&&t[e.schemaId];return n&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${n} */`:F.nil}function LA(t,e){if(tS(t)&&(nS(t),eS(t))){zA(t,e);return}(0,Yb.boolOrEmptySchema)(t,e)}function eS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function tS(t){return typeof t.schema!="boolean"}function zA(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&oS(t),FA(t),BA(t);let s=r.const("_errs",G.default.errors);rS(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function nS(t){(0,zn.checkUnknownRules)(t),HA(t)}function rS(t,e){if(t.opts.jtd)return Jb(t,[],!1,e);let n=(0,Kb.getSchemaTypes)(t.schema),r=(0,Kb.coerceAndCheckDataType)(t,n);Jb(t,n,!r,e)}function HA(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,zn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function UA(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,zn.checkStrictMode)(t,"default is ignored in the schema root")}function FA(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,IA.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function BA(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function oS({gen:t,schemaEnv:e,schema:n,errSchemaPath:r,opts:o}){let s=n.$comment;if(o.$comment===!0)t.code((0,F._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${r}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function ZA(t){let{gen:e,schemaEnv:n,validateName:r,ValidationError:o,opts:s}=t;n.$async?e.if((0,F._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,F._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,F._)`${r}.errors`,G.default.vErrors),s.unevaluated&&qA(t),e.return((0,F._)`${G.default.errors} === 0`))}function qA({gen:t,evaluated:e,props:n,items:r}){n instanceof F.Name&&t.assign((0,F._)`${e}.props`,n),r instanceof F.Name&&t.assign((0,F._)`${e}.items`,r)}function Jb(t,e,n,r){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,zn.schemaHasRulesButRef)(s,l))){o.block(()=>iS(t,"$ref",l.all.$ref.definition));return}c.jtd||VA(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,$f.shouldUseGroup)(s,f)&&(f.type?(o.if((0,Sc.checkDataType)(f.type,i,c.strictNumbers)),Xb(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,Sc.reportTypeError)(t)),o.endIf()):Xb(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function Xb(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,OA.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,$f.shouldUseRule)(r,s)&&iS(t,s.keyword,s.definition,e.type)})}function VA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(WA(t,e),t.opts.allowUnionTypes||KA(t,e),GA(t,t.dataTypes))}function WA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{sS(t.dataTypes,n)||Of(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),XA(t,e)}}function KA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Of(t,"use allowUnionTypes to allow union type keyword")}function GA(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,$f.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>JA(e,i))&&Of(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function JA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function sS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function XA(t,e){let n=[];for(let r of t.dataTypes)sS(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function Of(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,zn.checkStrictMode)(t,e,t.opts.strictTypes)}var kc=class{constructor(e,n,r){if((0,bi.validateKeywordUsage)(e,n,r),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=r,this.data=e.data,this.schema=e.schema[r],this.$data=n.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,zn.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",aS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,bi.validSchemaType)(this.schema,n.schemaType,n.allowUndefined))throw new Error(`${r} value must be ${JSON.stringify(n.schemaType)}`);("code"in n?n.trackErrors:n.errors!==!1)&&(this.errsCount=e.gen.const("_errs",G.default.errors))}result(e,n,r){this.failResult((0,F.not)(e),n,r)}failResult(e,n,r){this.gen.if(e),r?r():this.error(),n?(this.gen.else(),n(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,n){this.failResult((0,F.not)(e),void 0,n)}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:n}=this;this.fail((0,F._)`${n} !== undefined && (${(0,F.or)(this.invalid$data(),e)})`)}error(e,n,r){if(n){this.setParams(n),this._error(e,r),this.setParams({});return}this._error(e,r)}_error(e,n){(e?xi.reportExtraError:xi.reportError)(this,this.def.error,n)}$dataError(){(0,xi.reportError)(this,this.def.$dataError||xi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,xi.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,n){n?Object.assign(this.params,e):this.params=e}block$data(e,n,r=F.nil){this.gen.block(()=>{this.check$data(e,r),n()})}check$data(e=F.nil,n=F.nil){if(!this.$data)return;let{gen:r,schemaCode:o,schemaType:s,def:i}=this;r.if((0,F.or)((0,F._)`${o} === undefined`,n)),e!==F.nil&&r.assign(e,!0),(s.length||i.validateSchema)&&(r.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&r.assign(e,!1)),r.else()}invalid$data(){let{gen:e,schemaCode:n,schemaType:r,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(r.length){if(!(n instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(r)?r:[r];return(0,F._)`${(0,Sc.checkDataTypes)(c,n,s.opts.strictNumbers,Sc.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${c}(${n})`}return F.nil}}subschema(e,n){let r=(0,Cf.getSubschema)(this.it,e);(0,Cf.extendSubschemaData)(r,this.it,e),(0,Cf.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return LA(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=zn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=zn.mergeEvaluated.items(o,e.items,r.items,n)))}mergeValidEvaluated(e,n){let{it:r,gen:o}=this;if(r.opts.unevaluated&&(r.props!==!0||r.items!==!0))return o.if(n,()=>this.mergeEvaluated(e,F.Name)),!0}};lr.KeywordCxt=kc;function iS(t,e,n,r){let o=new kc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,bi.funcKeywordCode)(o,n):"macro"in n?(0,bi.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,bi.funcKeywordCode)(o,n)}var YA=/^\/(?:[^~]|~0|~1)*$/,QA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function aS(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!YA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=QA.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 r[e-l]}if(l>e)throw new Error(c("data",l));if(s=n[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,zn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}lr.getData=aS});var vc=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var If=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Af.default=If});var ki=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Nf=_i(),Df=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,Nf.resolveUrl)(e,n,r),this.missingSchema=(0,Nf.normalizeId)((0,Nf.getFullPath)(e,this.missingRef))}};Mf.default=Df});var wc=I(Bt=>{"use strict";Object.defineProperty(Bt,"__esModule",{value:!0});Bt.resolveSchema=Bt.getCompilingSchema=Bt.resolveRef=Bt.compileSchema=Bt.SchemaEnv=void 0;var sn=ee(),eN=vc(),eo=Ln(),an=_i(),cS=le(),tN=Si(),Xo=class{constructor(e){var n;this.refs={},this.dynamicAnchors={};let r;typeof e.schema=="object"&&(r=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(n=e.baseId)!==null&&n!==void 0?n:(0,an.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};Bt.SchemaEnv=Xo;function Lf(t){let e=uS.call(this,t);if(e)return e;let n=(0,an.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new sn.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:eN.default,code:(0,sn._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:eo.default.data,parentData:eo.default.parentData,parentDataProperty:eo.default.parentDataProperty,dataNames:[eo.default.data],dataPathArr:[sn.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,sn.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:sn.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,sn._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,tN.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(eo.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${eo.default.self}`,`${eo.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 sn.Name?void 0:p,items:h instanceof sn.Name?void 0:h,dynamicProps:p instanceof sn.Name,dynamicItems:h instanceof sn.Name},m.source&&(m.source.evaluated=(0,sn.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)}}Bt.compileSchema=Lf;function nN(t,e,n){var r;n=(0,an.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=sN.call(this,t,n);if(s===void 0){let i=(r=t.localRefs)===null||r===void 0?void 0:r[n],{schemaId:a}=this.opts;i&&(s=new Xo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=rN.call(this,s)}Bt.resolveRef=nN;function rN(t){return(0,an.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Lf.call(this,t)}function uS(t){for(let e of this._compilations)if(oN(e,t))return e}Bt.getCompilingSchema=uS;function oN(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function sN(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||Ec.call(this,t,e)}function Ec(t,e){let n=this.opts.uriResolver.parse(e),r=(0,an._getFullPath)(this.opts.uriResolver,n),o=(0,an.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return jf.call(this,n,t);let s=(0,an.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Ec.call(this,t,i);return typeof a?.schema!="object"?void 0:jf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Lf.call(this,i),s===(0,an.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,an.resolveUrl)(this.opts.uriResolver,o,u)),new Xo({schema:a,schemaId:c,root:t,baseId:o})}return jf.call(this,n,i)}}Bt.resolveSchema=Ec;var iN=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function jf(t,{baseId:e,schema:n,root:r}){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 n=="boolean")return;let c=n[(0,cS.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!iN.has(a)&&u&&(e=(0,an.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,cS.schemaHasRulesButRef)(n,this.RULES)){let a=(0,an.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=Ec.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Xo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var lS=I((L9,aN)=>{aN.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Zf=I((z9,yS)=>{"use strict";var cN=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Hf=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),uN=RegExp.prototype.test.bind(/^\d*$/u),to=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),Uf=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),pS=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),Ff=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),lN=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),Tt=new Array(256);{let t="0123456789ABCDEF";for(let e=0;e<256;e++)Tt[e]="%"+t[e>>4]+t[e&15]}function ut(t){return t<2048?Tt[192|t>>6]+Tt[128|t&63]:t<65536?Tt[224|t>>12]+Tt[128|t>>6&63]+Tt[128|t&63]:Tt[240|t>>18]+Tt[128|t>>12&63]+Tt[128|t>>6&63]+Tt[128|t&63]}function dN(t){let e="",n=0,r=0;for(r=0;r<t.length;r++)if(n=t[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r];break}for(r+=1;r<t.length;r++){if(n=t[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return"";e+=t[r]}return e}var pN=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),fN=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),mN=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),hN=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gN(t){if(t.length===0)return!1;for(let e=0;e<t.length;e++)if(!mN(t[e])){if(t[e]==="%"&&e+2<t.length&&to(t.slice(e+1,e+3))){e+=2;continue}return!1}return!0}function dS(t){let e=-1,n=0,r=-1,o=0;for(let a=0;a<t.length;a++)t[a]==="0"?(r===-1&&(r=a),o++,o>n&&(n=o,e=r)):(r=-1,o=0);if(n<2)return t.join(":");let s=t.slice(0,e).join(":"),i=t.slice(e+n).join(":");return s+"::"+i}function yN(t){let e=t.indexOf("::");if(e!==-1&&t.indexOf("::",e+1)!==-1)return;let n=e===-1?t.split(":"):t.slice(0,e).split(":"),r=e===-1?[]:t.slice(e+2).split(":");e!==-1&&(n.length===1&&n[0]===""&&(n.length=0),r.length===1&&r[0]===""&&(r.length=0));let o=n.concat(r),s=0;for(let a=0;a<o.length;a++){let c=o[a];if(c==="")return;if(c.indexOf(".")!==-1){if(a!==o.length-1||e!==-1&&r.length===0||!Hf(c))return;s+=2;continue}if(!pN(c))return;o[a]=parseInt(c,16).toString(16),s++}if(e===-1)return s!==8?void 0:dS(o);if(s>=8)return;let i=o.slice(0,n.length);for(let a=s;a<8;a++)i.push("0");for(let a=n.length;a<o.length;a++)i.push(o[a]);return dS(i)}function zf(t){let e=t[0]==="["&&t[t.length-1]==="]";if((t[0]==="["||t[t.length-1]==="]")&&!e)return{host:t,isIPV6:!1,error:!0};let r=e?t.slice(1,-1):t;if(e&&fN(r))return r=r.toLowerCase(),{host:`[${r}]`,escapedHost:r,isIPV6:!1,isIPVFuture:!0};if(_N(r,":")<2)return{host:t,isIPV6:!1,error:e};let o="",s=r.indexOf("%");if(s!==-1){let a=r.slice(s,s+3).toLowerCase()==="%25"?3:1;if(o=r.slice(s+a),!gN(o))return{host:t,isIPV6:!1,error:!0};r=r.slice(0,s)}let i=yN(r);return i===void 0?{host:t,isIPV6:!1,error:!0}:{host:i+(o?"%"+o:""),escapedHost:i+(o?"%25"+o:""),isIPV6:!0}}function _N(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function xN(t){let e=t,n=[],r=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){n.push("/");break}else{n.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]==="/")){n.push("/");break}}else if(o===3&&e==="/.."){n.length!==0&&n.pop(),n.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),n.length!==0&&n.pop();continue}}if((r=e.indexOf("/",1))===-1){n.push(e);break}else n.push(e.slice(0,r)),e=e.slice(r)}return n.join("")}var bN={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},SN=/[@/?#:]/g,kN=/[@/?#]/g;function fS(t,e){let n=e?kN:SN;return n.lastIndex=0,t.replace(n,r=>bN[r])}function mS(t,e=!1){if(t.indexOf("%")===-1)return t;let n="";for(let r=0;r<t.length;r++){if(t[r]==="%"&&r+2<t.length){let o=t.slice(r+1,r+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));e&&Uf(i)?n+=i:n+="%"+s,r+=2;continue}}n+=t[r]}return n}function vN(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));i!=="."&&Uf(i)?e+=i:e+="%"+s,n+=2;continue}}if(pS(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=gS(o)?r:Tt[o];else if(o<55296||o>57343)e+=ut(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=ut(65536+(o-55296<<10)+(s-56320)),n++):e+=ut(65533)}else e+=ut(65533)}}return e}function EN(t,e=!1){let n="",r=e&&t[0]!=="/";for(let o=0;o<t.length;o++){let s=t[o];if(s==="%"&&o+2<t.length){let i=t.slice(o+1,o+3);if(to(i)){n+="%"+i.toUpperCase(),o+=2;continue}}if(s==="/"&&(r=!1),pS(s)&&(s!==":"||!r))n+=s;else{let i=t.charCodeAt(o);if(i<128)n+=Tt[i];else if(i<55296||i>57343)n+=ut(i);else if(i<=56319&&o+1<t.length){let a=t.charCodeAt(o+1);a>=56320&&a<=57343?(n+=ut(65536+(i-55296<<10)+(a-56320)),o++):n+=ut(65533)}else n+=ut(65533)}}return n}function Bf(t,e){let n="";for(let r=0;r<t.length;r++){let o=t[r];if(o==="%"&&r+2<t.length){let s=t.slice(r+1,r+3);if(to(s)){n+="%"+s.toUpperCase(),r+=2;continue}}if(e(o))n+=o;else{let s=t.charCodeAt(r);if(s<128)n+=Tt[s];else if(s<55296||s>57343)n+=ut(s);else if(s<=56319&&r+1<t.length){let i=t.charCodeAt(r+1);i>=56320&&i<=57343?(n+=ut(65536+(s-55296<<10)+(i-56320)),r++):n+=ut(65533)}else n+=ut(65533)}}return n}function hS(t){return Bf(t,lN)}function wN(t){return Bf(t,Ff)}function TN(t){return Bf(t,Ff)}function gS(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===42||t===43||t===45||t===46||t===47||t===64||t===95}function PN(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];if(r==="%"&&n+2<t.length){let o=t.slice(n+1,n+3);if(to(o)){let s=o.toUpperCase(),i=String.fromCharCode(parseInt(s,16));Uf(i)?e+=i:e+="%"+s,n+=2;continue}}if(Ff(r))e+=r;else{let o=t.charCodeAt(n);if(o<128)e+=gS(o)?r:Tt[o];else if(o<55296||o>57343)e+=ut(o);else if(o<=56319&&n+1<t.length){let s=t.charCodeAt(n+1);s>=56320&&s<=57343?(e+=ut(65536+(o-55296<<10)+(s-56320)),n++):e+=ut(65533)}else e+=ut(65533)}}return e}function RN(t){let e="";for(let n=0;n<t.length;n++){if(t[n]==="%"&&n+2<t.length){let r=t.slice(n+1,n+3);if(to(r)){e+="%"+r.toUpperCase(),n+=2;continue}}e+=escape(t[n])}return e}function CN(t){let e=[];if(t.userinfo!==void 0&&(e.push(hS(t.userinfo)),e.push("@")),t.host!==void 0){let n=t.host;if(!Hf(n)){let r=zf(n);r.isIPV6!==!0&&r.isIPVFuture!==!0&&(n=mS(n,!0),r=zf(n)),r.isIPV6===!0||r.isIPVFuture===!0?n=`[${r.escapedHost}]`:n=fS(n,!1)}e.push(n)}if(typeof t.port=="number"||typeof t.port=="string"){let n=String(t.port);if(!uN(n))throw new TypeError("URI port is malformed.");e.push(":"),e.push(n)}return e.length?e.join(""):void 0}yS.exports={nonSimpleDomain:hN,recomposeAuthority:CN,reescapeHostDelimiters:fS,normalizePercentEncoding:mS,normalizePathEncoding:vN,serializePathEncoding:EN,normalizeQueryFragmentEncoding:PN,encodeUserinfo:hS,encodeQuery:wN,encodeFragment:TN,escapePreservingEscapes:RN,removeDotSegments:xN,isIPv4:Hf,isUUID:cN,normalizeIPv6:zf,stringArrayToHexStripped:dN}});var kS=I((H9,SS)=>{"use strict";var{isUUID:$N}=Zf(),ON=/^([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-./:;=@]|%[\da-f]{2})+)$/iu,IN=["http","https","ws","wss","urn","urn:uuid"];function AN(t){return IN.indexOf(t)!==-1}function qf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function _S(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function xS(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 NN(t){return t.secure=qf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function DN(t){if((t.port===(qf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let e=t.resourceName.indexOf("?"),n=e===-1?t.resourceName:t.resourceName.slice(0,e);t.path=n&&n!=="/"?n:void 0,t.query=e===-1?void 0:t.resourceName.slice(e+1),t.resourceName=void 0}return t.fragment=void 0,t}function MN(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(ON);if(n&&n[0]===t.path){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Vf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function jN(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let n=e.scheme||t.scheme||"urn",r=t.nid.toLowerCase(),o=`${n}:${e.nid||r}`,s=Vf(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${r||e.nid}:${a}`,e.skipEscape=!0,i}function LN(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!$N(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function zN(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var bS={scheme:"http",domainHost:!0,parse:_S,serialize:xS},HN={scheme:"https",domainHost:bS.domainHost,parse:_S,serialize:xS},Tc={scheme:"ws",domainHost:!0,parse:NN,serialize:DN},UN={scheme:"wss",domainHost:Tc.domainHost,parse:Tc.parse,serialize:Tc.serialize},FN={scheme:"urn",parse:MN,serialize:jN,skipNormalize:!0},BN={scheme:"urn:uuid",parse:LN,serialize:zN,skipNormalize:!0},Pc={http:bS,https:HN,ws:Tc,wss:UN,urn:FN,"urn:uuid":BN};Object.setPrototypeOf(Pc,null);function Vf(t){return t&&(Pc[t]||Pc[t.toLowerCase()])||void 0}SS.exports={wsIsSecure:qf,SCHEMES:Pc,isValidSchemeName:AN,getSchemeHandler:Vf}});var MS=I((U9,$c)=>{"use strict";var{normalizeIPv6:PS,removeDotSegments:Ei,recomposeAuthority:ZN,normalizePercentEncoding:RS,normalizePathEncoding:qN,serializePathEncoding:vS,normalizeQueryFragmentEncoding:ES,encodeQuery:VN,encodeFragment:WN,reescapeHostDelimiters:KN,isIPv4:CS,nonSimpleDomain:GN}=Zf(),{SCHEMES:$S,getSchemeHandler:Wf}=kS(),OS=/^[A-Za-z][A-Za-z0-9+.-]*$/u,IS="URI scheme is malformed.";function wS(t){let e=unescape(String(t));if(!OS.test(e))throw new TypeError(IS);return e}function JN(t,e){return typeof t=="string"?t=oD(t,e):typeof t=="object"&&(t=Cc(no(t,e),e)),t}function XN(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},{parsed:o,malformedAuthorityOrPort:s,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:c,malformedScheme:u}=Rc(t,r),{parsed:l,malformedAuthorityOrPort:d,malformedPercentEncoding:f,malformedSchemeSpecific:m,malformedHost:p,malformedScheme:h}=Rc(e,r);if(s||d||i||f||a||m||c||p||u||h)throw new Error(o.error||l.error||"URI is malformed.");let g=AS(o,l,r,!0),y=Wf(n&&n.scheme||g.scheme),_=g.host,x=_!==void 0&&_!==""&&(CS(_)||PS(_).isIPV6);NS(g,n||{},y,x);let b=_&&_.indexOf("%")!==-1&&!new RegExp("\\P{ASCII}","u").test(_);if(g.error&&!b)throw new Error(g.error);return r.skipEscape=!0,no(g,r)}function AS(t,e,n,r){let o={};return r||(t=Cc(no(t,n),n),e=Cc(no(e,n),n)),n=n||{},!n.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 YN(t,e,n){let r=TS(t,n),o=TS(e,n);return r!==void 0&&o!==void 0&&r===o}function no(t,e){let n={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:""},r=Object.assign({},e),o=[];n.scheme&&(n.scheme=wS(n.scheme));let s=Wf(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r);let i=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,a=!r.skipEscape&&n.scheme===void 0&&!i;n.path!==void 0&&(r.skipEscape?n.path=RS(n.path):n.path=vS(n.path,a)),r.reference!=="suffix"&&n.scheme&&(n.scheme=wS(n.scheme),o.push(n.scheme,":"));let c=ZN(n);if(c!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(c),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let u=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(u=Ei(u)),a&&(u=vS(u,!0)),c===void 0&&u[0]==="/"&&u[1]==="/"&&(u="/%2F"+u.slice(2)),o.push(u)}return n.query!==void 0&&o.push("?",VN(n.query)),n.fragment!==void 0&&o.push("#",WN(n.fragment)),o.join("")}var QN=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,eD=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,tD=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function nD(t,e){if(e[2]!==void 0&&t.path&&t.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof t.port=="number"&&(t.port<0||t.port>65535))return"URI port is malformed."}function vi(t){if(t===void 0)return!1;let e=t.indexOf("%");for(;e!==-1;){if(e+2>=t.length||!/^[\da-f]{2}$/iu.test(t.slice(e+1,e+3)))return!0;e=t.indexOf("%",e+3)}return!1}function Kf(t){return t[0]==="["&&t[t.length-1]==="]"}function rD(t){let e=t[4];return vi(t[3])||e!==void 0&&!Kf(e)&&vi(e)||vi(t[6])||vi(t[7])||vi(t[8])}function NS(t,e,n,r){if(!e.unicodeSupport&&(!n||!n.unicodeSupport)&&t.host&&!Kf(t.host)&&(e.domainHost||n&&n.domainHost)&&r===!1&&GN(t.host))try{t.host=new URL("http://"+t.host).hostname}catch(o){return t.error=t.error||"Host's domain name can not be converted to ASCII: "+o,!0}return!1}function Rc(t,e){let n=Object.assign({},e),r={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1,s=!1,i=!1,a=!1,c=!1,u=!1,l=!1;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let d=t.match(eD);d!==null&&d[1].indexOf("\\")!==-1&&(r.error="URI authority must not contain a literal backslash.",o=!0);let f=t.match(tD);if(f!==null){let p=f[1],h=p.replace(/[\t\n\r]/g,"");h.length>=2&&(h.slice(0,2)!=="//"?(r.error=r.error||"URI authority must not contain a literal backslash.",o=!0):p.length!==h.length&&(r.error=r.error||"URI authority introducer must not contain whitespace.",o=!0))}let m=t.match(QN);if(m){if(r.scheme=m[1],r.userinfo=m[3],r.host=m[4],r.port=parseInt(m[5],10),r.path=m[6]||"",r.query=m[7],r.fragment=m[8],r.scheme!==void 0){let g=unescape(r.scheme);OS.test(g)?r.scheme=g.toLowerCase():(r.error=r.error||IS,u=!0)}s=rD(m),s&&(r.error=r.error||"URI contains malformed percent-encoding."),isNaN(r.port)&&(r.port=m[5]);let p=nD(r,m);if(p!==void 0&&(r.error=r.error||p,o=!0),r.host)if(CS(r.host)===!1){let y=Kf(r.host),_=r.host.indexOf("[")!==-1||r.host.indexOf("]")!==-1,x=PS(r.host);l=x.isIPV6||x.isIPVFuture===!0,c=_&&(!y||x.error===!0),r.host=l?x.host:x.host.toLowerCase(),c&&(r.error=r.error||"URI host is malformed.",o=!0)}else l=!0;r.scheme===void 0&&r.userinfo===void 0&&r.host===void 0&&r.port===void 0&&r.query===void 0&&!r.path?r.reference="same-document":r.scheme===void 0?r.reference="relative":r.fragment===void 0?r.reference="absolute":r.reference="uri",n.reference&&n.reference!=="suffix"&&n.reference!==r.reference&&(r.error=r.error||"URI is not a "+n.reference+" reference.");let h=Wf(n.scheme||r.scheme);if(c||(a=NS(r,n,h,l)),!h||h&&!h.skipNormalize){if(t.indexOf("%")!==-1&&r.host!==void 0&&!c){let g=l?r.host:RS(r.host,!0);r.host=KN(g,l)}r.path&&(r.path=qN(r.path)),r.query&&(r.query=ES(r.query)),r.fragment&&(r.fragment=ES(r.fragment))}h&&h.parse&&(h.parse(r,n),h===$S.urn&&r.nid===void 0&&(i=!0))}else r.error=r.error||"URI can not be parsed.";return{parsed:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:u}}function Cc(t,e){return Rc(t,e).parsed}function oD(t,e){return DS(t,e).normalized}function DS(t,e){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}=Rc(t,e);return{normalized:r||o||s||i||a?t:no(n,e),malformedAuthorityOrPort:r,malformedPercentEncoding:o,malformedSchemeSpecific:s,malformedHost:i,malformedScheme:a}}function TS(t,e){if(typeof t!="string"&&typeof t!="object")return;let n;try{n=typeof t=="string"?t:no(t,e)}catch{return}let{normalized:r,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:i,malformedHost:a,malformedScheme:c}=DS(n,e);return o||s||i||a||c?void 0:r}var Gf={SCHEMES:$S,normalize:JN,resolve:XN,resolveComponent:AS,equal:YN,serialize:no,parse:Cc};$c.exports=Gf;$c.exports.default=Gf;$c.exports.fastUri=Gf});var LS=I(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var jS=MS();jS.code='require("ajv/dist/runtime/uri").default';Jf.default=jS});var VS=I(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.CodeGen=Qe.Name=Qe.nil=Qe.stringify=Qe.str=Qe._=Qe.KeywordCxt=void 0;var sD=Si();Object.defineProperty(Qe,"KeywordCxt",{enumerable:!0,get:function(){return sD.KeywordCxt}});var Yo=ee();Object.defineProperty(Qe,"_",{enumerable:!0,get:function(){return Yo._}});Object.defineProperty(Qe,"str",{enumerable:!0,get:function(){return Yo.str}});Object.defineProperty(Qe,"stringify",{enumerable:!0,get:function(){return Yo.stringify}});Object.defineProperty(Qe,"nil",{enumerable:!0,get:function(){return Yo.nil}});Object.defineProperty(Qe,"Name",{enumerable:!0,get:function(){return Yo.Name}});Object.defineProperty(Qe,"CodeGen",{enumerable:!0,get:function(){return Yo.CodeGen}});var iD=vc(),BS=ki(),aD=xf(),wi=wc(),cD=ee(),Ti=_i(),Oc=yi(),Yf=le(),zS=lS(),uD=LS(),ZS=(t,e)=>new RegExp(t,e);ZS.code="new RegExp";var lD=["removeAdditional","useDefaults","coerceTypes"],dD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),pD={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."},fD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},HS=200;function mD(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,x,b,v,O,R,j,M;let V=t.strict,w=(e=t.code)===null||e===void 0?void 0:e.optimize,P=w===!0||w===void 0?1:w||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:ZS,se=(o=t.uriResolver)!==null&&o!==void 0?o:uD.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:V)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:V)!==null&&c!==void 0?c:!0,strictTypes:(l=(u=t.strictTypes)!==null&&u!==void 0?u:V)!==null&&l!==void 0?l:"log",strictTuples:(f=(d=t.strictTuples)!==null&&d!==void 0?d:V)!==null&&f!==void 0?f:"log",strictRequired:(p=(m=t.strictRequired)!==null&&m!==void 0?m:V)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:P,regExp:H}:{optimize:P,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:HS,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:HS,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(j=t.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(M=t.int32range)!==null&&M!==void 0?M:!0,uriResolver:se}}var Pi=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,...mD(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new cD.ValueScope({scope:{},prefixes:dD,es5:n,lines:r}),this.logger=bD(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,aD.getRules)(),US.call(this,pD,e,"NOT SUPPORTED"),US.call(this,fD,e,"DEPRECATED","warn"),this._metaOpts=_D.call(this),e.formats&&gD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&yD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),hD.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=zS;r==="id"&&(o={...zS},o.id=o.$id,delete o.$id),n&&e&&this.addMetaSchema(o,o[r],!1)}defaultMeta(){let{meta:e,schemaId:n}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[n]||e:void 0}validate(e,n){let r;if(typeof e=="string"){if(r=this.getSchema(e),!r)throw new Error(`no schema with key or ref "${e}"`)}else r=this.compile(e);let o=r(n);return"$async"in r||(this.errors=r.errors),o}compile(e,n){let r=this._addSchema(e,n);return r.validate||this._compileSchemaEnv(r)}compileAsync(e,n){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:r}=this.opts;return o.call(this,e,n);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 BS.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,n)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=r(l))}finally{delete this._loading[l]}}}addSchema(e,n,r,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,r,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 n=(0,Ti.normalizeId)(n||s),this._checkUnique(n),this.schemas[n]=this._addSchema(e,r,n,o,!0),this}addMetaSchema(e,n,r=this.opts.validateSchema){return this.addSchema(e,n,!0,r),this}validateSchema(e,n){if(typeof e=="boolean")return!0;let r;if(r=e.$schema,r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this.opts.defaultMeta||this.defaultMeta(),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(r,e);if(!o&&n){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 n;for(;typeof(n=FS.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new wi.SchemaEnv({schema:{},schemaId:r});if(n=wi.resolveSchema.call(this,o,e),!n)return;this.refs[e]=n}return n.validate||this._compileSchemaEnv(n)}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 n=FS.call(this,e);return typeof n=="object"&&this._cache.delete(n.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let n=e;this._cache.delete(n);let r=e[this.opts.schemaId];return r&&(r=(0,Ti.normalizeId)(r),delete this.schemas[r],delete this.refs[r]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let n of e)this.addKeyword(n);return this}addKeyword(e,n){let r;if(typeof e=="string")r=e,typeof n=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),n.keyword=r);else if(typeof e=="object"&&n===void 0){if(n=e,r=n.keyword,Array.isArray(r)&&!r.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(kD.call(this,r,n),!n)return(0,Yf.eachItem)(r,s=>Xf.call(this,s)),this;ED.call(this,n);let o={...n,type:(0,Oc.getJSONTypes)(n.type),schemaType:(0,Oc.getJSONTypes)(n.schemaType)};return(0,Yf.eachItem)(r,o.type.length===0?s=>Xf.call(this,s,o):s=>o.type.forEach(i=>Xf.call(this,s,o,i))),this}getKeyword(e){let n=this.RULES.all[e];return typeof n=="object"?n.definition:!!n}removeKeyword(e){let{RULES:n}=this;delete n.keywords[e],delete n.all[e];for(let r of n.rules){let o=r.rules.findIndex(s=>s.keyword===e);o>=0&&r.rules.splice(o,1)}return this}addFormat(e,n){return typeof n=="string"&&(n=new RegExp(n)),this.formats[e]=n,this}errorsText(e=this.errors,{separator:n=", ",dataVar:r="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${r}${o.instancePath} ${o.message}`).reduce((o,s)=>o+n+s)}$dataMetaSchema(e,n){let r=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of n){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in r){let c=r[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=qS(l))}}return e}_removeAllSchemas(e,n){for(let r in e){let o=e[r];(!n||n.test(r))&&(typeof o=="string"?delete e[r]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[r]))}}_addSchema(e,n,r,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;r=(0,Ti.normalizeId)(i||r);let u=Ti.getSchemaRefs.call(this,e,r);return c=new wi.SchemaEnv({schema:e,schemaId:a,meta:n,baseId:r,localRefs:u}),this._cache.set(c.schema,c),s&&!r.startsWith("#")&&(r&&this._checkUnique(r),this.refs[r]=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):wi.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let n=this.opts;this.opts=this._metaOpts;try{wi.compileSchema.call(this,e)}finally{this.opts=n}}};Pi.ValidationError=iD.default;Pi.MissingRefError=BS.default;Qe.default=Pi;function US(t,e,n,r="error"){for(let o in t){let s=o;s in e&&this.logger[r](`${n}: option ${o}. ${t[s]}`)}}function FS(t){return t=(0,Ti.normalizeId)(t),this.schemas[t]||this.refs[t]}function hD(){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 gD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function yD(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 n=t[e];n.keyword||(n.keyword=e),this.addKeyword(n)}}function _D(){let t={...this.opts};for(let e of lD)delete t[e];return t}var xD={log(){},warn(){},error(){}};function bD(t){if(t===!1)return xD;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 SD=/^[a-z_$][a-z0-9_$:-]*$/i;function kD(t,e){let{RULES:n}=this;if((0,Yf.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!SD.test(r))throw new Error(`Keyword ${r} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Xf(t,e,n){var r;let o=e?.post;if(n&&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===n);if(i||(i={type:n,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Oc.getJSONTypes)(e.type),schemaType:(0,Oc.getJSONTypes)(e.schemaType)}};e.before?vD.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(r=e.implements)===null||r===void 0||r.forEach(c=>this.addKeyword(c))}function vD(t,e,n){let r=t.rules.findIndex(o=>o.keyword===n);r>=0?t.rules.splice(r,0,e):(t.rules.push(e),this.logger.warn(`rule ${n} is not defined`))}function ED(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=qS(e)),t.validateSchema=this.compile(e,!0))}var wD={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function qS(t){return{anyOf:[t,wD]}}});var WS=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var TD={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Qf.default=TD});var XS=I(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.callRef=ro.getValidate=void 0;var PD=ki(),KS=Ft(),Pt=ee(),Qo=Ln(),GS=wc(),Ic=le(),RD={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:n,it:r}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=r,{root:u}=s;if((n==="#"||n==="#/")&&o===u.baseId)return d();let l=GS.resolveRef.call(c,u,o,n);if(l===void 0)throw new PD.default(r.opts.uriResolver,o,n);if(l instanceof GS.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,Pt._)`${p}.validate`,u,u.$async)}function f(p){let h=JS(t,p);Ac(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Pt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function JS(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}ro.getValidate=JS;function Ac(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Qo.default.this:Pt.nil;r?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,Pt._)`await ${(0,KS.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,Pt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,KS.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,Pt._)`${p}.errors`;o.assign(Qo.default.vErrors,(0,Pt._)`${Qo.default.vErrors} === null ? ${h} : ${Qo.default.vErrors}.concat(${h})`),o.assign(Qo.default.errors,(0,Pt._)`${Qo.default.vErrors}.length`)}function m(p){var h;if(!s.opts.unevaluated)return;let g=(h=n?.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,Pt._)`${p}.evaluated.props`);s.props=Ic.mergeEvaluated.props(o,y,s.props,Pt.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,Pt._)`${p}.evaluated.items`);s.items=Ic.mergeEvaluated.items(o,y,s.items,Pt.Name)}}}ro.callRef=Ac;ro.default=RD});var YS=I(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var CD=WS(),$D=XS(),OD=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",CD.default,$D.default];em.default=OD});var QS=I(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Nc=ee(),dr=Nc.operators,Dc={maximum:{okStr:"<=",ok:dr.LTE,fail:dr.GT},minimum:{okStr:">=",ok:dr.GTE,fail:dr.LT},exclusiveMaximum:{okStr:"<",ok:dr.LT,fail:dr.GTE},exclusiveMinimum:{okStr:">",ok:dr.GT,fail:dr.LTE}},ID={message:({keyword:t,schemaCode:e})=>(0,Nc.str)`must be ${Dc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Nc._)`{comparison: ${Dc[t].okStr}, limit: ${e}}`},AD={keyword:Object.keys(Dc),type:"number",schemaType:"number",$data:!0,error:ID,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Nc._)`${n} ${Dc[e].fail} ${r} || isNaN(${n})`)}};tm.default=AD});var ek=I(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Ri=ee(),ND={message:({schemaCode:t})=>(0,Ri.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ri._)`{multipleOf: ${t}}`},DD={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:ND,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ri._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ri._)`${i} !== parseInt(${i})`;t.fail$data((0,Ri._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};nm.default=DD});var nk=I(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});function tk(t){let e=t.length,n=0,r=0,o;for(;r<e;)n++,o=t.charCodeAt(r++),o>=55296&&o<=56319&&r<e&&(o=t.charCodeAt(r),(o&64512)===56320&&r++);return n}rm.default=tk;tk.code='require("ajv/dist/runtime/ucs2length").default'});var rk=I(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var oo=ee(),MD=le(),jD=nk(),LD={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,oo.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,oo._)`{limit: ${t}}`},zD={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:LD,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?oo.operators.GT:oo.operators.LT,i=o.opts.unicode===!1?(0,oo._)`${n}.length`:(0,oo._)`${(0,MD.useFunc)(t.gen,jD.default)}(${n})`;t.fail$data((0,oo._)`${i} ${s} ${r}`)}};om.default=zD});var ok=I(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var HD=Ft(),UD=le(),es=ee(),FD={message:({schemaCode:t})=>(0,es.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,es._)`{pattern: ${t}}`},BD={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:FD,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(r){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,es._)`new RegExp`:(0,UD.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,es._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,es._)`!${l}`)}else{let c=(0,HD.usePattern)(t,o);t.fail$data((0,es._)`!${c}.test(${n})`)}}};sm.default=BD});var sk=I(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Ci=ee(),ZD={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,Ci.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,Ci._)`{limit: ${t}}`},qD={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ZD,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?Ci.operators.GT:Ci.operators.LT;t.fail$data((0,Ci._)`Object.keys(${n}).length ${o} ${r}`)}};im.default=qD});var ik=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var $i=Ft(),Oi=ee(),VD=le(),WD={message:({params:{missingProperty:t}})=>(0,Oi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Oi._)`{missingProperty: ${t}}`},KD={keyword:"required",type:"object",schemaType:"array",$data:!0,error:WD,code(t){let{gen:e,schema:n,schemaCode:r,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&n.length===0)return;let c=n.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let m=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of n)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,VD.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Oi.nil,d);else for(let m of n)(0,$i.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,$i.checkMissingProp)(t,n,m)),(0,$i.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,$i.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,$i.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Oi.not)(p),()=>{t.error(),e.break()})},Oi.nil)}}};am.default=KD});var ak=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var Ii=ee(),GD={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,Ii.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,Ii._)`{limit: ${t}}`},JD={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:GD,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?Ii.operators.GT:Ii.operators.LT;t.fail$data((0,Ii._)`${n}.length ${o} ${r}`)}};cm.default=JD});var Mc=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var ck=Pf();ck.code='require("ajv/dist/runtime/equal").default';um.default=ck});var uk=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var lm=yi(),et=ee(),XD=le(),YD=Mc(),QD={message:({params:{i:t,j:e}})=>(0,et.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,et._)`{i: ${t}, j: ${e}}`},eM={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:QD,code(t){let{gen:e,data:n,$data:r,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!r&&!o)return;let c=e.let("valid"),u=s.items?(0,lm.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,et._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,et._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,et._)`${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,lm.checkDataTypes)(u,g,a.opts.strictNumbers,lm.DataType.Wrong),_=e.const("indices",(0,et._)`{}`);e.for((0,et._)`;${p}--;`,()=>{e.let(g,(0,et._)`${n}[${p}]`),e.if(y,(0,et._)`continue`),u.length>1&&e.if((0,et._)`typeof ${g} == "string"`,(0,et._)`${g} += "_"`),e.if((0,et._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,et._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,et._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,XD.useFunc)(e,YD.default),y=e.name("outer");e.label(y).for((0,et._)`;${p}--;`,()=>e.for((0,et._)`${h} = ${p}; ${h}--;`,()=>e.if((0,et._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};dm.default=eM});var lk=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var pm=ee(),tM=le(),nM=Mc(),rM={message:"must be equal to constant",params:({schemaCode:t})=>(0,pm._)`{allowedValue: ${t}}`},oM={keyword:"const",$data:!0,error:rM,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,pm._)`!${(0,tM.useFunc)(e,nM.default)}(${n}, ${o})`):t.fail((0,pm._)`${s} !== ${n}`)}};fm.default=oM});var dk=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Ai=ee(),sM=le(),iM=Mc(),aM={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ai._)`{allowedValues: ${t}}`},cM={keyword:"enum",schemaType:"array",$data:!0,error:aM,code(t){let{gen:e,data:n,$data:r,schema:o,schemaCode:s,it:i}=t;if(!r&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,sM.useFunc)(e,iM.default)),l;if(a||r)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,Ai.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,Ai._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,Ai._)`${u()}(${n}, ${m}[${p}])`:(0,Ai._)`${n} === ${h}`}}};mm.default=cM});var pk=I(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var uM=QS(),lM=ek(),dM=rk(),pM=ok(),fM=sk(),mM=ik(),hM=ak(),gM=uk(),yM=lk(),_M=dk(),xM=[uM.default,lM.default,dM.default,pM.default,fM.default,mM.default,hM.default,gM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},yM.default,_M.default];hm.default=xM});var ym=I(Ni=>{"use strict";Object.defineProperty(Ni,"__esModule",{value:!0});Ni.validateAdditionalItems=void 0;var so=ee(),gm=le(),bM={message:({params:{len:t}})=>(0,so.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,so._)`{limit: ${t}}`},SM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:bM,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,gm.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}fk(t,r)}};function fk(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,so._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,so._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,gm.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,so._)`${a} <= ${e.length}`);n.if((0,so.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:gm.Type.Num},u),i.allErrors||n.if((0,so.not)(u),()=>n.break())})}}Ni.validateAdditionalItems=fk;Ni.default=SM});var _m=I(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.validateTuple=void 0;var mk=ee(),jc=le(),kM=Ft(),vM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return hk(t,"additionalItems",e);n.items=!0,!(0,jc.alwaysValidSchema)(n,e)&&t.ok((0,kM.validateArray)(t))}};function hk(t,e,n=t.schema){let{gen:r,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&n.length&&a.items!==!0&&(a.items=jc.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,mk._)`${s}.length`);n.forEach((d,f)=>{(0,jc.alwaysValidSchema)(a,d)||(r.if((0,mk._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=n.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,jc.checkStrictMode)(a,g,f.strictTuples)}}}Di.validateTuple=hk;Di.default=vM});var gk=I(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var EM=_m(),wM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,EM.validateTuple)(t,"items")};xm.default=wM});var _k=I(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});var yk=ee(),TM=le(),PM=Ft(),RM=ym(),CM={message:({params:{len:t}})=>(0,yk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,yk._)`{limit: ${t}}`},$M={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:CM,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,TM.alwaysValidSchema)(r,e)&&(o?(0,RM.validateAdditionalItems)(t,o):t.ok((0,PM.validateArray)(t)))}};bm.default=$M});var xk=I(Sm=>{"use strict";Object.defineProperty(Sm,"__esModule",{value:!0});var Zt=ee(),Lc=le(),OM={message:({params:{min:t,max:e}})=>e===void 0?(0,Zt.str)`must contain at least ${t} valid item(s)`:(0,Zt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Zt._)`{minContains: ${t}}`:(0,Zt._)`{minContains: ${t}, maxContains: ${e}}`},IM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:OM,code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=r;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Zt._)`${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,n)){let h=(0,Zt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Zt._)`${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,Zt._)`${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,Zt._)`${h}++`),a===void 0?e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Zt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};Sm.default=IM});var kk=I(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.validateSchemaDeps=kn.validatePropertyDeps=kn.error=void 0;var km=ee(),AM=le(),Mi=Ft();kn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,km.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,km._)`{property: ${t},
7
7
  missingProperty: ${r},
8
8
  depsCount: ${e},
9
- deps: ${n}}`};var AM={keyword:"dependencies",type:"object",schemaType:"object",error:vn.error,code(t){let[e,n]=NM(t);Sk(t,e),kk(t,n)}};function NM({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function Sk(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Mi.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Mi.checkReportMissingProp)(t,u)}):(n.if((0,km._)`${c} && (${(0,Mi.checkMissingProp)(t,a,s)})`),(0,Mi.reportMissingProp)(t,s),n.else())}}vn.validatePropertyDeps=Sk;function kk(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,IM.alwaysValidSchema)(s,e[a])||(n.if((0,Mi.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}vn.validateSchemaDeps=kk;vn.default=AM});var wk=I(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var Ek=ee(),DM=le(),MM={message:"property name must be valid",params:({params:t})=>(0,Ek._)`{propertyName: ${t.propertyName}}`},jM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:MM,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,DM.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,Ek.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};vm.default=jM});var wm=I(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var Hc=Ft(),cn=ee(),LM=zn(),Uc=le(),zM={message:"must NOT have additional properties",params:({params:t})=>(0,cn._)`{additionalProperty: ${t.additionalProperty}}`},HM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:zM,code(t){let{gen:e,schema:n,parentSchema:r,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,Uc.alwaysValidSchema)(i,n))return;let u=(0,Hc.allSchemaProperties)(r.properties),l=(0,Hc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,cn._)`${s} === ${LM.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 _=(0,Uc.schemaRefOrVal)(i,r.properties,"properties");y=(0,Hc.isOwnProperty)(e,_,g)}else u.length?y=(0,cn.or)(...u.map(_=>(0,cn._)`${g} === ${_}`)):y=cn.nil;return l.length&&(y=(0,cn.or)(y,...l.map(_=>(0,cn._)`${(0,Hc.usePattern)(t,_)}.test(${g})`))),(0,cn.not)(y)}function m(g){e.code((0,cn._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){m(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Uc.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,cn.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,cn.not)(y),()=>e.break()))}}function h(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:Uc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};Em.default=HM});var Rk=I(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});var UM=Si(),Tk=Ft(),Tm=le(),Pk=wm(),FM={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Pk.default.code(new UM.KeywordCxt(s,Pk.default,"additionalProperties"));let i=(0,Tk.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Tm.mergeEvaluated.props(e,(0,Tm.toHash)(i),s.props));let a=i.filter(d=>!(0,Tm.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,Tk.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Pm.default=FM});var Ik=I(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var Ck=Ft(),Fc=ee(),$k=le(),Ok=le(),BM={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Ck.allSchemaProperties)(n),c=a.filter(h=>(0,$k.alwaysValidSchema)(s,n[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,Ok.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,$k.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,Fc._)`${(0,Ck.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Ok.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())})})}}};Rm.default=BM});var Ak=I(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var ZM=le(),qM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,ZM.alwaysValidSchema)(r,n)){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"}};Cm.default=qM});var Nk=I($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var VM=Ft(),WM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:VM.validateUnion,error:{message:"must match a schema in anyOf"}};$m.default=WM});var Dk=I(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var Bc=ee(),KM=le(),GM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Bc._)`{passingSchemas: ${t.passing}}`},JM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:GM,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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,KM.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Bc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Bc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Bc.Name)})})}}};Om.default=JM});var Mk=I(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var XM=le(),YM={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,XM.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Im.default=YM});var zk=I(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var Zc=ee(),Lk=le(),QM={message:({params:t})=>(0,Zc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Zc._)`{failingKeyword: ${t.ifClause}}`},ej={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:QM,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Lk.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=jk(r,"then"),s=jk(r,"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,Zc.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,Zc._)`${l}`):t.setParams({ifClause:l})}}}};function jk(t,e){let n=t.schema[e];return n!==void 0&&!(0,Lk.alwaysValidSchema)(t,n)}Am.default=ej});var Hk=I(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var tj=le(),nj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,tj.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Nm.default=nj});var Uk=I(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var rj=ym(),oj=yk(),sj=_m(),ij=xk(),aj=bk(),cj=vk(),uj=wk(),lj=wm(),dj=Rk(),pj=Ik(),fj=Ak(),mj=Nk(),hj=Dk(),gj=Mk(),yj=zk(),_j=Hk();function xj(t=!1){let e=[fj.default,mj.default,hj.default,gj.default,yj.default,_j.default,uj.default,lj.default,cj.default,dj.default,pj.default];return t?e.push(oj.default,ij.default):e.push(rj.default,sj.default),e.push(aj.default),e}Dm.default=xj});var Fk=I(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var je=ee(),bj={message:({schemaCode:t})=>(0,je.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,je._)`{format: ${t}}`},Sj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:bj,code(t,e){let{gen:n,data:r,$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=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,je._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,je._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,je._)`${h}.type || "string"`).assign(y,(0,je._)`${h}.validate`),()=>n.assign(g,(0,je._)`"string"`).assign(y,h)),t.fail$data((0,je.or)(_(),x()));function _(){return c.strictSchema===!1?je.nil:(0,je._)`${i} && !${y}`}function x(){let b=l.$async?(0,je._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,je._)`${y}(${r})`,v=(0,je._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${r}))`;return(0,je._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=x(p);h===e&&t.pass(b());function _(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(v){let O=v instanceof RegExp?(0,je.regexpCode)(v):c.code.formats?(0,je._)`${c.code.formats}${(0,je.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,je._)`${R}.validate`]:["string",v,R]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,je._)`await ${y}(${r})`}return typeof g=="function"?(0,je._)`${y}(${r})`:(0,je._)`${y}.test(${r})`}}}};Mm.default=Sj});var Bk=I(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var kj=Fk(),vj=[kj.default];jm.default=vj});var Zk=I(rs=>{"use strict";Object.defineProperty(rs,"__esModule",{value:!0});rs.contentVocabulary=rs.metadataVocabulary=void 0;rs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];rs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Vk=I(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var Ej=QS(),wj=fk(),Tj=Uk(),Pj=Bk(),qk=Zk(),Rj=[Ej.default,wj.default,(0,Tj.default)(),Pj.default,qk.metadataVocabulary,qk.contentVocabulary];Lm.default=Rj});var Kk=I(qc=>{"use strict";Object.defineProperty(qc,"__esModule",{value:!0});qc.DiscrError=void 0;var Wk;(function(t){t.Tag="tag",t.Mapping="mapping"})(Wk||(qc.DiscrError=Wk={}))});var Jk=I(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});var os=ee(),zm=Kk(),Gk=Tc(),Cj=ki(),$j=le(),Oj={message:({params:{discrError:t,tagName:e}})=>t===zm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,os._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},Ij={keyword:"discriminator",type:"object",schemaType:"object",error:Oj,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,os._)`${n}${(0,os.getProperty)(a)}`);e.if((0,os._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:zm.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,os._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:zm.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,os.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let v=i[b];if(v?.$ref&&!(0,$j.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=Gk.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof Gk.SchemaEnv&&(v=v.schema),v===void 0)throw new Cj.default(s.opts.uriResolver,s.baseId,R)}let O=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(v)),_(O,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 _(b,v){if(b.const)x(b.const,v);else if(b.enum)for(let O of b.enum)x(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(b,v){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=v}}}};Hm.default=Ij});var Xk=I((RV,Aj)=>{Aj.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 Fm=I((we,Um)=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv=void 0;var Nj=WS(),Dj=Vk(),Mj=Jk(),Yk=Xk(),jj=["/properties"],Vc="http://json-schema.org/draft-07/schema",ss=class extends Nj.default{_addVocabularies(){super._addVocabularies(),Dj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(Mj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Yk,jj):Yk;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)}};we.Ajv=ss;Um.exports=we=ss;Um.exports.Ajv=ss;Object.defineProperty(we,"__esModule",{value:!0});we.default=ss;var Lj=Si();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return Lj.KeywordCxt}});var is=ee();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return is._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return is.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return is.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return is.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return is.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return is.CodeGen}});var zj=Ec();Object.defineProperty(we,"ValidationError",{enumerable:!0,get:function(){return zj.default}});var Hj=ki();Object.defineProperty(we,"MissingRefError",{enumerable:!0,get:function(){return Hj.default}})});var iv=I(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.formatNames=wn.fastFormats=wn.fullFormats=void 0;function En(t,e){return{validate:t,compare:e}}wn.fullFormats={date:En(nv,Vm),time:En(Zm(!0),Wm),"date-time":En(Qk(!0),ov),"iso-time":En(Zm(),rv),"iso-date-time":En(Qk(),sv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Vj,"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:Qj,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:Wj,int32:{type:"number",validate:Jj},int64:{type:"number",validate:Xj},float:{type:"number",validate:tv},double:{type:"number",validate:tv},password:!0,binary:!0};wn.fastFormats={...wn.fullFormats,date:En(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vm),time:En(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wm),"date-time":En(/^\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,ov),"iso-time":En(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,rv),"iso-date-time":En(/^\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,sv),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};wn.formatNames=Object.keys(wn.fullFormats);function Uj(t){return t%4===0&&(t%100!==0||t%400===0)}var Fj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Bj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nv(t){let e=Fj.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&Uj(n)?29:Bj[r])}function Vm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Bm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Zm(t){return function(n){let r=Bm.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[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 Wm(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function rv(t,e){if(!(t&&e))return;let n=Bm.exec(t),r=Bm.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var qm=/t|\s/i;function Qk(t){let e=Zm(t);return function(r){let o=r.split(qm);return o.length===2&&nv(o[0])&&e(o[1])}}function ov(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function sv(t,e){if(!(t&&e))return;let[n,r]=t.split(qm),[o,s]=e.split(qm),i=Vm(n,o);if(i!==void 0)return i||Wm(r,s)}var Zj=/\/|:/,qj=/^(?:[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 Vj(t){return Zj.test(t)&&qj.test(t)}var ev=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Wj(t){return ev.lastIndex=0,ev.test(t)}var Kj=-(2**31),Gj=2**31-1;function Jj(t){return Number.isInteger(t)&&t<=Gj&&t>=Kj}function Xj(t){return Number.isInteger(t)}function tv(){return!0}var Yj=/[^\\]\\Z/;function Qj(t){if(Yj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var av=I(as=>{"use strict";Object.defineProperty(as,"__esModule",{value:!0});as.formatLimitDefinition=void 0;var eL=Fm(),un=ee(),fr=un.operators,Wc={formatMaximum:{okStr:"<=",ok:fr.LTE,fail:fr.GT},formatMinimum:{okStr:">=",ok:fr.GTE,fail:fr.LT},formatExclusiveMaximum:{okStr:"<",ok:fr.LT,fail:fr.GTE},formatExclusiveMinimum:{okStr:">",ok:fr.GT,fail:fr.LTE}},tL={message:({keyword:t,schemaCode:e})=>(0,un.str)`should be ${Wc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,un._)`{comparison: ${Wc[t].okStr}, limit: ${e}}`};as.formatLimitDefinition={keyword:Object.keys(Wc),type:"string",schemaType:"string",$data:!0,error:tL,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new eL.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,un._)`${f}[${c.schemaCode}]`);t.fail$data((0,un.or)((0,un._)`typeof ${m} != "object"`,(0,un._)`${m} instanceof RegExp`,(0,un._)`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,un._)`${i.code.formats}${(0,un.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,un._)`${f}.compare(${n}, ${r}) ${Wc[o].fail} 0`}},dependencies:["format"]};var nL=t=>(t.addKeyword(as.formatLimitDefinition),t);as.default=nL});var dv=I((ji,lv)=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});var cs=iv(),rL=av(),Km=ee(),cv=new Km.Name("fullFormats"),oL=new Km.Name("fastFormats"),Gm=(t,e={keywords:!0})=>{if(Array.isArray(e))return uv(t,e,cs.fullFormats,cv),t;let[n,r]=e.mode==="fast"?[cs.fastFormats,oL]:[cs.fullFormats,cv],o=e.formats||cs.formatNames;return uv(t,o,n,r),e.keywords&&(0,rL.default)(t),t};Gm.get=(t,e="full")=>{let r=(e==="fast"?cs.fastFormats:cs.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function uv(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Km._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}lv.exports=ji=Gm;Object.defineProperty(ji,"__esModule",{value:!0});ji.default=Gm});function zi(t,e){let n=process.execPath.replace(/\\/g,"/");if(nu(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Qm.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function Le(t,e){if(nu(e?.platform))return zi(t,e);let r=wv().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function tu(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}function nu(t){return!!t&&fL.has(t)}var Qm,fL,Un=J(()=>{"use strict";ru();Qm=new Set(["node","bun","deno"]),fL=new Set(["opencode","kilo"])});import{execFileSync as nh,execSync as us}from"node:child_process";import{existsSync as ls}from"node:fs";function th(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function hL(t){return mL.test(th(t))}function gL(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function yL(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ue(t){try{let e=Hi?`where ${t}`:`command -v ${t}`;return us(e,{stdio:"pipe"}),!0}catch{return!1}}function eh(t){if(Hi)try{let n=us(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ue(t))return!1;try{return Hi?us(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):nh(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function rh(){if(Ue("bun"))return!0;for(let t of Rv())if(ls(t))return!0;return!1}function Pv(){for(let e of Rv())if(ls(e))return e;if(Ue("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Hi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Rv(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Hi){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function Cv(){let t;try{t=us("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of _L)if(ls(r))return r;return e}}return null}function xL(t=Cv()){return t??(Ue("sh")?"sh":Ue("pwsh")?"pwsh":Ue("powershell")?"powershell":"cmd.exe")}function qt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return us(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return nh(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function bL(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ue,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Qm.has(o)&&ls(n)?n:r("node")?"node":null}function ou(){let e=rh()?Pv():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Cv():null,s=n&&ls(n)&&hL(n)&&!(r&&gL(n))&&!(r&&o&&yL(n))?n:null;return{javascript:bL(e),typescript:e||(Ue("tsx")?"tsx":Ue("ts-node")?"ts-node":null),python:eh("python3")?"python3":eh("python")?"python":eh("py")?"py":null,shell:s??(r?xL(o):Ue("bash")?"bash":"sh"),ruby:Ue("ruby")?"ruby":null,go:Ue("go")?"go":null,rust:Ue("rustc")?"rustc":null,php:Ue("php")?"php":null,perl:Ue("perl")?"perl":null,r:Ue("Rscript")?"Rscript":Ue("r")?"r":null,elixir:Ue("elixir")?"elixir":null,csharp:Ue("dotnet-script")?"dotnet-script":null}}function su(){return rh()}function SL(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function kL(){return ls(process.execPath)?{path:process.execPath,isBun:!1}:Ue("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function wv(){if(Vt)return Vt;let t=kL();try{if(!rh())return Vt=t,Vt;let e=Pv(),n;try{if(process.platform==="win32"){let r=us(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=nh(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Vt=t,Vt}return SL(n)?(Vt={path:e,isBun:!0},Vt):(Vt=t,Vt)}catch{return Vt=t,Vt}}function $v(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${qt(t.javascript)})${n?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${qt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${qt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${qt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${qt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${qt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${qt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${qt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${qt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${qt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${qt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${qt(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
10
- `)}function Ov(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 Iv(t,e,n){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return Tv.test(th(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];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 Tv.test(th(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var mL,Tv,Hi,_L,Vt,ru=J(()=>{"use strict";Un();mL=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,Tv=/^bun(\.exe)?$/i;Hi=process.platform==="win32";_L=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Vt=null});import{createRequire as jL}from"node:module";import{existsSync as LL,unlinkSync as Uv,renameSync as zL}from"node:fs";import{tmpdir as HL}from"node:os";import{join as UL}from"node:path";function FL(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 BL(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.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 qe(){if(!ds){let t=jL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ds=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new ah(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(BL()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&FL(e)?ds=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new ch(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:ds=t("better-sqlite3")}else ds=t("better-sqlite3")}return ds}function ps(t,e=process.env){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");let n=ZL(e);if(n!==null)try{t.pragma(`mmap_size = ${n}`)}catch{}}function ZL(t=process.env){let e=t.CONTEXT_MODE_DB_MMAP_SIZE;if(e==null)return null;let n=String(e).trim();if(n==="")return null;let r=Number(n);return!Number.isFinite(r)||!Number.isInteger(r)||r<0?null:r}function ao(t){if(!LL(t))for(let e of["-wal","-shm"])try{Uv(t+e)}catch{}}function uh(t){for(let e of["","-wal","-shm"])try{Uv(t+e)}catch{}}function Bi(t){try{t.close()}catch{}}function Fv(t="context-mode"){return UL(HL(),`${t}-${process.pid}.db`)}function Bv(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?`${e} ${t.message}`:t.message}if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.code,n=t.message,r=[typeof e=="string"?e:"",typeof n=="string"?n:""].filter(Boolean);return r.length>0?r.join(" "):String(t)}return String(t)}function qL(t){let e=Bv(t);return e.includes("SQLITE_BUSY")||e.includes("database is locked")||e.includes("SQLITE_IOERR")||/disk i\/o error/i.test(e)}function De(t,e=[100,500,2e3]){let n;for(let s=0;s<=e.length;s++)try{return t()}catch(i){if(!qL(i))throw i;if(n=i instanceof Error?i:new Error(Bv(i)),!(i instanceof Error)){let a=Zi(i);a&&(n.code=a)}if(s<e.length){let a=e[s],c=Date.now();for(;Date.now()-c<a;);}}let r=new Error(`SQLITE_BUSY/SQLITE_IOERR: transient SQLite error after ${e.length} retries. Original error: ${n?.message}`),o=n?Zi(n):"";throw o&&(r.code=o),r}function lh(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 VL(t){let e=Date.now();for(let n of["","-wal","-shm"])try{zL(t+n,`${t}${n}.corrupt-${e}`)}catch{}}function Zi(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?e:""}if(t!==null&&typeof t=="object"){let e=t.code;return typeof e=="string"?e:""}return""}function cu(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.message;if(typeof e=="string"&&e)return e}return String(t)}function tt(t,e,n,r=Date.now()){try{let o=Zi(e),s=cu(e),i=n?` (${n})`:"",a=`${t}|${o}|${s}${i}`,c=hr.get(a);if(c!==void 0&&r-c<zv)return;if(hr.set(a,r),hr.size>Hv){for(let[m,p]of hr)r-p>=zv&&hr.delete(m);for(;hr.size>Hv;){let m=hr.keys().next().value;if(m===void 0)break;hr.delete(m)}}let u=process.env.OPENCODE_DEBUG,d=u!==void 0&&u!==""&&u!=="0"&&u!=="false"&&e instanceof Error&&e.stack?`
11
- ${e.stack}`:"",f=o?` [${o}]`:"";console.error(`${WL} ${t}${f}: ${s}${i}${d}`)}catch{}}var ah,ch,ds,WL,zv,Hv,hr,Fi,ih,au,co=J(()=>{"use strict";ah=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},ch=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},ds=null;WL="[context-mode:db]",zv=3e4,Hv=256,hr=new Map;Fi=Symbol.for("__context_mode_live_dbs_v3__"),ih=(()=>{let t=globalThis;return t[Fi]||(t[Fi]=new Set,process.on("exit",()=>{for(let e of t[Fi])Bi(e);t[Fi].clear()})),t[Fi]})(),au=class{#e;#t;constructor(e){let n=qe();this.#e=e,ao(e);let r;try{r=new n(e,{timeout:3e4}),ps(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(lh(s)){tt("SQLiteBase.open",o,e),VL(e),ao(e);try{r=new n(e,{timeout:3e4}),ps(r)}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=r,ih.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){ih.delete(this.#t),Bi(this.#t)}withRetry(e){return De(e)}cleanup(){ih.delete(this.#t),Bi(this.#t),uh(this.#e)}}});var dE,pE=J(()=>{"use strict";dE={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","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","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});import{createHash as Vi}from"node:crypto";import{execFileSync as Tz}from"node:child_process";import{accessSync as Pz,constants as Rz,existsSync as mu,mkdirSync as Cz,realpathSync as $z,renameSync as vh}from"node:fs";import{homedir as _E}from"node:os";import{dirname as Oz,isAbsolute as xE,join as gr,resolve as ms}from"node:path";function Eh(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):gr(Iz(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function Iz(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?mE(r.trim()):mE(t,_E())}function mE(t,e){return t.startsWith("~")?ms(_E(),t.replace(/^~[/\\]?/,"")):xE(t)?ms(t):e?ms(e,t):ms(t)}function Az(t,e,n){return new yr(t,e,Tn,void 0,[`Invalid ${Tn} for context-mode ${t} directory: ${n}`,EE()].join(`
12
- `))}function SE(t){let e=process.env[Tn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Tn,ignoredReason:"empty"};if(!xE(n))throw Az(t,n,`${Tn} must be an absolute path.`);return{kind:"override",root:ms(n)}}function Nz(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function kE(t,e){let n=SE(t);return n.kind!=="override"?null:{kind:t,path:gr(n.root,e),envVar:Tn,source:"override"}}function Dz(t,e,n){return{kind:t,path:ms(e()),envVar:null,source:"default",...n}}function Wi(t){let e=SE("session");return e.kind==="override"?{kind:"session",path:gr(e.root,bE),envVar:Tn,source:"override"}:Dz("session",t,Nz(e))}function wh(t){let e=kE("content",fE);if(e)return e;let n=Wi(t);return{kind:"content",path:gr(Oz(n.path),fE),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Th(t){let e=kE("stats",bE);if(e)return e;let n=Wi(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function vE(t){return t.message}function hu(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function gu(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=kh.get(e);if(n instanceof yr)throw n;if(n===t.path)return n;try{return Cz(t.path,{recursive:!0}),Pz(t.path,Rz.W_OK),kh.set(e,t.path),t.path}catch(r){let o=new yr(t.kind,Lz(r)??t.path,Tn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw kh.set(e,o),o}}function Mz(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,jz(n),EE()].filter(Boolean).join(`
13
- `)}function jz(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function EE(){return`Set ${Tn} to a writable absolute path.`}function Lz(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function uo(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function hE(t){let e=t;try{e=$z.native(t)}catch{}let n=uo(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function wE(t,e){return Tz("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function zz(t){let e=wE(t,["rev-parse","--show-toplevel"]);return e.length>0?uo(e):null}function Hz(t){let e=wE(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?uo(e):null}function yu(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(qi&&qi.projectDir===t&&qi.envSuffix===e)return qi.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=zz(t),o=Hz(t);if(r&&o){let s=hE(r),i=hE(o);s!==i&&(n=`__${Vi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return qi={projectDir:t,envSuffix:e,suffix:n},n}function Fn(t){return Vi("sha256").update(uo(t)).digest("hex").slice(0,16)}function nt(t){let e=uo(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Vi("sha256").update(n).digest("hex").slice(0,16)}function TE(t){let{projectDir:e,contentDir:n}=t,r=nt(e),o=gr(n,`${r}.db`);if(mu(o))return o;let s=Fn(e);if(s===r)return o;let i=gr(n,`${s}.db`);if(mu(i))try{vh(i,o);for(let a of["-wal","-shm"])try{vh(i+a,o+a)}catch{}}catch{}return o}function Ki(t){return Uz({...t,ext:".db"})}function Uz(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??yu(e),s=nt(e),i=gr(n,`${s}${o}${r}`);if(mu(i))return i;let a=Fn(e);if(a===s)return i;let c=gr(n,`${a}${o}${r}`);if(mu(c))try{vh(c,i)}catch{}return i}function fu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function PE(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of Fz)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function RE(t,e){let n=null;try{n=new e(t),PE(n)}catch(r){tt("ensureSessionEventsSchema",r,t)}finally{try{n?.close()}catch{}}}var Tn,bE,fE,yr,kh,qi,gE,yE,D,Fz,ln,Pn=J(()=>{"use strict";co();Tn="CONTEXT_MODE_DIR",bE="sessions",fE="content",yr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Tn,o,s,i={}){super(s??Mz(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},kh=new Map;gE=1e3,yE=5;D={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},Fz=[["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"]];ln=class extends au{constructor(e){super(e?.dbPath??Fv("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=(this.db.pragma("table_xinfo(session_events)")??[]).find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch(e){tt("SessionDB.initSchema.dataHashMigration",e,this.dbPath)}this.db.exec(`
9
+ deps: ${n}}`};var NM={keyword:"dependencies",type:"object",schemaType:"object",error:kn.error,code(t){let[e,n]=DM(t);bk(t,e),Sk(t,n)}};function DM({schema:t}){let e={},n={};for(let r in t){if(r==="__proto__")continue;let o=Array.isArray(t[r])?e:n;o[r]=t[r]}return[e,n]}function bk(t,e=t.schema){let{gen:n,data:r,it:o}=t;if(Object.keys(e).length===0)return;let s=n.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Mi.propertyInData)(n,r,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?n.if(c,()=>{for(let u of a)(0,Mi.checkReportMissingProp)(t,u)}):(n.if((0,km._)`${c} && (${(0,Mi.checkMissingProp)(t,a,s)})`),(0,Mi.reportMissingProp)(t,s),n.else())}}kn.validatePropertyDeps=bk;function Sk(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,AM.alwaysValidSchema)(s,e[a])||(n.if((0,Mi.propertyInData)(n,r,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>n.var(i,!0)),t.ok(i))}kn.validateSchemaDeps=Sk;kn.default=NM});var Ek=I(vm=>{"use strict";Object.defineProperty(vm,"__esModule",{value:!0});var vk=ee(),MM=le(),jM={message:"property name must be valid",params:({params:t})=>(0,vk._)`{propertyName: ${t.propertyName}}`},LM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:jM,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,MM.alwaysValidSchema)(o,n))return;let s=e.name("valid");e.forIn("key",r,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,vk.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};vm.default=LM});var wm=I(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var zc=Ft(),cn=ee(),zM=Ln(),Hc=le(),HM={message:"must NOT have additional properties",params:({params:t})=>(0,cn._)`{additionalProperty: ${t.additionalProperty}}`},UM={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:HM,code(t){let{gen:e,schema:n,parentSchema:r,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Hc.alwaysValidSchema)(i,n))return;let u=(0,zc.allSchemaProperties)(r.properties),l=(0,zc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,cn._)`${s} === ${zM.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 _=(0,Hc.schemaRefOrVal)(i,r.properties,"properties");y=(0,zc.isOwnProperty)(e,_,g)}else u.length?y=(0,cn.or)(...u.map(_=>(0,cn._)`${g} === ${_}`)):y=cn.nil;return l.length&&(y=(0,cn.or)(y,...l.map(_=>(0,cn._)`${(0,zc.usePattern)(t,_)}.test(${g})`))),(0,cn.not)(y)}function m(g){e.code((0,cn._)`delete ${o}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&n===!1){m(g);return}if(n===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof n=="object"&&!(0,Hc.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,cn.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,cn.not)(y),()=>e.break()))}}function h(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:Hc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};Em.default=UM});var Pk=I(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});var FM=Si(),wk=Ft(),Tm=le(),Tk=wm(),BM={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,parentSchema:r,data:o,it:s}=t;s.opts.removeAdditional==="all"&&r.additionalProperties===void 0&&Tk.default.code(new FM.KeywordCxt(s,Tk.default,"additionalProperties"));let i=(0,wk.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Tm.mergeEvaluated.props(e,(0,Tm.toHash)(i),s.props));let a=i.filter(d=>!(0,Tm.alwaysValidSchema)(s,n[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,wk.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&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};Pm.default=BM});var Ok=I(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var Rk=Ft(),Uc=ee(),Ck=le(),$k=le(),ZM={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:n,data:r,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,Rk.allSchemaProperties)(n),c=a.filter(h=>(0,Ck.alwaysValidSchema)(s,n[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 Uc.Name)&&(s.props=(0,$k.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,Ck.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,Uc._)`${(0,Rk.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:$k.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Uc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Uc.not)(l),()=>e.break())})})}}};Rm.default=ZM});var Ik=I(Cm=>{"use strict";Object.defineProperty(Cm,"__esModule",{value:!0});var qM=le(),VM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,qM.alwaysValidSchema)(r,n)){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"}};Cm.default=VM});var Ak=I($m=>{"use strict";Object.defineProperty($m,"__esModule",{value:!0});var WM=Ft(),KM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:WM.validateUnion,error:{message:"must match a schema in anyOf"}};$m.default=KM});var Nk=I(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var Fc=ee(),GM=le(),JM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Fc._)`{passingSchemas: ${t.passing}}`},XM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:JM,code(t){let{gen:e,schema:n,parentSchema:r,it:o}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");if(o.opts.discriminator&&r.discriminator)return;let s=n,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,GM.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Fc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Fc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Fc.Name)})})}}};Om.default=XM});var Dk=I(Im=>{"use strict";Object.defineProperty(Im,"__esModule",{value:!0});var YM=le(),QM={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:n,it:r}=t;if(!Array.isArray(n))throw new Error("ajv implementation error");let o=e.name("valid");n.forEach((s,i)=>{if((0,YM.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Im.default=QM});var Lk=I(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});var Bc=ee(),jk=le(),ej={message:({params:t})=>(0,Bc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Bc._)`{failingKeyword: ${t.ifClause}}`},tj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ej,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,jk.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Mk(r,"then"),s=Mk(r,"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,Bc.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,Bc._)`${l}`):t.setParams({ifClause:l})}}}};function Mk(t,e){let n=t.schema[e];return n!==void 0&&!(0,jk.alwaysValidSchema)(t,n)}Am.default=tj});var zk=I(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});var nj=le(),rj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,nj.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};Nm.default=rj});var Hk=I(Dm=>{"use strict";Object.defineProperty(Dm,"__esModule",{value:!0});var oj=ym(),sj=gk(),ij=_m(),aj=_k(),cj=xk(),uj=kk(),lj=Ek(),dj=wm(),pj=Pk(),fj=Ok(),mj=Ik(),hj=Ak(),gj=Nk(),yj=Dk(),_j=Lk(),xj=zk();function bj(t=!1){let e=[mj.default,hj.default,gj.default,yj.default,_j.default,xj.default,lj.default,dj.default,uj.default,pj.default,fj.default];return t?e.push(sj.default,aj.default):e.push(oj.default,ij.default),e.push(cj.default),e}Dm.default=bj});var Uk=I(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});var Le=ee(),Sj={message:({schemaCode:t})=>(0,Le.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Le._)`{format: ${t}}`},kj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:Sj,code(t,e){let{gen:n,data:r,$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=n.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=n.const("fDef",(0,Le._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Le._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Le._)`${h}.type || "string"`).assign(y,(0,Le._)`${h}.validate`),()=>n.assign(g,(0,Le._)`"string"`).assign(y,h)),t.fail$data((0,Le.or)(_(),x()));function _(){return c.strictSchema===!1?Le.nil:(0,Le._)`${i} && !${y}`}function x(){let b=l.$async?(0,Le._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Le._)`${y}(${r})`,v=(0,Le._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${r}))`;return(0,Le._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=x(p);h===e&&t.pass(b());function _(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(v){let O=v instanceof RegExp?(0,Le.regexpCode)(v):c.code.formats?(0,Le._)`${c.code.formats}${(0,Le.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Le._)`${R}.validate`]:["string",v,R]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Le._)`await ${y}(${r})`}return typeof g=="function"?(0,Le._)`${y}(${r})`:(0,Le._)`${y}.test(${r})`}}}};Mm.default=kj});var Fk=I(jm=>{"use strict";Object.defineProperty(jm,"__esModule",{value:!0});var vj=Uk(),Ej=[vj.default];jm.default=Ej});var Bk=I(ts=>{"use strict";Object.defineProperty(ts,"__esModule",{value:!0});ts.contentVocabulary=ts.metadataVocabulary=void 0;ts.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ts.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var qk=I(Lm=>{"use strict";Object.defineProperty(Lm,"__esModule",{value:!0});var wj=YS(),Tj=pk(),Pj=Hk(),Rj=Fk(),Zk=Bk(),Cj=[wj.default,Tj.default,(0,Pj.default)(),Rj.default,Zk.metadataVocabulary,Zk.contentVocabulary];Lm.default=Cj});var Wk=I(Zc=>{"use strict";Object.defineProperty(Zc,"__esModule",{value:!0});Zc.DiscrError=void 0;var Vk;(function(t){t.Tag="tag",t.Mapping="mapping"})(Vk||(Zc.DiscrError=Vk={}))});var Gk=I(Hm=>{"use strict";Object.defineProperty(Hm,"__esModule",{value:!0});var ns=ee(),zm=Wk(),Kk=wc(),$j=ki(),Oj=le(),Ij={message:({params:{discrError:t,tagName:e}})=>t===zm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,ns._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},Aj={keyword:"discriminator",type:"object",schemaType:"object",error:Ij,code(t){let{gen:e,data:n,schema:r,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=r.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(r.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,ns._)`${n}${(0,ns.getProperty)(a)}`);e.if((0,ns._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:zm.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,ns._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:zm.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,ns.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let v=i[b];if(v?.$ref&&!(0,Oj.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=Kk.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof Kk.SchemaEnv&&(v=v.schema),v===void 0)throw new $j.default(s.opts.uriResolver,s.baseId,R)}let O=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(v)),_(O,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 _(b,v){if(b.const)x(b.const,v);else if(b.enum)for(let O of b.enum)x(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(b,v){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=v}}}};Hm.default=Aj});var Jk=I((CV,Nj)=>{Nj.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 Fm=I((we,Um)=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.MissingRefError=we.ValidationError=we.CodeGen=we.Name=we.nil=we.stringify=we.str=we._=we.KeywordCxt=we.Ajv=void 0;var Dj=VS(),Mj=qk(),jj=Gk(),Xk=Jk(),Lj=["/properties"],qc="http://json-schema.org/draft-07/schema",rs=class extends Dj.default{_addVocabularies(){super._addVocabularies(),Mj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(jj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Xk,Lj):Xk;this.addMetaSchema(e,qc,!1),this.refs["http://json-schema.org/schema"]=qc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(qc)?qc:void 0)}};we.Ajv=rs;Um.exports=we=rs;Um.exports.Ajv=rs;Object.defineProperty(we,"__esModule",{value:!0});we.default=rs;var zj=Si();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return zj.KeywordCxt}});var os=ee();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return os._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return os.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return os.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return os.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return os.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return os.CodeGen}});var Hj=vc();Object.defineProperty(we,"ValidationError",{enumerable:!0,get:function(){return Hj.default}});var Uj=ki();Object.defineProperty(we,"MissingRefError",{enumerable:!0,get:function(){return Uj.default}})});var sv=I(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.formatNames=En.fastFormats=En.fullFormats=void 0;function vn(t,e){return{validate:t,compare:e}}En.fullFormats={date:vn(tv,Vm),time:vn(Zm(!0),Wm),"date-time":vn(Yk(!0),rv),"iso-time":vn(Zm(),nv),"iso-date-time":vn(Yk(),ov),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Wj,"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:eL,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:Kj,int32:{type:"number",validate:Xj},int64:{type:"number",validate:Yj},float:{type:"number",validate:ev},double:{type:"number",validate:ev},password:!0,binary:!0};En.fastFormats={...En.fullFormats,date:vn(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Vm),time:vn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Wm),"date-time":vn(/^\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,rv),"iso-time":vn(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,nv),"iso-date-time":vn(/^\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,ov),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};En.formatNames=Object.keys(En.fullFormats);function Fj(t){return t%4===0&&(t%100!==0||t%400===0)}var Bj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Zj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function tv(t){let e=Bj.exec(t);if(!e)return!1;let n=+e[1],r=+e[2],o=+e[3];return r>=1&&r<=12&&o>=1&&o<=(r===2&&Fj(n)?29:Zj[r])}function Vm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Bm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Zm(t){return function(n){let r=Bm.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[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 Wm(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function nv(t,e){if(!(t&&e))return;let n=Bm.exec(t),r=Bm.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var qm=/t|\s/i;function Yk(t){let e=Zm(t);return function(r){let o=r.split(qm);return o.length===2&&tv(o[0])&&e(o[1])}}function rv(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function ov(t,e){if(!(t&&e))return;let[n,r]=t.split(qm),[o,s]=e.split(qm),i=Vm(n,o);if(i!==void 0)return i||Wm(r,s)}var qj=/\/|:/,Vj=/^(?:[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 Wj(t){return qj.test(t)&&Vj.test(t)}var Qk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Kj(t){return Qk.lastIndex=0,Qk.test(t)}var Gj=-(2**31),Jj=2**31-1;function Xj(t){return Number.isInteger(t)&&t<=Jj&&t>=Gj}function Yj(t){return Number.isInteger(t)}function ev(){return!0}var Qj=/[^\\]\\Z/;function eL(t){if(Qj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var iv=I(ss=>{"use strict";Object.defineProperty(ss,"__esModule",{value:!0});ss.formatLimitDefinition=void 0;var tL=Fm(),un=ee(),pr=un.operators,Vc={formatMaximum:{okStr:"<=",ok:pr.LTE,fail:pr.GT},formatMinimum:{okStr:">=",ok:pr.GTE,fail:pr.LT},formatExclusiveMaximum:{okStr:"<",ok:pr.LT,fail:pr.GTE},formatExclusiveMinimum:{okStr:">",ok:pr.GT,fail:pr.LTE}},nL={message:({keyword:t,schemaCode:e})=>(0,un.str)`should be ${Vc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,un._)`{comparison: ${Vc[t].okStr}, limit: ${e}}`};ss.formatLimitDefinition={keyword:Object.keys(Vc),type:"string",schemaType:"string",$data:!0,error:nL,code(t){let{gen:e,data:n,schemaCode:r,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new tL.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,un._)`${f}[${c.schemaCode}]`);t.fail$data((0,un.or)((0,un._)`typeof ${m} != "object"`,(0,un._)`${m} instanceof RegExp`,(0,un._)`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,un._)`${i.code.formats}${(0,un.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,un._)`${f}.compare(${n}, ${r}) ${Vc[o].fail} 0`}},dependencies:["format"]};var rL=t=>(t.addKeyword(ss.formatLimitDefinition),t);ss.default=rL});var lv=I((ji,uv)=>{"use strict";Object.defineProperty(ji,"__esModule",{value:!0});var is=sv(),oL=iv(),Km=ee(),av=new Km.Name("fullFormats"),sL=new Km.Name("fastFormats"),Gm=(t,e={keywords:!0})=>{if(Array.isArray(e))return cv(t,e,is.fullFormats,av),t;let[n,r]=e.mode==="fast"?[is.fastFormats,sL]:[is.fullFormats,av],o=e.formats||is.formatNames;return cv(t,o,n,r),e.keywords&&(0,oL.default)(t),t};Gm.get=(t,e="full")=>{let r=(e==="fast"?is.fastFormats:is.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function cv(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Km._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}uv.exports=ji=Gm;Object.defineProperty(ji,"__esModule",{value:!0});ji.default=Gm});function zi(t,e){let n=process.execPath.replace(/\\/g,"/");if(tu(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Qm.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function ze(t,e){if(tu(e?.platform))return zi(t,e);let r=Ev().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function eu(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}function tu(t){return!!t&&mL.has(t)}var Qm,mL,Hn=J(()=>{"use strict";nu();Qm=new Set(["node","bun","deno"]),mL=new Set(["opencode","kilo"])});import{execFileSync as nh,execSync as as}from"node:child_process";import{existsSync as cs}from"node:fs";function th(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function gL(t){return hL.test(th(t))}function yL(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function _L(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function Ue(t){try{let e=Hi?`where ${t}`:`command -v ${t}`;return as(e,{stdio:"pipe"}),!0}catch{return!1}}function eh(t){if(Hi)try{let n=as(`where ${t}`,{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(n.length===0||n.filter(o=>!/\\Microsoft\\WindowsApps\\/i.test(o)).length===0)return!1}catch{return!1}else if(!Ue(t))return!1;try{return Hi?as(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):nh(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function rh(){if(Ue("bun"))return!0;for(let t of Pv())if(cs(t))return!0;return!1}function Tv(){for(let e of Pv())if(cs(e))return e;if(Ue("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Hi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Pv(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Hi){let e=process.env.LOCALAPPDATA??"",n=process.env.APPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[],...n?[`${n}\\npm\\node_modules\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function Rv(){let t;try{t=as("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean)}catch{return null}for(let e of t){let n=e.toLowerCase();if(!(n.includes("system32")||n.includes("windowsapps"))){for(let r of xL)if(cs(r))return r;return e}}return null}function bL(t=Rv()){return t??(Ue("sh")?"sh":Ue("pwsh")?"pwsh":Ue("powershell")?"powershell":"cmd.exe")}function qt(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return as(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return nh(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function SL(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??Ue,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Qm.has(o)&&cs(n)?n:r("node")?"node":null}function ru(){let e=rh()?Tv():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Rv():null,s=n&&cs(n)&&gL(n)&&!(r&&yL(n))&&!(r&&o&&_L(n))?n:null;return{javascript:SL(e),typescript:e||(Ue("tsx")?"tsx":Ue("ts-node")?"ts-node":null),python:eh("python3")?"python3":eh("python")?"python":eh("py")?"py":null,shell:s??(r?bL(o):Ue("bash")?"bash":"sh"),ruby:Ue("ruby")?"ruby":null,go:Ue("go")?"go":null,rust:Ue("rustc")?"rustc":null,php:Ue("php")?"php":null,perl:Ue("perl")?"perl":null,r:Ue("Rscript")?"Rscript":Ue("r")?"r":null,elixir:Ue("elixir")?"elixir":null,csharp:Ue("dotnet-script")?"dotnet-script":null}}function ou(){return rh()}function kL(t){let e=t.trim(),n=/^(\d+)\.(\d+)\.(\d+)/.exec(e);if(!n)return!1;let r=Number(n[1]);return Number.isFinite(r)&&r>=1}function vL(){return cs(process.execPath)?{path:process.execPath,isBun:!1}:Ue("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Ev(){if(Vt)return Vt;let t=vL();try{if(!rh())return Vt=t,Vt;let e=Tv(),n;try{if(process.platform==="win32"){let r=as(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=nh(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Vt=t,Vt}return kL(n)?(Vt={path:e,isBun:!0},Vt):(Vt=t,Vt)}catch{return Vt=t,Vt}}function Cv(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${qt(t.javascript)})${n?" \u26A1":""}`):e.push(" JavaScript: not available (install node or bun \u2014 host process is not a JS runtime)"),t.typescript?e.push(` TypeScript: ${t.typescript} (${qt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${qt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${qt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${qt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${qt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${qt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${qt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${qt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${qt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${qt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${qt(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
10
+ `)}function $v(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 Ov(t,e,n){switch(e){case"javascript":if(!t.javascript)throw new Error("No JavaScript runtime available. Install Node.js or Bun on PATH (the host process is not itself a JS runtime).");return wv.test(th(t.javascript))?[t.javascript,"run",n]:[t.javascript,n];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 wv.test(th(t.typescript))?[t.typescript,"run",n]:t.typescript==="tsx"?["tsx",n]:["ts-node",n];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,n];case"shell":{if(process.platform==="win32"){let o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let i=n.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${i}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-NoProfile","-ExecutionPolicy","Bypass","-File",n];let s=o.split(/[\\/]/).pop()??o;if(s==="cmd"||s==="cmd.exe")return[t.shell,"/d","/s","/c",n]}return[t.shell,n]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,n];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",n];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",n]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",n];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",n];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,n];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",n];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,n]}}var hL,wv,Hi,xL,Vt,nu=J(()=>{"use strict";Hn();hL=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,wv=/^bun(\.exe)?$/i;Hi=process.platform==="win32";xL=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Vt=null});import{createRequire as LL}from"node:module";import{existsSync as zL,unlinkSync as Hv,renameSync as HL}from"node:fs";import{tmpdir as UL}from"node:os";import{join as FL}from"node:path";function BL(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 ZL(t,e){let n=e!==void 0?e:globalThis.Bun;if(typeof n<"u"&&n!==null)return!0;let r=t??process.versions,[o,s]=(r.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 qe(){if(!us){let t=LL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;us=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new ah(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(ZL()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&BL(e)?us=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new ch(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:us=t("better-sqlite3")}else us=t("better-sqlite3")}return us}function ls(t,e=process.env){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");let n=qL(e);if(n!==null)try{t.pragma(`mmap_size = ${n}`)}catch{}}function qL(t=process.env){let e=t.CONTEXT_MODE_DB_MMAP_SIZE;if(e==null)return null;let n=String(e).trim();if(n==="")return null;let r=Number(n);return!Number.isFinite(r)||!Number.isInteger(r)||r<0?null:r}function io(t){if(!zL(t))for(let e of["-wal","-shm"])try{Hv(t+e)}catch{}}function uh(t){for(let e of["","-wal","-shm"])try{Hv(t+e)}catch{}}function Bi(t){try{t.close()}catch{}}function Uv(t="context-mode"){return FL(UL(),`${t}-${process.pid}.db`)}function Fv(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?`${e} ${t.message}`:t.message}if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.code,n=t.message,r=[typeof e=="string"?e:"",typeof n=="string"?n:""].filter(Boolean);return r.length>0?r.join(" "):String(t)}return String(t)}function VL(t){let e=Fv(t);return e.includes("SQLITE_BUSY")||e.includes("database is locked")||e.includes("SQLITE_IOERR")||/disk i\/o error/i.test(e)}function De(t,e=[100,500,2e3]){let n;for(let s=0;s<=e.length;s++)try{return t()}catch(i){if(!VL(i))throw i;if(n=i instanceof Error?i:new Error(Fv(i)),!(i instanceof Error)){let a=Zi(i);a&&(n.code=a)}if(s<e.length){let a=e[s],c=Date.now();for(;Date.now()-c<a;);}}let r=new Error(`SQLITE_BUSY/SQLITE_IOERR: transient SQLite error after ${e.length} retries. Original error: ${n?.message}`),o=n?Zi(n):"";throw o&&(r.code=o),r}function lh(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 WL(t){let e=Date.now();for(let n of["","-wal","-shm"])try{HL(t+n,`${t}${n}.corrupt-${e}`)}catch{}}function Zi(t){if(t instanceof Error){let e=t.code;return typeof e=="string"?e:""}if(t!==null&&typeof t=="object"){let e=t.code;return typeof e=="string"?e:""}return""}function au(t){if(t instanceof Error)return t.message;if(typeof t=="string")return t;if(t!==null&&typeof t=="object"){let e=t.message;if(typeof e=="string"&&e)return e}return String(t)}function tt(t,e,n,r=Date.now()){try{let o=Zi(e),s=au(e),i=n?` (${n})`:"",a=`${t}|${o}|${s}${i}`,c=mr.get(a);if(c!==void 0&&r-c<Lv)return;if(mr.set(a,r),mr.size>zv){for(let[m,p]of mr)r-p>=Lv&&mr.delete(m);for(;mr.size>zv;){let m=mr.keys().next().value;if(m===void 0)break;mr.delete(m)}}let u=process.env.OPENCODE_DEBUG,d=u!==void 0&&u!==""&&u!=="0"&&u!=="false"&&e instanceof Error&&e.stack?`
11
+ ${e.stack}`:"",f=o?` [${o}]`:"";console.error(`${KL} ${t}${f}: ${s}${i}${d}`)}catch{}}var ah,ch,us,KL,Lv,zv,mr,Fi,ih,iu,ao=J(()=>{"use strict";ah=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){let n="",r=null;for(let s=0;s<e.length;s++){let i=e[s];if(r)n+=i,i===r&&(r=null);else if(i==="'"||i==='"')n+=i,r=i;else if(i===";"){let a=n.trim();a&&this.#e.prepare(a).run(),n=""}else n+=i}let o=n.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>{let o=n.get(...r);return o===null?void 0:o},all:(...r)=>n.all(...r),iterate:(...r)=>n.iterate(...r)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},ch=class{#e;constructor(e){this.#e=e}pragma(e){let r=this.#e.prepare(`PRAGMA ${e}`).all();if(!r||r.length===0)return;if(r.length>1)return r;let o=Object.values(r[0]);return o.length===1?o[0]:r[0]}exec(e){return this.#e.exec(e),this}prepare(e){let n=this.#e.prepare(e);return{run:(...r)=>n.run(...r),get:(...r)=>n.get(...r),all:(...r)=>n.all(...r),iterate:(...r)=>typeof n.iterate=="function"?n.iterate(...r):n.all(...r)[Symbol.iterator]()}}transaction(e){return(...n)=>{this.#e.exec("BEGIN");try{let r=e(...n);return this.#e.exec("COMMIT"),r}catch(r){throw this.#e.exec("ROLLBACK"),r}}}close(){this.#e.close()}},us=null;KL="[context-mode:db]",Lv=3e4,zv=256,mr=new Map;Fi=Symbol.for("__context_mode_live_dbs_v3__"),ih=(()=>{let t=globalThis;return t[Fi]||(t[Fi]=new Set,process.on("exit",()=>{for(let e of t[Fi])Bi(e);t[Fi].clear()})),t[Fi]})(),iu=class{#e;#t;constructor(e){let n=qe();this.#e=e,io(e);let r;try{r=new n(e,{timeout:3e4}),ls(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(lh(s)){tt("SQLiteBase.open",o,e),WL(e),io(e);try{r=new n(e,{timeout:3e4}),ls(r)}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=r,ih.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){ih.delete(this.#t),Bi(this.#t)}withRetry(e){return De(e)}cleanup(){ih.delete(this.#t),Bi(this.#t),uh(this.#e)}}});var pE,fE=J(()=>{"use strict";pE={"claude-code":"claude-code","gemini-cli-mcp-client":"gemini-cli","antigravity-client":"antigravity","antigravity-cli":"antigravity-cli",agy:"antigravity-cli","cursor-vscode":"cursor","Visual-Studio-Code":"vscode-copilot","copilot-cli":"copilot-cli","GitHub Copilot CLI":"copilot-cli","github-copilot-cli":"copilot-cli","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","kimi-code":"kimi",kimi:"kimi","Kimi Code":"kimi"}});import{createHash as Vi}from"node:crypto";import{execFileSync as Pz}from"node:child_process";import{accessSync as Rz,constants as Cz,existsSync as fu,mkdirSync as $z,realpathSync as Oz,renameSync as Sh}from"node:fs";import{homedir as xE}from"node:os";import{dirname as Iz,isAbsolute as bE,join as hr,resolve as ps}from"node:path";function kh(t){let e=t.env??process.env,n=t.legacySessionDirEnv,r=n?e[n]?.trim():void 0;return r&&n?(t.onLegacySessionDir?.(n,r),r):hr(Az(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function Az(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?hE(r.trim()):hE(t,xE())}function hE(t,e){return t.startsWith("~")?ps(xE(),t.replace(/^~[/\\]?/,"")):bE(t)?ps(t):e?ps(e,t):ps(t)}function Nz(t,e,n){return new gr(t,e,wn,void 0,[`Invalid ${wn} for context-mode ${t} directory: ${n}`,wE()].join(`
12
+ `))}function kE(t){let e=process.env[wn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:wn,ignoredReason:"empty"};if(!bE(n))throw Nz(t,n,`${wn} must be an absolute path.`);return{kind:"override",root:ps(n)}}function Dz(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function vE(t,e){let n=kE(t);return n.kind!=="override"?null:{kind:t,path:hr(n.root,e),envVar:wn,source:"override"}}function Mz(t,e,n){return{kind:t,path:ps(e()),envVar:null,source:"default",...n}}function Wi(t){let e=kE("session");return e.kind==="override"?{kind:"session",path:hr(e.root,SE),envVar:wn,source:"override"}:Mz("session",t,Dz(e))}function vh(t){let e=vE("content",mE);if(e)return e;let n=Wi(t);return{kind:"content",path:hr(Iz(n.path),mE),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Eh(t){let e=vE("stats",SE);if(e)return e;let n=Wi(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function EE(t){return t.message}function mu(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function hu(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=bh.get(e);if(n instanceof gr)throw n;if(n===t.path)return n;try{return $z(t.path,{recursive:!0}),Rz(t.path,Cz.W_OK),bh.set(e,t.path),t.path}catch(r){let o=new gr(t.kind,zz(r)??t.path,wn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw bh.set(e,o),o}}function jz(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,Lz(n),wE()].filter(Boolean).join(`
13
+ `)}function Lz(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function wE(){return`Set ${wn} to a writable absolute path.`}function zz(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function co(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function gE(t){let e=t;try{e=Oz.native(t)}catch{}let n=co(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function TE(t,e){return Pz("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function Hz(t){let e=TE(t,["rev-parse","--show-toplevel"]);return e.length>0?co(e):null}function Uz(t){let e=TE(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?co(e):null}function gu(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(qi&&qi.projectDir===t&&qi.envSuffix===e)return qi.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=Hz(t),o=Uz(t);if(r&&o){let s=gE(r),i=gE(o);s!==i&&(n=`__${Vi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return qi={projectDir:t,envSuffix:e,suffix:n},n}function Un(t){return Vi("sha256").update(co(t)).digest("hex").slice(0,16)}function nt(t){let e=co(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Vi("sha256").update(n).digest("hex").slice(0,16)}function PE(t){let{projectDir:e,contentDir:n}=t,r=nt(e),o=hr(n,`${r}.db`);if(fu(o))return o;let s=Un(e);if(s===r)return o;let i=hr(n,`${s}.db`);if(fu(i))try{Sh(i,o);for(let a of["-wal","-shm"])try{Sh(i+a,o+a)}catch{}}catch{}return o}function Ki(t){return wh({...t,ext:".db"})}function wh(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??gu(e),s=nt(e),i=hr(n,`${s}${o}${r}`);if(fu(i))return i;let a=Un(e);if(a===s)return i;let c=hr(n,`${a}${o}${r}`);if(fu(c))try{Sh(c,i)}catch{}return i}function pu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function RE(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of Fz)n.has(o)||(t.exec(`ALTER TABLE session_events ADD COLUMN ${o} ${s}`),r=!0);return r&&t.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)"),r}function CE(t,e){let n=null;try{n=new e(t),RE(n)}catch(r){tt("ensureSessionEventsSchema",r,t)}finally{try{n?.close()}catch{}}}var wn,SE,mE,gr,bh,qi,yE,_E,D,Fz,ln,Tn=J(()=>{"use strict";ao();wn="CONTEXT_MODE_DIR",SE="sessions",mE="content",gr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=wn,o,s,i={}){super(s??jz(e,n,i),{cause:o}),this.name="StorageDirectoryError",this.kind=e,this.path=n,this.overrideEnvVar=r,this.ignoredEnvVar=i.ignoredEnvVar,this.ignoredReason=i.ignoredReason}},bh=new Map;yE=1e3,_E=5;D={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",getSessionRollup:"getSessionRollup",getMaxFileEdits:"getMaxFileEdits",getLatestCommitMessage:"getLatestCommitMessage",incrementCompactCount:"incrementCompactCount",getUsageCursor:"getUsageCursor",setUsageCursor:"setUsageCursor",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"},Fz=[["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"]];ln=class extends iu{constructor(e){super(e?.dbPath??Uv("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let n=(this.db.pragma("table_xinfo(session_events)")??[]).find(r=>r.name==="data_hash");n&&n.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch(e){tt("SessionDB.initSchema.dataHashMigration",e,this.dbPath)}this.db.exec(`
14
14
  CREATE TABLE IF NOT EXISTS session_events (
15
15
  id INTEGER PRIMARY KEY AUTOINCREMENT,
16
16
  session_id TEXT NOT NULL,
@@ -60,7 +60,7 @@ ${e.stack}`:"",f=o?` [${o}]`:"";console.error(`${WL} ${t}${f}: ${s}${i}${d}`)}ca
60
60
  );
61
61
 
62
62
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
63
- `);try{PE(this.db)}catch(e){tt("SessionDB.initSchema.migrateColumns",e,this.dbPath)}try{(this.db.pragma("table_xinfo(session_meta)")??[]).some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch(e){tt("SessionDB.initSchema.usageCursorMigration",e,this.dbPath)}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(D.insertEvent,`INSERT INTO session_events (
63
+ `);try{RE(this.db)}catch(e){tt("SessionDB.initSchema.migrateColumns",e,this.dbPath)}try{(this.db.pragma("table_xinfo(session_meta)")??[]).some(n=>n.name==="usage_cursor")||this.db.exec("ALTER TABLE session_meta ADD COLUMN usage_cursor TEXT")}catch(e){tt("SessionDB.initSchema.usageCursorMigration",e,this.dbPath)}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(D.insertEvent,`INSERT INTO session_events (
64
64
  session_id, type, category, priority, data,
65
65
  project_dir, attribution_source, attribution_confidence,
66
66
  bytes_avoided, bytes_returned,
@@ -149,53 +149,53 @@ ${e.stack}`:"",f=o?` [${o}]`:"";console.error(`${WL} ${t}${f}: ${s}${i}${d}`)}ca
149
149
  FROM tool_calls WHERE session_id = ?`),e(D.getToolCallByTool,`SELECT tool, calls, bytes_returned
150
150
  FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(D.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
151
151
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
152
- FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Vi("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=fu(s?.bytesAvoided),f=fu(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(D.checkDuplicate).get(e,yE,n.type,i))return;this.stmt(D.getEventCount).get(e).cnt>=gE&&this.stmt(D.evictLowestPriority).run(e),this.stmt(D.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,f,r,i),this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Vi("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=f===""?"":uo(f),p=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=fu(y?.bytesAvoided),x=fu(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:p,attributionConfidence:g,bytesAvoided:_,bytesReturned:x}}),a=this.db.transaction(()=>{let c=this.stmt(D.getEventCount).get(e).cnt;for(let u of i)this.stmt(D.checkDuplicate).get(e,yE,u.event.type,u.dataHash)||(c>=gE?this.stmt(D.evictLowestPriority).run(e):c++,this.stmt(D.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,r,u.dataHash));this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(D.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(D.getEventsByType).all(e,o,r):s!==void 0?this.stmt(D.getEventsByPriority).all(e,s,r):this.stmt(D.getEvents).all(e,r)}getEventCount(e){return this.stmt(D.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(D.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(D.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(n){return tt("SessionDB.getSessionProjectDir",n,this.dbPath),""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(D.searchEvents).all(r,s,s,i,i,n)}catch(s){return tt("SessionDB.searchEvents",s,this.dbPath),[]}}getSessionIdsForProject(e){try{let n=uo(e);return this.db.prepare(`SELECT DISTINCT session_id
152
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Vi("sha256").update(n.data).digest("hex").slice(0,16).toUpperCase(),a=String(o?.projectDir??n.project_dir??this._getSessionProjectDir(e)).trim(),c=String(o?.source??n.attribution_source??"unknown"),u=Number(o?.confidence??n.attribution_confidence??0),l=Number.isFinite(u)?Math.max(0,Math.min(1,u)):0,d=pu(s?.bytesAvoided),f=pu(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(D.checkDuplicate).get(e,_E,n.type,i))return;this.stmt(D.getEventCount).get(e).cnt>=yE&&this.stmt(D.evictLowestPriority).run(e),this.stmt(D.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,f,r,i),this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>m())}bulkInsertEvents(e,n,r="PostToolUse",o,s){if(!n||n.length===0)return;if(n.length===1){this.insertEvent(e,n[0],r,o?.[0],s?.[0]);return}let i=n.map((c,u)=>{let l=Vi("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=f===""?"":co(f),p=String(d?.source??c.attribution_source??"unknown"),h=Number(d?.confidence??c.attribution_confidence??0),g=Number.isFinite(h)?Math.max(0,Math.min(1,h)):0,y=s?.[u],_=pu(y?.bytesAvoided),x=pu(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:p,attributionConfidence:g,bytesAvoided:_,bytesReturned:x}}),a=this.db.transaction(()=>{let c=this.stmt(D.getEventCount).get(e).cnt;for(let u of i)this.stmt(D.checkDuplicate).get(e,_E,u.event.type,u.dataHash)||(c>=yE?this.stmt(D.evictLowestPriority).run(e):c++,this.stmt(D.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,r,u.dataHash));this.stmt(D.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,n){let r=n?.limit??1e3,o=n?.type,s=n?.minPriority;return o&&s!==void 0?this.stmt(D.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(D.getEventsByType).all(e,o,r):s!==void 0?this.stmt(D.getEventsByPriority).all(e,s,r):this.stmt(D.getEvents).all(e,r)}getEventCount(e){return this.stmt(D.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(D.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(D.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(n){return tt("SessionDB.getSessionProjectDir",n,this.dbPath),""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(D.searchEvents).all(r,s,s,i,i,n)}catch(s){return tt("SessionDB.searchEvents",s,this.dbPath),[]}}getSessionIdsForProject(e){try{let n=co(e);return this.db.prepare(`SELECT DISTINCT session_id
153
153
  FROM session_events
154
- WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch(n){return tt("SessionDB.getSessionIdsForProject",n,this.dbPath),[]}}ensureSession(e,n){this.stmt(D.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(D.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(D.getSessionRollup).get(e),r=this.stmt(D.getMaxFileEdits).get(e),o=this.stmt(D.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(D.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(D.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(D.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(D.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(D.getResume).get(e)??null}markResumeConsumed(e){this.stmt(D.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(D.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.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(e){return tt("SessionDB.getLatestSessionId",e,this.dbPath),null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(D.incrementToolCall).run(e,n,o)}catch(s){tt("SessionDB.incrementToolCall",s,this.dbPath)}}getToolCallStats(e){try{let n=this.stmt(D.getToolCallTotals).get(e),r=this.stmt(D.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch(n){return tt("SessionDB.getToolCallStats",n,this.dbPath),{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(D.deleteEvents).run(e),this.stmt(D.deleteResume).run(e),this.stmt(D.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(D.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as hs,resolve as CE}from"node:path";import{accessSync as Bz,copyFileSync as Zz,constants as qz,mkdirSync as Vz}from"node:fs";import{homedir as Ph}from"node:os";function lt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?CE(Ph(),e.replace(/^~[/\\]?/,"")):CE(e)}var ye,rt=J(()=>{"use strict";Pn();ye=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=lt(),n=e?hs(e,"context-mode","sessions"):hs(Ph(),...this.sessionDirSegments,"context-mode","sessions");return Vz(n,{recursive:!0}),n}getConfigDir(e){return hs(Ph(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=lt(),r=n?hs(n,"context-mode","memory"):hs(this.getConfigDir(),"memory");return e?hs(r,nt(e)):r}backupSettings(){let e=this.getSettingsPath();try{Bz(e,qz.R_OK);let n=e+".bak";return Zz(e,n),n}catch{return null}}}});var gs,Rh=J(()=>{"use strict";rt();gs=class extends ye{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Ch}from"node:fs";import{join as $h}from"node:path";async function Wz(){if(ys)return ys;if(_s)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 n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return ys=r,ys}catch(r){e=r}return _s=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return _s=t instanceof Error?t.message:String(t),null}}function Kz(t){let e=[];return Ch($h(t,"start.mjs"))||e.push("start.mjs"),!Ch($h(t,"server.bundle.mjs"))&&!Ch($h(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function $E(t){if(ys){let e=ys.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(_s){let e=Kz(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${_s}); the MCP server cannot start. Reinstall: npm install -g @mxalbert/context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${_s}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var ys,_s,OE=J(()=>{"use strict";ys=null,_s=null;Wz()});function Gi(t,e){let n=lo[e],r=Ih(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function Ih(t,e){if(e){let n=lo[t];return Le(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Ah(t){let e=tu(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function NE(t){let e=Object.values(lo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Wt,Gz,Oh,IE,Jz,mK,lo,AE,hK,DE=J(()=>{"use strict";Un();Wt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},Gz="mcp__",Oh=["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",Gz],IE=Oh.join("|"),Jz=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],mK=Jz.join("|"),lo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},AE=[Wt.PRE_TOOL_USE,Wt.SESSION_START],hK=[Wt.POST_TOOL_USE,Wt.PRE_COMPACT,Wt.USER_PROMPT_SUBMIT,Wt.STOP]});var Dh={};Me(Dh,{ClaudeCodeAdapter:()=>Nh});import{readFileSync as _u,writeFileSync as ME,existsSync as jE,readdirSync as Xz,chmodSync as Yz,accessSync as Qz,mkdirSync as e1,constants as t1}from"node:fs";import{resolve as xu,join as _r}from"node:path";import{homedir as LE}from"node:os";var Nh,Mh=J(()=>{"use strict";Rh();rt();po();OE();Un();DE();Nh=class extends gs{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 Dt()}getSessionDir(){let e=lt(),n=e?_r(e,"context-mode","sessions"):_r(this.getConfigDir(),"context-mode","sessions");return e1(n,{recursive:!0}),n}getSettingsPath(){return _r(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=Le(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Oh].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=_u(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){ME(this.getSettingsPath(),JSON.stringify(e,null,2)+`
155
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Wt.PRE_TOOL_USE);n.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,Wt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(lo).map(([o,s])=>{let i=_r(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>jE(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>$E(e)};return[...n,r]}readPluginHooks(e){let n=[_r(e,"hooks","hooks.json"),_r(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=_u(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Gi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Gi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=_r(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(_u(n,"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(),Dt(),xu(LE(),".claude"),xu(LE(),".config","claude")]));for(let n of e){let r=xu(n,"plugins","cache","context-mode","context-mode");try{let s=Xz(r).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 n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(m=>{let p=m;if(!NE(p))return!0;let h=p.hooks??[];return h.every(y=>!y.command||!Ah(y.command))?!0:h.every(y=>{let _=y.command?Ah(y.command):null;return _?jE(_):!0})}),f=l.length-d.length;f>0&&(r[u]=d,o.push(`Removed ${f} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&AE.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(lo),d=f=>f!=null&&(l.some(m=>f.includes(m))||f.includes("context-mode hook"));for(let f of Object.keys(r)){let m=r[f];if(!Array.isArray(m))continue;let p=0;for(let g of m){let y=g,_=y.hooks??[],x=_.length;y.hooks=_.filter(b=>!d(b.command)),p+=x-y.hooks.length}let h=m.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(p>0||h.length!==m.length)&&(r[f]=h,p>0&&o.push(`Removed ${p} duplicate ${f} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Wt.PRE_TOOL_USE,Wt.SESSION_START];for(let u of c){let l=Ih(u,e);if(u===Wt.PRE_TOOL_USE){let d={matcher:IE,hooks:[{type:"command",command:l}]},f=r.PreToolUse;if(f&&Array.isArray(f)){let m=f.findIndex(p=>Gi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=f}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},f=r[u];if(f&&Array.isArray(f)){let m=f.findIndex(p=>Gi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r[u]=f}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(lo)){let o=xu(e,"hooks",r);try{Qz(o,t1.R_OK),Yz(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=_r(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(_u(r,"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=n,a.lastUpdated=new Date().toISOString();ME(r,JSON.stringify(o,null,2)+`
156
- `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function xr(t,e){let n=bu[t];return e&&n?Le(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var me,zE,bu,PK,RK,HE=J(()=>{"use strict";Un();me={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},zE="mcp__(?!.*context-mode)",bu={[me.BEFORE_AGENT]:"beforeagent.mjs",[me.BEFORE_TOOL]:"beforetool.mjs",[me.AFTER_TOOL]:"aftertool.mjs",[me.AFTER_MODEL]:"aftermodel.mjs",[me.PRE_COMPRESS]:"precompress.mjs",[me.SESSION_START]:"sessionstart.mjs"},PK=[me.BEFORE_TOOL,me.SESSION_START],RK=[me.AFTER_TOOL,me.AFTER_MODEL,me.PRE_COMPRESS]});var BE={};Me(BE,{GeminiCLIAdapter:()=>Lh});import{readFileSync as jh,writeFileSync as UE,mkdirSync as n1,accessSync as r1,chmodSync as o1,existsSync as s1,constants as i1}from"node:fs";import{resolve as Ji,join as FE}from"node:path";import{homedir as Su}from"node:os";var Lh,ZE=J(()=>{"use strict";rt();HE();Lh=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Ji(Su(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[me.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:xr(me.BEFORE_AGENT,e)}]}],[me.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|${zE}`,hooks:[{type:"command",command:xr(me.BEFORE_TOOL,e)}]}],[me.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:xr(me.AFTER_TOOL,e)}]}],[me.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:xr(me.AFTER_MODEL,e)}]}],[me.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:xr(me.PRE_COMPRESS,e)}]}],[me.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:xr(me.SESSION_START,e)}]}]}}readSettings(){try{let e=jh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Ji(Su(),".gemini");n1(n,{recursive:!0}),UE(this.getSettingsPath(),JSON.stringify(e,null,2)+`
157
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[me.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[me.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(bu).map(([n,r])=>{let o=FE(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>s1(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).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=Ji(Su(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(jh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:me.BEFORE_AGENT},{name:me.BEFORE_TOOL},{name:me.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:xr(i.name,e)}]},u=r[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`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=FE(e,"hooks","gemini-cli");for(let o of Object.values(bu)){let s=Ji(r,o);try{r1(s,i1.R_OK),o1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Ji(Su(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(jh(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),UE(r,JSON.stringify(o,null,2)+`
158
- `,"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 dn,a1,Kt,qE,ku=J(()=>{"use strict";dn="@mxalbert/context-mode",a1="context-mode",Kt=`${a1}@${dn}`,qE=`https://registry.npmjs.org/${encodeURIComponent(dn)}/latest`});function Xi(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
154
+ WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch(n){return tt("SessionDB.getSessionIdsForProject",n,this.dbPath),[]}}ensureSession(e,n){this.stmt(D.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(D.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(D.getSessionRollup).get(e),r=this.stmt(D.getMaxFileEdits).get(e),o=this.stmt(D.getLatestCommitMessage).get(e),s=this.getSessionStats(e),i=(n?.tool_calls??0)>0?n?.unique_files??0:0,a=n?.errors??0,c=Math.min(i,a);return{tool_calls:n?.tool_calls??0,errors:n?.errors??0,unique_tools:n?.unique_tools??0,unique_files:n?.unique_files??0,max_file_edits:r?.max_file_edits??0,has_commit:n?.has_commit??0,commit_message:o?.data??"",edit_test_cycles:c,duration_min:n?.duration_min??0,compact_count:s?.compact_count??0,sources_indexed:n?.sources_indexed??0,total_chunks:n?.total_chunks??0,search_queries:n?.search_queries??0}}incrementCompactCount(e){this.stmt(D.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(D.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(D.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(D.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(D.getResume).get(e)??null}markResumeConsumed(e){this.stmt(D.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(D.claimLatestUnconsumedResume).get(e);return n?{sessionId:n.session_id,snapshot:n.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(e){return tt("SessionDB.getLatestSessionId",e,this.dbPath),null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(D.incrementToolCall).run(e,n,o)}catch(s){tt("SessionDB.incrementToolCall",s,this.dbPath)}}getToolCallStats(e){try{let n=this.stmt(D.getToolCallTotals).get(e),r=this.stmt(D.getToolCallByTool).all(e),o={};for(let s of r)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:n?.calls??0,totalBytesReturned:n?.bytes_returned??0,byTool:o}}catch(n){return tt("SessionDB.getToolCallStats",n,this.dbPath),{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(D.deleteEvents).run(e),this.stmt(D.deleteResume).run(e),this.stmt(D.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(D.getOldSessions).all(n);for(let{session_id:o}of r)this.deleteSession(o);return r.length}pruneOrphanedEvents(){let e=this.db.prepare("DELETE FROM session_events WHERE session_id NOT IN (SELECT session_id FROM session_meta)").run();return Number(e.changes??0)}}});import{join as fs,resolve as $E}from"node:path";import{accessSync as Bz,copyFileSync as Zz,constants as qz,mkdirSync as Vz}from"node:fs";import{homedir as Th}from"node:os";function lt(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?$E(Th(),e.replace(/^~[/\\]?/,"")):$E(e)}var ye,rt=J(()=>{"use strict";Tn();ye=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=lt(),n=e?fs(e,"context-mode","sessions"):fs(Th(),...this.sessionDirSegments,"context-mode","sessions");return Vz(n,{recursive:!0}),n}getConfigDir(e){return fs(Th(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=lt(),r=n?fs(n,"context-mode","memory"):fs(this.getConfigDir(),"memory");return e?fs(r,nt(e)):r}backupSettings(){let e=this.getSettingsPath();try{Bz(e,qz.R_OK);let n=e+".bak";return Zz(e,n),n}catch{return null}}}});var ms,Ph=J(()=>{"use strict";rt();ms=class extends ye{parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),e.updatedOutput&&(n.updatedMCPToolOutput=e.updatedOutput),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});import{existsSync as Rh}from"node:fs";import{join as Ch}from"node:path";async function Wz(){if(hs)return hs;if(gs)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 n of t)try{let r=await import(n.href);if(typeof r?.assertPluginCacheIntegrity=="function")return hs=r,hs}catch(r){e=r}return gs=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return gs=t instanceof Error?t.message:String(t),null}}function Kz(t){let e=[];return Rh(Ch(t,"start.mjs"))||e.push("start.mjs"),!Rh(Ch(t,"server.bundle.mjs"))&&!Rh(Ch(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function OE(t){if(hs){let e=hs.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(gs){let e=Kz(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${gs}); the MCP server cannot start. Reinstall: npm install -g @mxalbert/context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${gs}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var hs,gs,IE=J(()=>{"use strict";hs=null,gs=null;Wz()});function Gi(t,e){let n=uo[e],r=Oh(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function Oh(t,e){if(e){let n=uo[t];return ze(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function Ih(t){let e=eu(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function DE(t){let e=Object.values(uo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Wt,Gz,$h,AE,Jz,hK,uo,NE,gK,ME=J(()=>{"use strict";Hn();Wt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},Gz="mcp__",$h=["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",Gz],AE=$h.join("|"),Jz=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],hK=Jz.join("|"),uo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},NE=[Wt.PRE_TOOL_USE,Wt.SESSION_START],gK=[Wt.POST_TOOL_USE,Wt.PRE_COMPACT,Wt.USER_PROMPT_SUBMIT,Wt.STOP]});var Nh={};je(Nh,{ClaudeCodeAdapter:()=>Ah});import{readFileSync as yu,writeFileSync as jE,existsSync as LE,readdirSync as Xz,chmodSync as Yz,accessSync as Qz,mkdirSync as e1,constants as t1}from"node:fs";import{resolve as _u,join as yr}from"node:path";import{homedir as zE}from"node:os";var Ah,Dh=J(()=>{"use strict";Ph();rt();lo();IE();Hn();ME();Ah=class extends ms{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 Dt()}getSessionDir(){let e=lt(),n=e?yr(e,"context-mode","sessions"):yr(this.getConfigDir(),"context-mode","sessions");return e1(n,{recursive:!0}),n}getSettingsPath(){return yr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=ze(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...$h].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=yu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){jE(this.getSettingsPath(),JSON.stringify(e,null,2)+`
155
+ `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"PreToolUse hook",status:"fail",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"}),n;let o=r.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Wt.PRE_TOOL_USE);n.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,Wt.SESSION_START);return n.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),n}getHealthChecks(e){let n=Object.entries(uo).map(([o,s])=>{let i=yr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>LE(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>OE(e)};return[...n,r]}readPluginHooks(e){let n=[yr(e,"hooks","hooks.json"),yr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=yu(r,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,n,r){let o=e?.[r];if(o&&o.length>0&&o.some(i=>Gi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Gi(i,r)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let n=e.enabledPlugins;if(!n)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let r=Object.keys(n).find(o=>o.startsWith("context-mode"));return r&&n[r]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${r}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let n=yr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(yu(n,"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(),Dt(),_u(zE(),".claude"),_u(zE(),".config","claude")]));for(let n of e){let r=_u(n,"plugins","cache","context-mode","context-mode");try{let s=Xz(r).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 n=this.readSettings()??{},r=n.hooks??{},o=[];for(let u of Object.keys(r)){let l=r[u];if(!Array.isArray(l))continue;let d=l.filter(m=>{let p=m;if(!DE(p))return!0;let h=p.hooks??[];return h.every(y=>!y.command||!Ih(y.command))?!0:h.every(y=>{let _=y.command?Ih(y.command):null;return _?LE(_):!0})}),f=l.length-d.length;f>0&&(r[u]=d,o.push(`Removed ${f} stale ${u} hook(s)`))}let a=this.checkPluginRegistration().status==="pass"?this.readPluginHooks(e):void 0;if(a&&NE.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(uo),d=f=>f!=null&&(l.some(m=>f.includes(m))||f.includes("context-mode hook"));for(let f of Object.keys(r)){let m=r[f];if(!Array.isArray(m))continue;let p=0;for(let g of m){let y=g,_=y.hooks??[],x=_.length;y.hooks=_.filter(b=>!d(b.command)),p+=x-y.hooks.length}let h=m.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(p>0||h.length!==m.length)&&(r[f]=h,p>0&&o.push(`Removed ${p} duplicate ${f} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Wt.PRE_TOOL_USE,Wt.SESSION_START];for(let u of c){let l=Oh(u,e);if(u===Wt.PRE_TOOL_USE){let d={matcher:AE,hooks:[{type:"command",command:l}]},f=r.PreToolUse;if(f&&Array.isArray(f)){let m=f.findIndex(p=>Gi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r.PreToolUse=f}else r.PreToolUse=[d],o.push(`Created ${u} hooks section`)}else{let d={matcher:"",hooks:[{type:"command",command:l}]},f=r[u];if(f&&Array.isArray(f)){let m=f.findIndex(p=>Gi(p,u));m>=0?(f[m]=d,o.push(`Updated existing ${u} hook entry`)):(f.push(d),o.push(`Added ${u} hook entry`)),r[u]=f}else r[u]=[d],o.push(`Created ${u} hooks section`)}}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[];for(let[,r]of Object.entries(uo)){let o=_u(e,"hooks",r);try{Qz(o,t1.R_OK),Yz(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=yr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(yu(r,"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=n,a.lastUpdated=new Date().toISOString();jE(r,JSON.stringify(o,null,2)+`
156
+ `,"utf-8")}catch{}}extractSessionId(e){if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return e.session_id?e.session_id:process.env.CLAUDE_SESSION_ID?process.env.CLAUDE_SESSION_ID:`pid-${process.ppid}`}}});function _r(t,e){let n=xu[t];return e&&n?ze(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var me,HE,xu,RK,CK,UE=J(()=>{"use strict";Hn();me={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},HE="mcp__(?!.*context-mode)",xu={[me.BEFORE_AGENT]:"beforeagent.mjs",[me.BEFORE_TOOL]:"beforetool.mjs",[me.AFTER_TOOL]:"aftertool.mjs",[me.AFTER_MODEL]:"aftermodel.mjs",[me.PRE_COMPRESS]:"precompress.mjs",[me.SESSION_START]:"sessionstart.mjs"},RK=[me.BEFORE_TOOL,me.SESSION_START],CK=[me.AFTER_TOOL,me.AFTER_MODEL,me.PRE_COMPRESS]});var ZE={};je(ZE,{GeminiCLIAdapter:()=>jh});import{readFileSync as Mh,writeFileSync as FE,mkdirSync as n1,accessSync as r1,chmodSync as o1,existsSync as s1,constants as i1}from"node:fs";import{resolve as Ji,join as BE}from"node:path";import{homedir as bu}from"node:os";var jh,qE=J(()=>{"use strict";rt();UE();jh=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 Ji(bu(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[me.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:_r(me.BEFORE_AGENT,e)}]}],[me.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|${HE}`,hooks:[{type:"command",command:_r(me.BEFORE_TOOL,e)}]}],[me.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:_r(me.AFTER_TOOL,e)}]}],[me.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:_r(me.AFTER_MODEL,e)}]}],[me.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:_r(me.PRE_COMPRESS,e)}]}],[me.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:_r(me.SESSION_START,e)}]}]}}readSettings(){try{let e=Mh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Ji(bu(),".gemini");n1(n,{recursive:!0}),FE(this.getSettingsPath(),JSON.stringify(e,null,2)+`
157
+ `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),n;let o=r.hooks,s=o?.[me.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[me.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));n.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 n.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return n}getHealthChecks(e){return Object.entries(xu).map(([n,r])=>{let o=BE(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>s1(o)?{status:"OK",detail:o}:{status:"FAIL",detail:`not found at ${o}`}}})}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let n=e.extensions;return n&&(Array.isArray(n)?n.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(n).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=Ji(bu(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(Mh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[],s=[{name:me.BEFORE_AGENT},{name:me.BEFORE_TOOL},{name:me.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:_r(i.name,e)}]},u=r[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`)),r[i.name]=u}else r[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){let n=[],r=BE(e,"hooks","gemini-cli");for(let o of Object.values(xu)){let s=Ji(r,o);try{r1(s,i1.R_OK),o1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Ji(bu(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Mh(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),FE(r,JSON.stringify(o,null,2)+`
158
+ `,"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 dn,a1,Kt,VE,Su=J(()=>{"use strict";dn="@mxalbert/context-mode",a1="context-mode",Kt=`${a1}@${dn}`,VE=`https://registry.npmjs.org/${encodeURIComponent(dn)}/latest`});function Xi(t){let e="",n=!1,r=!1,o=!1;for(let c=0;c<t.length;c++){let u=t[c],l=t[c+1];if(o){u==="*"&&l==="/"&&(o=!1,c++);continue}if(r){e+=u,r=!1;continue}if(u==="\\"){e+=u,r=n;continue}if(u==='"'){n=!n,e+=u;continue}if(!n&&u==="/"&&l==="/"){for(;c<t.length&&t[c]!==`
159
159
  `;)c++;c<t.length&&(e+=`
160
160
  `);continue}if(!n&&u==="/"&&l==="*"){o=!0,c++;continue}e+=u}let s="",i=!1,a=!1;for(let c=0;c<e.length;c++){let u=e[c];if(a){s+=u,a=!1;continue}if(u==="\\"){s+=u,a=i;continue}if(u==='"'){i=!i,s+=u;continue}if(!i&&u===","){let l=c+1;for(;l<e.length&&(e[l]===" "||e[l]===" "||e[l]==="\r"||e[l]===`
161
- `);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function Bn(t){for(let e of[t,Xi(t)])try{return JSON.parse(e)}catch{}}var Yi=J(()=>{"use strict"});var fo,jK,LK,VE=J(()=>{"use strict";fo={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},jK=[fo.BEFORE,fo.AFTER],LK=[fo.COMPACTING]});var XE={};Me(XE,{OpenCodeAdapter:()=>zh,getPluginGlobalState:()=>h1,normalizeProjectKey:()=>GE,peekConfirmedNativeTools:()=>JE});import{readFileSync as WE,writeFileSync as c1,mkdirSync as u1,copyFileSync as l1,accessSync as d1,existsSync as p1,constants as f1,realpathSync as m1}from"node:fs";import{resolve as Ct,join as Zn}from"node:path";import{homedir as br}from"node:os";function Qi(t){return Array.isArray(t)&&t.some(e=>typeof e=="string"&&e.includes("context-mode"))}function h1(){let t=globalThis;return t[vu]||(t[vu]={activations:new Map,loggedOnce:new Set,errorDedupe:new Map}),t[vu]}function GE(t){let e;try{e=m1(t)}catch{e=Ct(t)}return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase():e}function JE(t){let n=globalThis[vu];if(!n)return;let r=n.activations.get(GE(t));return r?r.nativeToolsConfirmed===!0:!1}function KE(t){let e=JE(process.cwd());return e!==void 0?e:Qi(t.plugin)}var vu,zh,YE=J(()=>{"use strict";rt();ku();Yi();VE();vu="__contextModePluginState";zh=class extends ye{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities;platform;constructor(e="opencode",n){super([".config",e]),this.platform=e;let r=n?.sessionContextDegraded!==!0,o=n?.preCompactDegraded!==!0;this.capabilities={preToolUse:!0,postToolUse:!0,preCompact:o,sessionStart:r,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:r}}markCapabilityDegraded(e){e==="sessionStart"?this.capabilities.sessionStart=!1:e==="canInjectSessionContext"?this.capabilities.canInjectSessionContext=!1:this.capabilities.preCompact=!1}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ct(`${this.platform}.jsonc`);return p1(e)?e:Ct(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ct("kilo.jsonc"),Ct("kilo.json"),Ct(".kilo","kilo.jsonc"),Ct(".kilo","kilo.json"),Ct(".kilocode","kilo.jsonc"),Ct(".kilocode","kilo.json"),Zn(br(),".config","kilo","kilo.jsonc"),Zn(br(),".config","kilo","kilo.json")]:[Ct("opencode.jsonc"),Ct("opencode.json"),Ct(".opencode","opencode.jsonc"),Ct(".opencode","opencode.json"),Zn(br(),".config","opencode","opencode.jsonc"),Zn(br(),".config","opencode","opencode.json")]}getSessionDir(){let e=lt(),n=e?Zn(e,"context-mode","sessions"):Zn(this.getConfigDir(),"context-mode","sessions");return u1(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Zn(br(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Zn(br(),".config"),Zn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[fo.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}],[fo.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}],[fo.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(br()))),r=null,o;for(let s of e)try{let i=WE(s,"utf-8"),a=s.endsWith(".jsonc")?Xi(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){c1(this.getSettingsPath(),JSON.stringify(e,null,2)+`
162
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)||Array.isArray(r.plugins)?n.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"}):n.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(r)&&(KE(r)?n.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)"}):n.push({check:"Legacy MCP registration",status:"pass",message:"mcp.context-mode retained as tool fallback: v2 plugin native tool registration unconfirmed"})),this.capabilities.sessionStart?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}):n.push({check:"SessionStart hook",status:"warn",message:"SessionStart surrogate unavailable: session-context hook not confirmed on this host (v2 degraded) \u2014 resume snapshot injection inactive"}),n}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=Ct(br(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(WE(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=Array.isArray(n.plugin),s=Array.isArray(n.plugins);if(o){let c=[...n.plugin];Qi(c)?r.push("context-mode already in plugin array"):(c.push(dn),r.push("Added context-mode to plugin array")),n.plugin=c}if(s){let c=[...n.plugins];Qi(c)?r.push("context-mode already in plugins array"):(c.push(dn),r.push("Added context-mode to plugins array")),n.plugins=c}!o&&!s&&(n.plugin=[dn],r.push("Added context-mode to plugin array"));let i=KE(n),a=n.mcp;if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a;Object.prototype.hasOwnProperty.call(c,"context-mode")&&(i?(delete c["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")):r.push("Kept legacy context-mode MCP block (v2 native tool registration unconfirmed)")),Object.keys(c).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{d1(this.settingsPath,f1.R_OK);let n=this.settingsPath+".bak";return l1(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){return Qi(e.plugin)||Qi(e.plugins)}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var mo,WK,KK,QE=J(()=>{"use strict";mo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},WK=[mo.TOOL_CALL_BEFORE,mo.TOOL_CALL_AFTER],KK=[mo.COMMAND_NEW]});var ew={};Me(ew,{OpenClawAdapter:()=>Bh});import{readFileSync as Hh,writeFileSync as g1,copyFileSync as y1,accessSync as _1,constants as x1}from"node:fs";import{resolve as qn,join as Uh}from"node:path";import{homedir as Fh}from"node:os";var Bh,tw=J(()=>{"use strict";rt();QE();Bh=class extends ye{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 n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return qn("openclaw.json")}getConfigDir(e){return qn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Uh(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[mo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[mo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[mo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[qn("openclaw.json"),qn(".openclaw","openclaw.json"),Uh(Fh(),".openclaw","openclaw.json")];for(let n of e)try{let r=Hh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=qn("openclaw.json");g1(n,JSON.stringify(e,null,2)+`
163
- `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=qn(Fh(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(Hh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=qn("node_modules","context-mode","package.json"),n=JSON.parse(Hh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[qn("openclaw.json"),qn(".openclaw","openclaw.json"),Uh(Fh(),".openclaw","openclaw.json")];for(let n of e)try{_1(n,x1.R_OK);let r=n+".bak";return y1(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}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 nw}from"node:os";import{resolve as Zh}from"node:path";function rw(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Zh(nw(),t.replace(/^~[/\\]?/,"")):Zh(t):Zh(nw(),".codex")}var ow=J(()=>{"use strict"});var pw={};Me(pw,{CodexAdapter:()=>Wh,parseCodexContextModePluginRoot:()=>wu,probeCodexCliVersion:()=>lw});import{execFileSync as uw}from"node:child_process";import{existsSync as b1,readFileSync as xs,writeFileSync as sw,accessSync as S1,copyFileSync as k1,constants as v1,mkdirSync as qh}from"node:fs";import{resolve as Eu,dirname as Vh,join as Vn}from"node:path";import{fileURLToPath as E1}from"node:url";function lw(t=uw){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function wu(t){for(let e of t.split(/\r?\n/)){let n=e.match(new RegExp(`^\\s*${Kt}\\s+installed,\\s+enabled\\s+\\S+\\s+(.+?)\\s*$`));if(n?.[1])return n[1].trim()}return null}function Tu(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
164
- `):null}function dw(t){let e=Tu(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function P1(t){let e=Tu(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function iw(t){let e=Tu(t,`plugins."${Kt}"`);return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function aw(t){return Tu(t,"mcp_servers.context-mode")!==null}function R1(t){if(dw(t))return{text:t,changed:!1};let e=t.includes(`\r
161
+ `);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function Fn(t){for(let e of[t,Xi(t)])try{return JSON.parse(e)}catch{}}var Yi=J(()=>{"use strict"});var po,LK,zK,WE=J(()=>{"use strict";po={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},LK=[po.BEFORE,po.AFTER],zK=[po.COMPACTING]});var YE={};je(YE,{OpenCodeAdapter:()=>Lh,getPluginGlobalState:()=>h1,normalizeProjectKey:()=>JE,peekConfirmedNativeTools:()=>XE});import{readFileSync as KE,writeFileSync as c1,mkdirSync as u1,copyFileSync as l1,accessSync as d1,existsSync as p1,constants as f1,realpathSync as m1}from"node:fs";import{resolve as Ct,join as Bn}from"node:path";import{homedir as xr}from"node:os";function Qi(t){return Array.isArray(t)&&t.some(e=>typeof e=="string"&&e.includes("context-mode"))}function h1(){let t=globalThis;return t[ku]||(t[ku]={activations:new Map,loggedOnce:new Set,errorDedupe:new Map}),t[ku]}function JE(t){let e;try{e=m1(t)}catch{e=Ct(t)}return process.platform==="win32"||process.platform==="darwin"?e.toLowerCase():e}function XE(t){let n=globalThis[ku];if(!n)return;let r=n.activations.get(JE(t));return r?r.nativeToolsConfirmed===!0:!1}function GE(t){let e=XE(process.cwd());return e!==void 0?e:Qi(t.plugin)}var ku,Lh,QE=J(()=>{"use strict";rt();Su();Yi();WE();ku="__contextModePluginState";Lh=class extends ye{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities;platform;constructor(e="opencode",n){super([".config",e]),this.platform=e;let r=n?.sessionContextDegraded!==!0,o=n?.preCompactDegraded!==!0;this.capabilities={preToolUse:!0,postToolUse:!0,preCompact:o,sessionStart:r,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:r}}markCapabilityDegraded(e){e==="sessionStart"?this.capabilities.sessionStart=!1:e==="canInjectSessionContext"?this.capabilities.canInjectSessionContext=!1:this.capabilities.preCompact=!1}parsePreToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool??"",toolInput:n.args??{},toolOutput:n.output,isError:void 0,sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 n={};return e.updatedOutput&&(n.output=e.updatedOutput),e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){if(this.settingsPath)return this.settingsPath;let e=Ct(`${this.platform}.jsonc`);return p1(e)?e:Ct(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ct("kilo.jsonc"),Ct("kilo.json"),Ct(".kilo","kilo.jsonc"),Ct(".kilo","kilo.json"),Ct(".kilocode","kilo.jsonc"),Ct(".kilocode","kilo.json"),Bn(xr(),".config","kilo","kilo.jsonc"),Bn(xr(),".config","kilo","kilo.json")]:[Ct("opencode.jsonc"),Ct("opencode.json"),Ct(".opencode","opencode.jsonc"),Ct(".opencode","opencode.json"),Bn(xr(),".config","opencode","opencode.jsonc"),Bn(xr(),".config","opencode","opencode.json")]}getSessionDir(){let e=lt(),n=e?Bn(e,"context-mode","sessions"):Bn(this.getConfigDir(),"context-mode","sessions");return u1(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Bn(xr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Bn(xr(),".config"),Bn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[po.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}],[po.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}],[po.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:dn}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(xr()))),r=null,o;for(let s of e)try{let i=KE(s,"utf-8"),a=s.endsWith(".jsonc")?Xi(i):i,c=JSON.parse(a);r||(r=c,o=s);let u=n.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return r?(this.settingsPath=o,r):null}writeSettings(e){c1(this.getSettingsPath(),JSON.stringify(e,null,2)+`
162
+ `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:`Could not read ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),n;let o=this.hasContextModePlugin(r);return Array.isArray(r.plugin)||Array.isArray(r.plugins)?n.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"}):n.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(r)&&(GE(r)?n.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)"}):n.push({check:"Legacy MCP registration",status:"pass",message:"mcp.context-mode retained as tool fallback: v2 plugin native tool registration unconfirmed"})),this.capabilities.sessionStart?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}):n.push({check:"SessionStart hook",status:"warn",message:"SessionStart surrogate unavailable: session-context hook not confirmed on this host (v2 degraded) \u2014 resume snapshot injection inactive"}),n}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=Ct(xr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(KE(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=Array.isArray(n.plugin),s=Array.isArray(n.plugins);if(o){let c=[...n.plugin];Qi(c)?r.push("context-mode already in plugin array"):(c.push(dn),r.push("Added context-mode to plugin array")),n.plugin=c}if(s){let c=[...n.plugins];Qi(c)?r.push("context-mode already in plugins array"):(c.push(dn),r.push("Added context-mode to plugins array")),n.plugins=c}!o&&!s&&(n.plugin=[dn],r.push("Added context-mode to plugin array"));let i=GE(n),a=n.mcp;if(a&&typeof a=="object"&&!Array.isArray(a)){let c=a;Object.prototype.hasOwnProperty.call(c,"context-mode")&&(i?(delete c["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")):r.push("Kept legacy context-mode MCP block (v2 native tool registration unconfirmed)")),Object.keys(c).length===0&&delete n.mcp}return this.writeSettings(n),r}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{d1(this.settingsPath,f1.R_OK);let n=this.settingsPath+".bak";return l1(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){return Qi(e.plugin)||Qi(e.plugins)}hasLegacyContextModeMcp(e){let n=e.mcp;return!!(n&&typeof n=="object"&&!Array.isArray(n)&&Object.prototype.hasOwnProperty.call(n,"context-mode"))}extractSessionId(e){return e.sessionID?e.sessionID:`pid-${process.ppid}`}}});var fo,KK,GK,ew=J(()=>{"use strict";fo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},KK=[fo.TOOL_CALL_BEFORE,fo.TOOL_CALL_AFTER],GK=[fo.COMMAND_NEW]});var tw={};je(tw,{OpenClawAdapter:()=>Fh});import{readFileSync as zh,writeFileSync as g1,copyFileSync as y1,accessSync as _1,constants as x1}from"node:fs";import{resolve as Zn,join as Hh}from"node:path";import{homedir as Uh}from"node:os";var Fh,nw=J(()=>{"use strict";rt();ew();Fh=class extends ye{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 n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.toolName??n.tool_name??"",toolInput:n.params??n.tool_input??{},toolOutput:n.output??n.tool_output,isError:n.isError??n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n={};return e.additionalContext&&(n.additionalContext=e.additionalContext),Object.keys(n).length>0?n:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Zn("openclaw.json")}getConfigDir(e){return Zn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return Hh(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[fo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[fo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[fo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Zn("openclaw.json"),Zn(".openclaw","openclaw.json"),Hh(Uh(),".openclaw","openclaw.json")];for(let n of e)try{let r=zh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Zn("openclaw.json");g1(n,JSON.stringify(e,null,2)+`
163
+ `,"utf-8")}validateHooks(e){let n=[],r=this.readSettings();if(!r)return n.push({check:"Plugin configuration",status:"fail",message:"Could not read openclaw.json",fix:"context-mode upgrade"}),n;let o=r.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(n.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;n.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else n.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?n.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):n.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),n}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let r=e.plugins?.entries;return r&&Object.keys(r).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=Zn(Uh(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(zh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Zn("node_modules","context-mode","package.json"),n=JSON.parse(zh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[];n.plugins||(n.plugins={});let o=n.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},r.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,r.push("Enabled context-mode plugin")):r.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&r.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",r.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(n),r}backupSettings(){let e=[Zn("openclaw.json"),Zn(".openclaw","openclaw.json"),Hh(Uh(),".openclaw","openclaw.json")];for(let n of e)try{_1(n,x1.R_OK);let r=n+".bak";return y1(n,r),r}catch{continue}return null}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}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 rw}from"node:os";import{resolve as Bh}from"node:path";function ow(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Bh(rw(),t.replace(/^~[/\\]?/,"")):Bh(t):Bh(rw(),".codex")}var sw=J(()=>{"use strict"});var fw={};je(fw,{CodexAdapter:()=>Vh,parseCodexContextModePluginRoot:()=>Eu,probeCodexCliVersion:()=>dw});import{execFileSync as lw}from"node:child_process";import{existsSync as b1,readFileSync as ys,writeFileSync as iw,accessSync as S1,copyFileSync as k1,constants as v1,mkdirSync as Zh}from"node:fs";import{resolve as vu,dirname as qh,join as qn}from"node:path";import{fileURLToPath as E1}from"node:url";function dw(t=lw){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}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function Eu(t){for(let e of t.split(/\r?\n/)){let n=e.match(new RegExp(`^\\s*${Kt}\\s+installed,\\s+enabled\\s+\\S+\\s+(.+?)\\s*$`));if(n?.[1])return n[1].trim()}return null}function wu(t,e){let n=t.split(/\r?\n/),r=!1,o=[];for(let s of n){let i=s.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(i){if(r)break;r=i[1]?.trim()===e;continue}r&&o.push(s)}return r?o.join(`
164
+ `):null}function pw(t){let e=wu(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function P1(t){let e=wu(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function aw(t){let e=wu(t,`plugins."${Kt}"`);return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function cw(t){return wu(t,"mcp_servers.context-mode")!==null}function R1(t){if(pw(t))return{text:t,changed:!1};let e=t.includes(`\r
165
165
  `)?`\r
166
166
  `:`
167
167
  `,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
168
- `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function cw(t,e){let n=t.includes(`\r
168
+ `)?e:"";return{text:`${t}${s}[features]${e}hooks = true${e}`,changed:!0}}let o=n.length;for(let s=r+1;s<n.length;s++)if(/^\s*\[[^\]]+\]\s*(?:#.*)?$/.test(n[s]??"")){o=s;break}for(let s=r+1;s<o;s++)if(/^\s*hooks\s*=/.test(n[s]??""))return n[s]="hooks = true",{text:n.join(e),changed:!0};return n.splice(r+1,0,"hooks = true"),{text:n.join(e),changed:!0}}function uw(t,e){let n=t.includes(`\r
169
169
  `)?`\r
170
170
  `:`
171
- `,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function C1(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var w1,ho,T1,Wh,Kh=J(()=>{"use strict";rt();ku();Pn();ow();w1="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__",ho={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"},T1={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"]};Wh=class extends ye{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??uw}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 rw()}getSettingsPath(){return Vn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=lt(),n=e?Vn(e,"context-mode","sessions"):Vn(this.getConfigDir(),"context-mode","sessions");return qh(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=lt(),r=n?Vn(n,"context-mode","memories"):Vn(this.getConfigDir(),"memories");return e?Vn(r,nt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:w1,hooks:[{type:"command",command:ho.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:ho.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ho.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ho.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ho.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ho.Stop}]}]}}readSettings(){try{return{_raw_toml:xs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=lw(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=xs(this.getSettingsPath(),"utf-8"),s=!0;let m=dw(o),p=!m&&P1(o);n.push({check:"Codex hooks feature flag",status:m?"pass":"fail",message:m?`[features].hooks enabled in ${this.getSettingsPath()}`:p?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...m?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:`${Kt} is enabled, but \`codex plugin list\` did not report its runtime root`,fix:`Restart Codex or verify \`codex plugin list\` shows ${Kt} installed and enabled`}),c&&!u){let m=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${Vn(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&aw(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:`[mcp_servers.context-mode] is still registered while ${Kt} is enabled; Codex may start both plugin and standalone MCP surfaces`,fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let m=Object.keys(i).map(p=>({check:`${p} hook`,status:"pass",message:`${p} hook provided by ${Kt} plugin`}));return n.concat(m)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by ${Kt} plugin`})):Object.entries(i).map(([m,p])=>{let h=l.config.hooks?.[m],g=p[0],y=Array.isArray(h)&&h.some(x=>this.isExpectedHookEntry(m,x,g)),_=m==="PreCompact"?"warn":"fail";return{check:`${m} hook`,status:y?"pass":_,message:y?`${m} hook configured in ${this.getHooksPath()}`:m==="PreCompact"?`${m} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${m} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),f=[];for(let m of Object.keys(i)){let p=l.config.hooks?.[m];if(!Array.isArray(p))continue;let h=p.filter(g=>this.isManagedContextModeEntry(m,g)).length;h>1?f.push({check:`${m} duplicates`,status:"warn",message:`${h} context-mode entries found for ${m} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&f.push({check:`${m} plugin duplicate`,status:"warn",message:`${m} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,f)}checkPluginRegistration(){try{let e=xs(this.getSettingsPath(),"utf-8"),n=iw(e),r=aw(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:`${Kt} plugin is enabled, but standalone [mcp_servers.context-mode] is also configured`,fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:`${Kt} plugin enabled`}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=xs(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let p=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${p}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let p of Object.keys(l))this.removeManagedHookEntries(u,p,r);else for(let[p,h]of Object.entries(l))this.upsertManagedHookEntry(u,p,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let f=R1(s).text,m=f!==s;if(a){let p=cw(f,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));p.removed.length>0&&(f=p.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(f,u);h.removed.length>0&&(f=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(f!==s){let p=f.includes(`\r
171
+ `,r=t.split(/\r?\n/),o=[],s=[],i=!1;for(let a of r){let c=a.match(/^\s*\[([^\]]+)\]\s*(?:#.*)?$/);if(c){let u=c[1]?.trim()??"";i=e(u),i&&s.push(u)}i||o.push(a)}return{text:o.join(n),removed:s}}function C1(t){let e=t.trim();if(!e.startsWith('"')||!e.endsWith('"'))return null;try{let n=JSON.parse(e);return typeof n=="string"?n:null}catch{let n="",r=!1;for(let o of e.slice(1,-1))r?(n+=o==='"'||o==="\\"?o:`\\${o}`,r=!1):o==="\\"?r=!0:n+=o;return r&&(n+="\\"),n}}var w1,mo,T1,Vh,Wh=J(()=>{"use strict";rt();Su();Tn();sw();w1="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__",mo={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"},T1={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"]};Vh=class extends ye{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??lw}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 ow()}getSettingsPath(){return qn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=lt(),n=e?qn(e,"context-mode","sessions"):qn(this.getConfigDir(),"context-mode","sessions");return Zh(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=lt(),r=n?qn(n,"context-mode","memories"):qn(this.getConfigDir(),"memories");return e?qn(r,nt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:w1,hooks:[{type:"command",command:mo.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:mo.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:mo.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:mo.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:mo.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:mo.Stop}]}]}}readSettings(){try{return{_raw_toml:ys(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=dw(),o="",s=!1;n.push({check:"Codex CLI binary",status:r?"pass":"warn",message:r?`codex --version resolved to ${r}`:"Could not run codex --version; hooks need the Codex CLI available on PATH",...r?{}:{fix:"Install Codex CLI or make codex available on PATH"}});try{o=ys(this.getSettingsPath(),"utf-8"),s=!0;let m=pw(o),p=!m&&P1(o);n.push({check:"Codex hooks feature flag",status:m?"pass":"fail",message:m?`[features].hooks enabled in ${this.getSettingsPath()}`:p?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...m?{}:{fix:"context-mode upgrade"}})}catch{n.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let i=this.generateHookConfig(""),a=this.getCodexPluginHookStatus(e,o,s),c=a.enabled,u=a.hooksAvailable;if(c&&a.runtimeRoot?n.push({check:"Codex plugin root",status:a.rootMismatch?"warn":"pass",message:a.rootMismatch?`context-mode doctor is running from ${a.configuredRoot}, but Codex plugin manager reports ${a.runtimeRoot}`:`Codex plugin manager reports ${a.runtimeRoot}`,...a.rootMismatch?{fix:"Restart Codex after upgrade; run context-mode upgrade to keep native user-hook fallback until the plugin root converges"}:{}}):c&&n.push({check:"Codex plugin root",status:"warn",message:`${Kt} is enabled, but \`codex plugin list\` did not report its runtime root`,fix:`Restart Codex or verify \`codex plugin list\` shows ${Kt} installed and enabled`}),c&&!u){let m=a.runtimeRoot??e;n.push({check:"Codex plugin hooks",status:"fail",message:`context-mode Codex plugin is enabled, but ${qn(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&cw(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:`[mcp_servers.context-mode] is still registered while ${Kt} is enabled; Codex may start both plugin and standalone MCP surfaces`,fix:"context-mode upgrade (removes the standalone Codex MCP registration when the plugin owns context-mode)"});let l=this.readHooksConfig();if(!l.ok){if(l.reason==="missing"&&u){let m=Object.keys(i).map(p=>({check:`${p} hook`,status:"pass",message:`${p} hook provided by ${Kt} plugin`}));return n.concat(m)}return l.reason==="missing"?n.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"}]):l.reason==="invalid_json"?n.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${l.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):n.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${l.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}])}if(!l.config.hooks&&!u)return n.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 d=u?Object.keys(i).map(m=>({check:`${m} hook`,status:"pass",message:`${m} hook provided by ${Kt} plugin`})):Object.entries(i).map(([m,p])=>{let h=l.config.hooks?.[m],g=p[0],y=Array.isArray(h)&&h.some(x=>this.isExpectedHookEntry(m,x,g)),_=m==="PreCompact"?"warn":"fail";return{check:`${m} hook`,status:y?"pass":_,message:y?`${m} hook configured in ${this.getHooksPath()}`:m==="PreCompact"?`${m} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${m} hook missing or not pointing to context-mode`,fix:y?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}),f=[];for(let m of Object.keys(i)){let p=l.config.hooks?.[m];if(!Array.isArray(p))continue;let h=p.filter(g=>this.isManagedContextModeEntry(m,g)).length;h>1?f.push({check:`${m} duplicates`,status:"warn",message:`${h} context-mode entries found for ${m} in ${this.getHooksPath()}; Codex will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"}):u&&h===1&&f.push({check:`${m} plugin duplicate`,status:"warn",message:`${m} is configured in both ${this.getHooksPath()} and the context-mode Codex plugin; Codex will fire both hooks`,fix:"context-mode upgrade (removes user config context-mode hooks; preserves unrelated hooks)"})}return n.concat(d,f)}checkPluginRegistration(){try{let e=ys(this.getSettingsPath(),"utf-8"),n=aw(e),r=cw(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:`${Kt} plugin is enabled, but standalone [mcp_servers.context-mode] is also configured`,fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:`${Kt} plugin enabled`}:r?{check:"MCP registration",status:"pass",message:"context-mode found in [mcp_servers] config"}:o?{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 n=this.readHooksConfig(),r=[],o=this.getSettingsPath(),s="";try{s=ys(o,"utf-8")}catch{s=""}let a=this.getCodexPluginHookStatus(e,s,s.length>0).ownsHooksForUpgrade,c;if(n.ok)c=n.config;else if(n.reason==="missing")c={hooks:{}};else if(n.reason==="invalid_json"){let p=this.backupFile(this.getHooksPath(),".broken");r.push(`Backed up malformed Codex hooks to ${p}`),c={hooks:{}}}else throw new Error(`Failed to update ${this.getHooksPath()}: ${n.error}`);let u=c.hooks&&typeof c.hooks=="object"&&!Array.isArray(c.hooks)?c.hooks:{},l=this.generateHookConfig(e),d=r.length;if(a)for(let p of Object.keys(l))this.removeManagedHookEntries(u,p,r);else for(let[p,h]of Object.entries(l))this.upsertManagedHookEntry(u,p,h[0],r);r.length>d&&(c.hooks=u,this.writeHooksConfig(c),r.push(a?`Removed duplicate context-mode user hooks from ${this.getHooksPath()}`:`Wrote native Codex hooks to ${this.getHooksPath()}`));let f=R1(s).text,m=f!==s;if(a){let p=uw(f,g=>g==="mcp_servers.context-mode"||g.startsWith("mcp_servers.context-mode.tools."));p.removed.length>0&&(f=p.text,r.push("Removed standalone Codex context-mode MCP registration"));let h=this.pruneStaleUserHookTrustState(f,u);h.removed.length>0&&(f=h.text,r.push(`Removed ${h.removed.length} stale Codex hook trust entr${h.removed.length===1?"y":"ies"}`))}if(f!==s){let p=f.includes(`\r
172
172
  `)?`\r
173
173
  `:`
174
174
  `,h=f.endsWith(`
175
- `)?f:`${f}${p}`;qh(Vh(o),{recursive:!0}),sw(o,h,"utf-8"),m&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{S1(n,v1.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Eu(Vh(E1(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return xs(e,"utf-8")}catch{return`# context-mode
175
+ `)?f:`${f}${p}`;Zh(qh(o),{recursive:!0}),iw(o,h,"utf-8"),m&&r.push("Enabled Codex hooks feature flag")}return r}backupSettings(){let e=null;for(let n of[this.getHooksPath(),this.getSettingsPath()])try{S1(n,v1.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=vu(qh(E1(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return ys(e,"utf-8")}catch{return`# context-mode
176
176
 
177
- 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 Vn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return k1(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(xs(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();qh(Vh(n),{recursive:!0}),sw(n,JSON.stringify(e,null,2)+`
178
- `,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return b1(Vn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&iw(n),s=Eu(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return wu(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(Eu(e))===this.normalizeCommand(Eu(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return cw(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=C1(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),f=o[u.pop()??""];if(u.join(":")!==r||!f||!Number.isInteger(d)||!Number.isInteger(l))return!1;let p=n[f]?.[d];return!p||!Array.isArray(p.hooks)||!p.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(ho[e]??""),s=T1[e]??[];return r.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 fw,writeFileSync as $1,mkdirSync as O1,accessSync as I1,chmodSync as A1,constants as N1}from"node:fs";import{resolve as Pu,join as D1}from"node:path";var Sr,Ru=J(()=>{"use strict";rt();Sr=class extends ye{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 Pu(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=fw(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=fw(Pu(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();O1(Pu(".github","hooks"),{recursive:!0}),$1(n,JSON.stringify(e,null,2)+`
179
- `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=D1(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Pu(r,o);try{I1(s,N1.R_OK),A1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function mw(t,e){if(!Gh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Gt,Gh,g6,y6,hw=J(()=>{"use strict";Gt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Gh={[Gt.PRE_TOOL_USE]:"pretooluse.mjs",[Gt.POST_TOOL_USE]:"posttooluse.mjs",[Gt.PRE_COMPACT]:"precompact.mjs",[Gt.SESSION_START]:"sessionstart.mjs"},g6=[Gt.PRE_TOOL_USE,Gt.SESSION_START],y6=[Gt.POST_TOOL_USE,Gt.PRE_COMPACT]});var yw={};Me(yw,{VSCodeCopilotAdapter:()=>Yh});import{readFileSync as Jh,mkdirSync as gw,accessSync as M1,existsSync as j1,constants as L1}from"node:fs";import{resolve as bs,join as ea}from"node:path";import{homedir as Xh}from"node:os";var Yh,_w=J(()=>{"use strict";Ru();rt();hw();Yh=class extends Sr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Gt,HOOK_SCRIPTS:Gh,buildHookCommand:mw};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.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=lt();if(e){let s=ea(e,"context-mode","sessions");return gw(s,{recursive:!0}),s}let n=bs(".github","context-mode","sessions"),r=ea(Xh(),".vscode","context-mode","sessions"),o=j1(bs(".github"))?n:r;return gw(o,{recursive:!0}),o}getConfigDir(e){return bs(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=bs(".github","hooks");try{M1(r,L1.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=bs(r,"context-mode.json");try{let s=Jh(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Gt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Gt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=bs(".vscode","mcp.json"),n=Jh(e,"utf-8"),o=JSON.parse(n).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=[ea(Xh(),".vscode","extensions"),ea(Xh(),".vscode-insiders","extensions")];for(let n of e)try{let r=Jh(ea(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 xw(t,e){if(!Qh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Jt,Qh,w6,T6,bw=J(()=>{"use strict";Jt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Qh={[Jt.PRE_TOOL_USE]:"pretooluse.mjs",[Jt.POST_TOOL_USE]:"posttooluse.mjs",[Jt.PRE_COMPACT]:"precompact.mjs",[Jt.SESSION_START]:"sessionstart.mjs"},w6=[Jt.PRE_TOOL_USE,Jt.SESSION_START],T6=[Jt.POST_TOOL_USE,Jt.PRE_COMPACT]});var Sw={};Me(Sw,{JetBrainsCopilotAdapter:()=>eg});import{readFileSync as z1}from"node:fs";import{resolve as H1}from"node:path";var eg,kw=J(()=>{"use strict";Ru();bw();eg=class extends Sr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Jt,HOOK_SCRIPTS:Qh,buildHookCommand:xw};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 H1(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=z1(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Jt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Jt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function vw(t,e){let n=tg[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var ht,tg,A6,N6,Ew=J(()=>{"use strict";ht={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},tg={[ht.PRE_TOOL_USE]:"pretooluse.mjs",[ht.POST_TOOL_USE]:"posttooluse.mjs",[ht.PRE_COMPACT]:"precompact.mjs",[ht.SESSION_START]:"sessionstart.mjs",[ht.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[ht.STOP]:"stop.mjs"},A6=[ht.PRE_TOOL_USE,ht.SESSION_START],N6=[ht.POST_TOOL_USE,ht.PRE_COMPACT,ht.USER_PROMPT_SUBMIT,ht.STOP]});var $w={};Me($w,{CopilotCliAdapter:()=>rg,copilotCliHome:()=>$u,copilotCliMcpConfigPath:()=>Cu});import{existsSync as ww,mkdirSync as Tw,readFileSync as ng,writeFileSync as U1}from"node:fs";import{homedir as Pw}from"node:os";import{dirname as F1,join as Ss,resolve as Cw}from"node:path";function Rw(){return process.env[B1]==="1"}function Z1(t){return Cw(t,"configs","copilot-cli","hooks.json")}function q1(t){return Bn(ng(t,"utf-8"))??{}}function V1(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function $u(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?Ss(Pw(),t.replace(/^~[/\\]?/,"")):Cw(t):Ss(Pw(),".copilot")}function Cu(){return Ss($u(),"mcp-config.json")}var B1,rg,Ow=J(()=>{"use strict";Ru();rt();Yi();Ew();B1="CONTEXT_MODE_COPILOT_PLUGIN";rg=class extends Sr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:ht,HOOK_SCRIPTS:tg,buildHookCommand:vw};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return Ss($u(),"hooks","context-mode.json")}getConfigDir(e){return $u()}getSessionDir(){let e=lt(),n=e?Ss(e,"context-mode","sessions"):Ss(this.getConfigDir(),"context-mode","sessions");return Tw(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();Tw(F1(n),{recursive:!0}),U1(n,JSON.stringify(e,null,2)+`
180
- `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=ng(this.getSettingsPath(),"utf-8");return Bn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=Rw(),o=r?Z1(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=q1(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(ht)){let l=V1(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(Rw())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=ng(Cu(),"utf-8");return"context-mode"in((Bn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Cu()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return ww(Cu())||ww(this.getSettingsPath())?"standalone":"not installed"}}});function ta(t,e){let n=og[e],r=Xt(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function Xt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,og,W1,K1,sg,Iw,Aw,Nw=J(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},og={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},W1="MCP:(?!ctx_)",K1=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",W1],sg=K1.join("|"),Iw=[_e.PRE_TOOL_USE],Aw=[_e.POST_TOOL_USE]});var zw={};Me(zw,{CursorAdapter:()=>ig});import{readFileSync as Ou,writeFileSync as G1,mkdirSync as J1,accessSync as Dw,chmodSync as X1,constants as Mw,existsSync as jw,readdirSync as Y1}from"node:fs";import{execSync as Q1}from"node:child_process";import{resolve as go,join as yo}from"node:path";import{homedir as Iu}from"node:os";var Lw,ig,Hw=J(()=>{"use strict";rt();po();Nw();Lw="/Library/Application Support/Cursor/hooks.json",ig=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return go(".cursor","hooks.json")}getConfigDir(e){return go(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Xt(_e.PRE_TOOL_USE),matcher:sg,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Xt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Xt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Xt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Xt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=Ou(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();J1(go(".cursor"),{recursive:!0}),G1(n,JSON.stringify(e,null,2)+`
181
- `,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of Iw){let a=s[i],c=Array.isArray(a)&&a.some(u=>ta(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of Aw){let a=s[i],c=Array.isArray(a)&&a.some(u=>ta(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}jw(Lw)&&n.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()&&n.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&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>ta(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.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"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[yo(Iu(),".cursor","plugins","local"),yo(Iu(),".cursor","plugins","cache")],n=[];for(let r of e){try{Dw(r,Mw.F_OK)}catch{continue}let o=[];try{o=Y1(r)}catch{continue}for(let s of o){let i=yo(r,s,".cursor-plugin","plugin.json");try{let a=Ou(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[go(".cursor","mcp.json"),yo(Iu(),".cursor","mcp.json")];for(let r of e)try{let o=Ou(r,"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 ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return Q1("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,_e.PRE_TOOL_USE,{type:"command",command:Xt(_e.PRE_TOOL_USE),matcher:sg,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.POST_TOOL_USE,{type:"command",command:Xt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.SESSION_START,{type:"command",command:Xt(_e.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.STOP,{type:"command",command:Xt(_e.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Xt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=yo(e,"hooks","cursor");for(let o of Object.values(og)){let s=go(r,o);try{Dw(s,Mw.R_OK),X1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),yo(Iu(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Lw),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 n=Ou(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[go(".claude","settings.json"),go(".claude","settings.local.json"),yo(Dt(),"settings.json")].some(n=>jw(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>ta(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var Fw={};Me(Fw,{AntigravityAdapter:()=>na});import{readFileSync as Au,writeFileSync as eH,mkdirSync as tH}from"node:fs";import{resolve as Nu,dirname as Uw}from"node:path";import{fileURLToPath as nH}from"node:url";import{homedir as ag}from"node:os";var na,cg=J(()=>{"use strict";rt();na=class extends ye{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 Nu(ag(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Nu(ag(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Au(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();tH(Uw(n),{recursive:!0}),eH(n,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=Au(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=Nu(ag(),".gemini","extensions","context-mode","package.json");return JSON.parse(Au(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Nu(Uw(nH(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Au(e,"utf-8")}catch{return`# context-mode
177
+ 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 qn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return k1(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(ys(e,"utf-8"))}}catch(n){let r=n instanceof Error?n.message:String(n);return(typeof n=="object"&&n!==null&&"code"in n?String(n.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:n instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:r}:{ok:!1,reason:"read_error",error:r}}}writeHooksConfig(e){let n=this.getHooksPath();Zh(qh(n),{recursive:!0}),iw(n,JSON.stringify(e,null,2)+`
178
+ `,"utf-8")}upsertManagedHookEntry(e,n,r,o){let s=Array.isArray(e[n])?[...e[n]]:[],i=s.map((c,u)=>this.isManagedContextModeEntry(n,c)?u:-1).filter(c=>c>=0);if(i.length===0){s.push(r),e[n]=s,o.push(`Added ${n} hook`);return}let a=i[0];JSON.stringify(s[a])!==JSON.stringify(r)&&(s[a]=r,o.push(`Updated ${n} hook`));for(let c of i.slice(1).reverse())s.splice(c,1),o.push(`Removed duplicate ${n} context-mode hook`);e[n]=s}removeManagedHookEntries(e,n,r){let o=Array.isArray(e[n])?[...e[n]]:[],s=o.filter(a=>!this.isManagedContextModeEntry(n,a)),i=o.length-s.length;i!==0&&(s.length>0?e[n]=s:delete e[n],r.push(`Removed ${i} ${n} context-mode user hook${i===1?"":"s"}`))}hasCodexPluginHookManifest(e){return b1(qn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&aw(n),s=vu(e),i=this.hasCodexPluginHookManifest(s),a=o?this.probeCodexContextModePluginRoot():null,c=a?this.hasCodexPluginHookManifest(a):!1,u=a?!this.samePath(s,a):!1;return{enabled:o,configuredRoot:s,configuredManifestAvailable:i,runtimeRoot:a,runtimeManifestAvailable:c,rootMismatch:u,hooksAvailable:o&&(c||!a&&i),ownsHooksForUpgrade:o&&a!==null&&c&&!u}}probeCodexContextModePluginRoot(){try{let e=process.platform==="win32"?this.codexPluginListRunner("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):this.codexPluginListRunner("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});return Eu(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(vu(e))===this.normalizeCommand(vu(n))}pruneStaleUserHookTrustState(e,n){let r=this.normalizeCommand(this.getHooksPath()),o={post_compact:"PostCompact",post_tool_use:"PostToolUse",pre_compact:"PreCompact",pre_tool_use:"PreToolUse",session_start:"SessionStart",stop:"Stop",user_prompt_submit:"UserPromptSubmit"};return uw(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=C1(s.slice(i.length));if(a===null)return!1;let u=this.normalizeCommand(a).split(":"),l=Number(u.pop()),d=Number(u.pop()),f=o[u.pop()??""];if(u.join(":")!==r||!f||!Number.isInteger(d)||!Number.isInteger(l))return!1;let p=n[f]?.[d];return!p||!Array.isArray(p.hooks)||!p.hooks[l]})}isExpectedHookEntry(e,n,r){return!n||typeof n!="object"||e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}isManagedContextModeEntry(e,n){return!n||typeof n!="object"?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(Array.isArray(n.hooks)?n.hooks:[]).map(i=>this.normalizeCommand(i.command)).filter(i=>i.length>0),o=this.normalizeCommand(mo[e]??""),s=T1[e]??[];return r.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 mw,writeFileSync as $1,mkdirSync as O1,accessSync as I1,chmodSync as A1,constants as N1}from"node:fs";import{resolve as Tu,join as D1}from"node:path";var br,Pu=J(()=>{"use strict";rt();br=class extends ye{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),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 Tu(e??process.cwd(),".github","hooks","context-mode.json")}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule;return{[n.PRE_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_TOOL_USE,e)}]}],[n.POST_TOOL_USE]:[{matcher:"",hooks:[{type:"command",command:r(n.POST_TOOL_USE,e)}]}],[n.PRE_COMPACT]:[{matcher:"",hooks:[{type:"command",command:r(n.PRE_COMPACT,e)}]}],[n.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:r(n.SESSION_START,e)}]}]}}readSettings(){try{let e=mw(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=mw(Tu(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();O1(Tu(".github","hooks"),{recursive:!0}),$1(n,JSON.stringify(e,null,2)+`
179
+ `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.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)}]}],n.push(`Configured ${u} hook`));return r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`),n}setHookPermissions(e){let n=[],r=D1(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=Tu(r,o);try{I1(s,N1.R_OK),A1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function hw(t,e){if(!Kh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Gt,Kh,y6,_6,gw=J(()=>{"use strict";Gt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Kh={[Gt.PRE_TOOL_USE]:"pretooluse.mjs",[Gt.POST_TOOL_USE]:"posttooluse.mjs",[Gt.PRE_COMPACT]:"precompact.mjs",[Gt.SESSION_START]:"sessionstart.mjs"},y6=[Gt.PRE_TOOL_USE,Gt.SESSION_START],_6=[Gt.POST_TOOL_USE,Gt.PRE_COMPACT]});var _w={};je(_w,{VSCodeCopilotAdapter:()=>Xh});import{readFileSync as Gh,mkdirSync as yw,accessSync as M1,existsSync as j1,constants as L1}from"node:fs";import{resolve as _s,join as ea}from"node:path";import{homedir as Jh}from"node:os";var Xh,xw=J(()=>{"use strict";Pu();rt();gw();Xh=class extends br{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Gt,HOOK_SCRIPTS:Kh,buildHookCommand:hw};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.env.VSCODE_CWD||process.cwd()}getSessionDir(){let e=lt();if(e){let s=ea(e,"context-mode","sessions");return yw(s,{recursive:!0}),s}let n=_s(".github","context-mode","sessions"),r=ea(Jh(),".vscode","context-mode","sessions"),o=j1(_s(".github"))?n:r;return yw(o,{recursive:!0}),o}getConfigDir(e){return _s(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=_s(".github","hooks");try{M1(r,L1.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=_s(r,"context-mode.json");try{let s=Gh(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Gt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in context-mode.json",fix:"context-mode upgrade"}),a?.[Gt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"API stability",status:"warn",message:"VS Code Copilot hooks are in preview \u2014 API may change without notice"}),n.push({check:"Matcher support",status:"warn",message:"Matchers are parsed but IGNORED \u2014 all hooks fire on all tools"}),n}checkPluginRegistration(){try{let e=_s(".vscode","mcp.json"),n=Gh(e,"utf-8"),o=JSON.parse(n).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=[ea(Jh(),".vscode","extensions"),ea(Jh(),".vscode-insiders","extensions")];for(let n of e)try{let r=Gh(ea(n,"extensions.json"),"utf-8"),s=JSON.parse(r).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 bw(t,e){if(!Yh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Jt,Yh,T6,P6,Sw=J(()=>{"use strict";Jt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Yh={[Jt.PRE_TOOL_USE]:"pretooluse.mjs",[Jt.POST_TOOL_USE]:"posttooluse.mjs",[Jt.PRE_COMPACT]:"precompact.mjs",[Jt.SESSION_START]:"sessionstart.mjs"},T6=[Jt.PRE_TOOL_USE,Jt.SESSION_START],P6=[Jt.POST_TOOL_USE,Jt.PRE_COMPACT]});var kw={};je(kw,{JetBrainsCopilotAdapter:()=>Qh});import{readFileSync as z1}from"node:fs";import{resolve as H1}from"node:path";var Qh,vw=J(()=>{"use strict";Pu();Sw();Qh=class extends br{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Jt,HOOK_SCRIPTS:Yh,buildHookCommand:bw};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 H1(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=z1(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[Jt.PRE_TOOL_USE]?n.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):n.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Jt.SESSION_START]?n.push({check:"SessionStart hook",status:"pass",message:"SessionStart hook configured in .github/hooks/context-mode.json"}):n.push({check:"SessionStart hook",status:"fail",message:"SessionStart not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"})}catch{n.push({check:"Hook configuration",status:"fail",message:"Could not read .github/hooks/context-mode.json",fix:"context-mode upgrade"})}return n.push({check:"Hook scripts",status:"warn",message:`JetBrains hook wrappers should resolve to ${e}/hooks/jetbrains-copilot/*.mjs`}),n}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 n=this.readSettings()?.hooks;return n&&Object.keys(n).length>0?"configured":"unknown"}}});function Ew(t,e){let n=eg[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var ht,eg,N6,D6,ww=J(()=>{"use strict";ht={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},eg={[ht.PRE_TOOL_USE]:"pretooluse.mjs",[ht.POST_TOOL_USE]:"posttooluse.mjs",[ht.PRE_COMPACT]:"precompact.mjs",[ht.SESSION_START]:"sessionstart.mjs",[ht.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[ht.STOP]:"stop.mjs"},N6=[ht.PRE_TOOL_USE,ht.SESSION_START],D6=[ht.POST_TOOL_USE,ht.PRE_COMPACT,ht.USER_PROMPT_SUBMIT,ht.STOP]});var Ow={};je(Ow,{CopilotCliAdapter:()=>ng,copilotCliHome:()=>Cu,copilotCliMcpConfigPath:()=>Ru});import{existsSync as Tw,mkdirSync as Pw,readFileSync as tg,writeFileSync as U1}from"node:fs";import{homedir as Rw}from"node:os";import{dirname as F1,join as xs,resolve as $w}from"node:path";function Cw(){return process.env[B1]==="1"}function Z1(t){return $w(t,"configs","copilot-cli","hooks.json")}function q1(t){return Fn(tg(t,"utf-8"))??{}}function V1(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function Cu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?xs(Rw(),t.replace(/^~[/\\]?/,"")):$w(t):xs(Rw(),".copilot")}function Ru(){return xs(Cu(),"mcp-config.json")}var B1,ng,Iw=J(()=>{"use strict";Pu();rt();Yi();ww();B1="CONTEXT_MODE_COPILOT_PLUGIN";ng=class extends br{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:ht,HOOK_SCRIPTS:eg,buildHookCommand:Ew};hookSubdir="copilot-cli";extractSessionId(e){let n=e;if(n.transcript_path){let r=n.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(r)return r[1]}return n.conversation_id?n.conversation_id:n.session_id?n.session_id:e.sessionId?e.sessionId:`pid-${process.ppid}`}getProjectDir(){return process.cwd()}parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_result?.text_result_for_llm??n.toolResult?.textResultForLlm??(typeof n.tool_response=="string"?n.tool_response:void 0)??n.tool_output;return{toolName:n.tool_name??n.toolName??"",toolInput:n.tool_input??n.toolArgs??{},toolOutput:r,isError:n.is_error,sessionId:this.extractSessionId(n),projectDir:typeof n.cwd=="string"&&n.cwd?n.cwd:process.cwd(),raw:e}}getSettingsPath(e){return xs(Cu(),"hooks","context-mode.json")}getConfigDir(e){return Cu()}getSessionDir(){let e=lt(),n=e?xs(e,"context-mode","sessions"):xs(this.getConfigDir(),"context-mode","sessions");return Pw(n,{recursive:!0}),n}getInstructionFiles(){return[".github/copilot-instructions.md","AGENTS.md"]}generateHookConfig(e){let{HOOK_TYPES:n,buildHookCommand:r}=this.hookModule,o=i=>[{type:"command",command:r(i,e)}],s={};for(let i of Object.values(n))s[i]=o(i);return s}writeSettings(e){let n=this.getSettingsPath();Pw(F1(n),{recursive:!0}),U1(n,JSON.stringify(e,null,2)+`
180
+ `,"utf-8")}configureAllHooks(e){let n=[],r=this.readSettings()??{},o=r.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule;for(let c of Object.values(s)){if(!i[c])continue;let u=[{type:"command",command:a(c,e)}];JSON.stringify(o[c])!==JSON.stringify(u)&&(o[c]=u,n.push(`Configured ${c} hook`))}return r.version!==1&&n.push("Set hooks schema version to 1"),n.length>0&&(r.version=1,r.hooks=o,this.writeSettings(r),n.push(`Wrote hook config to ${this.getSettingsPath()}`)),n}readSettings(){try{let e=tg(this.getSettingsPath(),"utf-8");return Fn(e)??null}catch{return null}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="ask")return{permissionDecision:"ask",permissionDecisionReason:e.reason??"Action requires user confirmation"};if(e.decision==="modify"&&e.updatedInput)return{modifiedArgs:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext}}formatPostToolUseResponse(e){if(e.updatedOutput)return{modifiedResult:{resultType:"success",textResultForLlm:e.updatedOutput}};if(e.additionalContext)return{additionalContext:e.additionalContext}}formatPreCompactResponse(e){}formatSessionStartResponse(e){return e.context?{additionalContext:e.context}:void 0}validateHooks(e){let n=[],r=Cw(),o=r?Z1(e):this.getSettingsPath(),s=r?`Copilot CLI plugin bundle hooks.json (${o})`:o,i=r?"copilot plugin install mksglu/context-mode:configs/copilot-cli":"context-mode upgrade";try{let a=q1(o),c=a.hooks;n.push({check:"Hooks schema version",status:a.version===1?"pass":"fail",message:a.version===1?`${s} declares the required "version": 1`:`${s} is missing top-level "version": 1`,...a.version===1?{}:{fix:i}});for(let u of Object.values(ht)){let l=V1(c,u);n.push({check:`${u} hook`,status:l?"pass":"fail",message:l?`${u} hook configured in ${s}`:`${u} not found in ${s}`,...l?{}:{fix:i}})}}catch{n.push({check:"Hook configuration",status:"fail",message:`Could not read ${s}`,fix:i})}return n}checkPluginRegistration(){if(Cw())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=tg(Ru(),"utf-8");return"context-mode"in((Fn(e)??{})?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in Copilot CLI mcp-config.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in Copilot CLI mcpServers",fix:"copilot mcp add context-mode -- context-mode"}}catch{return{check:"MCP registration",status:"fail",message:`Could not read ${Ru()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return Tw(Ru())||Tw(this.getSettingsPath())?"standalone":"not installed"}}});function ta(t,e){let n=rg[e],r=Xt(e);if("command"in t){let s=t.command??"";return n!=null&&s.includes(n)||s.includes(r)}return t.hooks?.some(s=>{let i=s.command??"";return n!=null&&i.includes(n)||i.includes(r)})??!1}function Xt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,rg,W1,K1,og,Aw,Nw,Dw=J(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},rg={[_e.PRE_TOOL_USE]:"pretooluse.mjs",[_e.POST_TOOL_USE]:"posttooluse.mjs",[_e.SESSION_START]:"sessionstart.mjs",[_e.STOP]:"stop.mjs",[_e.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},W1="MCP:(?!ctx_)",K1=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",W1],og=K1.join("|"),Aw=[_e.PRE_TOOL_USE],Nw=[_e.POST_TOOL_USE]});var Hw={};je(Hw,{CursorAdapter:()=>sg});import{readFileSync as $u,writeFileSync as G1,mkdirSync as J1,accessSync as Mw,chmodSync as X1,constants as jw,existsSync as Lw,readdirSync as Y1}from"node:fs";import{execSync as Q1}from"node:child_process";import{resolve as ho,join as go}from"node:path";import{homedir as Ou}from"node:os";var zw,sg,Uw=J(()=>{"use strict";rt();lo();Dw();zw="/Library/Application Support/Cursor/hooks.json",sg=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_output??n.error_message,isError:!!n.error_message,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,r=n.source??n.trigger??"startup",o;switch(r){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),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 n=e;return{sessionId:n.conversation_id??`pid-${process.ppid}`,status:n.status??"completed",loopCount:n.loop_count??0,generationId:n.generation_id,transcriptPath:n.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return ho(".cursor","hooks.json")}getConfigDir(e){return ho(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Xt(_e.PRE_TOOL_USE),matcher:og,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Xt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Xt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Xt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Xt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=$u(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();J1(ho(".cursor"),{recursive:!0}),G1(n,JSON.stringify(e,null,2)+`
181
+ `,"utf-8")}validateHooks(e){let n=[],r=this.loadNativeHookConfig();if(!r)n.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=r.config.hooks??{};n.push({check:"Native hook config",status:"pass",message:`Loaded ${r.path}`});for(let i of Aw){let a=s[i],c=Array.isArray(a)&&a.some(u=>ta(u,i));n.push({check:i,status:c?"pass":"fail",message:c?`${i} hook configured`:`${i} hook not configured in ${r.path}`,fix:c?void 0:"context-mode upgrade"})}for(let i of Nw){let a=s[i],c=Array.isArray(a)&&a.some(u=>ta(u,i));n.push({check:i,status:c?"pass":"warn",message:c?`${i} hook configured`:`${i} hook missing \u2014 session event capture will be reduced`})}}Lw(zw)&&n.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()&&n.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&&((r?Object.entries(r.config.hooks??{}).some(([i,a])=>Array.isArray(a)&&a.some(c=>ta(c,i))):!1)&&r?n.push({check:"Plugin/native hook duplication",status:"warn",message:`context-mode plugin detected at ${o[0]} alongside native hooks in ${r.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"}):n.push({check:"Plugin install",status:"pass",message:`context-mode plugin installed at ${o[0]}`})),n}detectPluginInstalls(){let e=[go(Ou(),".cursor","plugins","local"),go(Ou(),".cursor","plugins","cache")],n=[];for(let r of e){try{Mw(r,jw.F_OK)}catch{continue}let o=[];try{o=Y1(r)}catch{continue}for(let s of o){let i=go(r,s,".cursor-plugin","plugin.json");try{let a=$u(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[ho(".cursor","mcp.json"),go(Ou(),".cursor","mcp.json")];for(let r of e)try{let o=$u(r,"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 ${r}`}}catch{continue}let n=this.detectPluginInstalls();return n.length>0?{check:"MCP registration",status:"pass",message:`context-mode registered via plugin manifest at ${n[0]}`}:{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return Q1("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=this.readSettings()??{version:1,hooks:{}},r=n.hooks??{},o=[];return this.upsertHookEntry(r,_e.PRE_TOOL_USE,{type:"command",command:Xt(_e.PRE_TOOL_USE),matcher:og,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.POST_TOOL_USE,{type:"command",command:Xt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.SESSION_START,{type:"command",command:Xt(_e.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.STOP,{type:"command",command:Xt(_e.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Xt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),n.version=1,n.hooks=r,this.writeSettings(n),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let n=[],r=go(e,"hooks","cursor");for(let o of Object.values(rg)){let s=ho(r,o);try{Mw(s,jw.R_OK),X1(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),go(Ou(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(zw),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 n=$u(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[ho(".claude","settings.json"),ho(".claude","settings.local.json"),go(Dt(),"settings.json")].some(n=>Lw(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>ta(c,n));a>=0?(i[a]=r,o.push(`Updated existing ${n} hook entry`)):(i.push(r),o.push(`Added ${n} hook entry`)),e[n]=i}}});var Bw={};je(Bw,{AntigravityAdapter:()=>na});import{readFileSync as Iu,writeFileSync as eH,mkdirSync as tH}from"node:fs";import{resolve as Au,dirname as Fw}from"node:path";import{fileURLToPath as nH}from"node:url";import{homedir as ig}from"node:os";var na,ag=J(()=>{"use strict";rt();na=class extends ye{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 Au(ig(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Au(ig(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Iu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();tH(Fw(n),{recursive:!0}),eH(n,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=Iu(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=Au(ig(),".gemini","extensions","context-mode","package.json");return JSON.parse(Iu(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=Au(Fw(nH(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Iu(e,"utf-8")}catch{return`# context-mode
182
182
 
183
- 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 Xw={};Me(Xw,{AntigravityCliAdapter:()=>mg,antigravityCliConfigDir:()=>Gw,antigravityCliHooksPath:()=>lg,antigravityCliMcpConfigPath:()=>Kw,antigravityCliPluginDir:()=>ju});import{mkdirSync as rH,readFileSync as Du,writeFileSync as oH}from"node:fs";import{dirname as sH,resolve as _o}from"node:path";import{homedir as Mu}from"node:os";function Kw(){return _o(Mu(),".gemini","config","mcp_config.json")}function Gw(){return _o(Mu(),".gemini","antigravity-cli")}function lg(){return _o(Mu(),".gemini","config","hooks.json")}function ju(){return _o(Mu(),".gemini","config","plugins","context-mode")}function iH(){return _o(ju(),"mcp_config.json")}function aH(){return _o(ju(),"hooks.json")}function Bw(t){for(let e of t)try{if("context-mode"in((Bn(Du(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function Rn(t){return t&&typeof t=="object"?t:{}}function Zw(t){let e=Rn(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function qw(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function Jw(t,e){let n=Rn(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>Rn(o).command===e)}function Vw(t,e){return JSON.stringify(t).includes(e)}function cH(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function Ww(t,e){return Array.isArray(t)&&t.some(n=>Jw(n,e))}function uH(t){return Array.isArray(t)&&t.some(e=>{let n=Rn(e);return cH(n.matcher)&&Jw(e,dg)})}function lH(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Bn(Du(n,"utf-8"))??{}).hooks??{},s=uH(o.PreToolUse),i=Ww(o.PostToolUse,pg),a=Ww(o.Stop,fg);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function pH(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function ug(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!Vw(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!Vw(a,r)),n],!0)}var dg,dH,pg,fg,mg,Yw=J(()=>{"use strict";cg();Yi();dg="context-mode hook antigravity-cli pretooluse",dH="run_command|view_file|grep_search|web_fetch|read_url_content",pg="context-mode hook antigravity-cli posttooluse",fg="context-mode hook antigravity-cli stop";mg=class extends na{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return Kw()}getConfigDir(e){return Gw()}parsePreToolUseInput(e){let n=Rn(e),r=Rn(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:Rn(r.args),sessionId:qw(n),projectDir:Zw(n),raw:e}}parsePostToolUseInput(e){let n=Rn(e),r=Rn(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:Rn(r.args),toolOutput:o,isError:o.length>0,sessionId:qw(n),projectDir:Zw(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:pH(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=Bw([iH(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=Bn(Du(_o(ju(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return Bw([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=lg(),o={};try{o=Bn(Du(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:dH,hooks:[{type:"command",command:dg}]},a={matcher:"",hooks:[{type:"command",command:pg}]},c={matcher:"",hooks:[{type:"command",command:fg}]},u=ug(s,"PreToolUse",i,dg),l=ug(s,"PostToolUse",a,pg),d=ug(s,"Stop",c,fg);return(u||l||d)&&(o.hooks=s,rH(sH(r),{recursive:!0}),oH(r,JSON.stringify(o,null,2)+`
184
- `,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=lH([aH(),lg()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function Lu(t,e){let n=Qw[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ks(t,e){let n=Qw[t];return e&&n?Le(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,Qw,fH,mH,hg,c3,u3,eT=J(()=>{"use strict";Un();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Qw={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},fH="@(?!context-mode/)",mH=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",fH],hg=mH.join("|"),c3=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],u3=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var oT={};Me(oT,{KiroAdapter:()=>gg});import{readFileSync as vs,writeFileSync as tT,mkdirSync as nT}from"node:fs";import{resolve as xo,dirname as rT}from"node:path";import{fileURLToPath as hH}from"node:url";import{homedir as zu}from"node:os";var gg,sT=J(()=>{"use strict";rt();eT();gg=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.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 xo(zu(),".kiro","settings","mcp.json")}getConfigDir(e){return xo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:hg,hooks:[{type:"command",command:ks(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ks(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ks(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ks(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=vs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();nT(rT(n),{recursive:!0}),tT(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=xo(zu(),".kiro","agents","default.json");try{let s=JSON.parse(vs(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Lu(u,i));n.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[Ie.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>Lu(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=vs(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=xo(zu(),".kiro","extensions","context-mode","package.json");return JSON.parse(vs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=xo(zu(),".kiro","agents"),o=xo(r,"default.json");try{nT(r,{recursive:!0});let s={};try{s=JSON.parse(vs(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,hg],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Lu(d,c))||(l.push({matcher:u,command:ks(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,tT(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=xo(rT(hH(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return vs(e,"utf-8")}catch{return`# context-mode
183
+ 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 Yw={};je(Yw,{AntigravityCliAdapter:()=>fg,antigravityCliConfigDir:()=>Jw,antigravityCliHooksPath:()=>ug,antigravityCliMcpConfigPath:()=>Gw,antigravityCliPluginDir:()=>Mu});import{mkdirSync as rH,readFileSync as Nu,writeFileSync as oH}from"node:fs";import{dirname as sH,resolve as yo}from"node:path";import{homedir as Du}from"node:os";function Gw(){return yo(Du(),".gemini","config","mcp_config.json")}function Jw(){return yo(Du(),".gemini","antigravity-cli")}function ug(){return yo(Du(),".gemini","config","hooks.json")}function Mu(){return yo(Du(),".gemini","config","plugins","context-mode")}function iH(){return yo(Mu(),"mcp_config.json")}function aH(){return yo(Mu(),"hooks.json")}function Zw(t){for(let e of t)try{if("context-mode"in((Fn(Nu(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function Pn(t){return t&&typeof t=="object"?t:{}}function qw(t){let e=Pn(t.workspace);if(typeof e.current_dir=="string"&&e.current_dir)return e.current_dir;let n=t.workspacePaths;return Array.isArray(n)&&n.length>0?String(n[0]):void 0}function Vw(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function Xw(t,e){let n=Pn(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>Pn(o).command===e)}function Ww(t,e){return JSON.stringify(t).includes(e)}function cH(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function Kw(t,e){return Array.isArray(t)&&t.some(n=>Xw(n,e))}function uH(t){return Array.isArray(t)&&t.some(e=>{let n=Pn(e);return cH(n.matcher)&&Xw(e,lg)})}function lH(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(Fn(Nu(n,"utf-8"))??{}).hooks??{},s=uH(o.PreToolUse),i=Kw(o.PostToolUse,dg),a=Kw(o.Stop,pg);(s||i||a)&&!e.where&&(e.where=n),e.preOk||=s,e.postOk||=i,e.stopOk||=a}catch{}return{...e,ok:e.preOk&&e.postOk}}function pH(t){let e=String(t??"").replace(/<\/?context_guidance>/g," ").replace(/<\/?tip>/g," ").replace(/\s+/g," ").trim();return e?`context-mode: use the context-mode MCP tools instead of this native tool. ${e}`:"context-mode: use the context-mode MCP tools instead of this native tool so raw bytes stay out of the conversation."}function cg(t,e,n,r){let o=Array.isArray(t[e])?t[e]:[],s=JSON.stringify(n);return o.some(a=>JSON.stringify(a)===s)&&o.every(a=>!Ww(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!Ww(a,r)),n],!0)}var lg,dH,dg,pg,fg,Qw=J(()=>{"use strict";ag();Yi();lg="context-mode hook antigravity-cli pretooluse",dH="run_command|view_file|grep_search|web_fetch|read_url_content",dg="context-mode hook antigravity-cli posttooluse",pg="context-mode hook antigravity-cli stop";fg=class extends na{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return Gw()}getConfigDir(e){return Jw()}parsePreToolUseInput(e){let n=Pn(e),r=Pn(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:Pn(r.args),sessionId:Vw(n),projectDir:qw(n),raw:e}}parsePostToolUseInput(e){let n=Pn(e),r=Pn(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:Pn(r.args),toolOutput:o,isError:o.length>0,sessionId:Vw(n),projectDir:qw(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{decision:"deny",reason:e.reason??"Denied by context-mode"}:e.decision==="ask"?{decision:"ask",reason:e.reason??"Action requires user confirmation"}:e.decision==="context"&&e.additionalContext?{decision:"deny",reason:pH(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=Zw([iH(),this.getSettingsPath()]);return e?{check:"MCP registration",status:"pass",message:`context-mode found in Antigravity CLI mcpServers (${n})`}:{check:"MCP registration",status:"fail",message:"context-mode not found in Antigravity CLI mcpServers",fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}getInstalledVersion(){try{let e=Fn(Nu(yo(Mu(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return Zw([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=ug(),o={};try{o=Fn(Nu(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:dH,hooks:[{type:"command",command:lg}]},a={matcher:"",hooks:[{type:"command",command:dg}]},c={matcher:"",hooks:[{type:"command",command:pg}]},u=cg(s,"PreToolUse",i,lg),l=cg(s,"PostToolUse",a,dg),d=cg(s,"Stop",c,pg);return(u||l||d)&&(o.hooks=s,rH(sH(r),{recursive:!0}),oH(r,JSON.stringify(o,null,2)+`
184
+ `,"utf-8"),n.push(`Configured Antigravity CLI PreToolUse/PostToolUse hooks and best-effort Stop hook in ${r}`)),n}validateHooks(e){let{ok:n,where:r,preOk:o,postOk:s,stopOk:i}=lH([aH(),ug()]),a=[o?null:"PreToolUse",s?null:"PostToolUse"].filter(Boolean).join(", ");return[{check:"Antigravity CLI hooks",status:n?"pass":"warn",message:n?`PreToolUse guard and PostToolUse capture configured in ${r}${i?"; best-effort Stop hook also configured":""}`:`Antigravity CLI hooks incomplete (${a||"none found"} missing) \u2014 MCP tools still work, but bounded routing enforcement and session capture are degraded. Run \`agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli\` or \`context-mode upgrade\` to repair hooks.`,...n?{}:{fix:"agy plugin install https://github.com/mksglu/context-mode/tree/main/configs/antigravity-cli"}}]}}});function ju(t,e){let n=eT[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function bs(t,e){let n=eT[t];return e&&n?ze(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,eT,fH,mH,mg,u3,l3,tT=J(()=>{"use strict";Hn();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},eT={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},fH="@(?!context-mode/)",mH=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",fH],mg=mH.join("|"),u3=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],l3=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var sT={};je(sT,{KiroAdapter:()=>hg});import{readFileSync as Ss,writeFileSync as nT,mkdirSync as rT}from"node:fs";import{resolve as _o,dirname as oT}from"node:path";import{fileURLToPath as hH}from"node:url";import{homedir as Lu}from"node:os";var hg,iT=J(()=>{"use strict";rt();tT();hg=class extends ye{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 n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let n=e,r=n.tool_response;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:typeof r=="string"?r:JSON.stringify(r??""),sessionId:`pid-${process.ppid}`,projectDir:n.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let n=e??{};return{source:n.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:n.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 _o(Lu(),".kiro","settings","mcp.json")}getConfigDir(e){return _o(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:mg,hooks:[{type:"command",command:bs(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:bs(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:bs(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:bs(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Ss(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();rT(oT(n),{recursive:!0}),nT(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=_o(Lu(),".kiro","agents","default.json");try{let s=JSON.parse(Ss(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>ju(u,i));n.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[Ie.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>ju(u,i));n.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{n.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return n}checkPluginRegistration(){try{let e=Ss(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=_o(Lu(),".kiro","extensions","context-mode","package.json");return JSON.parse(Ss(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=_o(Lu(),".kiro","agents"),o=_o(r,"default.json");try{rT(r,{recursive:!0});let s={};try{s=JSON.parse(Ss(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,mg],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>ju(d,c))||(l.push({matcher:u,command:bs(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,nT(o,JSON.stringify(s,null,2),"utf-8")}catch(s){n.push(`Failed to configure hooks: ${s.message}`)}return n}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=_o(oT(hH(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Ss(e,"utf-8")}catch{return`# context-mode
185
185
 
186
- 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 cT={};Me(cT,{ZedAdapter:()=>_g});import{readFileSync as yg,writeFileSync as gH,mkdirSync as yH}from"node:fs";import{resolve as iT,dirname as aT}from"node:path";import{fileURLToPath as _H}from"node:url";import{homedir as xH}from"node:os";var _g,uT=J(()=>{"use strict";rt();_g=class extends ye{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 iT(xH(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=yg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();yH(aT(n),{recursive:!0}),gH(n,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=yg(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{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,n){}getRoutingInstructions(){let e=iT(aT(_H(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return yg(e,"utf-8")}catch{return`# context-mode
186
+ 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 uT={};je(uT,{ZedAdapter:()=>yg});import{readFileSync as gg,writeFileSync as gH,mkdirSync as yH}from"node:fs";import{resolve as aT,dirname as cT}from"node:path";import{fileURLToPath as _H}from"node:url";import{homedir as xH}from"node:os";var yg,lT=J(()=>{"use strict";rt();yg=class extends ye{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 aT(xH(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=gg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();yH(cT(n),{recursive:!0}),gH(n,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=gg(this.getSettingsPath(),"utf-8"),r=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:r?{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,n){}getRoutingInstructions(){let e=aT(cT(_H(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return gg(e,"utf-8")}catch{return`# context-mode
187
187
 
188
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var xg,lT=J(()=>{"use strict";xg="mcp__(?!.*context-mode)"});var fT={};Me(fT,{QwenCodeAdapter:()=>bg});import{readFileSync as bH,writeFileSync as SH,existsSync as kH}from"node:fs";import{resolve as dT,join as vH}from"node:path";import{homedir as pT}from"node:os";var bg,mT=J(()=>{"use strict";Rh();lT();Un();bg=class extends gs{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 dT(pT(),".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",xg].join("|"),hooks:[{type:"command",command:Le(`${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:Le(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=bH(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){SH(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.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 n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.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 n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[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?kH(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[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",xg].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:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:Le(`${e}/hooks/${a}`)}]},l=r[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`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:dT(vH(pT(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var hT={};Me(hT,{OMPAdapter:()=>vg});import{readFileSync as Sg,writeFileSync as EH,mkdirSync as wH}from"node:fs";import{resolve as kg,dirname as TH}from"node:path";import{homedir as PH}from"node:os";var vg,gT=J(()=>{"use strict";rt();vg=class extends ye{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??kg(PH(),".omp","agent")}getSettingsPath(){return kg(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Sg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();wH(TH(n),{recursive:!0}),EH(n,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=Sg(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=kg(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Sg(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
188
+ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var _g,dT=J(()=>{"use strict";_g="mcp__(?!.*context-mode)"});var mT={};je(mT,{QwenCodeAdapter:()=>xg});import{readFileSync as bH,writeFileSync as SH,existsSync as kH}from"node:fs";import{resolve as pT,join as vH}from"node:path";import{homedir as fT}from"node:os";var xg,hT=J(()=>{"use strict";Ph();dT();Hn();xg=class extends ms{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 pT(fT(),".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",_g].join("|"),hooks:[{type:"command",command:ze(`${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:ze(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ze(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=bH(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){SH(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let n=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit","Stop"]){let i=Array.isArray(o[s])&&o[s].length>0;n.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 n}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let n=e.mcpServers;return Object.keys(n).some(r=>r.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 n=e.hooks;if(!n)return"not installed";let r=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(n))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&r.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=n.hooks??{},o=[];for(let i of Object.keys(r)){let a=r[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?kH(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(r[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",_g].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:""},{name:"Stop",script:"qwen-code/stop.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:ze(`${e}/hooks/${a}`)}]},l=r[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`)),r[i]=l}else r[i]=[u],o.push(`Created ${i} hooks`)}return n.hooks=r,this.writeSettings(n),o}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructionsConfig(){return{instructionsPath:pT(vH(fT(),".qwen","QWEN.md")),targetPath:"QWEN.md",platformName:"Qwen Code"}}extractSessionId(e){if(e.session_id)return e.session_id;if(e.transcript_path){let n=e.transcript_path.match(/([a-f0-9-]{36})\.jsonl$/);if(n)return n[1]}return process.env.QWEN_SESSION_ID?process.env.QWEN_SESSION_ID:`pid-${process.ppid}`}}});var gT={};je(gT,{OMPAdapter:()=>kg});import{readFileSync as bg,writeFileSync as EH,mkdirSync as wH}from"node:fs";import{resolve as Sg,dirname as TH}from"node:path";import{homedir as PH}from"node:os";var kg,yT=J(()=>{"use strict";rt();kg=class extends ye{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??Sg(PH(),".omp","agent")}getSettingsPath(){return Sg(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=bg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();wH(TH(n),{recursive:!0}),EH(n,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=bg(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=Sg(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(bg(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
189
189
 
190
- 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 yT={};Me(yT,{PiAdapter:()=>Pg});import{readFileSync as Eg,writeFileSync as RH,mkdirSync as CH}from"node:fs";import{resolve as wg,dirname as $H}from"node:path";import{homedir as Tg}from"node:os";var Pg,_T=J(()=>{"use strict";rt();Pg=class extends ye{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 wg(Tg(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Eg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();CH($H(n),{recursive:!0}),RH(n,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=wg(Tg(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Eg(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=wg(Tg(),".pi","extensions","context-mode","package.json");return JSON.parse(Eg(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
190
+ 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 _T={};je(_T,{PiAdapter:()=>Tg});import{readFileSync as vg,writeFileSync as RH,mkdirSync as CH}from"node:fs";import{resolve as Eg,dirname as $H}from"node:path";import{homedir as wg}from"node:os";var Tg,xT=J(()=>{"use strict";rt();Tg=class extends ye{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 Eg(wg(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=vg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();CH($H(n),{recursive:!0}),RH(n,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=Eg(wg(),".pi","extensions","context-mode","package.json");try{return JSON.parse(vg(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=Eg(wg(),".pi","extensions","context-mode","package.json");return JSON.parse(vg(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
191
191
 
192
- 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.`}}});import{homedir as xT}from"node:os";import{resolve as Rg,join as U3}from"node:path";function bT(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Rg(xT(),t.replace(/^~[/\\]?/,"")):Rg(t):Rg(xT(),".kimi-code")}var ST=J(()=>{"use strict"});var TT={};Me(TT,{KimiAdapter:()=>$g,probeKimiCliVersion:()=>wT});import{execFileSync as OH}from"node:child_process";import{readFileSync as ra,writeFileSync as IH,accessSync as AH,copyFileSync as NH,constants as DH,mkdirSync as kT}from"node:fs";import{resolve as MH,dirname as vT,join as bo}from"node:path";import{fileURLToPath as jH}from"node:url";function wT(t=OH){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function ET(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function HH(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
193
- `)}function Cg(t){return t.command.includes("context-mode hook kimi")}function UH(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var LH,kr,zH,$g,PT=J(()=>{"use strict";rt();Pn();ST();LH="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",kr={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},zH={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};$g=class extends ye{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}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 bT()}getSettingsPath(){return bo(this.getConfigDir(),"config.toml")}getMcpPath(){return bo(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=lt(),n=e?bo(e,"context-mode","sessions"):bo(this.getConfigDir(),"context-mode","sessions");return kT(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=lt(),r=n?bo(n,"context-mode","memory"):bo(this.getConfigDir(),"memory");return e?bo(r,nt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:LH,hooks:[{type:"command",command:kr.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:kr.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:kr.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:kr.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:kr.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:kr.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:kr.Stop}]}]}}readSettings(){try{return{_raw_toml:ra(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=wT();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=ra(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=ET(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(f=>f.event===a&&this.isExpectedHookEntry(a,f,u)),d=a==="PreCompact"?"warn":"fail";n.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&Cg(u)).length;c>1&&n.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return n}checkPluginRegistration(){try{let e=ra(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=[],r=this.generateHookConfig(""),o="";try{o=ra(this.getSettingsPath(),"utf-8")}catch{o=""}let s=ET(o),i=s.filter(l=>!Cg(l)),a=[];for(let[l,d]of Object.entries(r)){let f=UH(l,d[0]);f&&a.push(f)}let c=s.some(Cg),u=this.rebuildToml(o,i,a);return u!==o&&(kT(vT(this.getSettingsPath()),{recursive:!0}),IH(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{AH(n,DH.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=MH(vT(jH(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return ra(e,"utf-8")}catch{return`# context-mode
192
+ 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.`}}});import{homedir as bT}from"node:os";import{resolve as Pg,join as F3}from"node:path";function ST(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?Pg(bT(),t.replace(/^~[/\\]?/,"")):Pg(t):Pg(bT(),".kimi-code")}var kT=J(()=>{"use strict"});var PT={};je(PT,{KimiAdapter:()=>Cg,probeKimiCliVersion:()=>TT});import{execFileSync as OH}from"node:child_process";import{readFileSync as ra,writeFileSync as IH,accessSync as AH,copyFileSync as NH,constants as DH,mkdirSync as vT}from"node:fs";import{resolve as MH,dirname as ET,join as xo}from"node:path";import{fileURLToPath as jH}from"node:url";function TT(t=OH){try{let e=process.platform==="win32"?t("cmd.exe",["/d","/s","/c","kimi --version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):t("kimi",["--version"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:1500}),n=String(e).trim();return n.length>0?n:"available (version output empty)"}catch{return null}}function wT(t){let e=[],n=t.split(/\r?\n/),r=null;for(let o of n){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(o)){r&&r.event&&r.command&&e.push(r),r={};continue}if(!r)continue;let s=o.match(/^\s*(\w+)\s*=\s*(?:"([^"]*)"|(\d+))\s*(?:#.*)?$/);if(s){let i=s[1],a=s[2],c=s[3];a!==void 0?r[i]=a:c!==void 0&&(r[i]=Number(c))}}return r&&r.event&&r.command&&e.push(r),e}function HH(t){let e=["[[hooks]]"];return e.push(`event = "${t.event}"`),t.matcher&&e.push(`matcher = "${t.matcher}"`),e.push(`command = "${t.command}"`),t.timeout!==void 0&&e.push(`timeout = ${t.timeout}`),e.join(`
193
+ `)}function Rg(t){return t.command.includes("context-mode hook kimi")}function UH(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var LH,Sr,zH,Cg,RT=J(()=>{"use strict";rt();Tn();kT();LH="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Sr={PreToolUse:"context-mode hook kimi pretooluse",PostToolUse:"context-mode hook kimi posttooluse",SessionStart:"context-mode hook kimi sessionstart",SessionEnd:"context-mode hook kimi sessionend",PreCompact:"context-mode hook kimi precompact",UserPromptSubmit:"context-mode hook kimi userpromptsubmit",Stop:"context-mode hook kimi stop"},zH={PreToolUse:["hooks/pretooluse.mjs","hooks/kimi/pretooluse.mjs"],PostToolUse:["hooks/posttooluse.mjs","hooks/kimi/posttooluse.mjs"],SessionStart:["hooks/sessionstart.mjs","hooks/kimi/sessionstart.mjs"],SessionEnd:["hooks/sessionend.mjs","hooks/kimi/sessionend.mjs"],PreCompact:["hooks/precompact.mjs","hooks/kimi/precompact.mjs"],UserPromptSubmit:["hooks/userpromptsubmit.mjs","hooks/kimi/userpromptsubmit.mjs"],Stop:["hooks/stop.mjs","hooks/kimi/stop.mjs"]};Cg=class extends ye{constructor(){super([".kimi-code"])}name="Kimi Code CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePostToolUseInput(e){let n=e;return{toolName:n.tool_name??"",toolInput:n.tool_input??{},toolOutput:n.tool_response,sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parsePreCompactInput(e){let n=e;return{sessionId:this.extractSessionId(n),projectDir:this.getProjectDir(n),raw:e}}parseSessionStartInput(e){let n=e,o=(n.source??"startup")==="resume"?"resume":"startup";return{sessionId:this.extractSessionId(n),source:o,projectDir:this.getProjectDir(n),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:{}}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 ST()}getSettingsPath(){return xo(this.getConfigDir(),"config.toml")}getMcpPath(){return xo(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=lt(),n=e?xo(e,"context-mode","sessions"):xo(this.getConfigDir(),"context-mode","sessions");return vT(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=lt(),r=n?xo(n,"context-mode","memory"):xo(this.getConfigDir(),"memory");return e?xo(r,nt(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:LH,hooks:[{type:"command",command:Sr.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Sr.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Sr.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:Sr.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Sr.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Sr.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Sr.Stop}]}]}}readSettings(){try{return{_raw_toml:ra(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=TT();n.push({check:"Kimi Code CLI binary",status:r?"pass":"warn",message:r?`kimi --version resolved to ${r}`:"Could not run kimi --version; hooks need the Kimi Code CLI available on PATH",...r?{}:{fix:"Install Kimi Code CLI or make kimi available on PATH"}});let o="";try{o=ra(this.getSettingsPath(),"utf-8")}catch{return n.push({check:"Hooks config",status:"fail",message:`No readable ${this.getSettingsPath()} found`,fix:"Run context-mode upgrade to generate the initial config.toml"}),n}let s=wT(o),i=this.generateHookConfig("");for(let[a,c]of Object.entries(i)){let u=c[0],l=s.some(f=>f.event===a&&this.isExpectedHookEntry(a,f,u)),d=a==="PreCompact"?"warn":"fail";n.push({check:`${a} hook`,status:l?"pass":d,message:l?`${a} hook configured in ${this.getSettingsPath()}`:a==="PreCompact"?`${a} hook missing or not pointing to context-mode; compaction snapshots require a Kimi build that emits PreCompact`:`${a} hook missing or not pointing to context-mode`,fix:l?void 0:`Update ${this.getSettingsPath()} to include the managed ${a} [[hooks]] entry`})}for(let a of Object.keys(i)){let c=s.filter(u=>u.event===a&&Rg(u)).length;c>1&&n.push({check:`${a} duplicates`,status:"warn",message:`${c} context-mode entries found for ${a} in ${this.getSettingsPath()}; Kimi will fire all of them`,fix:"context-mode upgrade (collapses duplicate context-mode entries; preserves unrelated hooks)"})}return n}checkPluginRegistration(){try{let e=ra(this.getMcpPath(),"utf-8"),n=JSON.parse(e),r=e.includes("context-mode"),o=n.mcpServers!==void 0||n.mcp_servers!==void 0;return r&&o?{check:"MCP registration",status:"pass",message:"context-mode found in mcp.json"}:o?{check:"MCP registration",status:"fail",message:"mcpServers section exists but context-mode not found",fix:`Add context-mode to mcpServers in ${this.getMcpPath()}`}:{check:"MCP registration",status:"fail",message:"No mcpServers section in mcp.json",fix:`Add mcpServers.context-mode to ${this.getMcpPath()}`}}catch{return{check:"MCP registration",status:"warn",message:`Could not read ${this.getMcpPath()}`}}}getInstalledVersion(){return"standalone"}configureAllHooks(e){let n=[],r=this.generateHookConfig(""),o="";try{o=ra(this.getSettingsPath(),"utf-8")}catch{o=""}let s=wT(o),i=s.filter(l=>!Rg(l)),a=[];for(let[l,d]of Object.entries(r)){let f=UH(l,d[0]);f&&a.push(f)}let c=s.some(Rg),u=this.rebuildToml(o,i,a);return u!==o&&(vT(ET(this.getSettingsPath()),{recursive:!0}),IH(this.getSettingsPath(),u,"utf-8"),c?n.push(`Updated managed Kimi hooks in ${this.getSettingsPath()}`):n.push(`Wrote managed Kimi hooks to ${this.getSettingsPath()}`)),n}backupSettings(){let e=null;for(let n of[this.getSettingsPath(),this.getMcpPath()])try{AH(n,DH.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=MH(ET(jH(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return ra(e,"utf-8")}catch{return`# context-mode
194
194
 
195
- 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.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return NH(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(kr[e]??"").replace(/\\/g,"/"),s=zH[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...n,...r];if(a.length>0)for(let c of a)s.push(HH(c)),s.push("");return s.join(`
196
- `)}}});var Ig={};Me(Ig,{PLATFORM_ENV_VARS:()=>Es,__resetClaudeCodePluginCacheForTests:()=>ZH,__seedClaudeCodePluginCacheMissForTests:()=>qH,detectPlatform:()=>$t,foreignIdentificationEnv:()=>GH,foreignWorkspaceEnv:()=>KH,getAdapter:()=>JH,getEnvVarNames:()=>WH,getSessionDirSegments:()=>oa,workspaceEnvVarsFor:()=>Og});import{existsSync as Ve,readFileSync as FH}from"node:fs";import{resolve as Ae}from"node:path";import{homedir as RT}from"node:os";function BH(){if(So!==null)return So!=="miss"&&So.hasCM;try{let t=Ae(RT(),".claude","plugins","installed_plugins.json"),e=FH(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return So={hasCM:o},o}catch{return So="miss",!1}}function ZH(){So=null}function qH(){So="miss"}function WH(t){return(Es.get(t)??[]).map(e=>e.name)}function Og(t){return(Es.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function KH(t){let e=new Set;for(let[n,r]of Es)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function GH(t){let e=new Set;for(let[n,r]of Es)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function oa(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];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 $t(t){if(t?.name){let s=dE[t.name];if(s)return{platform:s,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of Es)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&BH()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=RT(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Ae(n,s.replace(/^~[/\\]?/,"")):Ae(s):Ae(n,".copilot")})(),o=Ve(Ae(r,"mcp-config.json"))||Ve(Ae(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Ve(Ae(n,".local","bin","agy"))||Ve(Ae(n,".gemini","antigravity-cli"))||Ve(Ae(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Ve(Ae(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ve(Ae(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ve(Ae(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ve(Ae(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ve(Ae(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ve(Ae(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ve(Ae(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ve(Ae(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Ve(Ae(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ve(Ae(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ve(Ae(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ve(Ae(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ve(Ae(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ve(Ae(n,".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 JH(t){let e=t??$t().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Mh(),Dh));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(ZE(),BE));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(YE(),XE));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(tw(),ew));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Kh(),pw));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(_w(),yw));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(kw(),Sw));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(Ow(),$w));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(Hw(),zw));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(cg(),Fw));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(Yw(),Xw));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(sT(),oT));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(uT(),cT));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(mT(),fT));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(gT(),hT));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(_T(),yT));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(PT(),TT));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Mh(),Dh));return new n}}}var So,VH,Es,ws=J(()=>{"use strict";pE();So=null;VH=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]]],Es=new Map(VH)});import{resolve as sa}from"node:path";import{homedir as Ag}from"node:os";function Dt(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?sa(Ag(),e.replace(/^~[/\\]?/,"")):sa(e):sa(Ag(),".claude")}function XH(t=process.env){return sa(Dt(t),"settings.json")}function Ng(t=process.env){let e=[],n=$t();if(n.platform!=="claude-code"){let o=oa(n.platform);o&&o.length>0&&e.push(sa(Ag(),...o,"settings.json"))}let r=XH(t);return e.includes(r)||e.push(r),e}var po=J(()=>{"use strict";ws()});var $={};Me($,{BRAND:()=>v0,DIRTY:()=>wr,EMPTY_PATH:()=>t0,INVALID:()=>Z,NEVER:()=>iR,OK:()=>st,ParseStatus:()=>Ge,Schema:()=>Q,ZodAny:()=>Yn,ZodArray:()=>Dn,ZodBigInt:()=>Pr,ZodBoolean:()=>Rr,ZodBranded:()=>Ds,ZodCatch:()=>zr,ZodDate:()=>Cr,ZodDefault:()=>Lr,ZodDiscriminatedUnion:()=>xa,ZodEffects:()=>Lt,ZodEnum:()=>Mr,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Sa,ZodIntersection:()=>Ar,ZodIssueCode:()=>E,ZodLazy:()=>Nr,ZodLiteral:()=>Dr,ZodMap:()=>$o,ZodNaN:()=>Io,ZodNativeEnum:()=>jr,ZodNever:()=>en,ZodNull:()=>Or,ZodNullable:()=>_n,ZodNumber:()=>Tr,ZodObject:()=>St,ZodOptional:()=>bt,ZodParsedType:()=>A,ZodPipeline:()=>Ms,ZodPromise:()=>Qn,ZodReadonly:()=>Hr,ZodRecord:()=>ba,ZodSchema:()=>Q,ZodSet:()=>Oo,ZodString:()=>Xn,ZodSymbol:()=>Ro,ZodTransformer:()=>Lt,ZodTuple:()=>yn,ZodType:()=>Q,ZodUndefined:()=>$r,ZodUnion:()=>Ir,ZodUnknown:()=>Nn,ZodVoid:()=>Co,addIssueToContext:()=>C,any:()=>I0,array:()=>M0,bigint:()=>P0,boolean:()=>Ry,coerce:()=>sR,custom:()=>wy,date:()=>R0,datetimeRegex:()=>vy,defaultErrorMap:()=>In,discriminatedUnion:()=>z0,effect:()=>X0,enum:()=>K0,function:()=>q0,getErrorMap:()=>wo,getParsedType:()=>gn,instanceof:()=>w0,intersection:()=>H0,isAborted:()=>ya,isAsync:()=>To,isDirty:()=>_a,isValid:()=>Jn,late:()=>E0,lazy:()=>V0,literal:()=>W0,makeIssue:()=>Ns,map:()=>B0,nan:()=>T0,nativeEnum:()=>G0,never:()=>N0,null:()=>O0,nullable:()=>Q0,number:()=>Py,object:()=>bl,objectUtil:()=>yl,oboolean:()=>oR,onumber:()=>rR,optional:()=>Y0,ostring:()=>nR,pipeline:()=>tR,preprocess:()=>eR,promise:()=>J0,quotelessJson:()=>YP,record:()=>F0,set:()=>Z0,setErrorMap:()=>e0,strictObject:()=>j0,string:()=>Ty,symbol:()=>C0,transformer:()=>X0,tuple:()=>U0,undefined:()=>$0,union:()=>L0,unknown:()=>A0,util:()=>oe,void:()=>D0});var oe;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(oe||(oe={}));var yl;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yl||(yl={}));var A=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),gn=t=>{switch(typeof t){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(t)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(t)?A.array:t===null?A.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?A.promise:typeof Map<"u"&&t instanceof Map?A.map:typeof Set<"u"&&t instanceof Set?A.set:typeof Date<"u"&&t instanceof Date?A.date:A.object;default:return A.unknown}};var E=oe.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"]),YP=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}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,oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};xt.create=t=>new xt(t);var QP=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===A.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:oe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,oe.assertNever(t)}return{message:n}},In=QP;var _y=In;function e0(t){_y=t}function wo(){return _y}var Ns=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},t0=[];function C(t,e){let n=wo(),r=Ns({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===In?void 0:In].filter(o=>!!o)});t.common.issues.push(r)}var Ge=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return Z;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Z;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},Z=Object.freeze({status:"aborted"}),wr=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),ya=t=>t.status==="aborted",_a=t=>t.status==="dirty",Jn=t=>t.status==="valid",To=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var jt=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},xy=(t,e)=>{if(Jn(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 n=new xt(t.common.issues);return this._error=n,this._error}}};function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var Q=class{get description(){return this._def.description}_getType(e){return gn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:gn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ge,ctx:{common:e.parent.common,data:e.data,parsedType:gn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(To(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gn(e)},o=this._parseSync({data:e,path:r.path,parent:r});return xy(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Jn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Jn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:gn(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(To(o)?o:Promise.resolve(o));return xy(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Lt({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:n=>this["~validate"](n)}}optional(){return bt.create(this,this._def)}nullable(){return _n.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Dn.create(this)}promise(){return Qn.create(this,this._def)}or(e){return Ir.create([this,e],this._def)}and(e){return Ar.create(this,e,this._def)}transform(e){return new Lt({...X(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Lr({...X(this._def),innerType:this,defaultValue:n,typeName:T.ZodDefault})}brand(){return new Ds({typeName:T.ZodBranded,type:this,...X(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new zr({...X(this._def),innerType:this,catchValue:n,typeName:T.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ms.create(this,e)}readonly(){return Hr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},n0=/^c[^\s-]{8,}$/i,r0=/^[0-9a-z]+$/,o0=/^[0-9A-HJKMNP-TV-Z]{26}$/i,s0=/^[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,i0=/^[a-z0-9_-]{21}$/i,a0=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,c0=/^[-+]?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)?)??$/,u0=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,l0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",_l,d0=/^(?:(?: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])$/,p0=/^(?:(?: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])$/,f0=/^(([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]))$/,m0=/^(([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])$/,h0=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,g0=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Sy="((\\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])))",y0=new RegExp(`^${Sy}$`);function ky(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function _0(t){return new RegExp(`^${ky(t)}$`)}function vy(t){let e=`${Sy}T${ky(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function x0(t,e){return!!((e==="v4"||!e)&&d0.test(t)||(e==="v6"||!e)&&f0.test(t))}function b0(t,e){if(!a0.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function S0(t,e){return!!((e==="v4"||!e)&&p0.test(t)||(e==="v6"||!e)&&m0.test(t))}var Xn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),Z}let r=new Ge,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.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?C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")u0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")_l||(_l=new RegExp(l0,"u")),_l.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")s0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")i0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")n0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")r0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")o0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),C(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.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),C(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?vy(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?y0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_0(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?c0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?x0(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?b0(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?S0(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?h0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?g0.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):oe.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...L.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...L.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...L.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...L.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...L.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...L.errToObj(n)})}nonempty(e){return this.min(1,L.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Xn.create=t=>new Xn({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...X(t)});function k0(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Tr=class t extends Q{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)!==A.number){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),Z}let r,o=new Ge;for(let s of this._def.checks)s.kind==="int"?oe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?k0(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_finite,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&oe.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Tr.create=t=>new Tr({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...X(t)});var Pr=class t extends Q{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)!==A.bigint)return this._getInvalidInput(e);let r,o=new Ge;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),Z}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Pr.create=t=>new Pr({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...X(t)});var Rr=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),Z}return st(e.data)}};Rr.create=t=>new Rr({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...X(t)});var Cr=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),Z}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_date}),Z}let r=new Ge,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):oe.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Cr.create=t=>new Cr({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...X(t)});var Ro=class extends Q{_parse(e){if(this._getType(e)!==A.symbol){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),Z}return st(e.data)}};Ro.create=t=>new Ro({typeName:T.ZodSymbol,...X(t)});var $r=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),Z}return st(e.data)}};$r.create=t=>new $r({typeName:T.ZodUndefined,...X(t)});var Or=class extends Q{_parse(e){if(this._getType(e)!==A.null){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),Z}return st(e.data)}};Or.create=t=>new Or({typeName:T.ZodNull,...X(t)});var Yn=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};Yn.create=t=>new Yn({typeName:T.ZodAny,...X(t)});var Nn=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};Nn.create=t=>new Nn({typeName:T.ZodUnknown,...X(t)});var en=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),Z}};en.create=t=>new en({typeName:T.ZodNever,...X(t)});var Co=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),Z}return st(e.data)}};Co.create=t=>new Co({typeName:T.ZodVoid,...X(t)});var Dn=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==A.array)return C(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),Z;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(C(n,{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}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(C(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(C(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new jt(n,i,n.path,a)))).then(i=>Ge.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new jt(n,i,n.path,a)));return Ge.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:L.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};Dn.create=(t,e)=>new Dn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...X(e)});function Po(t){if(t instanceof St){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=bt.create(Po(r))}return new St({...t._def,shape:()=>e})}else return t instanceof Dn?new Dn({...t._def,type:Po(t.element)}):t instanceof bt?bt.create(Po(t.unwrap())):t instanceof _n?_n.create(Po(t.unwrap())):t instanceof yn?yn.create(t.items.map(e=>Po(e))):t}var St=class t extends Q{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(),n=oe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==A.object){let u=this._getOrReturnCtx(e);return C(u,{code:E.invalid_type,expected:A.object,received:u.parsedType}),Z}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof en&&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 jt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof en){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&&(C(o,{code:E.unrecognized_keys,keys:a}),r.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 jt(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=>Ge.mergeObjectSync(r,u)):Ge.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:L.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,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of oe.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of oe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Po(this)}partial(e){let n={};for(let r of oe.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of oe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof bt;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return Ey(oe.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:en.create(),typeName:T.ZodObject,...X(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:en.create(),typeName:T.ZodObject,...X(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:en.create(),typeName:T.ZodObject,...X(e)});var Ir=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new xt(a.ctx.common.issues));return C(n,{code:E.invalid_union,unionErrors:i}),Z}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new xt(c));return C(n,{code:E.invalid_union,unionErrors:a}),Z}}get options(){return this._def.options}};Ir.create=(t,e)=>new Ir({options:t,typeName:T.ZodUnion,...X(e)});var An=t=>t instanceof Nr?An(t.schema):t instanceof Lt?An(t.innerType()):t instanceof Dr?[t.value]:t instanceof Mr?t.options:t instanceof jr?oe.objectValues(t.enum):t instanceof Lr?An(t._def.innerType):t instanceof $r?[void 0]:t instanceof Or?[null]:t instanceof bt?[void 0,...An(t.unwrap())]:t instanceof _n?[null,...An(t.unwrap())]:t instanceof Ds||t instanceof Hr?An(t.unwrap()):t instanceof zr?An(t._def.innerType):[],xa=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return C(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),Z;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(C(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=An(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:n,optionsMap:o,...X(r)})}};function xl(t,e){let n=gn(t),r=gn(e);if(t===e)return{valid:!0,data:t};if(n===A.object&&r===A.object){let o=oe.objectKeys(e),s=oe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=xl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.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=xl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ar=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ya(s)||ya(i))return Z;let a=xl(s.value,i.value);return a.valid?((_a(s)||_a(i))&&n.dirty(),{status:n.value,value:a.data}):(C(r,{code:E.invalid_intersection_types}),Z)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ar.create=(t,e,n)=>new Ar({left:t,right:e,typeName:T.ZodIntersection,...X(n)});var yn=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.array)return C(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),Z;if(r.data.length<this._def.items.length)return C(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&r.data.length>this._def.items.length&&(C(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new jt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Ge.mergeArray(n,i)):Ge.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};yn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new yn({items:t,typeName:T.ZodTuple,rest:null,...X(e)})};var ba=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return C(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),Z;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new jt(r,a,r.path,a)),value:i._parse(new jt(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ge.mergeObjectAsync(n,o):Ge.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:T.ZodRecord,...X(r)}):new t({keyType:Xn.create(),valueType:e,typeName:T.ZodRecord,...X(n)})}},$o=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.map)return C(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),Z;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new jt(r,a,r.path,[u,"key"])),value:s._parse(new jt(r,c,r.path,[u,"value"]))}));if(r.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 Z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 Z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};$o.create=(t,e,n)=>new $o({valueType:e,keyType:t,typeName:T.ZodMap,...X(n)});var Oo=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.set)return C(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),Z;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(C(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(C(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Z;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new jt(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:L.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Oo.create=(t,e)=>new Oo({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...X(e)});var Sa=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.function)return C(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),Z;function r(a,c){return Ns({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,wo(),In].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return Ns({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,wo(),In].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Qn){let a=this;return st(async function(...c){let u=new xt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(r(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 st(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new xt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new xt([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:yn.create(e).rest(Nn.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,n,r){return new t({args:e||yn.create([]).rest(Nn.create()),returns:n||Nn.create(),typeName:T.ZodFunction,...X(r)})}},Nr=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Nr.create=(t,e)=>new Nr({getter:t,typeName:T.ZodLazy,...X(e)});var Dr=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return C(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Dr.create=(t,e)=>new Dr({value:t,typeName:T.ZodLiteral,...X(e)});function Ey(t,e){return new Mr({values:t,typeName:T.ZodEnum,...X(e)})}var Mr=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{expected:oe.joinValues(r),received:n.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{received:n.data,code:E.invalid_enum_value,options:r}),Z}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Mr.create=Ey;var jr=class extends Q{_parse(e){let n=oe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=oe.objectValues(n);return C(r,{expected:oe.joinValues(o),received:r.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=oe.objectValues(n);return C(r,{received:r.data,code:E.invalid_enum_value,options:o}),Z}return st(e.data)}get enum(){return this._def.values}};jr.create=(t,e)=>new jr({values:t,typeName:T.ZodNativeEnum,...X(e)});var Qn=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.promise&&n.common.async===!1)return C(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),Z;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return st(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Qn.create=(t,e)=>new Qn({type:t,typeName:T.ZodPromise,...X(e)});var Lt=class extends Q{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:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{C(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return Z;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?Z:c.status==="dirty"?wr(c.value):n.value==="dirty"?wr(c.value):c});{if(n.value==="aborted")return Z;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?Z:a.status==="dirty"?wr(a.value):n.value==="dirty"?wr(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Z:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?Z:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Jn(i))return Z;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Jn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):Z);oe.assertNever(o)}};Lt.create=(t,e,n)=>new Lt({schema:t,typeName:T.ZodEffects,effect:e,...X(n)});Lt.createWithPreprocess=(t,e,n)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...X(n)});var bt=class extends Q{_parse(e){return this._getType(e)===A.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:T.ZodOptional,...X(e)});var _n=class extends Q{_parse(e){return this._getType(e)===A.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_n.create=(t,e)=>new _n({innerType:t,typeName:T.ZodNullable,...X(e)});var Lr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var zr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return To(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var Io=class extends Q{_parse(e){if(this._getType(e)!==A.nan){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),Z}return{status:"valid",value:e.data}}};Io.create=t=>new Io({typeName:T.ZodNaN,...X(t)});var v0=Symbol("zod_brand"),Ds=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ms=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Z:s.status==="dirty"?(n.dirty(),wr(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Z:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:T.ZodPipeline})}},Hr=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Jn(o)&&(o.value=Object.freeze(o.value)),o);return To(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Hr.create=(t,e)=>new Hr({innerType:t,typeName:T.ZodReadonly,...X(e)});function by(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function wy(t,e={},n){return t?Yn.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=by(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=by(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Yn.create()}var E0={object:St.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 w0=(t,e={message:`Input not instance of ${t.name}`})=>wy(n=>n instanceof t,e),Ty=Xn.create,Py=Tr.create,T0=Io.create,P0=Pr.create,Ry=Rr.create,R0=Cr.create,C0=Ro.create,$0=$r.create,O0=Or.create,I0=Yn.create,A0=Nn.create,N0=en.create,D0=Co.create,M0=Dn.create,bl=St.create,j0=St.strictCreate,L0=Ir.create,z0=xa.create,H0=Ar.create,U0=yn.create,F0=ba.create,B0=$o.create,Z0=Oo.create,q0=Sa.create,V0=Nr.create,W0=Dr.create,K0=Mr.create,G0=jr.create,J0=Qn.create,X0=Lt.create,Y0=bt.create,Q0=_n.create,eR=Lt.createWithPreprocess,tR=Ms.create,nR=()=>Ty().optional(),rR=()=>Py().optional(),oR=()=>Ry().optional(),sR={string:(t=>Xn.create({...t,coerce:!0})),number:(t=>Tr.create({...t,coerce:!0})),boolean:(t=>Rr.create({...t,coerce:!0})),bigint:(t=>Pr.create({...t,coerce:!0})),date:(t=>Cr.create({...t,coerce:!0}))};var iR=Z;var aR=Object.freeze({status:"aborted"});function k(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Mn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ka={};function It(t){return t&&Object.assign(ka,t),ka}var ie={};Me(ie,{BIGINT_FORMAT_RANGES:()=>$y,Class:()=>kl,NUMBER_FORMAT_RANGES:()=>Cl,aborted:()=>Fr,allowsEval:()=>Tl,assert:()=>pR,assertEqual:()=>cR,assertIs:()=>lR,assertNever:()=>dR,assertNotEqual:()=>uR,assignProp:()=>wl,cached:()=>zs,captureStackTrace:()=>Ea,cleanEnum:()=>wR,cleanRegex:()=>Us,clone:()=>At,createTransparentProxy:()=>_R,defineLazy:()=>be,esc:()=>Ur,escapeRegex:()=>er,extend:()=>SR,finalizeIssue:()=>tn,floatSafeRemainder:()=>El,getElementAtPath:()=>fR,getEnumValues:()=>Ls,getLengthableOrigin:()=>Fs,getParsedType:()=>yR,getSizableOrigin:()=>Oy,isObject:()=>Ao,isPlainObject:()=>No,issue:()=>$l,joinValues:()=>va,jsonStringifyReplacer:()=>vl,merge:()=>kR,normalizeParams:()=>q,nullish:()=>Hs,numKeys:()=>gR,omit:()=>bR,optionalKeys:()=>Rl,partial:()=>vR,pick:()=>xR,prefixIssues:()=>xn,primitiveTypes:()=>Cy,promiseAllObject:()=>mR,propertyKeyTypes:()=>Pl,randomString:()=>hR,required:()=>ER,stringifyPrimitive:()=>wa,unwrapMessage:()=>js});function cR(t){return t}function uR(t){return t}function lR(t){}function dR(t){throw new Error}function pR(t){}function Ls(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function va(t,e="|"){return t.map(n=>wa(n)).join(e)}function vl(t,e){return typeof e=="bigint"?e.toString():e}function zs(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Hs(t){return t==null}function Us(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function El(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function be(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function wl(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function fR(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function mR(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function hR(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Ur(t){return JSON.stringify(t)}var Ea=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ao(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Tl=zs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function No(t){if(Ao(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Ao(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function gR(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var yR=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}`)}},Pl=new Set(["string","number","symbol"]),Cy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function er(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function q(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 _R(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function wa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Rl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Cl={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]},$y={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function xR(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return At(t,{...t._zod.def,shape:n,checks:[]})}function bR(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return At(t,{...t._zod.def,shape:n,checks:[]})}function SR(t,e){if(!No(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return wl(this,"shape",r),r},checks:[]};return At(t,n)}function kR(t,e){return At(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return wl(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function vR(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return At(e,{...e._zod.def,shape:o,checks:[]})}function ER(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return At(e,{...e._zod.def,shape:o,checks:[]})}function Fr(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function xn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function js(t){return typeof t=="string"?t:t?.message}function tn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=js(t.inst?._zod.def?.error?.(t))??js(e?.error?.(t))??js(n.customError?.(t))??js(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function Oy(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function $l(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function wR(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var kl=class{constructor(...e){}};var Iy=(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,vl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ta=k("$ZodError",Iy),Bs=k("$ZodError",Iy,{Parent:Error});function Ol(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function Il(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var Al=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Mn;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tn(c,s,It())));throw Ea(a,o?.callee),a}return i.value},Nl=Al(Bs),Dl=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tn(c,s,It())));throw Ea(a,o?.callee),a}return i.value},Ml=Dl(Bs),jl=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Mn;return s.issues.length?{success:!1,error:new(t??Ta)(s.issues.map(i=>tn(i,o,It())))}:{success:!0,data:s.value}},Br=jl(Bs),Ll=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>tn(i,o,It())))}:{success:!0,data:s.value}},Zr=Ll(Bs);var Ay=/^[cC][^\s-]{8,}$/,Ny=/^[0-9a-z]+$/,Dy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,My=/^[0-9a-vA-V]{20}$/,jy=/^[A-Za-z0-9]{27}$/,Ly=/^[a-zA-Z0-9_-]{21}$/,zy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var Hy=/^([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})$/,zl=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 Uy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var PR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Fy(){return new RegExp(PR,"u")}var By=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Zy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,qy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Vy=/^(([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])$/,Wy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hl=/^[A-Za-z0-9_-]*$/,Ky=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Gy=/^\+(?:[0-9]){6,14}[0-9]$/,Jy="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Xy=new RegExp(`^${Jy}$`);function Yy(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 Qy(t){return new RegExp(`^${Yy(t)}$`)}function e_(t){let e=Yy({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Jy}T(?:${r})$`)}var t_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var n_=/^\d+$/,r_=/^-?\d+(?:\.\d+)?/i,o_=/true|false/i,s_=/null/i;var i_=/^[^A-Z]*$/,a_=/^[^a-z]*$/;var Je=k("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),c_={number:"number",bigint:"bigint",object:"date"},Ul=k("$ZodCheckLessThan",(t,e)=>{Je.init(t,e);let n=c_[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fl=k("$ZodCheckGreaterThan",(t,e)=>{Je.init(t,e);let n=c_[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),u_=k("$ZodCheckMultipleOf",(t,e)=>{Je.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):El(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),l_=k("$ZodCheckNumberFormat",(t,e)=>{Je.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Cl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=n_)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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 d_=k("$ZodCheckMaxLength",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=Fs(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),p_=k("$ZodCheckMinLength",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=Fs(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),f_=k("$ZodCheckLengthEquals",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=Fs(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Zs=k("$ZodCheckStringFormat",(t,e)=>{var n,r;Je.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),m_=k("$ZodCheckRegex",(t,e)=>{Zs.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),h_=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=i_),Zs.init(t,e)}),g_=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=a_),Zs.init(t,e)}),y_=k("$ZodCheckIncludes",(t,e)=>{Je.init(t,e);let n=er(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),__=k("$ZodCheckStartsWith",(t,e)=>{Je.init(t,e);let n=new RegExp(`^${er(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),x_=k("$ZodCheckEndsWith",(t,e)=>{Je.init(t,e);let n=new RegExp(`.*${er(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var b_=k("$ZodCheckOverwrite",(t,e)=>{Je.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Ra=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
195
+ 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.KIMI_PROJECT_DIR??process.cwd()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return NH(e,r),r}isExpectedHookEntry(e,n,r){return e==="PreToolUse"&&n.matcher!==r.matcher?!1:this.entryContainsManagedCommand(e,n)}entryContainsManagedCommand(e,n){let r=(n.command??"").replace(/\\/g,"/"),o=(Sr[e]??"").replace(/\\/g,"/"),s=zH[e]??[];return r.includes(o)||s.some(i=>r.includes(i))}rebuildToml(e,n,r){let o=e.split(/\r?\n/),s=[],i=!1;for(let c of o){if(/^\s*\[\[hooks\]\]\s*(?:#.*)?$/.test(c)){i=!0;continue}if(i){/^\s*\[/.test(c)&&(i=!1,s.push(c));continue}s.push(c)}for(;s.length>0&&s[s.length-1]==="";)s.pop();s.length>0&&s.push("");let a=[...n,...r];if(a.length>0)for(let c of a)s.push(HH(c)),s.push("");return s.join(`
196
+ `)}}});var Og={};je(Og,{PLATFORM_ENV_VARS:()=>ks,__resetClaudeCodePluginCacheForTests:()=>ZH,__seedClaudeCodePluginCacheMissForTests:()=>qH,detectPlatform:()=>$t,foreignIdentificationEnv:()=>GH,foreignWorkspaceEnv:()=>KH,getAdapter:()=>JH,getEnvVarNames:()=>WH,getSessionDirSegments:()=>oa,workspaceEnvVarsFor:()=>$g});import{existsSync as Ve,readFileSync as FH}from"node:fs";import{resolve as Ae}from"node:path";import{homedir as CT}from"node:os";function BH(){if(bo!==null)return bo!=="miss"&&bo.hasCM;try{let t=Ae(CT(),".claude","plugins","installed_plugins.json"),e=FH(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return bo={hasCM:o},o}catch{return bo="miss",!1}}function ZH(){bo=null}function qH(){bo="miss"}function WH(t){return(ks.get(t)??[]).map(e=>e.name)}function $g(t){return(ks.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function KH(t){let e=new Set;for(let[n,r]of ks)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function GH(t){let e=new Set;for(let[n,r]of ks)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function oa(t){switch(t){case"claude-code":return[".claude"];case"gemini-cli":return[".gemini"];case"antigravity":return[".gemini"];case"antigravity-cli":return[".gemini"];case"openclaw":return[".openclaw"];case"codex":return[".codex"];case"cursor":return[".cursor"];case"vscode-copilot":return[".vscode"];case"copilot-cli":return[".copilot"];case"kiro":return[".kiro"];case"pi":return[".pi"];case"omp":return[".omp"];case"qwen-code":return[".qwen"];case"kimi":return[".kimi-code"];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 $t(t){if(t?.name){let s=pE[t.name];if(s)return{platform:s,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","copilot-cli","cursor","antigravity","antigravity-cli","kiro","pi","omp","zed","qwen-code","kimi"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[s,i]of ks)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&BH()?{platform:"claude-code",confidence:"high",reason:"VSCODE_PID set but ~/.claude/plugins/installed_plugins.json lists context-mode (issue #539 fallback)"}:{platform:s,confidence:"high",reason:`${i.filter(a=>a.detect!==!1).map(a=>a.name).join(" or ")} env var set`};let n=CT(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Ae(n,s.replace(/^~[/\\]?/,"")):Ae(s):Ae(n,".copilot")})(),o=Ve(Ae(r,"mcp-config.json"))||Ve(Ae(r,"hooks","context-mode.json"));return process.env.COPILOT_HOME?.trim()&&o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in explicit COPILOT_HOME exists (mcp-config.json or hooks/context-mode.json)"}:Ve(Ae(n,".local","bin","agy"))||Ve(Ae(n,".gemini","antigravity-cli"))||Ve(Ae(n,".gemini","config","mcp_config.json"))?{platform:"antigravity-cli",confidence:"medium",reason:"Antigravity CLI marker exists (~/.local/bin/agy, ~/.gemini/antigravity-cli, or ~/.gemini/config/mcp_config.json)"}:o?{platform:"copilot-cli",confidence:"medium",reason:"context-mode config in Copilot CLI home exists (mcp-config.json or hooks/context-mode.json; honors COPILOT_HOME)"}:Ve(Ae(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ve(Ae(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ve(Ae(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ve(Ae(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ve(Ae(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ve(Ae(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ve(Ae(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ve(Ae(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:Ve(Ae(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ve(Ae(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ve(Ae(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ve(Ae(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ve(Ae(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ve(Ae(n,".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 JH(t){let e=t??$t().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Dh(),Nh));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(qE(),ZE));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(QE(),YE));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(nw(),tw));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Wh(),fw));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(xw(),_w));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(vw(),kw));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(Iw(),Ow));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(Uw(),Hw));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(ag(),Bw));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(Qw(),Yw));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(iT(),sT));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(lT(),uT));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(hT(),mT));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(yT(),gT));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(xT(),_T));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(RT(),PT));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(Dh(),Nh));return new n}}}var bo,VH,ks,vs=J(()=>{"use strict";fE();bo=null;VH=[["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"},{name:"PI_CODING_AGENT",role:"identification"}]]],ks=new Map(VH)});import{resolve as sa}from"node:path";import{homedir as Ig}from"node:os";function Dt(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?sa(Ig(),e.replace(/^~[/\\]?/,"")):sa(e):sa(Ig(),".claude")}function XH(t=process.env){return sa(Dt(t),"settings.json")}function Ag(t=process.env){let e=[],n=$t();if(n.platform!=="claude-code"){let o=oa(n.platform);o&&o.length>0&&e.push(sa(Ig(),...o,"settings.json"))}let r=XH(t);return e.includes(r)||e.push(r),e}var lo=J(()=>{"use strict";vs()});var $={};je($,{BRAND:()=>ER,DIRTY:()=>Er,EMPTY_PATH:()=>nR,INVALID:()=>Z,NEVER:()=>a0,OK:()=>st,ParseStatus:()=>Ge,Schema:()=>Q,ZodAny:()=>Xn,ZodArray:()=>Nn,ZodBigInt:()=>Tr,ZodBoolean:()=>Pr,ZodBranded:()=>Ds,ZodCatch:()=>Lr,ZodDate:()=>Rr,ZodDefault:()=>jr,ZodDiscriminatedUnion:()=>_a,ZodEffects:()=>Lt,ZodEnum:()=>Dr,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>ba,ZodIntersection:()=>Ir,ZodIssueCode:()=>E,ZodLazy:()=>Ar,ZodLiteral:()=>Nr,ZodMap:()=>Ro,ZodNaN:()=>$o,ZodNativeEnum:()=>Mr,ZodNever:()=>en,ZodNull:()=>$r,ZodNullable:()=>yn,ZodNumber:()=>wr,ZodObject:()=>St,ZodOptional:()=>bt,ZodParsedType:()=>A,ZodPipeline:()=>Ms,ZodPromise:()=>Yn,ZodReadonly:()=>zr,ZodRecord:()=>xa,ZodSchema:()=>Q,ZodSet:()=>Co,ZodString:()=>Jn,ZodSymbol:()=>To,ZodTransformer:()=>Lt,ZodTuple:()=>gn,ZodType:()=>Q,ZodUndefined:()=>Cr,ZodUnion:()=>Or,ZodUnknown:()=>An,ZodVoid:()=>Po,addIssueToContext:()=>C,any:()=>AR,array:()=>jR,bigint:()=>RR,boolean:()=>Py,coerce:()=>i0,custom:()=>Ey,date:()=>CR,datetimeRegex:()=>ky,defaultErrorMap:()=>On,discriminatedUnion:()=>HR,effect:()=>YR,enum:()=>GR,function:()=>VR,getErrorMap:()=>vo,getParsedType:()=>hn,instanceof:()=>TR,intersection:()=>UR,isAborted:()=>ga,isAsync:()=>Eo,isDirty:()=>ya,isValid:()=>Gn,late:()=>wR,lazy:()=>WR,literal:()=>KR,makeIssue:()=>Ns,map:()=>ZR,nan:()=>PR,nativeEnum:()=>JR,never:()=>DR,null:()=>IR,nullable:()=>e0,number:()=>Ty,object:()=>bl,objectUtil:()=>yl,oboolean:()=>s0,onumber:()=>o0,optional:()=>QR,ostring:()=>r0,pipeline:()=>n0,preprocess:()=>t0,promise:()=>XR,quotelessJson:()=>QP,record:()=>BR,set:()=>qR,setErrorMap:()=>tR,strictObject:()=>LR,string:()=>wy,symbol:()=>$R,transformer:()=>YR,tuple:()=>FR,undefined:()=>OR,union:()=>zR,unknown:()=>NR,util:()=>oe,void:()=>MR});var oe;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,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 r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(oe||(oe={}));var yl;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(yl||(yl={}));var A=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),hn=t=>{switch(typeof t){case"undefined":return A.undefined;case"string":return A.string;case"number":return Number.isNaN(t)?A.nan:A.number;case"boolean":return A.boolean;case"function":return A.function;case"bigint":return A.bigint;case"symbol":return A.symbol;case"object":return Array.isArray(t)?A.array:t===null?A.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?A.promise:typeof Map<"u"&&t instanceof Map?A.map:typeof Set<"u"&&t instanceof Set?A.set:typeof Date<"u"&&t instanceof Date?A.date:A.object;default:return A.unknown}};var E=oe.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"]),QP=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),r}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,oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};xt.create=t=>new xt(t);var eR=(t,e)=>{let n;switch(t.code){case E.invalid_type:t.received===A.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case E.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,oe.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:n=`Unrecognized key(s) in object: ${oe.joinValues(t.keys,", ")}`;break;case E.invalid_union:n="Invalid input";break;case E.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${oe.joinValues(t.options)}`;break;case E.invalid_enum_value:n=`Invalid enum value. Expected ${oe.joinValues(t.options)}, received '${t.received}'`;break;case E.invalid_arguments:n="Invalid function arguments";break;case E.invalid_return_type:n="Invalid function return type";break;case E.invalid_date:n="Invalid date";break;case E.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:oe.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case E.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case E.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case E.custom:n="Invalid input";break;case E.invalid_intersection_types:n="Intersection results could not be merged";break;case E.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case E.not_finite:n="Number must be finite";break;default:n=e.defaultError,oe.assertNever(t)}return{message:n}},On=eR;var yy=On;function tR(t){yy=t}function vo(){return yy}var Ns=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=r.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},nR=[];function C(t,e){let n=vo(),r=Ns({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===On?void 0:On].filter(o=>!!o)});t.common.issues.push(r)}var Ge=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return Z;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return Z;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},Z=Object.freeze({status:"aborted"}),Er=t=>({status:"dirty",value:t}),st=t=>({status:"valid",value:t}),ga=t=>t.status==="aborted",ya=t=>t.status==="dirty",Gn=t=>t.status==="valid",Eo=t=>typeof Promise<"u"&&t instanceof Promise;var L;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}));var jt=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,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}},_y=(t,e)=>{if(Gn(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 n=new xt(t.common.issues);return this._error=n,this._error}}};function X(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))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??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??n??a.defaultError}},description:o}}var Q=class{get description(){return this._def.description}_getType(e){return hn(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ge,ctx:{common:e.parent.common,data:e.data,parsedType:hn(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(Eo(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)},o=this._parseSync({data:e,path:r.path,parent:r});return _y(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Gn(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Gn(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:hn(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(Eo(o)?o:Promise.resolve(o));return _y(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:E.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new Lt({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:n=>this["~validate"](n)}}optional(){return bt.create(this,this._def)}nullable(){return yn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Nn.create(this)}promise(){return Yn.create(this,this._def)}or(e){return Or.create([this,e],this._def)}and(e){return Ir.create(this,e,this._def)}transform(e){return new Lt({...X(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new jr({...X(this._def),innerType:this,defaultValue:n,typeName:T.ZodDefault})}brand(){return new Ds({typeName:T.ZodBranded,type:this,...X(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Lr({...X(this._def),innerType:this,catchValue:n,typeName:T.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return Ms.create(this,e)}readonly(){return zr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},rR=/^c[^\s-]{8,}$/i,oR=/^[0-9a-z]+$/,sR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,iR=/^[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,aR=/^[a-z0-9_-]{21}$/i,cR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,uR=/^[-+]?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)?)??$/,lR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,dR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",_l,pR=/^(?:(?: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])$/,fR=/^(?:(?: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])$/,mR=/^(([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]))$/,hR=/^(([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])$/,gR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,by="((\\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])))",_R=new RegExp(`^${by}$`);function Sy(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function xR(t){return new RegExp(`^${Sy(t)}$`)}function ky(t){let e=`${by}T${Sy(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function bR(t,e){return!!((e==="v4"||!e)&&pR.test(t)||(e==="v6"||!e)&&mR.test(t))}function SR(t,e){if(!cR.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function kR(t,e){return!!((e==="v4"||!e)&&fR.test(t)||(e==="v6"||!e)&&hR.test(t))}var Jn=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.string,received:s.parsedType}),Z}let r=new Ge,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.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?C(o,{code:E.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&C(o,{code:E.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")lR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"email",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")_l||(_l=new RegExp(dR,"u")),_l.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"emoji",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")iR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"uuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")aR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"nanoid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")rR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")oR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cuid2",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")sR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ulid",code:E.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),C(o,{validation:"url",code:E.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"regex",code:E.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.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),C(o,{code:E.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?ky(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?_R.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?xR(s).test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?uR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?bR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"ip",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?SR(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"jwt",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?kR(e.data,s.version)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"cidr",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?gR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?yR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64url",code:E.invalid_string,message:s.message}),r.dirty()):oe.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:E.invalid_string,...L.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...L.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,...L.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...L.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...L.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...L.errToObj(n)})}nonempty(e){return this.min(1,L.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 n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Jn.create=t=>new Jn({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...X(t)});function vR(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var wr=class t extends Q{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)!==A.number){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.number,received:s.parsedType}),Z}let r,o=new Ge;for(let s of this._def.checks)s.kind==="int"?oe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?vR(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_finite,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&oe.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};wr.create=t=>new wr({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...X(t)});var Tr=class t extends Q{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)!==A.bigint)return this._getInvalidInput(e);let r,o=new Ge;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{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)&&(r=this._getOrReturnCtx(e,r),C(r,{code:E.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):oe.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.bigint,received:n.parsedType}),Z}gte(e,n){return this.setLimit("min",e,!0,L.toString(n))}gt(e,n){return this.setLimit("min",e,!1,L.toString(n))}lte(e,n){return this.setLimit("max",e,!0,L.toString(n))}lt(e,n){return this.setLimit("max",e,!1,L.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Tr.create=t=>new Tr({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...X(t)});var Pr=class extends Q{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.boolean,received:r.parsedType}),Z}return st(e.data)}};Pr.create=t=>new Pr({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...X(t)});var Rr=class t extends Q{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_type,expected:A.date,received:s.parsedType}),Z}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_date}),Z}let r=new Ge,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),C(o,{code:E.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):oe.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};Rr.create=t=>new Rr({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...X(t)});var To=class extends Q{_parse(e){if(this._getType(e)!==A.symbol){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.symbol,received:r.parsedType}),Z}return st(e.data)}};To.create=t=>new To({typeName:T.ZodSymbol,...X(t)});var Cr=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.undefined,received:r.parsedType}),Z}return st(e.data)}};Cr.create=t=>new Cr({typeName:T.ZodUndefined,...X(t)});var $r=class extends Q{_parse(e){if(this._getType(e)!==A.null){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.null,received:r.parsedType}),Z}return st(e.data)}};$r.create=t=>new $r({typeName:T.ZodNull,...X(t)});var Xn=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return st(e.data)}};Xn.create=t=>new Xn({typeName:T.ZodAny,...X(t)});var An=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return st(e.data)}};An.create=t=>new An({typeName:T.ZodUnknown,...X(t)});var en=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),Z}};en.create=t=>new en({typeName:T.ZodNever,...X(t)});var Po=class extends Q{_parse(e){if(this._getType(e)!==A.undefined){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.void,received:r.parsedType}),Z}return st(e.data)}};Po.create=t=>new Po({typeName:T.ZodVoid,...X(t)});var Nn=class t extends Q{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==A.array)return C(n,{code:E.invalid_type,expected:A.array,received:n.parsedType}),Z;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(C(n,{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}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(C(n,{code:E.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(C(n,{code:E.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new jt(n,i,n.path,a)))).then(i=>Ge.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new jt(n,i,n.path,a)));return Ge.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:L.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:L.toString(n)}})}nonempty(e){return this.min(1,e)}};Nn.create=(t,e)=>new Nn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...X(e)});function wo(t){if(t instanceof St){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=bt.create(wo(r))}return new St({...t._def,shape:()=>e})}else return t instanceof Nn?new Nn({...t._def,type:wo(t.element)}):t instanceof bt?bt.create(wo(t.unwrap())):t instanceof yn?yn.create(wo(t.unwrap())):t instanceof gn?gn.create(t.items.map(e=>wo(e))):t}var St=class t extends Q{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(),n=oe.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==A.object){let u=this._getOrReturnCtx(e);return C(u,{code:E.invalid_type,expected:A.object,received:u.parsedType}),Z}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof en&&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 jt(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof en){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&&(C(o,{code:E.unrecognized_keys,keys:a}),r.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 jt(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=>Ge.mergeObjectSync(r,u)):Ge.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:L.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,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of oe.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of oe.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return wo(this)}partial(e){let n={};for(let r of oe.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of oe.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof bt;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return vy(oe.objectKeys(this.shape))}};St.create=(t,e)=>new St({shape:()=>t,unknownKeys:"strip",catchall:en.create(),typeName:T.ZodObject,...X(e)});St.strictCreate=(t,e)=>new St({shape:()=>t,unknownKeys:"strict",catchall:en.create(),typeName:T.ZodObject,...X(e)});St.lazycreate=(t,e)=>new St({shape:t,unknownKeys:"strip",catchall:en.create(),typeName:T.ZodObject,...X(e)});var Or=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=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 n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new xt(a.ctx.common.issues));return C(n,{code:E.invalid_union,unionErrors:i}),Z}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of r){let u={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.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 n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new xt(c));return C(n,{code:E.invalid_union,unionErrors:a}),Z}}get options(){return this._def.options}};Or.create=(t,e)=>new Or({options:t,typeName:T.ZodUnion,...X(e)});var In=t=>t instanceof Ar?In(t.schema):t instanceof Lt?In(t.innerType()):t instanceof Nr?[t.value]:t instanceof Dr?t.options:t instanceof Mr?oe.objectValues(t.enum):t instanceof jr?In(t._def.innerType):t instanceof Cr?[void 0]:t instanceof $r?[null]:t instanceof bt?[void 0,...In(t.unwrap())]:t instanceof yn?[null,...In(t.unwrap())]:t instanceof Ds||t instanceof zr?In(t.unwrap()):t instanceof Lr?In(t._def.innerType):[],_a=class t extends Q{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return C(n,{code:E.invalid_type,expected:A.object,received:n.parsedType}),Z;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(C(n,{code:E.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=In(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:n,optionsMap:o,...X(r)})}};function xl(t,e){let n=hn(t),r=hn(e);if(t===e)return{valid:!0,data:t};if(n===A.object&&r===A.object){let o=oe.objectKeys(e),s=oe.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=xl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(n===A.array&&r===A.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=xl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return n===A.date&&r===A.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ir=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ga(s)||ga(i))return Z;let a=xl(s.value,i.value);return a.valid?((ya(s)||ya(i))&&n.dirty(),{status:n.value,value:a.data}):(C(r,{code:E.invalid_intersection_types}),Z)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ir.create=(t,e,n)=>new Ir({left:t,right:e,typeName:T.ZodIntersection,...X(n)});var gn=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.array)return C(r,{code:E.invalid_type,expected:A.array,received:r.parsedType}),Z;if(r.data.length<this._def.items.length)return C(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&r.data.length>this._def.items.length&&(C(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new jt(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>Ge.mergeArray(n,i)):Ge.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};gn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new gn({items:t,typeName:T.ZodTuple,rest:null,...X(e)})};var xa=class t extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.object)return C(r,{code:E.invalid_type,expected:A.object,received:r.parsedType}),Z;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new jt(r,a,r.path,a)),value:i._parse(new jt(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?Ge.mergeObjectAsync(n,o):Ge.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof Q?new t({keyType:e,valueType:n,typeName:T.ZodRecord,...X(r)}):new t({keyType:Jn.create(),valueType:e,typeName:T.ZodRecord,...X(n)})}},Ro=class extends Q{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.map)return C(r,{code:E.invalid_type,expected:A.map,received:r.parsedType}),Z;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new jt(r,a,r.path,[u,"key"])),value:s._parse(new jt(r,c,r.path,[u,"value"]))}));if(r.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 Z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.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 Z;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Ro.create=(t,e,n)=>new Ro({valueType:e,keyType:t,typeName:T.ZodMap,...X(n)});var Co=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==A.set)return C(r,{code:E.invalid_type,expected:A.set,received:r.parsedType}),Z;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(C(r,{code:E.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(C(r,{code:E.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return Z;l.status==="dirty"&&n.dirty(),u.add(l.value)}return{status:n.value,value:u}}let a=[...r.data.values()].map((c,u)=>s._parse(new jt(r,c,r.path,u)));return r.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:L.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:L.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};Co.create=(t,e)=>new Co({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...X(e)});var ba=class t extends Q{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.function)return C(n,{code:E.invalid_type,expected:A.function,received:n.parsedType}),Z;function r(a,c){return Ns({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vo(),On].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return Ns({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,vo(),On].filter(u=>!!u),issueData:{code:E.invalid_return_type,returnTypeError:c}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof Yn){let a=this;return st(async function(...c){let u=new xt([]),l=await a._def.args.parseAsync(c,s).catch(m=>{throw u.addIssue(r(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 st(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new xt([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new xt([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:gn.create(e).rest(An.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,n,r){return new t({args:e||gn.create([]).rest(An.create()),returns:n||An.create(),typeName:T.ZodFunction,...X(r)})}},Ar=class extends Q{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ar.create=(t,e)=>new Ar({getter:t,typeName:T.ZodLazy,...X(e)});var Nr=class extends Q{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return C(n,{received:n.data,code:E.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Nr.create=(t,e)=>new Nr({value:t,typeName:T.ZodLiteral,...X(e)});function vy(t,e){return new Dr({values:t,typeName:T.ZodEnum,...X(e)})}var Dr=class t extends Q{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{expected:oe.joinValues(r),received:n.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return C(n,{received:n.data,code:E.invalid_enum_value,options:r}),Z}return st(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};Dr.create=vy;var Mr=class extends Q{_parse(e){let n=oe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==A.string&&r.parsedType!==A.number){let o=oe.objectValues(n);return C(r,{expected:oe.joinValues(o),received:r.parsedType,code:E.invalid_type}),Z}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=oe.objectValues(n);return C(r,{received:r.data,code:E.invalid_enum_value,options:o}),Z}return st(e.data)}get enum(){return this._def.values}};Mr.create=(t,e)=>new Mr({values:t,typeName:T.ZodNativeEnum,...X(e)});var Yn=class extends Q{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==A.promise&&n.common.async===!1)return C(n,{code:E.invalid_type,expected:A.promise,received:n.parsedType}),Z;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return st(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Yn.create=(t,e)=>new Yn({type:t,typeName:T.ZodPromise,...X(e)});var Lt=class extends Q{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:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{C(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return Z;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?Z:c.status==="dirty"?Er(c.value):n.value==="dirty"?Er(c.value):c});{if(n.value==="aborted")return Z;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?Z:a.status==="dirty"?Er(a.value):n.value==="dirty"?Er(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(r.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(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?Z:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?Z:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!Gn(i))return Z;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:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Gn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):Z);oe.assertNever(o)}};Lt.create=(t,e,n)=>new Lt({schema:t,typeName:T.ZodEffects,effect:e,...X(n)});Lt.createWithPreprocess=(t,e,n)=>new Lt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...X(n)});var bt=class extends Q{_parse(e){return this._getType(e)===A.undefined?st(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};bt.create=(t,e)=>new bt({innerType:t,typeName:T.ZodOptional,...X(e)});var yn=class extends Q{_parse(e){return this._getType(e)===A.null?st(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};yn.create=(t,e)=>new yn({innerType:t,typeName:T.ZodNullable,...X(e)});var jr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===A.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};jr.create=(t,e)=>new jr({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});var Lr=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Eo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Lr.create=(t,e)=>new Lr({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});var $o=class extends Q{_parse(e){if(this._getType(e)!==A.nan){let r=this._getOrReturnCtx(e);return C(r,{code:E.invalid_type,expected:A.nan,received:r.parsedType}),Z}return{status:"valid",value:e.data}}};$o.create=t=>new $o({typeName:T.ZodNaN,...X(t)});var ER=Symbol("zod_brand"),Ds=class extends Q{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ms=class t extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?Z:s.status==="dirty"?(n.dirty(),Er(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?Z:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:T.ZodPipeline})}},zr=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Gn(o)&&(o.value=Object.freeze(o.value)),o);return Eo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};zr.create=(t,e)=>new zr({innerType:t,typeName:T.ZodReadonly,...X(e)});function xy(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function Ey(t,e={},n){return t?Xn.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=xy(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=xy(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Xn.create()}var wR={object:St.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 TR=(t,e={message:`Input not instance of ${t.name}`})=>Ey(n=>n instanceof t,e),wy=Jn.create,Ty=wr.create,PR=$o.create,RR=Tr.create,Py=Pr.create,CR=Rr.create,$R=To.create,OR=Cr.create,IR=$r.create,AR=Xn.create,NR=An.create,DR=en.create,MR=Po.create,jR=Nn.create,bl=St.create,LR=St.strictCreate,zR=Or.create,HR=_a.create,UR=Ir.create,FR=gn.create,BR=xa.create,ZR=Ro.create,qR=Co.create,VR=ba.create,WR=Ar.create,KR=Nr.create,GR=Dr.create,JR=Mr.create,XR=Yn.create,YR=Lt.create,QR=bt.create,e0=yn.create,t0=Lt.createWithPreprocess,n0=Ms.create,r0=()=>wy().optional(),o0=()=>Ty().optional(),s0=()=>Py().optional(),i0={string:(t=>Jn.create({...t,coerce:!0})),number:(t=>wr.create({...t,coerce:!0})),boolean:(t=>Pr.create({...t,coerce:!0})),bigint:(t=>Tr.create({...t,coerce:!0})),date:(t=>Rr.create({...t,coerce:!0}))};var a0=Z;var c0=Object.freeze({status:"aborted"});function k(t,e,n){function r(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=n?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=n?.Parent?new s:this;r(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>n?.Parent&&a instanceof n.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}var Dn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Sa={};function It(t){return t&&Object.assign(Sa,t),Sa}var ie={};je(ie,{BIGINT_FORMAT_RANGES:()=>Cy,Class:()=>kl,NUMBER_FORMAT_RANGES:()=>Cl,aborted:()=>Ur,allowsEval:()=>Tl,assert:()=>f0,assertEqual:()=>u0,assertIs:()=>d0,assertNever:()=>p0,assertNotEqual:()=>l0,assignProp:()=>wl,cached:()=>zs,captureStackTrace:()=>va,cleanEnum:()=>T0,cleanRegex:()=>Us,clone:()=>At,createTransparentProxy:()=>x0,defineLazy:()=>be,esc:()=>Hr,escapeRegex:()=>Qn,extend:()=>k0,finalizeIssue:()=>tn,floatSafeRemainder:()=>El,getElementAtPath:()=>m0,getEnumValues:()=>Ls,getLengthableOrigin:()=>Fs,getParsedType:()=>_0,getSizableOrigin:()=>$y,isObject:()=>Oo,isPlainObject:()=>Io,issue:()=>$l,joinValues:()=>ka,jsonStringifyReplacer:()=>vl,merge:()=>v0,normalizeParams:()=>q,nullish:()=>Hs,numKeys:()=>y0,omit:()=>S0,optionalKeys:()=>Rl,partial:()=>E0,pick:()=>b0,prefixIssues:()=>_n,primitiveTypes:()=>Ry,promiseAllObject:()=>h0,propertyKeyTypes:()=>Pl,randomString:()=>g0,required:()=>w0,stringifyPrimitive:()=>Ea,unwrapMessage:()=>js});function u0(t){return t}function l0(t){return t}function d0(t){}function p0(t){throw new Error}function f0(t){}function Ls(t){let e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,o])=>e.indexOf(+r)===-1).map(([r,o])=>o)}function ka(t,e="|"){return t.map(n=>Ea(n)).join(e)}function vl(t,e){return typeof e=="bigint"?e.toString():e}function zs(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Hs(t){return t==null}function Us(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function El(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function be(t,e,n){Object.defineProperty(t,e,{get(){{let o=n();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function wl(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function m0(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function h0(t){let e=Object.keys(t),n=e.map(r=>t[r]);return Promise.all(n).then(r=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=r[s];return o})}function g0(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Hr(t){return JSON.stringify(t)}var va=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Oo(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var Tl=zs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Io(t){if(Oo(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Oo(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function y0(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var _0=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}`)}},Pl=new Set(["string","number","symbol"]),Ry=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Qn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function At(t,e,n){let r=new t._zod.constr(e??t._zod.def);return(!e||n?.parent)&&(r._zod.parent=t),r}function q(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 x0(t){let e;return new Proxy({},{get(n,r,o){return e??(e=t()),Reflect.get(e,r,o)},set(n,r,o,s){return e??(e=t()),Reflect.set(e,r,o,s)},has(n,r){return e??(e=t()),Reflect.has(e,r)},deleteProperty(n,r){return e??(e=t()),Reflect.deleteProperty(e,r)},ownKeys(n){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(n,r){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,r)},defineProperty(n,r,o){return e??(e=t()),Reflect.defineProperty(e,r,o)}})}function Ea(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Rl(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var Cl={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]},Cy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function b0(t,e){let n={},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(n[o]=r.shape[o])}return At(t,{...t._zod.def,shape:n,checks:[]})}function S0(t,e){let n={...t._zod.def.shape},r=t._zod.def;for(let o in e){if(!(o in r.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete n[o]}return At(t,{...t._zod.def,shape:n,checks:[]})}function k0(t,e){if(!Io(e))throw new Error("Invalid input to extend: expected a plain object");let n={...t._zod.def,get shape(){let r={...t._zod.def.shape,...e};return wl(this,"shape",r),r},checks:[]};return At(t,n)}function v0(t,e){return At(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return wl(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function E0(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in r))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=t?new t({type:"optional",innerType:r[s]}):r[s])}else for(let s in r)o[s]=t?new t({type:"optional",innerType:r[s]}):r[s];return At(e,{...e._zod.def,shape:o,checks:[]})}function w0(t,e,n){let r=e._zod.def.shape,o={...r};if(n)for(let s in n){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);n[s]&&(o[s]=new t({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new t({type:"nonoptional",innerType:r[s]});return At(e,{...e._zod.def,shape:o,checks:[]})}function Ur(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function _n(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function js(t){return typeof t=="string"?t:t?.message}function tn(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=js(t.inst?._zod.def?.error?.(t))??js(e?.error?.(t))??js(n.customError?.(t))??js(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function $y(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fs(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function $l(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function T0(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var kl=class{constructor(...e){}};var Oy=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,vl,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},wa=k("$ZodError",Oy),Bs=k("$ZodError",Oy,{Parent:Error});function Ol(t,e=n=>n.message){let n={},r=[];for(let o of t.issues)o.path.length>0?(n[o.path[0]]=n[o.path[0]]||[],n[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:n}}function Il(t,e){let n=e||function(s){return s.message},r={_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)r._errors.push(n(i));else{let a=r,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(n(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),r}var Al=t=>(e,n,r,o)=>{let s=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise)throw new Dn;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tn(c,s,It())));throw va(a,o?.callee),a}return i.value},Nl=Al(Bs),Dl=t=>async(e,n,r,o)=>{let s=r?Object.assign(r,{async:!0}):{async:!0},i=e._zod.run({value:n,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>tn(c,s,It())));throw va(a,o?.callee),a}return i.value},Ml=Dl(Bs),jl=t=>(e,n,r)=>{let o=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},o);if(s instanceof Promise)throw new Dn;return s.issues.length?{success:!1,error:new(t??wa)(s.issues.map(i=>tn(i,o,It())))}:{success:!0,data:s.value}},Fr=jl(Bs),Ll=t=>async(e,n,r)=>{let o=r?Object.assign(r,{async:!0}):{async:!0},s=e._zod.run({value:n,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>tn(i,o,It())))}:{success:!0,data:s.value}},Br=Ll(Bs);var Iy=/^[cC][^\s-]{8,}$/,Ay=/^[0-9a-z]+$/,Ny=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Dy=/^[0-9a-vA-V]{20}$/,My=/^[A-Za-z0-9]{27}$/,jy=/^[a-zA-Z0-9_-]{21}$/,Ly=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var zy=/^([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})$/,zl=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 Hy=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var R0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Uy(){return new RegExp(R0,"u")}var Fy=/^(?:(?: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])$/,By=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Zy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,qy=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Vy=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hl=/^[A-Za-z0-9_-]*$/,Wy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Ky=/^\+(?:[0-9]){6,14}[0-9]$/,Gy="(?:(?:\\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])))",Jy=new RegExp(`^${Gy}$`);function Xy(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 Yy(t){return new RegExp(`^${Xy(t)}$`)}function Qy(t){let e=Xy({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-]\\d{2}:\\d{2})");let r=`${e}(?:${n.join("|")})`;return new RegExp(`^${Gy}T(?:${r})$`)}var e_=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var t_=/^\d+$/,n_=/^-?\d+(?:\.\d+)?/i,r_=/true|false/i,o_=/null/i;var s_=/^[^A-Z]*$/,i_=/^[^a-z]*$/;var Je=k("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),a_={number:"number",bigint:"bigint",object:"date"},Ul=k("$ZodCheckLessThan",(t,e)=>{Je.init(t,e);let n=a_[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Fl=k("$ZodCheckGreaterThan",(t,e)=>{Je.init(t,e);let n=a_[typeof e.value];t._zod.onattach.push(r=>{let o=r._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=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),c_=k("$ZodCheckMultipleOf",(t,e)=>{Je.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):El(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),u_=k("$ZodCheckNumberFormat",(t,e)=>{Je.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=Cl[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,n&&(a.pattern=t_)}),t._zod.check=i=>{let a=i.value;if(n){if(!Number.isInteger(a)){i.issues.push({expected:r,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:r,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:r,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 l_=k("$ZodCheckMaxLength",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let o=r.value;if(o.length<=e.maximum)return;let i=Fs(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),d_=k("$ZodCheckMinLength",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let o=r.value;if(o.length>=e.minimum)return;let i=Fs(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),p_=k("$ZodCheckLengthEquals",(t,e)=>{var n;Je.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Hs(o)&&o.length!==void 0}),t._zod.onattach.push(r=>{let o=r._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=r=>{let o=r.value,s=o.length;if(s===e.length)return;let i=Fs(o),a=s>e.length;r.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Zs=k("$ZodCheckStringFormat",(t,e)=>{var n,r;Je.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?(n=t._zod).check??(n.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})}):(r=t._zod).check??(r.check=()=>{})}),f_=k("$ZodCheckRegex",(t,e)=>{Zs.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),m_=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=s_),Zs.init(t,e)}),h_=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=i_),Zs.init(t,e)}),g_=k("$ZodCheckIncludes",(t,e)=>{Je.init(t,e);let n=Qn(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),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})}}),y_=k("$ZodCheckStartsWith",(t,e)=>{Je.init(t,e);let n=new RegExp(`^${Qn(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),__=k("$ZodCheckEndsWith",(t,e)=>{Je.init(t,e);let n=new RegExp(`.*${Qn(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}});var x_=k("$ZodCheckOverwrite",(t,e)=>{Je.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var Pa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
197
197
  `).filter(i=>i),o=Math.min(...r.map(i=>i.length-i.trimStart().length)),s=r.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,n=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...n,o.join(`
198
- `))}};var k_={major:4,minor:0,patch:0};var he=k("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=k_;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Fr(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 Mn;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Fr(s,d)))});else{if(s.issues.length===d)continue;c||(c=Fr(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 Mn;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Br(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Zr(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),qs=k("$ZodString",(t,e)=>{he.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??t_(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Se=k("$ZodStringFormat",(t,e)=>{Zs.init(t,e),qs.init(t,e)}),Zl=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Hy),Se.init(t,e)}),ql=k("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=zl(r))}else e.pattern??(e.pattern=zl());Se.init(t,e)}),Vl=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Uy),Se.init(t,e)}),Wl=k("$ZodURL",(t,e)=>{Se.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Ky.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Kl=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Fy()),Se.init(t,e)}),Gl=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Ly),Se.init(t,e)}),Jl=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Ay),Se.init(t,e)}),Xl=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ny),Se.init(t,e)}),Yl=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Dy),Se.init(t,e)}),Ql=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=My),Se.init(t,e)}),ed=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=jy),Se.init(t,e)}),I_=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=e_(e)),Se.init(t,e)}),A_=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Xy),Se.init(t,e)}),N_=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Qy(e)),Se.init(t,e)}),D_=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=zy),Se.init(t,e)}),td=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=By),Se.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),nd=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Zy),Se.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),rd=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=qy),Se.init(t,e)}),od=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Vy),Se.init(t,e),t._zod.check=n=>{let[r,o]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function M_(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var sd=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Wy),Se.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{M_(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function RR(t){if(!Hl.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return M_(n)}var id=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Hl),Se.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{RR(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),ad=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Gy),Se.init(t,e)});function CR(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var cd=k("$ZodJWT",(t,e)=>{Se.init(t,e),t._zod.check=n=>{CR(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var $a=k("$ZodNumber",(t,e)=>{he.init(t,e),t._zod.pattern=t._zod.bag.pattern??r_,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),ud=k("$ZodNumber",(t,e)=>{l_.init(t,e),$a.init(t,e)}),ld=k("$ZodBoolean",(t,e)=>{he.init(t,e),t._zod.pattern=o_,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}});var dd=k("$ZodNull",(t,e)=>{he.init(t,e),t._zod.pattern=s_,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var pd=k("$ZodUnknown",(t,e)=>{he.init(t,e),t._zod.parse=n=>n}),fd=k("$ZodNever",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function v_(t,e,n){t.issues.length&&e.issues.push(...xn(n,t.issues)),e.value[n]=t.value}var md=k("$ZodArray",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.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:[]},r);c instanceof Promise?s.push(c.then(u=>v_(u,n,i))):v_(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Ca(t,e,n){t.issues.length&&e.issues.push(...xn(n,t.issues)),e.value[n]=t.value}function E_(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(...xn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}var Oa=k("$ZodObject",(t,e)=>{he.init(t,e);let n=zs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof he))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=Rl(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});be(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 r=d=>{let f=new Ra(["shape","payload","ctx"]),m=n.value,p=_=>{let x=Ur(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of m.keys)h[_]=`key_${g++}`;f.write("const newResult = {}");for(let _ of m.keys)if(m.optionalKeys.has(_)){let x=h[_];f.write(`const ${x} = ${p(_)};`);let b=Ur(_);f.write(`
198
+ `))}};var S_={major:4,minor:0,patch:0};var he=k("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=S_;let r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(let o of r)for(let s of o._zod.onattach)s(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=Ur(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 Dn;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=Ur(s,d)))});else{if(s.issues.length===d)continue;c||(c=Ur(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 Dn;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Fr(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Br(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),qs=k("$ZodString",(t,e)=>{he.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??e_(t._zod.bag),t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=String(n.value)}catch{}return typeof n.value=="string"||n.issues.push({expected:"string",code:"invalid_type",input:n.value,inst:t}),n}}),Se=k("$ZodStringFormat",(t,e)=>{Zs.init(t,e),qs.init(t,e)}),Zl=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=zy),Se.init(t,e)}),ql=k("$ZodUUID",(t,e)=>{if(e.version){let r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=zl(r))}else e.pattern??(e.pattern=zl());Se.init(t,e)}),Vl=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Hy),Se.init(t,e)}),Wl=k("$ZodURL",(t,e)=>{Se.init(t,e),t._zod.check=n=>{try{let r=n.value,o=new URL(r),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Wy.source,input:n.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)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),!r.endsWith("/")&&s.endsWith("/")?n.value=s.slice(0,-1):n.value=s;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),Kl=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Uy()),Se.init(t,e)}),Gl=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=jy),Se.init(t,e)}),Jl=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Iy),Se.init(t,e)}),Xl=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ay),Se.init(t,e)}),Yl=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ny),Se.init(t,e)}),Ql=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Dy),Se.init(t,e)}),ed=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=My),Se.init(t,e)}),O_=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Qy(e)),Se.init(t,e)}),I_=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Jy),Se.init(t,e)}),A_=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Yy(e)),Se.init(t,e)}),N_=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ly),Se.init(t,e)}),td=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Fy),Se.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),nd=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=By),Se.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv6"}),t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),rd=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Zy),Se.init(t,e)}),od=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=qy),Se.init(t,e),t._zod.check=n=>{let[r,o]=n.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://[${r}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function D_(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var sd=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Vy),Se.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{D_(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function C0(t){if(!Hl.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return D_(n)}var id=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Hl),Se.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{C0(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),ad=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Ky),Se.init(t,e)});function $0(t,e=null){try{let n=t.split(".");if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let o=JSON.parse(atob(r));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}var cd=k("$ZodJWT",(t,e)=>{Se.init(t,e),t._zod.check=n=>{$0(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var Ca=k("$ZodNumber",(t,e)=>{he.init(t,e),t._zod.pattern=t._zod.bag.pattern??n_,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}let o=n.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return n;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),n}}),ud=k("$ZodNumber",(t,e)=>{u_.init(t,e),Ca.init(t,e)}),ld=k("$ZodBoolean",(t,e)=>{he.init(t,e),t._zod.pattern=r_,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=!!n.value}catch{}let o=n.value;return typeof o=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),n}});var dd=k("$ZodNull",(t,e)=>{he.init(t,e),t._zod.pattern=o_,t._zod.values=new Set([null]),t._zod.parse=(n,r)=>{let o=n.value;return o===null||n.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),n}});var pd=k("$ZodUnknown",(t,e)=>{he.init(t,e),t._zod.parse=n=>n}),fd=k("$ZodNever",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function k_(t,e,n){t.issues.length&&e.issues.push(..._n(n,t.issues)),e.value[n]=t.value}var md=k("$ZodArray",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Array.isArray(o))return n.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),n;n.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:[]},r);c instanceof Promise?s.push(c.then(u=>k_(u,n,i))):k_(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function Ra(t,e,n){t.issues.length&&e.issues.push(..._n(n,t.issues)),e.value[n]=t.value}function v_(t,e,n,r){t.issues.length?r[n]===void 0?n in r?e.value[n]=void 0:e.value[n]=t.value:e.issues.push(..._n(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}var $a=k("$ZodObject",(t,e)=>{he.init(t,e);let n=zs(()=>{let d=Object.keys(e.shape);for(let m of d)if(!(e.shape[m]instanceof he))throw new Error(`Invalid element at key "${m}": expected a Zod schema`);let f=Rl(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});be(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 r=d=>{let f=new Pa(["shape","payload","ctx"]),m=n.value,p=_=>{let x=Hr(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of m.keys)h[_]=`key_${g++}`;f.write("const newResult = {}");for(let _ of m.keys)if(m.optionalKeys.has(_)){let x=h[_];f.write(`const ${x} = ${p(_)};`);let b=Hr(_);f.write(`
199
199
  if (${x}.issues.length) {
200
200
  if (input[${b}] === undefined) {
201
201
  if (${b} in input) {
@@ -217,21 +217,21 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
217
217
  `)}else{let x=h[_];f.write(`const ${x} = ${p(_)};`),f.write(`
218
218
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
219
219
  ...iss,
220
- path: iss.path ? [${Ur(_)}, ...iss.path] : [${Ur(_)}]
221
- })));`),f.write(`newResult[${Ur(_)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,x)=>y(d,_,x)},o,s=Ao,i=!ka.jitless,c=i&&Tl.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=n.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=r(e.shape)),d=o(d,f);else{d.value={};let x=l.shape;for(let b of l.keys){let v=x[b],O=v._zod.run({value:m[b],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";O instanceof Promise?p.push(O.then(j=>R?E_(j,d,b,m):Ca(j,d,b))):R?E_(O,d,b,m):Ca(O,d,b)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(m)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let b=y.run({value:m[x],issues:[]},f);b instanceof Promise?p.push(b.then(v=>Ca(v,d,x))):Ca(b,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function w_(t,e,n,r){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:n,errors:t.map(o=>o.issues.map(s=>tn(s,r,It())))}),e}var Ia=k("$ZodUnion",(t,e)=>{he.init(t,e),be(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),be(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),be(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),be(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Us(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>w_(i,n,t,r)):w_(s,n,t,r)}}),hd=k("$ZodDiscriminatedUnion",(t,e)=>{Ia.init(t,e);let n=t._zod.parse;be(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 r=zs(()=>{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(!Ao(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),gd=k("$ZodIntersection",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>T_(n,c,u)):T_(n,s,i)}});function Bl(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(No(t)&&No(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Bl(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 n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=Bl(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function T_(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Fr(t))return t;let r=Bl(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}var yd=k("$ZodRecord",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!No(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(...xn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...xn(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>tn(u,r,It())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(...xn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...xn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}});var _d=k("$ZodEnum",(t,e)=>{he.init(t,e);let n=Ls(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Pl.has(typeof r)).map(r=>typeof r=="string"?er(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),xd=k("$ZodLiteral",(t,e)=>{he.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?er(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var bd=k("$ZodTransform",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new Mn;return n.value=o,n}}),Sd=k("$ZodOptional",(t,e)=>{he.init(t,e),t._zod.optin="optional",t._zod.optout="optional",be(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),be(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Us(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),kd=k("$ZodNullable",(t,e)=>{he.init(t,e),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Us(n.source)}|null)$`):void 0}),be(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),vd=k("$ZodDefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>P_(s,e)):P_(o,e)}});function P_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ed=k("$ZodPrefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),wd=k("$ZodNonOptional",(t,e)=>{he.init(t,e),be(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>R_(s,t)):R_(o,t)}});function R_(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 Td=k("$ZodCatch",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>tn(i,r,It()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>tn(s,r,It()))},input:n.value}),n.issues=[]),n)}});var Pd=k("$ZodPipe",(t,e)=>{he.init(t,e),be(t._zod,"values",()=>e.in._zod.values),be(t._zod,"optin",()=>e.in._zod.optin),be(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>C_(s,e,r)):C_(o,e,r)}});function C_(t,e,n){return Fr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var Rd=k("$ZodReadonly",(t,e)=>{he.init(t,e),be(t._zod,"propValues",()=>e.innerType._zod.propValues),be(t._zod,"values",()=>e.innerType._zod.values),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then($_):$_(o)}});function $_(t){return t.value=Object.freeze(t.value),t}var Cd=k("$ZodCustom",(t,e)=>{Je.init(t,e),he.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>O_(s,n,r,t));O_(o,n,r,t)}});function O_(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push($l(o))}}var $R=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},OR=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${$R(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${wa(r.values[0])}`:`Invalid option: expected one of ${va(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${va(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function j_(){return{localeError:OR()}}var Vs=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function L_(){return new Vs}var tr=L_();function $d(t,e){return new t({type:"string",...q(e)})}function Od(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function Aa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Id(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Ad(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function Nd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Dd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Md(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function jd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Ld(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function zd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Hd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Ud(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Fd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Bd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Zd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function qd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Vd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Wd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Kd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Gd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Jd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Xd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function z_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function H_(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function U_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function F_(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Yd(t,e){return new t({type:"number",checks:[],...q(e)})}function Qd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function ep(t,e){return new t({type:"boolean",...q(e)})}function tp(t,e){return new t({type:"null",...q(e)})}function np(t){return new t({type:"unknown"})}function rp(t,e){return new t({type:"never",...q(e)})}function Na(t,e){return new Ul({check:"less_than",...q(e),value:t,inclusive:!1})}function Ws(t,e){return new Ul({check:"less_than",...q(e),value:t,inclusive:!0})}function Da(t,e){return new Fl({check:"greater_than",...q(e),value:t,inclusive:!1})}function Ks(t,e){return new Fl({check:"greater_than",...q(e),value:t,inclusive:!0})}function Ma(t,e){return new u_({check:"multiple_of",...q(e),value:t})}function ja(t,e){return new d_({check:"max_length",...q(e),maximum:t})}function Do(t,e){return new p_({check:"min_length",...q(e),minimum:t})}function La(t,e){return new f_({check:"length_equals",...q(e),length:t})}function op(t,e){return new m_({check:"string_format",format:"regex",...q(e),pattern:t})}function sp(t){return new h_({check:"string_format",format:"lowercase",...q(t)})}function ip(t){return new g_({check:"string_format",format:"uppercase",...q(t)})}function ap(t,e){return new y_({check:"string_format",format:"includes",...q(e),includes:t})}function cp(t,e){return new __({check:"string_format",format:"starts_with",...q(e),prefix:t})}function up(t,e){return new x_({check:"string_format",format:"ends_with",...q(e),suffix:t})}function qr(t){return new b_({check:"overwrite",tx:t})}function lp(t){return qr(e=>e.normalize(t))}function dp(){return qr(t=>t.trim())}function pp(){return qr(t=>t.toLowerCase())}function fp(){return qr(t=>t.toUpperCase())}function B_(t,e,n){return new t({type:"array",element:e,...q(n)})}function mp(t,e,n){let r=q(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function hp(t,e,n){return new t({type:"custom",check:"custom",fn:e,...q(n)})}var za=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??tr,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.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:_,contentEncoding:x}=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),x&&(p.contentEncoding=x),_&&_.size>0){let b=[..._];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,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 x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);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 _ in h)p.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.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=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}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=Ls(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:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(p,h)):p.anyOf=_.map(x=>({...h,contentMediaType:x})):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"&&Be(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);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(r.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>
220
+ path: iss.path ? [${Hr(_)}, ...iss.path] : [${Hr(_)}]
221
+ })));`),f.write(`newResult[${Hr(_)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,x)=>y(d,_,x)},o,s=Oo,i=!Sa.jitless,c=i&&Tl.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=n.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=r(e.shape)),d=o(d,f);else{d.value={};let x=l.shape;for(let b of l.keys){let v=x[b],O=v._zod.run({value:m[b],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";O instanceof Promise?p.push(O.then(j=>R?v_(j,d,b,m):Ra(j,d,b))):R?v_(O,d,b,m):Ra(O,d,b)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(m)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let b=y.run({value:m[x],issues:[]},f);b instanceof Promise?p.push(b.then(v=>Ra(v,d,x))):Ra(b,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function E_(t,e,n,r){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:n,errors:t.map(o=>o.issues.map(s=>tn(s,r,It())))}),e}var Oa=k("$ZodUnion",(t,e)=>{he.init(t,e),be(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),be(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),be(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),be(t._zod,"pattern",()=>{if(e.options.every(n=>n._zod.pattern)){let n=e.options.map(r=>r._zod.pattern);return new RegExp(`^(${n.map(r=>Us(r.source)).join("|")})$`)}}),t._zod.parse=(n,r)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:n.value,issues:[]},r);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=>E_(i,n,t,r)):E_(s,n,t,r)}}),hd=k("$ZodDiscriminatedUnion",(t,e)=>{Oa.init(t,e);let n=t._zod.parse;be(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 r=zs(()=>{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(!Oo(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=r.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?n(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),gd=k("$ZodIntersection",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value,s=e.left._zod.run({value:o,issues:[]},r),i=e.right._zod.run({value:o,issues:[]},r);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>w_(n,c,u)):w_(n,s,i)}});function Bl(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(Io(t)&&Io(e)){let n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),o={...t,...e};for(let s of r){let i=Bl(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 n=[];for(let r=0;r<t.length;r++){let o=t[r],s=e[r],i=Bl(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[r,...i.mergeErrorPath]};n.push(i.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function w_(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Ur(t))return t;let r=Bl(e.value,n.value);if(!r.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(r.mergeErrorPath)}`);return t.value=r.data,t}var yd=k("$ZodRecord",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Io(o))return n.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),n;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;n.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:[]},r);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&n.issues.push(..._n(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(..._n(c,u.issues)),n.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&n.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{n.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},r);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){n.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>tn(u,r,It())),input:i,path:[i],inst:t}),n.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},r);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&n.issues.push(..._n(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(..._n(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}});var _d=k("$ZodEnum",(t,e)=>{he.init(t,e);let n=Ls(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>Pl.has(typeof r)).map(r=>typeof r=="string"?Qn(r):r.toString()).join("|")})$`),t._zod.parse=(r,o)=>{let s=r.value;return t._zod.values.has(s)||r.issues.push({code:"invalid_value",values:n,input:s,inst:t}),r}}),xd=k("$ZodLiteral",(t,e)=>{he.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Qn(n):n?n.toString():String(n)).join("|")})$`),t._zod.parse=(n,r)=>{let o=n.value;return t._zod.values.has(o)||n.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),n}});var bd=k("$ZodTransform",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=e.transform(n.value,n);if(r.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(n.value=i,n));if(o instanceof Promise)throw new Dn;return n.value=o,n}}),Sd=k("$ZodOptional",(t,e)=>{he.init(t,e),t._zod.optin="optional",t._zod.optout="optional",be(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),be(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Us(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(n,r):n.value===void 0?n:e.innerType._zod.run(n,r)}),kd=k("$ZodNullable",(t,e)=>{he.init(t,e),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${Us(n.source)}|null)$`):void 0}),be(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),vd=k("$ZodDefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(n.value===void 0)return n.value=e.defaultValue,n;let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>T_(s,e)):T_(o,e)}});function T_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var Ed=k("$ZodPrefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),wd=k("$ZodNonOptional",(t,e)=>{he.init(t,e),be(t._zod,"values",()=>{let n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>P_(s,t)):P_(o,t)}});function P_(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 Td=k("$ZodCatch",(t,e)=>{he.init(t,e),t._zod.optin="optional",be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(i=>tn(i,r,It()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>tn(s,r,It()))},input:n.value}),n.issues=[]),n)}});var Pd=k("$ZodPipe",(t,e)=>{he.init(t,e),be(t._zod,"values",()=>e.in._zod.values),be(t._zod,"optin",()=>e.in._zod.optin),be(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(n,r)=>{let o=e.in._zod.run(n,r);return o instanceof Promise?o.then(s=>R_(s,e,r)):R_(o,e,r)}});function R_(t,e,n){return Ur(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var Rd=k("$ZodReadonly",(t,e)=>{he.init(t,e),be(t._zod,"propValues",()=>e.innerType._zod.propValues),be(t._zod,"values",()=>e.innerType._zod.values),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(n,r)=>{let o=e.innerType._zod.run(n,r);return o instanceof Promise?o.then(C_):C_(o)}});function C_(t){return t.value=Object.freeze(t.value),t}var Cd=k("$ZodCustom",(t,e)=>{Je.init(t,e),he.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{let r=n.value,o=e.fn(r);if(o instanceof Promise)return o.then(s=>$_(s,n,r,t));$_(o,n,r,t)}});function $_(t,e,n,r){if(!t){let o={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(o.params=r._zod.def.params),e.issues.push($l(o))}}var O0=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},I0=()=>{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(r){return t[r]??null}let n={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 r=>{switch(r.code){case"invalid_type":return`Invalid input: expected ${r.expected}, received ${O0(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${Ea(r.values[0])}`:`Invalid option: expected one of ${ka(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${n[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${ka(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}};function M_(){return{localeError:I0()}}var Vs=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...n){let r=n[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){let n=e._zod.parent;if(n){let r={...this.get(n)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function j_(){return new Vs}var er=j_();function $d(t,e){return new t({type:"string",...q(e)})}function Od(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function Ia(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function Id(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function Ad(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function Nd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function Dd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Md(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function jd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Ld(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function zd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Hd(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Ud(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Fd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Bd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Zd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function qd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Vd(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Wd(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Kd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Gd(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Jd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Xd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function L_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function z_(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function H_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function U_(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Yd(t,e){return new t({type:"number",checks:[],...q(e)})}function Qd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function ep(t,e){return new t({type:"boolean",...q(e)})}function tp(t,e){return new t({type:"null",...q(e)})}function np(t){return new t({type:"unknown"})}function rp(t,e){return new t({type:"never",...q(e)})}function Aa(t,e){return new Ul({check:"less_than",...q(e),value:t,inclusive:!1})}function Ws(t,e){return new Ul({check:"less_than",...q(e),value:t,inclusive:!0})}function Na(t,e){return new Fl({check:"greater_than",...q(e),value:t,inclusive:!1})}function Ks(t,e){return new Fl({check:"greater_than",...q(e),value:t,inclusive:!0})}function Da(t,e){return new c_({check:"multiple_of",...q(e),value:t})}function Ma(t,e){return new l_({check:"max_length",...q(e),maximum:t})}function Ao(t,e){return new d_({check:"min_length",...q(e),minimum:t})}function ja(t,e){return new p_({check:"length_equals",...q(e),length:t})}function op(t,e){return new f_({check:"string_format",format:"regex",...q(e),pattern:t})}function sp(t){return new m_({check:"string_format",format:"lowercase",...q(t)})}function ip(t){return new h_({check:"string_format",format:"uppercase",...q(t)})}function ap(t,e){return new g_({check:"string_format",format:"includes",...q(e),includes:t})}function cp(t,e){return new y_({check:"string_format",format:"starts_with",...q(e),prefix:t})}function up(t,e){return new __({check:"string_format",format:"ends_with",...q(e),suffix:t})}function Zr(t){return new x_({check:"overwrite",tx:t})}function lp(t){return Zr(e=>e.normalize(t))}function dp(){return Zr(t=>t.trim())}function pp(){return Zr(t=>t.toLowerCase())}function fp(){return Zr(t=>t.toUpperCase())}function F_(t,e,n){return new t({type:"array",element:e,...q(n)})}function mp(t,e,n){let r=q(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function hp(t,e,n){return new t({type:"custom",check:"custom",fn:e,...q(n)})}var La=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??er,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,n={path:[],schemaPath:[]}){var r;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++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.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:_,contentEncoding:x}=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),x&&(p.contentEncoding=x),_&&_.size>0){let b=[..._];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,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 x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);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 _ in h)p.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.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=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}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=Ls(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:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(p,h)):p.anyOf=_.map(x=>({...h,contentMediaType:x})):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"&&Be(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,n){let r={cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.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(r.external){let h=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);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(r.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>
222
222
 
223
- 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(r.external){let m=r.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&&r.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}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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 gp(t,e){if(t instanceof Vs){let r=new za(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new za(e);return n.process(t),n.emit(t,e)}function Be(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 Be(o.element,n);case"object":{for(let s in o.shape)if(Be(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(Be(s,n))return!0;return!1}case"intersection":return Be(o.left,n)||Be(o.right,n);case"tuple":{for(let s of o.items)if(Be(s,n))return!0;return!!(o.rest&&Be(o.rest,n))}case"record":return Be(o.keyType,n)||Be(o.valueType,n);case"map":return Be(o.keyType,n)||Be(o.valueType,n);case"set":return Be(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Be(o.innerType,n);case"lazy":return Be(o.getter(),n);case"default":return Be(o.innerType,n);case"prefault":return Be(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Be(o.in,n)||Be(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var pC=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");he.init(t,e),t.def=e,t.parse=(n,r)=>Nl(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Br(t,n,r),t.parseAsync=async(n,r)=>Ml(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Zr(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>At(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var fC=k("ZodMiniObject",(t,e)=>{Oa.init(t,e),pC.init(t,e),ie.defineLazy(t,"shape",()=>e.shape)});function yp(t,e){let n={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new fC(n)}function bn(t){return!!t._zod}function Wr(t){let e=Object.values(t);if(e.length===0)return yp({});let n=e.every(bn),r=e.every(o=>!bn(o));if(n)return yp(t);if(r)return bl(t);throw new Error("Mixed Zod versions detected in object shape.")}function nr(t,e){return bn(t)?Br(t,e):t.safeParse(e)}async function Ha(t,e){return bn(t)?await Zr(t,e):await t.safeParseAsync(e)}function rr(t){if(!t)return;let e;if(bn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Mo(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Wr(t)}}if(bn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function hC(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Ua(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${hC(e.path)}`:e.message).join(`
224
- `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function q_(t){return t.description}function V_(t){if(bn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function jo(t){if(bn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var Gs={};Me(Gs,{ZodISODate:()=>K_,ZodISODateTime:()=>W_,ZodISODuration:()=>J_,ZodISOTime:()=>G_,date:()=>xp,datetime:()=>_p,duration:()=>Sp,time:()=>bp});var W_=k("ZodISODateTime",(t,e)=>{I_.init(t,e),Pe.init(t,e)});function _p(t){return z_(W_,t)}var K_=k("ZodISODate",(t,e)=>{A_.init(t,e),Pe.init(t,e)});function xp(t){return H_(K_,t)}var G_=k("ZodISOTime",(t,e)=>{N_.init(t,e),Pe.init(t,e)});function bp(t){return U_(G_,t)}var J_=k("ZodISODuration",(t,e)=>{D_.init(t,e),Pe.init(t,e)});function Sp(t){return F_(J_,t)}var X_=(t,e)=>{Ta.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Il(t,n)},flatten:{value:n=>Ol(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},ZZ=k("ZodError",X_),Js=k("ZodError",X_,{Parent:Error});var Y_=Al(Js),Q_=Dl(Js),ex=jl(Js),tx=Ll(Js);var Oe=k("ZodType",(t,e)=>(he.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>At(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>Y_(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>ex(t,n,r),t.parseAsync=async(n,r)=>Q_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>tx(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(d$(n,r)),t.superRefine=n=>t.check(p$(n)),t.overwrite=n=>t.check(qr(n)),t.optional=()=>Ce(t),t.nullable=()=>ox(t),t.nullish=()=>Ce(ox(t)),t.nonoptional=n=>o$(t,n),t.array=()=>ae(t),t.or=n=>ve([t,n]),t.and=n=>Ba(t,n),t.transform=n=>vp(t,lx(n)),t.default=n=>t$(t,n),t.prefault=n=>r$(t,n),t.catch=n=>i$(t,n),t.pipe=n=>vp(t,n),t.readonly=()=>u$(t),t.describe=n=>{let r=t.clone();return tr.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return tr.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return tr.get(t);let r=t.clone();return tr.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),sx=k("_ZodString",(t,e)=>{qs.init(t,e),Oe.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(op(...r)),t.includes=(...r)=>t.check(ap(...r)),t.startsWith=(...r)=>t.check(cp(...r)),t.endsWith=(...r)=>t.check(up(...r)),t.min=(...r)=>t.check(Do(...r)),t.max=(...r)=>t.check(ja(...r)),t.length=(...r)=>t.check(La(...r)),t.nonempty=(...r)=>t.check(Do(1,...r)),t.lowercase=r=>t.check(sp(r)),t.uppercase=r=>t.check(ip(r)),t.trim=()=>t.check(dp()),t.normalize=(...r)=>t.check(lp(...r)),t.toLowerCase=()=>t.check(pp()),t.toUpperCase=()=>t.check(fp())}),vC=k("ZodString",(t,e)=>{qs.init(t,e),sx.init(t,e),t.email=n=>t.check(Od(EC,n)),t.url=n=>t.check(Md(wC,n)),t.jwt=n=>t.check(Xd(HC,n)),t.emoji=n=>t.check(jd(TC,n)),t.guid=n=>t.check(Aa(nx,n)),t.uuid=n=>t.check(Id(Fa,n)),t.uuidv4=n=>t.check(Ad(Fa,n)),t.uuidv6=n=>t.check(Nd(Fa,n)),t.uuidv7=n=>t.check(Dd(Fa,n)),t.nanoid=n=>t.check(Ld(PC,n)),t.guid=n=>t.check(Aa(nx,n)),t.cuid=n=>t.check(zd(RC,n)),t.cuid2=n=>t.check(Hd(CC,n)),t.ulid=n=>t.check(Ud($C,n)),t.base64=n=>t.check(Kd(jC,n)),t.base64url=n=>t.check(Gd(LC,n)),t.xid=n=>t.check(Fd(OC,n)),t.ksuid=n=>t.check(Bd(IC,n)),t.ipv4=n=>t.check(Zd(AC,n)),t.ipv6=n=>t.check(qd(NC,n)),t.cidrv4=n=>t.check(Vd(DC,n)),t.cidrv6=n=>t.check(Wd(MC,n)),t.e164=n=>t.check(Jd(zC,n)),t.datetime=n=>t.check(_p(n)),t.date=n=>t.check(xp(n)),t.time=n=>t.check(bp(n)),t.duration=n=>t.check(Sp(n))});function S(t){return $d(vC,t)}var Pe=k("ZodStringFormat",(t,e)=>{Se.init(t,e),sx.init(t,e)}),EC=k("ZodEmail",(t,e)=>{Vl.init(t,e),Pe.init(t,e)});var nx=k("ZodGUID",(t,e)=>{Zl.init(t,e),Pe.init(t,e)});var Fa=k("ZodUUID",(t,e)=>{ql.init(t,e),Pe.init(t,e)});var wC=k("ZodURL",(t,e)=>{Wl.init(t,e),Pe.init(t,e)});var TC=k("ZodEmoji",(t,e)=>{Kl.init(t,e),Pe.init(t,e)});var PC=k("ZodNanoID",(t,e)=>{Gl.init(t,e),Pe.init(t,e)});var RC=k("ZodCUID",(t,e)=>{Jl.init(t,e),Pe.init(t,e)});var CC=k("ZodCUID2",(t,e)=>{Xl.init(t,e),Pe.init(t,e)});var $C=k("ZodULID",(t,e)=>{Yl.init(t,e),Pe.init(t,e)});var OC=k("ZodXID",(t,e)=>{Ql.init(t,e),Pe.init(t,e)});var IC=k("ZodKSUID",(t,e)=>{ed.init(t,e),Pe.init(t,e)});var AC=k("ZodIPv4",(t,e)=>{td.init(t,e),Pe.init(t,e)});var NC=k("ZodIPv6",(t,e)=>{nd.init(t,e),Pe.init(t,e)});var DC=k("ZodCIDRv4",(t,e)=>{rd.init(t,e),Pe.init(t,e)});var MC=k("ZodCIDRv6",(t,e)=>{od.init(t,e),Pe.init(t,e)});var jC=k("ZodBase64",(t,e)=>{sd.init(t,e),Pe.init(t,e)});var LC=k("ZodBase64URL",(t,e)=>{id.init(t,e),Pe.init(t,e)});var zC=k("ZodE164",(t,e)=>{ad.init(t,e),Pe.init(t,e)});var HC=k("ZodJWT",(t,e)=>{cd.init(t,e),Pe.init(t,e)});var ix=k("ZodNumber",(t,e)=>{$a.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(Da(r,o)),t.gte=(r,o)=>t.check(Ks(r,o)),t.min=(r,o)=>t.check(Ks(r,o)),t.lt=(r,o)=>t.check(Na(r,o)),t.lte=(r,o)=>t.check(Ws(r,o)),t.max=(r,o)=>t.check(Ws(r,o)),t.int=r=>t.check(rx(r)),t.safe=r=>t.check(rx(r)),t.positive=r=>t.check(Da(0,r)),t.nonnegative=r=>t.check(Ks(0,r)),t.negative=r=>t.check(Na(0,r)),t.nonpositive=r=>t.check(Ws(0,r)),t.multipleOf=(r,o)=>t.check(Ma(r,o)),t.step=(r,o)=>t.check(Ma(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function fe(t){return Yd(ix,t)}var UC=k("ZodNumberFormat",(t,e)=>{ud.init(t,e),ix.init(t,e)});function rx(t){return Qd(UC,t)}var FC=k("ZodBoolean",(t,e)=>{ld.init(t,e),Oe.init(t,e)});function We(t){return ep(FC,t)}var BC=k("ZodNull",(t,e)=>{dd.init(t,e),Oe.init(t,e)});function ax(t){return tp(BC,t)}var ZC=k("ZodUnknown",(t,e)=>{pd.init(t,e),Oe.init(t,e)});function Re(){return np(ZC)}var qC=k("ZodNever",(t,e)=>{fd.init(t,e),Oe.init(t,e)});function VC(t){return rp(qC,t)}var WC=k("ZodArray",(t,e)=>{md.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Do(n,r)),t.nonempty=n=>t.check(Do(1,n)),t.max=(n,r)=>t.check(ja(n,r)),t.length=(n,r)=>t.check(La(n,r)),t.unwrap=()=>t.element});function ae(t,e){return B_(WC,t,e)}var cx=k("ZodObject",(t,e)=>{Oa.init(t,e),Oe.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>kt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Re()}),t.loose=()=>t.clone({...t._zod.def,catchall:Re()}),t.strict=()=>t.clone({...t._zod.def,catchall:VC()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ie.extend(t,n),t.merge=n=>ie.merge(t,n),t.pick=n=>ie.pick(t,n),t.omit=n=>ie.omit(t,n),t.partial=(...n)=>ie.partial(dx,t,n[0]),t.required=(...n)=>ie.required(px,t,n[0])});function N(t,e){let n={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new cx(n)}function dt(t,e){return new cx({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:Re(),...ie.normalizeParams(e)})}var ux=k("ZodUnion",(t,e)=>{Ia.init(t,e),Oe.init(t,e),t.options=e.options});function ve(t,e){return new ux({type:"union",options:t,...ie.normalizeParams(e)})}var KC=k("ZodDiscriminatedUnion",(t,e)=>{ux.init(t,e),hd.init(t,e)});function Ep(t,e,n){return new KC({type:"union",options:e,discriminator:t,...ie.normalizeParams(n)})}var GC=k("ZodIntersection",(t,e)=>{gd.init(t,e),Oe.init(t,e)});function Ba(t,e){return new GC({type:"intersection",left:t,right:e})}var JC=k("ZodRecord",(t,e)=>{yd.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ke(t,e,n){return new JC({type:"record",keyType:t,valueType:e,...ie.normalizeParams(n)})}var kp=k("ZodEnum",(t,e)=>{_d.init(t,e),Oe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new kp({...e,checks:[],...ie.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new kp({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function kt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new kp({type:"enum",entries:n,...ie.normalizeParams(e)})}var XC=k("ZodLiteral",(t,e)=>{xd.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 XC({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var YC=k("ZodTransform",(t,e)=>{bd.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ie.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ie.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function lx(t){return new YC({type:"transform",transform:t})}var dx=k("ZodOptional",(t,e)=>{Sd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new dx({type:"optional",innerType:t})}var QC=k("ZodNullable",(t,e)=>{kd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function ox(t){return new QC({type:"nullable",innerType:t})}var e$=k("ZodDefault",(t,e)=>{vd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function t$(t,e){return new e$({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var n$=k("ZodPrefault",(t,e)=>{Ed.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function r$(t,e){return new n$({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var px=k("ZodNonOptional",(t,e)=>{wd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function o$(t,e){return new px({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var s$=k("ZodCatch",(t,e)=>{Td.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function i$(t,e){return new s$({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var a$=k("ZodPipe",(t,e)=>{Pd.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function vp(t,e){return new a$({type:"pipe",in:t,out:e})}var c$=k("ZodReadonly",(t,e)=>{Rd.init(t,e),Oe.init(t,e)});function u$(t){return new c$({type:"readonly",innerType:t})}var fx=k("ZodCustom",(t,e)=>{Cd.init(t,e),Oe.init(t,e)});function l$(t){let e=new Je({check:"custom"});return e._zod.check=t,e}function mx(t,e){return mp(fx,t??(()=>!0),e)}function d$(t,e={}){return hp(fx,t,e)}function p$(t){let e=l$(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ie.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ie.issue(o))}},t(n.value,n)));return e}function wp(t,e){return vp(lx(t),e)}It(j_());var Pp="2025-11-25";var hx=[Pp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],or="io.modelcontextprotocol/related-task",qa="2.0",Ze=mx(t=>t!==null&&(typeof t=="object"||typeof t=="function")),gx=ve([S(),fe().int()]),yx=S(),o2=dt({ttl:fe().optional(),pollInterval:fe().optional()}),f$=N({ttl:fe().optional()}),m$=N({taskId:S()}),Rp=dt({progressToken:gx.optional(),[or]:m$.optional()}),Nt=N({_meta:Rp.optional()}),Xs=Nt.extend({task:f$.optional()}),_x=t=>Xs.safeParse(t).success,Xe=N({method:S(),params:Nt.loose().optional()}),zt=N({_meta:Rp.optional()}),Ht=N({method:S(),params:zt.loose().optional()}),Ye=dt({_meta:Rp.optional()}),Va=ve([S(),fe().int()]),xx=N({jsonrpc:U(qa),id:Va,...Xe.shape}).strict(),Cp=t=>xx.safeParse(t).success,bx=N({jsonrpc:U(qa),...Ht.shape}).strict(),Sx=t=>bx.safeParse(t).success,$p=N({jsonrpc:U(qa),id:Va,result:Ye}).strict(),Ys=t=>$p.safeParse(t).success;var B;(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"})(B||(B={}));var Op=N({jsonrpc:U(qa),id:Va.optional(),error:N({code:fe().int(),message:S(),data:Re().optional()})}).strict();var kx=t=>Op.safeParse(t).success;var vx=ve([xx,bx,$p,Op]),s2=ve([$p,Op]),Wa=Ye.strict(),h$=zt.extend({requestId:Va.optional(),reason:S().optional()}),Ka=Ht.extend({method:U("notifications/cancelled"),params:h$}),g$=N({src:S(),mimeType:S().optional(),sizes:ae(S()).optional(),theme:kt(["light","dark"]).optional()}),Qs=N({icons:ae(g$).optional()}),Lo=N({name:S(),title:S().optional()}),Ex=Lo.extend({...Lo.shape,...Qs.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),y$=Ba(N({applyDefaults:We().optional()}),ke(S(),Re())),_$=wp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ba(N({form:y$.optional(),url:Ze.optional()}),ke(S(),Re()).optional())),x$=dt({list:Ze.optional(),cancel:Ze.optional(),requests:dt({sampling:dt({createMessage:Ze.optional()}).optional(),elicitation:dt({create:Ze.optional()}).optional()}).optional()}),b$=dt({list:Ze.optional(),cancel:Ze.optional(),requests:dt({tools:dt({call:Ze.optional()}).optional()}).optional()}),S$=N({experimental:ke(S(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:_$.optional(),roots:N({listChanged:We().optional()}).optional(),tasks:x$.optional(),extensions:ke(S(),Ze).optional()}),k$=Nt.extend({protocolVersion:S(),capabilities:S$,clientInfo:Ex}),Ip=Xe.extend({method:U("initialize"),params:k$});var v$=N({experimental:ke(S(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:We().optional()}).optional(),resources:N({subscribe:We().optional(),listChanged:We().optional()}).optional(),tools:N({listChanged:We().optional()}).optional(),tasks:b$.optional(),extensions:ke(S(),Ze).optional()}),E$=Ye.extend({protocolVersion:S(),capabilities:v$,serverInfo:Ex,instructions:S().optional()}),Ap=Ht.extend({method:U("notifications/initialized"),params:zt.optional()});var Ga=Xe.extend({method:U("ping"),params:Nt.optional()}),w$=N({progress:fe(),total:Ce(fe()),message:Ce(S())}),T$=N({...zt.shape,...w$.shape,progressToken:gx}),Ja=Ht.extend({method:U("notifications/progress"),params:T$}),P$=Nt.extend({cursor:yx.optional()}),ei=Xe.extend({params:P$.optional()}),ti=Ye.extend({nextCursor:yx.optional()}),R$=kt(["working","input_required","completed","failed","cancelled"]),ni=N({taskId:S(),status:R$,ttl:ve([fe(),ax()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ce(fe()),statusMessage:Ce(S())}),zo=Ye.extend({task:ni}),C$=zt.merge(ni),ri=Ht.extend({method:U("notifications/tasks/status"),params:C$}),Xa=Xe.extend({method:U("tasks/get"),params:Nt.extend({taskId:S()})}),Ya=Ye.merge(ni),Qa=Xe.extend({method:U("tasks/result"),params:Nt.extend({taskId:S()})}),i2=Ye.loose(),ec=ei.extend({method:U("tasks/list")}),tc=ti.extend({tasks:ae(ni)}),nc=Xe.extend({method:U("tasks/cancel"),params:Nt.extend({taskId:S()})}),wx=Ye.merge(ni),Tx=N({uri:S(),mimeType:Ce(S()),_meta:ke(S(),Re()).optional()}),Px=Tx.extend({text:S()}),Np=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Rx=Tx.extend({blob:Np}),oi=kt(["user","assistant"]),Ho=N({audience:ae(oi).optional(),priority:fe().min(0).max(1).optional(),lastModified:Gs.datetime({offset:!0}).optional()}),Cx=N({...Lo.shape,...Qs.shape,uri:S(),description:Ce(S()),mimeType:Ce(S()),size:Ce(fe()),annotations:Ho.optional(),_meta:Ce(dt({}))}),$$=N({...Lo.shape,...Qs.shape,uriTemplate:S(),description:Ce(S()),mimeType:Ce(S()),annotations:Ho.optional(),_meta:Ce(dt({}))}),Uo=ei.extend({method:U("resources/list")}),O$=ti.extend({resources:ae(Cx)}),Fo=ei.extend({method:U("resources/templates/list")}),I$=ti.extend({resourceTemplates:ae($$)}),Dp=Nt.extend({uri:S()}),A$=Dp,rc=Xe.extend({method:U("resources/read"),params:A$}),N$=Ye.extend({contents:ae(ve([Px,Rx]))}),D$=Ht.extend({method:U("notifications/resources/list_changed"),params:zt.optional()}),M$=Dp,j$=Xe.extend({method:U("resources/subscribe"),params:M$}),L$=Dp,z$=Xe.extend({method:U("resources/unsubscribe"),params:L$}),H$=zt.extend({uri:S()}),U$=Ht.extend({method:U("notifications/resources/updated"),params:H$}),F$=N({name:S(),description:Ce(S()),required:Ce(We())}),B$=N({...Lo.shape,...Qs.shape,description:Ce(S()),arguments:Ce(ae(F$)),_meta:Ce(dt({}))}),Bo=ei.extend({method:U("prompts/list")}),Z$=ti.extend({prompts:ae(B$)}),q$=Nt.extend({name:S(),arguments:ke(S(),S()).optional()}),oc=Xe.extend({method:U("prompts/get"),params:q$}),Mp=N({type:U("text"),text:S(),annotations:Ho.optional(),_meta:ke(S(),Re()).optional()}),jp=N({type:U("image"),data:Np,mimeType:S(),annotations:Ho.optional(),_meta:ke(S(),Re()).optional()}),Lp=N({type:U("audio"),data:Np,mimeType:S(),annotations:Ho.optional(),_meta:ke(S(),Re()).optional()}),V$=N({type:U("tool_use"),name:S(),id:S(),input:ke(S(),Re()),_meta:ke(S(),Re()).optional()}),W$=N({type:U("resource"),resource:ve([Px,Rx]),annotations:Ho.optional(),_meta:ke(S(),Re()).optional()}),K$=Cx.extend({type:U("resource_link")}),zp=ve([Mp,jp,Lp,K$,W$]),G$=N({role:oi,content:zp}),J$=Ye.extend({description:S().optional(),messages:ae(G$)}),X$=Ht.extend({method:U("notifications/prompts/list_changed"),params:zt.optional()}),Y$=N({title:S().optional(),readOnlyHint:We().optional(),destructiveHint:We().optional(),idempotentHint:We().optional(),openWorldHint:We().optional()}),Q$=N({taskSupport:kt(["required","optional","forbidden"]).optional()}),$x=N({...Lo.shape,...Qs.shape,description:S().optional(),inputSchema:N({type:U("object"),properties:ke(S(),Ze).optional(),required:ae(S()).optional()}).catchall(Re()),outputSchema:N({type:U("object"),properties:ke(S(),Ze).optional(),required:ae(S()).optional()}).catchall(Re()).optional(),annotations:Y$.optional(),execution:Q$.optional(),_meta:ke(S(),Re()).optional()}),Kr=ei.extend({method:U("tools/list")}),eO=ti.extend({tools:ae($x)}),sc=Ye.extend({content:ae(zp).default([]),structuredContent:ke(S(),Re()).optional(),isError:We().optional()}),a2=sc.or(Ye.extend({toolResult:Re()})),tO=Xs.extend({name:S(),arguments:ke(S(),Re()).optional()}),Zo=Xe.extend({method:U("tools/call"),params:tO}),nO=Ht.extend({method:U("notifications/tools/list_changed"),params:zt.optional()}),c2=N({autoRefresh:We().default(!0),debounceMs:fe().int().nonnegative().default(300)}),si=kt(["debug","info","notice","warning","error","critical","alert","emergency"]),rO=Nt.extend({level:si}),Hp=Xe.extend({method:U("logging/setLevel"),params:rO}),oO=zt.extend({level:si,logger:S().optional(),data:Re()}),sO=Ht.extend({method:U("notifications/message"),params:oO}),iO=N({name:S().optional()}),aO=N({hints:ae(iO).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),cO=N({mode:kt(["auto","required","none"]).optional()}),uO=N({type:U("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ae(zp).default([]),structuredContent:N({}).loose().optional(),isError:We().optional(),_meta:ke(S(),Re()).optional()}),lO=Ep("type",[Mp,jp,Lp]),Za=Ep("type",[Mp,jp,Lp,V$,uO]),dO=N({role:oi,content:ve([Za,ae(Za)]),_meta:ke(S(),Re()).optional()}),pO=Xs.extend({messages:ae(dO),modelPreferences:aO.optional(),systemPrompt:S().optional(),includeContext:kt(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ae(S()).optional(),metadata:Ze.optional(),tools:ae($x).optional(),toolChoice:cO.optional()}),fO=Xe.extend({method:U("sampling/createMessage"),params:pO}),ii=Ye.extend({model:S(),stopReason:Ce(kt(["endTurn","stopSequence","maxTokens"]).or(S())),role:oi,content:lO}),Up=Ye.extend({model:S(),stopReason:Ce(kt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:oi,content:ve([Za,ae(Za)])}),mO=N({type:U("boolean"),title:S().optional(),description:S().optional(),default:We().optional()}),hO=N({type:U("string"),title:S().optional(),description:S().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:kt(["email","uri","date","date-time"]).optional(),default:S().optional()}),gO=N({type:kt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),yO=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ae(S()),default:S().optional()}),_O=N({type:U("string"),title:S().optional(),description:S().optional(),oneOf:ae(N({const:S(),title:S()})),default:S().optional()}),xO=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ae(S()),enumNames:ae(S()).optional(),default:S().optional()}),bO=ve([yO,_O]),SO=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ae(S())}),default:ae(S()).optional()}),kO=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ae(N({const:S(),title:S()}))}),default:ae(S()).optional()}),vO=ve([SO,kO]),EO=ve([xO,bO,vO]),wO=ve([EO,mO,hO,gO]),TO=Xs.extend({mode:U("form").optional(),message:S(),requestedSchema:N({type:U("object"),properties:ke(S(),wO),required:ae(S()).optional()})}),PO=Xs.extend({mode:U("url"),message:S(),elicitationId:S(),url:S().url()}),RO=ve([TO,PO]),CO=Xe.extend({method:U("elicitation/create"),params:RO}),$O=zt.extend({elicitationId:S()}),OO=Ht.extend({method:U("notifications/elicitation/complete"),params:$O}),qo=Ye.extend({action:kt(["accept","decline","cancel"]),content:wp(t=>t===null?void 0:t,ke(S(),ve([S(),fe(),We(),ae(S())])).optional())}),IO=N({type:U("ref/resource"),uri:S()});var AO=N({type:U("ref/prompt"),name:S()}),NO=Nt.extend({ref:ve([AO,IO]),argument:N({name:S(),value:S()}),context:N({arguments:ke(S(),S()).optional()}).optional()}),ic=Xe.extend({method:U("completion/complete"),params:NO});function Ox(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Ix(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var DO=Ye.extend({completion:dt({values:ae(S()).max(100),total:Ce(fe().int()),hasMore:Ce(We())})}),MO=N({uri:S().startsWith("file://"),name:S().optional(),_meta:ke(S(),Re()).optional()}),jO=Xe.extend({method:U("roots/list"),params:Nt.optional()}),Fp=Ye.extend({roots:ae(MO)}),LO=Ht.extend({method:U("notifications/roots/list_changed"),params:zt.optional()}),u2=ve([Ga,Ip,ic,Hp,oc,Bo,Uo,Fo,rc,j$,z$,Zo,Kr,Xa,Qa,ec,nc]),l2=ve([Ka,Ja,Ap,LO,ri]),d2=ve([Wa,ii,Up,qo,Fp,Ya,tc,zo]),p2=ve([Ga,fO,CO,jO,Xa,Qa,ec,nc]),f2=ve([Ka,Ja,sO,U$,D$,nO,X$,ri,OO]),m2=ve([Wa,E$,DO,J$,Z$,O$,I$,N$,sc,eO,Ya,tc,zo]),z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===B.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new Tp(o.elicitations,n)}return new t(e,n,r)}},Tp=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function sr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Nx=Symbol("Let zodToJsonSchema decide on which parser to use");var Ax={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"},Dx=t=>typeof t=="string"?{...Ax,name:t}:{...Ax,...t};var Mx=t=>{let e=Dx(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Bp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ce(t,e,n,r,o){t[e]=n,Bp(t,e,r,o)}var ac=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].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"?ac(e,t.currentPath):e.join("/")}}function jx(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(n,"minItems",t.exactLength.value,t.exactLength.message,e),ce(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function Lx(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ce(n,"minimum",r.value,r.message,e):ce(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ce(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ce(n,"maximum",r.value,r.message,e):ce(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ce(n,"maximum",r.value,r.message,e));break;case"multipleOf":ce(n,"multipleOf",r.value,r.message,e);break}return n}function zx(){return{type:"boolean"}}function cc(t,e){return K(t.type._def,e)}var Hx=(t,e)=>K(t.innerType._def,e);function Zp(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Zp(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return zO(t,e)}}var zO=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ce(n,"minimum",r.value,r.message,e);break;case"max":ce(n,"maximum",r.value,r.message,e);break}return n};function Ux(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function Fx(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):$e(e)}function Bx(t){return{type:"string",enum:Array.from(t.values)}}var HO=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Zx(t,e){let n=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(HO(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}function qx(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var qp,nn={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:()=>(qp===void 0&&(qp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qp),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 uc(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ce(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ce(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":rn(n,"email",r.message,e);break;case"format:idn-email":rn(n,"idn-email",r.message,e);break;case"pattern:zod":pt(n,nn.email,r.message,e);break}break;case"url":rn(n,"uri",r.message,e);break;case"uuid":rn(n,"uuid",r.message,e);break;case"regex":pt(n,r.regex,r.message,e);break;case"cuid":pt(n,nn.cuid,r.message,e);break;case"cuid2":pt(n,nn.cuid2,r.message,e);break;case"startsWith":pt(n,RegExp(`^${Vp(r.value,e)}`),r.message,e);break;case"endsWith":pt(n,RegExp(`${Vp(r.value,e)}$`),r.message,e);break;case"datetime":rn(n,"date-time",r.message,e);break;case"date":rn(n,"date",r.message,e);break;case"time":rn(n,"time",r.message,e);break;case"duration":rn(n,"duration",r.message,e);break;case"length":ce(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ce(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{pt(n,RegExp(Vp(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&rn(n,"ipv4",r.message,e),r.version!=="v4"&&rn(n,"ipv6",r.message,e);break}case"base64url":pt(n,nn.base64url,r.message,e);break;case"jwt":pt(n,nn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&pt(n,nn.ipv4Cidr,r.message,e),r.version!=="v4"&&pt(n,nn.ipv6Cidr,r.message,e);break}case"emoji":pt(n,nn.emoji(),r.message,e);break;case"ulid":{pt(n,nn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{rn(n,"binary",r.message,e);break}case"contentEncoding:base64":{ce(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{pt(n,nn.base64,r.message,e);break}}break}case"nanoid":pt(n,nn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Vp(t,e){return e.patternStrategy==="escape"?FO(t):t}var UO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function FO(t){let e="";for(let n=0;n<t.length;n++)UO.has(t[n])||(e+="\\"),e+=t[n];return e}function rn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ce(t,"format",e,n,r)}function pt(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:Vx(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ce(t,"pattern",Vx(e,r),n,r)}function Vx(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
223
+ 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(r.external){let m=r.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&&r.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}`),r.external?.uri){let l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=r.external.uri(l)}Object.assign(c,o.def);let u=r.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}r.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 gp(t,e){if(t instanceof Vs){let r=new La(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;r.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]=r.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let n=new La(e);return n.process(t),n.emit(t,e)}function Be(t,e){let n=e??{seen:new Set};if(n.seen.has(t))return!1;n.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 Be(o.element,n);case"object":{for(let s in o.shape)if(Be(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(Be(s,n))return!0;return!1}case"intersection":return Be(o.left,n)||Be(o.right,n);case"tuple":{for(let s of o.items)if(Be(s,n))return!0;return!!(o.rest&&Be(o.rest,n))}case"record":return Be(o.keyType,n)||Be(o.valueType,n);case"map":return Be(o.keyType,n)||Be(o.valueType,n);case"set":return Be(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Be(o.innerType,n);case"lazy":return Be(o.getter(),n);case"default":return Be(o.innerType,n);case"prefault":return Be(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Be(o.in,n)||Be(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var fC=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");he.init(t,e),t.def=e,t.parse=(n,r)=>Nl(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Fr(t,n,r),t.parseAsync=async(n,r)=>Ml(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>Br(t,n,r),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>At(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var mC=k("ZodMiniObject",(t,e)=>{$a.init(t,e),fC.init(t,e),ie.defineLazy(t,"shape",()=>e.shape)});function yp(t,e){let n={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new mC(n)}function xn(t){return!!t._zod}function Vr(t){let e=Object.values(t);if(e.length===0)return yp({});let n=e.every(xn),r=e.every(o=>!xn(o));if(n)return yp(t);if(r)return bl(t);throw new Error("Mixed Zod versions detected in object shape.")}function tr(t,e){return xn(t)?Fr(t,e):t.safeParse(e)}async function za(t,e){return xn(t)?await Br(t,e):await t.safeParseAsync(e)}function nr(t){if(!t)return;let e;if(xn(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function No(t){if(t){if(typeof t=="object"){let e=t,n=t;if(!e._def&&!n._zod){let r=Object.values(t);if(r.length>0&&r.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Vr(t)}}if(xn(t)){let n=t._zod?.def;if(n&&(n.type==="object"||n.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function gC(t){return t.length===0?"object root":t.reduce((e,n,r)=>r===0?String(n):typeof n=="number"?`${e}[${n}]`:`${e}.${n}`,"")}function Ha(t){if(t&&typeof t=="object"){if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0)return t.issues.map(e=>e.path?.length?`${e.message} at ${gC(e.path)}`:e.message).join(`
224
+ `);if("message"in t&&typeof t.message=="string")return t.message;try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function Z_(t){return t.description}function q_(t){if(xn(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Do(t){if(xn(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 n=t._def;if(n){if(n.value!==void 0)return n.value;if(Array.isArray(n.values)&&n.values.length>0)return n.values[0]}let r=t.value;if(r!==void 0)return r}var Gs={};je(Gs,{ZodISODate:()=>W_,ZodISODateTime:()=>V_,ZodISODuration:()=>G_,ZodISOTime:()=>K_,date:()=>xp,datetime:()=>_p,duration:()=>Sp,time:()=>bp});var V_=k("ZodISODateTime",(t,e)=>{O_.init(t,e),Pe.init(t,e)});function _p(t){return L_(V_,t)}var W_=k("ZodISODate",(t,e)=>{I_.init(t,e),Pe.init(t,e)});function xp(t){return z_(W_,t)}var K_=k("ZodISOTime",(t,e)=>{A_.init(t,e),Pe.init(t,e)});function bp(t){return H_(K_,t)}var G_=k("ZodISODuration",(t,e)=>{N_.init(t,e),Pe.init(t,e)});function Sp(t){return U_(G_,t)}var J_=(t,e)=>{wa.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>Il(t,n)},flatten:{value:n=>Ol(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},qZ=k("ZodError",J_),Js=k("ZodError",J_,{Parent:Error});var X_=Al(Js),Y_=Dl(Js),Q_=jl(Js),ex=Ll(Js);var Oe=k("ZodType",(t,e)=>(he.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...n)=>t.clone({...e,checks:[...e.checks??[],...n.map(r=>typeof r=="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),t.clone=(n,r)=>At(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>X_(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Q_(t,n,r),t.parseAsync=async(n,r)=>Y_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>ex(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(p$(n,r)),t.superRefine=n=>t.check(f$(n)),t.overwrite=n=>t.check(Zr(n)),t.optional=()=>Ce(t),t.nullable=()=>rx(t),t.nullish=()=>Ce(rx(t)),t.nonoptional=n=>s$(t,n),t.array=()=>ae(t),t.or=n=>ve([t,n]),t.and=n=>Fa(t,n),t.transform=n=>vp(t,ux(n)),t.default=n=>n$(t,n),t.prefault=n=>o$(t,n),t.catch=n=>a$(t,n),t.pipe=n=>vp(t,n),t.readonly=()=>l$(t),t.describe=n=>{let r=t.clone();return er.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return er.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return er.get(t);let r=t.clone();return er.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),ox=k("_ZodString",(t,e)=>{qs.init(t,e),Oe.init(t,e);let n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,t.regex=(...r)=>t.check(op(...r)),t.includes=(...r)=>t.check(ap(...r)),t.startsWith=(...r)=>t.check(cp(...r)),t.endsWith=(...r)=>t.check(up(...r)),t.min=(...r)=>t.check(Ao(...r)),t.max=(...r)=>t.check(Ma(...r)),t.length=(...r)=>t.check(ja(...r)),t.nonempty=(...r)=>t.check(Ao(1,...r)),t.lowercase=r=>t.check(sp(r)),t.uppercase=r=>t.check(ip(r)),t.trim=()=>t.check(dp()),t.normalize=(...r)=>t.check(lp(...r)),t.toLowerCase=()=>t.check(pp()),t.toUpperCase=()=>t.check(fp())}),EC=k("ZodString",(t,e)=>{qs.init(t,e),ox.init(t,e),t.email=n=>t.check(Od(wC,n)),t.url=n=>t.check(Md(TC,n)),t.jwt=n=>t.check(Xd(UC,n)),t.emoji=n=>t.check(jd(PC,n)),t.guid=n=>t.check(Ia(tx,n)),t.uuid=n=>t.check(Id(Ua,n)),t.uuidv4=n=>t.check(Ad(Ua,n)),t.uuidv6=n=>t.check(Nd(Ua,n)),t.uuidv7=n=>t.check(Dd(Ua,n)),t.nanoid=n=>t.check(Ld(RC,n)),t.guid=n=>t.check(Ia(tx,n)),t.cuid=n=>t.check(zd(CC,n)),t.cuid2=n=>t.check(Hd($C,n)),t.ulid=n=>t.check(Ud(OC,n)),t.base64=n=>t.check(Kd(LC,n)),t.base64url=n=>t.check(Gd(zC,n)),t.xid=n=>t.check(Fd(IC,n)),t.ksuid=n=>t.check(Bd(AC,n)),t.ipv4=n=>t.check(Zd(NC,n)),t.ipv6=n=>t.check(qd(DC,n)),t.cidrv4=n=>t.check(Vd(MC,n)),t.cidrv6=n=>t.check(Wd(jC,n)),t.e164=n=>t.check(Jd(HC,n)),t.datetime=n=>t.check(_p(n)),t.date=n=>t.check(xp(n)),t.time=n=>t.check(bp(n)),t.duration=n=>t.check(Sp(n))});function S(t){return $d(EC,t)}var Pe=k("ZodStringFormat",(t,e)=>{Se.init(t,e),ox.init(t,e)}),wC=k("ZodEmail",(t,e)=>{Vl.init(t,e),Pe.init(t,e)});var tx=k("ZodGUID",(t,e)=>{Zl.init(t,e),Pe.init(t,e)});var Ua=k("ZodUUID",(t,e)=>{ql.init(t,e),Pe.init(t,e)});var TC=k("ZodURL",(t,e)=>{Wl.init(t,e),Pe.init(t,e)});var PC=k("ZodEmoji",(t,e)=>{Kl.init(t,e),Pe.init(t,e)});var RC=k("ZodNanoID",(t,e)=>{Gl.init(t,e),Pe.init(t,e)});var CC=k("ZodCUID",(t,e)=>{Jl.init(t,e),Pe.init(t,e)});var $C=k("ZodCUID2",(t,e)=>{Xl.init(t,e),Pe.init(t,e)});var OC=k("ZodULID",(t,e)=>{Yl.init(t,e),Pe.init(t,e)});var IC=k("ZodXID",(t,e)=>{Ql.init(t,e),Pe.init(t,e)});var AC=k("ZodKSUID",(t,e)=>{ed.init(t,e),Pe.init(t,e)});var NC=k("ZodIPv4",(t,e)=>{td.init(t,e),Pe.init(t,e)});var DC=k("ZodIPv6",(t,e)=>{nd.init(t,e),Pe.init(t,e)});var MC=k("ZodCIDRv4",(t,e)=>{rd.init(t,e),Pe.init(t,e)});var jC=k("ZodCIDRv6",(t,e)=>{od.init(t,e),Pe.init(t,e)});var LC=k("ZodBase64",(t,e)=>{sd.init(t,e),Pe.init(t,e)});var zC=k("ZodBase64URL",(t,e)=>{id.init(t,e),Pe.init(t,e)});var HC=k("ZodE164",(t,e)=>{ad.init(t,e),Pe.init(t,e)});var UC=k("ZodJWT",(t,e)=>{cd.init(t,e),Pe.init(t,e)});var sx=k("ZodNumber",(t,e)=>{Ca.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(Na(r,o)),t.gte=(r,o)=>t.check(Ks(r,o)),t.min=(r,o)=>t.check(Ks(r,o)),t.lt=(r,o)=>t.check(Aa(r,o)),t.lte=(r,o)=>t.check(Ws(r,o)),t.max=(r,o)=>t.check(Ws(r,o)),t.int=r=>t.check(nx(r)),t.safe=r=>t.check(nx(r)),t.positive=r=>t.check(Na(0,r)),t.nonnegative=r=>t.check(Ks(0,r)),t.negative=r=>t.check(Aa(0,r)),t.nonpositive=r=>t.check(Ws(0,r)),t.multipleOf=(r,o)=>t.check(Da(r,o)),t.step=(r,o)=>t.check(Da(r,o)),t.finite=()=>t;let n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function fe(t){return Yd(sx,t)}var FC=k("ZodNumberFormat",(t,e)=>{ud.init(t,e),sx.init(t,e)});function nx(t){return Qd(FC,t)}var BC=k("ZodBoolean",(t,e)=>{ld.init(t,e),Oe.init(t,e)});function We(t){return ep(BC,t)}var ZC=k("ZodNull",(t,e)=>{dd.init(t,e),Oe.init(t,e)});function ix(t){return tp(ZC,t)}var qC=k("ZodUnknown",(t,e)=>{pd.init(t,e),Oe.init(t,e)});function Re(){return np(qC)}var VC=k("ZodNever",(t,e)=>{fd.init(t,e),Oe.init(t,e)});function WC(t){return rp(VC,t)}var KC=k("ZodArray",(t,e)=>{md.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Ao(n,r)),t.nonempty=n=>t.check(Ao(1,n)),t.max=(n,r)=>t.check(Ma(n,r)),t.length=(n,r)=>t.check(ja(n,r)),t.unwrap=()=>t.element});function ae(t,e){return F_(KC,t,e)}var ax=k("ZodObject",(t,e)=>{$a.init(t,e),Oe.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>kt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Re()}),t.loose=()=>t.clone({...t._zod.def,catchall:Re()}),t.strict=()=>t.clone({...t._zod.def,catchall:WC()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>ie.extend(t,n),t.merge=n=>ie.merge(t,n),t.pick=n=>ie.pick(t,n),t.omit=n=>ie.omit(t,n),t.partial=(...n)=>ie.partial(lx,t,n[0]),t.required=(...n)=>ie.required(dx,t,n[0])});function N(t,e){let n={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new ax(n)}function dt(t,e){return new ax({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:Re(),...ie.normalizeParams(e)})}var cx=k("ZodUnion",(t,e)=>{Oa.init(t,e),Oe.init(t,e),t.options=e.options});function ve(t,e){return new cx({type:"union",options:t,...ie.normalizeParams(e)})}var GC=k("ZodDiscriminatedUnion",(t,e)=>{cx.init(t,e),hd.init(t,e)});function Ep(t,e,n){return new GC({type:"union",options:e,discriminator:t,...ie.normalizeParams(n)})}var JC=k("ZodIntersection",(t,e)=>{gd.init(t,e),Oe.init(t,e)});function Fa(t,e){return new JC({type:"intersection",left:t,right:e})}var XC=k("ZodRecord",(t,e)=>{yd.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function ke(t,e,n){return new XC({type:"record",keyType:t,valueType:e,...ie.normalizeParams(n)})}var kp=k("ZodEnum",(t,e)=>{_d.init(t,e),Oe.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let n=new Set(Object.keys(e.entries));t.extract=(r,o)=>{let s={};for(let i of r)if(n.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new kp({...e,checks:[],...ie.normalizeParams(o),entries:s})},t.exclude=(r,o)=>{let s={...e.entries};for(let i of r)if(n.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new kp({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function kt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new kp({type:"enum",entries:n,...ie.normalizeParams(e)})}var YC=k("ZodLiteral",(t,e)=>{xd.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 YC({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var QC=k("ZodTransform",(t,e)=>{bd.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(ie.issue(s,n.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=n.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),n.issues.push(ie.issue(i))}};let o=e.transform(n.value,n);return o instanceof Promise?o.then(s=>(n.value=s,n)):(n.value=o,n)}});function ux(t){return new QC({type:"transform",transform:t})}var lx=k("ZodOptional",(t,e)=>{Sd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new lx({type:"optional",innerType:t})}var e$=k("ZodNullable",(t,e)=>{kd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function rx(t){return new e$({type:"nullable",innerType:t})}var t$=k("ZodDefault",(t,e)=>{vd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function n$(t,e){return new t$({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var r$=k("ZodPrefault",(t,e)=>{Ed.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function o$(t,e){return new r$({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var dx=k("ZodNonOptional",(t,e)=>{wd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function s$(t,e){return new dx({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var i$=k("ZodCatch",(t,e)=>{Td.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function a$(t,e){return new i$({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var c$=k("ZodPipe",(t,e)=>{Pd.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function vp(t,e){return new c$({type:"pipe",in:t,out:e})}var u$=k("ZodReadonly",(t,e)=>{Rd.init(t,e),Oe.init(t,e)});function l$(t){return new u$({type:"readonly",innerType:t})}var px=k("ZodCustom",(t,e)=>{Cd.init(t,e),Oe.init(t,e)});function d$(t){let e=new Je({check:"custom"});return e._zod.check=t,e}function fx(t,e){return mp(px,t??(()=>!0),e)}function p$(t,e={}){return hp(px,t,e)}function f$(t){let e=d$(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(ie.issue(r,n.value,e._zod.def));else{let o=r;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=n.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),n.issues.push(ie.issue(o))}},t(n.value,n)));return e}function wp(t,e){return vp(ux(t),e)}It(M_());var Pp="2025-11-25";var mx=[Pp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],rr="io.modelcontextprotocol/related-task",Za="2.0",Ze=fx(t=>t!==null&&(typeof t=="object"||typeof t=="function")),hx=ve([S(),fe().int()]),gx=S(),s2=dt({ttl:fe().optional(),pollInterval:fe().optional()}),m$=N({ttl:fe().optional()}),h$=N({taskId:S()}),Rp=dt({progressToken:hx.optional(),[rr]:h$.optional()}),Nt=N({_meta:Rp.optional()}),Xs=Nt.extend({task:m$.optional()}),yx=t=>Xs.safeParse(t).success,Xe=N({method:S(),params:Nt.loose().optional()}),zt=N({_meta:Rp.optional()}),Ht=N({method:S(),params:zt.loose().optional()}),Ye=dt({_meta:Rp.optional()}),qa=ve([S(),fe().int()]),_x=N({jsonrpc:U(Za),id:qa,...Xe.shape}).strict(),Cp=t=>_x.safeParse(t).success,xx=N({jsonrpc:U(Za),...Ht.shape}).strict(),bx=t=>xx.safeParse(t).success,$p=N({jsonrpc:U(Za),id:qa,result:Ye}).strict(),Ys=t=>$p.safeParse(t).success;var B;(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"})(B||(B={}));var Op=N({jsonrpc:U(Za),id:qa.optional(),error:N({code:fe().int(),message:S(),data:Re().optional()})}).strict();var Sx=t=>Op.safeParse(t).success;var kx=ve([_x,xx,$p,Op]),i2=ve([$p,Op]),Va=Ye.strict(),g$=zt.extend({requestId:qa.optional(),reason:S().optional()}),Wa=Ht.extend({method:U("notifications/cancelled"),params:g$}),y$=N({src:S(),mimeType:S().optional(),sizes:ae(S()).optional(),theme:kt(["light","dark"]).optional()}),Qs=N({icons:ae(y$).optional()}),Mo=N({name:S(),title:S().optional()}),vx=Mo.extend({...Mo.shape,...Qs.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),_$=Fa(N({applyDefaults:We().optional()}),ke(S(),Re())),x$=wp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Fa(N({form:_$.optional(),url:Ze.optional()}),ke(S(),Re()).optional())),b$=dt({list:Ze.optional(),cancel:Ze.optional(),requests:dt({sampling:dt({createMessage:Ze.optional()}).optional(),elicitation:dt({create:Ze.optional()}).optional()}).optional()}),S$=dt({list:Ze.optional(),cancel:Ze.optional(),requests:dt({tools:dt({call:Ze.optional()}).optional()}).optional()}),k$=N({experimental:ke(S(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:x$.optional(),roots:N({listChanged:We().optional()}).optional(),tasks:b$.optional(),extensions:ke(S(),Ze).optional()}),v$=Nt.extend({protocolVersion:S(),capabilities:k$,clientInfo:vx}),Ip=Xe.extend({method:U("initialize"),params:v$});var E$=N({experimental:ke(S(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:We().optional()}).optional(),resources:N({subscribe:We().optional(),listChanged:We().optional()}).optional(),tools:N({listChanged:We().optional()}).optional(),tasks:S$.optional(),extensions:ke(S(),Ze).optional()}),w$=Ye.extend({protocolVersion:S(),capabilities:E$,serverInfo:vx,instructions:S().optional()}),Ap=Ht.extend({method:U("notifications/initialized"),params:zt.optional()});var Ka=Xe.extend({method:U("ping"),params:Nt.optional()}),T$=N({progress:fe(),total:Ce(fe()),message:Ce(S())}),P$=N({...zt.shape,...T$.shape,progressToken:hx}),Ga=Ht.extend({method:U("notifications/progress"),params:P$}),R$=Nt.extend({cursor:gx.optional()}),ei=Xe.extend({params:R$.optional()}),ti=Ye.extend({nextCursor:gx.optional()}),C$=kt(["working","input_required","completed","failed","cancelled"]),ni=N({taskId:S(),status:C$,ttl:ve([fe(),ix()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ce(fe()),statusMessage:Ce(S())}),jo=Ye.extend({task:ni}),$$=zt.merge(ni),ri=Ht.extend({method:U("notifications/tasks/status"),params:$$}),Ja=Xe.extend({method:U("tasks/get"),params:Nt.extend({taskId:S()})}),Xa=Ye.merge(ni),Ya=Xe.extend({method:U("tasks/result"),params:Nt.extend({taskId:S()})}),a2=Ye.loose(),Qa=ei.extend({method:U("tasks/list")}),ec=ti.extend({tasks:ae(ni)}),tc=Xe.extend({method:U("tasks/cancel"),params:Nt.extend({taskId:S()})}),Ex=Ye.merge(ni),wx=N({uri:S(),mimeType:Ce(S()),_meta:ke(S(),Re()).optional()}),Tx=wx.extend({text:S()}),Np=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Px=wx.extend({blob:Np}),oi=kt(["user","assistant"]),Lo=N({audience:ae(oi).optional(),priority:fe().min(0).max(1).optional(),lastModified:Gs.datetime({offset:!0}).optional()}),Rx=N({...Mo.shape,...Qs.shape,uri:S(),description:Ce(S()),mimeType:Ce(S()),size:Ce(fe()),annotations:Lo.optional(),_meta:Ce(dt({}))}),O$=N({...Mo.shape,...Qs.shape,uriTemplate:S(),description:Ce(S()),mimeType:Ce(S()),annotations:Lo.optional(),_meta:Ce(dt({}))}),zo=ei.extend({method:U("resources/list")}),I$=ti.extend({resources:ae(Rx)}),Ho=ei.extend({method:U("resources/templates/list")}),A$=ti.extend({resourceTemplates:ae(O$)}),Dp=Nt.extend({uri:S()}),N$=Dp,nc=Xe.extend({method:U("resources/read"),params:N$}),D$=Ye.extend({contents:ae(ve([Tx,Px]))}),M$=Ht.extend({method:U("notifications/resources/list_changed"),params:zt.optional()}),j$=Dp,L$=Xe.extend({method:U("resources/subscribe"),params:j$}),z$=Dp,H$=Xe.extend({method:U("resources/unsubscribe"),params:z$}),U$=zt.extend({uri:S()}),F$=Ht.extend({method:U("notifications/resources/updated"),params:U$}),B$=N({name:S(),description:Ce(S()),required:Ce(We())}),Z$=N({...Mo.shape,...Qs.shape,description:Ce(S()),arguments:Ce(ae(B$)),_meta:Ce(dt({}))}),Uo=ei.extend({method:U("prompts/list")}),q$=ti.extend({prompts:ae(Z$)}),V$=Nt.extend({name:S(),arguments:ke(S(),S()).optional()}),rc=Xe.extend({method:U("prompts/get"),params:V$}),Mp=N({type:U("text"),text:S(),annotations:Lo.optional(),_meta:ke(S(),Re()).optional()}),jp=N({type:U("image"),data:Np,mimeType:S(),annotations:Lo.optional(),_meta:ke(S(),Re()).optional()}),Lp=N({type:U("audio"),data:Np,mimeType:S(),annotations:Lo.optional(),_meta:ke(S(),Re()).optional()}),W$=N({type:U("tool_use"),name:S(),id:S(),input:ke(S(),Re()),_meta:ke(S(),Re()).optional()}),K$=N({type:U("resource"),resource:ve([Tx,Px]),annotations:Lo.optional(),_meta:ke(S(),Re()).optional()}),G$=Rx.extend({type:U("resource_link")}),zp=ve([Mp,jp,Lp,G$,K$]),J$=N({role:oi,content:zp}),X$=Ye.extend({description:S().optional(),messages:ae(J$)}),Y$=Ht.extend({method:U("notifications/prompts/list_changed"),params:zt.optional()}),Q$=N({title:S().optional(),readOnlyHint:We().optional(),destructiveHint:We().optional(),idempotentHint:We().optional(),openWorldHint:We().optional()}),eO=N({taskSupport:kt(["required","optional","forbidden"]).optional()}),Cx=N({...Mo.shape,...Qs.shape,description:S().optional(),inputSchema:N({type:U("object"),properties:ke(S(),Ze).optional(),required:ae(S()).optional()}).catchall(Re()),outputSchema:N({type:U("object"),properties:ke(S(),Ze).optional(),required:ae(S()).optional()}).catchall(Re()).optional(),annotations:Q$.optional(),execution:eO.optional(),_meta:ke(S(),Re()).optional()}),Wr=ei.extend({method:U("tools/list")}),tO=ti.extend({tools:ae(Cx)}),oc=Ye.extend({content:ae(zp).default([]),structuredContent:ke(S(),Re()).optional(),isError:We().optional()}),c2=oc.or(Ye.extend({toolResult:Re()})),nO=Xs.extend({name:S(),arguments:ke(S(),Re()).optional()}),Fo=Xe.extend({method:U("tools/call"),params:nO}),rO=Ht.extend({method:U("notifications/tools/list_changed"),params:zt.optional()}),u2=N({autoRefresh:We().default(!0),debounceMs:fe().int().nonnegative().default(300)}),si=kt(["debug","info","notice","warning","error","critical","alert","emergency"]),oO=Nt.extend({level:si}),Hp=Xe.extend({method:U("logging/setLevel"),params:oO}),sO=zt.extend({level:si,logger:S().optional(),data:Re()}),iO=Ht.extend({method:U("notifications/message"),params:sO}),aO=N({name:S().optional()}),cO=N({hints:ae(aO).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),uO=N({mode:kt(["auto","required","none"]).optional()}),lO=N({type:U("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ae(zp).default([]),structuredContent:N({}).loose().optional(),isError:We().optional(),_meta:ke(S(),Re()).optional()}),dO=Ep("type",[Mp,jp,Lp]),Ba=Ep("type",[Mp,jp,Lp,W$,lO]),pO=N({role:oi,content:ve([Ba,ae(Ba)]),_meta:ke(S(),Re()).optional()}),fO=Xs.extend({messages:ae(pO),modelPreferences:cO.optional(),systemPrompt:S().optional(),includeContext:kt(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ae(S()).optional(),metadata:Ze.optional(),tools:ae(Cx).optional(),toolChoice:uO.optional()}),mO=Xe.extend({method:U("sampling/createMessage"),params:fO}),ii=Ye.extend({model:S(),stopReason:Ce(kt(["endTurn","stopSequence","maxTokens"]).or(S())),role:oi,content:dO}),Up=Ye.extend({model:S(),stopReason:Ce(kt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:oi,content:ve([Ba,ae(Ba)])}),hO=N({type:U("boolean"),title:S().optional(),description:S().optional(),default:We().optional()}),gO=N({type:U("string"),title:S().optional(),description:S().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:kt(["email","uri","date","date-time"]).optional(),default:S().optional()}),yO=N({type:kt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),_O=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ae(S()),default:S().optional()}),xO=N({type:U("string"),title:S().optional(),description:S().optional(),oneOf:ae(N({const:S(),title:S()})),default:S().optional()}),bO=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ae(S()),enumNames:ae(S()).optional(),default:S().optional()}),SO=ve([_O,xO]),kO=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ae(S())}),default:ae(S()).optional()}),vO=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ae(N({const:S(),title:S()}))}),default:ae(S()).optional()}),EO=ve([kO,vO]),wO=ve([bO,SO,EO]),TO=ve([wO,hO,gO,yO]),PO=Xs.extend({mode:U("form").optional(),message:S(),requestedSchema:N({type:U("object"),properties:ke(S(),TO),required:ae(S()).optional()})}),RO=Xs.extend({mode:U("url"),message:S(),elicitationId:S(),url:S().url()}),CO=ve([PO,RO]),$O=Xe.extend({method:U("elicitation/create"),params:CO}),OO=zt.extend({elicitationId:S()}),IO=Ht.extend({method:U("notifications/elicitation/complete"),params:OO}),Bo=Ye.extend({action:kt(["accept","decline","cancel"]),content:wp(t=>t===null?void 0:t,ke(S(),ve([S(),fe(),We(),ae(S())])).optional())}),AO=N({type:U("ref/resource"),uri:S()});var NO=N({type:U("ref/prompt"),name:S()}),DO=Nt.extend({ref:ve([NO,AO]),argument:N({name:S(),value:S()}),context:N({arguments:ke(S(),S()).optional()}).optional()}),sc=Xe.extend({method:U("completion/complete"),params:DO});function $x(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Ox(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var MO=Ye.extend({completion:dt({values:ae(S()).max(100),total:Ce(fe().int()),hasMore:Ce(We())})}),jO=N({uri:S().startsWith("file://"),name:S().optional(),_meta:ke(S(),Re()).optional()}),LO=Xe.extend({method:U("roots/list"),params:Nt.optional()}),Fp=Ye.extend({roots:ae(jO)}),zO=Ht.extend({method:U("notifications/roots/list_changed"),params:zt.optional()}),l2=ve([Ka,Ip,sc,Hp,rc,Uo,zo,Ho,nc,L$,H$,Fo,Wr,Ja,Ya,Qa,tc]),d2=ve([Wa,Ga,Ap,zO,ri]),p2=ve([Va,ii,Up,Bo,Fp,Xa,ec,jo]),f2=ve([Ka,mO,$O,LO,Ja,Ya,Qa,tc]),m2=ve([Wa,Ga,iO,F$,M$,rO,Y$,ri,IO]),h2=ve([Va,w$,MO,X$,q$,I$,A$,D$,oc,tO,Xa,ec,jo]),z=class t extends Error{constructor(e,n,r){super(`MCP error ${e}: ${n}`),this.code=e,this.data=r,this.name="McpError"}static fromError(e,n,r){if(e===B.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new Tp(o.elicitations,n)}return new t(e,n,r)}},Tp=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function or(t){return t==="completed"||t==="failed"||t==="cancelled"}var Ax=Symbol("Let zodToJsonSchema decide on which parser to use");var Ix={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"},Nx=t=>typeof t=="string"?{...Ix,name:t}:{...Ix,...t};var Dx=t=>{let e=Nx(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Bp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ce(t,e,n,r,o){t[e]=n,Bp(t,e,r,o)}var ic=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].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"?ic(e,t.currentPath):e.join("/")}}function Mx(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ce(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ce(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ce(n,"minItems",t.exactLength.value,t.exactLength.message,e),ce(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function jx(t,e){let n={type:"integer",format:"int64"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ce(n,"minimum",r.value,r.message,e):ce(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ce(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ce(n,"maximum",r.value,r.message,e):ce(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ce(n,"maximum",r.value,r.message,e));break;case"multipleOf":ce(n,"multipleOf",r.value,r.message,e);break}return n}function Lx(){return{type:"boolean"}}function ac(t,e){return K(t.type._def,e)}var zx=(t,e)=>K(t.innerType._def,e);function Zp(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Zp(t,e,o))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return HO(t,e)}}var HO=(t,e)=>{let n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(let r of t.checks)switch(r.kind){case"min":ce(n,"minimum",r.value,r.message,e);break;case"max":ce(n,"maximum",r.value,r.message,e);break}return n};function Hx(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function Ux(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):$e(e)}function Fx(t){return{type:"string",enum:Array.from(t.values)}}var UO=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Bx(t,e){let n=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return n.forEach(s=>{if(UO(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else r=void 0;o.push(i)}}),o.length?{allOf:o,...r}:void 0}function Zx(t,e){let n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}var qp,nn={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:()=>(qp===void 0&&(qp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),qp),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 cc(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ce(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ce(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":rn(n,"email",r.message,e);break;case"format:idn-email":rn(n,"idn-email",r.message,e);break;case"pattern:zod":pt(n,nn.email,r.message,e);break}break;case"url":rn(n,"uri",r.message,e);break;case"uuid":rn(n,"uuid",r.message,e);break;case"regex":pt(n,r.regex,r.message,e);break;case"cuid":pt(n,nn.cuid,r.message,e);break;case"cuid2":pt(n,nn.cuid2,r.message,e);break;case"startsWith":pt(n,RegExp(`^${Vp(r.value,e)}`),r.message,e);break;case"endsWith":pt(n,RegExp(`${Vp(r.value,e)}$`),r.message,e);break;case"datetime":rn(n,"date-time",r.message,e);break;case"date":rn(n,"date",r.message,e);break;case"time":rn(n,"time",r.message,e);break;case"duration":rn(n,"duration",r.message,e);break;case"length":ce(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ce(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{pt(n,RegExp(Vp(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&rn(n,"ipv4",r.message,e),r.version!=="v4"&&rn(n,"ipv6",r.message,e);break}case"base64url":pt(n,nn.base64url,r.message,e);break;case"jwt":pt(n,nn.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&pt(n,nn.ipv4Cidr,r.message,e),r.version!=="v4"&&pt(n,nn.ipv6Cidr,r.message,e);break}case"emoji":pt(n,nn.emoji(),r.message,e);break;case"ulid":{pt(n,nn.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{rn(n,"binary",r.message,e);break}case"contentEncoding:base64":{ce(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{pt(n,nn.base64,r.message,e);break}}break}case"nanoid":pt(n,nn.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Vp(t,e){return e.patternStrategy==="escape"?BO(t):t}var FO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function BO(t){let e="";for(let n=0;n<t.length;n++)FO.has(t[n])||(e+="\\"),e+=t[n];return e}function rn(t,e,n,r){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.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,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ce(t,"format",e,n,r)}function pt(t,e,n,r){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.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:qx(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ce(t,"pattern",qx(e,r),n,r)}function qx(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
225
225
  ]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
226
226
  ]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
227
227
  `:`[${r[c]}\r
228
- ]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[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 lc(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((r,o)=>({...r,[o]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=uc(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...n,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:r,...o}=cc(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function Wx(t,e){if(e.mapStrategy==="record")return lc(t,e);let n=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),r=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Kx(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function Gx(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function Jx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ai={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Yx(t,e){if(e.target==="openApi3")return Xx(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in ai&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=ai[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return Xx(t,e)}var Xx=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>K(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Qx(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:ai[t.innerType._def.typeName],nullable:!0}:{type:[ai[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function eb(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Bp(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ce(n,"minimum",r.value,r.message,e):ce(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ce(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ce(n,"maximum",r.value,r.message,e):ce(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ce(n,"maximum",r.value,r.message,e));break;case"multipleOf":ce(n,"multipleOf",r.value,r.message,e);break}return n}function tb(t,e){let n=e.target==="openAi",r={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=ZO(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=BO(t,e);return i!==void 0&&(r.additionalProperties=i),r}function BO(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 ZO(t){try{return t.isOptional()}catch{return!0}}var nb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:$e(e)},n]}:$e(e)};var rb=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let n=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function ob(t,e){return K(t.type._def,e)}function sb(t,e){let r={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function ib(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function ab(t){return{not:$e(t)}}function cb(t){return $e(t)}var ub=(t,e)=>K(t.innerType._def,e);var lb=(t,e,n)=>{switch(e){case T.ZodString:return uc(t,n);case T.ZodNumber:return eb(t,n);case T.ZodObject:return tb(t,n);case T.ZodBigInt:return Lx(t,n);case T.ZodBoolean:return zx();case T.ZodDate:return Zp(t,n);case T.ZodUndefined:return ab(n);case T.ZodNull:return Jx(n);case T.ZodArray:return jx(t,n);case T.ZodUnion:case T.ZodDiscriminatedUnion:return Yx(t,n);case T.ZodIntersection:return Zx(t,n);case T.ZodTuple:return ib(t,n);case T.ZodRecord:return lc(t,n);case T.ZodLiteral:return qx(t,n);case T.ZodEnum:return Bx(t);case T.ZodNativeEnum:return Kx(t);case T.ZodNullable:return Qx(t,n);case T.ZodOptional:return nb(t,n);case T.ZodMap:return Wx(t,n);case T.ZodSet:return sb(t,n);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return ob(t,n);case T.ZodNaN:case T.ZodNever:return Gx(n);case T.ZodEffects:return Fx(t,n);case T.ZodAny:return $e(n);case T.ZodUnknown:return cb(n);case T.ZodDefault:return Ux(t,n);case T.ZodBranded:return cc(t,n);case T.ZodReadonly:return ub(t,n);case T.ZodCatch:return Hx(t,n);case T.ZodPipeline:return rb(t,n);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(r=>{})(e)}};function K(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Nx)return a}if(r&&!n){let a=qO(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=lb(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&VO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var qO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ac(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},VO=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Wp=(t,e)=>{let n=Mx(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:K(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??$e(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=K(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??$e(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 WO(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Kp(t,e){return bn(t)?gp(t,{target:WO(e?.target),io:e?.pipeStrategy??"input"}):Wp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gp(t){let n=rr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=jo(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Jp(t,e){let n=nr(t,e);if(!n.success)throw n.error;return n.data}var KO=6e4,dc=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(Ka,n=>{this._oncancel(n)}),this.setNotificationHandler(Ja,n=>{this._onprogress(n)}),this.setRequestHandler(Ga,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Xa,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Qa,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new z(B.InvalidParams,`Task not found: ${s}`);if(!sr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(sr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[or]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(ec,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(nc,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(B.InvalidParams,`Task not found: ${n.params.taskId}`);if(sr(o.status))throw new z(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(B.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(B.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ys(s)||kx(s)?this._onresponse(s):Cp(s)?this._onrequest(s,i):Sx(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=z.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[or]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:B.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=_x(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(B.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:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:B.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Ys(e))r(e);else{let i=new z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(Ys(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,n))}}if(s||this._progressHandlers.delete(n),Ys(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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(B.InternalError,String(i))}}return}let s;try{let i=await this.request(e,zo,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},sr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new z(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(B.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.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||{},[or]:c}});let p=_=>{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(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let x=_ instanceof z?_:new z(B.RequestTimeout,String(_));l(x)};this._responseHandlers.set(f,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=nr(n,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let h=r?.timeout??KO,g=()=>p(z.fromError(B.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let b=this._responseHandlers.get(f);b?b(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Ya,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},tc,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},wx,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[or]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[or]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[or]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Gp(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Jp(e,o);return Promise.resolve(n(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,n){let r=Gp(e);this._notificationHandlers.set(r,o=>{let s=Jp(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&Cp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(B.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new z(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new z(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new z(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=ri.parse({method:"notifications/tasks/status",params:a});await this.notification(c),sr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new z(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(sr(a.status))throw new z(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=ri.parse({method:"notifications/tasks/status",params:c});await this.notification(u),sr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function db(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function pb(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];db(i)&&db(s)?n[o]={...i,...s}:n[o]=s}return n}var pv=yy(Fm(),1),fv=yy(dv(),1);function sL(){let t=new pv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,fv.default)(t),t}var Kc=class{constructor(e){this._ajv=e??sL()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Gc=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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},ii,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},qo,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function mv(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function hv(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Jc=class extends dc{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(si.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Kc,this.setRequestHandler(Ip,r=>this._oninitialize(r)),this.setNotificationHandler(Ap,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Hp,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=si.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Gc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=pb(this._capabilities,e)}setRequestHandler(e,n){let o=rr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=jo(o);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=nr(Zo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new z(B.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let p=nr(zo,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new z(B.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=nr(sc,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new z(B.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){hv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&mv(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:hx.includes(n)?n:Pp,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"},Wa)}async createMessage(e,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},Up,n):this.request({method:"sampling/createMessage",params:e},ii,n)}async elicitInput(e,n){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},qo,n)}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},qo,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new z(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Fp,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 yv=Symbol.for("mcp.completable");function Jm(t){return!!t&&typeof t=="object"&&yv in t}function _v(t){return t[yv]?.complete}var gv;(function(t){t.Completable="McpCompletable"})(gv||(gv={}));var iL=/^[A-Za-z0-9._-]{1,128}$/;function aL(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"),!iL.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function cL(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 Xm(t){let e=aL(t);return cL(t,e.warnings),e.isValid}var Xc=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}};var Yc=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Jc(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Xc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Kr)),this.server.assertCanSetRequestHandler(mr(Zo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Kr,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=Mo(n.inputSchema);return o?Kp(o,{strictUnions:!0,pipeStrategy:"input"}):uL})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=Mo(n.outputSchema);o&&(r.outputSchema=Kp(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Zo,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(B.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new z(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof z&&r.code===B.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=Mo(e.inputSchema)??e.inputSchema,i=await Ha(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ua(a);throw new z(B.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new z(B.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=Mo(e.outputSchema),s=await Ha(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ua(i);throw new z(B.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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 r.taskStore.getTask(c);if(!d)throw new z(B.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(mr(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return Ox(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ix(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new z(B.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Li;let s=rr(r.argsSchema)?.[e.params.argument.name];if(!Jm(s))return Li;let i=_v(s);if(!i)return Li;let a=await i(e.params.argument.value,e.params.context);return bv(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Li;throw new z(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Li;let s=await o(e.params.argument.value,e.params.context);return bv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Uo)),this.server.assertCanSetRequestHandler(mr(Fo)),this.server.assertCanSetRequestHandler(mr(rc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Uo,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Fo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(rc,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new z(B.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new z(B.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(mr(Bo)),this.server.assertCanSetRequestHandler(mr(oc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Bo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?lL(n.argsSchema):void 0}))})),this.server.setRequestHandler(oc,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=Mo(r.argsSchema),s=await Ha(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ua(c);throw new z(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Wr(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=Wr(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 bt?c._def?.innerType:c;return Jm(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){Xm(e);let l={title:n,description:r,inputSchema:xv(o),outputSchema:xv(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"&&Xm(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=Wr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Wr(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(Ym(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Ym(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var uL={type:"object",properties:{}};function Sv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function kv(t){return"_def"in t||"_zod"in t||Sv(t)}function Ym(t){return typeof t!="object"||t===null||kv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Sv)}function xv(t){if(t){if(Ym(t))return Wr(t);if(!kv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function lL(t){let e=rr(t);return e?Object.entries(e).map(([n,r])=>{let o=q_(r),s=V_(r);return{name:n,description:o,required:!s}}):[]}function mr(t){let n=rr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=jo(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function bv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Li={completion:{values:[],hasMore:!1}};import Ev from"node:process";var dL=10*1024*1024,Qc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??dL}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
229
- `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),pL(n)}clear(){this._buffer=void 0}};function pL(t){return vx.parse(JSON.parse(t))}function vv(t){return JSON.stringify(t)+`
230
- `}var eu=class{constructor(e=Ev.stdin,n=Ev.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Qc({maxBufferSize:r?.maxBufferSize})}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(n=>{let r=vv(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as EP}from"node:module";import{existsSync as He,unlinkSync as Is,readdirSync as wP,readFileSync as ha,writeFileSync as il,writeSync as WU,renameSync as KU,rmSync as TP,mkdirSync as GU,statSync as PP,symlinkSync as JU,lstatSync as RP,realpathSync as CP}from"node:fs";import{spawnSync as al}from"node:child_process";import{join as yt,dirname as Eo,resolve as gt,sep as XU,isAbsolute as YU}from"node:path";import{fileURLToPath as QU}from"node:url";import{homedir as As,tmpdir as oy,cpus as eF}from"node:os";import{request as tF}from"node:https";import{AsyncLocalStorage as nF}from"node:async_hooks";ru();import{spawn as Av,execSync as vL,execFileSync as jv}from"node:child_process";import{mkdtempSync as EL,writeFileSync as Nv,rmSync as wL,existsSync as Dv}from"node:fs";import{join as iu,resolve as Lv}from"node:path";import{tmpdir as TL}from"node:os";var Rt=process.platform==="win32",PL={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 RL(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${PL[t]}`}function CL(t){return{windowsHide:t==="win32"}}function $L(t){return`'${t.replace(/'/g,"'\\''")}'`}function OL(t,e,n){return n==="win32"||!e?t:`export PATH=${$L(e)}
231
- ${t}`}function IL(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function AL(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
232
- `)}var NL=(()=>{if(Rt)return process.env.TEMP??process.env.TMP??TL();try{let t=jv(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:Lv(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function DL(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
228
+ ]`;continue}o+=r[c],r[c]==="\\"?s=!0:i&&r[c]==="]"?i=!1:!i&&r[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 uc(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((r,o)=>({...r,[o]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??$e(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let n={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=cc(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...n,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:r,...o}=ac(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function Vx(t,e){if(e.mapStrategy==="record")return uc(t,e);let n=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||$e(e),r=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||$e(e);return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function Wx(t){let e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(r.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:r}}function Kx(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function Gx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var ai={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Xx(t,e){if(e.target==="openApi3")return Jx(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in ai&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=ai[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){let r=n.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(r.length===n.length){let o=r.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:n.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,o)=>[...r,...o._def.values.filter(s=>!r.includes(s))],[])};return Jx(t,e)}var Jx=(t,e)=>{let n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,o)=>K(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function Yx(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:ai[t.innerType._def.typeName],nullable:!0}:{type:[ai[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function Qx(t,e){let n={type:"number"};if(!t.checks)return n;for(let r of t.checks)switch(r.kind){case"int":n.type="integer",Bp(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ce(n,"minimum",r.value,r.message,e):ce(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ce(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ce(n,"maximum",r.value,r.message,e):ce(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ce(n,"maximum",r.value,r.message,e));break;case"multipleOf":ce(n,"multipleOf",r.value,r.message,e);break}return n}function eb(t,e){let n=e.target==="openAi",r={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=qO(c);u&&n&&(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&&(r.properties[a]=l,u||o.push(a))}o.length&&(r.required=o);let i=ZO(t,e);return i!==void 0&&(r.additionalProperties=i),r}function ZO(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 qO(t){try{return t.isOptional()}catch{return!0}}var tb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:$e(e)},n]}:$e(e)};var nb=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let n=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(o=>o!==void 0)}};function rb(t,e){return K(t.type._def,e)}function ob(t,e){let r={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ce(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ce(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function sb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>K(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function ib(t){return{not:$e(t)}}function ab(t){return $e(t)}var cb=(t,e)=>K(t.innerType._def,e);var ub=(t,e,n)=>{switch(e){case T.ZodString:return cc(t,n);case T.ZodNumber:return Qx(t,n);case T.ZodObject:return eb(t,n);case T.ZodBigInt:return jx(t,n);case T.ZodBoolean:return Lx();case T.ZodDate:return Zp(t,n);case T.ZodUndefined:return ib(n);case T.ZodNull:return Gx(n);case T.ZodArray:return Mx(t,n);case T.ZodUnion:case T.ZodDiscriminatedUnion:return Xx(t,n);case T.ZodIntersection:return Bx(t,n);case T.ZodTuple:return sb(t,n);case T.ZodRecord:return uc(t,n);case T.ZodLiteral:return Zx(t,n);case T.ZodEnum:return Fx(t);case T.ZodNativeEnum:return Wx(t);case T.ZodNullable:return Yx(t,n);case T.ZodOptional:return tb(t,n);case T.ZodMap:return Vx(t,n);case T.ZodSet:return ob(t,n);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return rb(t,n);case T.ZodNaN:case T.ZodNever:return Kx(n);case T.ZodEffects:return Ux(t,n);case T.ZodAny:return $e(n);case T.ZodUnknown:return ab(n);case T.ZodDefault:return Hx(t,n);case T.ZodBranded:return ac(t,n);case T.ZodReadonly:return cb(t,n);case T.ZodCatch:return zx(t,n);case T.ZodPipeline:return nb(t,n);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(r=>{})(e)}};function K(t,e,n=!1){let r=e.seen.get(t);if(e.override){let a=e.override?.(t,e,r,n);if(a!==Ax)return a}if(r&&!n){let a=VO(r,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=ub(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&WO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var VO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:ic(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),$e(e)):e.$refStrategy==="seen"?$e(e):void 0}},WO=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Wp=(t,e)=>{let n=Dx(e),r=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:K(l._def,{...n,currentPath:[...n.basePath,n.definitionPath,u]},!0)??$e(n)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=K(t._def,o===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,o]},!1)??$e(n),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));let a=o===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,o].join("/"),[n.definitionPath]:{...r,[o]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.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 KO(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Kp(t,e){return xn(t)?gp(t,{target:KO(e?.target),io:e?.pipeStrategy??"input"}):Wp(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Gp(t){let n=nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Do(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Jp(t,e){let n=tr(t,e);if(!n.success)throw n.error;return n.data}var GO=6e4,lc=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(Wa,n=>{this._oncancel(n)}),this.setNotificationHandler(Ga,n=>{this._onprogress(n)}),this.setRequestHandler(Ka,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ja,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Ya,async(n,r)=>{let o=async()=>{let s=n.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,r.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:r.requestId})}}let i=await this._taskStore.getTask(s,r.sessionId);if(!i)throw new z(B.InvalidParams,`Task not found: ${s}`);if(!or(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(or(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[rr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Qa,async(n,r)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(n.params?.cursor,r.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new z(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(tc,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(B.InvalidParams,`Task not found: ${n.params.taskId}`);if(or(o.status))throw new z(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(n.params.taskId,"cancelled","Client cancelled task execution.",r.sessionId),this._clearTaskQueue(n.params.taskId);let s=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!s)throw new z(B.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(B.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,n,r,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,n),startTime:Date.now(),timeout:n,maxTotalTimeout:r,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let n=this._timeoutInfo.get(e);if(!n)return!1;let r=Date.now()-n.startTime;if(n.maxTotalTimeout&&r>=n.maxTotalTimeout)throw this._timeoutInfo.delete(e),z.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:n.maxTotalTimeout,totalElapsed:r});return clearTimeout(n.timeoutId),n.timeoutId=setTimeout(n.onTimeout,n.timeout),!0}_cleanupTimeout(e){let n=this._timeoutInfo.get(e);n&&(clearTimeout(n.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 n=this.transport?.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let r=this.transport?.onerror;this._transport.onerror=s=>{r?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Ys(s)||Sx(s)?this._onresponse(s):Cp(s)?this._onrequest(s,i):bx(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 r of this._timeoutInfo.values())clearTimeout(r.timeoutId);this._timeoutInfo.clear();for(let r of this._requestHandlerAbortControllers.values())r.abort();this._requestHandlerAbortControllers.clear();let n=z.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let r of e.values())r(n)}_onerror(e){this.onerror?.(e)}_onnotification(e){let n=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;n!==void 0&&Promise.resolve().then(()=>n(e)).catch(r=>this._onerror(new Error(`Uncaught error in notification handler: ${r}`)))}_onrequest(e,n){let r=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[rr]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:B.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=yx(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(B.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:n?.authInfo,requestId:e.id,requestInfo:n?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:n?.closeSSEStream,closeStandaloneSSEStream:n?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>r(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:B.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:n,...r}=e.params,o=Number(n),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(r)}_onresponse(e){let n=Number(e.id),r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),Ys(e))r(e);else{let i=new z(e.error.code,e.error.message,e.error.data);r(i)}return}let o=this._responseHandlers.get(n);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(n),this._cleanupTimeout(n);let s=!1;if(Ys(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,n))}}if(s||this._progressHandlers.delete(n),Ys(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,n,r){let{task:o}=r??{};if(!o){try{yield{type:"result",result:await this.request(e,n,r)}}catch(i){yield{type:"error",error:i instanceof z?i:new z(B.InternalError,String(i))}}return}let s;try{let i=await this.request(e,jo,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},or(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new z(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),r?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof z?i:new z(B.InternalError,String(i))}}}request(e,n,r){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=r??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}r?.signal?.throwIfAborted();let f=this._requestMessageId++,m={...e,jsonrpc:"2.0",id:f};r?.onprogress&&(this._progressHandlers.set(f,r.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||{},[rr]:c}});let p=_=>{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(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let x=_ instanceof z?_:new z(B.RequestTimeout,String(_));l(x)};this._responseHandlers.set(f,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=tr(n,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let h=r?.timeout??GO,g=()=>p(z.fromError(B.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let b=this._responseHandlers.get(f);b?b(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Xa,n)}async getTaskResult(e,n,r){return this.request({method:"tasks/result",params:e},n,r)}async listTasks(e,n){return this.request({method:"tasks/list",params:e},ec,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},Ex,n)}async notification(e,n){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let r=n?.relatedTask?.taskId;if(r){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[rr]:n.relatedTask}}};await this._enqueueTaskMessage(r,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!n?.relatedRequestId&&!n?.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"};n?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[rr]:n.relatedTask}}}),this._transport?.send(a,n).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};n?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[rr]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Gp(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Jp(e,o);return Promise.resolve(n(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,n){let r=Gp(e);this._notificationHandlers.set(r,o=>{let s=Jp(e,o);return Promise.resolve(n(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let n=this._taskProgressTokens.get(e);n!==void 0&&(this._progressHandlers.delete(n),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,n,r){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,n,r,o)}async _clearTaskQueue(e,n){if(this._taskMessageQueue){let r=await this._taskMessageQueue.dequeueAll(e,n);for(let o of r)if(o.type==="request"&&Cp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(B.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,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(r=o.pollInterval)}catch{}return new Promise((o,s)=>{if(n.aborted){s(new z(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new z(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,n){let r=this._taskStore;if(!r)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await r.createTask(o,e.id,{method:e.method,params:e.params},n)},getTask:async o=>{let s=await r.getTask(o,n);if(!s)throw new z(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await r.storeTaskResult(o,s,i,n);let a=await r.getTask(o,n);if(a){let c=ri.parse({method:"notifications/tasks/status",params:a});await this.notification(c),or(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>r.getTaskResult(o,n),updateTaskStatus:async(o,s,i)=>{let a=await r.getTask(o,n);if(!a)throw new z(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(or(a.status))throw new z(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=ri.parse({method:"notifications/tasks/status",params:c});await this.notification(u),or(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function lb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function db(t,e){let n={...t};for(let r in e){let o=r,s=e[o];if(s===void 0)continue;let i=n[o];lb(i)&&lb(s)?n[o]={...i,...s}:n[o]=s}return n}var dv=gy(Fm(),1),pv=gy(lv(),1);function iL(){let t=new dv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,pv.default)(t),t}var Wc=class{constructor(e){this._ajv=e??iL()}getValidator(e){let n="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return r=>n(r)?{valid:!0,data:r,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(n.errors)}}};var Kc=class{constructor(e){this._server=e}requestStream(e,n,r){return this._server.requestStream(e,n,r)}createMessageStream(e,n){let r=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!r?.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},ii,n)}elicitInputStream(e,n){let r=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!r?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!r?.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},Bo,n)}async getTask(e,n){return this._server.getTask({taskId:e},n)}async getTaskResult(e,n,r){return this._server.getTaskResult({taskId:e},n,r)}async listTasks(e,n){return this._server.listTasks(e?{cursor:e}:void 0,n)}async cancelTask(e,n){return this._server.cancelTask({taskId:e},n)}};function fv(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${n} does not support task creation for tools/call (required for ${e})`);break;default:break}}function mv(t,e,n){if(!t)throw new Error(`${n} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${n} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${n} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var Gc=class extends lc{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(si.options.map((r,o)=>[r,o])),this.isMessageIgnored=(r,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(r)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=n?.capabilities??{},this._instructions=n?.instructions,this._jsonSchemaValidator=n?.jsonSchemaValidator??new Wc,this.setRequestHandler(Ip,r=>this._oninitialize(r)),this.setNotificationHandler(Ap,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Hp,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=si.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Kc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=db(this._capabilities,e)}setRequestHandler(e,n){let o=nr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s=Do(o);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=tr(Fo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new z(B.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let p=tr(jo,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new z(B.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=tr(oc,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new z(B.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,n)}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){mv(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&fv(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let n=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:mx.includes(n)?n:Pp,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,n){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 r=e.messages[e.messages.length-1],o=Array.isArray(r.content)?r.content:[r.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},Up,n):this.request({method:"sampling/createMessage",params:e},ii,n)}async elicitInput(e,n){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},Bo,n)}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},Bo,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new z(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,n){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}},n)}async listRoots(e,n){return this.request({method:"roots/list",params:e},Fp,n)}async sendLoggingMessage(e,n){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,n))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 gv=Symbol.for("mcp.completable");function Jm(t){return!!t&&typeof t=="object"&&gv in t}function yv(t){return t[gv]?.complete}var hv;(function(t){t.Completable="McpCompletable"})(hv||(hv={}));var aL=/^[A-Za-z0-9._-]{1,128}$/;function cL(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"),!aL.test(t)){let n=t.split("").filter(r=>!/[A-Za-z0-9._-]/.test(r)).filter((r,o,s)=>s.indexOf(r)===o);return e.push(`Tool name contains invalid characters: ${n.map(r=>`"${r}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function uL(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let n of e)console.warn(` - ${n}`);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 Xm(t){let e=cL(t);return uL(t,e.warnings),e.isValid}var Jc=class{constructor(e){this._mcpServer=e}registerToolTask(e,n,r){let o={taskSupport:"required",...n.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,n.title,n.description,n.inputSchema,n.outputSchema,n.annotations,o,n._meta,r)}};var Xc=class{constructor(e,n){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Gc(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Jc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(fr(Wr)),this.server.assertCanSetRequestHandler(fr(Fo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Wr,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,n])=>{let r={name:e,title:n.title,description:n.description,inputSchema:(()=>{let o=No(n.inputSchema);return o?Kp(o,{strictUnions:!0,pipeStrategy:"input"}):lL})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=No(n.outputSchema);o&&(r.outputSchema=Kp(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Fo,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(B.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=r.execution?.taskSupport,i="createTask"in r.handler;if((s==="required"||s==="optional")&&!i)throw new z(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(r,e,n);let a=await this.validateToolInput(r,e.params.arguments,e.params.name),c=await this.executeToolHandler(r,a,n);return o||await this.validateToolOutput(r,c,e.params.name),c}catch(r){if(r instanceof z&&r.code===B.UrlElicitationRequired)throw r;return this.createToolError(r instanceof Error?r.message:String(r))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,n,r){if(!e.inputSchema)return;let s=No(e.inputSchema)??e.inputSchema,i=await za(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ha(a);throw new z(B.InvalidParams,`Input validation error: Invalid arguments for tool ${r}: ${c}`)}return i.data}async validateToolOutput(e,n,r){if(!e.outputSchema||!("content"in n)||n.isError)return;if(!n.structuredContent)throw new z(B.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=No(e.outputSchema),s=await za(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ha(i);throw new z(B.InvalidParams,`Output validation error: Invalid structured content for tool ${r}: ${a}`)}}async executeToolHandler(e,n,r){let o=e.handler;if("createTask"in o){if(!r.taskStore)throw new Error("No task store provided.");let i={...r,taskStore:r.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(n,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(n,r))}else{let i=o;return await Promise.resolve(i(r))}}async handleAutomaticTaskPolling(e,n,r){if(!r.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,n.params.arguments,n.params.name),s=e.handler,i={...r,taskStore:r.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 r.taskStore.getTask(c);if(!d)throw new z(B.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(fr(sc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(sc,async e=>{switch(e.params.ref.type){case"ref/prompt":return $x(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Ox(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new z(B.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Li;let s=nr(r.argsSchema)?.[e.params.argument.name];if(!Jm(s))return Li;let i=yv(s);if(!i)return Li;let a=await i(e.params.argument.value,e.params.context);return xv(a)}async handleResourceCompletion(e,n){let r=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===n.uri);if(!r){if(this._registeredResources[n.uri])return Li;throw new z(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Li;let s=await o(e.params.argument.value,e.params.context);return xv(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(fr(zo)),this.server.assertCanSetRequestHandler(fr(Ho)),this.server.assertCanSetRequestHandler(fr(nc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(zo,async(e,n)=>{let r=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(n);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...r,...o]}}),this.server.setRequestHandler(Ho,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(nc,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new z(B.InvalidParams,`Resource ${r} disabled`);return o.readCallback(r,n)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(r.toString());if(i)return s.readCallback(r,i,n)}throw new z(B.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(fr(Uo)),this.server.assertCanSetRequestHandler(fr(rc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Uo,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?dL(n.argsSchema):void 0}))})),this.server.setRequestHandler(rc,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=No(r.argsSchema),s=await za(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ha(c);throw new z(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=r.callback;return await Promise.resolve(a(i,n))}else{let o=r.callback;return await Promise.resolve(o(n))}}),this._promptHandlersInitialized=!0)}resource(e,n,...r){let o;typeof r[0]=="object"&&(o=r.shift());let s=r[0];if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let i=this._createRegisteredResource(e,void 0,n,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,n,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,n,r,o){if(typeof n=="string"){if(this._registeredResources[n])throw new Error(`Resource ${n} is already registered`);let s=this._createRegisteredResource(e,r.title,n,r,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,r.title,n,r,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,n,r,o,s){let i={name:e,title:n,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!==r&&(delete this._registeredResources[r],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[r]=i,i}_createRegisteredResourceTemplate(e,n,r,o,s){let i={resourceTemplate:r,title:n,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=r.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!r.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,n,r,o,s){let i={title:n,description:r,argsSchema:o===void 0?void 0:Vr(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=Vr(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 bt?c._def?.innerType:c;return Jm(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){Xm(e);let l={title:n,description:r,inputSchema:_v(o),outputSchema:_v(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"&&Xm(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=Vr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Vr(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,...n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let r,o,s,i;if(typeof n[0]=="string"&&(r=n.shift()),n.length>1){let c=n[0];if(Ym(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Ym(n[0])&&(i=n.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=n.shift()}}let a=n[0];return this._createRegisteredTool(e,void 0,r,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,n,r){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}=n;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,r)}prompt(e,...n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let r;typeof n[0]=="string"&&(r=n.shift());let o;n.length>1&&(o=n.shift());let s=n[0],i=this._createRegisteredPrompt(e,void 0,r,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,n,r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=n,a=this._createRegisteredPrompt(e,o,s,i,r);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,n){return this.server.sendLoggingMessage(e,n)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}};var lL={type:"object",properties:{}};function bv(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Sv(t){return"_def"in t||"_zod"in t||bv(t)}function Ym(t){return typeof t!="object"||t===null||Sv(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(bv)}function _v(t){if(t){if(Ym(t))return Vr(t);if(!Sv(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function dL(t){let e=nr(t);return e?Object.entries(e).map(([n,r])=>{let o=Z_(r),s=q_(r);return{name:n,description:o,required:!s}}):[]}function fr(t){let n=nr(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Do(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function xv(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Li={completion:{values:[],hasMore:!1}};import vv from"node:process";var pL=10*1024*1024,Yc=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??pL}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
229
+ `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),fL(n)}clear(){this._buffer=void 0}};function fL(t){return kx.parse(JSON.parse(t))}function kv(t){return JSON.stringify(t)+`
230
+ `}var Qc=class{constructor(e=vv.stdin,n=vv.stdout,r){this._stdin=e,this._stdout=n,this._started=!1,this._ondata=o=>{try{this._readBuffer.append(o),this.processReadBuffer()}catch(s){this.onerror?.(s),this.close().catch(()=>{})}},this._onerror=o=>{this.onerror?.(o)},this._readBuffer=new Yc({maxBufferSize:r?.maxBufferSize})}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(n=>{let r=kv(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as TP}from"node:module";import{existsSync as Me,unlinkSync as $s,readdirSync as WU,readFileSync as ma,writeFileSync as sl,writeSync as KU,renameSync as GU,rmSync as PP,mkdirSync as JU,statSync as RP,symlinkSync as XU,lstatSync as CP,realpathSync as $P}from"node:fs";import{spawnSync as il}from"node:child_process";import{join as Ot,dirname as As,resolve as gt,sep as YU,isAbsolute as QU}from"node:path";import{fileURLToPath as eF}from"node:url";import{homedir as Os,tmpdir as ry,cpus as tF}from"node:os";import{request as nF}from"node:https";import{AsyncLocalStorage as rF}from"node:async_hooks";nu();import{spawn as Iv,execSync as EL,execFileSync as Mv}from"node:child_process";import{mkdtempSync as wL,writeFileSync as Av,rmSync as TL,existsSync as Nv}from"node:fs";import{join as su,resolve as jv}from"node:path";import{tmpdir as PL}from"node:os";var Rt=process.platform==="win32",RL={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 CL(t,e,n){if(e==="win32"&&t==="shell"){let r=n?.toLowerCase()??"";if(r.includes("powershell")||r.includes("pwsh"))return"script.ps1";let o=r.split(/[\\/]/).pop()??r;return o==="cmd"||o==="cmd.exe"?"script.cmd":"script"}return`script.${RL[t]}`}function $L(t){return{windowsHide:t==="win32"}}function OL(t){return`'${t.replace(/'/g,"'\\''")}'`}function IL(t,e,n){return n==="win32"||!e?t:`export PATH=${OL(e)}
231
+ ${t}`}function AL(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function NL(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
232
+ `)}var DL=(()=>{if(Rt)return process.env.TEMP??process.env.TMP??PL();try{let t=Mv(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:jv(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function ML(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
233
233
  `]),r="",o=!0,s=0;for(;s<t.length;){let i=t[s];if(o&&(i===" "||i===" ")){r+=i,s++;continue}if(o&&t.startsWith("mvn",s)){let a=t[s+3];if(a===void 0||a===" "||a===" "||a===`
234
- `){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function Mv(t){try{wL(t,{recursive:!0,force:!0,maxRetries:Rt?8:2,retryDelay:100})}catch{}}function oh(t){if(Rt&&t.pid)try{vL(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Ui=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??ou()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Rt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=EL(iu(NL,".ctx-mode-"));try{let c=this.#a(a,r,n),u=Iv(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||Mv(a),d}catch(c){throw Mv(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=Lv(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
234
+ `){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function Dv(t){try{TL(t,{recursive:!0,force:!0,maxRetries:Rt?8:2,retryDelay:100})}catch{}}function oh(t){if(Rt&&t.pid)try{EL(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Ui=class{#e;#t;#n;#o=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let n=e?.projectRoot;typeof n=="function"?this.#t=n:typeof n=="string"?this.#t=()=>n:this.#t=()=>process.cwd(),this.#n=e?.runtimes??ru()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Rt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=wL(su(DL,".ctx-mode-"));try{let c=this.#a(a,r,n),u=Ov(this.#n,n,c);if(u[0]==="__rust_compile_run__")return await this.#c(c,a,o);let l=i??this.#s,d=await this.#i(u,l,a,o,s);return d.backgrounded||Dv(a),d}catch(c){throw Dv(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=jv(this.#s,n),a=this.#l(i,r,o);return this.execute({language:r,code:a,timeout:s})}#a(e,n,r){r==="go"&&!n.includes("package ")&&(n=`package main
235
235
 
236
236
  import "fmt"
237
237
 
@@ -239,12 +239,12 @@ func main() {
239
239
  ${n}
240
240
  }
241
241
  `),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
242
- ${n}`),r==="elixir"&&Dv(iu(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(iu(this.#s,"_build/dev/lib"))}, "*/ebin"))
242
+ ${n}`),r==="elixir"&&Nv(su(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(su(this.#s,"_build/dev/lib"))}, "*/ebin"))
243
243
  |> Enum.each(&Code.prepend_path/1)
244
244
 
245
- ${n}`);let o=iu(e,RL(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=DL(n,process.platform),a=Rt&&IL(s)?AL(i):i;Nv(o,OL(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else Nv(o,n,"utf-8");return o}async#c(e,n,r){let o=Rt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{jv("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
246
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=Rt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Rt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Rt?e.slice(1).map(x=>x.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!Rt,...CL(process.platform)},d;if(a){let x=[c,...u].map(b=>/\s/.test(b)?JSON.stringify(b):b).join(" ");d=Av(x,[],{...l,shell:!0})}else d=Av(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.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let x=Buffer.concat(h).toString("utf-8"),b=Buffer.concat(g).toString("utf-8");i({stdout:x,stderr:b,exitCode:0,timedOut:!0,backgrounded:!0})}else oh(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",x=>{y+=x.length,y<=this.#e?h.push(x):_||(_=!0,oh(d))}),d.stderr.on("data",x=>{y+=x.length,y<=this.#e?g.push(x):_||(_=!0,oh(d))}),d.on("close",x=>{if(clearTimeout(p),m)return;let b=Buffer.concat(h).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");_&&(v+=`
247
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:v,exitCode:f?1:x??1,timedOut:f})}),d.on("error",x=>{clearTimeout(p),!m&&i({stdout:"",stderr:x.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Rt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Rt?"":"/usr/local/bin:/usr/bin:/bin"),Rt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}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=Rt?[]:["/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(Dv(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
245
+ ${n}`);let o=su(e,CL(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=ML(n,process.platform),a=Rt&&AL(s)?NL(i):i;Av(o,IL(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else Av(o,n,"utf-8");return o}async#c(e,n,r){let o=Rt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{Mv("rustc",[e,"-o",s],{cwd:n,timeout:r===void 0?6e4:Math.min(r,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
246
+ ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],n,n,r)}async#i(e,n,r,o,s=!1){return new Promise(i=>{let a=Rt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;Rt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Rt?e.slice(1).map(x=>x.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!Rt,...$L(process.platform)},d;if(a){let x=[c,...u].map(b=>/\s/.test(b)?JSON.stringify(b):b).join(" ");d=Iv(x,[],{...l,shell:!0})}else d=Iv(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.#o.add(d.pid),d.unref(),d.stdout&&(d.stdout.removeAllListeners("data"),d.stdout.on("data",()=>{})),d.stderr&&(d.stderr.removeAllListeners("data"),d.stderr.on("data",()=>{}));let x=Buffer.concat(h).toString("utf-8"),b=Buffer.concat(g).toString("utf-8");i({stdout:x,stderr:b,exitCode:0,timedOut:!0,backgrounded:!0})}else oh(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",x=>{y+=x.length,y<=this.#e?h.push(x):_||(_=!0,oh(d))}),d.stderr.on("data",x=>{y+=x.length,y<=this.#e?g.push(x):_||(_=!0,oh(d))}),d.on("close",x=>{if(clearTimeout(p),m)return;let b=Buffer.concat(h).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");_&&(v+=`
247
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:b,stderr:v,exitCode:f?1:x??1,timedOut:f})}),d.on("error",x=>{clearTimeout(p),!m&&i({stdout:"",stderr:x.message,exitCode:1,timedOut:!1})})})}#u(e){let n=process.env.HOME??process.env.USERPROFILE??e,r=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&&!r.has(s)&&!s.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(s)&&(o[s]=i);if(o.TMPDIR=e,o.HOME=n,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Rt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Rt?"":"/usr/local/bin:/usr/bin:/bin"),Rt){for(let a of Object.keys(o)){let c=a.toUpperCase();(c==="MSYS_NO_PATHCONV"||c==="MSYS2_ARG_CONV_EXCL")&&delete o[a]}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=Rt?[]:["/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(Nv(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,n,r){let o=JSON.stringify(e);switch(n){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
248
248
  const file_path = FILE_CONTENT_PATH;
249
249
  const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
250
250
  ${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
@@ -302,7 +302,7 @@ file_content = File.read!(file_content_path)
302
302
  ${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
303
303
  var file_path = FILE_CONTENT_PATH;
304
304
  var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
305
- ${r}`}}};import{cpus as ML}from"node:os";async function sh(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,ML().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}}co();import{readFileSync as Gv,readdirSync as tE,unlinkSync as ph,existsSync as dh,statSync as lu,openSync as Jv,fstatSync as Xv,closeSync as Yv}from"node:fs";import{createHash as Qv}from"node:crypto";import{tmpdir as nE}from"node:os";import{join as fh}from"node:path";import{readdirSync as KL,statSync as GL,lstatSync as JL,realpathSync as Zv,existsSync as XL,readFileSync as YL}from"node:fs";import{join as Vv,extname as QL,relative as Wv,sep as ez,resolve as tz}from"node:path";var nz=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],rz=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],oz=5,sz=200;function iz(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function qv(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=iz(r);if(o.test(t)||o.test(n))return!0}return!1}function az(t){let e=Vv(t,".gitignore");if(!XL(e))return[];try{return YL(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function cz(t,e){return Wv(t,e).split(ez).join("/")}function Kv(t,e={}){let{include:n,exclude:r,maxDepth:o=oz,maxFiles:s=sz,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Zv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:rz).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...nz,...r??[],...a?az(u):[]],f=n??[],m=[],p=new Set([u]),h=0,g=!1;function y(_,x){if(g||x>o)return;let b;try{b=KL(_,{withFileTypes:!0})}catch{return}for(let v of b){if(g)return;let O=Vv(_,v.name),R=cz(u,O);if(qv(R,d))continue;let j=v.isDirectory(),M=v.isFile(),V=!1;try{V=JL(O).isSymbolicLink()}catch{continue}if(V){if(!c)continue;let P;try{P=Zv(O)}catch{continue}let H=Wv(u,P);if((H.startsWith("..")||tz(H)===P)&&H.startsWith("..")||p.has(P))continue;p.add(P);try{let se=GL(P);j=se.isDirectory(),M=se.isFile()}catch{continue}}if(j){y(O,x+1);continue}if(!M)continue;let w=QL(O).toLowerCase();if(l.includes(w)&&!(f.length>0&&!qv(R,f))){if(h++,m.length>=s){g=!0;return}m.push(O)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var fs=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 rE(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function uz(t,e="AND"){let n=rE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!fs.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function lz(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=rE(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!fs.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function dz(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function pz(t){return t<=4?1:t<=12?2:3}var uu=4096,fz=3,mz=200,hz=5e3,eE=80,gz=.5;function mh(){let t=nE(),e=0;try{let n=tE(t);for(let r of n){let o=r.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=fh(t,r);for(let a of["","-wal","-shm"])try{ph(i+a)}catch{}e++}}}catch{}return e}function hh(t,e){let n=0;try{if(!dh(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=tE(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=fh(t,s),c=lu(i).mtimeMs<r;if(!c){let u=i+"-wal";if(dh(u))try{let l=lu(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{ph(i+u)}catch{}n++}}catch{}}catch{}return n}function yz(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function _z(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=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+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(r++,u++)}}return r}function xz(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var bz="[context-mode:store]",oE=Symbol.for("__context_mode_db_error_logged__");function sE(t){try{return typeof t=="object"&&t!==null&&t[oE]===!0}catch{return!1}}function Ke(t,e,n,r){if(sE(e))return e;tt(t,e,n);let o=cu(e),s=Zi(e),i=s?` (${s})`:"",a=new Error(`${bz} ${t} failed on ${n}: ${r??o}${i}`);return s&&(a.code=s),Object.defineProperty(a,oE,{value:!0,enumerable:!1}),a}var du=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#x;#b;#S;#k;#v;#E;#w;#T;#P;#R;#C;#$;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=qe();this.#t=e??fh(nE(),`context-mode-${process.pid}.db`),ao(this.#t);let r=()=>{let s=new n(this.#t,{timeout:3e4});return ps(s),s},o;try{o=De(r)}catch(s){let i=s instanceof Error?s.message:String(s);if(lh(i)){tt("store.open",s,this.#t),uh(this.#t),ao(this.#t);try{o=De(r)}catch(a){throw Ke("store.open",a,this.#t,`Failed to create fresh DB after deleting corrupt file: ${cu(a)}`)}}else throw Ke("store.open",s,this.#t)}this.#e=o;try{this.#B(),this.#Z()}catch(s){throw Ke("store.initSchema",s,this.#t)}}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{ph(this.#t+e)}catch{}}#B(){this.#e.exec(`
305
+ ${r}`}}};import{cpus as jL}from"node:os";async function sh(t,e){let{concurrency:n,capByCpuCount:r=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,n),i=r?Math.max(1,jL().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}}ao();import{readFileSync as Kv,readdirSync as eE,unlinkSync as dh,existsSync as tE,statSync as uu,openSync as Gv,fstatSync as Jv,closeSync as Xv}from"node:fs";import{createHash as Yv}from"node:crypto";import{tmpdir as nE}from"node:os";import{join as ph}from"node:path";import{readdirSync as GL,statSync as JL,lstatSync as XL,realpathSync as Bv,existsSync as YL,readFileSync as QL}from"node:fs";import{join as qv,extname as ez,relative as Vv,sep as tz,resolve as nz}from"node:path";var rz=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],oz=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],sz=5,iz=200;function az(t){let e="";for(let n=0;n<t.length;n++){let r=t[n];r==="*"?t[n+1]==="*"?(e+=".*",n++):e+="[^/]*":r==="?"?e+="[^/]":"\\^$.|+()[]{}".includes(r)?e+="\\"+r:e+=r}return new RegExp(`^${e}$`)}function Zv(t,e){if(e.length===0)return!1;let n=t.split("/").pop()??t;for(let r of e){if(!r.includes("/")&&!r.includes("*")){if(n===r||t.split("/").includes(r))return!0;continue}let o=az(r);if(o.test(t)||o.test(n))return!0}return!1}function cz(t){let e=qv(t,".gitignore");if(!YL(e))return[];try{return QL(e,"utf-8").split(/\r?\n/).map(r=>r.trim()).filter(r=>r.length>0&&!r.startsWith("#")&&!r.startsWith("!")).map(r=>r.replace(/^\//,"").replace(/\/$/,""))}catch{return[]}}function uz(t,e){return Vv(t,e).split(tz).join("/")}function Wv(t,e={}){let{include:n,exclude:r,maxDepth:o=sz,maxFiles:s=iz,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=Bv(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:oz).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...rz,...r??[],...a?cz(u):[]],f=n??[],m=[],p=new Set([u]),h=0,g=!1;function y(_,x){if(g||x>o)return;let b;try{b=GL(_,{withFileTypes:!0})}catch{return}for(let v of b){if(g)return;let O=qv(_,v.name),R=uz(u,O);if(Zv(R,d))continue;let j=v.isDirectory(),M=v.isFile(),V=!1;try{V=XL(O).isSymbolicLink()}catch{continue}if(V){if(!c)continue;let P;try{P=Bv(O)}catch{continue}let H=Vv(u,P);if((H.startsWith("..")||nz(H)===P)&&H.startsWith("..")||p.has(P))continue;p.add(P);try{let se=JL(P);j=se.isDirectory(),M=se.isFile()}catch{continue}}if(j){y(O,x+1);continue}if(!M)continue;let w=ez(O).toLowerCase();if(l.includes(w)&&!(f.length>0&&!Zv(R,f))){if(h++,m.length>=s){g=!0;return}m.push(O)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var ds=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 rE(t){let e=new Set,n=[];for(let r of t){let o=r.toLowerCase();e.has(o)||(e.add(o),n.push(r))}return n}function lz(t,e="AND"){let n=rE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(n.length===0)return'""';let r=n.filter(s=>!ds.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function dz(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=rE(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!ds.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function pz(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let n=Array.from({length:e.length+1},(r,o)=>o);for(let r=1;r<=t.length;r++){let o=[r];for(let s=1;s<=e.length;s++)o[s]=t[r-1]===e[s-1]?n[s-1]:1+Math.min(n[s],o[s-1],n[s-1]);n=o}return n[e.length]}function fz(t){return t<=4?1:t<=12?2:3}var cu=4096,mz=3,hz=200,gz=5e3,Qv=80,yz=.5;function fh(){let t=nE(),e=0;try{let n=eE(t);for(let r of n){let o=r.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=ph(t,r);for(let a of["","-wal","-shm"])try{dh(i+a)}catch{}e++}}}catch{}return e}function oE(t,e){let n=0;try{if(!tE(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=eE(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=ph(t,s),a=uu(i).mtimeMs;try{let c=uu(i+"-wal");c.size>0&&c.mtimeMs>a&&(a=c.mtimeMs)}catch{}if(a<r){for(let c of["","-wal","-shm"])try{dh(i+c)}catch{}n++}}catch{}}catch{}return n}function _z(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function xz(t,e,n=30){if(t.length<2||e.length<2)return 0;let r=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+n;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=f&&(r++,u++)}}return r}function bz(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t,n=new Array(e.length).fill(0),r=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][n[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<r&&(r=a),n[i]++,n[i]>=e[i].length)break}return r}var Sz="[context-mode:store]",sE=Symbol.for("__context_mode_db_error_logged__");function iE(t){try{return typeof t=="object"&&t!==null&&t[sE]===!0}catch{return!1}}function Ke(t,e,n,r){if(iE(e))return e;tt(t,e,n);let o=au(e),s=Zi(e),i=s?` (${s})`:"",a=new Error(`${Sz} ${t} failed on ${n}: ${r??o}${i}`);return s&&(a.code=s),Object.defineProperty(a,sE,{value:!0,enumerable:!1}),a}var lu=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#x;#b;#S;#k;#v;#E;#w;#T;#P;#R;#C;#$;#O;#I;#A;#N;#D;#M;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=qe();this.#t=e??ph(nE(),`context-mode-${process.pid}.db`),io(this.#t);let r=()=>{let s=new n(this.#t,{timeout:3e4});return ls(s),s},o;try{o=De(r)}catch(s){let i=s instanceof Error?s.message:String(s);if(lh(i)){tt("store.open",s,this.#t),uh(this.#t),io(this.#t);try{o=De(r)}catch(a){throw Ke("store.open",a,this.#t,`Failed to create fresh DB after deleting corrupt file: ${au(a)}`)}}else throw Ke("store.open",s,this.#t)}this.#e=o;try{this.#B(),this.#Z()}catch(s){throw Ke("store.initSchema",s,this.#t)}}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{dh(this.#t+e)}catch{}}#B(){this.#e.exec(`
306
306
  CREATE TABLE IF NOT EXISTS sources (
307
307
  id INTEGER PRIMARY KEY AUTOINCREMENT,
308
308
  label TEXT NOT NULL,
@@ -554,7 +554,7 @@ ${r}`}}};import{cpus as ML}from"node:os";async function sh(t,e){let{concurrency:
554
554
  (SELECT COUNT(*) FROM sources) AS sources,
555
555
  (SELECT COUNT(*) FROM chunks) AS chunks,
556
556
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
557
- `),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let f=Jv(r,"r");try{if(!Xv(f).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=Gv(f,"utf-8")}finally{Yv(f)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?Qv("sha256").update(a).digest("hex"):void 0;try{return De(()=>this.#d(u,c,a,l,d,s))}catch(f){throw Ke("store.index",f,this.#t)}}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=Kv(n,i),c=0,u=0,l=0,d=0;for(let f of a.files){if(s&&s(f)){l++;continue}try{let m=r?`${r}:${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:r??n}}indexPlainText(e,n,r=20,o,s=uu){if(!e||e.trim().length===0)try{return De(()=>this.#d([],n,"",void 0,void 0,o))}catch(a){throw Ke("store.indexPlainText",a,this.#t)}let i=this.#J(e,r,s);try{return De(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}catch(a){throw Ke("store.indexPlainText",a,this.#t)}}indexJSON(e,n,r=uu,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];if(this.#F(s,[],i,r),i.length===0)return this.indexPlainText(e,n,void 0,o,r);try{return De(()=>this.#d(i,n,e,void 0,void 0,o))}catch(a){throw Ke("store.indexJSON",a,this.#t)}}#d(e,n,r,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(n),this.#l.run(n),this.#m.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let f=this.#s.run(n,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 r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=uz(e,o),c,u;r&&s?(c=i==="exact"?this.#E:this.#v,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#k,u=[a,s,n]):(c=this.#h,u=[a,n]);try{return De(()=>this.#L(c.all(...u)))}catch(l){throw Ke("store.search",l,this.#t)}}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=lz(e,o);if(!a)return[];let c,u;r&&s?(c=i==="exact"?this.#P:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#b:this.#x,u=[a,this.#p(r,i),n]):s?(c=this.#w,u=[a,s,n]):(c=this.#_,u=[a,n]);try{return De(()=>this.#L(c.all(...u)))}catch(l){throw Ke("store.searchTrigram",l,this.#t)}}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=pz(n.length),o;try{o=De(()=>this.#S.all(n.length-r,n.length+r))}catch(u){throw Ke("store.fuzzyCorrect",u,this.#t)}let s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=dz(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?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(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"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,n).map(({result:f,score:m})=>({...f,rank:-m}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!fs.has(i)),s=o.length>0?o:r;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=>yz(m,h));if(!p.some(h=>h.length===0)){d=1/(1+xz(p)/Math.max(m.length,1));let g=_z(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,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!fs.has(h)),f=d.join(" "),p=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(p!==f){let h=this.#z(p,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),p).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e;try{e=De(()=>this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all())}catch(n){throw Ke("store.refreshStaleSources",n,this.#t)}for(let n of e)try{if(!dh(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=lu(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Jv(n.file_path,"r"),i;try{if(!Xv(s).isFile())continue;i=Gv(s,"utf-8")}finally{Yv(s)}if(Qv("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch(r){sE(r)||tt("store.refreshStaleSources",r,this.#t)}}getSourceMeta(e){let n;try{n=De(()=>this.#A.get(e))}catch(r){throw Ke("store.getSourceMeta",r,this.#t)}return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){try{return De(()=>this.#R.all())}catch(e){throw Ke("store.listSources",e,this.#t)}}getIndexState(){let e;try{e=De(()=>this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get())}catch(n){throw Ke("store.getIndexState",n,this.#t)}return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){let n;try{n=De(()=>this.#C.all(e))}catch(r){throw Ke("store.getChunksBySource",r,this.#t)}return n.map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r;try{r=De(()=>this.#$.get(e))}catch(d){throw Ke("store.getDistinctiveTerms",d,this.#t)}if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=()=>{let d=new Map;for(let f of this.#O.iterate(e)){let m=new Set(f.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!fs.has(p)));for(let p of m)d.set(p,(d.get(p)??0)+1)}return d},c;try{c=De(a)}catch(d){throw Ke("store.getDistinctiveTerms",d,this.#t)}return Array.from(c.entries()).filter(([,d])=>d>=s&&d<=i).map(([d,f])=>{let m=Math.log(o/f),p=Math.min(d.length/20,.5),h=/[_]/.test(d),g=d.length>=12,y=h?1.5:g?.8:0;return{word:d,score:m+p+y}}).sort((d,f)=>f.score-d.score).slice(0,n).map(d=>d.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){let n=this.#e.transaction(r=>(this.#N.run(r),this.#D.run(r),this.#M.run(r)));try{return De(()=>n(e)).changes}catch(r){throw Ke("store.cleanupStaleSources",r,this.#t)}}getDBSizeBytes(){try{return lu(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(e){tt("store.optimizeFTS",e,this.#t)}}close(){this.#U(),Bi(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!fs.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=uu){let r=[],o=e.split(`
557
+ `),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:n,path:r,source:o,attribution:s}=e,i=typeof n=="string"&&n.length>0;if(!i&&!r)throw new Error("Either content or path must be provided");let a;if(i)a=n;else{let f=Gv(r,"r");try{if(!Jv(f).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=Kv(f,"utf-8")}finally{Xv(f)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?Yv("sha256").update(a).digest("hex"):void 0;try{return De(()=>this.#d(u,c,a,l,d,s))}catch(f){throw Ke("store.index",f,this.#t)}}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=Wv(n,i),c=0,u=0,l=0,d=0;for(let f of a.files){if(s&&s(f)){l++;continue}try{let m=r?`${r}:${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:r??n}}indexPlainText(e,n,r=20,o,s=cu){if(!e||e.trim().length===0)try{return De(()=>this.#d([],n,"",void 0,void 0,o))}catch(a){throw Ke("store.indexPlainText",a,this.#t)}let i=this.#J(e,r,s);try{return De(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}catch(a){throw Ke("store.indexPlainText",a,this.#t)}}indexJSON(e,n,r=cu,o){if(!e||e.trim().length===0)return this.indexPlainText("",n,void 0,o,r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,n,void 0,o,r)}let i=[];if(this.#F(s,[],i,r),i.length===0)return this.indexPlainText(e,n,void 0,o,r);try{return De(()=>this.#d(i,n,e,void 0,void 0,o))}catch(a){throw Ke("store.indexJSON",a,this.#t)}}#d(e,n,r,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(n),this.#l.run(n),this.#m.run(n),e.length===0){let h=this.#o.run(n,o??null,s??null);return Number(h.lastInsertRowid)}let f=this.#s.run(n,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 r&&this.#W(r),this.#j++,this.#j%t.OPTIMIZE_EVERY===0&&this.#U(),{sourceId:d,label:n,totalChunks:e.length,codeChunks:a}}#L(e){return e.map(n=>({title:n.title,content:n.content,source:n.label,rank:n.rank,contentType:n.content_type,highlighted:n.highlighted,timestamp:n.timestamp??void 0,sessionId:n.session_id??""}))}#p(e,n){return n==="exact"?e:`%${e.replace(/\\/g,"\\\\").replace(/%/g,"\\%").replace(/_/g,"\\_")}%`}search(e,n=3,r,o="AND",s,i="like"){let a=lz(e,o),c,u;r&&s?(c=i==="exact"?this.#E:this.#v,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#y:this.#g,u=[a,this.#p(r,i),n]):s?(c=this.#k,u=[a,s,n]):(c=this.#h,u=[a,n]);try{return De(()=>this.#L(c.all(...u)))}catch(l){throw Ke("store.search",l,this.#t)}}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=dz(e,o);if(!a)return[];let c,u;r&&s?(c=i==="exact"?this.#P:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#b:this.#x,u=[a,this.#p(r,i),n]):s?(c=this.#w,u=[a,s,n]):(c=this.#_,u=[a,n]);try{return De(()=>this.#L(c.all(...u)))}catch(l){throw Ke("store.searchTrigram",l,this.#t)}}fuzzyCorrect(e){let n=e.toLowerCase().trim();if(n.length<3)return null;if(this.#r.has(n)){let u=this.#r.get(n)??null;return this.#r.delete(n),this.#r.set(n,u),u}let r=fz(n.length),o;try{o=De(()=>this.#S.all(n.length-r,n.length+r))}catch(u){throw Ke("store.fuzzyCorrect",u,this.#t)}let s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=pz(n,u);l<i&&(i=l,s=u)}let c=a?null:i<=r?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(n,c),c}#z(e,n,r,o,s="like"){let a=Math.max(n*2,10),c=this.search(e,a,r,"OR",o,s),u=this.searchTrigram(e,a,r,"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,n).map(({result:f,score:m})=>({...f,rank:-m}))}#H(e,n){let r=n.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=r.filter(i=>!ds.has(i)),s=o.length>0?o:r;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=>_z(m,h));if(!p.some(h=>h.length===0)){d=1/(1+bz(p)/Math.max(m.length,1));let g=xz(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,n=3,r,o,s="like",i){this.#V();let a=i?Math.max(n*8,40):n,c=this.#q(i),u=this.#z(e,a,r,o,s),l=c?u.filter(c):u;if(l.length>0)return this.#H(l.slice(0,n),e).map(g=>({...g,matchLayer:"rrf"}));let d=e.toLowerCase().trim().split(/\s+/).filter(h=>h.length>=3&&!ds.has(h)),f=d.join(" "),p=d.map(h=>this.fuzzyCorrect(h)??h).join(" ");if(p!==f){let h=this.#z(p,a,r,o,s),g=c?h.filter(c):h;if(g.length>0)return this.#H(g.slice(0,n),p).map(_=>({..._,matchLayer:"rrf-fuzzy"}))}return[]}#q(e){return e?n=>{let r=n.sessionId??"";return r===""||e.has(r)}:null}lastRefreshCount=0;#V(){this.lastRefreshCount=0;let e;try{e=De(()=>this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all())}catch(n){throw Ke("store.refreshStaleSources",n,this.#t)}for(let n of e)try{if(!tE(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=uu(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=Gv(n.file_path,"r"),i;try{if(!Jv(s).isFile())continue;i=Kv(s,"utf-8")}finally{Xv(s)}if(Yv("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch(r){iE(r)||tt("store.refreshStaleSources",r,this.#t)}}getSourceMeta(e){let n;try{n=De(()=>this.#A.get(e))}catch(r){throw Ke("store.getSourceMeta",r,this.#t)}return n?{label:n.label,chunkCount:n.chunk_count,codeChunkCount:n.code_chunk_count,indexedAt:n.indexed_at,filePath:n.file_path??null,contentHash:n.content_hash??null}:null}listSources(){try{return De(()=>this.#R.all())}catch(e){throw Ke("store.listSources",e,this.#t)}}getIndexState(){let e;try{e=De(()=>this.#e.prepare("SELECT COALESCE(SUM(chunk_count), 0) AS total_chunks, COUNT(*) AS total_sources, MAX(indexed_at) AS last_indexed_at FROM sources").get())}catch(n){throw Ke("store.getIndexState",n,this.#t)}return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){let n;try{n=De(()=>this.#C.all(e))}catch(r){throw Ke("store.getChunksBySource",r,this.#t)}return n.map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r;try{r=De(()=>this.#$.get(e))}catch(d){throw Ke("store.getDistinctiveTerms",d,this.#t)}if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=()=>{let d=new Map;for(let f of this.#O.iterate(e)){let m=new Set(f.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!ds.has(p)));for(let p of m)d.set(p,(d.get(p)??0)+1)}return d},c;try{c=De(a)}catch(d){throw Ke("store.getDistinctiveTerms",d,this.#t)}return Array.from(c.entries()).filter(([,d])=>d>=s&&d<=i).map(([d,f])=>{let m=Math.log(o/f),p=Math.min(d.length/20,.5),h=/[_]/.test(d),g=d.length>=12,y=h?1.5:g?.8:0;return{word:d,score:m+p+y}}).sort((d,f)=>f.score-d.score).slice(0,n).map(d=>d.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){let n=this.#e.transaction(r=>(this.#N.run(r),this.#D.run(r),this.#M.run(r)));try{return De(()=>n(e)).changes}catch(r){throw Ke("store.cleanupStaleSources",r,this.#t)}}getDBSizeBytes(){try{return uu(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(e){tt("store.optimizeFTS",e,this.#t)}}close(){this.#U(),Bi(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!ds.has(s)),r=[...new Set(n)],o=0;this.#e.transaction(()=>{for(let s of r){let i=this.#i.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#K(e,n=cu){let r=[],o=e.split(`
558
558
  `),s=[],i=[],a="",c=()=>{let l=i.join(`
559
559
  `).trim();if(l.length===0)return;let d=this.#ee(s,a),f=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=n){r.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(`
560
560
 
@@ -562,13 +562,13 @@ ${r}`}}};import{cpus as ML}from"node:os";async function sh(t,e){let{concurrency:
562
562
 
563
563
  `);Buffer.byteLength(_)>n&&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(),r}#G(e,n){if(Buffer.byteLength(e)<=n)return e;let r="",o=0;for(let s of e){let i=Buffer.byteLength(s);if(o+i>n)break;r+=s,o+=i}return r.length===0?[...e][0]??"":r}#f(e,n,r){let o=[],s=[],i=1,a=()=>{if(s.length===0)return;let c=s.join(`
564
564
  `),u=i===1?n:`${n} (${i})`;o.push({title:u,content:c}),i++,s=[]};for(let c of e){if(Buffer.byteLength(c)>r){a();let l=c,d=1;for(;l.length>0;){let f=this.#G(l,r);if(f.length<l.length){let p=f.lastIndexOf(" "),h=f.lastIndexOf(`
565
- `),g=Math.max(p,h);g>f.length*gz&&(f=f.slice(0,g))}let m=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:m,content:f}),l=l.slice(f.length),d++,i++}continue}let u=s.length>0?s.join(`
565
+ `),g=Math.max(p,h);g>f.length*yz&&(f=f.slice(0,g))}let m=i===1&&d===1?n:`${n} (${i}.${d})`;o.push({title:m,content:f}),l=l.slice(f.length),d++,i++}continue}let u=s.length>0?s.join(`
566
566
  `)+`
567
- `+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=uu){let o=e.split(/\n\s*\n/);if(o.length>=fz&&o.length<=mz&&o.every(u=>Buffer.byteLength(u)<hz))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let f=d.split(`
568
- `)[0].slice(0,eE)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:f,content:d}]:this.#f(d.split(`
567
+ `+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=cu){let o=e.split(/\n\s*\n/);if(o.length>=mz&&o.length<=hz&&o.every(u=>Buffer.byteLength(u)<gz))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let f=d.split(`
568
+ `)[0].slice(0,Qv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:f,content:d}]:this.#f(d.split(`
569
569
  `),f,r)});let s=e.split(`
570
- `);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#f(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,f=Math.min(u+l.length,s.length),m=l[0]?.trim().slice(0,eE),p=l.join(`
571
- `);if(Buffer.byteLength(p)<=r)i.push({title:m||`Lines ${d}-${f}`,content:p});else{let h=this.#f(l,m||`Lines ${d}-${f}`,r);i.push(...h)}}return i}#F(e,n,r,o){let s=n.length>0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.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)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}};function gh(t,e){return t===void 0?e:`${t}::${e}`}co();function iE(t){try{let e=new URL(t);return e.hash="",e.toString()}catch{return t}}function aE(t){try{return new URL(t).host.toLowerCase()}catch{return""}}var pu=class{#e;constructor(e){let n=qe();ao(e),this.#e=new n(e,{timeout:3e4}),ps(this.#e),this.#e.exec(`
570
+ `);if(s.length<=n)return Buffer.byteLength(e)<=r?[{title:"Output",content:e}]:this.#f(s,"Output",r);let i=[],c=Math.max(n-2,1);for(let u=0;u<s.length;u+=c){let l=s.slice(u,u+n);if(l.length===0)break;let d=u+1,f=Math.min(u+l.length,s.length),m=l[0]?.trim().slice(0,Qv),p=l.join(`
571
+ `);if(Buffer.byteLength(p)<=r)i.push({title:m||`Lines ${d}-${f}`,content:p});else{let h=this.#f(l,m||`Lines ${d}-${f}`,r);i.push(...h)}}return i}#F(e,n,r,o){let s=n.length>0?n.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))){r.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.#F(u,[...n,c],r,o);return}r.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#Q(e,n,r,o);return}r.push({title:s,content:i,hasCode:!1})}#X(e){if(e.length===0)return null;let n=e[0];if(typeof n!="object"||n===null||Array.isArray(n))return null;let r=["id","name","title","path","slug","key","label"],o=n;for(let s of r)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#Y(e,n,r,o,s){let i=e?`${e} > `:"";if(!s)return n===r?`${i}[${n}]`:`${i}[${n}-${r}]`;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])}`}#Q(e,n,r,o){let s=n.length>0?n.join(" > "):"(root)",i=this.#X(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#Y(s,c,l,a,i);r.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)}#ee(e,n){return e.length===0?n||"Untitled":e.map(r=>r.text).join(" > ")}};function mh(t,e){return t===void 0?e:`${t}::${e}`}ao();function aE(t){try{let e=new URL(t);return e.hash="",e.toString()}catch{return t}}function cE(t){try{return new URL(t).host.toLowerCase()}catch{return""}}var du=class{#e;constructor(e){let n=qe();io(e),this.#e=new n(e,{timeout:3e4}),ls(this.#e),this.#e.exec(`
572
572
  CREATE TABLE IF NOT EXISTS pages (
573
573
  page_key TEXT PRIMARY KEY,
574
574
  host TEXT NOT NULL,
@@ -601,31 +601,31 @@ ${r}`}}};import{cpus as ML}from"node:os";async function sh(t,e){let{concurrency:
601
601
  host = excluded.host, url = excluded.url, source_label = excluded.source_label,
602
602
  route = excluded.route, provisional = excluded.provisional,
603
603
  fetched_at = excluded.fetched_at, full_text = excluded.full_text`),o=this.#e.prepare("DELETE FROM page_blocks WHERE page_key = ?"),s=this.#e.prepare("INSERT INTO page_blocks (page_key, ordinal, hash, kind, raw, text) VALUES (?, ?, ?, ?, ?, ?)"),i=this.#e.transaction(()=>{r.run(e.pageKey,e.host,e.url,e.sourceLabel,e.route,e.provisional?1:0,e.fullText),o.run(e.pageKey);for(let a of n)s.run(e.pageKey,a.ordinal,a.hash,a.kind,a.raw,a.text)});De(()=>i())}relabelPage(e,n,r){let o=this.#e.prepare("UPDATE page_blocks SET kind = ? WHERE page_key = ? AND ordinal = ?"),s=this.#e.prepare("UPDATE pages SET provisional = ? WHERE page_key = ?"),i=this.#e.transaction(()=>{for(let a of n)o.run(a.kind,e,a.ordinal);s.run(r?1:0,e)});De(()=>i())}provisionalPages(e,n){return this.#e.prepare(`SELECT page_key, host, url, source_label, route, provisional, full_text
604
- FROM pages WHERE host = ? AND provisional = 1 AND page_key <> ?`).all(e,n).map(o=>({pageKey:String(o.page_key),host:String(o.host),url:String(o.url),sourceLabel:String(o.source_label),route:String(o.route),provisional:Number(o.provisional)===1,fullText:String(o.full_text)}))}blocksOf(e){return this.#e.prepare("SELECT ordinal, hash, kind, raw, text FROM page_blocks WHERE page_key = ? ORDER BY ordinal").all(e).map(r=>({ordinal:Number(r.ordinal),hash:String(r.hash),kind:String(r.kind)==="template"?"template":"content",raw:String(r.raw),text:String(r.text)}))}fullTextOf(e){let n=this.#e.prepare("SELECT full_text FROM pages WHERE page_key = ?").get(e);return n?n.full_text:null}close(){try{this.#e.close()}catch{}}};import{createHash as Sz}from"node:crypto";function yh(t,e){return t.lastIndexOf(e,0)===0}function _h(t){return t===" "||t===" "||t===`
605
- `||t==="\r"||t==="\f"||t==="\v"}function xh(t){let e=0,n=t.length;for(;e<n&&_h(t.charAt(e));)e++;for(;n>e&&_h(t.charAt(n-1));)n--;return e===0&&n===t.length?t:t.substring(e,n)}function kz(t){let e=[],n=0;for(let r=0;r<t.length;r++)t.charAt(r)===`
606
- `&&(e.push(t.substring(n,r+1)),n=r+1);return n<t.length&&e.push(t.substring(n)),e}function cE(t){let e=[];if(t.length===0)return e;let n=kz(t),r=[],o=!1,s=!1,i=!1,a=()=>{if(r.length===0)return;let c=r.join(""),u=xh(c);e.push({ordinal:e.length,raw:c,text:u,hash:Ez(u)}),r=[],o=!1};for(let c of n){let u=xh(c),l=yh(u,"```")||yh(u,"~~~"),d=!s&&u.length===0,f=!s&&!l&&yh(u,"#");!d&&(i||f)&&o&&(a(),i=!1),l&&(s=!s),r.push(c),d||(o=!0),d&&(i=!0)}return a(),e}function vz(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t.charAt(r);if(_h(o)){n=!0;continue}n&&e.length>0&&(e+=" "),n=!1,e+=o}return e.toLowerCase()}function Ez(t){return Sz("sha256").update(vz(t),"utf-8").digest("hex")}function bh(t){let{blocks:e,otherPageCount:n,hostPageCount:r,authored:o}=t,s=!o&&r<1,i=[],a=0,c=0,u=!1,l=!1;for(let d of e){let f=d.text.length>0;f&&(l=!0);let p=f&&!o&&!s&&n(d.hash)>=1?"template":"content";p==="content"?(f&&(u=!0),a+=Buffer.byteLength(d.text,"utf-8")):c+=Buffer.byteLength(d.text,"utf-8"),i.push({...d,kind:p})}return{blocks:i,provisional:s,allTemplate:l&&!u,contentBytes:a,templateBytes:c}}function Sh(t){let e="";for(let n of t)n.kind==="content"&&(e+=n.raw);return xh(e)}function uE(t){return t==="json"||t==="text"}function lE(t){let{url:e,sourceLabel:n,document:r,route:o,store:s}=t,i=iE(e),a=aE(e),c=Buffer.byteLength(r,"utf-8"),u=cE(r),l=o==="markdown",d=s.hostPageCount(a,i),f=l?new Map:s.otherPageCounts(a,i,u.map(h=>h.hash)),m=bh({blocks:u,otherPageCount:h=>f.get(h)??0,hostPageCount:d,authored:l});if(s.recordPage({pageKey:i,host:a,url:e,sourceLabel:n,route:o,provisional:m.provisional,fullText:r},m.blocks),m.allTemplate)return{kind:"refuse",storedBytes:c,route:o,reason:`every block of this page is byte-identical to blocks already seen on other pages of ${a}, so the response carried the site shell rather than this page \u2014 its content is rendered client-side by JavaScript and an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered). Retrying this URL returns the same shell; look for this site's llms.txt, a raw .md source, an OpenAPI spec, or a repository README instead.`};let p=[];if(!m.provisional)for(let h of s.provisionalPages(a,i)){let g=s.blocksOf(h.pageKey),y=s.otherPageCounts(a,h.pageKey,g.map(x=>x.hash)),_=bh({blocks:g.map(x=>({ordinal:x.ordinal,raw:x.raw,text:x.text,hash:x.hash})),otherPageCount:x=>y.get(x)??0,hostPageCount:s.hostPageCount(h.host,h.pageKey),authored:h.route==="markdown"});_.allTemplate||(s.relabelPage(h.pageKey,_.blocks,_.provisional),_.templateBytes>0&&p.push({sourceLabel:h.sourceLabel,url:h.url,indexText:Sh(_.blocks),templateBytes:_.templateBytes}))}return{kind:"index",indexText:Sh(m.blocks),storedBytes:c,contentBytes:m.contentBytes,templateBytes:m.templateBytes,templateBlocks:wz(m.blocks),totalBlocks:m.blocks.length,provisional:m.provisional,route:o,relabelled:p}}function wz(t){let e=0;for(let n of t)n.kind==="template"&&e++;return e}po();import{readFileSync as $T,realpathSync as Mg}from"node:fs";import{relative as YH,resolve as ko,sep as QH}from"node:path";function OT(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function eU(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function tU(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function CT(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function nU(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=tU(o),a=CT(s);n=`^${i}(\\s${a})?$`}else n=`^${CT(t)}$`;return new RegExp(n,e?"i":"")}function rU(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function oU(t,e,n=!1){for(let r of e){let o=OT(r);if(o&&nU(o,n).test(t))return r}return null}function IT(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function sU(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=IT(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
607
- `||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function AT(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=IT(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...AT(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),f=t.slice(d,c);e.push(f)}}}return e}function NT(t){let e=[],n=sU(t);for(let r of n){e.push(r);for(let o of AT(r))e.push(...NT(o))}return e}function Dg(t){let e;try{e=$T(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&OT(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function jg(t,e){let n=[];if(t){let o=ko(t,".claude","settings.local.json"),s=Dg(o);s&&n.push(s);let i=ko(t,".claude","settings.json"),a=Dg(i);a&&n.push(a)}let r=e!==void 0?[e]:Ng();for(let o of r){let s=Dg(o);s&&n.push(s)}return n}function Hu(t,e,n){return Lg(t,"deny",e,n)}function Lg(t,e,n,r){let o=[],s=a=>{let c;try{c=$T(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let f of l){if(typeof f!="string")continue;let m=eU(f);m&&m.tool===t&&d.push(m.glob)}return d};if(n){let a=s(ko(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(ko(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:Ng();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function zg(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=NT(t);for(let o of r)for(let s of e){let i=oU(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function ia(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=ko(r,t);s.add(o(i));try{s.add(o(Mg(i)))}catch{}}for(let i of e)for(let a of i){let c=rU(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function iU(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=ko(e),o=ko(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=YH(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+QH)||aU(l))};if(!s(r,o))return!1;try{let i=Mg(r),a=Mg(o);if(!s(i,a))return!1}catch{}return!0}function aU(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function DT(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return iU(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&ia(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}var cU={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 uU(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function MT(t,e){let n=cU[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...uU(t)),r}ru();function Hg(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
604
+ FROM pages WHERE host = ? AND provisional = 1 AND page_key <> ?`).all(e,n).map(o=>({pageKey:String(o.page_key),host:String(o.host),url:String(o.url),sourceLabel:String(o.source_label),route:String(o.route),provisional:Number(o.provisional)===1,fullText:String(o.full_text)}))}blocksOf(e){return this.#e.prepare("SELECT ordinal, hash, kind, raw, text FROM page_blocks WHERE page_key = ? ORDER BY ordinal").all(e).map(r=>({ordinal:Number(r.ordinal),hash:String(r.hash),kind:String(r.kind)==="template"?"template":"content",raw:String(r.raw),text:String(r.text)}))}fullTextOf(e){let n=this.#e.prepare("SELECT full_text FROM pages WHERE page_key = ?").get(e);return n?n.full_text:null}close(){try{this.#e.close()}catch{}}};import{createHash as kz}from"node:crypto";function hh(t,e){return t.lastIndexOf(e,0)===0}function gh(t){return t===" "||t===" "||t===`
605
+ `||t==="\r"||t==="\f"||t==="\v"}function yh(t){let e=0,n=t.length;for(;e<n&&gh(t.charAt(e));)e++;for(;n>e&&gh(t.charAt(n-1));)n--;return e===0&&n===t.length?t:t.substring(e,n)}function vz(t){let e=[],n=0;for(let r=0;r<t.length;r++)t.charAt(r)===`
606
+ `&&(e.push(t.substring(n,r+1)),n=r+1);return n<t.length&&e.push(t.substring(n)),e}function uE(t){let e=[];if(t.length===0)return e;let n=vz(t),r=[],o=!1,s=!1,i=!1,a=()=>{if(r.length===0)return;let c=r.join(""),u=yh(c);e.push({ordinal:e.length,raw:c,text:u,hash:wz(u)}),r=[],o=!1};for(let c of n){let u=yh(c),l=hh(u,"```")||hh(u,"~~~"),d=!s&&u.length===0,f=!s&&!l&&hh(u,"#");!d&&(i||f)&&o&&(a(),i=!1),l&&(s=!s),r.push(c),d||(o=!0),d&&(i=!0)}return a(),e}function Ez(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t.charAt(r);if(gh(o)){n=!0;continue}n&&e.length>0&&(e+=" "),n=!1,e+=o}return e.toLowerCase()}function wz(t){return kz("sha256").update(Ez(t),"utf-8").digest("hex")}function _h(t){let{blocks:e,otherPageCount:n,hostPageCount:r,authored:o}=t,s=!o&&r<1,i=[],a=0,c=0,u=!1,l=!1;for(let d of e){let f=d.text.length>0;f&&(l=!0);let p=f&&!o&&!s&&n(d.hash)>=1?"template":"content";p==="content"?(f&&(u=!0),a+=Buffer.byteLength(d.text,"utf-8")):c+=Buffer.byteLength(d.text,"utf-8"),i.push({...d,kind:p})}return{blocks:i,provisional:s,allTemplate:l&&!u,contentBytes:a,templateBytes:c}}function xh(t){let e="";for(let n of t)n.kind==="content"&&(e+=n.raw);return yh(e)}function lE(t){return t==="json"||t==="text"}function dE(t){let{url:e,sourceLabel:n,document:r,route:o,store:s}=t,i=aE(e),a=cE(e),c=Buffer.byteLength(r,"utf-8"),u=uE(r),l=o==="markdown",d=s.hostPageCount(a,i),f=l?new Map:s.otherPageCounts(a,i,u.map(h=>h.hash)),m=_h({blocks:u,otherPageCount:h=>f.get(h)??0,hostPageCount:d,authored:l});if(s.recordPage({pageKey:i,host:a,url:e,sourceLabel:n,route:o,provisional:m.provisional,fullText:r},m.blocks),m.allTemplate)return{kind:"refuse",storedBytes:c,route:o,reason:`every block of this page is byte-identical to blocks already seen on other pages of ${a}, so the response carried the site shell rather than this page \u2014 its content is rendered client-side by JavaScript and an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered). Retrying this URL returns the same shell; look for this site's llms.txt, a raw .md source, an OpenAPI spec, or a repository README instead.`};let p=[];if(!m.provisional)for(let h of s.provisionalPages(a,i)){let g=s.blocksOf(h.pageKey),y=s.otherPageCounts(a,h.pageKey,g.map(x=>x.hash)),_=_h({blocks:g.map(x=>({ordinal:x.ordinal,raw:x.raw,text:x.text,hash:x.hash})),otherPageCount:x=>y.get(x)??0,hostPageCount:s.hostPageCount(h.host,h.pageKey),authored:h.route==="markdown"});_.allTemplate||(s.relabelPage(h.pageKey,_.blocks,_.provisional),_.templateBytes>0&&p.push({sourceLabel:h.sourceLabel,url:h.url,indexText:xh(_.blocks),templateBytes:_.templateBytes}))}return{kind:"index",indexText:xh(m.blocks),storedBytes:c,contentBytes:m.contentBytes,templateBytes:m.templateBytes,templateBlocks:Tz(m.blocks),totalBlocks:m.blocks.length,provisional:m.provisional,route:o,relabelled:p}}function Tz(t){let e=0;for(let n of t)n.kind==="template"&&e++;return e}lo();import{readFileSync as OT,realpathSync as Dg}from"node:fs";import{relative as YH,resolve as So,sep as QH}from"node:path";function IT(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function eU(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function tU(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function $T(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function nU(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=tU(o),a=$T(s);n=`^${i}(\\s${a})?$`}else n=`^${$T(t)}$`;return new RegExp(n,e?"i":"")}function rU(t,e=!1){let n="",r=0;for(;r<t.length;)t[r]==="*"&&t[r+1]==="*"?r+2<t.length&&t[r+2]==="/"?(n+="(.*/)?",r+=3):(n+=".*",r+=2):t[r]==="*"?(n+="[^/]*",r++):t[r]==="?"?(n+="[^/]",r++):(n+=t[r].replace(/[.+^${}()|[\]\\\/\-]/g,"\\$&"),r++);return new RegExp(`^${n}$`,e?"i":"")}function oU(t,e,n=!1){for(let r of e){let o=IT(r);if(o&&nU(o,n).test(t))return r}return null}function AT(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function sU(t){let e=[],n="",r=!1,o=!1,s=!1,i=0;for(let a=0;a<t.length;a++){let c=t[a],u=AT(t,a);c==="'"&&!o&&!s&&!u?(r=!r,n+=c):c==='"'&&!r&&!s&&!u?(o=!o,n+=c):c==="`"&&!r&&!o&&!u?(s=!s,n+=c):!r&&!o&&!s?c==="$"&&t[a+1]==="("&&!u?(i++,n+=c+t[a+1],a++):i>0&&c==="("&&!u?(i++,n+=c):c===")"&&i>0&&!u?(i--,n+=c):i===0&&(c===";"||c===`
607
+ `||c==="\r")&&!u?(e.push(n.trim()),n=""):i===0&&c==="|"&&t[a+1]==="|"||i===0&&c==="&"&&t[a+1]==="&"?(e.push(n.trim()),n="",a++):i===0&&c==="&"&&!u||i===0&&c==="|"?(e.push(n.trim()),n=""):n+=c:n+=c}return n.trim()&&e.push(n.trim()),e.filter(a=>a.length>0)}function NT(t){let e=[],n=!1,r=!1,o=-1,s=[],i=[],a=0;for(let c=0;c<t.length;c++){let u=t[c],l=AT(t,c);if(u==="'"&&!r&&o===-1&&!l)n=!n;else if(u==='"'&&!n&&o===-1&&!l)r=!r;else if(u==="`"&&!n&&!r&&!l)if(o===-1)o=c+1;else{let d=t.slice(o,c);e.push(d),e.push(...NT(d)),o=-1}else if(!n&&o===-1){if(u==="$"&&t[c+1]==="("&&!l)t[c+2]==="("?(a+=2,c+=2):(s.push(c+2),i.push(a),a++,c++);else if(u==="("&&!l)a++;else if(u===")"&&!l&&(a>0&&a--,i.length>0&&a===i[i.length-1])){i.pop();let d=s.pop(),f=t.slice(d,c);e.push(f)}}}return e}function DT(t){let e=[],n=sU(t);for(let r of n){e.push(r);for(let o of NT(r))e.push(...DT(o))}return e}function Ng(t){let e;try{e=OT(t,"utf-8")}catch{return null}let n;try{n=JSON.parse(e)}catch{return null}let r=n?.permissions;if(!r||typeof r!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&IT(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function Mg(t,e){let n=[];if(t){let o=So(t,".claude","settings.local.json"),s=Ng(o);s&&n.push(s);let i=So(t,".claude","settings.json"),a=Ng(i);a&&n.push(a)}let r=e!==void 0?[e]:Ag();for(let o of r){let s=Ng(o);s&&n.push(s)}return n}function zu(t,e,n){return jg(t,"deny",e,n)}function jg(t,e,n,r){let o=[],s=a=>{let c;try{c=OT(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.[e];if(!Array.isArray(l))return[];let d=[];for(let f of l){if(typeof f!="string")continue;let m=eU(f);m&&m.tool===t&&d.push(m.glob)}return d};if(n){let a=s(So(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(So(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:Ag();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function Lg(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=DT(t);for(let o of r)for(let s of e){let i=oU(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function ia(t,e,n=process.platform==="win32"||process.platform==="darwin",r){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),r){let i=So(r,t);s.add(o(i));try{s.add(o(Dg(i)))}catch{}}for(let i of e)for(let a of i){let c=rU(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function iU(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=So(e),o=So(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=YH(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+QH)||aU(l))};if(!s(r,o))return!1;try{let i=Dg(r),a=Dg(o);if(!s(i,a))return!1}catch{}return!0}function aU(t){if(t.startsWith("/"))return!0;if(t.length>=3&&t[1]===":"&&(t[2]==="\\"||t[2]==="/")){let e=t.charCodeAt(0);return e>=65&&e<=90||e>=97&&e<=122}return!1}function MT(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return iU(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&ia(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}var cU={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 uU(t){let e=[],n=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,r;for(;(r=n.exec(t))!==null;){let s=[...r[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function jT(t,e){let n=cU[e];if(!n&&e!=="python")return[];let r=[];if(n)for(let o of n){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&r.push(i)}}return e==="python"&&r.push(...uU(t)),r}nu();function zg(t){let{language:e,exitCode:n,stdout:r,stderr:o}=t,s=e==="shell"&&n===1&&r.trim().length>0;return{isError:!s,output:s?r:`Exit code: ${n}
608
608
 
609
609
  stdout:
610
610
  ${r}
611
611
 
612
612
  stderr:
613
- ${o}`}}import{execFileSync as lU}from"node:child_process";function dU(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=lU("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function pU(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??dU,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var fU=pU();function mU(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function hU(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function gU(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}var aa=Date.now(),Uu=0;function Ug(){aa=Date.now()}function jT(){Uu++,aa=Date.now()}function LT(){Uu>0&&Uu--,aa=Date.now()}function zT(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{Ug()}catch{}return e(n,r)})}function HT(t){let e=t.checkIntervalMs??mU(),n=t.isParentAlive??fU,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??hU(),u;return c>0&&(aa=Date.now(),u=setInterval(()=>{Uu===0&&Date.now()-aa>=c&&(process.stderr.write(gU(c)+`
614
- `),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}function UT(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}Pn();co();Pn();import{existsSync as Fg,unlinkSync as yU}from"node:fs";import{join as ca}from"node:path";var _U=["","-wal","-shm"];function Bg(t,e){try{return yU(t),e.push(t),!0}catch{return!1}}function Fu(t,e){let n=!1;for(let r of _U)Bg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function FT(t){let{projectDir:e,sessionsDir:n,storePath:r,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 x=yu(e),b=nt(e),v=Fn(e),O=b===v?[b]:[b,v],R=!1;for(let V of O){let w=ca(n,`${V}${x}.db`);if(!Fg(w))continue;let P=null;try{P=new ln({dbPath:w});let H=P.getEvents(a).length;P.deleteSession(a),H>0&&(R=!0)}catch{}finally{try{P?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let j=[];if(r&&Fg(r)&&j.push(r),o){let V=nt(e),w=Fn(e),P=V===w?[V]:[V,w];for(let H of P){let se=ca(o,`${H}.db`);Fg(se)&&!j.includes(se)&&j.push(se)}}let M=!1;for(let V of j)try{let w=qe(),P=new w(V,{timeout:3e4});try{let H=P.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;P.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),P.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(M=!0)}finally{try{P.close()}catch{}}}catch{}return M&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Fu(r,l)&&(f=!0),o){let x=nt(e),b=Fn(e),v=x===b?[x]:[x,b];for(let O of v){let R=ca(o,`${O}.db`);Fu(R,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 x=ca(s,`${i}.db`);Fu(x,l)}let m=yu(e),p=nt(e),h=Fn(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let x of g){let b=ca(n,`${x}${m}`);Fu(`${b}.db`,l)&&(y=!0),Bg(`${b}-events.md`,l)&&(_=!0),Bg(`${b}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}ku();Pn();import{existsSync as xU}from"node:fs";function Zg(t,e){try{if(!xU(t))return;let n=new ln({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function BT(t){Zg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 ZT(t){Zg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 qT(t){Zg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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})})}Pn();import{existsSync as VT}from"node:fs";function WT(t,e,n){try{if(!VT(t))return;let r=new ln({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function KT(t){try{if(!VT(t))return null;let e=new ln({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);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}}po();Pn();import{existsSync as qg,readFileSync as bU,readdirSync as SU,statSync as kU}from"node:fs";import{join as Ts,isAbsolute as vU}from"node:path";var GT=process.env.DEBUG?.includes("context-mode");function XT(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?JT(n,a):null)??r??Dt(),l=o?.getMemoryDir(n),d=Ts(u,"memory"),f=n?Ts(d,nt(n)):d,m=l?JT(n,l):f,p=[];if(n)for(let h of i){let g=Ts(n,h);qg(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=Ts(u,h);qg(g)&&p.push({path:g,label:`user/${h}`})}if(m&&qg(m))try{let h=SU(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:Ts(m,g),label:`memory/${g}`})}catch(h){GT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
613
+ ${o}`}}import{execFileSync as lU}from"node:child_process";function dU(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=lU("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),n=parseInt(e,10);return Number.isFinite(n)?n:NaN}catch{return NaN}}function pU(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??dU,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var fU=pU();function mU(t=process.env){let e=t.CONTEXT_MODE_BRIDGE_DEPTH;if(e===void 0)return 3e4;let n=Number.parseInt(e,10);return!Number.isFinite(n)||n<=0?3e4:1e3}function hU(t=process.env){let e=Number.parseInt(t.CONTEXT_MODE_BRIDGE_DEPTH??"",10);if(!Number.isFinite(e)||e<=0)return 0;let n=t.CONTEXT_MODE_BRIDGE_IDLE_MS;if(n!==void 0){let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>0?r:0}return 18e4}function gU(t){return`[context-mode] Released an idle MCP helper after ${Math.round(t/1e3)}s of inactivity to free memory; it reconnects automatically on next use. (#854)`}var aa=Date.now(),Hu=0;function Hg(){aa=Date.now()}function LT(){Hu++,aa=Date.now()}function zT(){Hu>0&&Hu--,aa=Date.now()}function HT(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{Hg()}catch{}return e(n,r)})}function UT(t){let e=t.checkIntervalMs??mU(),n=t.isParentAlive??fU,r=!1,o=()=>{r||(r=!0,t.onShutdown())},s=setInterval(()=>{n()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let l of i)process.on(l,o);let a=()=>{n()||o()};process.stdin.isTTY||process.stdin.on("end",a);let c=t.bridgeIdleMs??hU(),u;return c>0&&(aa=Date.now(),u=setInterval(()=>{Hu===0&&Date.now()-aa>=c&&(process.stderr.write(gU(c)+`
614
+ `),o())},Math.max(1e3,Math.min(Math.floor(c/4),3e4))),u.unref()),()=>{r=!0,clearInterval(s),u&&clearInterval(u);for(let l of i)process.removeListener(l,o);process.stdin.removeListener("end",a)}}function FT(t,e){if(e<=0)return"";if(t.length<=e)return t;let n=e,r=t.charCodeAt(n-1);return r>=55296&&r<=56319&&(n-=1),t.slice(0,n)}Tn();ao();Tn();import{existsSync as Ug,unlinkSync as yU}from"node:fs";import{join as ca}from"node:path";var _U=["","-wal","-shm"];function Fg(t,e){try{return yU(t),e.push(t),!0}catch{return!1}}function Uu(t,e){let n=!1;for(let r of _U)Fg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function BT(t){let{projectDir:e,sessionsDir:n,storePath:r,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 x=gu(e),b=nt(e),v=Un(e),O=b===v?[b]:[b,v],R=!1;for(let V of O){let w=ca(n,`${V}${x}.db`);if(!Ug(w))continue;let P=null;try{P=new ln({dbPath:w});let H=P.getEvents(a).length;P.deleteSession(a),H>0&&(R=!0)}catch{}finally{try{P?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let j=[];if(r&&Ug(r)&&j.push(r),o){let V=nt(e),w=Un(e),P=V===w?[V]:[V,w];for(let H of P){let se=ca(o,`${H}.db`);Ug(se)&&!j.includes(se)&&j.push(se)}}let M=!1;for(let V of j)try{let w=qe(),P=new w(V,{timeout:3e4});try{let H=P.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;P.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),P.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(M=!0)}finally{try{P.close()}catch{}}}catch{}return M&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Uu(r,l)&&(f=!0),o){let x=nt(e),b=Un(e),v=x===b?[x]:[x,b];for(let O of v){let R=ca(o,`${O}.db`);Uu(R,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 x=ca(s,`${i}.db`);Uu(x,l)}let m=gu(e),p=nt(e),h=Un(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let x of g){let b=ca(n,`${x}${m}`);Uu(`${b}.db`,l)&&(y=!0),Fg(`${b}-events.md`,l)&&(_=!0),Fg(`${b}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}Su();Tn();import{existsSync as xU}from"node:fs";function Bg(t,e){try{if(!xU(t))return;let n=new ln({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function ZT(t){Bg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 qT(t){Bg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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 VT(t){Bg(t.sessionDbPath,(e,n)=>{e.insertEvent(n,{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})})}Tn();import{existsSync as WT}from"node:fs";function KT(t,e,n){try{if(!WT(t))return;let r=new ln({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function GT(t){try{if(!WT(t))return null;let e=new ln({dbPath:t});try{let n=e.getLatestSessionId();if(!n)return null;let r=e.getToolCallStats(n),o={},s={};for(let[a,c]of Object.entries(r.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(n);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}}lo();Tn();import{existsSync as Zg,readFileSync as bU,readdirSync as SU,statSync as kU}from"node:fs";import{join as Es,isAbsolute as vU}from"node:path";var JT=process.env.DEBUG?.includes("context-mode");function YT(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?XT(n,a):null)??r??Dt(),l=o?.getMemoryDir(n),d=Es(u,"memory"),f=n?Es(d,nt(n)):d,m=l?XT(n,l):f,p=[];if(n)for(let h of i){let g=Es(n,h);Zg(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=Es(u,h);Zg(g)&&p.push({path:g,label:`user/${h}`})}if(m&&Zg(m))try{let h=SU(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:Es(m,g),label:`memory/${g}`})}catch(h){JT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
615
615
  `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=kU(h.path),g.size>1e6)continue}catch{continue}let y=bU(h.path,"utf-8"),_=y.toLowerCase();for(let x of t){if(s.length>=e)break;let v=x.toLowerCase().split(/\s+/).filter(R=>R.length>=3);if(v.some(R=>{try{return new RegExp(`\\b${R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(R)}})){let R=v.reduce((H,se)=>{let _t=_.indexOf(se);return _t>=0&&(H<0||_t<H)?_t:H},-1),j=Math.max(0,R-200),M=Math.min(y.length,R+500),V=y.lastIndexOf(`
616
616
 
617
617
  `,j),w=y.indexOf(`
618
618
 
619
- `,M);V>=0&&(j=V+2),w>=0&&(M=w);let P=y.slice(j,M).trim();s.push({title:`[auto-memory] ${h.label}`,content:P,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){GT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
620
- `)}}return s.slice(0,e)}function JT(t,e){return e?vU(e)||!t?e:Ts(t,e):t??""}var Bu=process.env.DEBUG?.includes("context-mode");function YT(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,f=[],m=new Date().toISOString(),p;if(typeof d=="string"&&a)try{p=new Set(a.getSessionIdsForProject(d))}catch(h){Bu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
621
- `)}try{let h=r.searchWithFallback(e,n,s,i,"like",p);f.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||m,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){Bu&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
622
- `)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);f.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){Bu&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
623
- `)}try{let h=XT([e],n,c,u,l);f.push(...h)}catch(h){Bu&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
624
- `)}}for(let h of f)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&f.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),f.slice(0,n)}function EU(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function QT(t){let e=t?{project:$.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return $.object({queries:$.preprocess(EU,$.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."),...e})}function eP(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var Vg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var Zu=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}};Un();ws();Kh();Un();function wU(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function TU(t){let e=tu(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function tP(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of wU(s)){let a=TU(i);a&&n.add(a)}return[...n]}Yi();po();ws();import*as Fe from"node:fs";import*as nP from"node:os";import*as Ps from"node:path";var PU=["CONTEXT_MODE_PROJECT_DIR"],RU=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function qu(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function CU(t){if(!Fe.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Fe.readdirSync(t.projectsRoot)){let o=Ps.join(t.projectsRoot,r),s;try{s=Fe.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Fe.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=Ps.join(o,a);try{let u=Fe.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Fe.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Fe.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
625
- `).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{Fe.closeSync(r)}}catch{}}function $U(t){let e=t?.codexHome??process.env.CODEX_HOME??Ps.join(nP.homedir(),".codex"),n=Ps.join(e,"sessions");if(!Fe.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Fe.readdirSync(u)}catch{return}d.sort().reverse();for(let f of d){if(s>=o)return;s++;let m=Ps.join(u,f),p;try{p=Fe.statSync(m)}catch{continue}if(p.isDirectory()){l<r&&c(m,l+1);continue}if(!p.isFile()||!f.endsWith(".jsonl"))continue;let h=p.mtimeMs;h>a&&(a=h,i=m)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Fe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Fe.readSync(u,l,0,l.length,0),f=l.subarray(0,d).toString("utf-8");for(let m of f.split(`
626
- `).slice(0,10))if(m.trim())try{let p=JSON.parse(m),h=p?.meta?.cwd??(p?.type==="session_meta"?p?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return qu(h)?null:h}catch{return null}}finally{Fe.closeSync(u)}}catch{return null}return null}function rP(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...Og(a),...PU]:RU;for(let l of u){let d=e[l];if(d&&!qu(d))return d}if(o){let l=CU({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!qu(l))return l}if(a==="codex"){let l=$U({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!qu(r)?r:n}co();co();Pn();po();import{execFileSync as OU}from"node:child_process";import{existsSync as Wn,readdirSync as Rs,statSync as IU}from"node:fs";import{homedir as Ju}from"node:os";import{join as Mt,sep as AU}from"node:path";function dP(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}var Wu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"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"},NU={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"},Cs=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=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=n.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)}n.set(i,a)}let r=[];for(let[o,s]of n){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=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((P,H)=>P+H,0),s=Object.values(e.calls).reduce((P,H)=>P+H,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(P=>({tool:P,calls:e.calls[P]||0,context_kb:Math.round((e.bytesReturned[P]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[P]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let P=a+e.cacheBytesSaved,H=P/Math.max(o,1),se=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),_t=e.cacheHits+h,$n=_t>0?e.cacheHits/_t:0;p={hits:e.cacheHits,misses:h,hit_rate:$n,bytes_saved:e.cacheBytesSaved,ttl_hours_left:se,total_with_cache:P,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,b=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=b?!b.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),R=new Map;for(let P of O){R.has(P.category)||R.set(P.category,new Set);let H=R.get(P.category);if(H.size<5){let se=P.data;P.category==="file"?se=P.data.split("/").pop()||P.data:(P.category==="prompt"||P.category==="user-prompt")&&(se=se.length>50?se.slice(0,47)+"...":se),se.length>40&&(se=se.slice(0,37)+"..."),H.add(se)}}let j=y.map(P=>({category:P.category,count:P.cnt,label:Wu[P.category]||P.category,preview:R.get(P.category)?Array.from(R.get(P.category)).join(", "):"",why:NU[P.category]||"Survives context resets"})),M=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(P=>P.cnt>0).map(P=>({category:P.category,count:P.cnt,label:Wu[P.category]||P.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:r,uptime_min:m},continuity:{total_events:g,by_category:j,compact_count:x,resume_ready:v},projectMemory:{total_events:M.cnt,session_count:M.sessions,by_category:w}}}};function DU(t){let e=t?.home??Ju();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=Mt(e,...o,"context-mode");return{name:r,sessionsDir:Mt(s,"sessions"),contentDir:Mt(s,"content")}})}function MU(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function ua(t){let e=Dt(),n=t?.sessionsDir??Mt(e,"context-mode","sessions"),r=t?.memoryRoot??Mt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Wn(n)){let m=[];try{m=Rs(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():qe()}catch{}if(p)for(let h of m){let g=Mt(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of b)v.category&&(u[v.category]=(u[v.category]??0)+(v.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 v=b.t.endsWith("Z")?b.t:b.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of b)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Wn(r)){let m=[];try{m=Rs(r).filter(p=>{try{return IU(Mt(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Mt(r,p,"memory");if(!Wn(h))continue;let g=[];try{g=Rs(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=MU(y);f[_]=(f[_]??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 pP(t){let e=t.sessionsDir??Mt(Ju(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Wn(e))return r;let o=[];try{o=Rs(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():qe()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=x=>Math.floor(x/864e5)*864e5;for(let x of o){let b=Mt(e,x),v=!1;try{let O=new s(b,{readonly:!0});try{let R=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let M of R)M.category&&(i[M.category]=(i[M.category]??0)+(M.cnt??0),a+=M.cnt??0,v=!0);let j=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(j?.mn){let M=Date.parse(j.mn+(j.mn.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M<d&&(d=M)}if(j?.mx){let M=Date.parse(j.mx+(j.mx.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M>f&&(f=M)}try{let M=O.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let V of M){if(!V.sec)continue;let w=parseInt(V.sec,10)*1e3;if(!Number.isFinite(w))continue;let P=h(w),H=p.get(P)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(P,H)}}catch{}try{let M=O.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(n);if(M?.bytes&&(u+=M.bytes),M?.n&&(l+=M.n),M?.lastSec){let V=parseInt(M.lastSec,10)*1e3;if(Number.isFinite(V)&&V>m&&(m=V),Number.isFinite(V)&&(M?.bytes??0)>0){let w=h(V),P=p.get(w)??{count:0,rescueBytes:0};P.rescueBytes=Math.max(P.rescueBytes,M.bytes),p.set(w,P)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,b])=>({category:x,count:b,label:Wu[x]||x})).sort((x,b)=>b.count-x.count),_=[...p.entries()].sort((x,b)=>x[0]-b[0]).map(([x,b])=>({ms:x,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:n,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:_}}function jU(t,e,n){if(!t||!e||!Wn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():qe()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
627
- FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function fP(t,e){if(!t||!Wn(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():qe()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
628
- FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function la(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??Mt(Ju(),".claude","context-mode","sessions");if(!Wn(n))return e;let r=[];try{r=Rs(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():qe()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let f=Mt(n,d);RE(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
619
+ `,M);V>=0&&(j=V+2),w>=0&&(M=w);let P=y.slice(j,M).trim();s.push({title:`[auto-memory] ${h.label}`,content:P,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){JT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
620
+ `)}}return s.slice(0,e)}function XT(t,e){return e?vU(e)||!t?e:Es(t,e):t??""}var Fu=process.env.DEBUG?.includes("context-mode");function QT(t){let{query:e,limit:n,store:r,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l,projectScope:d}=t,f=[],m=new Date().toISOString(),p;if(typeof d=="string"&&a)try{p=new Set(a.getSessionIdsForProject(d))}catch(h){Fu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
621
+ `)}try{let h=r.searchWithFallback(e,n,s,i,"like",p);f.push(...h.map(g=>({title:g.title,content:g.content,source:g.source,origin:"current-session",timestamp:g.timestamp||m,rank:g.rank,matchLayer:g.matchLayer,highlighted:g.highlighted,contentType:g.contentType})))}catch(h){Fu&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
622
+ `)}if(o==="timeline"){try{if(a){let h=a.searchEvents(e,n,c||"",s);f.push(...h.map(g=>({title:`[${g.category}] ${g.type}`,content:g.data,source:"prior-session",origin:"prior-session",timestamp:g.created_at})))}}catch(h){Fu&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
623
+ `)}try{let h=YT([e],n,c,u,l);f.push(...h)}catch(h){Fu&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
624
+ `)}}for(let h of f)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return o==="timeline"&&f.sort((h,g)=>(h.timestamp||"").localeCompare(g.timestamp||"")),f.slice(0,n)}function EU(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function eP(t){let e=t?{project:$.string().optional().describe("Project scope. Default (omit): this session's project \u2014 auto-resolved from the host adapter. 'global': span every project in the shared store (cross-project recall). <absolute-path>: scope to that specific project directory.")}:{};return $.object({queries:$.preprocess(EU,$.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."),...e})}function tP(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var qg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var Bu=class{#e;#t=new Map;#n;constructor(e,n=4096){this.#e=e,this.#n=Math.max(1,n)}record(e,n=Date.now()){let r=this.#t.get(e);return(!r||n-r.windowStart>this.#e.windowMs)&&(r={count:0,windowStart:n},this.#t.set(e,r),this.#o()),r.count++,{count:r.count,windowStart:r.windowStart,blocked:r.count>this.#e.blockAfter,softCapped:r.count>this.#e.softCapAfter}}size(){return this.#t.size}#o(){if(this.#t.size<=this.#n)return;let e,n=1/0;for(let[r,o]of this.#t)o.windowStart<n&&(n=o.windowStart,e=r);e!==void 0&&this.#t.delete(e)}};Hn();vs();Wh();Hn();function wU(t){let e=[];if(t&&typeof t=="object"){let n=t.command;typeof n=="string"&&e.push(n);let r=t.hooks;if(Array.isArray(r)){for(let o of r)if(o&&typeof o=="object"){let s=o.command;typeof s=="string"&&e.push(s)}}}return e}function TU(t){let e=eu(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let n=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(n)return n[1];let r=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return r?r[1]:null}function nP(t,e){let n=new Set,r=t.generateHookConfig(e);for(let o of Object.values(r))if(Array.isArray(o))for(let s of o)for(let i of wU(s)){let a=TU(i);a&&n.add(a)}return[...n]}Yi();lo();vs();import*as Fe from"node:fs";import*as rP from"node:os";import*as ws from"node:path";var PU=["CONTEXT_MODE_PROJECT_DIR"],RU=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Zu(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function CU(t){if(!Fe.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Fe.readdirSync(t.projectsRoot)){let o=ws.join(t.projectsRoot,r),s;try{s=Fe.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Fe.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=ws.join(o,a);try{let u=Fe.statSync(c).mtimeMs;u>n&&(n=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-n>t.maxAgeMs))try{let r=Fe.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Fe.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
625
+ `).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{Fe.closeSync(r)}}catch{}}function $U(t){let e=t?.codexHome??process.env.CODEX_HOME??ws.join(rP.homedir(),".codex"),n=ws.join(e,"sessions");if(!Fe.existsSync(n))return null;let r=4,o=1e4,s=0,i,a=0,c=(u,l)=>{if(s>=o)return;let d;try{d=Fe.readdirSync(u)}catch{return}d.sort().reverse();for(let f of d){if(s>=o)return;s++;let m=ws.join(u,f),p;try{p=Fe.statSync(m)}catch{continue}if(p.isDirectory()){l<r&&c(m,l+1);continue}if(!p.isFile()||!f.endsWith(".jsonl"))continue;let h=p.mtimeMs;h>a&&(a=h,i=m)}};try{c(n,0)}catch{return null}if(!i||typeof t?.transcriptMaxAgeMs=="number"&&(t.now??Date.now())-a>t.transcriptMaxAgeMs)return null;try{let u=Fe.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Fe.readSync(u,l,0,l.length,0),f=l.subarray(0,d).toString("utf-8");for(let m of f.split(`
626
+ `).slice(0,10))if(m.trim())try{let p=JSON.parse(m),h=p?.meta?.cwd??(p?.type==="session_meta"?p?.payload?.cwd:void 0);if(typeof h!="string"||h.length===0)continue;return Zu(h)?null:h}catch{return null}}finally{Fe.closeSync(u)}}catch{return null}return null}function oP(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...$g(a),...PU]:RU;for(let l of u){let d=e[l];if(d&&!Zu(d))return d}if(o){let l=CU({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Zu(l))return l}if(a==="codex"){let l=$U({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Zu(r)?r:n}ao();ao();Tn();lo();import{execFileSync as OU}from"node:child_process";import{existsSync as Vn,readdirSync as Ts,statSync as IU}from"node:fs";import{homedir as Gu}from"node:os";import{join as Mt,sep as AU}from"node:path";function pP(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}var Vu={file:"Files tracked",cwd:"Working directory",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",intent:"Session intent",goal:"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"},NU={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"},Ps=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,n){let r=e-n,o=e>0?Math.round(r/e*1e3)/10:0;return{rawBytes:e,contextBytes:n,savedBytes:r,savedPercent:o}}static thinkInCodeComparison(e,n){let r=n>0?Math.round(e/n*10)/10:0;return{fileBytes:e,outputBytes:n,ratio:r}}static toolSavings(e){return e.map(n=>({...n,savedBytes:n.rawBytes-n.contextBytes}))}static sandboxIO(e,n){return{inputBytes:e,outputBytes:n}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let n=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=n.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)}n.set(i,a)}let r=[];for(let[o,s]of n){let i=null,a=null;if(s.concurrencies.length>0){s.concurrencies.sort((l,d)=>l-d);let c=s.concurrencies,u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}r.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return r.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),r}queryAll(e){let r=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((P,H)=>P+H,0),s=Object.values(e.calls).reduce((P,H)=>P+H,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(P=>({tool:P,calls:e.calls[P]||0,context_kb:Math.round((e.bytesReturned[P]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[P]||0)/4)})),m=((Date.now()-e.sessionStart)/6e4).toFixed(1),p,h=e.cacheMisses??0;if(e.cacheHits>0||e.cacheBytesSaved>0||h>0){let P=a+e.cacheBytesSaved,H=P/Math.max(o,1),se=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),_t=e.cacheHits+h,Cn=_t>0?e.cacheHits/_t:0;p={hits:e.cacheHits,misses:h,hit_rate:Cn,bytes_saved:e.cacheBytesSaved,ttl_hours_left:se,total_with_cache:P,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,b=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=b?!b.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),R=new Map;for(let P of O){R.has(P.category)||R.set(P.category,new Set);let H=R.get(P.category);if(H.size<5){let se=P.data;P.category==="file"?se=P.data.split("/").pop()||P.data:(P.category==="prompt"||P.category==="user-prompt")&&(se=se.length>50?se.slice(0,47)+"...":se),se.length>40&&(se=se.slice(0,37)+"..."),H.add(se)}}let j=y.map(P=>({category:P.category,count:P.cnt,label:Vu[P.category]||P.category,preview:R.get(P.category)?Array.from(R.get(P.category)).join(", "):"",why:NU[P.category]||"Survives context resets"})),M=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(P=>P.cnt>0).map(P=>({category:P.category,count:P.cnt,label:Vu[P.category]||P.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:r,uptime_min:m},continuity:{total_events:g,by_category:j,compact_count:x,resume_ready:v},projectMemory:{total_events:M.cnt,session_count:M.sessions,by_category:w}}}};function DU(t){let e=t?.home??Gu();return[["claude-code",[".claude"]],["gemini-cli",[".gemini"]],["antigravity",[".gemini"]],["antigravity-cli",[".gemini"]],["openclaw",[".openclaw"]],["codex",[".codex"]],["cursor",[".cursor"]],["vscode-copilot",[".vscode"]],["copilot-cli",[".copilot"]],["kiro",[".kiro"]],["pi",[".pi"]],["omp",[".omp"]],["qwen-code",[".qwen"]],["kilo",[".config","kilo"]],["opencode",[".config","opencode"]],["zed",[".config","zed"]],["jetbrains-copilot",[".config","JetBrains"]]].map(([r,o])=>{let s=Mt(e,...o,"context-mode");return{name:r,sessionsDir:Mt(s,"sessions"),contentDir:Mt(s,"content")}})}function MU(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function ua(t){let e=Dt(),n=t?.sessionsDir??Mt(e,"context-mode","sessions"),r=t?.memoryRoot??Mt(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Vn(n)){let m=[];try{m=Ts(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():qe()}catch{}if(p)for(let h of m){let g=Mt(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of b)v.category&&(u[v.category]=(u[v.category]??0)+(v.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 v=b.t.endsWith("Z")?b.t:b.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of b)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Vn(r)){let m=[];try{m=Ts(r).filter(p=>{try{return IU(Mt(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Mt(r,p,"memory");if(!Vn(h))continue;let g=[];try{g=Ts(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=MU(y);f[_]=(f[_]??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 fP(t){let e=t.sessionsDir??Mt(Gu(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Vn(e))return r;let o=[];try{o=Ts(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():qe()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=x=>Math.floor(x/864e5)*864e5;for(let x of o){let b=Mt(e,x),v=!1;try{let O=new s(b,{readonly:!0});try{let R=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let M of R)M.category&&(i[M.category]=(i[M.category]??0)+(M.cnt??0),a+=M.cnt??0,v=!0);let j=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(j?.mn){let M=Date.parse(j.mn+(j.mn.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M<d&&(d=M)}if(j?.mx){let M=Date.parse(j.mx+(j.mx.endsWith("Z")?"":"Z"));Number.isFinite(M)&&M>f&&(f=M)}try{let M=O.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(n);for(let V of M){if(!V.sec)continue;let w=parseInt(V.sec,10)*1e3;if(!Number.isFinite(w))continue;let P=h(w),H=p.get(P)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(P,H)}}catch{}try{let M=O.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(n);if(M?.bytes&&(u+=M.bytes),M?.n&&(l+=M.n),M?.lastSec){let V=parseInt(M.lastSec,10)*1e3;if(Number.isFinite(V)&&V>m&&(m=V),Number.isFinite(V)&&(M?.bytes??0)>0){let w=h(V),P=p.get(w)??{count:0,rescueBytes:0};P.rescueBytes=Math.max(P.rescueBytes,M.bytes),p.set(w,P)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,b])=>({category:x,count:b,label:Vu[x]||x})).sort((x,b)=>b.count-x.count),_=[...p.entries()].sort((x,b)=>x[0]-b[0]).map(([x,b])=>({ms:x,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:n,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:_}}function jU(t,e,n){if(!t||!e||!Vn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():qe()}catch{return 0}if(!r)return 0;try{let o=new r(e,{readonly:!0});try{let s=o.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
627
+ FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function mP(t,e){if(!t||!Vn(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():qe()}catch{return 0}if(!n)return 0;try{let r=new n(t,{readonly:!0});try{let o=r.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
628
+ FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function la(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??Mt(Gu(),".claude","context-mode","sessions");if(!Vn(n))return e;let r=[];try{r=Ts(n).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(r.length===0)return e;let o=null;try{o=t.loadDatabase?t.loadDatabase():qe()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let f=Mt(n,d);CE(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
629
629
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
630
630
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
631
631
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
@@ -651,46 +651,46 @@ ${o}`}}import{execFileSync as lU}from"node:child_process";function dU(){if(proce
651
651
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
652
652
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
653
653
  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{}try{let h=m.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
654
- WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=jU(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 LU={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function zU(t,e,n){let r={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(!Wn(t.sessionsDir))return r;let o=[];try{o=Rs(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=Mt(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&&(r.eventCount+=Number(m.cnt??0),r.dataBytes+=Number(m.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.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&&(r.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<r.firstMs&&(r.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>r.lastMs&&(r.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{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function Xu(t){let e=DU({home:t?.home}),n=t?.loadDatabase??qe,r={...LU,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Wn(c.sessionsDir))continue;let u=zU(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var mP={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},HU={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};function Ku(t){return HU[t]??t}function ot(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function UU(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function Vu(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function FU(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Vu(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=OU("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!Vu(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!Vu(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return Vu(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function oP(t){let e=Ju();return e?t===e?"~":t.startsWith(e+AU)?"~"+t.slice(e.length):t:t}function BU(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*da(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),m=(e*1/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):p?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${ot(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function ZU(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*uP,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*uP,_=Math.round((n?.rescueBytes??0)/4),x=y+_,b=o?.lifetime?.totalSavedTokens??0,v=Math.max(x,b),O=o?.lifetime?.bytesReturned??0,R=o?.lifetime?.bytesAvoided??0,j=O+R>0?Math.max(1,Math.floor(O/4)):Math.max(1,Math.round(v*.02)),M=r?.totalBytes&&r.totalBytes>0?r.totalBytes:v*4,V=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,w=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`,P=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=P>0?Math.max(1,Math.round((c-P)/864e5)):0,se=r?.totalSessions??n?.totalSessions??1,_t=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,$n;if(r&&_t>=2)$n=`across ${_t} AI tools`;else if(r&&_t===1){let Ne=r.perAdapter.find(Yt=>Yt.isReal);$n=`in ${Ne?Ku(Ne.name):"Claude Code"}`}else $n="in Claude Code";H>0?d.push(` Across ${H} days you ran ${pn(se)} conversations ${$n}.`):d.push(` You ran ${pn(se)} conversations ${$n}.`);let fl=H>0?M/H:0;d.push(` context-mode kept ${ot(M)} out of your context window \u2014 about ${ot(fl)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let dy=e.firstEventMs&&e.firstEventMs>0?sP(e.firstEventMs,i,a):"";if(dy?d.push(` This conversation started ${dy} in ${oP(s)}.`):d.push(` This conversation lives in ${oP(s)}.`),d.push(` ${w}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?sP(e.lastRescueMs,i,a):"",Yt=Math.round(e.snapshotBytes/1024);Ne?d.push(` On ${Ne}, /compact fired \u2014 ${Yt} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Yt} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let py=o?.conversation,fy=py?.bytesAvoided??0,ml=py?.bytesReturned??0;if(fy+ml===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ne=fy+ml,Yt=Math.max(1,ml),Qt=Math.max(1,Math.floor(Ne/4)),On=Math.max(1,Math.floor(Yt/4)),hl=vr(Qt,Qt,32),BP=vr(On,Qt,32),ZP=(1-On/Qt)*100,qP=Math.max(1,Math.round(Qt/On));d.push(` Without context-mode ${ot(Ne).padStart(8)} ${hl} ${pn(Qt).padStart(7)} tokens`),d.push(` With context-mode ${ot(Yt).padStart(8)} ${BP} ${pn(On).padStart(7)} tokens`),d.push(` ${ZP.toFixed(1)}% kept out of context \xB7 your AI ran ${qP}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ne=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${ot(V)} built up \u2014 ${Ne} days, ${e.byDay.length} active:`),d.push(""),d.push(...VU(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 zP=e.byCategory.reduce((Ne,Yt)=>Ne+Yt.count,0).toLocaleString(i);d.push(` ${zP} things \u2014 files, errors, decisions, agent runs:`),d.push("");let HP=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${vr(Ne.count,HP,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let my=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",hy=P>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(P)):"",gy=n?.distinctProjects??0,UP=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${ot(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${my?` \xB7 started ${my}`:""}.`),d.push(` All your work: ${ot(M)} kept out \xB7 ${UP.toLocaleString(i)} captures across ${gy} project${gy===1?"":"s"}${hy?` \xB7 since ${hy}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...BU(M,v,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Ne=Object.entries(n.autoMemoryByPrefix).sort((Qt,On)=>On[1]-Qt[1]),Yt=Ne.length>0?Ne[0][1]:1;for(let[Qt,On]of Ne){let hl=mP[Qt]??Qt;d.push(` ${hl.padEnd(26)} ${String(On).padStart(2)} ${vr(On,Yt,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 FP=u?`v${u}`:"context-mode";return d.push(` ${FP}`),u&&l&&l!=="unknown"&&dP(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),qU(d)}function qU(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function VU(t,e,n){if(t.length===0)return[];let r=[...t].sort((f,m)=>f.ms-m.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let f of r)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of r){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:n,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 r){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 sP(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),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} (${n})`}function pn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function da(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}var ZG=5/1e6;function Gu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*da()).toFixed(2)}`}function vr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function iP(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=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 ${pn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${pn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${pn(h)} sessions`,y=a*256+n;o.push(` ${pn(a)} events \xB7 ${g} \xB7 ~${Gu(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:Wu[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let f=d.slice(0,r),m=f.length>0?f[0].count:1;for(let h of f)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${vr(h.count,m,30)}`);let p=Math.max(0,d.length-r);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function aP(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=mP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${vr(s,r,20)}`)}return e}function cP(t,e){let n=[],r=Gu(t),o=(e?.totalEvents??0)*256+t,s=Gu(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}var uP=256;function lP(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?pn(u.eventCount):"\u2014",f=ot(u.dataBytes),m=ot(l);r.push(` ${Ku(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${m.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>Ku(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function Yu(t,e,n,r){let o=[],s=UU(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(O=>O.isReal).length??0;if(l&&d>0){let O=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,j=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,M=j>0?`Across ${j} day${j===1?"":"s"} `:"",V=O>0?`you ran ${pn(O)} conversation${O===1?"":"s"} `:"you ran ",w;if(d>=2)w=`across ${d} AI tools`;else{let P=l.perAdapter.find(H=>H.isReal);w=`in ${P?Ku(P.name):"Claude Code"}`}o.push(`${M}${V}${w}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=FU(),R=r?.cwd??process.cwd(),j=r?.now??Date.now(),M=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...ZU({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:M,tz:V,now:j,version:e,latestVersion:n})),o.join(`
655
- `)}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),_=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(`${ot(m)} entered context | 0 tokens saved`),o.push(...iP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...lP(l)),o.push(...aP(i)),o.push(...cP(0,i)),o.push("");let O=e?`v${e}`:"context-mode";return o.push(O),e&&n&&n!=="unknown"&&dP(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
656
- `)}o.push(`${pn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Gu(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${vr(h,h)}| ${ot(h)}`),o.push(`With context-mode |${vr(m,h)}| ${ot(m)}`),o.push(""),_>=2?o.push(`${ot(f)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${ot(f)} kept out of your conversation. Never entered context.`),o.push("");let x=[`${p} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${ot(t.cache.bytes_saved)})`),o.push(x.join(" \xB7 "));let b=t.savings.by_tool.filter(O=>O.calls>0);if(b.length>=2){o.push("");let O=b.map(R=>{let j=R.context_kb*1024,M=g<100?j/(1-g/100):j,V=Math.max(0,M-j);return{...R,returnedBytes:j,estimatedSaved:V}}).sort((R,j)=>j.estimatedSaved-R.estimatedSaved);for(let R of O){let j=R.tool.length>22?R.tool.slice(0,19)+"...":R.tool;o.push(` ${j.padEnd(22)} ${String(R.calls).padStart(4)} calls ${ot(R.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(R=>R.median_concurrency!=null&&(R.max_concurrency??1)>1);if(O.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 R of O){let j=R.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${j.padEnd(22)} ${R.calls} batches \xB7 ${R.median_concurrency} typical, ${R.max_concurrency} peak`)}}}o.push(...iP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...lP(l)),o.push(...aP(i)),o.push(...cP(y,i)),o.push("");let v=e?`v${e}`:"context-mode";return o.push(v),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
657
- `)}var rl=Eo(QU(import.meta.url)),Kn=(()=>{for(let t of["../package.json","./package.json"]){let e=gt(rl,t);if(He(e))try{return JSON.parse(ha(e,"utf8")).version}catch{}}return"unknown"})();function $P(){return He(gt(rl,"package.json"))?rl:Eo(rl)}function rF(t){try{let e=process.platform==="win32"?al("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):al("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=wu(String(e.stdout));if(n&&He(gt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function OP(t){let e=$P();return t==="codex"?rF(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
658
- `)}),process.on("uncaughtException",t=>{try{WU(2,`[context-mode] uncaughtException: ${t?.message??t}
659
- `)}finally{process.exit(1)}}));var vo=ou(),ol=Ov(vo),Te=new Yc({name:"context-mode",version:Kn}),oF=[];function sF(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??$t().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??iF(n);return aF(r)&&cF(r)}function iF(t){let e=t==="kilo"?"kilo":"opencode",n=[gt(`${e}.json`),gt(`${e}.jsonc`),gt(`.${e}`,`${e}.json`),gt(`.${e}`,`${e}.jsonc`),yt(As(),".config",e,`${e}.json`),yt(As(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!He(r))continue;return JSON.parse(Xi(ha(r,"utf8")))}catch{}return null}function aF(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function cF(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var IP=sF(),Yg=!1;function uF(t={}){if(Yg)return;Yg=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["${dn}"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
660
- `)}function A5(){Yg=!1}function lF(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Kr,async()=>({tools:[]}))}var dF=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(IP){uF();return}let o=pF(e,r);return oF.push({name:e,config:n,handler:o}),t[2]=o,dF(...t)};function pF(t,e){return async n=>{jT();try{return await e(n)}catch(r){let o=xF(r);if(o)try{return W(t,o)}catch(s){if(s instanceof yr)return o;throw s}throw r}finally{LT()}}}IP&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&lF(Te);var sy=new nF;async function N5(t,e){let n=typeof t=="string"?{projectDir:t}:t;return sy.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Bo,async()=>({prompts:[]}));Te.server.setRequestHandler(Uo,async()=>({resources:[]}));Te.server.setRequestHandler(Fo,async()=>({resourceTemplates:[]}));function Qg(t){if(Array.isArray(t))return t.map(Qg);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=Qg(r)}return e}function fF(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Kr,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=Qg(i.inputSchema)}catch{}}return s})}catch{}}var ga=new Ui({runtimes:vo,projectRoot:()=>Ot()}),pl=yt(oy(),`cm-fs-preload-${process.pid}.js`);il(pl,`(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){}})();
661
- `);process.on("exit",()=>{try{Is(pl)}catch{}});var fn=null;function Er(){let t=sy.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??mF();if(e)return{sessionId:e}}var Qu;function mF(t){let e=Date.now();if(!t?.bypassCache&&Qu&&e-Qu.checkedAt<2e3)return Qu.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??ze(),o=Ki({projectDir:n,sessionsDir:r});if(!He(o))return;let s=qe(),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&&(Qu={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function hF(t){try{let e=ze();if(!He(e))return;let n=wP(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=yt(e,r);try{t.index({path:o,source:"session-events",attribution:Er()}),Is(o)}catch{}}}catch{}}var mn=null;async function gF(){if(mn)return mn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(ws(),Ig)),e=$t();return await t(e.platform)}catch{return null}}function $s(){if(mn)return mn.getSessionDir();try{let t=$t(),e=oa(t.platform);if(e)return Eh({configDir:yt(...e),configDirEnv:yF(e)})}catch{}return Eh({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function yF(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function ze(){return gu(Wi($s))}function Ot(){let t=sy.getStore();if(t)return t.projectDir;let e,n,r;try{let o=$t().platform;n=o,o==="claude-code"&&(e=yt(As(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??yt(As(),".codex"))}catch{}return rP({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function _F(t){return YU(t)?t:gt(Ot(),t)}function fa(){return Ki({projectDir:Ot(),sessionsDir:ze()})}function ma(){let t=gu(wh($s));return TE({projectDir:Ot(),contentDir:t})}function Cn(){if(!fn){let t=ma();fn=new du(t),fn.setDenyChecker(e=>{try{let n=Ot(),r=Hu("Read",n);return ia(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=Eo(ma());hh(e,14),fn.cleanupStaleSources(14);let n=yt(As(),".context-mode","content");He(n)&&hh(n,0)}catch{}mh()}return hF(fn),fn}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function xF(t){return t instanceof yr?{content:[{type:"text",text:vE(t)}],isError:!0}:null}var Gn=null,el=0,hP=0,bF=3,SF=3600*1e3;async function gP(){return new Promise(t=>{let e=tF(qE,{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function kF(){let t=mn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g @mxalbert/context-mode"}function vF(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function EF(){return!Gn||Gn==="unknown"?!1:vF(Gn,Kn)}function wF(){if(!EF())return!1;let t=Date.now();if(el>=bF){if(t-hP<SF)return!1;el=0}return el===0&&(hP=t),el++,!0}var yP=!1;function TF(){if(!yP){yP=!0;try{let t=Dt(),e=gt(t,"plugins","installed_plugins.json");if(!He(e))return;let n=JSON.parse(ha(e,"utf-8")),r=gt(t,"plugins","cache"),o;try{o=CP(r)}catch{o=r}let s=$P();for(let[i,a]of Object.entries(n.plugins??{}))if(i===Kt)for(let c of a){let u=c.installPath;if(!u||He(u)||!gt(u).startsWith(o+XU))continue;try{RP(u).isSymbolicLink()&&Is(u)}catch{}let l=Eo(u);He(l)||GU(l,{recursive:!0}),He(s)&&JU(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(Ug(),TF(),wF()&&e.content.length>0){let r=kF();e.content[0].text=`\u26A0\uFE0F context-mode v${Kn} outdated \u2192 v${Gn} available. Upgrade: ${r}
662
-
663
- `+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ne.calls[t]=(ne.calls[t]||0)+1,ne.bytesReturned[t]=(ne.bytesReturned[t]||0)+n,cl(),setImmediate(()=>WT(fa(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>BT({sessionDbPath:fa(),toolName:t,bytesReturned:n})),e}function hn(t,e="unknown"){ne.bytesIndexed+=t,cl(),t>0&&setImmediate(()=>ZT({sessionDbPath:fa(),source:e,bytesAvoided:t}))}var PF=500,RF=2,CF=3e4,$F=256,ey=0,tl,OF=/^[A-Za-z0-9._-]+$/;function IF(t){return OF.test(t)?t:`pid-${process.ppid}`}function AP(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=IF(t),n=gu(Th($s));return yt(n,`stats-${e}.json`)}function cl(){let t=Date.now();if(!(t-ey<PF)){ey=t;try{let e=Object.values(ne.bytesReturned).reduce((d,f)=>d+f,0),n=Object.values(ne.calls).reduce((d,f)=>d+f,0),r=ne.bytesIndexed+ne.bytesSandboxed+ne.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=tl?.tokens??0;if(!tl||t-tl.computedAt>CF)try{a=(ua({sessionsDir:ze()})?.totalEvents??0)*$F,tl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:RF,version:Kn,updated_at:t,session_start:ne.sessionStart,uptime_ms:t-ne.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ne.bytesIndexed,bytes_sandboxed:ne.bytesSandboxed,cache_hits:ne.cacheHits,cache_bytes_saved:ne.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*da()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*da()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ne.calls,...ne.bytesReturned}).map(d=>[d,{calls:ne.calls[d]||0,bytes:ne.bytesReturned[d]||0}]))},u=AP(),l=`${u}.tmp`;il(l,JSON.stringify(c)),KU(l,u)}catch{}}}function iy(t,e){try{let n=jg(process.env.CLAUDE_PROJECT_DIR),r=zg(t,n);if(r.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function NP(t,e,n){try{let r=MT(t,e);if(r.length===0)return null;let o=jg(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=zg(s,o);if(i.decision==="deny")return W(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function AF(t,e){try{let n=Ot(),r=Lg("Read","allow",n);return DT(t,n,r).allowed?null:W(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function ty(t,e){try{let n=Ot(),r=Hu("Read",n),o=ia(t,r,process.platform==="win32",n);if(o.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}var NF=ol.join(", "),DF=su()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",MF="",jF="";function LF(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===MF){for(e.push(n),r++;r<t.length&&t[r]!==jF;)n++,r++;r<t.length&&r++}else n++,r++;return e}function DP(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of LF(r))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,n)+`
654
+ WHERE tool IN ('ctx_search', 'ctx_fetch_and_index')`).get();h?.bytes&&(a+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=jU(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 LU={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function zU(t,e,n){let r={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(!Vn(t.sessionsDir))return r;let o=[];try{o=Ts(t.sessionsDir).filter(l=>l.endsWith(".db"))}catch{return r}if(o.length===0)return r;let s=null;try{s=e()}catch{return r}if(!s)return r;let i=new Set,a=new Set;for(let l of o){let d=Mt(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&&(r.eventCount+=Number(m.cnt??0),r.dataBytes+=Number(m.bytes??0));try{let p=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();r.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&&(r.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<r.firstMs&&(r.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>r.lastMs&&(r.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{}}r.projectDirs=Array.from(i),r.uuidConvs=a.size;let c=r.eventCount>0?r.dataBytes/r.eventCount:0,u=r.lastMs>0&&n.nowMs-r.lastMs<=n.recencyMs;return r.isReal=r.eventCount>=n.minEvents&&i.size>=n.minProjects&&u&&c>=n.minAvgBytes,r}function Ju(t){let e=DU({home:t?.home}),n=t?.loadDatabase??qe,r={...LU,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Vn(c.sessionsDir))continue;let u=zU(c,n,r);o.push(u),s+=u.eventCount,i+=u.sessionCount,a+=u.dataBytes+u.rescueBytes}return{totalEvents:s,totalSessions:i,totalBytes:a,perAdapter:o}}var hP={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},HU={"claude-code":"Claude Code","gemini-cli":"Gemini CLI",antigravity:"Antigravity","antigravity-cli":"Antigravity CLI",openclaw:"Openclaw",codex:"Codex CLI",cursor:"Cursor","vscode-copilot":"VS Code Copilot","copilot-cli":"GitHub Copilot CLI",kiro:"Kiro",pi:"Pi",omp:"OMP","qwen-code":"Qwen Code",kilo:"Kilo",opencode:"OpenCode",zed:"Zed","jetbrains-copilot":"JetBrains"};function Wu(t){return HU[t]??t}function ot(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 n=e/1024;if(n<1024)return n<100?`${n.toFixed(1)} MB`:`${Math.round(n)} MB`;let r=n/1024;return r<100?`${r.toFixed(2)} GB`:`${r.toFixed(1)} GB`}function UU(t){let e=parseFloat(t);if(isNaN(e)||e<1)return"< 1 min";if(e<60)return`${Math.round(e)} min`;let n=Math.floor(e/60),r=Math.round(e%60);return r>0?`${n}h ${r}m`:`${n}h`}function qu(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function FU(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!qu(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=OU("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!qu(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!qu(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let n=t.CONTEXT_MODE_TZ??"";if(!n)try{n=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{n="UTC"}return qu(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function sP(t){let e=Gu();return e?t===e?"~":t.startsWith(e+AU)?"~"+t.slice(e.length):t:t}function BU(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*da(),o=(y,_=2)=>y.toFixed(_),s=Math.round(r/20),i=(r/200).toFixed(1),a=Math.round(r/73.67),c=Math.round(r*10),u=n>0?Math.round(r*10/n*365):0,l=(e*3/1e6).toFixed(2),d=(e*2.5/1e6).toFixed(2),f=(e*1.25/1e6).toFixed(2),m=(e*1/1e6).toFixed(2),p=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN!==void 0,h=process.env.PI_CONTEXT_MODE_MODEL_ID,g=[];return p&&h?g.push(` $${o(r)} of ${h} tokens your team didn't burn.`):p?g.push(` $${o(r)} of tokens your team didn't burn.`):g.push(` $${o(r)} of Opus 4.7 tokens your team didn't burn.`),g.push(` context-mode kept ${ot(t)} out of context \u2014 that's ${s} months of Cursor Pro paid for itself.`),c>0&&u>0&&(g.push(""),g.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p||(g.push(""),g.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)")),g}function ZU(t){let{conversation:e,lifetime:n,multiAdapter:r,realBytes:o,cwd:s,locale:i,tz:a,now:c,version:u,latestVersion:l}=t,d=[],f=e.events*lP,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*lP,_=Math.round((n?.rescueBytes??0)/4),x=y+_,b=o?.lifetime?.totalSavedTokens??0,v=Math.max(x,b),O=o?.lifetime?.bytesReturned??0,R=o?.lifetime?.bytesAvoided??0,j=O+R>0?Math.max(1,Math.floor(O/4)):Math.max(1,Math.round(v*.02)),M=r?.totalBytes&&r.totalBytes>0?r.totalBytes:v*4,V=o?.conversation?o.conversation.eventDataBytes+o.conversation.bytesAvoided+o.conversation.snapshotBytes:g*4,w=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`,P=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=P>0?Math.max(1,Math.round((c-P)/864e5)):0,se=r?.totalSessions??n?.totalSessions??1,_t=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,Cn;if(r&&_t>=2)Cn=`across ${_t} AI tools`;else if(r&&_t===1){let Ne=r.perAdapter.find(Yt=>Yt.isReal);Cn=`in ${Ne?Wu(Ne.name):"Claude Code"}`}else Cn="in Claude Code";H>0?d.push(` Across ${H} days you ran ${pn(se)} conversations ${Cn}.`):d.push(` You ran ${pn(se)} conversations ${Cn}.`);let fl=H>0?M/H:0;d.push(` context-mode kept ${ot(M)} out of your context window \u2014 about ${ot(fl)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let ly=e.firstEventMs&&e.firstEventMs>0?iP(e.firstEventMs,i,a):"";if(ly?d.push(` This conversation started ${ly} in ${sP(s)}.`):d.push(` This conversation lives in ${sP(s)}.`),d.push(` ${w}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?iP(e.lastRescueMs,i,a):"",Yt=Math.round(e.snapshotBytes/1024);Ne?d.push(` On ${Ne}, /compact fired \u2014 ${Yt} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Yt} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let dy=o?.conversation,py=dy?.bytesAvoided??0,ml=dy?.bytesReturned??0;if(py+ml===0)d.push(" No measurable redirect activity captured yet \u2014 bars will appear once context-mode diverts its first payload."),d.push("");else{let Ne=py+ml,Yt=Math.max(1,ml),Qt=Math.max(1,Math.floor(Ne/4)),$n=Math.max(1,Math.floor(Yt/4)),hl=kr(Qt,Qt,32),ZP=kr($n,Qt,32),qP=(1-$n/Qt)*100,VP=Math.max(1,Math.round(Qt/$n));d.push(` Without context-mode ${ot(Ne).padStart(8)} ${hl} ${pn(Qt).padStart(7)} tokens`),d.push(` With context-mode ${ot(Yt).padStart(8)} ${ZP} ${pn($n).padStart(7)} tokens`),d.push(` ${qP.toFixed(1)}% kept out of context \xB7 your AI ran ${VP}\xD7 longer before /compact fired`),d.push("")}if(e.byDay&&e.byDay.length>0){let Ne=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;d.push(` How that ${ot(V)} built up \u2014 ${Ne} days, ${e.byDay.length} active:`),d.push(""),d.push(...VU(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 HP=e.byCategory.reduce((Ne,Yt)=>Ne+Yt.count,0).toLocaleString(i);d.push(` ${HP} things \u2014 files, errors, decisions, agent runs:`),d.push("");let UP=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${kr(Ne.count,UP,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let fy=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",my=P>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(P)):"",hy=n?.distinctProjects??0,FP=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${ot(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${fy?` \xB7 started ${fy}`:""}.`),d.push(` All your work: ${ot(M)} kept out \xB7 ${FP.toLocaleString(i)} captures across ${hy} project${hy===1?"":"s"}${my?` \xB7 since ${my}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...BU(M,v,H)),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 5. What context-mode learned about how you work \u2500\u2500\u2500"),d.push(""),n&&n.autoMemoryCount>0){d.push(` ${n.autoMemoryCount} preferences picked up across ${n.autoMemoryProjects} project${n.autoMemoryProjects===1?"":"s"}:`);let Ne=Object.entries(n.autoMemoryByPrefix).sort((Qt,$n)=>$n[1]-Qt[1]),Yt=Ne.length>0?Ne[0][1]:1;for(let[Qt,$n]of Ne){let hl=hP[Qt]??Qt;d.push(` ${hl.padEnd(26)} ${String($n).padStart(2)} ${kr($n,Yt,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 BP=u?`v${u}`:"context-mode";return d.push(` ${BP}`),u&&l&&l!=="unknown"&&pP(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),qU(d)}function qU(t){let e=[],n=0;for(let r of t)r===""?(n++,n<=2&&e.push(r)):(n=0,e.push(r));for(;e.length>0&&e[e.length-1]==="";)e.pop();return e}function VU(t,e,n){if(t.length===0)return[];let r=[...t].sort((f,m)=>f.ms-m.ms),o=r[0],s=r[r.length-1],i=Math.max(1,s.ms-o.ms),a=r[0];for(let f of r)f.count>a.count&&(a=f);let c=56,u=Array.from({length:c},()=>"\u2500");for(let f of r){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:n,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 r){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 iP(t,e,n){if(!Number.isFinite(t)||t<=0)return"";let r=new Date(t);if(Number.isNaN(r.getTime()))return"";let o=new Intl.DateTimeFormat(e,{timeZone:n,year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(r),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} (${n})`}function pn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function da(){let t=process.env.PI_CONTEXT_MODE_PRICE_OUTPUT_PER_TOKEN;if(t!==void 0&&t!==""){let e=Number(t);if(Number.isFinite(e)&&e>0)return e}return 5/1e6}var qG=5/1e6;function Ku(t){return`$${((Number.isFinite(t)&&t>0?t:0)*da()).toFixed(2)}`}function kr(t,e,n=40){if(e<=0)return"\u2591".repeat(n);let r=Math.max(1,Math.round(t/e*n));return"\u2588".repeat(Math.min(r,n))+"\u2591".repeat(Math.max(0,n-r))}function aP(t,e){let n=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&n===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let r=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 ${pn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${pn(c)} conversations`)}else{o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&n>0?1:c,g=h===1?"1 session":`${pn(h)} sessions`,y=a*256+n;o.push(` ${pn(a)} events \xB7 ${g} \xB7 ~${Ku(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:Vu[h]||h})).sort((h,g)=>g.count-h.count):d=(t.by_category??[]).filter(h=>h&&h.count>0);let f=d.slice(0,r),m=f.length>0?f[0].count:1;for(let h of f)o.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${kr(h.count,m,30)}`);let p=Math.max(0,d.length-r);return p>0&&o.push(` ... ${p} more categor${p===1?"y":"ies"}`),o}function cP(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 n=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),r=n.length>0?n[0][1]:1;for(let[o,s]of n){let i=hP[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${kr(s,r,20)}`)}return e}function uP(t,e){let n=[],r=Ku(t),o=(e?.totalEvents??0)*256+t,s=Ku(o);return n.push(""),n.push("\u2500".repeat(65)),n.push("Your AI talks less, remembers more, costs less."),n.push(`${r} this session \xB7 ${s} lifetime`),n.push("\u2500".repeat(65)),n}var lP=256;function dP(t){if(!t)return[];let e=[],n=[];for(let o of t.perAdapter)(o.isReal?e:n).push(o);if(e.length===0&&n.length===0)return[];let r=[];if(e.length>0){r.push(""),r.push("Where it came from (tools you actually used \u2014 fixtures + probes filtered):"),r.push("");let o=16,s=10,i=10,a=16;r.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?pn(u.eventCount):"\u2014",f=ot(u.dataBytes),m=ot(l);r.push(` ${Wu(u.name).padEnd(o)}${d.padStart(s)}${f.padStart(i)}${m.padStart(a)}`)}}if(n.length>0){e.length>0&&r.push("");let o=n.map(s=>Wu(s.name)).join(", ");r.push(` Skipped (${n.length}): ${o}`),r.push(" These adapters have DBs on disk but only test fixtures, dev skeletons,"),r.push(" or detection probes \u2014 no real chat activity.")}return r}function Xu(t,e,n,r){let o=[],s=UU(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(O=>O.isReal).length??0;if(l&&d>0){let O=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,j=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,M=j>0?`Across ${j} day${j===1?"":"s"} `:"",V=O>0?`you ran ${pn(O)} conversation${O===1?"":"s"} `:"you ran ",w;if(d>=2)w=`across ${d} AI tools`;else{let P=l.perAdapter.find(H=>H.isReal);w=`in ${P?Wu(P.name):"Claude Code"}`}o.push(`${M}${V}${w}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=FU(),R=r?.cwd??process.cwd(),j=r?.now??Date.now(),M=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...ZU({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:M,tz:V,now:j,version:e,latestVersion:n})),o.join(`
655
+ `)}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),_=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(`${ot(m)} entered context | 0 tokens saved`),o.push(...aP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...dP(l)),o.push(...cP(i)),o.push(...uP(0,i)),o.push("");let O=e?`v${e}`:"context-mode";return o.push(O),e&&n&&n!=="unknown"&&pP(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
656
+ `)}o.push(`${pn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Ku(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${kr(h,h)}| ${ot(h)}`),o.push(`With context-mode |${kr(m,h)}| ${ot(m)}`),o.push(""),_>=2?o.push(`${ot(f)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${ot(f)} kept out of your conversation. Never entered context.`),o.push("");let x=[`${p} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${ot(t.cache.bytes_saved)})`),o.push(x.join(" \xB7 "));let b=t.savings.by_tool.filter(O=>O.calls>0);if(b.length>=2){o.push("");let O=b.map(R=>{let j=R.context_kb*1024,M=g<100?j/(1-g/100):j,V=Math.max(0,M-j);return{...R,returnedBytes:j,estimatedSaved:V}}).sort((R,j)=>j.estimatedSaved-R.estimatedSaved);for(let R of O){let j=R.tool.length>22?R.tool.slice(0,19)+"...":R.tool;o.push(` ${j.padEnd(22)} ${String(R.calls).padStart(4)} calls ${ot(R.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(R=>R.median_concurrency!=null&&(R.max_concurrency??1)>1);if(O.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 R of O){let j=R.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${j.padEnd(22)} ${R.calls} batches \xB7 ${R.median_concurrency} typical, ${R.max_concurrency} peak`)}}}o.push(...aP(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...dP(l)),o.push(...cP(i)),o.push(...uP(y,i)),o.push("");let v=e?`v${e}`:"context-mode";return o.push(v),e&&n&&n!=="unknown"&&n!==e&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
657
+ `)}var nl=As(eF(import.meta.url)),Wn=(()=>{for(let t of["../package.json","./package.json"]){let e=gt(nl,t);if(Me(e))try{return JSON.parse(ma(e,"utf8")).version}catch{}}return"unknown"})();function OP(){return Me(gt(nl,"package.json"))?nl:As(nl)}function oF(t){try{let e=process.platform==="win32"?il("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):il("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=Eu(String(e.stdout));if(n&&Me(gt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function IP(t){let e=OP();return t==="codex"?oF(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
658
+ `)}),process.on("uncaughtException",t=>{try{KU(2,`[context-mode] uncaughtException: ${t?.message??t}
659
+ `)}finally{process.exit(1)}}));var ko=ru(),rl=$v(ko),Te=new Xc({name:"context-mode",version:Wn}),sF=[];function iF(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??$t().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??aF(n);return cF(r)&&uF(r)}function aF(t){let e=t==="kilo"?"kilo":"opencode",n=[gt(`${e}.json`),gt(`${e}.jsonc`),gt(`.${e}`,`${e}.json`),gt(`.${e}`,`${e}.jsonc`),Ot(Os(),".config",e,`${e}.json`),Ot(Os(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!Me(r))continue;return JSON.parse(Xi(ma(r,"utf8")))}catch{}return null}function cF(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function uF(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var AP=iF(),Xg=!1;function lF(t={}){if(Xg)return;Xg=!0;let e=t.write??(r=>{process.stderr.write(r)}),n=t.platform??"opencode/kilo";e(`[context-mode] ctx_* tools/list intentionally empty on this MCP child: legacy mcp.context-mode block coexists with plugin: ["${dn}"] in ${n}.json \u2014 plugin-native tools are the supported path (#623). Run \`context-mode upgrade\` to remove the legacy block (preserves other MCP servers).
660
+ `)}function N5(){Xg=!1}function dF(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Wr,async()=>({tools:[]}))}var pF=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(AP){lF();return}let o=fF(e,r);return sF.push({name:e,config:n,handler:o}),t[2]=o,pF(...t)};function fF(t,e){return async n=>{LT();try{return await e(n)}catch(r){let o=bF(r);if(o)try{return W(t,o)}catch(s){if(s instanceof gr)return o;throw s}throw r}finally{zT()}}}AP&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&dF(Te);var oy=new rF;async function D5(t,e){let n=typeof t=="string"?{projectDir:t}:t;return oy.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Uo,async()=>({prompts:[]}));Te.server.setRequestHandler(zo,async()=>({resources:[]}));Te.server.setRequestHandler(Ho,async()=>({resourceTemplates:[]}));function Yg(t){if(Array.isArray(t))return t.map(Yg);if(t===null||typeof t!="object")return t;let e={};for(let[n,r]of Object.entries(t))if(n!=="additionalProperties"){if(n==="const"){e.enum=[r];continue}e[n]=Yg(r)}return e}function mF(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Wr,async(r,o)=>{let s=await n(r,o);if(s&&Array.isArray(s.tools)){for(let i of s.tools)if(!(!i||i.inputSchema==null))try{i.inputSchema=Yg(i.inputSchema)}catch{}}return s})}catch{}}var ha=new Ui({runtimes:ko,projectRoot:()=>yt()}),dl=Ot(ry(),`cm-fs-preload-${process.pid}.js`);sl(dl,`(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){}})();
661
+ `);process.on("exit",()=>{try{$s(dl)}catch{}});var Is=new Map,gP=!1;function vr(){let t=oy.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??hF();if(e)return{sessionId:e}}var Yu;function hF(t){let e=Date.now();if(!t?.bypassCache&&Yu&&e-Yu.checkedAt<2e3)return Yu.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??He(),o=Ki({projectDir:n,sessionsDir:r});if(!Me(o))return;let s=qe(),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&&(Yu={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function gF(t){try{let e=He();if(!Me(e))return;let n=wh({projectDir:yt(),sessionsDir:e,ext:"-events.md"});if(!Me(n))return;try{t.index({path:n,source:"session-events",attribution:vr()}),$s(n)}catch{}}catch{}}var fn=null;async function yF(){if(fn)return fn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(vs(),Og)),e=$t();return await t(e.platform)}catch{return null}}function Rs(){if(fn)return fn.getSessionDir();try{let t=$t(),e=oa(t.platform);if(e)return kh({configDir:Ot(...e),configDirEnv:_F(e)})}catch{}return kh({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function _F(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 hu(Wi(Rs))}function yt(){let t=oy.getStore();if(t)return t.projectDir;let e,n,r;try{let o=$t().platform;n=o,o==="claude-code"&&(e=Ot(Os(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??Ot(Os(),".codex"))}catch{}return oP({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function xF(t){return QU(t)?t:gt(yt(),t)}function fa(){return Ki({projectDir:yt(),sessionsDir:He()})}function pl(){let t=hu(vh(Rs));return PE({projectDir:yt(),contentDir:t})}function Rn(){let t=pl(),e=Is.get(t);if(!e){e=new lu(t),Is.set(t,e);let n=yt();e.setDenyChecker(r=>{try{let o=zu("Read",n);return ia(r,o,process.platform==="win32",n).denied}catch{return!0}});try{e.cleanupStaleSources(14)}catch{}if(!gP){gP=!0;try{let r=Ot(Os(),".context-mode","content");Me(r)&&oE(r,0)}catch{}fh()}}return gF(e),e}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function bF(t){return t instanceof gr?{content:[{type:"text",text:EE(t)}],isError:!0}:null}var Kn=null,Qu=0,yP=0,SF=3,kF=3600*1e3;async function _P(){return new Promise(t=>{let e=nF(VE,{headers:{Connection:"close"}},n=>{let r="";n.on("data",o=>{r+=o}),n.on("end",()=>{try{let o=JSON.parse(r);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function vF(){let t=fn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g @mxalbert/context-mode"}function EF(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number);for(let o=0;o<3;o++){if((n[o]??0)>(r[o]??0))return!0;if((n[o]??0)<(r[o]??0))return!1}return!1}function wF(){return!Kn||Kn==="unknown"?!1:EF(Kn,Wn)}function TF(){if(!wF())return!1;let t=Date.now();if(Qu>=SF){if(t-yP<kF)return!1;Qu=0}return Qu===0&&(yP=t),Qu++,!0}var xP=!1;function PF(){if(!xP){xP=!0;try{let t=Dt(),e=gt(t,"plugins","installed_plugins.json");if(!Me(e))return;let n=JSON.parse(ma(e,"utf-8")),r=gt(t,"plugins","cache"),o;try{o=$P(r)}catch{o=r}let s=OP();for(let[i,a]of Object.entries(n.plugins??{}))if(i===Kt)for(let c of a){let u=c.installPath;if(!u||Me(u)||!gt(u).startsWith(o+YU))continue;try{CP(u).isSymbolicLink()&&$s(u)}catch{}let l=As(u);Me(l)||JU(l,{recursive:!0}),Me(s)&&XU(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(Hg(),PF(),TF()&&e.content.length>0){let r=vF();e.content[0].text=`\u26A0\uFE0F context-mode v${Wn} outdated \u2192 v${Kn} available. Upgrade: ${r}
662
+
663
+ `+e.content[0].text}let n=e.content.reduce((r,o)=>r+Buffer.byteLength(o.text),0);return ne.calls[t]=(ne.calls[t]||0)+1,ne.bytesReturned[t]=(ne.bytesReturned[t]||0)+n,al(),setImmediate(()=>KT(fa(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>ZT({sessionDbPath:fa(),toolName:t,bytesReturned:n})),e}function mn(t,e="unknown"){ne.bytesIndexed+=t,al(),t>0&&setImmediate(()=>qT({sessionDbPath:fa(),source:e,bytesAvoided:t}))}var RF=500,CF=2,$F=3e4,OF=256,Qg=0,el,IF=/^[A-Za-z0-9._-]+$/;function AF(t){return IF.test(t)?t:`pid-${process.ppid}`}function NP(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=AF(t),n=hu(Eh(Rs));return Ot(n,`stats-${e}.json`)}function al(){let t=Date.now();if(!(t-Qg<RF)){Qg=t;try{let e=Object.values(ne.bytesReturned).reduce((d,f)=>d+f,0),n=Object.values(ne.calls).reduce((d,f)=>d+f,0),r=ne.bytesIndexed+ne.bytesSandboxed+ne.cacheBytesSaved,o=r+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(r/4),a=el?.tokens??0;if(!el||t-el.computedAt>$F)try{a=(ua({sessionsDir:He()})?.totalEvents??0)*OF,el={tokens:a,computedAt:t}}catch{}let c={schemaVersion:CF,version:Wn,updated_at:t,session_start:ne.sessionStart,uptime_ms:t-ne.sessionStart,total_calls:n,bytes_returned:e,bytes_indexed:ne.bytesIndexed,bytes_sandboxed:ne.bytesSandboxed,cache_hits:ne.cacheHits,cache_bytes_saved:ne.cacheBytesSaved,kept_out:r,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*da()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*da()).toFixed(2),by_tool:Object.fromEntries(Object.keys({...ne.calls,...ne.bytesReturned}).map(d=>[d,{calls:ne.calls[d]||0,bytes:ne.bytesReturned[d]||0}]))},u=NP(),l=`${u}.tmp`;sl(l,JSON.stringify(c)),GU(l,u)}catch{}}}function sy(t,e){try{let n=Mg(process.env.CLAUDE_PROJECT_DIR),r=Lg(t,n);if(r.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${r.matchedPattern}`}],isError:!0})}catch{}return null}function DP(t,e,n){try{let r=jT(t,e);if(r.length===0)return null;let o=Mg(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=Lg(s,o);if(i.decision==="deny")return W(n,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function NF(t,e){try{let n=yt(),r=jg("Read","allow",n);return MT(t,n,r).allowed?null:W(e,{content:[{type:"text",text:`File access blocked: "${t}" resolves outside the project root (${n}). context-mode confines ${e} to the workspace so it cannot be used to bypass the host's sandbox/permission controls (issue #852). To intentionally process a file outside the project, add a host allow rule, e.g. "permissions": { "allow": ["Read(${t})"] } in your settings.`}],isError:!0})}catch{}return null}function ey(t,e){try{let n=yt(),r=zu("Read",n),o=ia(t,r,process.platform==="win32",n);if(o.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}var DF=rl.join(", "),MF=ou()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",jF="",LF="";function zF(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===jF){for(e.push(n),r++;r<t.length&&t[r]!==LF;)n++,r++;r<t.length&&r++}else n++,r++;return e}function MP(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of zF(r))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,n)+`
664
664
  \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>=n)break;let d=t.slice(u,Math.min(l,u+(n-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
665
665
 
666
- `)}function zF(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
666
+ `)}function HF(t,e,n,r=80*1024,o="batch"){let s=[],i=0,a=o==="global"?void 0:n;for(let c of e){if(i>r){s.push(`## ${c}
667
667
  (output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
668
- `);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=DP(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
669
- > **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function HF(t){return`'${t.replace(/'/g,"'\\''")}'`}function UF(t){return`'${t.replace(/'/g,"''")}'`}function FF(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${UF(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${HF(n)} `}var _P=500;function MP(t){let e=t.replace(/\s+/g," ").trim();return e.length<=_P?e:e.slice(0,_P)+"\u2026"}var BF=12e4;function ay(t){if(t!==void 0)return t;if($t().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:BF}var xP=2e3;function ZF(t){return t.length<=xP?t:t.slice(0,xP)+`
670
- \u2026 (truncated)`}function jP(t,e,n){let r=n?`path=${n}
668
+ `);continue}let u=t.searchWithFallback(c,3,a,void 0,"exact");if(s.push(`## ${c}`),s.push(""),u.length>0){for(let l of u){let d=MP(l.content,c,3e3,l.highlighted);s.push(`### ${l.title}`),s.push(d),s.push(""),i+=d.length+l.title.length}continue}s.push("No matching sections found."),s.push("")}return o==="global"?s.push(`
669
+ > **Scope:** Queries searched the entire persistent index (query_scope: "global").`):s.push('\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])` or call ctx_batch_execute with `query_scope: "global"`.'),s}function UF(t){return`'${t.replace(/'/g,"'\\''")}'`}function FF(t){return`'${t.replace(/'/g,"''")}'`}function BF(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${FF(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${UF(n)} `}var bP=500;function jP(t){let e=t.replace(/\s+/g," ").trim();return e.length<=bP?e:e.slice(0,bP)+"\u2026"}var ZF=12e4;function iy(t){if(t!==void 0)return t;if($t().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:ZF}var SP=2e3;function qF(t){return t.length<=SP?t:t.slice(0,SP)+`
670
+ \u2026 (truncated)`}function LP(t,e,n){let r=n?`path=${n}
671
671
  `:"",o=`\`\`\`${t}
672
- ${ZF(e)}
672
+ ${qF(e)}
673
673
  \`\`\``;return`${r}${o}
674
674
 
675
- `}function bP(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=MP(e);return`# ${t}
675
+ `}function kP(t,e,n,r){let o=n||"(no output)",s=o.matchAll(/__CM_FS__:(\d+)/g),i=0;for(let c of s)i+=parseInt(c[1]);i>0&&(r?.(i),o=o.replace(/__CM_FS__:\d+\n?/g,""));let a=jP(e);return`# ${t}
676
676
 
677
677
  $ ${a}
678
678
 
679
679
  ${o}
680
- `}function SP(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
680
+ `}function vP(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
681
681
  `)?"":`
682
- `}${n}`:n:e}async function qF(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let f=[],m=Date.now(),p=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let x=Date.now()-m,b=r-x;if(b<=0){f.push(`# ${g.label}
682
+ `}${n}`:n:e}async function VF(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let f=[],m=Date.now(),p=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let x=Date.now()-m,b=r-x;if(b<=0){f.push(`# ${g.label}
683
683
 
684
684
  (skipped \u2014 batch timeout exceeded)
685
- `),p=!0;continue}y=b}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(f.push(bP(g.label,g.command,SP(_),a)),_.timedOut){p=!0;for(let x=h+1;x<t.length;x++)f.push(`# ${t[x].label}
685
+ `),p=!0;continue}y=b}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(f.push(kP(g.label,g.command,vP(_),a)),_.timedOut){p=!0;for(let x=h+1;x<t.length;x++)f.push(`# ${t[x].label}
686
686
 
687
687
  (skipped \u2014 batch timeout exceeded)
688
- `);break}}return{outputs:f,timedOut:p}}let c=t.map(f=>({run:async()=>{let m=await n.execute({language:"shell",code:`${s}${f.command}`,timeout:r,cwd:i}),p=bP(f.label,f.command,SP(m),a);return{output:m.timedOut?p.replace(/\n$/,"")+`
688
+ `);break}}return{outputs:f,timedOut:p}}let c=t.map(f=>({run:async()=>{let m=await n.execute({language:"shell",code:`${s}${f.command}`,timeout:r,cwd:i}),p=kP(f.label,f.command,vP(m),a);return{output:m.timedOut?p.replace(/\n$/,"")+`
689
689
  (timed out after ${r??"?"}ms)
690
690
  `:p,timedOut:!!m.timedOut}}})),{settled:u}=await sh(c,{concurrency:o}),l=new Array(t.length),d=!1;for(let f=0;f<u.length;f++){let m=u[f];if(m.status==="fulfilled")l[f]=m.value.output,m.value.timedOut&&(d=!0);else{let p=m.reason instanceof Error?m.reason.message:String(m.reason);l[f]=`# ${t[f].label}
691
691
 
692
692
  (executor error: ${p})
693
- `}}return{outputs:l,timedOut:d}}Te.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${DF} Languages: ${NF}.
693
+ `}}return{outputs:l,timedOut:d}}Te.registerTool("ctx_execute",{title:"Run code in a sandbox (executes the supplied code)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run code in a sandboxed subprocess.${MF} Languages: ${DF}.
694
694
 
695
695
  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.
696
696
 
@@ -721,9 +721,9 @@ RETURNS:
721
721
  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.
722
722
 
723
723
  EXAMPLE: ctx_execute(language: "javascript", code: "const out = require('child_process').execSync('npm test', {encoding:'utf8', stdio:['ignore','pipe','pipe']}); console.log(out.split('\\\\n').filter(l => /(FAIL|\u2717|\xD7|Error:|Tests +.*(failed|passed))/i.test(l)).slice(0, 60).join('\\\\n'))")
724
- 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(ly,$.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."),cwd:$.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),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'.
724
+ 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(uy,$.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."),cwd:$.string().optional().describe("Optional working directory for shell commands. Non-shell languages still execute from their sandbox temp directory."),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'.
725
725
 
726
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=iy(e,"execute");if(i)return i}else{let i=NP(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
726
+ TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:n,background:r,cwd:o,intent:s})=>{if(t==="shell"){let i=sy(e,"execute");if(i)return i}else{let i=DP(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
727
727
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
728
728
  let __cm_fs=0;
729
729
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -782,16 +782,16 @@ ${e}
782
782
  }
783
783
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
784
784
  setInterval(()=>{},2147483647);`:""}
785
- })(typeof require!=='undefined'?require:null);`);let a=ay(n),c=await ga.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=jP(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ne.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ne.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let m=c.stdout?.trim();return c.backgrounded&&m?W("ctx_execute",{content:[{type:"text",text:`${u}${m}
785
+ })(typeof require!=='undefined'?require:null);`);let a=iy(n),c=await ha.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=LP(t,e),l=c.stderr?.match(/__CM_NET__:(\d+)/);l&&(ne.bytesSandboxed+=parseInt(l[1]),c.stderr=c.stderr.replace(/\n?__CM_NET__:\d+\n?/g,""));let d=c.stderr?.match(/__CM_FS__:(\d+)/);if(d&&(ne.bytesSandboxed+=parseInt(d[1]),c.stderr=c.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),c.timedOut){let m=c.stdout?.trim();return c.backgrounded&&m?W("ctx_execute",{content:[{type:"text",text:`${u}${m}
786
786
 
787
787
  _(process backgrounded after ${a}ms \u2014 still running)_`}]}):m?W("ctx_execute",{content:[{type:"text",text:`${u}${m}
788
788
 
789
789
  _(timed out after ${a}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
790
790
 
791
791
  stderr:
792
- ${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:p}=Hg({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(p)>ul?(hn(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Os(p,s,m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):Buffer.byteLength(p)>ll?(hn(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Os(p,"errors failures exceptions",m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):W("ctx_execute",{content:[{type:"text",text:`${u}${p}`}],isError:m})}let f=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(f)>ul)return hn(Buffer.byteLength(f)),W("ctx_execute",{content:[{type:"text",text:`${u}${Os(f,s,`execute:${t}`)}`}]});if(Buffer.byteLength(f)>ll){let m=LP(f,`execute:${t}`),p={...m,content:m.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return W("ctx_execute",p)}return W("ctx_execute",{content:[{type:"text",text:`${u}${f}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});function LP(t,e){let n=Cn();hn(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:Er()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
793
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}var ul=5e3,ll=102400;function Os(t,e,n,r=5){let o=t.split(`
794
- `).length,s=Buffer.byteLength(t),i=Cn(),a=i.indexPlainText(t,n,void 0,Er()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" 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(`
792
+ ${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:p}=zg({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(p)>cl?(mn(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Cs(p,s,m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):Buffer.byteLength(p)>ul?(mn(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${Cs(p,"errors failures exceptions",m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):W("ctx_execute",{content:[{type:"text",text:`${u}${p}`}],isError:m})}let f=c.stdout||"(no output)";if(s&&s.trim().length>0&&Buffer.byteLength(f)>cl)return mn(Buffer.byteLength(f)),W("ctx_execute",{content:[{type:"text",text:`${u}${Cs(f,s,`execute:${t}`)}`}]});if(Buffer.byteLength(f)>ul){let m=zP(f,`execute:${t}`),p={...m,content:m.content.map((h,g)=>g===0&&h.type==="text"?{...h,text:`${u}${h.text}`}:h)};return W("ctx_execute",p)}return W("ctx_execute",{content:[{type:"text",text:`${u}${f}`}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});function zP(t,e){let n=Rn();mn(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:vr()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
793
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}var cl=5e3,ul=102400;function Cs(t,e,n,r=5){let o=t.split(`
794
+ `).length,s=Buffer.byteLength(t),i=Rn(),a=i.indexPlainText(t,n,void 0,vr()),c=i.searchWithFallback(e,r,n),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${n}" 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(`
795
795
  `)}let l=[`Indexed ${a.totalChunks} sections from "${n}" 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(`
796
796
  `)[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(`
797
797
  `)}Te.registerTool("ctx_execute_file",{title:"Run code over a file (executes code, reads the given path)",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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.
@@ -813,7 +813,7 @@ RETURNS:
813
813
  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.
814
814
 
815
815
  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'))")
816
- 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:n,timeout:r,intent:o})=>{let s=AF(t,"ctx_execute_file");if(s)return s;let i=ty(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=iy(n,"execute_file");if(a)return a}else{let a=NP(n,e,"execute_file");if(a)return a}try{let a=ay(r),c=await ga.executeFile({path:t,language:e,code:n,timeout:a}),u=jP(e,n,t);if(c.timedOut)return W("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:f}=Hg({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(f)>ul?(hn(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Os(f,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>ll?(hn(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Os(f,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):W("ctx_execute_file",{content:[{type:"text",text:`${u}${f}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>ul)return hn(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Os(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>ll){let d=LP(l,`file:${t}`),f={...d,content:d.content.map((m,p)=>p===0&&m.type==="text"?{...m,text:`${u}${m.text}`}:m)};return W("ctx_execute_file",f)}return W("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Te.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},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.
816
+ 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:n,timeout:r,intent:o})=>{let s=NF(t,"ctx_execute_file");if(s)return s;let i=ey(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=sy(n,"execute_file");if(a)return a}else{let a=DP(n,e,"execute_file");if(a)return a}try{let a=iy(r),c=await ha.executeFile({path:t,language:e,code:n,timeout:a}),u=LP(e,n,t);if(c.timedOut)return W("ctx_execute_file",{content:[{type:"text",text:`${u}Timed out processing ${t} after ${a}ms`}],isError:!0});if(c.exitCode!==0){let{isError:d,output:f}=zg({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(f)>cl?(mn(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Cs(f,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>ul?(mn(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Cs(f,"errors failures exceptions",d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):W("ctx_execute_file",{content:[{type:"text",text:`${u}${f}`}],isError:d})}let l=c.stdout||"(no output)";if(o&&o.trim().length>0&&Buffer.byteLength(l)>cl)return mn(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Cs(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>ul){let d=zP(l,`file:${t}`),f={...d,content:d.content.map((m,p)=>p===0&&m.type==="text"?{...m,text:`${u}${m.text}`}:m)};return W("ctx_execute_file",f)}return W("ctx_execute_file",{content:[{type:"text",text:`${u}${l}`}]})}catch(a){let c=a instanceof Error?a.message:String(a);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${c}`}],isError:!0})}});Te.registerTool("ctx_index",{title:"Index Content",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},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.
817
817
 
818
818
  WHEN:
819
819
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -831,20 +831,20 @@ RETURNS:
831
831
  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.
832
832
 
833
833
  EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
834
- 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:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=ty(e,"ctx_index");if(l)return l}try{let l=e?_F(e):void 0;if(l&&He(l)&&RP(l).isSymbolicLink()){let p;try{p=CP(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=ty(p,"ctx_index");if(h)return h}}if(l&&He(l)&&PP(l).isDirectory()){let m=Cn(),p=Ot(),h=Hu("Read",p),g=process.platform==="win32",y=O=>{try{return ia(O,h,g,p).denied}catch{return!1}},_=m.indexDirectory({path:l,source:n??l,attribution:Er(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",b=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",v=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${b}${v}
835
- Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)hn(Buffer.byteLength(t));else if(l)try{let m=await import("fs");hn(m.readFileSync(l).byteLength)}catch{}let f=Cn().index({content:t,path:l,source:n??l,attribution:Er()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
836
- 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 W("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});function cy(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var VF=cy("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),ny=cy("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),sl=cy("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),WF=new Zu({windowMs:VF,softCapAfter:ny,blockAfter:sl});function KF(){try{return Er()?.sessionId??"__default__"}catch{return"__default__"}}function uy(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function ly(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function GF(t){let e=uy(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}Te.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\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:QT(Vg)},async t=>{try{let e=Cn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
834
+ 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:n,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u})=>{if(!t&&!e)return W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let l=ey(e,"ctx_index");if(l)return l}try{let l=e?xF(e):void 0;if(l&&Me(l)&&CP(l).isSymbolicLink()){let p;try{p=$P(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=ey(p,"ctx_index");if(h)return h}}if(l&&Me(l)&&RP(l).isDirectory()){let m=Rn(),p=yt(),h=zu("Read",p),g=process.platform==="win32",y=O=>{try{return ia(O,h,g,p).denied}catch{return!1}},_=m.indexDirectory({path:l,source:n??l,attribution:vr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",b=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",v=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${b}${v}
835
+ Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)mn(Buffer.byteLength(t));else if(l)try{let m=await import("fs");mn(m.readFileSync(l).byteLength)}catch{}let f=Rn().index({content:t,path:l,source:n??l,attribution:vr()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
836
+ 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 W("ctx_index",{content:[{type:"text",text:`Index error: ${d}`}],isError:!0})}});function ay(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var WF=ay("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),ty=ay("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),ol=ay("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),KF=new Bu({windowMs:WF,softCapAfter:ty,blockAfter:ol});function GF(){try{return vr()?.sessionId??"__default__"}catch{return"__default__"}}function cy(t){if(typeof t=="string"){if(t.trim().length===0)return t;try{let n=JSON.parse(t);if(Array.isArray(n))return n}catch{}return[t]}return t}function uy(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function JF(t){let e=cy(t);return Array.isArray(e)?e.map((n,r)=>typeof n=="string"?{label:`cmd_${r+1}`,command:n}:n):e}Te.registerTool("ctx_search",{title:"Search Indexed Content",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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. Each response carries a throttle counter (call #N/M in the rolling time window); results taper toward the soft cap and calls block after the hard cap. Tune via CONTEXT_MODE_SEARCH_WINDOW_MS, CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER, CONTEXT_MODE_SEARCH_BLOCK_AFTER.\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:eP(qg)},async t=>{try{let e=Rn(),n=t.sort||"relevance";if(n!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
837
837
 
838
838
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
839
839
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
840
840
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
841
841
  \u2022 ctx_index(content, source) \u2014 manually index text content
842
842
 
843
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=eP(c,Vg,()=>Ot()),l=Date.now(),d=WF.record(KF(),l),f=d.count;if(d.blocked)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${f} search calls in ${Math.round((l-d.windowStart)/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 m=d.softCapped?1:Math.min(s,2),p=40*1024,h=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let j=ze(),M=Ot(),V=Ki({projectDir:M,sessionsDir:j});He(V)&&(y=new ln({dbPath:V}))}catch{}let x;if(typeof u=="string"&&y)try{x=new Set(y.getSessionIdsForProject(u))}catch{}let b=mn?.getConfigDir()??Dt();try{for(let j of o){if(h>p){g.push(`## ${j}
843
+ After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let r=t,o=[];if(Array.isArray(r.queries)&&r.queries.length>0?o.push(...r.queries):typeof r.query=="string"&&r.query.length>0&&o.push(r.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a,project:c}=t,u=tP(c,qg,()=>yt()),l=Date.now(),d=KF.record(GF(),l),f=d.count;if(d.blocked)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${f} search calls in ${Math.round((l-d.windowStart)/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 m=d.softCapped?1:Math.min(s,2),p=40*1024,h=0,g=[],y=null;if(n==="timeline"||typeof u=="string")try{let j=He(),M=yt(),V=Ki({projectDir:M,sessionsDir:j});Me(V)&&(y=new ln({dbPath:V}))}catch{}let x;if(typeof u=="string"&&y)try{x=new Set(y.getSessionIdsForProject(u))}catch{}let b=fn?.getConfigDir()??Dt();try{for(let j of o){if(h>p){g.push(`## ${j}
844
844
  (output cap reached)
845
- `);continue}let M;if(n==="timeline"?M=YT({query:j,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Ot(),configDir:b,adapter:mn??void 0,projectScope:u}):M=e.searchWithFallback(j,m,i,a,"like",x),M.length===0){g.push(`## ${j}
846
- No results found.`);continue}let V=M.map((w,P)=>{let H=w.origin||"current-session",se=w.timestamp?w.timestamp.slice(0,16).replace("T"," "):"",_t=`--- [${H}${se?" | "+se:""} | ${w.source}] ---`,$n=`### ${w.title}`,fl=DP(w.content,j,1500,w.highlighted);return`${_t}
847
- ${$n}
845
+ `);continue}let M;if(n==="timeline"?M=QT({query:j,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:yt(),configDir:b,adapter:fn??void 0,projectScope:u}):M=e.searchWithFallback(j,m,i,a,"like",x),M.length===0){g.push(`## ${j}
846
+ No results found.`);continue}let V=M.map((w,P)=>{let H=w.origin||"current-session",se=w.timestamp?w.timestamp.slice(0,16).replace("T"," "):"",_t=`--- [${H}${se?" | "+se:""} | ${w.source}] ---`,Cn=`### ${w.title}`,fl=MP(w.content,j,1500,w.highlighted);return`${_t}
847
+ ${Cn}
848
848
 
849
849
  ${fl}`}).join(`
850
850
 
@@ -856,13 +856,13 @@ ${V}`),h+=V.length}}finally{try{y?.close()}catch{}}let v=g.join(`
856
856
 
857
857
  `);e.lastRefreshCount>0&&(v=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
858
858
 
859
- `+v);let O=Math.max(0,sl-f),R=Math.max(0,ny-f);if(f>=ny?v+=`
859
+ `+v);let O=Math.max(0,ol-f),R=Math.max(0,ty-f);if(f>=ty?v+=`
860
860
 
861
- \u26A0 search call #${f}/${sl} in this window. Results limited to ${m}/query. ${O} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:v+=`
861
+ \u26A0 search call #${f}/${ol} in this window. Results limited to ${m}/query. ${O} call(s) remaining before block. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`:v+=`
862
862
 
863
- > Throttle: call #${f}/${sl} in this window. ${R} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,v.trim().length===0){let j=e.listSources(),M=j.length>0?`
864
- Indexed sources: ${j.map(V=>`"${V.label}" (${V.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${M}`}]})}return W("ctx_search",{content:[{type:"text",text:v}]})}catch(e){let n=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});var Wg=null,Kg=null;function JF(){return Wg||(Wg=EP(import.meta.url).resolve("turndown")),Wg}function XF(){return Kg||(Kg=EP(import.meta.url).resolve("turndown-plugin-gfm")),Kg}function YF(t,e){let n=JSON.stringify(JF()),r=JSON.stringify(XF()),o=JSON.stringify(e),s=dl.toString(),i=dl.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
865
- var classifyIp = ${i};`,c=ry.toString(),u=ry.name||"classifyExtraction",l=u==="classifyExtraction"?`var classifyExtraction = ${c};`:`var ${u} = ${c};
863
+ > Throttle: call #${f}/${ol} in this window. ${R} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,v.trim().length===0){let j=e.listSources(),M=j.length>0?`
864
+ Indexed sources: ${j.map(V=>`"${V.label}" (${V.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${M}`}]})}return W("ctx_search",{content:[{type:"text",text:v}]})}catch(e){let n=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${n}`}],isError:!0})}});var Vg=null,Wg=null;function XF(){return Vg||(Vg=TP(import.meta.url).resolve("turndown")),Vg}function YF(){return Wg||(Wg=TP(import.meta.url).resolve("turndown-plugin-gfm")),Wg}function QF(t,e){let n=JSON.stringify(XF()),r=JSON.stringify(YF()),o=JSON.stringify(e),s=ll.toString(),i=ll.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
865
+ var classifyIp = ${i};`,c=ny.toString(),u=ny.name||"classifyExtraction",l=u==="classifyExtraction"?`var classifyExtraction = ${c};`:`var ${u} = ${c};
866
866
  var classifyExtraction = ${u};`,d=process.env.CTX_FETCH_STRICT==="1";return`
867
867
  const TurndownService = require(${n});
868
868
  const { gfm } = require(${r});
@@ -1326,8 +1326,8 @@ async function main() {
1326
1326
  emit('text', text, Buffer.byteLength(text, 'utf-8'), 'text', '1-text-passthrough', []);
1327
1327
  }
1328
1328
  main();
1329
- `}var QF=1440*60*1e3,kP=3072;function eB(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}function ry(t,e){if(!Number.isFinite(e)||e<=0)return{kind:"ok"};if(!Number.isFinite(t)||t>=200)return{kind:"ok"};let o=t/e;return o>=.02?{kind:"ok"}:{kind:"shell",textBytes:t,sourceBytes:e,yieldPct:(o*100).toFixed(2)}}async function tB(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 n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=dl(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"&&n)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(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),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 dl(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?dl(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.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 nB(t,e,n,r){let o=await tB(t);if(o)return o;if(!n&&r!==0){let i=Cn(),a=gh(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??QF;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:eB(d)}}}}let s=yt(oy(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=YF(t,s),a=await ga.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let g=a.stderr||a.stdout||"unknown error",_=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(g)?" \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:`${g}${_}`,reason:"exit"}}let c=(a.stdout||"").trim().split(`
1330
- `),u=(c[0]||"").trim(),l=Number.parseInt((c[1]||"").trim(),10),d=rB((c[2]||"").trim()),f=(c[3]||"").trim()||"unreported",m=oB(c[4]||""),p;try{let y=PP(s).size;if(y>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${y} bytes exceeds cap 52428800`,reason:"read"};p=ha(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}if(p.length===0)return{kind:"fetch_error",url:t,error:"empty content",reason:"empty"};let h=ry(p.length,l);if(h.kind==="shell"){let g=m.length>0?` The ladder was climbed first and every rung came back empty: ${m.join(", ")}.`:"";return{kind:"fetch_error",url:t,error:`extracted only ${h.textBytes} bytes of text from ${h.sourceBytes} bytes received (${h.yieldPct}% yield) \u2014 the response was a shell whose content is rendered client-side by JavaScript, so an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered).${g} Retrying this URL returns the same shell. Fetch this page's source instead: its repository README or raw doc file on GitHub, its OpenAPI or JSON schema endpoint, or a sibling page of the same host that is server-rendered.`,reason:"shell"}}return{kind:"fetched",url:t,source:e,markdown:p,header:u,route:d,rung:f}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{TP(s)}catch{}}}function rB(t){return t==="markdown"?"markdown":t==="json"?"json":t==="text"?"text":"html"}function oB(t){let e=t.trim();if(e.length===0)return[];let n;try{n=JSON.parse(e)}catch{return[]}if(!Array.isArray(n))return[];let r=[];for(let o of n)typeof o=="string"&&o.length>0&&r.push(o);return r}function nl(t){return t==="1-accept-markdown"?"rung 1 \u2014 the site served markdown to the Accept header on the request we were already making":t==="1-html-converted"?"rung 1 \u2014 the site served HTML and it converted to an article":t==="1-json-passthrough"?"rung 1 \u2014 JSON response, indexed as-is":t==="1-text-passthrough"?"rung 1 \u2014 plain-text response, indexed as-is":t==="2a-md-sibling"?"rung 2a \u2014 rung 1 returned a JavaScript shell, and the page's .md sibling carried the article":t==="2b-llms-txt"?"rung 2b \u2014 rung 1 returned a JavaScript shell, and this host's llms.txt named the article elsewhere":t==="ladder-exhausted"?"ladder exhausted \u2014 every rung came back empty":t==="unreported"?"rung not reported (older fetch bundle)":`rung ${t}`}var Gg=null;function sB(){return Gg||(Gg=new pu(yt(Eo(ma()),"fetch-pages.db"))),Gg}function iB(t){let e=Cn(),n=gh(t.source,t.url),r=Er(),o=t.route??"html",s=t.rung??"unreported",i=t.markdown,a,c=[];if(!uE(o))try{let d=lE({url:t.url,sourceLabel:n,document:t.markdown,route:o,store:sB()});if(d.kind==="refuse")return{label:n,totalChunks:0,totalBytes:d.storedBytes,preview:"",refusal:`${nl(s)}; ${d.reason}`};i=d.indexText,c=d.relabelled,o==="markdown"?a=`${nl(s)}; site-authored markdown (${d.storedBytes} B) \u2014 no extraction needed`:d.provisional?a=`${nl(s)}; rung 4 (block classification) \u2014 first page seen from this host, so all ${d.totalBlocks} blocks were indexed as content (PROVISIONAL); they are re-classified automatically when a second page of this host is fetched`:a=`${nl(s)}; rung 4 (block classification) \u2014 ${d.totalBlocks-d.templateBlocks}/${d.totalBlocks} blocks indexed as content (${d.contentBytes} B); ${d.templateBlocks} blocks (${d.templateBytes} B) were seen on other pages of this host, so they are labelled template \u2014 stored whole, kept out of the index`}catch(d){a=`extraction unavailable (${d instanceof Error?d.message:String(d)}) \u2014 indexed the full document`,i=t.markdown}let u;t.header==="__CM_CT__:json"?u=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?u=e.indexPlainText(t.markdown,n,void 0,r):u=e.index({content:i,source:n,attribution:r});for(let d of c)try{e.index({content:d.indexText,source:d.sourceLabel,attribution:r})}catch{}c.length>0&&(a=(a?a+"; ":"")+`re-classified ${c.length} earlier page(s) of this host now that a second page exists`),hn(Buffer.byteLength(t.markdown));let l=i.length>kP?UT(i,kP)+`
1329
+ `}var eB=1440*60*1e3,EP=3072;function tB(t){if(t===0)return"0ms";let e=1440*60*1e3,n=3600*1e3,r=60*1e3;return t%e===0?`${t/e}d`:t%n===0?`${t/n}h`:t%r===0?`${t/r}m`:`${t}ms`}function ny(t,e){if(!Number.isFinite(e)||e<=0)return{kind:"ok"};if(!Number.isFinite(t)||t>=200)return{kind:"ok"};let o=t/e;return o>=.02?{kind:"ok"}:{kind:"shell",textBytes:t,sourceBytes:e,yieldPct:(o*100).toFixed(2)}}async function nB(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 n=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:r}=await import("node:dns/promises"),o=await r(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=ll(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"&&n)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(r){let o=r?.code??"",s=o==="ETIMEOUT"||o==="ETIMEDOUT"||o==="EAI_AGAIN"||o==="ENETUNREACH"||o==="EPERM",i=r instanceof Error?r.message:String(r),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 ll(t){let e=t.indexOf("%"),n=e===-1?t:t.slice(0,e),r=n.toLowerCase();if(r.includes(":")){let a=r.match(/^::ffff:([\d.]+)$/);return a?ll(a[1]):r==="::"||r.startsWith("fe8")||r.startsWith("fe9")||r.startsWith("fea")||r.startsWith("feb")||r.startsWith("ff")?"block":r==="::1"||r.startsWith("fc")||r.startsWith("fd")?"private":"public"}if(!n.includes("."))return"block";let o=n.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 rB(t,e,n,r){let o=await nB(t);if(o)return o;if(!n&&r!==0){let i=Rn(),a=mh(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??eB;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:tB(d)}}}}let s=Ot(ry(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=QF(t,s),a=await ha.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let g=a.stderr||a.stdout||"unknown error",_=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(g)?" \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:`${g}${_}`,reason:"exit"}}let c=(a.stdout||"").trim().split(`
1330
+ `),u=(c[0]||"").trim(),l=Number.parseInt((c[1]||"").trim(),10),d=oB((c[2]||"").trim()),f=(c[3]||"").trim()||"unreported",m=sB(c[4]||""),p;try{let y=RP(s).size;if(y>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${y} bytes exceeds cap 52428800`,reason:"read"};p=ma(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}if(p.length===0)return{kind:"fetch_error",url:t,error:"empty content",reason:"empty"};let h=ny(p.length,l);if(h.kind==="shell"){let g=m.length>0?` The ladder was climbed first and every rung came back empty: ${m.join(", ")}.`:"";return{kind:"fetch_error",url:t,error:`extracted only ${h.textBytes} bytes of text from ${h.sourceBytes} bytes received (${h.yieldPct}% yield) \u2014 the response was a shell whose content is rendered client-side by JavaScript, so an HTTP fetch cannot see it. Nothing was indexed (the response is stored whole and unaltered).${g} Retrying this URL returns the same shell. Fetch this page's source instead: its repository README or raw doc file on GitHub, its OpenAPI or JSON schema endpoint, or a sibling page of the same host that is server-rendered.`,reason:"shell"}}return{kind:"fetched",url:t,source:e,markdown:p,header:u,route:d,rung:f}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{PP(s)}catch{}}}function oB(t){return t==="markdown"?"markdown":t==="json"?"json":t==="text"?"text":"html"}function sB(t){let e=t.trim();if(e.length===0)return[];let n;try{n=JSON.parse(e)}catch{return[]}if(!Array.isArray(n))return[];let r=[];for(let o of n)typeof o=="string"&&o.length>0&&r.push(o);return r}function tl(t){return t==="1-accept-markdown"?"rung 1 \u2014 the site served markdown to the Accept header on the request we were already making":t==="1-html-converted"?"rung 1 \u2014 the site served HTML and it converted to an article":t==="1-json-passthrough"?"rung 1 \u2014 JSON response, indexed as-is":t==="1-text-passthrough"?"rung 1 \u2014 plain-text response, indexed as-is":t==="2a-md-sibling"?"rung 2a \u2014 rung 1 returned a JavaScript shell, and the page's .md sibling carried the article":t==="2b-llms-txt"?"rung 2b \u2014 rung 1 returned a JavaScript shell, and this host's llms.txt named the article elsewhere":t==="ladder-exhausted"?"ladder exhausted \u2014 every rung came back empty":t==="unreported"?"rung not reported (older fetch bundle)":`rung ${t}`}var Kg=null;function iB(){return Kg||(Kg=new du(Ot(As(pl()),"fetch-pages.db"))),Kg}function aB(t){let e=Rn(),n=mh(t.source,t.url),r=vr(),o=t.route??"html",s=t.rung??"unreported",i=t.markdown,a,c=[];if(!lE(o))try{let d=dE({url:t.url,sourceLabel:n,document:t.markdown,route:o,store:iB()});if(d.kind==="refuse")return{label:n,totalChunks:0,totalBytes:d.storedBytes,preview:"",refusal:`${tl(s)}; ${d.reason}`};i=d.indexText,c=d.relabelled,o==="markdown"?a=`${tl(s)}; site-authored markdown (${d.storedBytes} B) \u2014 no extraction needed`:d.provisional?a=`${tl(s)}; rung 4 (block classification) \u2014 first page seen from this host, so all ${d.totalBlocks} blocks were indexed as content (PROVISIONAL); they are re-classified automatically when a second page of this host is fetched`:a=`${tl(s)}; rung 4 (block classification) \u2014 ${d.totalBlocks-d.templateBlocks}/${d.totalBlocks} blocks indexed as content (${d.contentBytes} B); ${d.templateBlocks} blocks (${d.templateBytes} B) were seen on other pages of this host, so they are labelled template \u2014 stored whole, kept out of the index`}catch(d){a=`extraction unavailable (${d instanceof Error?d.message:String(d)}) \u2014 indexed the full document`,i=t.markdown}let u;t.header==="__CM_CT__:json"?u=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?u=e.indexPlainText(t.markdown,n,void 0,r):u=e.index({content:i,source:n,attribution:r});for(let d of c)try{e.index({content:d.indexText,source:d.sourceLabel,attribution:r})}catch{}c.length>0&&(a=(a?a+"; ":"")+`re-classified ${c.length} earlier page(s) of this host now that a second page exists`),mn(Buffer.byteLength(t.markdown));let l=i.length>EP?FT(i,EP)+`
1331
1331
 
1332
1332
  \u2026[preview window only \u2014 the full document is stored; use ctx_search() to retrieve any section]`:i;return{label:u.label,totalChunks:u.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:l,extraction:a}}Te.registerTool("ctx_fetch_and_index",{title:"Fetch & Index URL(s)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},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.
1333
1333
 
@@ -1351,14 +1351,14 @@ RETURNS:
1351
1351
  EXAMPLE: ctx_fetch_and_index(
1352
1352
  requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
1353
1353
  concurrency: 5
1354
- )`,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(uy,$.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(ly,$.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:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return W("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=!n&&i.length===1,c=r??1,u=i.map(w=>({run:()=>nB(w.url,w.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await sh(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let w=0;w<l.length;w++){let P=l[w];if(P.status==="rejected"){let se=P.reason instanceof Error?P.reason.message:String(P.reason);m.push({kind:"job_error",url:i[w].url,error:se});continue}let H=P.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let se=H.estimatedBytes,_t=H.label;setImmediate(()=>qT({sessionDbPath:fa(),source:_t,bytesAvoided:se})),m.push({kind:"cached",label:H.label,chunkCount:H.chunkCount,ageStr:H.ageStr,ttlStr:H.ttlStr})}else if(H.kind==="fetch_error")m.push({kind:"fetch_error",url:H.url,error:H.error,reason:H.reason});else{ne.cacheMisses++;let se=iB(H);se.refusal?m.push({kind:"fetch_error",url:H.url,error:se.refusal,reason:"shell"}):m.push({kind:"fetched",indexed:se})}}if(a){let w=m[0];if(w.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${w.label}** \u2014 ${w.chunkCount} sections, indexed ${w.ageStr} (fresh, TTL: ${w.ttlStr}).
1354
+ )`,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(cy,$.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(uy,$.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:n,concurrency:r,force:o,ttl:s})=>{let i=n||(t?[{url:t,source:e}]:[]);if(i.length===0)return W("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=!n&&i.length===1,c=r??1,u=i.map(w=>({run:()=>rB(w.url,w.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await sh(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let w=0;w<l.length;w++){let P=l[w];if(P.status==="rejected"){let se=P.reason instanceof Error?P.reason.message:String(P.reason);m.push({kind:"job_error",url:i[w].url,error:se});continue}let H=P.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let se=H.estimatedBytes,_t=H.label;setImmediate(()=>VT({sessionDbPath:fa(),source:_t,bytesAvoided:se})),m.push({kind:"cached",label:H.label,chunkCount:H.chunkCount,ageStr:H.ageStr,ttlStr:H.ttlStr})}else if(H.kind==="fetch_error")m.push({kind:"fetch_error",url:H.url,error:H.error,reason:H.reason});else{ne.cacheMisses++;let se=aB(H);se.refusal?m.push({kind:"fetch_error",url:H.url,error:se.refusal,reason:"shell"}):m.push({kind:"fetched",indexed:se})}}if(a){let w=m[0];if(w.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${w.label}** \u2014 ${w.chunkCount} sections, indexed ${w.ageStr} (fresh, TTL: ${w.ttlStr}).
1355
1355
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
1356
1356
 
1357
1357
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
1358
1358
  Use: ctx_search(queries: [...], source: "${w.label}")`}]});if(w.kind==="fetched"){let P=(w.indexed.totalBytes/1024).toFixed(1),H=[`Fetched and indexed **${w.indexed.totalChunks} sections** (${P}KB) from: ${w.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${w.indexed.label}") for specific lookups.`,...w.indexed.extraction?[w.indexed.extraction]:[],"","---","",w.indexed.preview].join(`
1359
1359
  `);return W("ctx_fetch_and_index",{content:[{type:"text",text:H}]})}if(w.kind==="fetch_error"){let P=w.reason==="empty"?`Fetched ${w.url} but got empty content`:w.reason==="shell"?`Fetched ${w.url} but ${w.error}`:w.reason==="read"?`Fetched ${w.url} but could not read subprocess output`:w.reason==="exit"?`Failed to fetch ${w.url}: ${w.error}`:`Fetch error: ${w.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:P}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${w.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,_=0,x=0,b=0,v=[];for(let w of m)if(w.kind==="cached")_++,h.push(`- [cache] ${w.label} \u2014 ${w.chunkCount} sections (${w.ageStr}, TTL: ${w.ttlStr})`);else if(w.kind==="fetched"){x++,g+=w.indexed.totalChunks,y+=w.indexed.totalBytes;let P=(w.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${w.indexed.label} \u2014 ${w.indexed.totalChunks} sections (${P}KB)`);let H=w.indexed.preview.length>p?w.indexed.preview.slice(0,p).trimEnd()+"\u2026":w.indexed.preview;v.push(`### ${w.indexed.label}
1360
1360
 
1361
- ${H}`)}else b++,h.push(`- [err] ${w.url}: ${w.error}`);let O=(y/1024).toFixed(1),R=f?` cap=${d}/${eF().length}cpu`:"",j=(w,P,H)=>`${w} ${w===1?P:H}`,V=[`fetched ${i.length} c=${d}${R}. ok=${x} cache=${_} err=${b}. ${j(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
1361
+ ${H}`)}else b++,h.push(`- [err] ${w.url}: ${w.error}`);let O=(y/1024).toFixed(1),R=f?` cap=${d}/${tF().length}cpu`:"",j=(w,P,H)=>`${w} ${w===1?P:H}`,V=[`fetched ${i.length} c=${d}${R}. ok=${x} cache=${_} err=${b}. ${j(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
1362
1362
  `);return W("ctx_fetch_and_index",{content:[{type:"text",text:V}],isError:b===i.length})});Te.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},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.
1363
1363
 
1364
1364
  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).
@@ -1384,12 +1384,12 @@ EXAMPLE: ctx_batch_execute(
1384
1384
  ],
1385
1385
  queries: ["root cause", "proposed fix"],
1386
1386
  concurrency: 2
1387
- )`,inputSchema:$.object({commands:$.preprocess(GF,$.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(uy,$.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."),cwd:$.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:$.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=iy(i.command,"batch_execute");if(a)return a}try{let i=FF(vo.shell,pl),a=ay(n),{outputs:c,timedOut:u}=await qF(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:R=>{ne.bytesSandboxed+=R}},ga),l=c.join(`
1387
+ )`,inputSchema:$.object({commands:$.preprocess(JF,$.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(cy,$.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."),cwd:$.string().optional().describe("Optional working directory for all shell commands in this batch."),query_scope:$.enum(["batch","global"]).optional().default("batch").describe("Scope for `queries` (default: `batch`). `batch` searches ONLY the chunks produced by this batch's commands \u2014 useful when you want answers about the just-fetched output. `global` searches the entire persistent index (same scope as ctx_search) \u2014 useful when you want the batch commands to enrich context and the queries to also surface related prior knowledge in one round trip.")})},async({commands:t,queries:e,timeout:n,concurrency:r,cwd:o,query_scope:s})=>{for(let i of t){let a=sy(i.command,"batch_execute");if(a)return a}try{let i=BF(ko.shell,dl),a=iy(n),{outputs:c,timedOut:u}=await VF(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:R=>{ne.bytesSandboxed+=R}},ha),l=c.join(`
1388
1388
  `),d=Buffer.byteLength(l),f=l.split(`
1389
- `).length;if(u&&c.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});hn(d);let m=Cn(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:Er()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${MP(R.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],x=[];for(let R of y){let j=Buffer.byteLength(R.content);_.push(`- ${R.title} (${(j/1024).toFixed(1)}KB)`),x.push(R.title)}let b=zF(m,e,p,void 0,s),v=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],O=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...b,v.length>0?`
1389
+ `).length;if(u&&c.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${a}ms. No output captured.`}],isError:!0});mn(d);let m=Rn(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:vr()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${jP(R.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],x=[];for(let R of y){let j=Buffer.byteLength(R.content);_.push(`- ${R.title} (${(j/1024).toFixed(1)}KB)`),x.push(R.title)}let b=HF(m,e,p,void 0,s),v=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],O=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...b,v.length>0?`
1390
1390
  Searchable terms for follow-up: ${v.join(", ")}`:""].join(`
1391
- `);return W("ctx_batch_execute",{content:[{type:"text",text:O}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});function Jg(t,e){if(!He(e))return;let n=0;try{for(let r of wP(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ha(yt(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function vP(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Te.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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=Ot(),n=nt(e),r=Ki({projectDir:e,sessionsDir:ze()});if(He(r)){let o=qe(),s=new o(r,{readonly:!0});try{let i=new Cs(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=ua({sessionsDir:ze()}),l;try{l=Xu()}catch{}let d,f;try{let p=process.env.CLAUDE_SESSION_ID;if(p||(p=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),p){d=pP({sessionId:p,sessionsDir:ze(),worktreeHash:n});let h=ma(),g;try{let b=qe(),v=(await import("node:fs")).readdirSync(ze()).filter(R=>R.endsWith(".db")&&(!n||R.startsWith(n))),O;for(let R of v)try{let j=new b((await import("node:path")).join(ze(),R),{readonly:!0});try{let M=j.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(M?.project_dir){O=M.project_dir;break}}finally{j.close()}}catch{}g=O?la({projectDir:O,sessionsDir:ze(),worktreeHash:n,contentDbPath:h}):la({sessionId:p,sessionsDir:ze(),worktreeHash:n,contentDbPath:h})}catch{g=la({sessionId:p,sessionsDir:ze(),worktreeHash:n,contentDbPath:h})}let y=la({sessionsDir:ze()}),_=fP(h),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:x}}}catch{}mn?.name==="Pi"&&Jg(u,ze());let m;try{m=Cn().getIndexState()}catch{}t=Yu(a,Kn,Gn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new Cs(vP()).queryAll(ne),i=ua({sessionsDir:ze()});mn?.name==="Pi"&&Jg(i,ze());let a;try{a=Xu()}catch{}let c;try{c=Cn().getIndexState()}catch{}t=Yu(s,Kn,Gn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new Cs(vP()).queryAll(ne),r;try{r=ua({sessionsDir:ze()})}catch{}mn?.name==="Pi"&&r&&Jg(r,ze());let o;try{o=Xu()}catch{}t=Yu(n,Kn,Gn,r||o?{lifetime:r,multiAdapter:o}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Te.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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;try{e=$t(Te.server.getClientVersion()??void 0).platform}catch{e=$t().platform}let n=OP(e),r=11,o=(ol.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${ol.length}/${r} (${o}%) \u2014 ${ol.join(", ")}`),su()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=Wi($s),i=wh($s),a=Th($s);t.push(`[OK] Storage sessions: ${s.path} (${hu(s)})`),t.push(`[OK] Storage content: ${i.path} (${hu(i)})`),t.push(`[OK] Storage stats: ${a.path} (${hu(a)})`);{let u=new Ui({runtimes:vo});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=qe();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await gF();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",f=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${f}`)}let u=tP(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=gt(n,l);He(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Kn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
1392
- `)}]})});Te.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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="",e,n;try{let c=Te.server.getClientVersion(),u=$t(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=nu(u.platform)&&vo.javascript?{platform:u.platform,jsRuntime:vo.javascript}:void 0}catch{try{n=$t().platform}catch{}}let r=OP(n),o=gt(r,"cli.bundle.mjs"),s=gt(r,"build","cli.js");try{let c=ze(),u=yt(Eo(c),"insight-cache");He(u)&&(uB(4747),TP(u,{recursive:!0,force:!0}))}catch{}let i;if(He(o))i=`${zi(o,e)} upgrade${t}`;else if(He(s))i=`${zi(s,e)} upgrade${t}`;else{let u=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(r)};`,'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/mxalbert1996/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"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'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(`
1391
+ `);return W("ctx_batch_execute",{content:[{type:"text",text:O}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${a}`}],isError:!0})}});function Gg(t,e){if(!Me(e))return;let n=0;try{for(let r of WU(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ma(Ot(e,r),"utf-8"));n+=(o?.bytes_sandboxed??0)+(o?.bytes_indexed??0)}catch{}}catch{}if(n>0){let r=(t.rescueBytes??0)/4;t.totalEvents=Math.round((n/4+r)/256)}}function wP(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}Te.registerTool("ctx_stats",{title:"Session Statistics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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=yt(),n=nt(e),r=Ki({projectDir:e,sessionsDir:He()});if(Me(r)){let o=qe(),s=new o(r,{readonly:!0});try{let i=new Ps(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=ua({sessionsDir:He()}),l;try{l=Ju()}catch{}let d,f;try{let p=process.env.CLAUDE_SESSION_ID;if(p||(p=s.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),p){d=fP({sessionId:p,sessionsDir:He(),worktreeHash:n});let h=pl(),g;try{let b=qe(),v=(await import("node:fs")).readdirSync(He()).filter(R=>R.endsWith(".db")&&(!n||R.startsWith(n))),O;for(let R of v)try{let j=new b((await import("node:path")).join(He(),R),{readonly:!0});try{let M=j.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(M?.project_dir){O=M.project_dir;break}}finally{j.close()}}catch{}g=O?la({projectDir:O,sessionsDir:He(),worktreeHash:n,contentDbPath:h}):la({sessionId:p,sessionsDir:He(),worktreeHash:n,contentDbPath:h})}catch{g=la({sessionId:p,sessionsDir:He(),worktreeHash:n,contentDbPath:h})}let y=la({sessionsDir:He()}),_=mP(h),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:x}}}catch{}fn?.name==="Pi"&&Gg(u,He());let m;try{m=Rn().getIndexState()}catch{}t=Xu(a,Wn,Kn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new Ps(wP()).queryAll(ne),i=ua({sessionsDir:He()});fn?.name==="Pi"&&Gg(i,He());let a;try{a=Ju()}catch{}let c;try{c=Rn().getIndexState()}catch{}t=Xu(s,Wn,Kn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new Ps(wP()).queryAll(ne),r;try{r=ua({sessionsDir:He()})}catch{}fn?.name==="Pi"&&r&&Gg(r,He());let o;try{o=Ju()}catch{}t=Xu(n,Wn,Kn,r||o?{lifetime:r,multiAdapter:o}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Te.registerTool("ctx_doctor",{title:"Run Diagnostics",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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;try{e=$t(Te.server.getClientVersion()??void 0).platform}catch{e=$t().platform}let n=IP(e),r=11,o=(rl.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${rl.length}/${r} (${o}%) \u2014 ${rl.join(", ")}`),ou()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=Wi(Rs),i=vh(Rs),a=Eh(Rs);t.push(`[OK] Storage sessions: ${s.path} (${mu(s)})`),t.push(`[OK] Storage content: ${i.path} (${mu(i)})`),t.push(`[OK] Storage stats: ${a.path} (${mu(a)})`);{let u=new Ui({runtimes:ko});try{let l=await u.execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(l.exitCode===0&&l.stdout.trim()==="ok")t.push("[OK] Server test: PASS");else{let d=l.stderr?.trim()?` (${l.stderr.trim().slice(0,200)})`:"";t.push(`[FAIL] Server test: FAIL \u2014 exit ${l.exitCode}${d}`)}}catch(l){t.push(`[FAIL] Server test: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{u.cleanupBackgrounded()}}{let u;try{let l=qe();u=new l(":memory:"),u.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),u.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let d=u.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();d&&d.content==="hello world"?t.push("[OK] FTS5 / SQLite: PASS \u2014 native module works"):t.push("[FAIL] FTS5 / SQLite: FAIL \u2014 unexpected result")}catch(l){t.push(`[FAIL] FTS5 / SQLite: FAIL \u2014 ${l instanceof Error?l.message:l}`)}finally{try{u?.close()}catch{}}}let c=await yF();if(c){for(let l of c.validateHooks(n)){let d=l.status==="pass"?"[OK]":l.status==="warn"?"[WARN]":"[FAIL]",f=l.fix?` \u2014 fix: ${l.fix}`:"";t.push(`${d} ${l.check}: ${l.message}${f}`)}let u=nP(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=gt(n,l);Me(d)?t.push(`[OK] Hook script: PASS \u2014 ${d}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${d}`)}}else t.push("[WARN] Hooks: adapter detection unavailable");return t.push(`[OK] Version: v${Wn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
1392
+ `)}]})});Te.registerTool("ctx_upgrade",{title:"Upgrade Plugin",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},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="",e,n;try{let c=Te.server.getClientVersion(),u=$t(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=tu(u.platform)&&ko.javascript?{platform:u.platform,jsRuntime:ko.javascript}:void 0}catch{try{n=$t().platform}catch{}}let r=IP(n),o=gt(r,"cli.bundle.mjs"),s=gt(r,"build","cli.js");try{let c=He(),u=Ot(As(c),"insight-cache");Me(u)&&(lB(4747),PP(u,{recursive:!0,force:!0}))}catch{}let i;if(Me(o))i=`${zi(o,e)} upgrade${t}`;else if(Me(s))i=`${zi(s,e)} upgrade${t}`;else{let u=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync,readFileSync,writeFileSync,lstatSync}from"node:fs";','import{join,resolve,sep}from"node:path";','import{tmpdir}from"node:os";',`const P=${JSON.stringify(r)};`,'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/mxalbert1996/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"];',"const PW=resolve(P)+sep;const TW=resolve(T)+sep;","const noSymlink=(src)=>{try{return !lstatSync(src).isSymbolicLink()}catch{return false}};","for(const item of items){const from=resolve(T,item);const to=resolve(P,item);if(!(to+sep).startsWith(PW))continue;if(!(from+sep).startsWith(TW))continue;if(!noSymlink(from))continue;if(existsSync(from)){rmSync(to,{recursive:true,force:true});cpSync(from,to,{recursive:true,force:true,filter:noSymlink});}}",'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(`
1393
1393
  `),l=gt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=zi(l,e)}let a=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",i,"```","","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(`
1394
1394
  `);return W("ctx_upgrade",{content:[{type:"text",text:a}]})});Te.registerTool("ctx_purge",{title:"Purge Knowledge Base",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},description:`DESTRUCTIVE: permanently delete indexed content. Cannot be undone. Requires confirm:true and exactly one scope.
1395
1395
 
@@ -1415,7 +1415,7 @@ RETURNS:
1415
1415
  A summary of removed rows + the resolved scope.
1416
1416
 
1417
1417
  EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
1418
- EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(ly,$.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:n})=>{if(e&&n==="project")return W("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 W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!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=ma()}catch{}if(fn){try{fn.cleanup()}catch{}fn=null}let s=o?Eo(o):void 0,{deleted:i}=FT({projectDir:Ot(),sessionsDir:ze(),storePath:o,contentDir:s,legacyContentDir:yt(As(),".context-mode","content"),contentHash:Fn(Ot()),scope:r,sessionId:e});if(r==="project"){ne.calls={},ne.bytesReturned={},ne.bytesIndexed=0,ne.bytesSandboxed=0,ne.cacheHits=0,ne.cacheBytesSaved=0,ne.sessionStart=Date.now(),i.push("session stats");try{let c=AP();He(c)&&Is(c)}catch{}}let a=r==="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 W("ctx_purge",{content:[{type:"text",text:a}]})});var pa=5e3;function aB(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 cB(t,e=process.platform,n=al){let r=aB(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:pa});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 uB(t,e=process.platform,n=al){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:pa});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;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){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:pa});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:pa});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:pa});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}var Xg="https://context-mode.com/insight";Te.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:$.object({})},async()=>{let t=cB(Xg),e=t.ok?`Opening Insight in your browser: ${Xg}`:`Could not auto-open your browser (${t.reason}).
1419
- Open Insight manually: ${Xg}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function lB(){let t=mh();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?oy():"/tmp",n=yt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{ga.cleanupBackgrounded(),fn&&fn.close();try{Is(pl)}catch{}try{Is(n)}catch{}r&&clearInterval(r)},s=async()=>{try{ey=0,cl()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),HT({onShutdown:()=>s()});let i=new eu;await Te.connect(i),zT(i);try{il(n,String(process.pid))}catch{}r=setInterval(()=>{try{il(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(ws(),Ig)),u=Te.server.getClientVersion(),l=a(u??void 0);mn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=KT(fa());if(a){for(let[c,u]of Object.entries(a.calls))ne.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ne.bytesReturned[c]=u;a.sessionStart>0&&(ne.sessionStart=a.sessionStart)}}catch{}gP().then(a=>{a!=="unknown"&&(Gn=a)}),setInterval(()=>{gP().then(a=>{a!=="unknown"&&(Gn=a)})},3600*1e3).unref(),setInterval(()=>cl(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Kn} running on stdio`),console.error(`Detected runtimes:
1420
- ${$v(vo)}`),su()||(console.error(`
1421
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}fF();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&lB().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{BF as AGY_DEFAULT_EXEC_TIMEOUT_MS,oF as REGISTERED_CTX_TOOLS,A5 as __resetSuppressionDiagnosticForTests,aB as browserOpenArgv,FF as buildBatchNodeOptionsPrefix,YF as buildFetchCode,ry as classifyExtraction,dl as classifyIp,Er as currentAttribution,nl as describeRung,uF as emitSuppressionDiagnostic,DP as extractSnippet,zF as formatBatchQueryResults,Ot as getProjectDir,fF as installStrictClientSchemaCompat,uB as killProcessOnPort,cB as openBrowserSync,oB as parseLadderTried,LF as positionsFromHighlight,lF as registerEmptyToolsListHandler,ay as resolveExecTimeout,mF as resolveSessionIdFromSessionDB,qF as runBatchCommands,Qg as sanitizeSchemaForStrictClients,Te as server,sF as shouldSuppressMcpToolsForNativePluginHost,N5 as withProjectDirOverride};
1418
+ EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(uy,$.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:n})=>{if(e&&n==="project")return W("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 W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let r=n??(e?"session":"project");!n&&!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=pl()}catch{}if(o){let c=Is.get(o);if(c){try{c.cleanup()}catch{}Is.delete(o)}}let s=o?As(o):void 0,{deleted:i}=BT({projectDir:yt(),sessionsDir:He(),storePath:o,contentDir:s,legacyContentDir:Ot(Os(),".context-mode","content"),contentHash:Un(yt()),scope:r,sessionId:e});if(r==="project"){ne.calls={},ne.bytesReturned={},ne.bytesIndexed=0,ne.bytesSandboxed=0,ne.cacheHits=0,ne.cacheBytesSaved=0,ne.sessionStart=Date.now(),i.push("session stats");try{let c=NP();Me(c)&&$s(c)}catch{}}let a=r==="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 W("ctx_purge",{content:[{type:"text",text:a}]})});var pa=5e3;function cB(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 uB(t,e=process.platform,n=il){let r=cB(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:pa});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 lB(t,e=process.platform,n=il){let r={killedPids:[],attemptedPids:[],errors:[]};if(!Number.isInteger(t)||t<1||t>65535)return r.errors.push(`invalid port: ${t}`),r;try{if(e==="win32"){let o=n("netstat",["-ano"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:pa});if(o.error)return r.errors.push(`netstat: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;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){r.attemptedPids.push(a);try{let c=n("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:pa});c.error||c.status!==0?r.errors.push(`taskkill ${a}: ${c.error?.message??`status=${c.status}`}`):r.killedPids.push(a)}catch(c){r.errors.push(`taskkill ${a}: ${c instanceof Error?c.message:String(c)}`)}}}else{let o=n("lsof",["-ti",`:${t}`],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:pa});if(o.error)return r.errors.push(`lsof: ${o.error.message}`),r;if(o.status!==0||typeof o.stdout!="string")return r;let s=o.stdout.split(/\r?\n/).filter(i=>/^\d+$/.test(i));for(let i of s){r.attemptedPids.push(i);try{let a=n("kill",[i],{stdio:"ignore",timeout:pa});a.error||a.status!==0?r.errors.push(`kill ${i}: ${a.error?.message??`status=${a.status}`}`):r.killedPids.push(i)}catch(a){r.errors.push(`kill ${i}: ${a instanceof Error?a.message:String(a)}`)}}}}catch(o){r.errors.push(o instanceof Error?o.message:String(o))}return r}var Jg="https://context-mode.com/insight";Te.registerTool("ctx_insight",{title:"Open Insight Dashboard",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},description:"Opens the context-mode Insight dashboard (https://context-mode.com/insight) in your default browser \u2014 a dashboard launcher for the hosted analytics layer, not a Q&A engine. Insight surfaces per-engineer productive rate, retry waste, blocker detection, and role-narrowed views for CTO, EM, IC, CISO, FinOps, and DevOps. For natural-language queries over your indexed content, use ctx_search.",inputSchema:$.object({})},async()=>{let t=uB(Jg),e=t.ok?`Opening Insight in your browser: ${Jg}`:`Could not auto-open your browser (${t.reason}).
1419
+ Open Insight manually: ${Jg}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function dB(){let t=fh();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?ry():"/tmp",n=Ot(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{ha.cleanupBackgrounded();for(let a of Is.values())try{a.close()}catch{}Is.clear();try{$s(dl)}catch{}try{$s(n)}catch{}r&&clearInterval(r)},s=async()=>{try{Qg=0,al()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),UT({onShutdown:()=>s()});let i=new Qc;await Te.connect(i),HT(i);try{sl(n,String(process.pid))}catch{}r=setInterval(()=>{try{sl(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(vs(),Og)),u=Te.server.getClientVersion(),l=a(u??void 0);fn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=GT(fa());if(a){for(let[c,u]of Object.entries(a.calls))ne.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))ne.bytesReturned[c]=u;a.sessionStart>0&&(ne.sessionStart=a.sessionStart)}}catch{}_P().then(a=>{a!=="unknown"&&(Kn=a)}),setInterval(()=>{_P().then(a=>{a!=="unknown"&&(Kn=a)})},3600*1e3).unref(),setInterval(()=>al(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Wn} running on stdio`),console.error(`Detected runtimes:
1420
+ ${Cv(ko)}`),ou()||(console.error(`
1421
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}mF();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&dB().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{ZF as AGY_DEFAULT_EXEC_TIMEOUT_MS,sF as REGISTERED_CTX_TOOLS,N5 as __resetSuppressionDiagnosticForTests,cB as browserOpenArgv,BF as buildBatchNodeOptionsPrefix,QF as buildFetchCode,ny as classifyExtraction,ll as classifyIp,vr as currentAttribution,tl as describeRung,lF as emitSuppressionDiagnostic,MP as extractSnippet,HF as formatBatchQueryResults,yt as getProjectDir,mF as installStrictClientSchemaCompat,lB as killProcessOnPort,uB as openBrowserSync,sB as parseLadderTried,zF as positionsFromHighlight,dF as registerEmptyToolsListHandler,iy as resolveExecTimeout,hF as resolveSessionIdFromSessionDB,VF as runBatchCommands,Yg as sanitizeSchemaForStrictClients,Te as server,iF as shouldSuppressMcpToolsForNativePluginHost,D5 as withProjectDirOverride};