Files
Mert Koseoglu e31360dc86 docs(tool): stop telling callers SPA pages cannot be fetched
The WHEN NOT block said 'the page is SPA-rendered — this is a plain HTTP fetch,
no headless browser', which now reads as an instruction to give up on exactly
the pages the ladder recovers. It is replaced with the measurement (4 of 36
pages had the article absent from the HTTP response; 4 of 4 recovered without
JavaScript) and with the ladder itself, so the caller can read which rung
answered rather than guess.

WHEN NOT now names the case that really has no answer: an application rather
than a document — a whiteboard, a diagram editor — where there is no article to
fetch and the refusal says so.
2026-08-12 23:39:30 +03:00

1420 lines
678 KiB
JavaScript
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
var rR=Object.create;var nl=Object.defineProperty;var oR=Object.getOwnPropertyDescriptor;var sR=Object.getOwnPropertyNames;var iR=Object.getPrototypeOf,aR=Object.prototype.hasOwnProperty;var X=(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)nl(t,n,{get:e[n],enumerable:!0})},cR=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of sR(e))!aR.call(t,o)&&o!==n&&nl(t,o,{get:()=>e[o],enumerable:!(r=oR(e,o))||r.enumerable});return t};var Xg=(t,e,n)=>(n=t!=null?rR(iR(t)):{},cR(e||!t||!t.__esModule?nl(n,"default",{value:t,enumerable:!0}):n,t));var ni=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 ei=class{};pe._CodeOrName=ei;pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Br=class extends ei{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=Br;var jt=class extends ei{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 Br&&(n[r.str]=(n[r.str]||0)+1),n),{})}};pe._Code=jt;pe.nil=new jt("");function Wb(t,...e){let n=[t[0]],r=0;for(;r<e.length;)Lp(n,e[r]),n.push(t[++r]);return new jt(n)}pe._=Wb;var jp=new jt("+");function Kb(t,...e){let n=[ti(t[0])],r=0;for(;r<e.length;)n.push(jp),Lp(n,e[r]),n.push(jp,ti(t[++r]));return sO(n),new jt(n)}pe.str=Kb;function Lp(t,e){e instanceof jt?t.push(...e._items):e instanceof Br?t.push(e):t.push(cO(e))}pe.addCodeArg=Lp;function sO(t){let e=1;for(;e<t.length-1;){if(t[e]===jp){let n=iO(t[e-1],t[e+1]);if(n!==void 0){t.splice(e-1,3,n);continue}t[e++]="+"}e++}}function iO(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Br||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 Br))return`"${t}${e.slice(1)}`}function aO(t,e){return e.emptyStr()?t:t.emptyStr()?e:Kb`${t}${e}`}pe.strConcat=aO;function cO(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ti(Array.isArray(t)?t.join(","):t)}function uO(t){return new jt(ti(t))}pe.stringify=uO;function ti(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}pe.safeStringify=ti;function lO(t){return typeof t=="string"&&pe.IDENTIFIER.test(t)?new jt(`.${t}`):Wb`[${t}]`}pe.getProperty=lO;function dO(t){if(typeof t=="string"&&pe.IDENTIFIER.test(t))return new jt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}pe.getEsmExportName=dO;function pO(t){return new jt(t.toString())}pe.regexpCode=pO});var Up=I(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ValueScope=xt.ValueScopeName=xt.Scope=xt.varKinds=xt.UsedValueState=void 0;var bt=ni(),zp=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},nc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(nc||(xt.UsedValueState=nc={}));xt.varKinds={const:new bt.Name("const"),let:new bt.Name("let"),var:new bt.Name("var")};var rc=class{constructor({prefixes:e,parent:n}={}){this._names={},this._prefixes=e,this._parent=n}toName(e){return e instanceof bt.Name?e:this.name(e)}name(e){return new bt.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}}};xt.Scope=rc;var oc=class extends bt.Name{constructor(e,n){super(n),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,bt._)`.${new bt.Name(n)}[${r}]`}};xt.ValueScopeName=oc;var fO=(0,bt._)`\n`,Hp=class extends rc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?fO:bt.nil}}get(){return this._scope}name(e){return new oc(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,bt._)`${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=bt.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,nc.Started);let l=n(u);if(l){let d=this.opts.es5?xt.varKinds.var:xt.varKinds.const;s=(0,bt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,bt._)`${s}${l}${this.opts._n}`;else throw new zp(u);c.set(u,nc.Completed)})}return s}};xt.ValueScope=Hp});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=ni(),Qt=Up(),nr=ni();Object.defineProperty(te,"_",{enumerable:!0,get:function(){return nr._}});Object.defineProperty(te,"str",{enumerable:!0,get:function(){return nr.str}});Object.defineProperty(te,"strConcat",{enumerable:!0,get:function(){return nr.strConcat}});Object.defineProperty(te,"nil",{enumerable:!0,get:function(){return nr.nil}});Object.defineProperty(te,"getProperty",{enumerable:!0,get:function(){return nr.getProperty}});Object.defineProperty(te,"stringify",{enumerable:!0,get:function(){return nr.stringify}});Object.defineProperty(te,"regexpCode",{enumerable:!0,get:function(){return nr.regexpCode}});Object.defineProperty(te,"Name",{enumerable:!0,get:function(){return nr.Name}});var cc=Up();Object.defineProperty(te,"Scope",{enumerable:!0,get:function(){return cc.Scope}});Object.defineProperty(te,"ValueScope",{enumerable:!0,get:function(){return cc.ValueScope}});Object.defineProperty(te,"ValueScopeName",{enumerable:!0,get:function(){return cc.ValueScopeName}});Object.defineProperty(te,"varKinds",{enumerable:!0,get:function(){return cc.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 In=class{optimizeNodes(){return this}optimizeNames(e,n){return this}},Fp=class extends In{constructor(e,n,r){super(),this.varKind=e,this.name=n,this.rhs=r}render({es5:e,_n:n}){let r=e?Qt.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=Ho(this.rhs,e,n)),this}get names(){return this.rhs instanceof ue._CodeOrName?this.rhs.names:{}}},sc=class extends In{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=Ho(this.rhs,e,n),this}get names(){let e=this.lhs instanceof ue.Name?{}:{...this.lhs.names};return ac(e,this.rhs)}},Zp=class extends sc{constructor(e,n,r,o){super(e,r,o),this.op=n}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Bp=class extends In{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},qp=class extends In{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Vp=class extends In{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Wp=class extends In{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=Ho(this.code,e,n),this}get names(){return this.code instanceof ue._CodeOrName?this.code.names:{}}},ri=class extends In{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)||(mO(e,s.names),r.splice(o,1))}return r.length>0?this:void 0}get names(){return this.nodes.reduce((e,n)=>Wr(e,n.names),{})}},An=class extends ri{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Kp=class extends ri{},zo=class extends An{};zo.kind="else";var qr=class t extends An{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(Gb(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=Ho(this.condition,e,n),this}get names(){let e=super.names;return ac(e,this.condition),this.else&&Wr(e,this.else.names),e}};qr.kind="if";var Vr=class extends An{};Vr.kind="for";var Gp=class extends Vr{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=Ho(this.iteration,e,n),this}get names(){return Wr(super.names,this.iteration.names)}},Jp=class extends Vr{constructor(e,n,r,o){super(),this.varKind=e,this.name=n,this.from=r,this.to=o}render(e){let n=e.es5?Qt.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=ac(super.names,this.from);return ac(e,this.to)}},ic=class extends Vr{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=Ho(this.iterable,e,n),this}get names(){return Wr(super.names,this.iterable.names)}},oi=class extends An{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)}};oi.kind="func";var si=class extends ri{render(e){return"return "+super.render(e)}};si.kind="return";var Xp=class extends An{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&&Wr(e,this.catch.names),this.finally&&Wr(e,this.finally.names),e}},ii=class extends An{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ii.kind="catch";var ai=class extends An{render(e){return"finally"+super.render(e)}};ai.kind="finally";var Yp=class{constructor(e,n={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...n,_n:n.lines?`
`:""},this._extScope=e,this._scope=new Qt.Scope({parent:e}),this._nodes=[new Kp]}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 Fp(e,s,r)),s}const(e,n,r){return this._def(Qt.varKinds.const,e,n,r)}let(e,n,r){return this._def(Qt.varKinds.let,e,n,r)}var(e,n,r){return this._def(Qt.varKinds.var,e,n,r)}assign(e,n,r){return this._leafNode(new sc(e,n,r))}add(e,n){return this._leafNode(new Zp(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ue.nil&&this._leafNode(new Wp(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 qr(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 qr(e))}else(){return this._elseNode(new zo)}endIf(){return this._endBlockNode(qr,zo)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Gp(e),n)}forRange(e,n,r,o,s=this.opts.es5?Qt.varKinds.var:Qt.varKinds.let){let i=this._scope.toName(e);return this._for(new Jp(s,i,n,r),()=>o(i))}forOf(e,n,r,o=Qt.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 ic("of",o,s,n),()=>r(s))}forIn(e,n,r,o=this.opts.es5?Qt.varKinds.var:Qt.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 ic("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Vr)}label(e){return this._leafNode(new Bp(e))}break(e){return this._leafNode(new qp(e))}return(e){let n=new si;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(si)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Xp;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new ii(s),n(s)}return r&&(this._currNode=o.finally=new ai,this.code(r)),this._endBlockNode(ii,ai)}throw(e){return this._leafNode(new Vp(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 oi(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(oi)}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 qr))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=Yp;function Wr(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function ac(t,e){return e instanceof ue._CodeOrName?Wr(t,e.names):t}function Ho(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 mO(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Gb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ue._)`!${Qp(t)}`}te.not=Gb;var hO=Jb(te.operators.AND);function gO(...t){return t.reduce(hO)}te.and=gO;var yO=Jb(te.operators.OR);function _O(...t){return t.reduce(yO)}te.or=_O;function Jb(t){return(e,n)=>e===ue.nil?n:n===ue.nil?e:(0,ue._)`${Qp(e)} ${t} ${Qp(n)}`}function Qp(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 be=ee(),bO=ni();function xO(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=xO;function kO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Qb(t,e),!ex(e,t.self.RULES.all))}re.alwaysValidSchema=kO;function Qb(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]||rx(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=Qb;function ex(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=ex;function SO(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=SO;function vO({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,be._)`${n}`}return(0,be._)`${t}${e}${(0,be.getProperty)(r)}`}re.schemaRefOrVal=vO;function EO(t){return tx(decodeURIComponent(t))}re.unescapeFragment=EO;function wO(t){return encodeURIComponent(tf(t))}re.escapeFragment=wO;function tf(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=tf;function tx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=tx;function TO(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=TO;function Xb({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof be.Name?(s instanceof be.Name?t(o,s,i):e(o,s,i),i):s instanceof be.Name?(e(o,i,s),s):n(s,i);return a===be.Name&&!(c instanceof be.Name)?r(o,c):c}}re.mergeEvaluated={props:Xb({mergeNames:(t,e,n)=>t.if((0,be._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,be._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,be._)`${n} || {}`).code((0,be._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,be._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,be._)`${n} || {}`),nf(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:nx}),items:Xb({mergeNames:(t,e,n)=>t.if((0,be._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,be._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,be._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,be._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function nx(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,be._)`{}`);return e!==void 0&&nf(t,n,e),n}re.evaluatedPropsToName=nx;function nf(t,e,n){Object.keys(n).forEach(r=>t.assign((0,be._)`${e}${(0,be.getProperty)(r)}`,!0))}re.setEvaluated=nf;var Yb={};function RO(t,e){return t.scopeValue("func",{ref:e,code:Yb[e.code]||(Yb[e.code]=new bO._Code(e.code))})}re.useFunc=RO;var ef;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ef||(re.Type=ef={}));function PO(t,e,n){if(t instanceof be.Name){let r=e===ef.Num;return n?r?(0,be._)`"[" + ${t} + "]"`:(0,be._)`"['" + ${t} + "']"`:r?(0,be._)`"/" + ${t}`:(0,be._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,be.getProperty)(t).toString():"/"+tf(t)}re.getErrorPath=PO;function rx(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=rx});var Nn=I(rf=>{"use strict";Object.defineProperty(rf,"__esModule",{value:!0});var rt=ee(),CO={data:new rt.Name("data"),valCxt:new rt.Name("valCxt"),instancePath:new rt.Name("instancePath"),parentData:new rt.Name("parentData"),parentDataProperty:new rt.Name("parentDataProperty"),rootData:new rt.Name("rootData"),dynamicAnchors:new rt.Name("dynamicAnchors"),vErrors:new rt.Name("vErrors"),errors:new rt.Name("errors"),this:new rt.Name("this"),self:new rt.Name("self"),scope:new rt.Name("scope"),json:new rt.Name("json"),jsonPos:new rt.Name("jsonPos"),jsonLen:new rt.Name("jsonLen"),jsonPart:new rt.Name("jsonPart")};rf.default=CO});var ci=I(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.extendErrors=ot.resetErrorsCount=ot.reportExtraError=ot.reportError=ot.keyword$DataError=ot.keywordError=void 0;var de=ee(),uc=le(),ut=Nn();ot.keywordError={message:({keyword:t})=>(0,de.str)`must pass "${t}" keyword validation`};ot.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 $O(t,e=ot.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=ix(t,e,n);r??(i||a)?ox(s,c):sx(o,(0,de._)`[${c}]`)}ot.reportError=$O;function OO(t,e=ot.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=ix(t,e,n);ox(o,a),s||i||sx(r,ut.default.vErrors)}ot.reportExtraError=OO;function IO(t,e){t.assign(ut.default.errors,e),t.if((0,de._)`${ut.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,de._)`${ut.default.vErrors}.length`,e),()=>t.assign(ut.default.vErrors,null)))}ot.resetErrorsCount=IO;function AO({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,ut.default.errors,a=>{t.const(i,(0,de._)`${ut.default.vErrors}[${a}]`),t.if((0,de._)`${i}.instancePath === undefined`,()=>t.assign((0,de._)`${i}.instancePath`,(0,de.strConcat)(ut.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))})}ot.extendErrors=AO;function ox(t,e){let n=t.const("err",e);t.if((0,de._)`${ut.default.vErrors} === null`,()=>t.assign(ut.default.vErrors,(0,de._)`[${n}]`),(0,de._)`${ut.default.vErrors}.push(${n})`),t.code((0,de._)`${ut.default.errors}++`)}function sx(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 Kr={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 ix(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,de._)`{}`:NO(t,e,n)}function NO(t,e,n={}){let{gen:r,it:o}=t,s=[MO(o,n),DO(t,n)];return jO(t,e,s),r.object(...s)}function MO({errorPath:t},{instancePath:e}){let n=e?(0,de.str)`${t}${(0,uc.getErrorPath)(e,uc.Type.Str)}`:t;return[ut.default.instancePath,(0,de.strConcat)(ut.default.instancePath,n)]}function DO({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,uc.getErrorPath)(n,uc.Type.Str)}`),[Kr.schemaPath,o]}function jO(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([Kr.keyword,o],[Kr.params,typeof e=="function"?e(t):e||(0,de._)`{}`]),c.messages&&r.push([Kr.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Kr.schema,i],[Kr.parentSchema,(0,de._)`${l}${d}`],[ut.default.data,s]),u&&r.push([Kr.propertyName,u])}});var cx=I(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.boolOrEmptySchema=Uo.topBoolOrEmptySchema=void 0;var LO=ci(),zO=ee(),HO=Nn(),UO={message:"boolean schema is false"};function FO(t){let{gen:e,schema:n,validateName:r}=t;n===!1?ax(t,!1):typeof n=="object"&&n.$async===!0?e.return(HO.default.data):(e.assign((0,zO._)`${r}.errors`,null),e.return(!0))}Uo.topBoolOrEmptySchema=FO;function ZO(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),ax(t)):n.var(e,!0)}Uo.boolOrEmptySchema=ZO;function ax(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,LO.reportError)(o,UO,void 0,e)}});var of=I(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.getRules=Fo.isJSONType=void 0;var BO=["string","number","integer","boolean","null","object","array"],qO=new Set(BO);function VO(t){return typeof t=="string"&&qO.has(t)}Fo.isJSONType=VO;function WO(){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:{}}}Fo.getRules=WO});var sf=I(rr=>{"use strict";Object.defineProperty(rr,"__esModule",{value:!0});rr.shouldUseRule=rr.shouldUseGroup=rr.schemaHasRulesForType=void 0;function KO({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&ux(t,r)}rr.schemaHasRulesForType=KO;function ux(t,e){return e.rules.some(n=>lx(t,n))}rr.shouldUseGroup=ux;function lx(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))}rr.shouldUseRule=lx});var ui=I(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.reportTypeError=st.checkDataTypes=st.checkDataType=st.coerceAndCheckDataType=st.getJSONTypes=st.getSchemaTypes=st.DataType=void 0;var GO=of(),JO=sf(),XO=ci(),Y=ee(),dx=le(),Zo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Zo||(st.DataType=Zo={}));function YO(t){let e=px(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}st.getSchemaTypes=YO;function px(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(GO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}st.getJSONTypes=px;function QO(t,e){let{gen:n,data:r,opts:o}=t,s=eI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,JO.schemaHasRulesForType)(t,e[0]));if(i){let a=cf(e,r,o.strictNumbers,Zo.Wrong);n.if(a,()=>{s.length?tI(t,e,s):uf(t)})}return i}st.coerceAndCheckDataType=QO;var fx=new Set(["string","number","integer","boolean","null"]);function eI(t,e){return e?t.filter(n=>fx.has(n)||e==="array"&&n==="array"):[]}function tI(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(cf(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,Y._)`${a} !== undefined`);for(let u of n)(fx.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),uf(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(o,a),nI(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
|| (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":r.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
|| (${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"
|| ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function nI({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function af(t,e,n,r=Zo.Correct){let o=r===Zo.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===Zo.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)}}st.checkDataType=af;function cf(t,e,n,r){if(t.length===1)return af(t[0],e,n,r);let o,s=(0,dx.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,af(i,e,n,r));return o}st.checkDataTypes=cf;var rI={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function uf(t){let e=oI(t);(0,XO.reportError)(e,rI)}st.reportTypeError=uf;function oI(t){let{gen:e,data:n,schema:r}=t,o=(0,dx.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var hx=I(lc=>{"use strict";Object.defineProperty(lc,"__esModule",{value:!0});lc.assignDefaults=void 0;var Bo=ee(),sI=le();function iI(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)mx(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>mx(t,s,o.default))}lc.assignDefaults=iI;function mx(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Bo._)`${s}${(0,Bo.getProperty)(e)}`;if(o){(0,sI.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Bo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Bo._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Bo._)`${a} = ${(0,Bo.stringify)(n)}`)}});var Lt=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(),lf=le(),or=Nn(),aI=le();function cI(t,e){let{gen:n,data:r,it:o}=t;n.if(pf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ee._)`${e}`},!0),t.error()})}ge.checkReportMissingProp=cI;function uI({gen:t,data:e,it:{opts:n}},r,o){return(0,Ee.or)(...r.map(s=>(0,Ee.and)(pf(t,e,s,n.ownProperties),(0,Ee._)`${o} = ${s}`)))}ge.checkMissingProp=uI;function lI(t,e){t.setParams({missingProperty:e},!0),t.error()}ge.reportMissingProp=lI;function gx(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ee._)`Object.prototype.hasOwnProperty`})}ge.hasPropFunc=gx;function df(t,e,n){return(0,Ee._)`${gx(t)}.call(${e}, ${n})`}ge.isOwnProperty=df;function dI(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} !== undefined`;return r?(0,Ee._)`${o} && ${df(t,e,n)}`:o}ge.propertyInData=dI;function pf(t,e,n,r){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(n)} === undefined`;return r?(0,Ee.or)(o,(0,Ee.not)(df(t,e,n))):o}ge.noPropertyInData=pf;function yx(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ge.allSchemaProperties=yx;function pI(t,e){return yx(e).filter(n=>!(0,lf.alwaysValidSchema)(t,e[n]))}ge.schemaProperties=pI;function fI({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=[[or.default.instancePath,(0,Ee.strConcat)(or.default.instancePath,s)],[or.default.parentData,i.parentData],[or.default.parentDataProperty,i.parentDataProperty],[or.default.rootData,or.default.rootData]];i.opts.dynamicRef&&d.push([or.default.dynamicAnchors,or.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=fI;var mI=(0,Ee._)`new RegExp`;function hI({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"?mI:(0,aI.useFunc)(t,o)}(${n}, ${r})`})}ge.usePattern=hI;function gI(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:lf.Type.Num},s),e.if((0,Ee.not)(s),a)})}}ge.validateArray=gI;function yI(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,lf.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=yI});var xx=I(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.validateKeywordUsage=mn.validSchemaType=mn.funcKeywordCode=mn.macroKeywordCode=void 0;var lt=ee(),Gr=Nn(),_I=Lt(),bI=ci();function xI(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=bx(n,r,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=n.name("valid");t.subschema({schema:a,schemaPath:lt.nil,errSchemaPath:`${i.errSchemaPath}/${r}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}mn.macroKeywordCode=xI;function kI(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;vI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=bx(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&&_x(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&_x(t),g(()=>SI(t,y))}}function m(){let y=r.let("ruleErrs",null);return r.try(()=>h((0,lt._)`await `),_=>r.assign(d,!1).if((0,lt._)`${_} instanceof ${c.ValidationError}`,()=>r.assign(y,(0,lt._)`${_}.errors`),()=>r.throw(_))),y}function p(){let y=(0,lt._)`${l}.errors`;return r.assign(y,null),h(lt.nil),y}function h(y=e.async?(0,lt._)`await `:lt.nil){let _=c.opts.passContext?Gr.default.this:Gr.default.self,b=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,lt._)`${y}${(0,_I.callValidateCode)(t,l,_,b)}`,e.modifying)}function g(y){var _;r.if((0,lt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}mn.funcKeywordCode=kI;function _x(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,lt._)`${r.parentData}[${r.parentDataProperty}]`))}function SI(t,e){let{gen:n}=t;n.if((0,lt._)`Array.isArray(${e})`,()=>{n.assign(Gr.default.vErrors,(0,lt._)`${Gr.default.vErrors} === null ? ${e} : ${Gr.default.vErrors}.concat(${e})`).assign(Gr.default.errors,(0,lt._)`${Gr.default.vErrors}.length`),(0,bI.extendErrors)(t)},()=>t.error())}function vI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function bx(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,lt.stringify)(n)})}function EI(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")}mn.validSchemaType=EI;function wI({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)}}mn.validateKeywordUsage=wI});var Sx=I(sr=>{"use strict";Object.defineProperty(sr,"__esModule",{value:!0});sr.extendSubschemaMode=sr.extendSubschemaData=sr.getSubschema=void 0;var hn=ee(),kx=le();function TI(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,hn._)`${t.schemaPath}${(0,hn.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[n],schemaPath:(0,hn._)`${t.schemaPath}${(0,hn.getProperty)(e)}${(0,hn.getProperty)(n)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,kx.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')}sr.getSubschema=TI;function RI(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,hn._)`${e.data}${(0,hn.getProperty)(n)}`,!0);c(f),t.errorPath=(0,hn.str)`${u}${(0,kx.getErrorPath)(n,r,d.jsPropertySyntax)}`,t.parentDataProperty=(0,hn._)`${n}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof hn.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]}}sr.extendSubschemaData=RI;function PI(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}sr.extendSubschemaMode=PI});var ff=I((p4,vx)=>{"use strict";vx.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 wx=I((f4,Ex)=>{"use strict";var ir=Ex.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(){};dc(e,r,o,t,"",t)};ir.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};ir.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};ir.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};ir.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 dc(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 ir.arrayKeywords)for(var f=0;f<d.length;f++)dc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in ir.propsKeywords){if(d&&typeof d=="object")for(var m in d)dc(t,e,n,d[m],o+"/"+l+"/"+CI(m),s,o,l,r,m)}else(l in ir.keywords||t.allKeys&&!(l in ir.skipKeywords))&&dc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function CI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var li=I(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.getSchemaRefs=kt.resolveUrl=kt.normalizeId=kt._getFullPath=kt.getFullPath=kt.inlineRef=void 0;var $I=le(),OI=ff(),II=wx(),AI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function NI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!mf(t):e?Tx(t)<=e:!1}kt.inlineRef=NI;var MI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function mf(t){for(let e in t){if(MI.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(mf)||typeof n=="object"&&mf(n))return!0}return!1}function Tx(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!AI.has(n)&&(typeof t[n]=="object"&&(0,$I.eachItem)(t[n],r=>e+=Tx(r)),e===1/0))return 1/0}return e}function Rx(t,e="",n){n!==!1&&(e=qo(e));let r=t.parse(e);return Px(t,r)}kt.getFullPath=Rx;function Px(t,e){return t.serialize(e).split("#")[0]+"#"}kt._getFullPath=Px;var DI=/#\/?$/;function qo(t){return t?t.replace(DI,""):""}kt.normalizeId=qo;function jI(t,e,n){return n=qo(n),t.resolve(e,n)}kt.resolveUrl=jI;var LI=/^[a-z_][-a-z0-9._]*$/i;function zI(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=qo(t[n]||e),s={"":o},i=Rx(r,o,!1),a={},c=new Set;return II(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(b){let k=this.opts.uriResolver.resolve;if(b=qo(g?k(g,b):b),c.has(b))throw l(b);c.add(b);let v=this.refs[b];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,b):b!==qo(h)&&(b[0]==="#"?(u(d,a[b],b),a[b]=d):this.refs[b]=h),b}function _(b){if(typeof b=="string"){if(!LI.test(b))throw new Error(`invalid anchor "${b}"`);y.call(this,`#${b}`)}}}),a;function u(d,f,m){if(f!==void 0&&!OI(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}kt.getSchemaRefs=zI});var fi=I(ar=>{"use strict";Object.defineProperty(ar,"__esModule",{value:!0});ar.getData=ar.KeywordCxt=ar.validateFunctionCode=void 0;var Ax=cx(),Cx=ui(),gf=sf(),pc=ui(),HI=hx(),pi=xx(),hf=Sx(),F=ee(),G=Nn(),UI=li(),Mn=le(),di=ci();function FI(t){if(Dx(t)&&(jx(t),Mx(t))){qI(t);return}Nx(t,()=>(0,Ax.topBoolOrEmptySchema)(t))}ar.validateFunctionCode=FI;function Nx({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"; ${$x(n,o)}`),BI(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${ZI(o)}`,r.$async,()=>t.code($x(n,o)).code(s))}function ZI(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 BI(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 qI(t){let{schema:e,opts:n,gen:r}=t;Nx(t,()=>{n.$comment&&e.$comment&&zx(t),JI(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&VI(t),Lx(t),QI(t)})}function VI(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 $x(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 WI(t,e){if(Dx(t)&&(jx(t),Mx(t))){KI(t,e);return}(0,Ax.boolOrEmptySchema)(t,e)}function Mx({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 Dx(t){return typeof t.schema!="boolean"}function KI(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&zx(t),XI(t),YI(t);let s=r.const("_errs",G.default.errors);Lx(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function jx(t){(0,Mn.checkUnknownRules)(t),GI(t)}function Lx(t,e){if(t.opts.jtd)return Ox(t,[],!1,e);let n=(0,Cx.getSchemaTypes)(t.schema),r=(0,Cx.coerceAndCheckDataType)(t,n);Ox(t,n,!r,e)}function GI(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Mn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function JI(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Mn.checkStrictMode)(t,"default is ignored in the schema root")}function XI(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,UI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function YI(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function zx({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 QI(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&&eA(t),e.return((0,F._)`${G.default.errors} === 0`))}function eA({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 Ox(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,Mn.schemaHasRulesButRef)(s,l))){o.block(()=>Ux(t,"$ref",l.all.$ref.definition));return}c.jtd||tA(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,gf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,pc.checkDataType)(f.type,i,c.strictNumbers)),Ix(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,pc.reportTypeError)(t)),o.endIf()):Ix(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function Ix(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,HI.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,gf.shouldUseRule)(r,s)&&Ux(t,s.keyword,s.definition,e.type)})}function tA(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(nA(t,e),t.opts.allowUnionTypes||rA(t,e),oA(t,t.dataTypes))}function nA(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{Hx(t.dataTypes,n)||yf(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),iA(t,e)}}function rA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&yf(t,"use allowUnionTypes to allow union type keyword")}function oA(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,gf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>sA(e,i))&&yf(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function sA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Hx(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function iA(t,e){let n=[];for(let r of t.dataTypes)Hx(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function yf(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Mn.checkStrictMode)(t,e,t.opts.strictTypes)}var fc=class{constructor(e,n,r){if((0,pi.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,Mn.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",Fx(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,pi.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?di.reportExtraError:di.reportError)(this,this.def.error,n)}$dataError(){(0,di.reportError)(this,this.def.$dataError||di.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,di.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,pc.checkDataTypes)(c,n,s.opts.strictNumbers,pc.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,hf.getSubschema)(this.it,e);(0,hf.extendSubschemaData)(r,this.it,e),(0,hf.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return WI(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Mn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Mn.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}};ar.KeywordCxt=fc;function Ux(t,e,n,r){let o=new fc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,pi.funcKeywordCode)(o,n):"macro"in n?(0,pi.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,pi.funcKeywordCode)(o,n)}var aA=/^\/(?:[^~]|~0|~1)*$/,cA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fx(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!aA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=cA.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,Mn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}ar.getData=Fx});var mc=I(bf=>{"use strict";Object.defineProperty(bf,"__esModule",{value:!0});var _f=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bf.default=_f});var mi=I(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var xf=li(),kf=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,xf.resolveUrl)(e,n,r),this.missingSchema=(0,xf.normalizeId)((0,xf.getFullPath)(e,this.missingRef))}};Sf.default=kf});var gc=I(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.resolveSchema=zt.getCompilingSchema=zt.resolveRef=zt.compileSchema=zt.SchemaEnv=void 0;var en=ee(),uA=mc(),Jr=Nn(),tn=li(),Zx=le(),lA=fi(),Vo=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,tn.normalizeId)(r?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=r?.$async,this.refs={}}};zt.SchemaEnv=Vo;function Ef(t){let e=Bx.call(this,t);if(e)return e;let n=(0,tn.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:r,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new en.CodeGen(this.scope,{es5:r,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:uA.default,code:(0,en._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Jr.default.data,parentData:Jr.default.parentData,parentDataProperty:Jr.default.parentDataProperty,dataNames:[Jr.default.data],dataPathArr:[en.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,en.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:n,baseId:t.baseId||n,schemaPath:en.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,en._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,lA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Jr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Jr.default.self}`,`${Jr.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 en.Name?void 0:p,items:h instanceof en.Name?void 0:h,dynamicProps:p instanceof en.Name,dynamicItems:h instanceof en.Name},m.source&&(m.source.evaluated=(0,en.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)}}zt.compileSchema=Ef;function dA(t,e,n){var r;n=(0,tn.resolveUrl)(this.opts.uriResolver,e,n);let o=t.refs[n];if(o)return o;let s=mA.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 Vo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=pA.call(this,s)}zt.resolveRef=dA;function pA(t){return(0,tn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ef.call(this,t)}function Bx(t){for(let e of this._compilations)if(fA(e,t))return e}zt.getCompilingSchema=Bx;function fA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function mA(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||hc.call(this,t,e)}function hc(t,e){let n=this.opts.uriResolver.parse(e),r=(0,tn._getFullPath)(this.opts.uriResolver,n),o=(0,tn.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&r===o)return vf.call(this,n,t);let s=(0,tn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=hc.call(this,t,i);return typeof a?.schema!="object"?void 0:vf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||Ef.call(this,i),s===(0,tn.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,tn.resolveUrl)(this.opts.uriResolver,o,u)),new Vo({schema:a,schemaId:c,root:t,baseId:o})}return vf.call(this,n,i)}}zt.resolveSchema=hc;var hA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function vf(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,Zx.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!hA.has(a)&&u&&(e=(0,tn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,Zx.schemaHasRulesButRef)(n,this.RULES)){let a=(0,tn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=hc.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Vo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var qx=I((b4,gA)=>{gA.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 Tf=I((x4,Gx)=>{"use strict";var yA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Wx=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function wf(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 _A=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Vx(t){return t.length=0,!0}function bA(t,e,n){if(t.length){let r=wf(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function xA(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=bA;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,r,n))break;if(++e>7){n.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),r.push(":");continue}else if(u==="%"){if(!a(o,r,n))break;a=Vx}else{o.push(u);continue}}return o.length&&(a===Vx?n.zone=o.join(""):i?r.push(o.join("")):r.push(wf(o))),n.address=r.join(""),n}function Kx(t){if(kA(t,":")<2)return{host:t,isIPV6:!1};let e=xA(t);if(e.error)return{host:t,isIPV6:!1};{let n=e.address,r=e.address;return e.zone&&(n+="%"+e.zone,r+="%25"+e.zone),{host:n,isIPV6:!0,escapedHost:r}}}function kA(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function SA(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("")}function vA(t,e){let n=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=n(t.scheme)),t.userinfo!==void 0&&(t.userinfo=n(t.userinfo)),t.host!==void 0&&(t.host=n(t.host)),t.path!==void 0&&(t.path=n(t.path)),t.query!==void 0&&(t.query=n(t.query)),t.fragment!==void 0&&(t.fragment=n(t.fragment)),t}function EA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!Wx(n)){let r=Kx(n);r.isIPV6===!0?n=`[${r.escapedHost}]`:n=t.host}e.push(n)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Gx.exports={nonSimpleDomain:_A,recomposeAuthority:EA,normalizeComponentEncoding:vA,removeDotSegments:SA,isIPv4:Wx,isUUID:yA,normalizeIPv6:Kx,stringArrayToHexStripped:wf}});var ek=I((k4,Qx)=>{"use strict";var{isUUID:wA}=Tf(),TA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,RA=["http","https","ws","wss","urn","urn:uuid"];function PA(t){return RA.indexOf(t)!==-1}function Rf(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 Jx(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Xx(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 CA(t){return t.secure=Rf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function $A(t){if((t.port===(Rf(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,n]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=n,t.resourceName=void 0}return t.fragment=void 0,t}function OA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(TA);if(n){let r=e.scheme||t.scheme||"urn";t.nid=n[1].toLowerCase(),t.nss=n[2];let o=`${r}:${e.nid||t.nid}`,s=Pf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function IA(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=Pf(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 AA(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!wA(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function NA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Yx={scheme:"http",domainHost:!0,parse:Jx,serialize:Xx},MA={scheme:"https",domainHost:Yx.domainHost,parse:Jx,serialize:Xx},yc={scheme:"ws",domainHost:!0,parse:CA,serialize:$A},DA={scheme:"wss",domainHost:yc.domainHost,parse:yc.parse,serialize:yc.serialize},jA={scheme:"urn",parse:OA,serialize:IA,skipNormalize:!0},LA={scheme:"urn:uuid",parse:AA,serialize:NA,skipNormalize:!0},_c={http:Yx,https:MA,ws:yc,wss:DA,urn:jA,"urn:uuid":LA};Object.setPrototypeOf(_c,null);function Pf(t){return t&&(_c[t]||_c[t.toLowerCase()])||void 0}Qx.exports={wsIsSecure:Rf,SCHEMES:_c,isValidSchemeName:PA,getSchemeHandler:Pf}});var rk=I((S4,xc)=>{"use strict";var{normalizeIPv6:zA,removeDotSegments:hi,recomposeAuthority:HA,normalizeComponentEncoding:bc,isIPv4:UA,nonSimpleDomain:FA}=Tf(),{SCHEMES:ZA,getSchemeHandler:tk}=ek();function BA(t,e){return typeof t=="string"?t=gn(Dn(t,e),e):typeof t=="object"&&(t=Dn(gn(t,e),e)),t}function qA(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=nk(Dn(t,r),Dn(e,r),r,!0);return r.skipEscape=!0,gn(o,r)}function nk(t,e,n,r){let o={};return r||(t=Dn(gn(t,n),n),e=Dn(gn(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=hi(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=hi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=hi(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=hi(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 VA(t,e,n){return typeof t=="string"?(t=unescape(t),t=gn(bc(Dn(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=gn(bc(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=gn(bc(Dn(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=gn(bc(e,!0),{...n,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function gn(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=[],s=tk(r.scheme||n.scheme);s&&s.serialize&&s.serialize(n,r),n.path!==void 0&&(r.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split("%3A").join(":")))),r.reference!=="suffix"&&n.scheme&&o.push(n.scheme,":");let i=HA(n);if(i!==void 0&&(r.reference!=="suffix"&&o.push("//"),o.push(i),n.path&&n.path[0]!=="/"&&o.push("/")),n.path!==void 0){let a=n.path;!r.absolutePath&&(!s||!s.absolutePath)&&(a=hi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return n.query!==void 0&&o.push("?",n.query),n.fragment!==void 0&&o.push("#",n.fragment),o.join("")}var WA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Dn(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;n.reference==="suffix"&&(n.scheme?t=n.scheme+":"+t:t="//"+t);let s=t.match(WA);if(s){if(r.scheme=s[1],r.userinfo=s[3],r.host=s[4],r.port=parseInt(s[5],10),r.path=s[6]||"",r.query=s[7],r.fragment=s[8],isNaN(r.port)&&(r.port=s[5]),r.host)if(UA(r.host)===!1){let c=zA(r.host);r.host=c.host.toLowerCase(),o=c.isIPV6}else o=!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 i=tk(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&FA(r.host))try{r.host=URL.domainToASCII(r.host.toLowerCase())}catch(a){r.error=r.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(r.scheme!==void 0&&(r.scheme=unescape(r.scheme)),r.host!==void 0&&(r.host=unescape(r.host))),r.path&&(r.path=escape(unescape(r.path))),r.fragment&&(r.fragment=encodeURI(decodeURIComponent(r.fragment)))),i&&i.parse&&i.parse(r,n)}else r.error=r.error||"URI can not be parsed.";return r}var Cf={SCHEMES:ZA,normalize:BA,resolve:qA,resolveComponent:nk,equal:VA,serialize:gn,parse:Dn};xc.exports=Cf;xc.exports.default=Cf;xc.exports.fastUri=Cf});var sk=I($f=>{"use strict";Object.defineProperty($f,"__esModule",{value:!0});var ok=rk();ok.code='require("ajv/dist/runtime/uri").default';$f.default=ok});var fk=I(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.CodeGen=Xe.Name=Xe.nil=Xe.stringify=Xe.str=Xe._=Xe.KeywordCxt=void 0;var KA=fi();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return KA.KeywordCxt}});var Wo=ee();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return Wo._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return Wo.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return Wo.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return Wo.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return Wo.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return Wo.CodeGen}});var GA=mc(),lk=mi(),JA=of(),gi=gc(),XA=ee(),yi=li(),kc=ui(),If=le(),ik=qx(),YA=sk(),dk=(t,e)=>new RegExp(t,e);dk.code="new RegExp";var QA=["removeAdditional","useDefaults","coerceTypes"],eN=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),tN={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."},nN={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},ak=200;function rN(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,b,k,v,O,P,j,D;let V=t.strict,w=(e=t.code)===null||e===void 0?void 0:e.optimize,R=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:dk,se=(o=t.uriResolver)!==null&&o!==void 0?o:YA.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:R,regExp:H}:{optimize:R,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:ak,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:ak,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(b=t.inlineRefs)!==null&&b!==void 0?b:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(P=t.validateFormats)!==null&&P!==void 0?P:!0,unicodeRegExp:(j=t.unicodeRegExp)!==null&&j!==void 0?j:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:se}}var _i=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...rN(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new XA.ValueScope({scope:{},prefixes:eN,es5:n,lines:r}),this.logger=uN(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,JA.getRules)(),ck.call(this,tN,e,"NOT SUPPORTED"),ck.call(this,nN,e,"DEPRECATED","warn"),this._metaOpts=aN.call(this),e.formats&&sN.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&iN.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),oN.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=ik;r==="id"&&(o={...ik},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 lk.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,yi.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=uk.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new gi.SchemaEnv({schema:{},schemaId:r});if(n=gi.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=uk.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,yi.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(dN.call(this,r,n),!n)return(0,If.eachItem)(r,s=>Of.call(this,s)),this;fN.call(this,n);let o={...n,type:(0,kc.getJSONTypes)(n.type),schemaType:(0,kc.getJSONTypes)(n.schemaType)};return(0,If.eachItem)(r,o.type.length===0?s=>Of.call(this,s,o):s=>o.type.forEach(i=>Of.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]=pk(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,yi.normalizeId)(i||r);let u=yi.getSchemaRefs.call(this,e,r);return c=new gi.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):gi.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{gi.compileSchema.call(this,e)}finally{this.opts=n}}};_i.ValidationError=GA.default;_i.MissingRefError=lk.default;Xe.default=_i;function ck(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 uk(t){return t=(0,yi.normalizeId)(t),this.schemas[t]||this.refs[t]}function oN(){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 sN(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function iN(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 aN(){let t={...this.opts};for(let e of QA)delete t[e];return t}var cN={log(){},warn(){},error(){}};function uN(t){if(t===!1)return cN;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 lN=/^[a-z_$][a-z0-9_$:-]*$/i;function dN(t,e){let{RULES:n}=this;if((0,If.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!lN.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 Of(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,kc.getJSONTypes)(e.type),schemaType:(0,kc.getJSONTypes)(e.schemaType)}};e.before?pN.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 pN(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 fN(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=pk(e)),t.validateSchema=this.compile(e,!0))}var mN={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function pk(t){return{anyOf:[t,mN]}}});var mk=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var hN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Af.default=hN});var _k=I(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.callRef=Xr.getValidate=void 0;var gN=mi(),hk=Lt(),St=ee(),Ko=Nn(),gk=gc(),Sc=le(),yN={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=gk.resolveRef.call(c,u,o,n);if(l===void 0)throw new gN.default(r.opts.uriResolver,o,n);if(l instanceof gk.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return vc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return vc(t,(0,St._)`${p}.validate`,u,u.$async)}function f(p){let h=yk(t,p);vc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,St.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:St.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function yk(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,St._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Xr.getValidate=yk;function vc(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Ko.default.this:St.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,St._)`await ${(0,hk.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,St._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,hk.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,St._)`${p}.errors`;o.assign(Ko.default.vErrors,(0,St._)`${Ko.default.vErrors} === null ? ${h} : ${Ko.default.vErrors}.concat(${h})`),o.assign(Ko.default.errors,(0,St._)`${Ko.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=Sc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,St._)`${p}.evaluated.props`);s.props=Sc.mergeEvaluated.props(o,y,s.props,St.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Sc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,St._)`${p}.evaluated.items`);s.items=Sc.mergeEvaluated.items(o,y,s.items,St.Name)}}}Xr.callRef=vc;Xr.default=yN});var bk=I(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var _N=mk(),bN=_k(),xN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",_N.default,bN.default];Nf.default=xN});var xk=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Ec=ee(),cr=Ec.operators,wc={maximum:{okStr:"<=",ok:cr.LTE,fail:cr.GT},minimum:{okStr:">=",ok:cr.GTE,fail:cr.LT},exclusiveMaximum:{okStr:"<",ok:cr.LT,fail:cr.GTE},exclusiveMinimum:{okStr:">",ok:cr.GT,fail:cr.LTE}},kN={message:({keyword:t,schemaCode:e})=>(0,Ec.str)`must be ${wc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ec._)`{comparison: ${wc[t].okStr}, limit: ${e}}`},SN={keyword:Object.keys(wc),type:"number",schemaType:"number",$data:!0,error:kN,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,Ec._)`${n} ${wc[e].fail} ${r} || isNaN(${n})`)}};Mf.default=SN});var kk=I(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});var bi=ee(),vN={message:({schemaCode:t})=>(0,bi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,bi._)`{multipleOf: ${t}}`},EN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vN,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,bi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,bi._)`${i} !== parseInt(${i})`;t.fail$data((0,bi._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Df.default=EN});var vk=I(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});function Sk(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}jf.default=Sk;Sk.code='require("ajv/dist/runtime/ucs2length").default'});var Ek=I(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var Yr=ee(),wN=le(),TN=vk(),RN={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Yr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Yr._)`{limit: ${t}}`},PN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:RN,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Yr.operators.GT:Yr.operators.LT,i=o.opts.unicode===!1?(0,Yr._)`${n}.length`:(0,Yr._)`${(0,wN.useFunc)(t.gen,TN.default)}(${n})`;t.fail$data((0,Yr._)`${i} ${s} ${r}`)}};Lf.default=PN});var wk=I(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var CN=Lt(),$N=le(),Go=ee(),ON={message:({schemaCode:t})=>(0,Go.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Go._)`{pattern: ${t}}`},IN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:ON,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,Go._)`new RegExp`:(0,$N.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Go._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,Go._)`!${l}`)}else{let c=(0,CN.usePattern)(t,o);t.fail$data((0,Go._)`!${c}.test(${n})`)}}};zf.default=IN});var Tk=I(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var xi=ee(),AN={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,xi.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,xi._)`{limit: ${t}}`},NN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:AN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?xi.operators.GT:xi.operators.LT;t.fail$data((0,xi._)`Object.keys(${n}).length ${o} ${r}`)}};Hf.default=NN});var Rk=I(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var ki=Lt(),Si=ee(),MN=le(),DN={message:({params:{missingProperty:t}})=>(0,Si.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Si._)`{missingProperty: ${t}}`},jN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:DN,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,MN.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Si.nil,d);else for(let m of n)(0,ki.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,ki.checkMissingProp)(t,n,m)),(0,ki.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,ki.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,ki.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Si.not)(p),()=>{t.error(),e.break()})},Si.nil)}}};Uf.default=jN});var Pk=I(Ff=>{"use strict";Object.defineProperty(Ff,"__esModule",{value:!0});var vi=ee(),LN={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,vi.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,vi._)`{limit: ${t}}`},zN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:LN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?vi.operators.GT:vi.operators.LT;t.fail$data((0,vi._)`${n}.length ${o} ${r}`)}};Ff.default=zN});var Tc=I(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Ck=ff();Ck.code='require("ajv/dist/runtime/equal").default';Zf.default=Ck});var $k=I(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Bf=ui(),Ye=ee(),HN=le(),UN=Tc(),FN={message:({params:{i:t,j:e}})=>(0,Ye.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Ye._)`{i: ${t}, j: ${e}}`},ZN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:FN,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,Bf.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Ye._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Ye._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Ye._)`${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,Bf.checkDataTypes)(u,g,a.opts.strictNumbers,Bf.DataType.Wrong),_=e.const("indices",(0,Ye._)`{}`);e.for((0,Ye._)`;${p}--;`,()=>{e.let(g,(0,Ye._)`${n}[${p}]`),e.if(y,(0,Ye._)`continue`),u.length>1&&e.if((0,Ye._)`typeof ${g} == "string"`,(0,Ye._)`${g} += "_"`),e.if((0,Ye._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Ye._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Ye._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,HN.useFunc)(e,UN.default),y=e.name("outer");e.label(y).for((0,Ye._)`;${p}--;`,()=>e.for((0,Ye._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Ye._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};qf.default=ZN});var Ok=I(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Vf=ee(),BN=le(),qN=Tc(),VN={message:"must be equal to constant",params:({schemaCode:t})=>(0,Vf._)`{allowedValue: ${t}}`},WN={keyword:"const",$data:!0,error:VN,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Vf._)`!${(0,BN.useFunc)(e,qN.default)}(${n}, ${o})`):t.fail((0,Vf._)`${s} !== ${n}`)}};Wf.default=WN});var Ik=I(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});var Ei=ee(),KN=le(),GN=Tc(),JN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ei._)`{allowedValues: ${t}}`},XN={keyword:"enum",schemaType:"array",$data:!0,error:JN,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,KN.useFunc)(e,GN.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,Ei.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,Ei._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,Ei._)`${u()}(${n}, ${m}[${p}])`:(0,Ei._)`${n} === ${h}`}}};Kf.default=XN});var Ak=I(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var YN=xk(),QN=kk(),eM=Ek(),tM=wk(),nM=Tk(),rM=Rk(),oM=Pk(),sM=$k(),iM=Ok(),aM=Ik(),cM=[YN.default,QN.default,eM.default,tM.default,nM.default,rM.default,oM.default,sM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},iM.default,aM.default];Gf.default=cM});var Xf=I(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateAdditionalItems=void 0;var Qr=ee(),Jf=le(),uM={message:({params:{len:t}})=>(0,Qr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Qr._)`{limit: ${t}}`},lM={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:uM,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Jf.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}Nk(t,r)}};function Nk(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Qr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Qr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Jf.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Qr._)`${a} <= ${e.length}`);n.if((0,Qr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Jf.Type.Num},u),i.allErrors||n.if((0,Qr.not)(u),()=>n.break())})}}wi.validateAdditionalItems=Nk;wi.default=lM});var Yf=I(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});Ti.validateTuple=void 0;var Mk=ee(),Rc=le(),dM=Lt(),pM={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Dk(t,"additionalItems",e);n.items=!0,!(0,Rc.alwaysValidSchema)(n,e)&&t.ok((0,dM.validateArray)(t))}};function Dk(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=Rc.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,Rc.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,Rc.checkStrictMode)(a,g,f.strictTuples)}}}Ti.validateTuple=Dk;Ti.default=pM});var jk=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var fM=Yf(),mM={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,fM.validateTuple)(t,"items")};Qf.default=mM});var zk=I(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});var Lk=ee(),hM=le(),gM=Lt(),yM=Xf(),_M={message:({params:{len:t}})=>(0,Lk.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Lk._)`{limit: ${t}}`},bM={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:_M,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,hM.alwaysValidSchema)(r,e)&&(o?(0,yM.validateAdditionalItems)(t,o):t.ok((0,gM.validateArray)(t)))}};em.default=bM});var Hk=I(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Ht=ee(),Pc=le(),xM={message:({params:{min:t,max:e}})=>e===void 0?(0,Ht.str)`must contain at least ${t} valid item(s)`:(0,Ht.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Ht._)`{minContains: ${t}}`:(0,Ht._)`{minContains: ${t}, maxContains: ${e}}`},kM={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:xM,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,Ht._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Pc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Pc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Pc.alwaysValidSchema)(s,n)){let h=(0,Ht._)`${l} >= ${i}`;a!==void 0&&(h=(0,Ht._)`${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,Ht._)`${o}.length > 0`,f)):(e.let(d,!1),f()),t.result(d,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);m(h,()=>e.if(h,()=>p(g)))}function m(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Pc.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Ht._)`${h}++`),a===void 0?e.if((0,Ht._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Ht._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Ht._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};tm.default=kM});var Zk=I(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateSchemaDeps=yn.validatePropertyDeps=yn.error=void 0;var nm=ee(),SM=le(),Ri=Lt();yn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,nm.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,nm._)`{property: ${t},
missingProperty: ${r},
depsCount: ${e},
deps: ${n}}`};var vM={keyword:"dependencies",type:"object",schemaType:"object",error:yn.error,code(t){let[e,n]=EM(t);Uk(t,e),Fk(t,n)}};function EM({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 Uk(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,Ri.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,Ri.checkReportMissingProp)(t,u)}):(n.if((0,nm._)`${c} && (${(0,Ri.checkMissingProp)(t,a,s)})`),(0,Ri.reportMissingProp)(t,s),n.else())}}yn.validatePropertyDeps=Uk;function Fk(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,SM.alwaysValidSchema)(s,e[a])||(n.if((0,Ri.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))}yn.validateSchemaDeps=Fk;yn.default=vM});var qk=I(rm=>{"use strict";Object.defineProperty(rm,"__esModule",{value:!0});var Bk=ee(),wM=le(),TM={message:"property name must be valid",params:({params:t})=>(0,Bk._)`{propertyName: ${t.propertyName}}`},RM={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:TM,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,wM.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,Bk.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};rm.default=RM});var sm=I(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var Cc=Lt(),nn=ee(),PM=Nn(),$c=le(),CM={message:"must NOT have additional properties",params:({params:t})=>(0,nn._)`{additionalProperty: ${t.additionalProperty}}`},$M={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:CM,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,$c.alwaysValidSchema)(i,n))return;let u=(0,Cc.allSchemaProperties)(r.properties),l=(0,Cc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,nn._)`${s} === ${PM.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,$c.schemaRefOrVal)(i,r.properties,"properties");y=(0,Cc.isOwnProperty)(e,_,g)}else u.length?y=(0,nn.or)(...u.map(_=>(0,nn._)`${g} === ${_}`)):y=nn.nil;return l.length&&(y=(0,nn.or)(y,...l.map(_=>(0,nn._)`${(0,Cc.usePattern)(t,_)}.test(${g})`))),(0,nn.not)(y)}function m(g){e.code((0,nn._)`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,$c.alwaysValidSchema)(i,n)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,nn.not)(y),()=>{t.reset(),m(g)})):(h(g,y),a||e.if((0,nn.not)(y),()=>e.break()))}}function h(g,y,_){let b={keyword:"additionalProperties",dataProp:g,dataPropType:$c.Type.Str};_===!1&&Object.assign(b,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(b,y)}}};om.default=$M});var Kk=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var OM=fi(),Vk=Lt(),im=le(),Wk=sm(),IM={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&&Wk.default.code(new OM.KeywordCxt(s,Wk.default,"additionalProperties"));let i=(0,Vk.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=im.mergeEvaluated.props(e,(0,im.toHash)(i),s.props));let a=i.filter(d=>!(0,im.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,Vk.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)}}};am.default=IM});var Yk=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var Gk=Lt(),Oc=ee(),Jk=le(),Xk=le(),AM={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,Gk.allSchemaProperties)(n),c=a.filter(h=>(0,Jk.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 Oc.Name)&&(s.props=(0,Xk.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,Jk.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,Oc._)`${(0,Gk.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Xk.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Oc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Oc.not)(l),()=>e.break())})})}}};cm.default=AM});var Qk=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var NM=le(),MM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,NM.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"}};um.default=MM});var eS=I(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var DM=Lt(),jM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:DM.validateUnion,error:{message:"must match a schema in anyOf"}};lm.default=jM});var tS=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var Ic=ee(),LM=le(),zM={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ic._)`{passingSchemas: ${t.passing}}`},HM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:zM,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,LM.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Ic._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ic._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Ic.Name)})})}}};dm.default=HM});var nS=I(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var UM=le(),FM={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,UM.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};pm.default=FM});var sS=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var Ac=ee(),oS=le(),ZM={message:({params:t})=>(0,Ac.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ac._)`{failingKeyword: ${t.ifClause}}`},BM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:ZM,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,oS.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=rS(r,"then"),s=rS(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,Ac.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,Ac._)`${l}`):t.setParams({ifClause:l})}}}};function rS(t,e){let n=t.schema[e];return n!==void 0&&!(0,oS.alwaysValidSchema)(t,n)}fm.default=BM});var iS=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var qM=le(),VM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,qM.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};mm.default=VM});var aS=I(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var WM=Xf(),KM=jk(),GM=Yf(),JM=zk(),XM=Hk(),YM=Zk(),QM=qk(),eD=sm(),tD=Kk(),nD=Yk(),rD=Qk(),oD=eS(),sD=tS(),iD=nS(),aD=sS(),cD=iS();function uD(t=!1){let e=[rD.default,oD.default,sD.default,iD.default,aD.default,cD.default,QM.default,eD.default,YM.default,tD.default,nD.default];return t?e.push(KM.default,JM.default):e.push(WM.default,GM.default),e.push(XM.default),e}hm.default=uD});var cS=I(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var De=ee(),lD={message:({schemaCode:t})=>(0,De.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,De._)`{format: ${t}}`},dD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:lD,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,De._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,De._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,De._)`${h}.type || "string"`).assign(y,(0,De._)`${h}.validate`),()=>n.assign(g,(0,De._)`"string"`).assign(y,h)),t.fail$data((0,De.or)(_(),b()));function _(){return c.strictSchema===!1?De.nil:(0,De._)`${i} && !${y}`}function b(){let k=l.$async?(0,De._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,De._)`${y}(${r})`,v=(0,De._)`(typeof ${y} == "function" ? ${k} : ${y}.test(${r}))`;return(0,De._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=b(p);h===e&&t.pass(k());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 b(v){let O=v instanceof RegExp?(0,De.regexpCode)(v):c.code.formats?(0,De._)`${c.code.formats}${(0,De.getProperty)(s)}`:void 0,P=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,De._)`${P}.validate`]:["string",v,P]}function k(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,De._)`await ${y}(${r})`}return typeof g=="function"?(0,De._)`${y}(${r})`:(0,De._)`${y}.test(${r})`}}}};gm.default=dD});var uS=I(ym=>{"use strict";Object.defineProperty(ym,"__esModule",{value:!0});var pD=cS(),fD=[pD.default];ym.default=fD});var lS=I(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.contentVocabulary=Jo.metadataVocabulary=void 0;Jo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Jo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var pS=I(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var mD=bk(),hD=Ak(),gD=aS(),yD=uS(),dS=lS(),_D=[mD.default,hD.default,(0,gD.default)(),yD.default,dS.metadataVocabulary,dS.contentVocabulary];_m.default=_D});var mS=I(Nc=>{"use strict";Object.defineProperty(Nc,"__esModule",{value:!0});Nc.DiscrError=void 0;var fS;(function(t){t.Tag="tag",t.Mapping="mapping"})(fS||(Nc.DiscrError=fS={}))});var gS=I(xm=>{"use strict";Object.defineProperty(xm,"__esModule",{value:!0});var Xo=ee(),bm=mS(),hS=gc(),bD=mi(),xD=le(),kD={message:({params:{discrError:t,tagName:e}})=>t===bm.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Xo._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},SD={keyword:"discriminator",type:"object",schemaType:"object",error:kD,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,Xo._)`${n}${(0,Xo.getProperty)(a)}`);e.if((0,Xo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:bm.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,Xo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:bm.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,Xo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let k=0;k<i.length;k++){let v=i[k];if(v?.$ref&&!(0,xD.schemaHasRulesButRef)(v,s.self.RULES)){let P=v.$ref;if(v=hS.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,P),v instanceof hS.SchemaEnv&&(v=v.schema),v===void 0)throw new bD.default(s.opts.uriResolver,s.baseId,P)}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,k)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:k}){return Array.isArray(k)&&k.includes(a)}function _(k,v){if(k.const)b(k.const,v);else if(k.enum)for(let O of k.enum)b(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function b(k,v){if(typeof k!="string"||k in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[k]=v}}}};xm.default=SD});var yS=I((l9,vD)=>{vD.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 Sm=I((we,km)=>{"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 ED=fk(),wD=pS(),TD=gS(),_S=yS(),RD=["/properties"],Mc="http://json-schema.org/draft-07/schema",Yo=class extends ED.default{_addVocabularies(){super._addVocabularies(),wD.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(TD.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(_S,RD):_S;this.addMetaSchema(e,Mc,!1),this.refs["http://json-schema.org/schema"]=Mc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mc)?Mc:void 0)}};we.Ajv=Yo;km.exports=we=Yo;km.exports.Ajv=Yo;Object.defineProperty(we,"__esModule",{value:!0});we.default=Yo;var PD=fi();Object.defineProperty(we,"KeywordCxt",{enumerable:!0,get:function(){return PD.KeywordCxt}});var Qo=ee();Object.defineProperty(we,"_",{enumerable:!0,get:function(){return Qo._}});Object.defineProperty(we,"str",{enumerable:!0,get:function(){return Qo.str}});Object.defineProperty(we,"stringify",{enumerable:!0,get:function(){return Qo.stringify}});Object.defineProperty(we,"nil",{enumerable:!0,get:function(){return Qo.nil}});Object.defineProperty(we,"Name",{enumerable:!0,get:function(){return Qo.Name}});Object.defineProperty(we,"CodeGen",{enumerable:!0,get:function(){return Qo.CodeGen}});var CD=mc();Object.defineProperty(we,"ValidationError",{enumerable:!0,get:function(){return CD.default}});var $D=mi();Object.defineProperty(we,"MissingRefError",{enumerable:!0,get:function(){return $D.default}})});var TS=I(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.formatNames=bn.fastFormats=bn.fullFormats=void 0;function _n(t,e){return{validate:t,compare:e}}bn.fullFormats={date:_n(SS,Tm),time:_n(Em(!0),Rm),"date-time":_n(bS(!0),ES),"iso-time":_n(Em(),vS),"iso-date-time":_n(bS(),wS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:DD,"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:ZD,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:jD,int32:{type:"number",validate:HD},int64:{type:"number",validate:UD},float:{type:"number",validate:kS},double:{type:"number",validate:kS},password:!0,binary:!0};bn.fastFormats={...bn.fullFormats,date:_n(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Tm),time:_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Rm),"date-time":_n(/^\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,ES),"iso-time":_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,vS),"iso-date-time":_n(/^\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,wS),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};bn.formatNames=Object.keys(bn.fullFormats);function OD(t){return t%4===0&&(t%100!==0||t%400===0)}var ID=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,AD=[0,31,28,31,30,31,30,31,31,30,31,30,31];function SS(t){let e=ID.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&&OD(n)?29:AD[r])}function Tm(t,e){if(t&&e)return t>e?1:t<e?-1:0}var vm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Em(t){return function(n){let r=vm.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 Rm(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 vS(t,e){if(!(t&&e))return;let n=vm.exec(t),r=vm.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 wm=/t|\s/i;function bS(t){let e=Em(t);return function(r){let o=r.split(wm);return o.length===2&&SS(o[0])&&e(o[1])}}function ES(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function wS(t,e){if(!(t&&e))return;let[n,r]=t.split(wm),[o,s]=e.split(wm),i=Tm(n,o);if(i!==void 0)return i||Rm(r,s)}var ND=/\/|:/,MD=/^(?:[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 DD(t){return ND.test(t)&&MD.test(t)}var xS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function jD(t){return xS.lastIndex=0,xS.test(t)}var LD=-(2**31),zD=2**31-1;function HD(t){return Number.isInteger(t)&&t<=zD&&t>=LD}function UD(t){return Number.isInteger(t)}function kS(){return!0}var FD=/[^\\]\\Z/;function ZD(t){if(FD.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var RS=I(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.formatLimitDefinition=void 0;var BD=Sm(),rn=ee(),ur=rn.operators,Dc={formatMaximum:{okStr:"<=",ok:ur.LTE,fail:ur.GT},formatMinimum:{okStr:">=",ok:ur.GTE,fail:ur.LT},formatExclusiveMaximum:{okStr:"<",ok:ur.LT,fail:ur.GTE},formatExclusiveMinimum:{okStr:">",ok:ur.GT,fail:ur.LTE}},qD={message:({keyword:t,schemaCode:e})=>(0,rn.str)`should be ${Dc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rn._)`{comparison: ${Dc[t].okStr}, limit: ${e}}`};es.formatLimitDefinition={keyword:Object.keys(Dc),type:"string",schemaType:"string",$data:!0,error:qD,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 BD.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,rn._)`${f}[${c.schemaCode}]`);t.fail$data((0,rn.or)((0,rn._)`typeof ${m} != "object"`,(0,rn._)`${m} instanceof RegExp`,(0,rn._)`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,rn._)`${i.code.formats}${(0,rn.getProperty)(f)}`:void 0});t.fail$data(d(p))}function d(f){return(0,rn._)`${f}.compare(${n}, ${r}) ${Dc[o].fail} 0`}},dependencies:["format"]};var VD=t=>(t.addKeyword(es.formatLimitDefinition),t);es.default=VD});var OS=I((Pi,$S)=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});var ts=TS(),WD=RS(),Pm=ee(),PS=new Pm.Name("fullFormats"),KD=new Pm.Name("fastFormats"),Cm=(t,e={keywords:!0})=>{if(Array.isArray(e))return CS(t,e,ts.fullFormats,PS),t;let[n,r]=e.mode==="fast"?[ts.fastFormats,KD]:[ts.fullFormats,PS],o=e.formats||ts.formatNames;return CS(t,o,n,r),e.keywords&&(0,WD.default)(t),t};Cm.get=(t,e="full")=>{let r=(e==="fast"?ts.fastFormats:ts.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function CS(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Pm._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}$S.exports=Pi=Cm;Object.defineProperty(Pi,"__esModule",{value:!0});Pi.default=Cm});function $i(t,e){let n=process.execPath.replace(/\\/g,"/");if(qc(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Am.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function je(t,e){if(qc(e?.platform))return $i(t,e);let r=qS().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Bc(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 qc(t){return!!t&&nj.has(t)}var Am,nj,jn=X(()=>{"use strict";Vc();Am=new Set(["node","bun","deno"]),nj=new Set(["opencode","kilo"])});import{execFileSync as Dm,execSync as ns}from"node:child_process";import{existsSync as rs}from"node:fs";function Mm(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function oj(t){return rj.test(Mm(t))}function sj(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function ij(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function He(t){try{let e=Oi?`where ${t}`:`command -v ${t}`;return ns(e,{stdio:"pipe"}),!0}catch{return!1}}function Nm(t){if(Oi)try{let n=ns(`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(!He(t))return!1;try{return Oi?ns(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Dm(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function jm(){if(He("bun"))return!0;for(let t of KS())if(rs(t))return!0;return!1}function WS(){for(let e of KS())if(rs(e))return e;if(He("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Oi?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function KS(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Oi){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 GS(){let t;try{t=ns("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 aj)if(rs(r))return r;return e}}return null}function cj(t=GS()){return t??(He("sh")?"sh":He("pwsh")?"pwsh":He("powershell")?"powershell":"cmd.exe")}function Ut(t,e=["--version"]){try{if(process.platform==="win32"){let n=[t,...e].map(r=>/[\s"&|<>^()%!]/.test(r)?JSON.stringify(r):r).join(" ");return ns(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Dm(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function uj(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??He,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Am.has(o)&&rs(n)?n:r("node")?"node":null}function Wc(){let e=jm()?WS():null,n=process.env.SHELL,r=process.platform==="win32",o=r?GS():null,s=n&&rs(n)&&oj(n)&&!(r&&sj(n))&&!(r&&o&&ij(n))?n:null;return{javascript:uj(e),typescript:e||(He("tsx")?"tsx":He("ts-node")?"ts-node":null),python:Nm("python3")?"python3":Nm("python")?"python":Nm("py")?"py":null,shell:s??(r?cj(o):He("bash")?"bash":"sh"),ruby:He("ruby")?"ruby":null,go:He("go")?"go":null,rust:He("rustc")?"rustc":null,php:He("php")?"php":null,perl:He("perl")?"perl":null,r:He("Rscript")?"Rscript":He("r")?"r":null,elixir:He("elixir")?"elixir":null,csharp:He("dotnet-script")?"dotnet-script":null}}function Kc(){return jm()}function lj(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 dj(){return rs(process.execPath)?{path:process.execPath,isBun:!1}:He("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function qS(){if(Ft)return Ft;let t=dj();try{if(!jm())return Ft=t,Ft;let e=WS(),n;try{if(process.platform==="win32"){let r=ns(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Dm(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return lj(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function JS(t){let e=[],n=t.javascript?.endsWith("bun")??!1;return t.javascript?e.push(` JavaScript: ${t.javascript} (${Ut(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} (${Ut(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Ut(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Ut(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Ut(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Ut(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Ut(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Ut(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Ut(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Ut(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Ut(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Ut(t.csharp)})`),n||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
`)}function XS(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 YS(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 VS.test(Mm(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 VS.test(Mm(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 rj,VS,Oi,aj,Ft,Vc=X(()=>{"use strict";jn();rj=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,VS=/^bun(\.exe)?$/i;Oi=process.platform==="win32";aj=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ft=null});import{createRequire as Tj}from"node:module";import{existsSync as Rj,unlinkSync as sv,renameSync as Pj}from"node:fs";import{tmpdir as Cj}from"node:os";import{join as $j}from"node:path";function Oj(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 Ij(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 Be(){if(!os){let t=Tj(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;os=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new Um(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(Ij()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&Oj(e)?os=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new Fm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:os=t("better-sqlite3")}else os=t("better-sqlite3")}return os}function eo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function to(t){if(!Rj(t))for(let e of["-wal","-shm"])try{sv(t+e)}catch{}}function Zm(t){for(let e of["","-wal","-shm"])try{sv(t+e)}catch{}}function Ni(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function iv(t="context-mode"){return $j(Cj(),`${t}-${process.pid}.db`)}function xn(t,e=[100,500,2e3]){let n;for(let r=0;r<=e.length;r++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(n=o instanceof Error?o:new Error(s),r<e.length){let i=e[r],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${n?.message}`)}function Bm(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 Aj(t){let e=Date.now();for(let n of["","-wal","-shm"])try{Pj(t+n,`${t}${n}.corrupt-${e}`)}catch{}}var Um,Fm,os,Ai,Hm,Jc,no=X(()=>{"use strict";Um=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()}},Fm=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()}},os=null;Ai=Symbol.for("__context_mode_live_dbs_v3__"),Hm=(()=>{let t=globalThis;return t[Ai]||(t[Ai]=new Set,process.on("exit",()=>{for(let e of t[Ai])Ni(e);t[Ai].clear()})),t[Ai]})(),Jc=class{#e;#t;constructor(e){let n=Be();this.#e=e,to(e);let r;try{r=new n(e,{timeout:3e4}),eo(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Bm(s)){Aj(e),to(e);try{r=new n(e,{timeout:3e4}),eo(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,Hm.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Hm.delete(this.#t),Ni(this.#t)}withRetry(e){return xn(e)}cleanup(){Hm.delete(this.#t),Ni(this.#t),Zm(this.#e)}}});var Tv,Rv=X(()=>{"use strict";Tv={"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 Di}from"node:crypto";import{execFileSync as dL}from"node:child_process";import{accessSync as pL,constants as fL,existsSync as nu,mkdirSync as mL,realpathSync as hL,renameSync as rh}from"node:fs";import{homedir as Av}from"node:os";import{dirname as gL,isAbsolute as Nv,join as dr,resolve as is}from"node:path";function oh(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):dr(yL(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function yL(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?Cv(r.trim()):Cv(t,Av())}function Cv(t,e){return t.startsWith("~")?is(Av(),t.replace(/^~[/\\]?/,"")):Nv(t)?is(t):e?is(e,t):is(t)}function _L(t,e,n){return new pr(t,e,kn,void 0,[`Invalid ${kn} for context-mode ${t} directory: ${n}`,zv()].join(`
`))}function Dv(t){let e=process.env[kn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:kn,ignoredReason:"empty"};if(!Nv(n))throw _L(t,n,`${kn} must be an absolute path.`);return{kind:"override",root:is(n)}}function bL(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function jv(t,e){let n=Dv(t);return n.kind!=="override"?null:{kind:t,path:dr(n.root,e),envVar:kn,source:"override"}}function xL(t,e,n){return{kind:t,path:is(e()),envVar:null,source:"default",...n}}function ji(t){let e=Dv("session");return e.kind==="override"?{kind:"session",path:dr(e.root,Mv),envVar:kn,source:"override"}:xL("session",t,bL(e))}function sh(t){let e=jv("content",Pv);if(e)return e;let n=ji(t);return{kind:"content",path:dr(gL(n.path),Pv),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function ih(t){let e=jv("stats",Mv);if(e)return e;let n=ji(t);return{kind:"stats",path:n.path,envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Lv(t){return t.message}function ru(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function ou(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=nh.get(e);if(n instanceof pr)throw n;if(n===t.path)return n;try{return mL(t.path,{recursive:!0}),pL(t.path,fL.W_OK),nh.set(e,t.path),t.path}catch(r){let o=new pr(t.kind,vL(r)??t.path,kn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw nh.set(e,o),o}}function kL(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,SL(n),zv()].filter(Boolean).join(`
`)}function SL(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function zv(){return`Set ${kn} to a writable absolute path.`}function vL(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function ro(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function $v(t){let e=t;try{e=hL.native(t)}catch{}let n=ro(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function Hv(t,e){return dL("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function EL(t){let e=Hv(t,["rev-parse","--show-toplevel"]);return e.length>0?ro(e):null}function wL(t){let e=Hv(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?ro(e):null}function su(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Mi&&Mi.projectDir===t&&Mi.envSuffix===e)return Mi.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=EL(t),o=wL(t);if(r&&o){let s=$v(r),i=$v(o);s!==i&&(n=`__${Di("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return Mi={projectDir:t,envSuffix:e,suffix:n},n}function Ln(t){return Di("sha256").update(ro(t)).digest("hex").slice(0,16)}function Qe(t){let e=ro(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Di("sha256").update(n).digest("hex").slice(0,16)}function Uv(t){let{projectDir:e,contentDir:n}=t,r=Qe(e),o=dr(n,`${r}.db`);if(nu(o))return o;let s=Ln(e);if(s===r)return o;let i=dr(n,`${s}.db`);if(nu(i))try{rh(i,o);for(let a of["-wal","-shm"])try{rh(i+a,o+a)}catch{}}catch{}return o}function Li(t){return TL({...t,ext:".db"})}function TL(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??su(e),s=Qe(e),i=dr(n,`${s}${o}${r}`);if(nu(i))return i;let a=Ln(e);if(a===s)return i;let c=dr(n,`${a}${o}${r}`);if(nu(c))try{rh(c,i)}catch{}return i}function tu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function Fv(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of RL)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 Zv(t,e){let n=null;try{n=new e(t),Fv(n)}catch{}finally{try{n?.close()}catch{}}}var kn,Mv,Pv,pr,nh,Mi,Ov,Iv,M,RL,on,Sn=X(()=>{"use strict";no();kn="CONTEXT_MODE_DIR",Mv="sessions",Pv="content",pr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=kn,o,s,i={}){super(s??kL(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}},nh=new Map;Ov=1e3,Iv=5;M={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"},RL=[["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"]];on=class extends Jc{constructor(e){super(e?.dbPath??iv("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{}this.db.exec(`
CREATE TABLE IF NOT EXISTS session_events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL,
type TEXT NOT NULL,
category TEXT NOT NULL,
priority INTEGER NOT NULL DEFAULT 2,
data TEXT NOT NULL,
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,
source_hook TEXT NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
data_hash TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_session_events_session ON session_events(session_id);
CREATE INDEX IF NOT EXISTS idx_session_events_type ON session_events(session_id, type);
CREATE INDEX IF NOT EXISTS idx_session_events_priority ON session_events(session_id, priority);
CREATE TABLE IF NOT EXISTS session_meta (
session_id TEXT PRIMARY KEY,
project_dir TEXT NOT NULL,
started_at TEXT NOT NULL DEFAULT (datetime('now')),
last_event_at TEXT,
event_count INTEGER NOT NULL DEFAULT 0,
compact_count INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS session_resume (
id INTEGER PRIMARY KEY AUTOINCREMENT,
session_id TEXT NOT NULL UNIQUE,
snapshot TEXT NOT NULL,
event_count INTEGER NOT NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
consumed INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS tool_calls (
session_id TEXT NOT NULL,
tool TEXT NOT NULL,
calls INTEGER NOT NULL DEFAULT 0,
bytes_returned INTEGER NOT NULL DEFAULT 0,
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
PRIMARY KEY (session_id, tool)
);
CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
`);try{Fv(this.db)}catch{}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{}}prepareStatements(){this.stmts=new Map;let e=(n,r)=>{this.stmts.set(n,this.db.prepare(r))};e(M.insertEvent,`INSERT INTO session_events (
session_id, type, category, priority, data,
project_dir, attribution_source, attribution_confidence,
bytes_avoided, bytes_returned,
source_hook, data_hash
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(M.getEvents,`SELECT id, session_id, type, category, priority, data,
project_dir, attribution_source, attribution_confidence,
bytes_avoided, bytes_returned,
source_hook, created_at, data_hash
FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(M.getEventsByType,`SELECT id, session_id, type, category, priority, data,
project_dir, attribution_source, attribution_confidence,
bytes_avoided, bytes_returned,
source_hook, created_at, data_hash
FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(M.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
project_dir, attribution_source, attribution_confidence,
bytes_avoided, bytes_returned,
source_hook, created_at, data_hash
FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(M.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
project_dir, attribution_source, attribution_confidence,
bytes_avoided, bytes_returned,
source_hook, created_at, data_hash
FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(M.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(M.getLatestAttributedProject,`SELECT project_dir
FROM session_events
WHERE session_id = ? AND project_dir != ''
ORDER BY id DESC
LIMIT 1`),e(M.checkDuplicate,`SELECT 1 FROM (
SELECT type, data_hash FROM session_events
WHERE session_id = ? ORDER BY id DESC LIMIT ?
) AS recent
WHERE recent.type = ? AND recent.data_hash = ?
LIMIT 1`),e(M.evictLowestPriority,`DELETE FROM session_events WHERE id = (
SELECT id FROM session_events WHERE session_id = ?
ORDER BY priority ASC, id ASC LIMIT 1
)`),e(M.updateMetaLastEvent,`UPDATE session_meta
SET last_event_at = datetime('now'), event_count = event_count + 1
WHERE session_id = ?`),e(M.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(M.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
FROM session_meta WHERE session_id = ?`),e(M.getSessionRollup,`SELECT
COUNT(*) AS tool_calls,
COALESCE(SUM(CASE WHEN category = 'error' THEN 1 ELSE 0 END), 0) AS errors,
COUNT(DISTINCT type) AS unique_tools,
COUNT(DISTINCT CASE WHEN category = 'file' THEN data END) AS unique_files,
CASE WHEN SUM(CASE WHEN type = 'git_commit' THEN 1 ELSE 0 END) > 0 THEN 1 ELSE 0 END AS has_commit,
CAST(COALESCE((MAX(strftime('%s', created_at)) - MIN(strftime('%s', created_at))) / 60.0, 0) AS INTEGER) AS duration_min,
COALESCE(SUM(CASE WHEN type = 'external_ref' THEN 1 ELSE 0 END), 0) AS sources_indexed,
CAST(COALESCE(SUM(bytes_avoided) / 1024.0, 0) AS INTEGER) AS total_chunks,
COALESCE(SUM(CASE WHEN type IN ('file_search', 'file_glob') THEN 1 ELSE 0 END), 0) AS search_queries
FROM session_events
WHERE session_id = ?`),e(M.getMaxFileEdits,`SELECT COALESCE(MAX(c), 0) AS max_file_edits
FROM (
SELECT COUNT(*) AS c
FROM session_events
WHERE session_id = ? AND category = 'file' AND type IN ('file_edit', 'file_write')
GROUP BY data
)`),e(M.getLatestCommitMessage,`SELECT data
FROM session_events
WHERE session_id = ? AND type = 'git_commit'
ORDER BY id DESC
LIMIT 1`),e(M.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(M.getUsageCursor,"SELECT usage_cursor FROM session_meta WHERE session_id = ?"),e(M.setUsageCursor,"UPDATE session_meta SET usage_cursor = ? WHERE session_id = ?"),e(M.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
VALUES (?, ?, ?)
ON CONFLICT(session_id) DO UPDATE SET
snapshot = excluded.snapshot,
event_count = excluded.event_count,
created_at = datetime('now'),
consumed = 0`),e(M.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(M.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(M.claimLatestUnconsumedResume,`UPDATE session_resume
SET consumed = 1
WHERE id = (
SELECT id FROM session_resume
WHERE consumed = 0
AND session_id != ?
ORDER BY created_at DESC, id DESC
LIMIT 1
)
RETURNING session_id, snapshot`),e(M.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(M.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(M.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(M.searchEvents,`SELECT id, session_id, category, type, data, created_at
FROM session_events
WHERE (project_dir = ? OR project_dir = '')
AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
AND (? IS NULL OR category = ?)
ORDER BY id ASC
LIMIT ?`),e(M.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(M.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
VALUES (?, ?, 1, ?)
ON CONFLICT(session_id, tool) DO UPDATE SET
calls = calls + 1,
bytes_returned = bytes_returned + excluded.bytes_returned,
updated_at = datetime('now')`),e(M.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
FROM tool_calls WHERE session_id = ?`),e(M.getToolCallByTool,`SELECT tool, calls, bytes_returned
FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(M.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Di("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=tu(s?.bytesAvoided),f=tu(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(M.checkDuplicate).get(e,Iv,n.type,i))return;this.stmt(M.getEventCount).get(e).cnt>=Ov&&this.stmt(M.evictLowestPriority).run(e),this.stmt(M.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,f,r,i),this.stmt(M.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=Di("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===""?"":ro(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],_=tu(y?.bytesAvoided),b=tu(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:p,attributionConfidence:g,bytesAvoided:_,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(M.getEventCount).get(e).cnt;for(let u of i)this.stmt(M.checkDuplicate).get(e,Iv,u.event.type,u.dataHash)||(c>=Ov?this.stmt(M.evictLowestPriority).run(e):c++,this.stmt(M.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(M.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(M.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(M.getEventsByType).all(e,o,r):s!==void 0?this.stmt(M.getEventsByPriority).all(e,s,r):this.stmt(M.getEvents).all(e,r)}getEventCount(e){return this.stmt(M.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(M.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(M.getLatestAttributedProject).get(e)?.project_dir||null}_getSessionProjectDir(e){try{return this.db.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(e)?.project_dir||""}catch{return""}}searchEvents(e,n,r,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(M.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=ro(e);return this.db.prepare(`SELECT DISTINCT session_id
FROM session_events
WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(M.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(M.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(M.getSessionRollup).get(e),r=this.stmt(M.getMaxFileEdits).get(e),o=this.stmt(M.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(M.incrementCompactCount).run(e)}getUsageCursor(e){return this.stmt(M.getUsageCursor).get(e)?.usage_cursor??null}setUsageCursor(e,n){this.stmt(M.setUsageCursor).run(n,e)}upsertResume(e,n,r){this.stmt(M.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(M.getResume).get(e)??null}markResumeConsumed(e){this.stmt(M.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(M.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{return null}}incrementToolCall(e,n,r=0){let o=Number.isFinite(r)&&r>0?Math.round(r):0;try{this.stmt(M.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(M.getToolCallTotals).get(e),r=this.stmt(M.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{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(M.deleteEvents).run(e),this.stmt(M.deleteResume).run(e),this.stmt(M.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(M.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 as,resolve as Bv}from"node:path";import{accessSync as PL,copyFileSync as CL,constants as $L,mkdirSync as OL}from"node:fs";import{homedir as ah}from"node:os";function it(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?Bv(ah(),e.replace(/^~[/\\]?/,"")):Bv(e)}var ye,et=X(()=>{"use strict";Sn();ye=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=it(),n=e?as(e,"context-mode","sessions"):as(ah(),...this.sessionDirSegments,"context-mode","sessions");return OL(n,{recursive:!0}),n}getConfigDir(e){return as(ah(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=it(),r=n?as(n,"context-mode","memory"):as(this.getConfigDir(),"memory");return e?as(r,Qe(e)):r}backupSettings(){let e=this.getSettingsPath();try{PL(e,$L.R_OK);let n=e+".bak";return CL(e,n),n}catch{return null}}}});var cs,ch=X(()=>{"use strict";et();cs=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 uh}from"node:fs";import{join as lh}from"node:path";async function IL(){if(us)return us;if(ls)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 us=r,us}catch(r){e=r}return ls=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return ls=t instanceof Error?t.message:String(t),null}}function AL(t){let e=[];return uh(lh(t,"start.mjs"))||e.push("start.mjs"),!uh(lh(t,"server.bundle.mjs"))&&!uh(lh(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function qv(t){if(us){let e=us.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(ls){let e=AL(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${ls}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${ls}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var us,ls,Vv=X(()=>{"use strict";us=null,ls=null;IL()});function zi(t,e){let n=oo[e],r=ph(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function ph(t,e){if(e){let n=oo[t];return je(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function fh(t){let e=Bc(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 Gv(t){let e=Object.values(oo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Zt,NL,dh,Wv,ML,JV,oo,Kv,XV,Jv=X(()=>{"use strict";jn();Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},NL="mcp__",dh=["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",NL],Wv=dh.join("|"),ML=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],JV=ML.join("|"),oo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Kv=[Zt.PRE_TOOL_USE,Zt.SESSION_START],XV=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT,Zt.USER_PROMPT_SUBMIT,Zt.STOP]});var hh={};Me(hh,{ClaudeCodeAdapter:()=>mh});import{readFileSync as iu,writeFileSync as Xv,existsSync as Yv,readdirSync as DL,chmodSync as jL,accessSync as LL,mkdirSync as zL,constants as HL}from"node:fs";import{resolve as au,join as fr}from"node:path";import{homedir as Qv}from"node:os";var mh,gh=X(()=>{"use strict";ch();et();so();Vv();jn();Jv();mh=class extends cs{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 Ct()}getSessionDir(){let e=it(),n=e?fr(e,"context-mode","sessions"):fr(this.getConfigDir(),"context-mode","sessions");return zL(n,{recursive:!0}),n}getSettingsPath(){return fr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=je(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...dh].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=iu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Xv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
`,"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,Zt.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,Zt.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(oo).map(([o,s])=>{let i=fr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>Yv(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>qv(e)};return[...n,r]}readPluginHooks(e){let n=[fr(e,"hooks","hooks.json"),fr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=iu(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=>zi(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>zi(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=fr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(iu(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(),Ct(),au(Qv(),".claude"),au(Qv(),".config","claude")]));for(let n of e){let r=au(n,"plugins","cache","context-mode","context-mode");try{let s=DL(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(!Gv(p))return!0;let h=p.hooks??[];return h.every(y=>!y.command||!fh(y.command))?!0:h.every(y=>{let _=y.command?fh(y.command):null;return _?Yv(_):!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&&Kv.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(oo),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??[],b=_.length;y.hooks=_.filter(k=>!d(k.command)),p+=b-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=[Zt.PRE_TOOL_USE,Zt.SESSION_START];for(let u of c){let l=ph(u,e);if(u===Zt.PRE_TOOL_USE){let d={matcher:Wv,hooks:[{type:"command",command:l}]},f=r.PreToolUse;if(f&&Array.isArray(f)){let m=f.findIndex(p=>zi(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=>zi(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(oo)){let o=au(e,"hooks",r);try{LL(o,HL.R_OK),jL(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=fr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(iu(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();Xv(r,JSON.stringify(o,null,2)+`
`,"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 mr(t,e){let n=cu[t];return e&&n?je(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var me,eE,cu,uW,lW,tE=X(()=>{"use strict";jn();me={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",AFTER_MODEL:"AfterModel",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},eE="mcp__(?!.*context-mode)",cu={[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"},uW=[me.BEFORE_TOOL,me.SESSION_START],lW=[me.AFTER_TOOL,me.AFTER_MODEL,me.PRE_COMPRESS]});var oE={};Me(oE,{GeminiCLIAdapter:()=>_h});import{readFileSync as yh,writeFileSync as nE,mkdirSync as UL,accessSync as FL,chmodSync as ZL,existsSync as BL,constants as qL}from"node:fs";import{resolve as Hi,join as rE}from"node:path";import{homedir as uu}from"node:os";var _h,sE=X(()=>{"use strict";et();tE();_h=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 Hi(uu(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[me.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:mr(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|${eE}`,hooks:[{type:"command",command:mr(me.BEFORE_TOOL,e)}]}],[me.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:mr(me.AFTER_TOOL,e)}]}],[me.AFTER_MODEL]:[{matcher:"",hooks:[{type:"command",command:mr(me.AFTER_MODEL,e)}]}],[me.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:mr(me.PRE_COMPRESS,e)}]}],[me.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:mr(me.SESSION_START,e)}]}]}}readSettings(){try{let e=yh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Hi(uu(),".gemini");UL(n,{recursive:!0}),nE(this.getSettingsPath(),JSON.stringify(e,null,2)+`
`,"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(cu).map(([n,r])=>{let o=rE(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>BL(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=Hi(uu(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(yh(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:mr(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=rE(e,"hooks","gemini-cli");for(let o of Object.values(cu)){let s=Hi(r,o);try{FL(s,qL.R_OK),ZL(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Hi(uu(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(yh(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),nE(r,JSON.stringify(o,null,2)+`
`,"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}`}}});function Ui(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]!==`
`;)c++;c<t.length&&(e+=`
`);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]===`
`);)l++;if(e[l]==="}"||e[l]==="]")continue}s+=u}return s}function zn(t){for(let e of[t,Ui(t)])try{return JSON.parse(e)}catch{}}var Fi=X(()=>{"use strict"});var io,_W,bW,iE=X(()=>{"use strict";io={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},_W=[io.BEFORE,io.AFTER],bW=[io.COMPACTING]});var cE={};Me(cE,{OpenCodeAdapter:()=>bh});import{readFileSync as aE,writeFileSync as VL,mkdirSync as WL,copyFileSync as KL,accessSync as GL,existsSync as JL,constants as XL}from"node:fs";import{resolve as $t,join as Hn}from"node:path";import{homedir as hr}from"node:os";var bh,uE=X(()=>{"use strict";et();Fi();iE();bh=class extends ye{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let 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=$t(`${this.platform}.jsonc`);return JL(e)?e:$t(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[$t("kilo.jsonc"),$t("kilo.json"),$t(".kilo","kilo.jsonc"),$t(".kilo","kilo.json"),$t(".kilocode","kilo.jsonc"),$t(".kilocode","kilo.json"),Hn(hr(),".config","kilo","kilo.jsonc"),Hn(hr(),".config","kilo","kilo.json")]:[$t("opencode.jsonc"),$t("opencode.json"),$t(".opencode","opencode.jsonc"),$t(".opencode","opencode.json"),Hn(hr(),".config","opencode","opencode.jsonc"),Hn(hr(),".config","opencode","opencode.json")]}getSessionDir(){let e=it(),n=e?Hn(e,"context-mode","sessions"):Hn(this.getConfigDir(),"context-mode","sessions");return WL(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Hn(hr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Hn(hr(),".config"),Hn(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[io.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[io.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[io.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),n=new Set(e.filter(s=>s.includes(hr()))),r=null,o;for(let s of e)try{let i=aE(s,"utf-8"),a=s.endsWith(".jsonc")?Ui(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){VL(this.getSettingsPath(),JSON.stringify(e,null,2)+`
`,"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)?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)&&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:"SessionStart hook",status:"pass",message:"SessionStart via experimental.chat.system.transform surrogate (native hook pending #14808, #5409)"}),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=$t(hr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(aE(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}return"not installed"}configureAllHooks(e){let n=this.readSettings()??{},r=[],o=n.plugin??[];o.some(i=>i.includes("context-mode"))?r.push("context-mode already in plugin array"):(o.push("context-mode"),r.push("Added context-mode to plugin array")),n.plugin=o;let s=n.mcp;if(s&&typeof s=="object"&&!Array.isArray(s)){let i=s;Object.prototype.hasOwnProperty.call(i,"context-mode")&&(delete i["context-mode"],r.push("Removed legacy context-mode MCP block (plugin-native tools)")),Object.keys(i).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{GL(this.settingsPath,XL.R_OK);let n=this.settingsPath+".bak";return KL(this.settingsPath,n),n}catch{return null}}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}hasContextModePlugin(e){let n=e.plugin;return Array.isArray(n)&&n.some(r=>typeof r=="string"&&r.includes("context-mode"))}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 ao,RW,PW,lE=X(()=>{"use strict";ao={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},RW=[ao.TOOL_CALL_BEFORE,ao.TOOL_CALL_AFTER],PW=[ao.COMMAND_NEW]});var dE={};Me(dE,{OpenClawAdapter:()=>vh});import{readFileSync as xh,writeFileSync as YL,copyFileSync as QL,accessSync as ez,constants as tz}from"node:fs";import{resolve as Un,join as kh}from"node:path";import{homedir as Sh}from"node:os";var vh,pE=X(()=>{"use strict";et();lE();vh=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 Un("openclaw.json")}getConfigDir(e){return Un(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return kh(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[ao.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ao.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ao.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Un("openclaw.json"),Un(".openclaw","openclaw.json"),kh(Sh(),".openclaw","openclaw.json")];for(let n of e)try{let r=xh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Un("openclaw.json");YL(n,JSON.stringify(e,null,2)+`
`,"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=Un(Sh(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(xh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Un("node_modules","context-mode","package.json"),n=JSON.parse(xh(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=[Un("openclaw.json"),Un(".openclaw","openclaw.json"),kh(Sh(),".openclaw","openclaw.json")];for(let n of e)try{ez(n,tz.R_OK);let r=n+".bak";return QL(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 fE}from"node:os";import{resolve as Eh}from"node:path";function mE(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?Eh(fE(),t.replace(/^~[/\\]?/,"")):Eh(t):Eh(fE(),".codex")}var hE=X(()=>{"use strict"});var vE={};Me(vE,{CodexAdapter:()=>Rh,parseCodexContextModePluginRoot:()=>du,probeCodexCliVersion:()=>kE});import{execFileSync as xE}from"node:child_process";import{existsSync as nz,readFileSync as ds,writeFileSync as gE,accessSync as rz,copyFileSync as oz,constants as sz,mkdirSync as wh}from"node:fs";import{resolve as lu,dirname as Th,join as Fn}from"node:path";import{fileURLToPath as iz}from"node:url";function kE(t=xE){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 du(t){for(let e of t.split(/\r?\n/)){let n=e.match(/^\s*context-mode@context-mode\s+installed,\s+enabled\s+\S+\s+(.+?)\s*$/);if(n?.[1])return n[1].trim()}return null}function pu(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(`
`):null}function SE(t){let e=pu(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function uz(t){let e=pu(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function yE(t){let e=pu(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function _E(t){return pu(t,"mcp_servers.context-mode")!==null}function lz(t){if(SE(t))return{text:t,changed:!1};let e=t.includes(`\r
`)?`\r
`:`
`,n=t.split(/\r?\n/),r=n.findIndex(s=>/^\s*\[features\]\s*(?:#.*)?$/.test(s));if(r===-1){let s=t.length>0&&!t.endsWith(`
`)?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 bE(t,e){let n=t.includes(`\r
`)?`\r
`:`
`,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 dz(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 az,co,cz,Rh,Ph=X(()=>{"use strict";et();Sn();hE();az="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__",co={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"},cz={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"]};Rh=class extends ye{codexPluginListRunner;constructor(e={}){super([".codex"]),this.codexPluginListRunner=e.codexPluginListRunner??xE}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 mE()}getSettingsPath(){return Fn(this.getConfigDir(),"config.toml")}getSessionDir(){let e=it(),n=e?Fn(e,"context-mode","sessions"):Fn(this.getConfigDir(),"context-mode","sessions");return wh(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=it(),r=n?Fn(n,"context-mode","memories"):Fn(this.getConfigDir(),"memories");return e?Fn(r,Qe(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:az,hooks:[{type:"command",command:co.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:co.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:co.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:co.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:co.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:co.Stop}]}]}}readSettings(){try{return{_raw_toml:ds(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=kE(),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=ds(this.getSettingsPath(),"utf-8"),s=!0;let m=SE(o),p=!m&&uz(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:"context-mode@context-mode is enabled, but `codex plugin list` did not report its runtime root",fix:"Restart Codex or verify `codex plugin list` shows context-mode@context-mode 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 ${Fn(m,".codex-plugin","hooks.json")} is missing`,fix:"Reinstall or upgrade the context-mode Codex plugin"})}c&&_E(o)&&n.push({check:"Standalone MCP duplicate",status:"warn",message:"[mcp_servers.context-mode] is still registered while context-mode@context-mode 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 context-mode@context-mode 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 context-mode@context-mode plugin`})):Object.entries(i).map(([m,p])=>{let h=l.config.hooks?.[m],g=p[0],y=Array.isArray(h)&&h.some(b=>this.isExpectedHookEntry(m,b,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=ds(this.getSettingsPath(),"utf-8"),n=yE(e),r=_E(e),o=e.includes("[mcp_servers]")||e.includes("[mcp_servers.");return n&&r?{check:"MCP registration",status:"warn",message:"context-mode@context-mode plugin is enabled, but standalone [mcp_servers.context-mode] is also configured",fix:"context-mode upgrade"}:n?{check:"MCP registration",status:"pass",message:"context-mode@context-mode 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=ds(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=lz(s).text,m=f!==s;if(a){let p=bE(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
`)?`\r
`:`
`,h=f.endsWith(`
`)?f:`${f}${p}`;wh(Th(o),{recursive:!0}),gE(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{rz(n,sz.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=lu(Th(iz(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return ds(e,"utf-8")}catch{return`# context-mode
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 Fn(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return oz(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(ds(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();wh(Th(n),{recursive:!0}),gE(n,JSON.stringify(e,null,2)+`
`,"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 nz(Fn(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&yE(n),s=lu(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 du(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(lu(e))===this.normalizeCommand(lu(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 bE(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=dz(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(co[e]??""),s=cz[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 EE,writeFileSync as pz,mkdirSync as fz,accessSync as mz,chmodSync as hz,constants as gz}from"node:fs";import{resolve as fu,join as yz}from"node:path";var gr,mu=X(()=>{"use strict";et();gr=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 fu(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=EE(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=EE(fu(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();fz(fu(".github","hooks"),{recursive:!0}),pz(n,JSON.stringify(e,null,2)+`
`,"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=yz(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=fu(r,o);try{mz(s,gz.R_OK),hz(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function wE(t,e){if(!Ch[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Bt,Ch,GW,JW,TE=X(()=>{"use strict";Bt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Ch={[Bt.PRE_TOOL_USE]:"pretooluse.mjs",[Bt.POST_TOOL_USE]:"posttooluse.mjs",[Bt.PRE_COMPACT]:"precompact.mjs",[Bt.SESSION_START]:"sessionstart.mjs"},GW=[Bt.PRE_TOOL_USE,Bt.SESSION_START],JW=[Bt.POST_TOOL_USE,Bt.PRE_COMPACT]});var PE={};Me(PE,{VSCodeCopilotAdapter:()=>Ih});import{readFileSync as $h,mkdirSync as RE,accessSync as _z,existsSync as bz,constants as xz}from"node:fs";import{resolve as ps,join as Zi}from"node:path";import{homedir as Oh}from"node:os";var Ih,CE=X(()=>{"use strict";mu();et();TE();Ih=class extends gr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Bt,HOOK_SCRIPTS:Ch,buildHookCommand:wE};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=it();if(e){let s=Zi(e,"context-mode","sessions");return RE(s,{recursive:!0}),s}let n=ps(".github","context-mode","sessions"),r=Zi(Oh(),".vscode","context-mode","sessions"),o=bz(ps(".github"))?n:r;return RE(o,{recursive:!0}),o}getConfigDir(e){return ps(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=ps(".github","hooks");try{_z(r,xz.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=ps(r,"context-mode.json");try{let s=$h(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Bt.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?.[Bt.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=ps(".vscode","mcp.json"),n=$h(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=[Zi(Oh(),".vscode","extensions"),Zi(Oh(),".vscode-insiders","extensions")];for(let n of e)try{let r=$h(Zi(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 $E(t,e){if(!Ah[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,Ah,oK,sK,OE=X(()=>{"use strict";qt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Ah={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},oK=[qt.PRE_TOOL_USE,qt.SESSION_START],sK=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var IE={};Me(IE,{JetBrainsCopilotAdapter:()=>Nh});import{readFileSync as kz}from"node:fs";import{resolve as Sz}from"node:path";var Nh,AE=X(()=>{"use strict";mu();OE();Nh=class extends gr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Ah,buildHookCommand:$E};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 Sz(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=kz(this.getSettingsPath(),"utf-8"),s=JSON.parse(r).hooks;s?.[qt.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?.[qt.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 NE(t,e){let n=Mh[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var dt,Mh,pK,fK,ME=X(()=>{"use strict";dt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Mh={[dt.PRE_TOOL_USE]:"pretooluse.mjs",[dt.POST_TOOL_USE]:"posttooluse.mjs",[dt.PRE_COMPACT]:"precompact.mjs",[dt.SESSION_START]:"sessionstart.mjs",[dt.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[dt.STOP]:"stop.mjs"},pK=[dt.PRE_TOOL_USE,dt.SESSION_START],fK=[dt.POST_TOOL_USE,dt.PRE_COMPACT,dt.USER_PROMPT_SUBMIT,dt.STOP]});var UE={};Me(UE,{CopilotCliAdapter:()=>jh,copilotCliHome:()=>gu,copilotCliMcpConfigPath:()=>hu});import{existsSync as DE,mkdirSync as jE,readFileSync as Dh,writeFileSync as vz}from"node:fs";import{homedir as LE}from"node:os";import{dirname as Ez,join as fs,resolve as HE}from"node:path";function zE(){return process.env[wz]==="1"}function Tz(t){return HE(t,"configs","copilot-cli","hooks.json")}function Rz(t){return zn(Dh(t,"utf-8"))??{}}function Pz(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function gu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?fs(LE(),t.replace(/^~[/\\]?/,"")):HE(t):fs(LE(),".copilot")}function hu(){return fs(gu(),"mcp-config.json")}var wz,jh,FE=X(()=>{"use strict";mu();et();Fi();ME();wz="CONTEXT_MODE_COPILOT_PLUGIN";jh=class extends gr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:dt,HOOK_SCRIPTS:Mh,buildHookCommand:NE};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 fs(gu(),"hooks","context-mode.json")}getConfigDir(e){return gu()}getSessionDir(){let e=it(),n=e?fs(e,"context-mode","sessions"):fs(this.getConfigDir(),"context-mode","sessions");return jE(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();jE(Ez(n),{recursive:!0}),vz(n,JSON.stringify(e,null,2)+`
`,"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=Dh(this.getSettingsPath(),"utf-8");return zn(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=zE(),o=r?Tz(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=Rz(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(dt)){let l=Pz(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(zE())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Dh(hu(),"utf-8");return"context-mode"in((zn(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 ${hu()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return DE(hu())||DE(this.getSettingsPath())?"standalone":"not installed"}}});function Bi(t,e){let n=Lh[e],r=Vt(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 Vt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,Lh,Cz,$z,zh,ZE,BE,qE=X(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Lh={[_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"},Cz="MCP:(?!ctx_)",$z=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",Cz],zh=$z.join("|"),ZE=[_e.PRE_TOOL_USE],BE=[_e.POST_TOOL_USE]});var JE={};Me(JE,{CursorAdapter:()=>Hh});import{readFileSync as yu,writeFileSync as Oz,mkdirSync as Iz,accessSync as VE,chmodSync as Az,constants as WE,existsSync as KE,readdirSync as Nz}from"node:fs";import{execSync as Mz}from"node:child_process";import{resolve as uo,join as lo}from"node:path";import{homedir as _u}from"node:os";var GE,Hh,XE=X(()=>{"use strict";et();so();qE();GE="/Library/Application Support/Cursor/hooks.json",Hh=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 uo(".cursor","hooks.json")}getConfigDir(e){return uo(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Vt(_e.PRE_TOOL_USE),matcher:zh,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Vt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Vt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Vt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Vt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=yu(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();Iz(uo(".cursor"),{recursive:!0}),Oz(n,JSON.stringify(e,null,2)+`
`,"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 ZE){let a=s[i],c=Array.isArray(a)&&a.some(u=>Bi(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 BE){let a=s[i],c=Array.isArray(a)&&a.some(u=>Bi(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`})}}KE(GE)&&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=>Bi(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=[lo(_u(),".cursor","plugins","local"),lo(_u(),".cursor","plugins","cache")],n=[];for(let r of e){try{VE(r,WE.F_OK)}catch{continue}let o=[];try{o=Nz(r)}catch{continue}for(let s of o){let i=lo(r,s,".cursor-plugin","plugin.json");try{let a=yu(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[uo(".cursor","mcp.json"),lo(_u(),".cursor","mcp.json")];for(let r of e)try{let o=yu(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 Mz("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:Vt(_e.PRE_TOOL_USE),matcher:zh,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.POST_TOOL_USE,{type:"command",command:Vt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.SESSION_START,{type:"command",command:Vt(_e.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.STOP,{type:"command",command:Vt(_e.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Vt(_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=lo(e,"hooks","cursor");for(let o of Object.values(Lh)){let s=uo(r,o);try{VE(s,WE.R_OK),Az(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),lo(_u(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(GE),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=yu(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[uo(".claude","settings.json"),uo(".claude","settings.local.json"),lo(Ct(),"settings.json")].some(n=>KE(n))}upsertHookEntry(e,n,r,o){let s=e[n],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>Bi(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 QE={};Me(QE,{AntigravityAdapter:()=>qi});import{readFileSync as bu,writeFileSync as Dz,mkdirSync as jz}from"node:fs";import{resolve as xu,dirname as YE}from"node:path";import{fileURLToPath as Lz}from"node:url";import{homedir as Uh}from"node:os";var qi,Fh=X(()=>{"use strict";et();qi=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 xu(Uh(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return xu(Uh(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=bu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();jz(YE(n),{recursive:!0}),Dz(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=bu(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=xu(Uh(),".gemini","extensions","context-mode","package.json");return JSON.parse(bu(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=xu(YE(Lz(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return bu(e,"utf-8")}catch{return`# context-mode
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 cw={};Me(cw,{AntigravityCliAdapter:()=>Kh,antigravityCliConfigDir:()=>iw,antigravityCliHooksPath:()=>Bh,antigravityCliMcpConfigPath:()=>sw,antigravityCliPluginDir:()=>vu});import{mkdirSync as zz,readFileSync as ku,writeFileSync as Hz}from"node:fs";import{dirname as Uz,resolve as po}from"node:path";import{homedir as Su}from"node:os";function sw(){return po(Su(),".gemini","config","mcp_config.json")}function iw(){return po(Su(),".gemini","antigravity-cli")}function Bh(){return po(Su(),".gemini","config","hooks.json")}function vu(){return po(Su(),".gemini","config","plugins","context-mode")}function Fz(){return po(vu(),"mcp_config.json")}function Zz(){return po(vu(),"hooks.json")}function ew(t){for(let e of t)try{if("context-mode"in((zn(ku(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function vn(t){return t&&typeof t=="object"?t:{}}function tw(t){let e=vn(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 nw(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function aw(t,e){let n=vn(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>vn(o).command===e)}function rw(t,e){return JSON.stringify(t).includes(e)}function Bz(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function ow(t,e){return Array.isArray(t)&&t.some(n=>aw(n,e))}function qz(t){return Array.isArray(t)&&t.some(e=>{let n=vn(e);return Bz(n.matcher)&&aw(e,qh)})}function Vz(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(zn(ku(n,"utf-8"))??{}).hooks??{},s=qz(o.PreToolUse),i=ow(o.PostToolUse,Vh),a=ow(o.Stop,Wh);(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 Kz(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 Zh(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=>!rw(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!rw(a,r)),n],!0)}var qh,Wz,Vh,Wh,Kh,uw=X(()=>{"use strict";Fh();Fi();qh="context-mode hook antigravity-cli pretooluse",Wz="run_command|view_file|grep_search|web_fetch|read_url_content",Vh="context-mode hook antigravity-cli posttooluse",Wh="context-mode hook antigravity-cli stop";Kh=class extends qi{name="Antigravity CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};getSettingsPath(){return sw()}getConfigDir(e){return iw()}parsePreToolUseInput(e){let n=vn(e),r=vn(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:vn(r.args),sessionId:nw(n),projectDir:tw(n),raw:e}}parsePostToolUseInput(e){let n=vn(e),r=vn(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:vn(r.args),toolOutput:o,isError:o.length>0,sessionId:nw(n),projectDir:tw(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:Kz(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=ew([Fz(),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=zn(ku(po(vu(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return ew([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=Bh(),o={};try{o=zn(ku(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:Wz,hooks:[{type:"command",command:qh}]},a={matcher:"",hooks:[{type:"command",command:Vh}]},c={matcher:"",hooks:[{type:"command",command:Wh}]},u=Zh(s,"PreToolUse",i,qh),l=Zh(s,"PostToolUse",a,Vh),d=Zh(s,"Stop",c,Wh);return(u||l||d)&&(o.hooks=s,zz(Uz(r),{recursive:!0}),Hz(r,JSON.stringify(o,null,2)+`
`,"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}=Vz([Zz(),Bh()]),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 Eu(t,e){let n=lw[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ms(t,e){let n=lw[t];return e&&n?je(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,lw,Gz,Jz,Gh,UK,FK,dw=X(()=>{"use strict";jn();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},lw={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},Gz="@(?!context-mode/)",Jz=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",Gz],Gh=Jz.join("|"),UK=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],FK=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var hw={};Me(hw,{KiroAdapter:()=>Jh});import{readFileSync as hs,writeFileSync as pw,mkdirSync as fw}from"node:fs";import{resolve as fo,dirname as mw}from"node:path";import{fileURLToPath as Xz}from"node:url";import{homedir as wu}from"node:os";var Jh,gw=X(()=>{"use strict";et();dw();Jh=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 fo(wu(),".kiro","settings","mcp.json")}getConfigDir(e){return fo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:Gh,hooks:[{type:"command",command:ms(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ms(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ms(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ms(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=hs(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();fw(mw(n),{recursive:!0}),pw(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=fo(wu(),".kiro","agents","default.json");try{let s=JSON.parse(hs(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>Eu(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=>Eu(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=hs(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=fo(wu(),".kiro","extensions","context-mode","package.json");return JSON.parse(hs(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=fo(wu(),".kiro","agents"),o=fo(r,"default.json");try{fw(r,{recursive:!0});let s={};try{s=JSON.parse(hs(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,Gh],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>Eu(d,c))||(l.push({matcher:u,command:ms(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,pw(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=fo(mw(Xz(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return hs(e,"utf-8")}catch{return`# context-mode
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 bw={};Me(bw,{ZedAdapter:()=>Yh});import{readFileSync as Xh,writeFileSync as Yz,mkdirSync as Qz}from"node:fs";import{resolve as yw,dirname as _w}from"node:path";import{fileURLToPath as e1}from"node:url";import{homedir as t1}from"node:os";var Yh,xw=X(()=>{"use strict";et();Yh=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 yw(t1(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Xh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();Qz(_w(n),{recursive:!0}),Yz(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=Xh(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=yw(_w(e1(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Xh(e,"utf-8")}catch{return`# context-mode
Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var Qh,kw=X(()=>{"use strict";Qh="mcp__(?!.*context-mode)"});var Ew={};Me(Ew,{QwenCodeAdapter:()=>eg});import{readFileSync as n1,writeFileSync as r1,existsSync as o1}from"node:fs";import{resolve as Sw,join as s1}from"node:path";import{homedir as vw}from"node:os";var eg,ww=X(()=>{"use strict";ch();kw();jn();eg=class extends cs{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 Sw(vw(),".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",Qh].join("|"),hooks:[{type:"command",command:je(`${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:je(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:je(`${e}/hooks/qwen-code/stop.mjs`)}]}]}}readSettings(){try{let e=n1(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){r1(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?o1(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",Qh].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:je(`${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:Sw(s1(vw(),".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 Tw={};Me(Tw,{OMPAdapter:()=>rg});import{readFileSync as tg,writeFileSync as i1,mkdirSync as a1}from"node:fs";import{resolve as ng,dirname as c1}from"node:path";import{homedir as u1}from"node:os";var rg,Rw=X(()=>{"use strict";et();rg=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??ng(u1(),".omp","agent")}getSettingsPath(){return ng(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=tg(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();a1(c1(n),{recursive:!0}),i1(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=tg(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=ng(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(tg(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
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 Pw={};Me(Pw,{PiAdapter:()=>ag});import{readFileSync as og,writeFileSync as l1,mkdirSync as d1}from"node:fs";import{resolve as sg,dirname as p1}from"node:path";import{homedir as ig}from"node:os";var ag,Cw=X(()=>{"use strict";et();ag=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 sg(ig(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=og(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();d1(p1(n),{recursive:!0}),l1(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=sg(ig(),".pi","extensions","context-mode","package.json");try{return JSON.parse(og(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=sg(ig(),".pi","extensions","context-mode","package.json");return JSON.parse(og(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){return`# context-mode
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 $w}from"node:os";import{resolve as cg,join as x6}from"node:path";function Ow(){let t=process.env.KIMI_CODE_HOME;return t?t.startsWith("~")?cg($w(),t.replace(/^~[/\\]?/,"")):cg(t):cg($w(),".kimi-code")}var Iw=X(()=>{"use strict"});var jw={};Me(jw,{KimiAdapter:()=>lg,probeKimiCliVersion:()=>Dw});import{execFileSync as f1}from"node:child_process";import{readFileSync as Vi,writeFileSync as m1,accessSync as h1,copyFileSync as g1,constants as y1,mkdirSync as Aw}from"node:fs";import{resolve as _1,dirname as Nw,join as mo}from"node:path";import{fileURLToPath as b1}from"node:url";function Dw(t=f1){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 Mw(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 S1(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(`
`)}function ug(t){return t.command.includes("context-mode hook kimi")}function v1(t,e){let n=(e.hooks?.[0]?.command??"").trim();return n?{event:t,matcher:e.matcher||void 0,command:n,timeout:30}:null}var x1,yr,k1,lg,Lw=X(()=>{"use strict";et();Sn();Iw();x1="Bash|Shell|Read|Edit|Write|WebFetch|Agent|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",yr={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"},k1={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"]};lg=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 Ow()}getSettingsPath(){return mo(this.getConfigDir(),"config.toml")}getMcpPath(){return mo(this.getConfigDir(),"mcp.json")}getSessionDir(){let e=it(),n=e?mo(e,"context-mode","sessions"):mo(this.getConfigDir(),"context-mode","sessions");return Aw(n,{recursive:!0}),n}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(e){let n=it(),r=n?mo(n,"context-mode","memory"):mo(this.getConfigDir(),"memory");return e?mo(r,Qe(e)):r}generateHookConfig(e){return{PreToolUse:[{matcher:x1,hooks:[{type:"command",command:yr.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:yr.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:yr.SessionStart}]}],SessionEnd:[{matcher:"",hooks:[{type:"command",command:yr.SessionEnd}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:yr.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:yr.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:yr.Stop}]}]}}readSettings(){try{return{_raw_toml:Vi(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let n=[],r=Dw();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=Vi(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=Mw(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&&ug(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=Vi(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=Vi(this.getSettingsPath(),"utf-8")}catch{o=""}let s=Mw(o),i=s.filter(l=>!ug(l)),a=[];for(let[l,d]of Object.entries(r)){let f=v1(l,d[0]);f&&a.push(f)}let c=s.some(ug),u=this.rebuildToml(o,i,a);return u!==o&&(Aw(Nw(this.getSettingsPath()),{recursive:!0}),m1(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{h1(n,y1.R_OK);let r=this.backupFile(n);e??=r}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=_1(Nw(b1(import.meta.url)),"..","..","..","configs","kimi","AGENTS.md");try{return Vi(e,"utf-8")}catch{return`# context-mode
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 g1(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=(yr[e]??"").replace(/\\/g,"/"),s=k1[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(S1(c)),s.push("");return s.join(`
`)}}});var pg={};Me(pg,{PLATFORM_ENV_VARS:()=>gs,__resetClaudeCodePluginCacheForTests:()=>T1,__seedClaudeCodePluginCacheMissForTests:()=>R1,detectPlatform:()=>Et,foreignIdentificationEnv:()=>O1,foreignWorkspaceEnv:()=>$1,getAdapter:()=>I1,getEnvVarNames:()=>C1,getSessionDirSegments:()=>Wi,workspaceEnvVarsFor:()=>dg});import{existsSync as qe,readFileSync as E1}from"node:fs";import{resolve as Ae}from"node:path";import{homedir as zw}from"node:os";function w1(){if(ho!==null)return ho!=="miss"&&ho.hasCM;try{let t=Ae(zw(),".claude","plugins","installed_plugins.json"),e=E1(t,"utf-8"),n=JSON.parse(e),o=[...Object.keys(n.plugins??{}),...Object.keys(n.enabledPlugins??{})].some(s=>s.includes("context-mode"));return ho={hasCM:o},o}catch{return ho="miss",!1}}function T1(){ho=null}function R1(){ho="miss"}function C1(t){return(gs.get(t)??[]).map(e=>e.name)}function dg(t){return(gs.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function $1(t){let e=new Set;for(let[n,r]of gs)if(n!==t)for(let o of r)o.role==="workspace"&&e.add(o.name);return e}function O1(t){let e=new Set;for(let[n,r]of gs)if(n!==t)for(let o of r)o.role==="identification"&&e.add(o.name);return e}function Wi(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 Et(t){if(t?.name){let s=Tv[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 gs)if(i.some(a=>a.detect!==!1&&process.env[a.name]))return s==="vscode-copilot"&&w1()?{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=zw(),r=(()=>{let s=process.env.COPILOT_HOME;return s&&s.trim()!==""?s.startsWith("~")?Ae(n,s.replace(/^~[/\\]?/,"")):Ae(s):Ae(n,".copilot")})(),o=qe(Ae(r,"mcp-config.json"))||qe(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)"}:qe(Ae(n,".local","bin","agy"))||qe(Ae(n,".gemini","antigravity-cli"))||qe(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)"}:qe(Ae(n,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:qe(Ae(n,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:qe(Ae(n,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:qe(Ae(n,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:qe(Ae(n,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:qe(Ae(n,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:qe(Ae(n,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:qe(Ae(n,".kimi-code"))?{platform:"kimi",confidence:"medium",reason:"~/.kimi-code/ directory exists"}:qe(Ae(n,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:qe(Ae(n,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:qe(Ae(n,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:qe(Ae(n,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:qe(Ae(n,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:qe(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 I1(t){let e=t??Et().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(gh(),hh));return new n}case"gemini-cli":{let{GeminiCLIAdapter:n}=await Promise.resolve().then(()=>(sE(),oE));return new n}case"kilo":case"opencode":{let{OpenCodeAdapter:n}=await Promise.resolve().then(()=>(uE(),cE));return new n(e)}case"openclaw":{let{OpenClawAdapter:n}=await Promise.resolve().then(()=>(pE(),dE));return new n}case"codex":{let{CodexAdapter:n}=await Promise.resolve().then(()=>(Ph(),vE));return new n}case"vscode-copilot":{let{VSCodeCopilotAdapter:n}=await Promise.resolve().then(()=>(CE(),PE));return new n}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:n}=await Promise.resolve().then(()=>(AE(),IE));return new n}case"copilot-cli":{let{CopilotCliAdapter:n}=await Promise.resolve().then(()=>(FE(),UE));return new n}case"cursor":{let{CursorAdapter:n}=await Promise.resolve().then(()=>(XE(),JE));return new n}case"antigravity":{let{AntigravityAdapter:n}=await Promise.resolve().then(()=>(Fh(),QE));return new n}case"antigravity-cli":{let{AntigravityCliAdapter:n}=await Promise.resolve().then(()=>(uw(),cw));return new n}case"kiro":{let{KiroAdapter:n}=await Promise.resolve().then(()=>(gw(),hw));return new n}case"zed":{let{ZedAdapter:n}=await Promise.resolve().then(()=>(xw(),bw));return new n}case"qwen-code":{let{QwenCodeAdapter:n}=await Promise.resolve().then(()=>(ww(),Ew));return new n}case"omp":{let{OMPAdapter:n}=await Promise.resolve().then(()=>(Rw(),Tw));return new n}case"pi":{let{PiAdapter:n}=await Promise.resolve().then(()=>(Cw(),Pw));return new n}case"kimi":{let{KimiAdapter:n}=await Promise.resolve().then(()=>(Lw(),jw));return new n}default:{let{ClaudeCodeAdapter:n}=await Promise.resolve().then(()=>(gh(),hh));return new n}}}var ho,P1,gs,ys=X(()=>{"use strict";Rv();ho=null;P1=[["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"}]]],gs=new Map(P1)});import{resolve as Ki}from"node:path";import{homedir as fg}from"node:os";function Ct(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Ki(fg(),e.replace(/^~[/\\]?/,"")):Ki(e):Ki(fg(),".claude")}function A1(t=process.env){return Ki(Ct(t),"settings.json")}function mg(t=process.env){let e=[],n=Et();if(n.platform!=="claude-code"){let o=Wi(n.platform);o&&o.length>0&&e.push(Ki(fg(),...o,"settings.json"))}let r=A1(t);return e.includes(r)||e.push(r),e}var so=X(()=>{"use strict";ys()});var $={};Me($,{BRAND:()=>NR,DIRTY:()=>xr,EMPTY_PATH:()=>pR,INVALID:()=>B,NEVER:()=>yP,OK:()=>nt,ParseStatus:()=>We,Schema:()=>Q,ZodAny:()=>Kn,ZodArray:()=>$n,ZodBigInt:()=>Sr,ZodBoolean:()=>vr,ZodBranded:()=>Rs,ZodCatch:()=>Nr,ZodDate:()=>Er,ZodDefault:()=>Ar,ZodDiscriminatedUnion:()=>ca,ZodEffects:()=>At,ZodEnum:()=>Or,ZodError:()=>ht,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>la,ZodIntersection:()=>Pr,ZodIssueCode:()=>E,ZodLazy:()=>Cr,ZodLiteral:()=>$r,ZodMap:()=>Eo,ZodNaN:()=>To,ZodNativeEnum:()=>Ir,ZodNever:()=>Gt,ZodNull:()=>Tr,ZodNullable:()=>pn,ZodNumber:()=>kr,ZodObject:()=>yt,ZodOptional:()=>gt,ZodParsedType:()=>A,ZodPipeline:()=>Ps,ZodPromise:()=>Gn,ZodReadonly:()=>Mr,ZodRecord:()=>ua,ZodSchema:()=>Q,ZodSet:()=>wo,ZodString:()=>Wn,ZodSymbol:()=>So,ZodTransformer:()=>At,ZodTuple:()=>dn,ZodType:()=>Q,ZodUndefined:()=>wr,ZodUnion:()=>Rr,ZodUnknown:()=>Cn,ZodVoid:()=>vo,addIssueToContext:()=>C,any:()=>ZR,array:()=>WR,bigint:()=>LR,boolean:()=>cy,coerce:()=>gP,custom:()=>sy,date:()=>zR,datetimeRegex:()=>ry,defaultErrorMap:()=>Rn,discriminatedUnion:()=>JR,effect:()=>cP,enum:()=>sP,function:()=>nP,getErrorMap:()=>bo,getParsedType:()=>ln,instanceof:()=>DR,intersection:()=>XR,isAborted:()=>ia,isAsync:()=>xo,isDirty:()=>aa,isValid:()=>Vn,late:()=>MR,lazy:()=>rP,literal:()=>oP,makeIssue:()=>Ts,map:()=>eP,nan:()=>jR,nativeEnum:()=>iP,never:()=>qR,null:()=>FR,nullable:()=>lP,number:()=>ay,object:()=>il,objectUtil:()=>rl,oboolean:()=>hP,onumber:()=>mP,optional:()=>uP,ostring:()=>fP,pipeline:()=>pP,preprocess:()=>dP,promise:()=>aP,quotelessJson:()=>uR,record:()=>QR,set:()=>tP,setErrorMap:()=>dR,strictObject:()=>KR,string:()=>iy,symbol:()=>HR,transformer:()=>cP,tuple:()=>YR,undefined:()=>UR,union:()=>GR,unknown:()=>BR,util:()=>oe,void:()=>VR});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 rl;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(rl||(rl={}));var A=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ln=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"]),uR=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),ht=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()}};ht.create=t=>new ht(t);var lR=(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}},Rn=lR;var Yg=Rn;function dR(t){Yg=t}function bo(){return Yg}var Ts=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}},pR=[];function C(t,e){let n=bo(),r=Ts({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Rn?void 0:Rn].filter(o=>!!o)});t.common.issues.push(r)}var We=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 B;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 B;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}}},B=Object.freeze({status:"aborted"}),xr=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),ia=t=>t.status==="aborted",aa=t=>t.status==="dirty",Vn=t=>t.status==="valid",xo=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 It=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}},Qg=(t,e)=>{if(Vn(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 ht(t.common.issues);return this._error=n,this._error}}};function J(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 ln(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ln(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new We,ctx:{common:e.parent.common,data:e.data,parsedType:ln(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if(xo(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:ln(e)},o=this._parseSync({data:e,path:r.path,parent:r});return Qg(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ln(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return Vn(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=>Vn(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:ln(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await(xo(o)?o:Promise.resolve(o));return Qg(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 At({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 gt.create(this,this._def)}nullable(){return pn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $n.create(this)}promise(){return Gn.create(this,this._def)}or(e){return Rr.create([this,e],this._def)}and(e){return Pr.create(this,e,this._def)}transform(e){return new At({...J(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new Ar({...J(this._def),innerType:this,defaultValue:n,typeName:T.ZodDefault})}brand(){return new Rs({typeName:T.ZodBranded,type:this,...J(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new Nr({...J(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 Ps.create(this,e)}readonly(){return Mr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},fR=/^c[^\s-]{8,}$/i,mR=/^[0-9a-z]+$/,hR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gR=/^[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,yR=/^[a-z0-9_-]{21}$/i,_R=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bR=/^[-+]?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)?)??$/,xR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",ol,SR=/^(?:(?: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])$/,vR=/^(?:(?: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])$/,ER=/^(([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]))$/,wR=/^(([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])$/,TR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,RR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ty="((\\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])))",PR=new RegExp(`^${ty}$`);function ny(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 CR(t){return new RegExp(`^${ny(t)}$`)}function ry(t){let e=`${ty}T${ny(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 $R(t,e){return!!((e==="v4"||!e)&&SR.test(t)||(e==="v6"||!e)&&ER.test(t))}function OR(t,e){if(!_R.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 IR(t,e){return!!((e==="v4"||!e)&&vR.test(t)||(e==="v6"||!e)&&wR.test(t))}var Wn=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}),B}let r=new We,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")xR.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")ol||(ol=new RegExp(kR,"u")),ol.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")gR.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")yR.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")fR.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")mR.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")hR.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"?ry(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"?PR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{code:E.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?CR(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"?bR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"duration",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?$R(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"?OR(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"?IR(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"?TR.test(e.data)||(o=this._getOrReturnCtx(e,o),C(o,{validation:"base64",code:E.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?RR.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}};Wn.create=t=>new Wn({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...J(t)});function AR(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 kr=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}),B}let r,o=new We;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"?AR(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)}};kr.create=t=>new kr({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...J(t)});var Sr=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 We;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}),B}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}};Sr.create=t=>new Sr({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...J(t)});var vr=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}),B}return nt(e.data)}};vr.create=t=>new vr({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...J(t)});var Er=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}),B}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return C(s,{code:E.invalid_date}),B}let r=new We,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}};Er.create=t=>new Er({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...J(t)});var So=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}),B}return nt(e.data)}};So.create=t=>new So({typeName:T.ZodSymbol,...J(t)});var wr=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}),B}return nt(e.data)}};wr.create=t=>new wr({typeName:T.ZodUndefined,...J(t)});var Tr=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}),B}return nt(e.data)}};Tr.create=t=>new Tr({typeName:T.ZodNull,...J(t)});var Kn=class extends Q{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};Kn.create=t=>new Kn({typeName:T.ZodAny,...J(t)});var Cn=class extends Q{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};Cn.create=t=>new Cn({typeName:T.ZodUnknown,...J(t)});var Gt=class extends Q{_parse(e){let n=this._getOrReturnCtx(e);return C(n,{code:E.invalid_type,expected:A.never,received:n.parsedType}),B}};Gt.create=t=>new Gt({typeName:T.ZodNever,...J(t)});var vo=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}),B}return nt(e.data)}};vo.create=t=>new vo({typeName:T.ZodVoid,...J(t)});var $n=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}),B;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 It(n,i,n.path,a)))).then(i=>We.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new It(n,i,n.path,a)));return We.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)}};$n.create=(t,e)=>new $n({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...J(e)});function ko(t){if(t instanceof yt){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=gt.create(ko(r))}return new yt({...t._def,shape:()=>e})}else return t instanceof $n?new $n({...t._def,type:ko(t.element)}):t instanceof gt?gt.create(ko(t.unwrap())):t instanceof pn?pn.create(ko(t.unwrap())):t instanceof dn?dn.create(t.items.map(e=>ko(e))):t}var yt=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}),B}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gt&&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 It(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Gt){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 It(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=>We.mergeObjectSync(r,u)):We.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 ko(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 gt;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return oy(oe.objectKeys(this.shape))}};yt.create=(t,e)=>new yt({shape:()=>t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});yt.strictCreate=(t,e)=>new yt({shape:()=>t,unknownKeys:"strict",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});yt.lazycreate=(t,e)=>new yt({shape:t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});var Rr=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 ht(a.ctx.common.issues));return C(n,{code:E.invalid_union,unionErrors:i}),B}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 ht(c));return C(n,{code:E.invalid_union,unionErrors:a}),B}}get options(){return this._def.options}};Rr.create=(t,e)=>new Rr({options:t,typeName:T.ZodUnion,...J(e)});var Pn=t=>t instanceof Cr?Pn(t.schema):t instanceof At?Pn(t.innerType()):t instanceof $r?[t.value]:t instanceof Or?t.options:t instanceof Ir?oe.objectValues(t.enum):t instanceof Ar?Pn(t._def.innerType):t instanceof wr?[void 0]:t instanceof Tr?[null]:t instanceof gt?[void 0,...Pn(t.unwrap())]:t instanceof pn?[null,...Pn(t.unwrap())]:t instanceof Rs||t instanceof Mr?Pn(t.unwrap()):t instanceof Nr?Pn(t._def.innerType):[],ca=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}),B;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]}),B)}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=Pn(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,...J(r)})}};function sl(t,e){let n=ln(t),r=ln(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=sl(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=sl(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 Pr=class extends Q{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(ia(s)||ia(i))return B;let a=sl(s.value,i.value);return a.valid?((aa(s)||aa(i))&&n.dirty(),{status:n.value,value:a.data}):(C(r,{code:E.invalid_intersection_types}),B)};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}))}};Pr.create=(t,e,n)=>new Pr({left:t,right:e,typeName:T.ZodIntersection,...J(n)});var dn=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}),B;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"}),B;!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 It(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>We.mergeArray(n,i)):We.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};dn.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new dn({items:t,typeName:T.ZodTuple,rest:null,...J(e)})};var ua=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}),B;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new It(r,a,r.path,a)),value:i._parse(new It(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?We.mergeObjectAsync(n,o):We.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,...J(r)}):new t({keyType:Wn.create(),valueType:e,typeName:T.ZodRecord,...J(n)})}},Eo=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}),B;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,c],u)=>({key:o._parse(new It(r,a,r.path,[u,"key"])),value:s._parse(new It(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 B;(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 B;(u.status==="dirty"||l.status==="dirty")&&n.dirty(),a.set(u.value,l.value)}return{status:n.value,value:a}}}};Eo.create=(t,e,n)=>new Eo({valueType:e,keyType:t,typeName:T.ZodMap,...J(n)});var wo=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}),B;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 B;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 It(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)}};wo.create=(t,e)=>new wo({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...J(e)});var la=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}),B;function r(a,c){return Ts({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),Rn].filter(u=>!!u),issueData:{code:E.invalid_arguments,argumentsError:c}})}function o(a,c){return Ts({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,bo(),Rn].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 Gn){let a=this;return nt(async function(...c){let u=new ht([]),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 nt(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new ht([r(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new ht([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:dn.create(e).rest(Cn.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||dn.create([]).rest(Cn.create()),returns:n||Cn.create(),typeName:T.ZodFunction,...J(r)})}},Cr=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})}};Cr.create=(t,e)=>new Cr({getter:t,typeName:T.ZodLazy,...J(e)});var $r=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}),B}return{status:"valid",value:e.data}}get value(){return this._def.value}};$r.create=(t,e)=>new $r({value:t,typeName:T.ZodLiteral,...J(e)});function oy(t,e){return new Or({values:t,typeName:T.ZodEnum,...J(e)})}var Or=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}),B}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}),B}return nt(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})}};Or.create=oy;var Ir=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}),B}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}),B}return nt(e.data)}get enum(){return this._def.values}};Ir.create=(t,e)=>new Ir({values:t,typeName:T.ZodNativeEnum,...J(e)});var Gn=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}),B;let r=n.parsedType===A.promise?n.data:Promise.resolve(n.data);return nt(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};Gn.create=(t,e)=>new Gn({type:t,typeName:T.ZodPromise,...J(e)});var At=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 B;let c=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return c.status==="aborted"?B:c.status==="dirty"?xr(c.value):n.value==="dirty"?xr(c.value):c});{if(n.value==="aborted")return B;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?B:a.status==="dirty"?xr(a.value):n.value==="dirty"?xr(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"?B:(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"?B:(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(!Vn(i))return B;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>Vn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):B);oe.assertNever(o)}};At.create=(t,e,n)=>new At({schema:t,typeName:T.ZodEffects,effect:e,...J(n)});At.createWithPreprocess=(t,e,n)=>new At({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...J(n)});var gt=class extends Q{_parse(e){return this._getType(e)===A.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};gt.create=(t,e)=>new gt({innerType:t,typeName:T.ZodOptional,...J(e)});var pn=class extends Q{_parse(e){return this._getType(e)===A.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pn.create=(t,e)=>new pn({innerType:t,typeName:T.ZodNullable,...J(e)});var Ar=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}};Ar.create=(t,e)=>new Ar({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});var Nr=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 xo(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new ht(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new ht(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Nr.create=(t,e)=>new Nr({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});var To=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}),B}return{status:"valid",value:e.data}}};To.create=t=>new To({typeName:T.ZodNaN,...J(t)});var NR=Symbol("zod_brand"),Rs=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}},Ps=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"?B:s.status==="dirty"?(n.dirty(),xr(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"?B: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})}},Mr=class extends Q{_parse(e){let n=this._def.innerType._parse(e),r=o=>(Vn(o)&&(o.value=Object.freeze(o.value)),o);return xo(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Mr.create=(t,e)=>new Mr({innerType:t,typeName:T.ZodReadonly,...J(e)});function ey(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function sy(t,e={},n){return t?Kn.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=ey(e,r),c=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=ey(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Kn.create()}var MR={object:yt.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 DR=(t,e={message:`Input not instance of ${t.name}`})=>sy(n=>n instanceof t,e),iy=Wn.create,ay=kr.create,jR=To.create,LR=Sr.create,cy=vr.create,zR=Er.create,HR=So.create,UR=wr.create,FR=Tr.create,ZR=Kn.create,BR=Cn.create,qR=Gt.create,VR=vo.create,WR=$n.create,il=yt.create,KR=yt.strictCreate,GR=Rr.create,JR=ca.create,XR=Pr.create,YR=dn.create,QR=ua.create,eP=Eo.create,tP=wo.create,nP=la.create,rP=Cr.create,oP=$r.create,sP=Or.create,iP=Ir.create,aP=Gn.create,cP=At.create,uP=gt.create,lP=pn.create,dP=At.createWithPreprocess,pP=Ps.create,fP=()=>iy().optional(),mP=()=>ay().optional(),hP=()=>cy().optional(),gP={string:(t=>Wn.create({...t,coerce:!0})),number:(t=>kr.create({...t,coerce:!0})),boolean:(t=>vr.create({...t,coerce:!0})),bigint:(t=>Sr.create({...t,coerce:!0})),date:(t=>Er.create({...t,coerce:!0}))};var yP=B;var _P=Object.freeze({status:"aborted"});function S(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 On=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},da={};function Tt(t){return t&&Object.assign(da,t),da}var ie={};Me(ie,{BIGINT_FORMAT_RANGES:()=>ly,Class:()=>cl,NUMBER_FORMAT_RANGES:()=>hl,aborted:()=>jr,allowsEval:()=>pl,assert:()=>vP,assertEqual:()=>bP,assertIs:()=>kP,assertNever:()=>SP,assertNotEqual:()=>xP,assignProp:()=>dl,cached:()=>Os,captureStackTrace:()=>fa,cleanEnum:()=>DP,cleanRegex:()=>As,clone:()=>Rt,createTransparentProxy:()=>CP,defineLazy:()=>xe,esc:()=>Dr,escapeRegex:()=>Jn,extend:()=>IP,finalizeIssue:()=>Jt,floatSafeRemainder:()=>ll,getElementAtPath:()=>EP,getEnumValues:()=>$s,getLengthableOrigin:()=>Ns,getParsedType:()=>PP,getSizableOrigin:()=>dy,isObject:()=>Ro,isPlainObject:()=>Po,issue:()=>gl,joinValues:()=>pa,jsonStringifyReplacer:()=>ul,merge:()=>AP,normalizeParams:()=>q,nullish:()=>Is,numKeys:()=>RP,omit:()=>OP,optionalKeys:()=>ml,partial:()=>NP,pick:()=>$P,prefixIssues:()=>fn,primitiveTypes:()=>uy,promiseAllObject:()=>wP,propertyKeyTypes:()=>fl,randomString:()=>TP,required:()=>MP,stringifyPrimitive:()=>ma,unwrapMessage:()=>Cs});function bP(t){return t}function xP(t){return t}function kP(t){}function SP(t){throw new Error}function vP(t){}function $s(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 pa(t,e="|"){return t.map(n=>ma(n)).join(e)}function ul(t,e){return typeof e=="bigint"?e.toString():e}function Os(t){return{get value(){{let n=t();return Object.defineProperty(this,"value",{value:n}),n}throw new Error("cached value already set")}}}function Is(t){return t==null}function As(t){let e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function ll(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 xe(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 dl(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function EP(t,e){return e?e.reduce((n,r)=>n?.[r],t):t}function wP(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 TP(t=10){let e="abcdefghijklmnopqrstuvwxyz",n="";for(let r=0;r<t;r++)n+=e[Math.floor(Math.random()*e.length)];return n}function Dr(t){return JSON.stringify(t)}var fa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};function Ro(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var pl=Os(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});function Po(t){if(Ro(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let n=e.prototype;return!(Ro(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function RP(t){let e=0;for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&e++;return e}var PP=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}`)}},fl=new Set(["string","number","symbol"]),uy=new Set(["string","number","bigint","boolean","symbol","undefined"]);function Jn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rt(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 CP(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 ma(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function ml(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}var hl={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]},ly={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function $P(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 Rt(t,{...t._zod.def,shape:n,checks:[]})}function OP(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 Rt(t,{...t._zod.def,shape:n,checks:[]})}function IP(t,e){if(!Po(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 dl(this,"shape",r),r},checks:[]};return Rt(t,n)}function AP(t,e){return Rt(t,{...t._zod.def,get shape(){let n={...t._zod.def.shape,...e._zod.def.shape};return dl(this,"shape",n),n},catchall:e._zod.def.catchall,checks:[]})}function NP(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 Rt(e,{...e._zod.def,shape:o,checks:[]})}function MP(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 Rt(e,{...e._zod.def,shape:o,checks:[]})}function jr(t,e=0){for(let n=e;n<t.issues.length;n++)if(t.issues[n]?.continue!==!0)return!0;return!1}function fn(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Cs(t){return typeof t=="string"?t:t?.message}function Jt(t,e,n){let r={...t,path:t.path??[]};if(!t.message){let o=Cs(t.inst?._zod.def?.error?.(t))??Cs(e?.error?.(t))??Cs(n.customError?.(t))??Cs(n.localeError?.(t))??"Invalid input";r.message=o}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}function dy(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ns(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gl(...t){let[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}function DP(t){return Object.entries(t).filter(([e,n])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var cl=class{constructor(...e){}};var py=(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,ul,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ha=S("$ZodError",py),Ms=S("$ZodError",py,{Parent:Error});function yl(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 _l(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 bl=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 On;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Jt(c,s,Tt())));throw fa(a,o?.callee),a}return i.value},xl=bl(Ms),kl=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=>Jt(c,s,Tt())));throw fa(a,o?.callee),a}return i.value},Sl=kl(Ms),vl=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 On;return s.issues.length?{success:!1,error:new(t??ha)(s.issues.map(i=>Jt(i,o,Tt())))}:{success:!0,data:s.value}},Lr=vl(Ms),El=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=>Jt(i,o,Tt())))}:{success:!0,data:s.value}},zr=El(Ms);var fy=/^[cC][^\s-]{8,}$/,my=/^[0-9a-z]+$/,hy=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,gy=/^[0-9a-vA-V]{20}$/,yy=/^[A-Za-z0-9]{27}$/,_y=/^[a-zA-Z0-9_-]{21}$/,by=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var xy=/^([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})$/,wl=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 ky=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var LP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Sy(){return new RegExp(LP,"u")}var vy=/^(?:(?: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])$/,Ey=/^(([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})$/,wy=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ty=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ry=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Tl=/^[A-Za-z0-9_-]*$/,Py=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;var Cy=/^\+(?:[0-9]){6,14}[0-9]$/,$y="(?:(?:\\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])))",Oy=new RegExp(`^${$y}$`);function Iy(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 Ay(t){return new RegExp(`^${Iy(t)}$`)}function Ny(t){let e=Iy({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(`^${$y}T(?:${r})$`)}var My=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)};var Dy=/^\d+$/,jy=/^-?\d+(?:\.\d+)?/i,Ly=/true|false/i,zy=/null/i;var Hy=/^[^A-Z]*$/,Uy=/^[^a-z]*$/;var Ke=S("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),Fy={number:"number",bigint:"bigint",object:"date"},Rl=S("$ZodCheckLessThan",(t,e)=>{Ke.init(t,e);let n=Fy[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})}}),Pl=S("$ZodCheckGreaterThan",(t,e)=>{Ke.init(t,e);let n=Fy[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})}}),Zy=S("$ZodCheckMultipleOf",(t,e)=>{Ke.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):ll(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})}}),By=S("$ZodCheckNumberFormat",(t,e)=>{Ke.init(t,e),e.format=e.format||"float64";let n=e.format?.includes("int"),r=n?"int":"number",[o,s]=hl[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=Dy)}),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 qy=S("$ZodCheckMaxLength",(t,e)=>{var n;Ke.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Is(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=Ns(o);r.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Vy=S("$ZodCheckMinLength",(t,e)=>{var n;Ke.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Is(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=Ns(o);r.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Wy=S("$ZodCheckLengthEquals",(t,e)=>{var n;Ke.init(t,e),(n=t._zod.def).when??(n.when=r=>{let o=r.value;return!Is(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=Ns(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})}}),Ds=S("$ZodCheckStringFormat",(t,e)=>{var n,r;Ke.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=()=>{})}),Ky=S("$ZodCheckRegex",(t,e)=>{Ds.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})}}),Gy=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Hy),Ds.init(t,e)}),Jy=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Uy),Ds.init(t,e)}),Xy=S("$ZodCheckIncludes",(t,e)=>{Ke.init(t,e);let n=Jn(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})}}),Yy=S("$ZodCheckStartsWith",(t,e)=>{Ke.init(t,e);let n=new RegExp(`^${Jn(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})}}),Qy=S("$ZodCheckEndsWith",(t,e)=>{Ke.init(t,e);let n=new RegExp(`.*${Jn(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 e_=S("$ZodCheckOverwrite",(t,e)=>{Ke.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});var ya=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(`
`).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(`
`))}};var n_={major:4,minor:0,patch:0};var he=S("$ZodType",(t,e)=>{var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=n_;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=jr(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 On;if(u||f instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await f,s.issues.length!==d&&(c||(c=jr(s,d)))});else{if(s.issues.length===d)continue;c||(c=jr(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 On;return a.then(c=>o(c,r,i))}return o(a,r,i)}}t["~standard"]={validate:o=>{try{let s=Lr(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}}),js=S("$ZodString",(t,e)=>{he.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??My(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}}),ke=S("$ZodStringFormat",(t,e)=>{Ds.init(t,e),js.init(t,e)}),$l=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=xy),ke.init(t,e)}),Ol=S("$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=wl(r))}else e.pattern??(e.pattern=wl());ke.init(t,e)}),Il=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=ky),ke.init(t,e)}),Al=S("$ZodURL",(t,e)=>{ke.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:Py.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})}}}),Nl=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Sy()),ke.init(t,e)}),Ml=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=_y),ke.init(t,e)}),Dl=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=fy),ke.init(t,e)}),jl=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=my),ke.init(t,e)}),Ll=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=hy),ke.init(t,e)}),zl=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=gy),ke.init(t,e)}),Hl=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=yy),ke.init(t,e)}),p_=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Ny(e)),ke.init(t,e)}),f_=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Oy),ke.init(t,e)}),m_=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Ay(e)),ke.init(t,e)}),h_=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=by),ke.init(t,e)}),Ul=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=vy),ke.init(t,e),t._zod.onattach.push(n=>{let r=n._zod.bag;r.format="ipv4"})}),Fl=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ey),ke.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})}}}),Zl=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wy),ke.init(t,e)}),Bl=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ty),ke.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 g_(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}var ql=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ry),ke.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64"}),t._zod.check=n=>{g_(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function zP(t){if(!Tl.test(t))return!1;let e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return g_(n)}var Vl=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Tl),ke.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.contentEncoding="base64url"}),t._zod.check=n=>{zP(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Wl=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Cy),ke.init(t,e)});function HP(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 Kl=S("$ZodJWT",(t,e)=>{ke.init(t,e),t._zod.check=n=>{HP(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}});var ba=S("$ZodNumber",(t,e)=>{he.init(t,e),t._zod.pattern=t._zod.bag.pattern??jy,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}}),Gl=S("$ZodNumber",(t,e)=>{By.init(t,e),ba.init(t,e)}),Jl=S("$ZodBoolean",(t,e)=>{he.init(t,e),t._zod.pattern=Ly,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 Xl=S("$ZodNull",(t,e)=>{he.init(t,e),t._zod.pattern=zy,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 Yl=S("$ZodUnknown",(t,e)=>{he.init(t,e),t._zod.parse=n=>n}),Ql=S("$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 r_(t,e,n){t.issues.length&&e.issues.push(...fn(n,t.issues)),e.value[n]=t.value}var ed=S("$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=>r_(u,n,i))):r_(c,n,i)}return s.length?Promise.all(s).then(()=>n):n}});function _a(t,e,n){t.issues.length&&e.issues.push(...fn(n,t.issues)),e.value[n]=t.value}function o_(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(...fn(n,t.issues)):t.value===void 0?n in r&&(e.value[n]=void 0):e.value[n]=t.value}var xa=S("$ZodObject",(t,e)=>{he.init(t,e);let n=Os(()=>{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=ml(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(f)}});xe(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 ya(["shape","payload","ctx"]),m=n.value,p=_=>{let b=Dr(_);return`shape[${b}]._zod.run({ value: input[${b}], 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 b=h[_];f.write(`const ${b} = ${p(_)};`);let k=Dr(_);f.write(`
if (${b}.issues.length) {
if (input[${k}] === undefined) {
if (${k} in input) {
newResult[${k}] = undefined;
}
} else {
payload.issues = payload.issues.concat(
${b}.issues.map((iss) => ({
...iss,
path: iss.path ? [${k}, ...iss.path] : [${k}],
}))
);
}
} else if (${b}.value === undefined) {
if (${k} in input) newResult[${k}] = undefined;
} else {
newResult[${k}] = ${b}.value;
}
`)}else{let b=h[_];f.write(`const ${b} = ${p(_)};`),f.write(`
if (${b}.issues.length) payload.issues = payload.issues.concat(${b}.issues.map(iss => ({
...iss,
path: iss.path ? [${Dr(_)}, ...iss.path] : [${Dr(_)}]
})));`),f.write(`newResult[${Dr(_)}] = ${b}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,b)=>y(d,_,b)},o,s=Ro,i=!da.jitless,c=i&&pl.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 b=l.shape;for(let k of l.keys){let v=b[k],O=v._zod.run({value:m[k],issues:[]},f),P=v._zod.optin==="optional"&&v._zod.optout==="optional";O instanceof Promise?p.push(O.then(j=>P?o_(j,d,k,m):_a(j,d,k))):P?o_(O,d,k,m):_a(O,d,k)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let b of Object.keys(m)){if(g.has(b))continue;if(_==="never"){h.push(b);continue}let k=y.run({value:m[b],issues:[]},f);k instanceof Promise?p.push(k.then(v=>_a(v,d,b))):_a(k,d,b)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function s_(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=>Jt(s,r,Tt())))}),e}var ka=S("$ZodUnion",(t,e)=>{he.init(t,e),xe(t._zod,"optin",()=>e.options.some(n=>n._zod.optin==="optional")?"optional":void 0),xe(t._zod,"optout",()=>e.options.some(n=>n._zod.optout==="optional")?"optional":void 0),xe(t._zod,"values",()=>{if(e.options.every(n=>n._zod.values))return new Set(e.options.flatMap(n=>Array.from(n._zod.values)))}),xe(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=>As(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=>s_(i,n,t,r)):s_(s,n,t,r)}}),td=S("$ZodDiscriminatedUnion",(t,e)=>{ka.init(t,e);let n=t._zod.parse;xe(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=Os(()=>{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(!Ro(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)}}),nd=S("$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])=>i_(n,c,u)):i_(n,s,i)}});function Cl(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(Po(t)&&Po(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=Cl(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=Cl(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 i_(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),jr(t))return t;let r=Cl(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 rd=S("$ZodRecord",(t,e)=>{he.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Po(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(...fn(c,l.issues)),n.value[c]=l.value})):(u.issues.length&&n.issues.push(...fn(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=>Jt(u,r,Tt())),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(...fn(i,u.issues)),n.value[a.value]=u.value})):(c.issues.length&&n.issues.push(...fn(i,c.issues)),n.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}});var od=S("$ZodEnum",(t,e)=>{he.init(t,e);let n=$s(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>fl.has(typeof r)).map(r=>typeof r=="string"?Jn(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}}),sd=S("$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"?Jn(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 id=S("$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 On;return n.value=o,n}}),ad=S("$ZodOptional",(t,e)=>{he.init(t,e),t._zod.optin="optional",t._zod.optout="optional",xe(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),xe(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${As(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)}),cd=S("$ZodNullable",(t,e)=>{he.init(t,e),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(t._zod,"pattern",()=>{let n=e.innerType._zod.pattern;return n?new RegExp(`^(${As(n.source)}|null)$`):void 0}),xe(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)}),ud=S("$ZodDefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",xe(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=>a_(s,e)):a_(o,e)}});function a_(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var ld=S("$ZodPrefault",(t,e)=>{he.init(t,e),t._zod.optin="optional",xe(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))}),dd=S("$ZodNonOptional",(t,e)=>{he.init(t,e),xe(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=>c_(s,t)):c_(o,t)}});function c_(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 pd=S("$ZodCatch",(t,e)=>{he.init(t,e),t._zod.optin="optional",xe(t._zod,"optout",()=>e.innerType._zod.optout),xe(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=>Jt(i,r,Tt()))},input:n.value}),n.issues=[]),n)):(n.value=o.value,o.issues.length&&(n.value=e.catchValue({...n,error:{issues:o.issues.map(s=>Jt(s,r,Tt()))},input:n.value}),n.issues=[]),n)}});var fd=S("$ZodPipe",(t,e)=>{he.init(t,e),xe(t._zod,"values",()=>e.in._zod.values),xe(t._zod,"optin",()=>e.in._zod.optin),xe(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=>u_(s,e,r)):u_(o,e,r)}});function u_(t,e,n){return jr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var md=S("$ZodReadonly",(t,e)=>{he.init(t,e),xe(t._zod,"propValues",()=>e.innerType._zod.propValues),xe(t._zod,"values",()=>e.innerType._zod.values),xe(t._zod,"optin",()=>e.innerType._zod.optin),xe(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(l_):l_(o)}});function l_(t){return t.value=Object.freeze(t.value),t}var hd=S("$ZodCustom",(t,e)=>{Ke.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=>d_(s,n,r,t));d_(o,n,r,t)}});function d_(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(gl(o))}}var UP=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},FP=()=>{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 ${UP(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${ma(r.values[0])}`:`Invalid option: expected one of ${pa(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":""}: ${pa(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 y_(){return{localeError:FP()}}var Ls=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 __(){return new Ls}var Xn=__();function gd(t,e){return new t({type:"string",...q(e)})}function yd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function Sa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function _d(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function bd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function xd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function kd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...q(e)})}function Sd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...q(e)})}function vd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function Ed(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function wd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Td(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function Rd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Pd(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Cd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function $d(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Od(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function Id(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Ad(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Nd(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Md(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Dd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function jd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function b_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function x_(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function k_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function S_(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Ld(t,e){return new t({type:"number",checks:[],...q(e)})}function zd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function Hd(t,e){return new t({type:"boolean",...q(e)})}function Ud(t,e){return new t({type:"null",...q(e)})}function Fd(t){return new t({type:"unknown"})}function Zd(t,e){return new t({type:"never",...q(e)})}function va(t,e){return new Rl({check:"less_than",...q(e),value:t,inclusive:!1})}function zs(t,e){return new Rl({check:"less_than",...q(e),value:t,inclusive:!0})}function Ea(t,e){return new Pl({check:"greater_than",...q(e),value:t,inclusive:!1})}function Hs(t,e){return new Pl({check:"greater_than",...q(e),value:t,inclusive:!0})}function wa(t,e){return new Zy({check:"multiple_of",...q(e),value:t})}function Ta(t,e){return new qy({check:"max_length",...q(e),maximum:t})}function Co(t,e){return new Vy({check:"min_length",...q(e),minimum:t})}function Ra(t,e){return new Wy({check:"length_equals",...q(e),length:t})}function Bd(t,e){return new Ky({check:"string_format",format:"regex",...q(e),pattern:t})}function qd(t){return new Gy({check:"string_format",format:"lowercase",...q(t)})}function Vd(t){return new Jy({check:"string_format",format:"uppercase",...q(t)})}function Wd(t,e){return new Xy({check:"string_format",format:"includes",...q(e),includes:t})}function Kd(t,e){return new Yy({check:"string_format",format:"starts_with",...q(e),prefix:t})}function Gd(t,e){return new Qy({check:"string_format",format:"ends_with",...q(e),suffix:t})}function Hr(t){return new e_({check:"overwrite",tx:t})}function Jd(t){return Hr(e=>e.normalize(t))}function Xd(){return Hr(t=>t.trim())}function Yd(){return Hr(t=>t.toLowerCase())}function Qd(){return Hr(t=>t.toUpperCase())}function v_(t,e,n){return new t({type:"array",element:e,...q(n)})}function ep(t,e,n){let r=q(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function tp(t,e,n){return new t({type:"custom",check:"custom",fn:e,...q(n)})}var Pa=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Xn,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:b}=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),b&&(p.contentEncoding=b),_&&_.size>0){let k=[..._];k.length===1?p.pattern=k[0].source:k.length>1&&(a.schema.allOf=[...k.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:b,exclusiveMinimum:k}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof k=="number"&&(p.exclusiveMinimum=k),typeof h=="number"&&(p.minimum=h,typeof k=="number"&&(k>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=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 b=o.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.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=b=>"allOf"in b&&Object.keys(b).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((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));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=$s(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(b=>({...h,contentMediaType:b})):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"&&Fe(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>
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 np(t,e){if(t instanceof Ls){let r=new Pa(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 Pa(e);return n.process(t),n.emit(t,e)}function Fe(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 Fe(o.element,n);case"object":{for(let s in o.shape)if(Fe(o.shape[s],n))return!0;return!1}case"union":{for(let s of o.options)if(Fe(s,n))return!0;return!1}case"intersection":return Fe(o.left,n)||Fe(o.right,n);case"tuple":{for(let s of o.items)if(Fe(s,n))return!0;return!!(o.rest&&Fe(o.rest,n))}case"record":return Fe(o.keyType,n)||Fe(o.valueType,n);case"map":return Fe(o.keyType,n)||Fe(o.valueType,n);case"set":return Fe(o.valueType,n);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Fe(o.innerType,n);case"lazy":return Fe(o.getter(),n);case"default":return Fe(o.innerType,n);case"prefault":return Fe(o.innerType,n);case"custom":return!1;case"transform":return!0;case"pipe":return Fe(o.in,n)||Fe(o.out,n);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var v0=S("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");he.init(t,e),t.def=e,t.parse=(n,r)=>xl(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Lr(t,n,r),t.parseAsync=async(n,r)=>Sl(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)=>Rt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var E0=S("ZodMiniObject",(t,e)=>{xa.init(t,e),v0.init(t,e),ie.defineLazy(t,"shape",()=>e.shape)});function rp(t,e){let n={type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},...ie.normalizeParams(e)};return new E0(n)}function Nt(t){return!!t._zod}function Fr(t){let e=Object.values(t);if(e.length===0)return rp({});let n=e.every(Nt),r=e.every(o=>!Nt(o));if(n)return rp(t);if(r)return il(t);throw new Error("Mixed Zod versions detected in object shape.")}function Yn(t,e){return Nt(t)?Lr(t,e):t.safeParse(e)}async function Ca(t,e){return Nt(t)?await zr(t,e):await t.safeParseAsync(e)}function Qn(t){if(!t)return;let e;if(Nt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function $o(t){if(t){if(typeof t=="object"){let e=t,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 Fr(t)}}if(Nt(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 $a(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function w_(t){return t.description}function T_(t){if(Nt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Oa(t){if(Nt(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 Us={};Me(Us,{ZodISODate:()=>P_,ZodISODateTime:()=>R_,ZodISODuration:()=>$_,ZodISOTime:()=>C_,date:()=>sp,datetime:()=>op,duration:()=>ap,time:()=>ip});var R_=S("ZodISODateTime",(t,e)=>{p_.init(t,e),Re.init(t,e)});function op(t){return b_(R_,t)}var P_=S("ZodISODate",(t,e)=>{f_.init(t,e),Re.init(t,e)});function sp(t){return x_(P_,t)}var C_=S("ZodISOTime",(t,e)=>{m_.init(t,e),Re.init(t,e)});function ip(t){return k_(C_,t)}var $_=S("ZodISODuration",(t,e)=>{h_.init(t,e),Re.init(t,e)});function ap(t){return S_($_,t)}var O_=(t,e)=>{ha.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>_l(t,n)},flatten:{value:n=>yl(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},TZ=S("ZodError",O_),Fs=S("ZodError",O_,{Parent:Error});var I_=bl(Fs),A_=kl(Fs),N_=vl(Fs),M_=El(Fs);var Oe=S("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)=>Rt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>I_(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>N_(t,n,r),t.parseAsync=async(n,r)=>A_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>M_(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(kC(n,r)),t.superRefine=n=>t.check(SC(n)),t.overwrite=n=>t.check(Hr(n)),t.optional=()=>Ce(t),t.nullable=()=>L_(t),t.nullish=()=>Ce(L_(t)),t.nonoptional=n=>mC(t,n),t.array=()=>ae(t),t.or=n=>ve([t,n]),t.and=n=>Aa(t,n),t.transform=n=>up(t,B_(n)),t.default=n=>dC(t,n),t.prefault=n=>fC(t,n),t.catch=n=>gC(t,n),t.pipe=n=>up(t,n),t.readonly=()=>bC(t),t.describe=n=>{let r=t.clone();return Xn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Xn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Xn.get(t);let r=t.clone();return Xn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),z_=S("_ZodString",(t,e)=>{js.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(Bd(...r)),t.includes=(...r)=>t.check(Wd(...r)),t.startsWith=(...r)=>t.check(Kd(...r)),t.endsWith=(...r)=>t.check(Gd(...r)),t.min=(...r)=>t.check(Co(...r)),t.max=(...r)=>t.check(Ta(...r)),t.length=(...r)=>t.check(Ra(...r)),t.nonempty=(...r)=>t.check(Co(1,...r)),t.lowercase=r=>t.check(qd(r)),t.uppercase=r=>t.check(Vd(r)),t.trim=()=>t.check(Xd()),t.normalize=(...r)=>t.check(Jd(...r)),t.toLowerCase=()=>t.check(Yd()),t.toUpperCase=()=>t.check(Qd())}),A0=S("ZodString",(t,e)=>{js.init(t,e),z_.init(t,e),t.email=n=>t.check(yd(N0,n)),t.url=n=>t.check(Sd(M0,n)),t.jwt=n=>t.check(jd(J0,n)),t.emoji=n=>t.check(vd(D0,n)),t.guid=n=>t.check(Sa(D_,n)),t.uuid=n=>t.check(_d(Ia,n)),t.uuidv4=n=>t.check(bd(Ia,n)),t.uuidv6=n=>t.check(xd(Ia,n)),t.uuidv7=n=>t.check(kd(Ia,n)),t.nanoid=n=>t.check(Ed(j0,n)),t.guid=n=>t.check(Sa(D_,n)),t.cuid=n=>t.check(wd(L0,n)),t.cuid2=n=>t.check(Td(z0,n)),t.ulid=n=>t.check(Rd(H0,n)),t.base64=n=>t.check(Nd(W0,n)),t.base64url=n=>t.check(Md(K0,n)),t.xid=n=>t.check(Pd(U0,n)),t.ksuid=n=>t.check(Cd(F0,n)),t.ipv4=n=>t.check($d(Z0,n)),t.ipv6=n=>t.check(Od(B0,n)),t.cidrv4=n=>t.check(Id(q0,n)),t.cidrv6=n=>t.check(Ad(V0,n)),t.e164=n=>t.check(Dd(G0,n)),t.datetime=n=>t.check(op(n)),t.date=n=>t.check(sp(n)),t.time=n=>t.check(ip(n)),t.duration=n=>t.check(ap(n))});function x(t){return gd(A0,t)}var Re=S("ZodStringFormat",(t,e)=>{ke.init(t,e),z_.init(t,e)}),N0=S("ZodEmail",(t,e)=>{Il.init(t,e),Re.init(t,e)});var D_=S("ZodGUID",(t,e)=>{$l.init(t,e),Re.init(t,e)});var Ia=S("ZodUUID",(t,e)=>{Ol.init(t,e),Re.init(t,e)});var M0=S("ZodURL",(t,e)=>{Al.init(t,e),Re.init(t,e)});var D0=S("ZodEmoji",(t,e)=>{Nl.init(t,e),Re.init(t,e)});var j0=S("ZodNanoID",(t,e)=>{Ml.init(t,e),Re.init(t,e)});var L0=S("ZodCUID",(t,e)=>{Dl.init(t,e),Re.init(t,e)});var z0=S("ZodCUID2",(t,e)=>{jl.init(t,e),Re.init(t,e)});var H0=S("ZodULID",(t,e)=>{Ll.init(t,e),Re.init(t,e)});var U0=S("ZodXID",(t,e)=>{zl.init(t,e),Re.init(t,e)});var F0=S("ZodKSUID",(t,e)=>{Hl.init(t,e),Re.init(t,e)});var Z0=S("ZodIPv4",(t,e)=>{Ul.init(t,e),Re.init(t,e)});var B0=S("ZodIPv6",(t,e)=>{Fl.init(t,e),Re.init(t,e)});var q0=S("ZodCIDRv4",(t,e)=>{Zl.init(t,e),Re.init(t,e)});var V0=S("ZodCIDRv6",(t,e)=>{Bl.init(t,e),Re.init(t,e)});var W0=S("ZodBase64",(t,e)=>{ql.init(t,e),Re.init(t,e)});var K0=S("ZodBase64URL",(t,e)=>{Vl.init(t,e),Re.init(t,e)});var G0=S("ZodE164",(t,e)=>{Wl.init(t,e),Re.init(t,e)});var J0=S("ZodJWT",(t,e)=>{Kl.init(t,e),Re.init(t,e)});var H_=S("ZodNumber",(t,e)=>{ba.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(Ea(r,o)),t.gte=(r,o)=>t.check(Hs(r,o)),t.min=(r,o)=>t.check(Hs(r,o)),t.lt=(r,o)=>t.check(va(r,o)),t.lte=(r,o)=>t.check(zs(r,o)),t.max=(r,o)=>t.check(zs(r,o)),t.int=r=>t.check(j_(r)),t.safe=r=>t.check(j_(r)),t.positive=r=>t.check(Ea(0,r)),t.nonnegative=r=>t.check(Hs(0,r)),t.negative=r=>t.check(va(0,r)),t.nonpositive=r=>t.check(zs(0,r)),t.multipleOf=(r,o)=>t.check(wa(r,o)),t.step=(r,o)=>t.check(wa(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 Ld(H_,t)}var X0=S("ZodNumberFormat",(t,e)=>{Gl.init(t,e),H_.init(t,e)});function j_(t){return zd(X0,t)}var Y0=S("ZodBoolean",(t,e)=>{Jl.init(t,e),Oe.init(t,e)});function Ve(t){return Hd(Y0,t)}var Q0=S("ZodNull",(t,e)=>{Xl.init(t,e),Oe.init(t,e)});function U_(t){return Ud(Q0,t)}var eC=S("ZodUnknown",(t,e)=>{Yl.init(t,e),Oe.init(t,e)});function Pe(){return Fd(eC)}var tC=S("ZodNever",(t,e)=>{Ql.init(t,e),Oe.init(t,e)});function nC(t){return Zd(tC,t)}var rC=S("ZodArray",(t,e)=>{ed.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(Co(n,r)),t.nonempty=n=>t.check(Co(1,n)),t.max=(n,r)=>t.check(Ta(n,r)),t.length=(n,r)=>t.check(Ra(n,r)),t.unwrap=()=>t.element});function ae(t,e){return v_(rC,t,e)}var F_=S("ZodObject",(t,e)=>{xa.init(t,e),Oe.init(t,e),ie.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>_t(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Pe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Pe()}),t.strict=()=>t.clone({...t._zod.def,catchall:nC()}),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(q_,t,n[0]),t.required=(...n)=>ie.required(V_,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 F_(n)}function at(t,e){return new F_({type:"object",get shape(){return ie.assignProp(this,"shape",{...t}),this.shape},catchall:Pe(),...ie.normalizeParams(e)})}var Z_=S("ZodUnion",(t,e)=>{ka.init(t,e),Oe.init(t,e),t.options=e.options});function ve(t,e){return new Z_({type:"union",options:t,...ie.normalizeParams(e)})}var oC=S("ZodDiscriminatedUnion",(t,e)=>{Z_.init(t,e),td.init(t,e)});function lp(t,e,n){return new oC({type:"union",options:e,discriminator:t,...ie.normalizeParams(n)})}var sC=S("ZodIntersection",(t,e)=>{nd.init(t,e),Oe.init(t,e)});function Aa(t,e){return new sC({type:"intersection",left:t,right:e})}var iC=S("ZodRecord",(t,e)=>{rd.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function Se(t,e,n){return new iC({type:"record",keyType:t,valueType:e,...ie.normalizeParams(n)})}var cp=S("ZodEnum",(t,e)=>{od.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 cp({...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 cp({...e,checks:[],...ie.normalizeParams(o),entries:s})}});function _t(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new cp({type:"enum",entries:n,...ie.normalizeParams(e)})}var aC=S("ZodLiteral",(t,e)=>{sd.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 aC({type:"literal",values:Array.isArray(t)?t:[t],...ie.normalizeParams(e)})}var cC=S("ZodTransform",(t,e)=>{id.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 B_(t){return new cC({type:"transform",transform:t})}var q_=S("ZodOptional",(t,e)=>{ad.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new q_({type:"optional",innerType:t})}var uC=S("ZodNullable",(t,e)=>{cd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function L_(t){return new uC({type:"nullable",innerType:t})}var lC=S("ZodDefault",(t,e)=>{ud.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function dC(t,e){return new lC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var pC=S("ZodPrefault",(t,e)=>{ld.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function fC(t,e){return new pC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var V_=S("ZodNonOptional",(t,e)=>{dd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function mC(t,e){return new V_({type:"nonoptional",innerType:t,...ie.normalizeParams(e)})}var hC=S("ZodCatch",(t,e)=>{pd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function gC(t,e){return new hC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var yC=S("ZodPipe",(t,e)=>{fd.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function up(t,e){return new yC({type:"pipe",in:t,out:e})}var _C=S("ZodReadonly",(t,e)=>{md.init(t,e),Oe.init(t,e)});function bC(t){return new _C({type:"readonly",innerType:t})}var W_=S("ZodCustom",(t,e)=>{hd.init(t,e),Oe.init(t,e)});function xC(t){let e=new Ke({check:"custom"});return e._zod.check=t,e}function K_(t,e){return ep(W_,t??(()=>!0),e)}function kC(t,e={}){return tp(W_,t,e)}function SC(t){let e=xC(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 dp(t,e){return up(B_(t),e)}Tt(y_());var fp="2025-11-25";var G_=[fp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],er="io.modelcontextprotocol/related-task",Ma="2.0",Ze=K_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),J_=ve([x(),fe().int()]),X_=x(),HZ=at({ttl:fe().optional(),pollInterval:fe().optional()}),vC=N({ttl:fe().optional()}),EC=N({taskId:x()}),mp=at({progressToken:J_.optional(),[er]:EC.optional()}),Pt=N({_meta:mp.optional()}),Zs=Pt.extend({task:vC.optional()}),Y_=t=>Zs.safeParse(t).success,Ge=N({method:x(),params:Pt.loose().optional()}),Mt=N({_meta:mp.optional()}),Dt=N({method:x(),params:Mt.loose().optional()}),Je=at({_meta:mp.optional()}),Da=ve([x(),fe().int()]),Q_=N({jsonrpc:U(Ma),id:Da,...Ge.shape}).strict(),hp=t=>Q_.safeParse(t).success,eb=N({jsonrpc:U(Ma),...Dt.shape}).strict(),tb=t=>eb.safeParse(t).success,gp=N({jsonrpc:U(Ma),id:Da,result:Je}).strict(),Bs=t=>gp.safeParse(t).success;var Z;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(Z||(Z={}));var yp=N({jsonrpc:U(Ma),id:Da.optional(),error:N({code:fe().int(),message:x(),data:Pe().optional()})}).strict();var nb=t=>yp.safeParse(t).success;var rb=ve([Q_,eb,gp,yp]),UZ=ve([gp,yp]),ja=Je.strict(),wC=Mt.extend({requestId:Da.optional(),reason:x().optional()}),La=Dt.extend({method:U("notifications/cancelled"),params:wC}),TC=N({src:x(),mimeType:x().optional(),sizes:ae(x()).optional(),theme:_t(["light","dark"]).optional()}),qs=N({icons:ae(TC).optional()}),Oo=N({name:x(),title:x().optional()}),ob=Oo.extend({...Oo.shape,...qs.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),RC=Aa(N({applyDefaults:Ve().optional()}),Se(x(),Pe())),PC=dp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Aa(N({form:RC.optional(),url:Ze.optional()}),Se(x(),Pe()).optional())),CC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({sampling:at({createMessage:Ze.optional()}).optional(),elicitation:at({create:Ze.optional()}).optional()}).optional()}),$C=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({tools:at({call:Ze.optional()}).optional()}).optional()}),OC=N({experimental:Se(x(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:PC.optional(),roots:N({listChanged:Ve().optional()}).optional(),tasks:CC.optional(),extensions:Se(x(),Ze).optional()}),IC=Pt.extend({protocolVersion:x(),capabilities:OC,clientInfo:ob}),_p=Ge.extend({method:U("initialize"),params:IC});var AC=N({experimental:Se(x(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:Ve().optional()}).optional(),resources:N({subscribe:Ve().optional(),listChanged:Ve().optional()}).optional(),tools:N({listChanged:Ve().optional()}).optional(),tasks:$C.optional(),extensions:Se(x(),Ze).optional()}),NC=Je.extend({protocolVersion:x(),capabilities:AC,serverInfo:ob,instructions:x().optional()}),bp=Dt.extend({method:U("notifications/initialized"),params:Mt.optional()});var za=Ge.extend({method:U("ping"),params:Pt.optional()}),MC=N({progress:fe(),total:Ce(fe()),message:Ce(x())}),DC=N({...Mt.shape,...MC.shape,progressToken:J_}),Ha=Dt.extend({method:U("notifications/progress"),params:DC}),jC=Pt.extend({cursor:X_.optional()}),Vs=Ge.extend({params:jC.optional()}),Ws=Je.extend({nextCursor:X_.optional()}),LC=_t(["working","input_required","completed","failed","cancelled"]),Ks=N({taskId:x(),status:LC,ttl:ve([fe(),U_()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:Ce(fe()),statusMessage:Ce(x())}),Io=Je.extend({task:Ks}),zC=Mt.merge(Ks),Gs=Dt.extend({method:U("notifications/tasks/status"),params:zC}),Ua=Ge.extend({method:U("tasks/get"),params:Pt.extend({taskId:x()})}),Fa=Je.merge(Ks),Za=Ge.extend({method:U("tasks/result"),params:Pt.extend({taskId:x()})}),FZ=Je.loose(),Ba=Vs.extend({method:U("tasks/list")}),qa=Ws.extend({tasks:ae(Ks)}),Va=Ge.extend({method:U("tasks/cancel"),params:Pt.extend({taskId:x()})}),sb=Je.merge(Ks),ib=N({uri:x(),mimeType:Ce(x()),_meta:Se(x(),Pe()).optional()}),ab=ib.extend({text:x()}),xp=x().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),cb=ib.extend({blob:xp}),Js=_t(["user","assistant"]),Ao=N({audience:ae(Js).optional(),priority:fe().min(0).max(1).optional(),lastModified:Us.datetime({offset:!0}).optional()}),ub=N({...Oo.shape,...qs.shape,uri:x(),description:Ce(x()),mimeType:Ce(x()),size:Ce(fe()),annotations:Ao.optional(),_meta:Ce(at({}))}),HC=N({...Oo.shape,...qs.shape,uriTemplate:x(),description:Ce(x()),mimeType:Ce(x()),annotations:Ao.optional(),_meta:Ce(at({}))}),No=Vs.extend({method:U("resources/list")}),UC=Ws.extend({resources:ae(ub)}),Mo=Vs.extend({method:U("resources/templates/list")}),FC=Ws.extend({resourceTemplates:ae(HC)}),kp=Pt.extend({uri:x()}),ZC=kp,Wa=Ge.extend({method:U("resources/read"),params:ZC}),BC=Je.extend({contents:ae(ve([ab,cb]))}),qC=Dt.extend({method:U("notifications/resources/list_changed"),params:Mt.optional()}),VC=kp,WC=Ge.extend({method:U("resources/subscribe"),params:VC}),KC=kp,GC=Ge.extend({method:U("resources/unsubscribe"),params:KC}),JC=Mt.extend({uri:x()}),XC=Dt.extend({method:U("notifications/resources/updated"),params:JC}),YC=N({name:x(),description:Ce(x()),required:Ce(Ve())}),QC=N({...Oo.shape,...qs.shape,description:Ce(x()),arguments:Ce(ae(YC)),_meta:Ce(at({}))}),Do=Vs.extend({method:U("prompts/list")}),e$=Ws.extend({prompts:ae(QC)}),t$=Pt.extend({name:x(),arguments:Se(x(),x()).optional()}),Ka=Ge.extend({method:U("prompts/get"),params:t$}),Sp=N({type:U("text"),text:x(),annotations:Ao.optional(),_meta:Se(x(),Pe()).optional()}),vp=N({type:U("image"),data:xp,mimeType:x(),annotations:Ao.optional(),_meta:Se(x(),Pe()).optional()}),Ep=N({type:U("audio"),data:xp,mimeType:x(),annotations:Ao.optional(),_meta:Se(x(),Pe()).optional()}),n$=N({type:U("tool_use"),name:x(),id:x(),input:Se(x(),Pe()),_meta:Se(x(),Pe()).optional()}),r$=N({type:U("resource"),resource:ve([ab,cb]),annotations:Ao.optional(),_meta:Se(x(),Pe()).optional()}),o$=ub.extend({type:U("resource_link")}),wp=ve([Sp,vp,Ep,o$,r$]),s$=N({role:Js,content:wp}),i$=Je.extend({description:x().optional(),messages:ae(s$)}),a$=Dt.extend({method:U("notifications/prompts/list_changed"),params:Mt.optional()}),c$=N({title:x().optional(),readOnlyHint:Ve().optional(),destructiveHint:Ve().optional(),idempotentHint:Ve().optional(),openWorldHint:Ve().optional()}),u$=N({taskSupport:_t(["required","optional","forbidden"]).optional()}),lb=N({...Oo.shape,...qs.shape,description:x().optional(),inputSchema:N({type:U("object"),properties:Se(x(),Ze).optional(),required:ae(x()).optional()}).catchall(Pe()),outputSchema:N({type:U("object"),properties:Se(x(),Ze).optional(),required:ae(x()).optional()}).catchall(Pe()).optional(),annotations:c$.optional(),execution:u$.optional(),_meta:Se(x(),Pe()).optional()}),Zr=Vs.extend({method:U("tools/list")}),l$=Ws.extend({tools:ae(lb)}),Ga=Je.extend({content:ae(wp).default([]),structuredContent:Se(x(),Pe()).optional(),isError:Ve().optional()}),ZZ=Ga.or(Je.extend({toolResult:Pe()})),d$=Zs.extend({name:x(),arguments:Se(x(),Pe()).optional()}),jo=Ge.extend({method:U("tools/call"),params:d$}),p$=Dt.extend({method:U("notifications/tools/list_changed"),params:Mt.optional()}),BZ=N({autoRefresh:Ve().default(!0),debounceMs:fe().int().nonnegative().default(300)}),Xs=_t(["debug","info","notice","warning","error","critical","alert","emergency"]),f$=Pt.extend({level:Xs}),Tp=Ge.extend({method:U("logging/setLevel"),params:f$}),m$=Mt.extend({level:Xs,logger:x().optional(),data:Pe()}),h$=Dt.extend({method:U("notifications/message"),params:m$}),g$=N({name:x().optional()}),y$=N({hints:ae(g$).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),_$=N({mode:_t(["auto","required","none"]).optional()}),b$=N({type:U("tool_result"),toolUseId:x().describe("The unique identifier for the corresponding tool call."),content:ae(wp).default([]),structuredContent:N({}).loose().optional(),isError:Ve().optional(),_meta:Se(x(),Pe()).optional()}),x$=lp("type",[Sp,vp,Ep]),Na=lp("type",[Sp,vp,Ep,n$,b$]),k$=N({role:Js,content:ve([Na,ae(Na)]),_meta:Se(x(),Pe()).optional()}),S$=Zs.extend({messages:ae(k$),modelPreferences:y$.optional(),systemPrompt:x().optional(),includeContext:_t(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ae(x()).optional(),metadata:Ze.optional(),tools:ae(lb).optional(),toolChoice:_$.optional()}),v$=Ge.extend({method:U("sampling/createMessage"),params:S$}),Ys=Je.extend({model:x(),stopReason:Ce(_t(["endTurn","stopSequence","maxTokens"]).or(x())),role:Js,content:x$}),Rp=Je.extend({model:x(),stopReason:Ce(_t(["endTurn","stopSequence","maxTokens","toolUse"]).or(x())),role:Js,content:ve([Na,ae(Na)])}),E$=N({type:U("boolean"),title:x().optional(),description:x().optional(),default:Ve().optional()}),w$=N({type:U("string"),title:x().optional(),description:x().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:_t(["email","uri","date","date-time"]).optional(),default:x().optional()}),T$=N({type:_t(["number","integer"]),title:x().optional(),description:x().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),R$=N({type:U("string"),title:x().optional(),description:x().optional(),enum:ae(x()),default:x().optional()}),P$=N({type:U("string"),title:x().optional(),description:x().optional(),oneOf:ae(N({const:x(),title:x()})),default:x().optional()}),C$=N({type:U("string"),title:x().optional(),description:x().optional(),enum:ae(x()),enumNames:ae(x()).optional(),default:x().optional()}),$$=ve([R$,P$]),O$=N({type:U("array"),title:x().optional(),description:x().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ae(x())}),default:ae(x()).optional()}),I$=N({type:U("array"),title:x().optional(),description:x().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ae(N({const:x(),title:x()}))}),default:ae(x()).optional()}),A$=ve([O$,I$]),N$=ve([C$,$$,A$]),M$=ve([N$,E$,w$,T$]),D$=Zs.extend({mode:U("form").optional(),message:x(),requestedSchema:N({type:U("object"),properties:Se(x(),M$),required:ae(x()).optional()})}),j$=Zs.extend({mode:U("url"),message:x(),elicitationId:x(),url:x().url()}),L$=ve([D$,j$]),z$=Ge.extend({method:U("elicitation/create"),params:L$}),H$=Mt.extend({elicitationId:x()}),U$=Dt.extend({method:U("notifications/elicitation/complete"),params:H$}),Lo=Je.extend({action:_t(["accept","decline","cancel"]),content:dp(t=>t===null?void 0:t,Se(x(),ve([x(),fe(),Ve(),ae(x())])).optional())}),F$=N({type:U("ref/resource"),uri:x()});var Z$=N({type:U("ref/prompt"),name:x()}),B$=Pt.extend({ref:ve([Z$,F$]),argument:N({name:x(),value:x()}),context:N({arguments:Se(x(),x()).optional()}).optional()}),Ja=Ge.extend({method:U("completion/complete"),params:B$});function db(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function pb(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var q$=Je.extend({completion:at({values:ae(x()).max(100),total:Ce(fe().int()),hasMore:Ce(Ve())})}),V$=N({uri:x().startsWith("file://"),name:x().optional(),_meta:Se(x(),Pe()).optional()}),W$=Ge.extend({method:U("roots/list"),params:Pt.optional()}),Pp=Je.extend({roots:ae(V$)}),K$=Dt.extend({method:U("notifications/roots/list_changed"),params:Mt.optional()}),qZ=ve([za,_p,Ja,Tp,Ka,Do,No,Mo,Wa,WC,GC,jo,Zr,Ua,Za,Ba,Va]),VZ=ve([La,Ha,bp,K$,Gs]),WZ=ve([ja,Ys,Rp,Lo,Pp,Fa,qa,Io]),KZ=ve([za,v$,z$,W$,Ua,Za,Ba,Va]),GZ=ve([La,Ha,h$,XC,qC,p$,a$,Gs,U$]),JZ=ve([ja,NC,q$,i$,e$,UC,FC,BC,Ga,l$,Fa,qa,Io]),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===Z.UrlElicitationRequired&&r){let o=r;if(o.elicitations)return new pp(o.elicitations,n)}return new t(e,n,r)}},pp=class extends z{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function tr(t){return t==="completed"||t==="failed"||t==="cancelled"}var mb=Symbol("Let zodToJsonSchema decide on which parser to use");var fb={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"},hb=t=>typeof t=="string"?{...fb,name:t}:{...fb,...t};var gb=t=>{let e=hb(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 Cp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ce(t,e,n,r,o){t[e]=n,Cp(t,e,r,o)}var Xa=(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"?Xa(e,t.currentPath):e.join("/")}}function yb(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 _b(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 bb(){return{type:"boolean"}}function Ya(t,e){return K(t.type._def,e)}var xb=(t,e)=>K(t.innerType._def,e);function $p(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>$p(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 G$(t,e)}}var G$=(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 kb(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function Sb(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):$e(e)}function vb(t){return{type:"string",enum:Array.from(t.values)}}var J$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function Eb(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(J$(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 wb(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 Op,Xt={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:()=>(Op===void 0&&(Op=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Op),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 Qa(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":Yt(n,"email",r.message,e);break;case"format:idn-email":Yt(n,"idn-email",r.message,e);break;case"pattern:zod":ct(n,Xt.email,r.message,e);break}break;case"url":Yt(n,"uri",r.message,e);break;case"uuid":Yt(n,"uuid",r.message,e);break;case"regex":ct(n,r.regex,r.message,e);break;case"cuid":ct(n,Xt.cuid,r.message,e);break;case"cuid2":ct(n,Xt.cuid2,r.message,e);break;case"startsWith":ct(n,RegExp(`^${Ip(r.value,e)}`),r.message,e);break;case"endsWith":ct(n,RegExp(`${Ip(r.value,e)}$`),r.message,e);break;case"datetime":Yt(n,"date-time",r.message,e);break;case"date":Yt(n,"date",r.message,e);break;case"time":Yt(n,"time",r.message,e);break;case"duration":Yt(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":{ct(n,RegExp(Ip(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Yt(n,"ipv4",r.message,e),r.version!=="v4"&&Yt(n,"ipv6",r.message,e);break}case"base64url":ct(n,Xt.base64url,r.message,e);break;case"jwt":ct(n,Xt.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&ct(n,Xt.ipv4Cidr,r.message,e),r.version!=="v4"&&ct(n,Xt.ipv6Cidr,r.message,e);break}case"emoji":ct(n,Xt.emoji(),r.message,e);break;case"ulid":{ct(n,Xt.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yt(n,"binary",r.message,e);break}case"contentEncoding:base64":{ce(n,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{ct(n,Xt.base64,r.message,e);break}}break}case"nanoid":ct(n,Xt.nanoid,r.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return n}function Ip(t,e){return e.patternStrategy==="escape"?Y$(t):t}var X$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Y$(t){let e="";for(let n=0;n<t.length;n++)X$.has(t[n])||(e+="\\"),e+=t[n];return e}function Yt(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 ct(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:Tb(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ce(t,"pattern",Tb(e,r),n,r)}function Tb(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
]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
`:`[${r[c]}\r
]`;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 ec(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}=Qa(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}=Ya(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function Rb(t,e){if(e.mapStrategy==="record")return ec(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 Pb(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 Cb(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function $b(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Qs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Ib(t,e){if(e.target==="openApi3")return Ob(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Qs&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Qs[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 Ob(t,e)}var Ob=(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 Ab(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:Qs[t.innerType._def.typeName],nullable:!0}:{type:[Qs[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 Nb(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",Cp(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 Mb(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=eO(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=Q$(t,e);return i!==void 0&&(r.additionalProperties=i),r}function Q$(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 eO(t){try{return t.isOptional()}catch{return!0}}var Db=(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 jb=(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 Lb(t,e){return K(t.type._def,e)}function zb(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 Hb(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 Ub(t){return{not:$e(t)}}function Fb(t){return $e(t)}var Zb=(t,e)=>K(t.innerType._def,e);var Bb=(t,e,n)=>{switch(e){case T.ZodString:return Qa(t,n);case T.ZodNumber:return Nb(t,n);case T.ZodObject:return Mb(t,n);case T.ZodBigInt:return _b(t,n);case T.ZodBoolean:return bb();case T.ZodDate:return $p(t,n);case T.ZodUndefined:return Ub(n);case T.ZodNull:return $b(n);case T.ZodArray:return yb(t,n);case T.ZodUnion:case T.ZodDiscriminatedUnion:return Ib(t,n);case T.ZodIntersection:return Eb(t,n);case T.ZodTuple:return Hb(t,n);case T.ZodRecord:return ec(t,n);case T.ZodLiteral:return wb(t,n);case T.ZodEnum:return vb(t);case T.ZodNativeEnum:return Pb(t);case T.ZodNullable:return Ab(t,n);case T.ZodOptional:return Db(t,n);case T.ZodMap:return Rb(t,n);case T.ZodSet:return zb(t,n);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return Lb(t,n);case T.ZodNaN:case T.ZodNever:return Cb(n);case T.ZodEffects:return Sb(t,n);case T.ZodAny:return $e(n);case T.ZodUnknown:return Fb(n);case T.ZodDefault:return kb(t,n);case T.ZodBranded:return Ya(t,n);case T.ZodReadonly:return Zb(t,n);case T.ZodCatch:return xb(t,n);case T.ZodPipeline:return jb(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!==mb)return a}if(r&&!n){let a=tO(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=Bb(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&nO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var tO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Xa(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}},nO=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Ap=(t,e)=>{let n=gb(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 rO(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Np(t,e){return Nt(t)?np(t,{target:rO(e?.target),io:e?.pipeStrategy??"input"}):Ap(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Mp(t){let n=Qn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Oa(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Dp(t,e){let n=Yn(t,e);if(!n.success)throw n.error;return n.data}var oO=6e4,tc=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(La,n=>{this._oncancel(n)}),this.setNotificationHandler(Ha,n=>{this._onprogress(n)}),this.setRequestHandler(za,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ua,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Za,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(Z.InvalidParams,`Task not found: ${s}`);if(!tr(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(tr(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[er]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Ba,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(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(Va,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new z(Z.InvalidParams,`Task not found: ${n.params.taskId}`);if(tr(o.status))throw new z(Z.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(Z.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof z?o:new z(Z.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,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(Z.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),Bs(s)||nb(s)?this._onresponse(s):hp(s)?this._onrequest(s,i):tb(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(Z.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?.[er]?.taskId;if(r===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Y_(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,f)=>{if(i.signal.aborted)throw new z(Z.ConnectionClosed,"Request was cancelled");let m={...f,relatedRequestId:e.id};s&&!m.relatedTask&&(m.relatedTask={taskId:s});let p=m.relatedTask?.taskId??s;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(l,d,m)},authInfo: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:Z.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken: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),Bs(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(Bs(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),Bs(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(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Io,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new z(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},tr(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(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new z(Z.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},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(Z.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||{},[er]: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(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let b=_ instanceof z?_:new z(Z.RequestTimeout,String(_));l(b)};this._responseHandlers.set(f,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let b=Yn(n,_.result);b.success?u(b.data):l(b.error)}catch(b){l(b)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let h=r?.timeout??oO,g=()=>p(z.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,r?.maxTotalTimeout,g,r?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=b=>{let k=this._responseHandlers.get(f);k?k(b):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(b=>{this._cleanupTimeout(f),l(b)})}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},Fa,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},qa,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},sb,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||{},[er]: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||{},[er]: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||{},[er]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Mp(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Dp(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=Mp(e);this._notificationHandlers.set(r,o=>{let s=Dp(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"&&hp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new z(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,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(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new z(Z.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(Z.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=Gs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),tr(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(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(tr(a.status))throw new z(Z.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await r.updateTaskStatus(o,s,i,n);let c=await r.getTask(o,n);if(c){let u=Gs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),tr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function qb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Vb(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];qb(i)&&qb(s)?n[o]={...i,...s}:n[o]=s}return n}var IS=Xg(Sm(),1),AS=Xg(OS(),1);function GD(){let t=new IS.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,AS.default)(t),t}var jc=class{constructor(e){this._ajv=e??GD()}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 Lc=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},Ys,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},Lo,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 NS(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 MS(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 zc=class extends tc{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Xs.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 jc,this.setRequestHandler(_p,r=>this._oninitialize(r)),this.setNotificationHandler(bp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Tp,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Xs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Lc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Vb(this._capabilities,e)}setRequestHandler(e,n){let o=Qn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(Nt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Yn(jo,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new z(Z.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let p=Yn(Io,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new z(Z.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=Yn(Ga,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new z(Z.InvalidParams,`Invalid tools/call result: ${p}`)}return m.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,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){MS(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&NS(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:G_.includes(n)?n:fp,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"},ja)}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},Rp,n):this.request({method:"sampling/createMessage",params:e},Ys,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},Lo,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},Lo,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(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof z?i:new z(Z.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,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},Pp,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 jS=Symbol.for("mcp.completable");function $m(t){return!!t&&typeof t=="object"&&jS in t}function LS(t){return t[jS]?.complete}var DS;(function(t){t.Completable="McpCompletable"})(DS||(DS={}));var JD=/^[A-Za-z0-9._-]{1,128}$/;function XD(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"),!JD.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 YD(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 Om(t){let e=XD(t);return YD(t,e.warnings),e.isValid}var Hc=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 Uc=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 zc(e,n)}get experimental(){return this._experimental||(this._experimental={tasks:new Hc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(Zr)),this.server.assertCanSetRequestHandler(lr(jo)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zr,()=>({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=$o(n.inputSchema);return o?Np(o,{strictUnions:!0,pipeStrategy:"input"}):QD})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=$o(n.outputSchema);o&&(r.outputSchema=Np(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(jo,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new z(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new z(Z.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(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new z(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(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===Z.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=$o(e.inputSchema)??e.inputSchema,i=await Ca(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=$a(a);throw new z(Z.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(Z.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=$o(e.outputSchema),s=await Ca(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=$a(i);throw new z(Z.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(Z.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(lr(Ja)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ja,async e=>{switch(e.params.ref.type){case"ref/prompt":return db(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return pb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new z(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,n){let r=this._registeredPrompts[n.name];if(!r)throw new z(Z.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new z(Z.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Ci;let s=Qn(r.argsSchema)?.[e.params.argument.name];if(!$m(s))return Ci;let i=LS(s);if(!i)return Ci;let a=await i(e.params.argument.value,e.params.context);return HS(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 Ci;throw new z(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ci;let s=await o(e.params.argument.value,e.params.context);return HS(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(No)),this.server.assertCanSetRequestHandler(lr(Mo)),this.server.assertCanSetRequestHandler(lr(Wa)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(No,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(Mo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Wa,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new z(Z.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(Z.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(lr(Do)),this.server.assertCanSetRequestHandler(lr(Ka)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Do,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?ej(n.argsSchema):void 0}))})),this.server.setRequestHandler(Ka,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new z(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new z(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=$o(r.argsSchema),s=await Ca(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=$a(c);throw new z(Z.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:Fr(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=Fr(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 gt?c._def?.innerType:c;return $m(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){Om(e);let l={title:n,description:r,inputSchema:zS(o),outputSchema:zS(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"&&Om(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=Fr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Fr(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(Im(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!Im(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 QD={type:"object",properties:{}};function US(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function FS(t){return"_def"in t||"_zod"in t||US(t)}function Im(t){return typeof t!="object"||t===null||FS(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(US)}function zS(t){if(t){if(Im(t))return Fr(t);if(!FS(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function ej(t){let e=Qn(t);return e?Object.entries(e).map(([n,r])=>{let o=w_(r),s=T_(r);return{name:n,description:o,required:!s}}):[]}function lr(t){let n=Qn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=Oa(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function HS(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ci={completion:{values:[],hasMore:!1}};import BS from"node:process";var Fc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
`);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),tj(n)}clear(){this._buffer=void 0}};function tj(t){return rb.parse(JSON.parse(t))}function ZS(t){return JSON.stringify(t)+`
`}var Zc=class{constructor(e=BS.stdin,n=BS.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Fc,this._started=!1,this._ondata=r=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=r=>{this.onerror?.(r)}}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=ZS(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as MT}from"node:module";import{existsSync as ze,unlinkSync as Es,readdirSync as DT,readFileSync as oa,writeFileSync as Vu,writeSync as CH,renameSync as $H,rmSync as jT,mkdirSync as OH,statSync as LT,symlinkSync as IH,lstatSync as zT,realpathSync as HT}from"node:fs";import{spawnSync as Wu}from"node:child_process";import{join as ft,dirname as _o,resolve as pt,sep as AH,isAbsolute as NH}from"node:path";import{fileURLToPath as MH}from"node:url";import{homedir as ws,tmpdir as Lg,cpus as DH}from"node:os";import{request as jH}from"node:https";import{AsyncLocalStorage as LH}from"node:async_hooks";Vc();import{spawn as QS,execSync as pj,execFileSync as rv}from"node:child_process";import{mkdtempSync as fj,writeFileSync as ev,rmSync as mj,existsSync as tv}from"node:fs";import{join as Gc,resolve as ov}from"node:path";import{tmpdir as hj}from"node:os";var vt=process.platform==="win32",gj={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 yj(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.${gj[t]}`}function _j(t){return{windowsHide:t==="win32"}}function bj(t){return`'${t.replace(/'/g,"'\\''")}'`}function xj(t,e,n){return n==="win32"||!e?t:`export PATH=${bj(e)}
${t}`}function kj(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function Sj(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
`)}var vj=(()=>{if(vt)return process.env.TEMP??process.env.TMP??hj();try{let t=rv(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:ov(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function Ej(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
`]),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===`
`){r+="mvn.cmd",s+=3,o=!1;continue}}r+=i,o=n.has(i),s++}return r}function nv(t){try{mj(t,{recursive:!0,force:!0,maxRetries:vt?8:2,retryDelay:100})}catch{}}function Lm(t){if(vt&&t.pid)try{pj(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Ii=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??Wc()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(vt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:n,code:r,timeout:o,background:s=!1,cwd:i}=e,a=fj(Gc(vj,".ctx-mode-"));try{let c=this.#a(a,r,n),u=YS(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||nv(a),d}catch(c){throw nv(a),c}}async executeFile(e){let{path:n,language:r,code:o,timeout:s}=e,i=ov(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
import "fmt"
func main() {
${n}
}
`),r==="php"&&!n.trimStart().startsWith("<?")&&(n=`<?php
${n}`),r==="elixir"&&tv(Gc(this.#s,"mix.exs"))&&(n=`Path.wildcard(Path.join(${JSON.stringify(Gc(this.#s,"_build/dev/lib"))}, "*/ebin"))
|> Enum.each(&Code.prepend_path/1)
${n}`);let o=Gc(e,yj(r,process.platform,r==="shell"?this.#n.shell:null));if(r==="shell"){let s=this.#n.shell,i=Ej(n,process.platform),a=vt&&kj(s)?Sj(i):i;ev(o,xj(a,process.env.PATH,process.platform),{encoding:"utf-8",mode:448})}else ev(o,n,"utf-8");return o}async#c(e,n,r){let o=vt?".exe":"",s=e.replace(/\.rs$/,"")+o;try{rv("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:
${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=vt&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;vt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=vt?e.slice(1).map(b=>b.replace(/\\/g,"/")):e.slice(1);let l={cwd:n,stdio:["ignore","pipe","pipe"],env:this.#u(r),detached:!vt,..._j(process.platform)},d;if(a){let b=[c,...u].map(k=>/\s/.test(k)?JSON.stringify(k):k).join(" ");d=QS(b,[],{...l,shell:!0})}else d=QS(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 b=Buffer.concat(h).toString("utf-8"),k=Buffer.concat(g).toString("utf-8");i({stdout:b,stderr:k,exitCode:0,timedOut:!0,backgrounded:!0})}else Lm(d)},o),h=[],g=[],y=0,_=!1;d.stdout.on("data",b=>{y+=b.length,y<=this.#e?h.push(b):_||(_=!0,Lm(d))}),d.stderr.on("data",b=>{y+=b.length,y<=this.#e?g.push(b):_||(_=!0,Lm(d))}),d.on("close",b=>{if(clearTimeout(p),m)return;let k=Buffer.concat(h).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");_&&(v+=`
[output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:k,stderr:v,exitCode:f?1:b??1,timedOut:f})}),d.on("error",b=>{clearTimeout(p),!m&&i({stdout:"",stderr:b.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",vt&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=vt?"":"/usr/local/bin:/usr/bin:/bin"),vt){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=vt?[]:["/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(tv(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};
const file_path = FILE_CONTENT_PATH;
const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
${r}`;case"python":return`FILE_CONTENT_PATH = ${o}
file_path = FILE_CONTENT_PATH
with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
FILE_CONTENT = _f.read()
${r}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
file_path=${s}
FILE_CONTENT=$(cat ${s})
${r}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
file_path = FILE_CONTENT_PATH
FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
${r}`;case"go":return`package main
import (
"fmt"
"os"
)
var FILE_CONTENT_PATH = ${o}
var file_path = FILE_CONTENT_PATH
func main() {
b, _ := os.ReadFile(FILE_CONTENT_PATH)
FILE_CONTENT := string(b)
_ = FILE_CONTENT
_ = fmt.Sprint()
${r}
}
`;case"rust":return`#![allow(unused_variables)]
use std::fs;
fn main() {
let file_content_path = ${o};
let file_path = file_content_path;
let file_content = fs::read_to_string(file_content_path).unwrap();
${r}
}
`;case"php":return`<?php
$FILE_CONTENT_PATH = ${o};
$file_path = $FILE_CONTENT_PATH;
$FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
${r}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
my $file_path = $FILE_CONTENT_PATH;
open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
my $FILE_CONTENT = do { local $/; <$fh> };
close($fh);
${r}`;case"r":return`FILE_CONTENT_PATH <- ${o}
file_path <- FILE_CONTENT_PATH
FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
${r}`;case"elixir":return`file_content_path = ${o}
file_path = file_content_path
file_content = File.read!(file_content_path)
${r}`;case"csharp":return`var FILE_CONTENT_PATH = ${o};
var file_path = FILE_CONTENT_PATH;
var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
${r}`}}};import{cpus as wj}from"node:os";async function zm(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,wj().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}}no();import{readFileSync as pv,readdirSync as _v,unlinkSync as Vm,existsSync as qm,statSync as Yc,openSync as fv,fstatSync as mv,closeSync as hv}from"node:fs";import{createHash as gv}from"node:crypto";import{tmpdir as bv}from"node:os";import{join as Wm}from"node:path";import{readdirSync as Nj,statSync as Mj,lstatSync as Dj,realpathSync as av,existsSync as jj,readFileSync as Lj}from"node:fs";import{join as uv,extname as zj,relative as lv,sep as Hj,resolve as Uj}from"node:path";var Fj=["node_modules",".git","dist","build",".next","coverage",".venv","__pycache__",".DS_Store"],Zj=[".md",".mdx",".txt",".json",".yaml",".yml",".ts",".tsx",".js",".jsx",".py",".rs",".go",".sh"],Bj=5,qj=200;function Vj(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 cv(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=Vj(r);if(o.test(t)||o.test(n))return!0}return!1}function Wj(t){let e=uv(t,".gitignore");if(!jj(e))return[];try{return Lj(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 Kj(t,e){return lv(t,e).split(Hj).join("/")}function dv(t,e={}){let{include:n,exclude:r,maxDepth:o=Bj,maxFiles:s=qj,extensions:i,respectGitignore:a=!0,followSymlinks:c=!1}=e,u;try{u=av(t)}catch{return{files:[],capped:!1,totalSeen:0}}let l=(i&&i.length>0?i:Zj).map(_=>(_.startsWith(".")?_:"."+_).toLowerCase()),d=[...Fj,...r??[],...a?Wj(u):[]],f=n??[],m=[],p=new Set([u]),h=0,g=!1;function y(_,b){if(g||b>o)return;let k;try{k=Nj(_,{withFileTypes:!0})}catch{return}for(let v of k){if(g)return;let O=uv(_,v.name),P=Kj(u,O);if(cv(P,d))continue;let j=v.isDirectory(),D=v.isFile(),V=!1;try{V=Dj(O).isSymbolicLink()}catch{continue}if(V){if(!c)continue;let R;try{R=av(O)}catch{continue}let H=lv(u,R);if((H.startsWith("..")||Uj(H)===R)&&H.startsWith("..")||p.has(R))continue;p.add(R);try{let se=Mj(R);j=se.isDirectory(),D=se.isFile()}catch{continue}}if(j){y(O,b+1);continue}if(!D)continue;let w=zj(O).toLowerCase();if(l.includes(w)&&!(f.length>0&&!cv(P,f))){if(h++,m.length>=s){g=!0;return}m.push(O)}}}return y(u,0),{files:m,capped:g,totalSeen:h}}var ss=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 xv(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 Gj(t,e="AND"){let n=xv(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=>!ss.has(s.toLowerCase()));return(r.length>0?r:n).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function Jj(t,e="AND"){let n=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(n.length<3)return"";let r=xv(n.split(/\s+/).filter(i=>i.length>=3));if(r.length===0)return"";let o=r.filter(i=>!ss.has(i.toLowerCase()));return(o.length>0?o:r).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function Xj(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 Yj(t){return t<=4?1:t<=12?2:3}var Xc=4096,Qj=3,eL=200,tL=5e3,yv=80,nL=.5;function Km(){let t=bv(),e=0;try{let n=_v(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=Wm(t,r);for(let a of["","-wal","-shm"])try{Vm(i+a)}catch{}e++}}}catch{}return e}function Gm(t,e){let n=0;try{if(!qm(t))return 0;let r=Date.now()-e*24*60*60*1e3,o=_v(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Wm(t,s),c=Yc(i).mtimeMs<r;if(!c){let u=i+"-wal";if(qm(u))try{let l=Yc(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Vm(i+u)}catch{}n++}}catch{}}catch{}return n}function rL(t,e){let n=[],r=t.indexOf(e);for(;r!==-1;)n.push(r),r=t.indexOf(e,r+1);return n}function oL(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 sL(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 Qc=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#h;#g;#y;#_;#b;#x;#k;#S;#v;#E;#w;#T;#R;#P;#C;#$;#O;#I;#A;#N;#M;#D;#j=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let n=Be();this.#t=e??Wm(bv(),`context-mode-${process.pid}.db`),to(this.#t);let r;try{r=new n(this.#t,{timeout:3e4}),eo(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Bm(s)){Zm(this.#t),to(this.#t);try{r=new n(this.#t,{timeout:3e4}),eo(r)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=r,this.#Z(),this.#B()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Vm(this.#t+e)}catch{}}#Z(){this.#e.exec(`
CREATE TABLE IF NOT EXISTS sources (
id INTEGER PRIMARY KEY AUTOINCREMENT,
label TEXT NOT NULL,
chunk_count INTEGER NOT NULL DEFAULT 0,
code_chunk_count INTEGER NOT NULL DEFAULT 0,
indexed_at TEXT NOT NULL DEFAULT (datetime('now')),
file_path TEXT,
content_hash TEXT
);
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
title,
content,
source_id UNINDEXED,
content_type UNINDEXED,
source_category UNINDEXED,
session_id UNINDEXED,
event_id UNINDEXED,
timestamp UNINDEXED,
tokenize='porter unicode61'
);
CREATE VIRTUAL TABLE IF NOT EXISTS chunks_trigram USING fts5(
title,
content,
source_id UNINDEXED,
content_type UNINDEXED,
source_category UNINDEXED,
session_id UNINDEXED,
event_id UNINDEXED,
timestamp UNINDEXED,
tokenize='trigram'
);
CREATE TABLE IF NOT EXISTS vocabulary (
word TEXT PRIMARY KEY
);
CREATE INDEX IF NOT EXISTS idx_sources_label ON sources(label);
`);try{let e=this.#e.prepare("SELECT name FROM pragma_table_xinfo('chunks')").all(),n=new Set(e.map(r=>r.name));e.length>0&&!n.has("source_category")&&(this.#e.exec("DROP TABLE IF EXISTS chunks"),this.#e.exec("DROP TABLE IF EXISTS chunks_trigram"),this.#e.exec(`
CREATE VIRTUAL TABLE chunks USING fts5(
title,
content,
source_id UNINDEXED,
content_type UNINDEXED,
source_category UNINDEXED,
session_id UNINDEXED,
event_id UNINDEXED,
timestamp UNINDEXED,
tokenize='porter unicode61'
);
CREATE VIRTUAL TABLE chunks_trigram USING fts5(
title,
content,
source_id UNINDEXED,
content_type UNINDEXED,
source_category UNINDEXED,
session_id UNINDEXED,
event_id UNINDEXED,
timestamp UNINDEXED,
tokenize='trigram'
);
`))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#B(){this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#h=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ?
ORDER BY rank
LIMIT ?
`),this.#g=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\'
ORDER BY rank
LIMIT ?
`),this.#y=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ? AND sources.label = ?
ORDER BY rank
LIMIT ?
`),this.#_=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ?
ORDER BY rank
LIMIT ?
`),this.#b=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\'
ORDER BY rank
LIMIT ?
`),this.#x=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ? AND sources.label = ?
ORDER BY rank
LIMIT ?
`),this.#S=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ? AND chunks.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#v=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#E=this.#e.prepare(`
SELECT
chunks.title,
chunks.content,
chunks.content_type,
chunks.timestamp,
sources.label,
bm25(chunks, 5.0, 1.0) AS rank,
highlight(chunks, 1, char(2), char(3)) AS highlighted,
chunks.session_id
FROM chunks
JOIN sources ON sources.id = chunks.source_id
WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#w=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#T=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ? AND sources.label LIKE ? ESCAPE '\\' AND chunks_trigram.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#R=this.#e.prepare(`
SELECT
chunks_trigram.title,
chunks_trigram.content,
chunks_trigram.content_type,
chunks_trigram.timestamp,
sources.label,
bm25(chunks_trigram, 5.0, 1.0) AS rank,
highlight(chunks_trigram, 1, char(2), char(3)) AS highlighted,
chunks_trigram.session_id
FROM chunks_trigram
JOIN sources ON sources.id = chunks_trigram.source_id
WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
ORDER BY rank
LIMIT ?
`),this.#k=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#P=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#C=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
FROM chunks c
JOIN sources s ON s.id = c.source_id
WHERE c.source_id = ?
ORDER BY c.rowid`),this.#$=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#O=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#A=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#I=this.#e.prepare(`
SELECT
(SELECT COUNT(*) FROM sources) AS sources,
(SELECT COUNT(*) FROM chunks) AS chunks,
(SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
`),this.#N=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#M=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content: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=fv(r,"r");try{if(!mv(f).isFile())throw new Error(`refusing to index ${r}: not a regular file`);a=pv(f,"utf-8")}finally{hv(f)}}let c=o??r??"untitled",u=this.#K(a),l=r??void 0,d=l?gv("sha256").update(a).digest("hex"):void 0;return xn(()=>this.#d(u,c,a,l,d,s))}indexDirectory(e){let{path:n,source:r,attribution:o,perFileDeny:s,...i}=e,a=dv(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=Xc){if(!e||e.trim().length===0)return this.#d([],n,"",void 0,void 0,o);let i=this.#J(e,r,s);return xn(()=>this.#d(i.map(a=>({...a,hasCode:!1})),n,e,void 0,void 0,o))}indexJSON(e,n,r=Xc,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=[];return this.#F(s,[],i,r),i.length===0?this.indexPlainText(e,n,void 0,o,r):xn(()=>this.#d(i,n,e,void 0,void 0,o))}#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=Gj(e,o),c,u;return 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.#S,u=[a,s,n]):(c=this.#h,u=[a,n]),xn(()=>this.#L(c.all(...u)))}searchTrigram(e,n=3,r,o="AND",s,i="like"){let a=Jj(e,o);if(!a)return[];let c,u;return r&&s?(c=i==="exact"?this.#R:this.#T,u=[a,this.#p(r,i),s,n]):r?(c=i==="exact"?this.#x:this.#b,u=[a,this.#p(r,i),n]):s?(c=this.#w,u=[a,s,n]):(c=this.#_,u=[a,n]),xn(()=>this.#L(c.all(...u)))}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=Yj(n.length),o=this.#k.all(n.length-r,n.length+r),s=null,i=r+1,a=!1;for(let{word:u}of o){if(u===n){a=!0;break}let l=Xj(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=>!ss.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=>rL(m,h));if(!p.some(h=>h.length===0)){d=1/(1+sL(p)/Math.max(m.length,1));let g=oL(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&&!ss.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=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let n of e)try{if(!qm(n.file_path)||this.#n&&this.#n(n.file_path))continue;let r=Yc(n.file_path).mtime,o=new Date(n.indexed_at+"Z");if(r<=o)continue;let s=fv(n.file_path,"r"),i;try{if(!mv(s).isFile())continue;i=pv(s,"utf-8")}finally{hv(s)}if(gv("sha256").update(i).digest("hex")===n.content_hash)continue;this.index({content:i,path:n.file_path,source:n.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let n=this.#A.get(e);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(){return this.#P.all()}getIndexState(){let e=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();return{totalChunks:e.total_chunks??0,totalSources:e.total_sources??0,lastIndexedAt:e.last_indexed_at??void 0}}getChunksBySource(e){return this.#C.all(e).map(r=>({title:r.title,content:r.content,source:r.label,rank:0,contentType:r.content_type}))}getDistinctiveTerms(e,n=40){let r=this.#$.get(e);if(!r||r.chunk_count<3)return[];let o=r.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#O.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(f=>f.length>=3&&!ss.has(f)));for(let f of d)a.set(f,(a.get(f)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let f=Math.log(o/d),m=Math.min(l.length/20,.5),p=/[_]/.test(l),h=l.length>=12,g=p?1.5:h?.8:0;return{word:l,score:f+m+g}}).sort((l,d)=>d.score-l.score).slice(0,n).map(l=>l.word)}getStats(){let e=this.#I.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#N.run(o),this.#M.run(o),this.#D.run(o)))(e).changes}getDBSizeBytes(){try{return Yc(this.#t).size}catch{return 0}}#U(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#U(),Ni(this.#e)}#W(e){let n=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!ss.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=Xc){let r=[],o=e.split(`
`),s=[],i=[],a="",c=()=>{let l=i.join(`
`).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(`
`).trim();if(y.length===0)return;let _=m.length>1?`${d} (${h})`:d;h++,r.push({title:_,content:y,hasCode:y.includes("```")}),p=[]};for(let y of m){p.push(y);let _=p.join(`
`);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(`
`),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(`
`),g=Math.max(p,h);g>f.length*nL&&(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(`
`)+`
`+c:c;Buffer.byteLength(u)>r&&s.length>0&&a(),s.push(c)}return a(),o}#J(e,n,r=Xc){let o=e.split(/\n\s*\n/);if(o.length>=Qj&&o.length<=eL&&o.every(u=>Buffer.byteLength(u)<tL))return o.flatMap((u,l)=>{let d=u.trim();if(d.length===0)return[];let f=d.split(`
`)[0].slice(0,yv)||`Section ${l+1}`;return Buffer.byteLength(d)<=r?[{title:f,content:d}]:this.#f(d.split(`
`),f,r)});let s=e.split(`
`);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,yv),p=l.join(`
`);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 Jm(t,e){return t===void 0?e:`${t}::${e}`}no();function kv(t){try{let e=new URL(t);return e.hash="",e.toString()}catch{return t}}function Sv(t){try{return new URL(t).host.toLowerCase()}catch{return""}}var eu=class{#e;constructor(e){let n=Be();to(e),this.#e=new n(e,{timeout:3e4}),eo(this.#e),this.#e.exec(`
CREATE TABLE IF NOT EXISTS pages (
page_key TEXT PRIMARY KEY,
host TEXT NOT NULL,
url TEXT NOT NULL,
source_label TEXT NOT NULL,
route TEXT NOT NULL,
provisional INTEGER NOT NULL DEFAULT 0,
fetched_at TEXT NOT NULL DEFAULT (datetime('now')),
full_text TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS page_blocks (
page_key TEXT NOT NULL,
ordinal INTEGER NOT NULL,
hash TEXT NOT NULL,
kind TEXT NOT NULL,
raw TEXT NOT NULL,
text TEXT NOT NULL,
PRIMARY KEY (page_key, ordinal)
);
CREATE INDEX IF NOT EXISTS idx_pages_host ON pages(host);
CREATE INDEX IF NOT EXISTS idx_page_blocks_hash ON page_blocks(hash);
`)}hostPageCount(e,n){let r=this.#e.prepare("SELECT COUNT(*) AS n FROM pages WHERE host = ? AND page_key <> ?").get(e,n);return r?r.n:0}otherPageCounts(e,n,r){let o=new Map;if(r.length===0)return o;let s=Array.from(new Set(r)),i=this.#e.prepare(`SELECT COUNT(DISTINCT b.page_key) AS n
FROM page_blocks b
JOIN pages p ON p.page_key = b.page_key
WHERE b.hash = ? AND p.host = ? AND b.page_key <> ?`);for(let a of s){let c=i.get(a,e,n);o.set(a,c?c.n:0)}return o}recordPage(e,n){let r=this.#e.prepare(`INSERT INTO pages (page_key, host, url, source_label, route, provisional, fetched_at, full_text)
VALUES (?, ?, ?, ?, ?, ?, datetime('now'), ?)
ON CONFLICT(page_key) DO UPDATE SET
host = excluded.host, url = excluded.url, source_label = excluded.source_label,
route = excluded.route, provisional = excluded.provisional,
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)});xn(()=>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)});xn(()=>i())}provisionalPages(e,n){return this.#e.prepare(`SELECT page_key, host, url, source_label, route, provisional, full_text
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 iL}from"node:crypto";function Xm(t,e){return t.lastIndexOf(e,0)===0}function Ym(t){return t===" "||t===" "||t===`
`||t==="\r"||t==="\f"||t==="\v"}function Qm(t){let e=0,n=t.length;for(;e<n&&Ym(t.charAt(e));)e++;for(;n>e&&Ym(t.charAt(n-1));)n--;return e===0&&n===t.length?t:t.substring(e,n)}function aL(t){let e=[],n=0;for(let r=0;r<t.length;r++)t.charAt(r)===`
`&&(e.push(t.substring(n,r+1)),n=r+1);return n<t.length&&e.push(t.substring(n)),e}function vv(t){let e=[];if(t.length===0)return e;let n=aL(t),r=[],o=!1,s=!1,i=!1,a=()=>{if(r.length===0)return;let c=r.join(""),u=Qm(c);e.push({ordinal:e.length,raw:c,text:u,hash:uL(u)}),r=[],o=!1};for(let c of n){let u=Qm(c),l=Xm(u,"```")||Xm(u,"~~~"),d=!s&&u.length===0,f=!s&&!l&&Xm(u,"#");!d&&(i||f)&&o&&(a(),i=!1),l&&(s=!s),r.push(c),d||(o=!0),d&&(i=!0)}return a(),e}function cL(t){let e="",n=!1;for(let r=0;r<t.length;r++){let o=t.charAt(r);if(Ym(o)){n=!0;continue}n&&e.length>0&&(e+=" "),n=!1,e+=o}return e.toLowerCase()}function uL(t){return iL("sha256").update(cL(t),"utf-8").digest("hex")}function eh(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 th(t){let e="";for(let n of t)n.kind==="content"&&(e+=n.raw);return Qm(e)}function Ev(t){return t==="json"||t==="text"}function wv(t){let{url:e,sourceLabel:n,document:r,route:o,store:s}=t,i=kv(e),a=Sv(e),c=Buffer.byteLength(r,"utf-8"),u=vv(r),l=o==="markdown",d=s.hostPageCount(a,i),f=l?new Map:s.otherPageCounts(a,i,u.map(h=>h.hash)),m=eh({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(b=>b.hash)),_=eh({blocks:g.map(b=>({ordinal:b.ordinal,raw:b.raw,text:b.text,hash:b.hash})),otherPageCount:b=>y.get(b)??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:th(_.blocks),templateBytes:_.templateBytes}))}return{kind:"index",indexText:th(m.blocks),storedBytes:c,contentBytes:m.contentBytes,templateBytes:m.templateBytes,templateBlocks:lL(m.blocks),totalBlocks:m.blocks.length,provisional:m.provisional,route:o,relabelled:p}}function lL(t){let e=0;for(let n of t)n.kind==="template"&&e++;return e}so();import{readFileSync as Uw,realpathSync as gg}from"node:fs";import{relative as N1,resolve as go,sep as M1}from"node:path";function Fw(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function D1(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function j1(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function Hw(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function L1(t,e=!1){let n,r=t.indexOf(":");if(r!==-1){let o=t.slice(0,r),s=t.slice(r+1),i=j1(o),a=Hw(s);n=`^${i}(\\s${a})?$`}else n=`^${Hw(t)}$`;return new RegExp(n,e?"i":"")}function z1(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 H1(t,e,n=!1){for(let r of e){let o=Fw(r);if(o&&L1(o,n).test(t))return r}return null}function Zw(t,e){let n=0;for(let r=e-1;r>=0&&t[r]==="\\";r--)n++;return n%2===1}function U1(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=Zw(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===`
`||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 Bw(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=Zw(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(...Bw(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 qw(t){let e=[],n=U1(t);for(let r of n){e.push(r);for(let o of Bw(r))e.push(...qw(o))}return e}function hg(t){let e;try{e=Uw(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"&&Fw(i)!==null):[];return{allow:o(r.allow),deny:o(r.deny),ask:o(r.ask)}}function yg(t,e){let n=[];if(t){let o=go(t,".claude","settings.local.json"),s=hg(o);s&&n.push(s);let i=go(t,".claude","settings.json"),a=hg(i);a&&n.push(a)}let r=e!==void 0?[e]:mg();for(let o of r){let s=hg(o);s&&n.push(s)}return n}function Tu(t,e,n){return _g(t,"deny",e,n)}function _g(t,e,n,r){let o=[],s=a=>{let c;try{c=Uw(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=D1(f);m&&m.tool===t&&d.push(m.glob)}return d};if(n){let a=s(go(n,".claude","settings.local.json"));a!==null&&o.push(a);let c=s(go(n,".claude","settings.json"));c!==null&&o.push(c)}let i=r!==void 0?[r]:mg();for(let a of i){let c=s(a);c!==null&&o.push(c)}return o}function bg(t,e,n=process.platform==="win32"||process.platform==="darwin"){let r=qw(t);for(let o of r)for(let s of e){let i=H1(o,s.deny,n);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Gi(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=go(r,t);s.add(o(i));try{s.add(o(gg(i)))}catch{}}for(let i of e)for(let a of i){let c=z1(o(a),n);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function F1(t,e,n=process.platform==="win32"||process.platform==="darwin"){if(!e)return!0;let r=go(e),o=go(e,t),s=(i,a)=>{let c=i,u=a;if(n&&(c=c.toLowerCase(),u=u.toLowerCase()),c===u)return!0;let l=N1(c,u);return l===""?!0:!(l===".."||l.startsWith(".."+M1)||Z1(l))};if(!s(r,o))return!1;try{let i=gg(r),a=gg(o);if(!s(i,a))return!1}catch{}return!0}function Z1(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 Vw(t,e,n=[],r=process.platform==="win32"||process.platform==="darwin"){return F1(t,e,r)?{allowed:!0,reason:"inside"}:n.some(o=>o.length>0)&&Gi(t,n,r,e).denied?{allowed:!0,reason:"allow-rule"}:{allowed:!1,reason:"outside"}}var B1={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 q1(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 Ww(t,e){let n=B1[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(...q1(t)),r}Vc();function xg(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}
stdout:
${r}
stderr:
${o}`}}import{execFileSync as V1}from"node:child_process";function W1(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=V1("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 K1(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??W1,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var G1=K1();function J1(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 X1(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 Y1(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 Ji=Date.now(),Ru=0;function kg(){Ji=Date.now()}function Kw(){Ru++,Ji=Date.now()}function Gw(){Ru>0&&Ru--,Ji=Date.now()}function Jw(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{kg()}catch{}return e(n,r)})}function Xw(t){let e=t.checkIntervalMs??J1(),n=t.isParentAlive??G1,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??X1(),u;return c>0&&(Ji=Date.now(),u=setInterval(()=>{Ru===0&&Date.now()-Ji>=c&&(process.stderr.write(Y1(c)+`
`),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 Yw(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)}Sn();no();Sn();import{existsSync as Sg,unlinkSync as Q1}from"node:fs";import{join as Xi}from"node:path";var eH=["","-wal","-shm"];function vg(t,e){try{return Q1(t),e.push(t),!0}catch{return!1}}function Pu(t,e){let n=!1;for(let r of eH)vg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function Qw(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 b=su(e),k=Qe(e),v=Ln(e),O=k===v?[k]:[k,v],P=!1;for(let V of O){let w=Xi(n,`${V}${b}.db`);if(!Sg(w))continue;let R=null;try{R=new on({dbPath:w});let H=R.getEvents(a).length;R.deleteSession(a),H>0&&(P=!0)}catch{}finally{try{R?.close()}catch{}}}P&&u.push(`session rows for ${a}`);let j=[];if(r&&Sg(r)&&j.push(r),o){let V=Qe(e),w=Ln(e),R=V===w?[V]:[V,w];for(let H of R){let se=Xi(o,`${H}.db`);Sg(se)&&!j.includes(se)&&j.push(se)}}let D=!1;for(let V of j)try{let w=Be(),R=new w(V,{timeout:3e4});try{let H=R.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;R.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),R.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(D=!0)}finally{try{R.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Pu(r,l)&&(f=!0),o){let b=Qe(e),k=Ln(e),v=b===k?[b]:[b,k];for(let O of v){let P=Xi(o,`${O}.db`);Pu(P,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 b=Xi(s,`${i}.db`);Pu(b,l)}let m=su(e),p=Qe(e),h=Ln(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let b of g){let k=Xi(n,`${b}${m}`);Pu(`${k}.db`,l)&&(y=!0),vg(`${k}-events.md`,l)&&(_=!0),vg(`${k}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}Sn();import{existsSync as tH}from"node:fs";function Eg(t,e){try{if(!tH(t))return;let n=new on({dbPath:t});try{let r=n.getLatestSessionId();if(!r)return;e(n,r)}finally{try{n.close()}catch{}}}catch{}}function eT(t){Eg(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 tT(t){Eg(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 nT(t){Eg(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})})}Sn();import{existsSync as rT}from"node:fs";function oT(t,e,n){try{if(!rT(t))return;let r=new on({dbPath:t});try{let o=r.getLatestSessionId();if(!o)return;r.incrementToolCall(o,e,n)}finally{r.close()}}catch{}}function sT(t){try{if(!rT(t))return null;let e=new on({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}}so();Sn();import{existsSync as wg,readFileSync as nH,readdirSync as rH,statSync as oH}from"node:fs";import{join as _s,isAbsolute as sH}from"node:path";var iT=process.env.DEBUG?.includes("context-mode");function cT(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?aT(n,a):null)??r??Ct(),l=o?.getMemoryDir(n),d=_s(u,"memory"),f=n?_s(d,Qe(n)):d,m=l?aT(n,l):f,p=[];if(n)for(let h of i){let g=_s(n,h);wg(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=_s(u,h);wg(g)&&p.push({path:g,label:`user/${h}`})}if(m&&wg(m))try{let h=rH(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:_s(m,g),label:`memory/${g}`})}catch(h){iT&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
`)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=oH(h.path),g.size>1e6)continue}catch{continue}let y=nH(h.path,"utf-8"),_=y.toLowerCase();for(let b of t){if(s.length>=e)break;let v=b.toLowerCase().split(/\s+/).filter(P=>P.length>=3);if(v.some(P=>{try{return new RegExp(`\\b${P.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(P)}})){let P=v.reduce((H,se)=>{let mt=_.indexOf(se);return mt>=0&&(H<0||mt<H)?mt:H},-1),j=Math.max(0,P-200),D=Math.min(y.length,P+500),V=y.lastIndexOf(`
`,j),w=y.indexOf(`
`,D);V>=0&&(j=V+2),w>=0&&(D=w);let R=y.slice(j,D).trim();s.push({title:`[auto-memory] ${h.label}`,content:R,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){iT&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
`)}}return s.slice(0,e)}function aT(t,e){return e?sH(e)||!t?e:_s(t,e):t??""}var Cu=process.env.DEBUG?.includes("context-mode");function uT(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){Cu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
`)}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){Cu&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
`)}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){Cu&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
`)}try{let h=cT([e],n,c,u,l);f.push(...h)}catch(h){Cu&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
`)}}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 iH(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 lT(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(iH,$.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 dT(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var Tg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var $u=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)}};jn();ys();Ph();jn();function aH(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 cH(t){let e=Bc(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 pT(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 aH(s)){let a=cH(i);a&&n.add(a)}return[...n]}Fi();so();ys();import*as Ue from"node:fs";import*as fT from"node:os";import*as bs from"node:path";var uH=["CONTEXT_MODE_PROJECT_DIR"],lH=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Ou(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function dH(t){if(!Ue.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Ue.readdirSync(t.projectsRoot)){let o=bs.join(t.projectsRoot,r),s;try{s=Ue.statSync(o)}catch{continue}if(!s.isDirectory())continue;let i;try{i=Ue.readdirSync(o)}catch{continue}for(let a of i){if(!a.endsWith(".jsonl"))continue;let c=bs.join(o,a);try{let u=Ue.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=Ue.openSync(e,"r");try{let o=Buffer.alloc(8192),s=Ue.readSync(r,o,0,o.length,0),i=o.subarray(0,s).toString("utf-8");for(let a of i.split(`
`).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{Ue.closeSync(r)}}catch{}}function pH(t){let e=t?.codexHome??process.env.CODEX_HOME??bs.join(fT.homedir(),".codex"),n=bs.join(e,"sessions");if(!Ue.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=Ue.readdirSync(u)}catch{return}d.sort().reverse();for(let f of d){if(s>=o)return;s++;let m=bs.join(u,f),p;try{p=Ue.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=Ue.openSync(i,"r");try{let l=Buffer.alloc(1048576),d=Ue.readSync(u,l,0,l.length,0),f=l.subarray(0,d).toString("utf-8");for(let m of f.split(`
`).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 Ou(h)?null:h}catch{return null}}finally{Ue.closeSync(u)}}catch{return null}return null}function mT(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...dg(a),...uH]:lH;for(let l of u){let d=e[l];if(d&&!Ou(d))return d}if(o){let l=dH({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Ou(l))return l}if(a==="codex"){let l=pH({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Ou(r)?r:n}no();no();Sn();so();import{execFileSync as fH}from"node:child_process";import{existsSync as Zn,readdirSync as xs,statSync as mH}from"node:fs";import{homedir as Du}from"node:os";import{join as Ot,sep as hH}from"node:path";function ST(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 Au={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"},gH={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"},ks=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((R,H)=>R+H,0),s=Object.values(e.calls).reduce((R,H)=>R+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(R=>({tool:R,calls:e.calls[R]||0,context_kb:Math.round((e.bytesReturned[R]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[R]||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 R=a+e.cacheBytesSaved,H=R/Math.max(o,1),se=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),mt=e.cacheHits+h,wn=mt>0?e.cacheHits/mt:0;p={hits:e.cacheHits,misses:h,hit_rate:wn,bytes_saved:e.cacheBytesSaved,ttl_hours_left:se,total_with_cache:R,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),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,k=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=k?!k.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),P=new Map;for(let R of O){P.has(R.category)||P.set(R.category,new Set);let H=P.get(R.category);if(H.size<5){let se=R.data;R.category==="file"?se=R.data.split("/").pop()||R.data:(R.category==="prompt"||R.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(R=>({category:R.category,count:R.cnt,label:Au[R.category]||R.category,preview:P.get(R.category)?Array.from(P.get(R.category)).join(", "):"",why:gH[R.category]||"Survives context resets"})),D=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(R=>R.cnt>0).map(R=>({category:R.category,count:R.cnt,label:Au[R.category]||R.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:b,resume_ready:v},projectMemory:{total_events:D.cnt,session_count:D.sessions,by_category:w}}}};function yH(t){let e=t?.home??Du();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=Ot(e,...o,"context-mode");return{name:r,sessionsDir:Ot(s,"sessions"),contentDir:Ot(s,"content")}})}function _H(t){let n=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return n?n[1].toLowerCase():"other"}function Yi(t){let e=Ct(),n=t?.sessionsDir??Ot(e,"context-mode","sessions"),r=t?.memoryRoot??Ot(e,"projects"),o=0,s=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Zn(n)){let m=[];try{m=xs(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Be()}catch{}if(p)for(let h of m){let g=Ot(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),b=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=b?.cnt??0;try{let k=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of k)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let k=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();k?.bytes&&(i+=k.bytes)}catch{}try{let k=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(k?.t){let v=k.t.endsWith("Z")?k.t:k.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let k=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of k)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Zn(r)){let m=[];try{m=xs(r).filter(p=>{try{return mH(Ot(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Ot(r,p,"memory");if(!Zn(h))continue;let g=[];try{g=xs(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=_H(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 vT(t){let e=t.sessionsDir??Ot(Du(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Zn(e))return r;let o=[];try{o=xs(e).filter(b=>!(!b.endsWith(".db")||t.worktreeHash&&!b.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():Be()}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=b=>Math.floor(b/864e5)*864e5;for(let b of o){let k=Ot(e,b),v=!1;try{let O=new s(k,{readonly:!0});try{let P=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let D of P)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.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 D=Date.parse(j.mn+(j.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<d&&(d=D)}if(j?.mx){let D=Date.parse(j.mx+(j.mx.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D>f&&(f=D)}try{let D=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 D){if(!V.sec)continue;let w=parseInt(V.sec,10)*1e3;if(!Number.isFinite(w))continue;let R=h(w),H=p.get(R)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(R,H)}}catch{}try{let D=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(D?.bytes&&(u+=D.bytes),D?.n&&(l+=D.n),D?.lastSec){let V=parseInt(D.lastSec,10)*1e3;if(Number.isFinite(V)&&V>m&&(m=V),Number.isFinite(V)&&(D?.bytes??0)>0){let w=h(V),R=p.get(w)??{count:0,rescueBytes:0};R.rescueBytes=Math.max(R.rescueBytes,D.bytes),p.set(w,R)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,b])=>b>0).map(([b,k])=>({category:b,count:k,label:Au[b]||b})).sort((b,k)=>k.count-b.count),_=[...p.entries()].sort((b,k)=>b[0]-k[0]).map(([b,k])=>({ms:b,count:k.count,...k.rescueBytes>0?{rescueBytes:k.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 bH(t,e,n){if(!t||!e||!Zn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():Be()}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
FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function ET(t,e){if(!t||!Zn(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():Be()}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
FROM chunks`).get();return Number(o?.bytes??0)}finally{r.close()}}catch{return 0}}function Qi(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},n=t.sessionsDir??Ot(Du(),".claude","context-mode","sessions");if(!Zn(n))return e;let r=[];try{r=xs(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():Be()}catch{return e}if(!o)return e;let s=0,i=0,a=0,c=0;for(let d of r){let f=Ot(n,d);Zv(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
FROM session_events WHERE session_id = ?`).get(t.sessionId);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);h?.bytes&&(c+=Number(h.bytes))}catch{}try{let h=m.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes FROM tool_calls
WHERE session_id = ? AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.sessionId);h?.bytes&&(a+=Number(h.bytes))}catch{}}else if(t.projectDir){let p=m.prepare(`SELECT
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
FROM session_events
WHERE session_id IN (
SELECT session_id FROM session_meta WHERE project_dir = ?
)`).get(t.projectDir);p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare(`SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes
FROM session_resume
WHERE session_id IN (
SELECT session_id FROM session_meta WHERE project_dir = ?
)`).get(t.projectDir);h?.bytes&&(c+=Number(h.bytes))}catch{}try{let h=m.prepare(`SELECT COALESCE(SUM(bytes_returned), 0) AS bytes
FROM tool_calls
WHERE session_id IN (
SELECT session_id FROM session_meta WHERE project_dir = ?
)
AND tool IN ('ctx_search', 'ctx_fetch_and_index')`).get(t.projectDir);h?.bytes&&(a+=Number(h.bytes))}catch{}}else{let p=m.prepare(`SELECT
COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
COALESCE(SUM(bytes_returned), 0) AS bytes_returned
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
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=bH(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 xH={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function kH(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(!Zn(t.sessionsDir))return r;let o=[];try{o=xs(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=Ot(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=yH({home:t?.home}),n=t?.loadDatabase??Be,r={...xH,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Zn(c.sessionsDir))continue;let u=kH(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 wT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},SH={"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 Nu(t){return SH[t]??t}function tt(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 vH(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 Iu(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function EH(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!Iu(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=fH("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!Iu(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!Iu(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 Iu(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function hT(t){let e=Du();return e?t===e?"~":t.startsWith(e+hH)?"~"+t.slice(e.length):t:t}function wH(t,e,n){if(!Number.isFinite(e)||e<=0)return[];let r=e*ea(),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 ${tt(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 TH(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*xT,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*xT,_=Math.round((n?.rescueBytes??0)/4),b=y+_,k=o?.lifetime?.totalSavedTokens??0,v=Math.max(b,k),O=o?.lifetime?.bytesReturned??0,P=o?.lifetime?.bytesAvoided??0,j=O+P>0?Math.max(1,Math.floor(O/4)):Math.max(1,Math.round(v*.02)),D=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`,R=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=R>0?Math.max(1,Math.round((c-R)/864e5)):0,se=r?.totalSessions??n?.totalSessions??1,mt=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,wn;if(r&&mt>=2)wn=`across ${mt} AI tools`;else if(r&&mt===1){let Ne=r.perAdapter.find(Wt=>Wt.isReal);wn=`in ${Ne?Nu(Ne.name):"Claude Code"}`}else wn="in Claude Code";H>0?d.push(` Across ${H} days you ran ${sn(se)} conversations ${wn}.`):d.push(` You ran ${sn(se)} conversations ${wn}.`);let Qu=H>0?D/H:0;d.push(` context-mode kept ${tt(D)} out of your context window \u2014 about ${tt(Qu)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let qg=e.firstEventMs&&e.firstEventMs>0?gT(e.firstEventMs,i,a):"";if(qg?d.push(` This conversation started ${qg} in ${hT(s)}.`):d.push(` This conversation lives in ${hT(s)}.`),d.push(` ${w}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?gT(e.lastRescueMs,i,a):"",Wt=Math.round(e.snapshotBytes/1024);Ne?d.push(` On ${Ne}, /compact fired \u2014 ${Wt} KB rescued from snapshot.`):d.push(` /compact fired \u2014 ${Wt} KB rescued from snapshot.`),d.push(" Without that, you'd be re-explaining everything to a blank model right now.")}d.push("");let Vg=o?.conversation,Wg=Vg?.bytesAvoided??0,el=Vg?.bytesReturned??0;if(Wg+el===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=Wg+el,Wt=Math.max(1,el),Kt=Math.max(1,Math.floor(Ne/4)),Tn=Math.max(1,Math.floor(Wt/4)),tl=_r(Kt,Kt,32),eR=_r(Tn,Kt,32),tR=(1-Tn/Kt)*100,nR=Math.max(1,Math.round(Kt/Tn));d.push(` Without context-mode ${tt(Ne).padStart(8)} ${tl} ${sn(Kt).padStart(7)} tokens`),d.push(` With context-mode ${tt(Wt).padStart(8)} ${eR} ${sn(Tn).padStart(7)} tokens`),d.push(` ${tR.toFixed(1)}% kept out of context \xB7 your AI ran ${nR}\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 ${tt(V)} built up \u2014 ${Ne} days, ${e.byDay.length} active:`),d.push(""),d.push(...PH(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 JT=e.byCategory.reduce((Ne,Wt)=>Ne+Wt.count,0).toLocaleString(i);d.push(` ${JT} things \u2014 files, errors, decisions, agent runs:`),d.push("");let XT=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${_r(Ne.count,XT,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Kg=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Gg=R>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(R)):"",Jg=n?.distinctProjects??0,YT=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${tt(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Kg?` \xB7 started ${Kg}`:""}.`),d.push(` All your work: ${tt(D)} kept out \xB7 ${YT.toLocaleString(i)} captures across ${Jg} project${Jg===1?"":"s"}${Gg?` \xB7 since ${Gg}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...wH(D,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((Kt,Tn)=>Tn[1]-Kt[1]),Wt=Ne.length>0?Ne[0][1]:1;for(let[Kt,Tn]of Ne){let tl=wT[Kt]??Kt;d.push(` ${tl.padEnd(26)} ${String(Tn).padStart(2)} ${_r(Tn,Wt,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 QT=u?`v${u}`:"context-mode";return d.push(` ${QT}`),u&&l&&l!=="unknown"&&ST(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),RH(d)}function RH(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 PH(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 gT(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 sn(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ea(){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 v3=5/1e6;function Mu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*ea()).toFixed(2)}`}function _r(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 yT(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 ${sn(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${sn(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":`${sn(h)} sessions`,y=a*256+n;o.push(` ${sn(a)} events \xB7 ${g} \xB7 ~${Mu(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:Au[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)} ${_r(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 _T(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=wT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${_r(s,r,20)}`)}return e}function bT(t,e){let n=[],r=Mu(t),o=(e?.totalEvents??0)*256+t,s=Mu(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 xT=256;function kT(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?sn(u.eventCount):"\u2014",f=tt(u.dataBytes),m=tt(l);r.push(` ${Nu(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=>Nu(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 Lu(t,e,n,r){let o=[],s=vH(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,P=i?.firstEventMs??0,j=P>0?Math.max(1,Math.round((Date.now()-P)/864e5)):0,D=j>0?`Across ${j} day${j===1?"":"s"} `:"",V=O>0?`you ran ${sn(O)} conversation${O===1?"":"s"} `:"you ran ",w;if(d>=2)w=`across ${d} AI tools`;else{let R=l.perAdapter.find(H=>H.isReal);w=`in ${R?Nu(R.name):"Claude Code"}`}o.push(`${D}${V}${w}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=EH(),P=r?.cwd??process.cwd(),j=r?.now??Date.now(),D=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...TH({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:P,locale:D,tz:V,now:j,version:e,latestVersion:n})),o.join(`
`)}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(`${tt(m)} entered context | 0 tokens saved`),o.push(...yT(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...kT(l)),o.push(..._T(i)),o.push(...bT(0,i)),o.push("");let O=e?`v${e}`:"context-mode";return o.push(O),e&&n&&n!=="unknown"&&ST(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
`)}o.push(`${sn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Mu(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${_r(h,h)}| ${tt(h)}`),o.push(`With context-mode |${_r(m,h)}| ${tt(m)}`),o.push(""),_>=2?o.push(`${tt(f)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):o.push(`${tt(f)} kept out of your conversation. Never entered context.`),o.push("");let b=[`${p} calls`];t.cache&&t.cache.hits>0&&b.push(`${t.cache.hits} cache hits (+${tt(t.cache.bytes_saved)})`),o.push(b.join(" \xB7 "));let k=t.savings.by_tool.filter(O=>O.calls>0);if(k.length>=2){o.push("");let O=k.map(P=>{let j=P.context_kb*1024,D=g<100?j/(1-g/100):j,V=Math.max(0,D-j);return{...P,returnedBytes:j,estimatedSaved:V}}).sort((P,j)=>j.estimatedSaved-P.estimatedSaved);for(let P of O){let j=P.tool.length>22?P.tool.slice(0,19)+"...":P.tool;o.push(` ${j.padEnd(22)} ${String(P.calls).padStart(4)} calls ${tt(P.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(P=>P.median_concurrency!=null&&(P.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 P of O){let j=P.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${j.padEnd(22)} ${P.calls} batches \xB7 ${P.median_concurrency} typical, ${P.max_concurrency} peak`)}}}o.push(...yT(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...kT(l)),o.push(..._T(i)),o.push(...bT(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(`
`)}var Zu=_o(MH(import.meta.url)),Bn=(()=>{for(let t of["../package.json","./package.json"]){let e=pt(Zu,t);if(ze(e))try{return JSON.parse(oa(e,"utf8")).version}catch{}}return"unknown"})();function UT(){return ze(pt(Zu,"package.json"))?Zu:_o(Zu)}function zH(t){try{let e=process.platform==="win32"?Wu("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):Wu("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=du(String(e.stdout));if(n&&ze(pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function FT(t){let e=UT();return t==="codex"?zH(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
`)}),process.on("uncaughtException",t=>{try{CH(2,`[context-mode] uncaughtException: ${t?.message??t}
`)}finally{process.exit(1)}}));var yo=Wc(),Bu=XS(yo),Te=new Uc({name:"context-mode",version:Bn}),HH=[];function UH(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??Et().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??FH(n);return ZH(r)&&BH(r)}function FH(t){let e=t==="kilo"?"kilo":"opencode",n=[pt(`${e}.json`),pt(`${e}.jsonc`),pt(`.${e}`,`${e}.json`),pt(`.${e}`,`${e}.jsonc`),ft(ws(),".config",e,`${e}.json`),ft(ws(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!ze(r))continue;return JSON.parse(Ui(oa(r,"utf8")))}catch{}return null}function ZH(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function BH(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var ZT=UH(),Ig=!1;function qH(t={}){if(Ig)return;Ig=!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: ["context-mode"] 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).
`)}function d5(){Ig=!1}function VH(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Zr,async()=>({tools:[]}))}var WH=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(ZT){qH();return}let o=KH(e,r);return HH.push({name:e,config:n,handler:o}),t[2]=o,WH(...t)};function KH(t,e){return async n=>{Kw();try{return await e(n)}catch(r){let o=tU(r);if(o)try{return W(t,o)}catch(s){if(s instanceof pr)return o;throw s}throw r}finally{Gw()}}}ZT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&VH(Te);var zg=new LH;async function p5(t,e){let n=typeof t=="string"?{projectDir:t}:t;return zg.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Do,async()=>({prompts:[]}));Te.server.setRequestHandler(No,async()=>({resources:[]}));Te.server.setRequestHandler(Mo,async()=>({resourceTemplates:[]}));function Ag(t){if(Array.isArray(t))return t.map(Ag);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]=Ag(r)}return e}function GH(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Zr,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=Ag(i.inputSchema)}catch{}}return s})}catch{}}var sa=new Ii({runtimes:yo,projectRoot:()=>wt()}),Yu=ft(Lg(),`cm-fs-preload-${process.pid}.js`);Vu(Yu,`(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){}})();
`);process.on("exit",()=>{try{Es(Yu)}catch{}});var an=null;function br(){let t=zg.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??JH();if(e)return{sessionId:e}}var zu;function JH(t){let e=Date.now();if(!t?.bypassCache&&zu&&e-zu.checkedAt<2e3)return zu.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??Le(),o=Li({projectDir:n,sessionsDir:r});if(!ze(o))return;let s=Be(),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&&(zu={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function XH(t){try{let e=Le();if(!ze(e))return;let n=DT(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=ft(e,r);try{t.index({path:o,source:"session-events",attribution:br()}),Es(o)}catch{}}}catch{}}var cn=null;async function YH(){if(cn)return cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(ys(),pg)),e=Et();return await t(e.platform)}catch{return null}}function Ss(){if(cn)return cn.getSessionDir();try{let t=Et(),e=Wi(t.platform);if(e)return oh({configDir:ft(...e),configDirEnv:QH(e)})}catch{}return oh({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function QH(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function Le(){return ou(ji(Ss))}function wt(){let t=zg.getStore();if(t)return t.projectDir;let e,n,r;try{let o=Et().platform;n=o,o==="claude-code"&&(e=ft(ws(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??ft(ws(),".codex"))}catch{}return mT({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function eU(t){return NH(t)?t:pt(wt(),t)}function na(){return Li({projectDir:wt(),sessionsDir:Le()})}function ra(){let t=ou(sh(Ss));return Uv({projectDir:wt(),contentDir:t})}function En(){if(!an){let t=ra();an=new Qc(t),an.setDenyChecker(e=>{try{let n=wt(),r=Tu("Read",n);return Gi(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=_o(ra());Gm(e,14),an.cleanupStaleSources(14);let n=ft(ws(),".context-mode","content");ze(n)&&Gm(n,0)}catch{}Km()}return XH(an),an}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function tU(t){return t instanceof pr?{content:[{type:"text",text:Lv(t)}],isError:!0}:null}var qn=null,Hu=0,TT=0,nU=3,rU=3600*1e3;async function RT(){return new Promise(t=>{let e=jH("https://registry.npmjs.org/context-mode/latest",{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 oU(){let t=cn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function sU(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 iU(){return!qn||qn==="unknown"?!1:sU(qn,Bn)}function aU(){if(!iU())return!1;let t=Date.now();if(Hu>=nU){if(t-TT<rU)return!1;Hu=0}return Hu===0&&(TT=t),Hu++,!0}var PT=!1;function cU(){if(!PT){PT=!0;try{let t=Ct(),e=pt(t,"plugins","installed_plugins.json");if(!ze(e))return;let n=JSON.parse(oa(e,"utf-8")),r=pt(t,"plugins","cache"),o;try{o=HT(r)}catch{o=r}let s=UT();for(let[i,a]of Object.entries(n.plugins??{}))if(i==="context-mode@context-mode")for(let c of a){let u=c.installPath;if(!u||ze(u)||!pt(u).startsWith(o+AH))continue;try{zT(u).isSymbolicLink()&&Es(u)}catch{}let l=_o(u);ze(l)||OH(l,{recursive:!0}),ze(s)&&IH(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(kg(),cU(),aU()&&e.content.length>0){let r=oU();e.content[0].text=`\u26A0\uFE0F context-mode v${Bn} outdated \u2192 v${qn} available. Upgrade: ${r}
`+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,Ku(),setImmediate(()=>oT(na(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>eT({sessionDbPath:na(),toolName:t,bytesReturned:n})),e}function un(t,e="unknown"){ne.bytesIndexed+=t,Ku(),t>0&&setImmediate(()=>tT({sessionDbPath:na(),source:e,bytesAvoided:t}))}var uU=500,lU=2,dU=3e4,pU=256,Ng=0,Uu,fU=/^[A-Za-z0-9._-]+$/;function mU(t){return fU.test(t)?t:`pid-${process.ppid}`}function BT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=mU(t),n=ou(ih(Ss));return ft(n,`stats-${e}.json`)}function Ku(){let t=Date.now();if(!(t-Ng<uU)){Ng=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=Uu?.tokens??0;if(!Uu||t-Uu.computedAt>dU)try{a=(Yi({sessionsDir:Le()})?.totalEvents??0)*pU,Uu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:lU,version:Bn,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*ea()).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*ea()).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=BT(),l=`${u}.tmp`;Vu(l,JSON.stringify(c)),$H(l,u)}catch{}}}function Hg(t,e){try{let n=yg(process.env.CLAUDE_PROJECT_DIR),r=bg(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 qT(t,e,n){try{let r=Ww(t,e);if(r.length===0)return null;let o=yg(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=bg(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 hU(t,e){try{let n=wt(),r=_g("Read","allow",n);return Vw(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 Mg(t,e){try{let n=wt(),r=Tu("Read",n),o=Gi(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 gU=Bu.join(", "),yU=Kc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",_U="",bU="";function xU(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===_U){for(e.push(n),r++;r<t.length&&t[r]!==bU;)n++,r++;r<t.length&&r++}else n++,r++;return e}function VT(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of xU(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)+`
\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(`
`)}function kU(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}
(output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
`);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=VT(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(`
> **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 SU(t){return`'${t.replace(/'/g,"'\\''")}'`}function vU(t){return`'${t.replace(/'/g,"''")}'`}function EU(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${vU(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${SU(n)} `}var CT=500;function WT(t){let e=t.replace(/\s+/g," ").trim();return e.length<=CT?e:e.slice(0,CT)+"\u2026"}var wU=12e4;function Ug(t){if(t!==void 0)return t;if(Et().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:wU}var $T=2e3;function TU(t){return t.length<=$T?t:t.slice(0,$T)+`
\u2026 (truncated)`}function KT(t,e,n){let r=n?`path=${n}
`:"",o=`\`\`\`${t}
${TU(e)}
\`\`\``;return`${r}${o}
`}function OT(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=WT(e);return`# ${t}
$ ${a}
${o}
`}function IT(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
`)?"":`
`}${n}`:n:e}async function RU(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 b=Date.now()-m,k=r-b;if(k<=0){f.push(`# ${g.label}
(skipped \u2014 batch timeout exceeded)
`),p=!0;continue}y=k}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(f.push(OT(g.label,g.command,IT(_),a)),_.timedOut){p=!0;for(let b=h+1;b<t.length;b++)f.push(`# ${t[b].label}
(skipped \u2014 batch timeout exceeded)
`);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=OT(f.label,f.command,IT(m),a);return{output:m.timedOut?p.replace(/\n$/,"")+`
(timed out after ${r??"?"}ms)
`:p,timedOut:!!m.timedOut}}})),{settled:u}=await zm(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}
(executor error: ${p})
`}}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.${yU} Languages: ${gU}.
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.
Concrete shape \u2014 analyze 47 source files without reading any of them:
ctx_execute(language: "javascript", code: \`
const fs = require('fs');
const files = fs.readdirSync('src').filter(f => f.endsWith('.ts'));
files.forEach(f => {
const lines = fs.readFileSync('src/'+f,'utf8').split('\\\\n').length;
console.log(f + ': ' + lines + ' lines');
});
\`)
// 47 files analyzed, 15,314 LoC summarized \u2014 output ~3.6 KB instead of 47 Read() calls = ~700 KB.
WHEN:
- You intend to derive an answer FROM data (filter, count, aggregate, parse, compare, transform) \u2014 do the derivation in code and print only the answer
- Output shape or size cannot be predicted before execution (recursive finds, repo-wide greps, list endpoints, query results, log scans)
- You would otherwise read raw output and then mentally compute \u2014 that compute belongs here, in code, where its inputs stay out of your conversation
- You need to keep a long-running process alive (dev server, watcher, daemon) \u2014 pass \`background: true\` to detach on timeout instead of killing the process
- The output may legitimately be large but you only want recall-by-topic later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed into the knowledge base and only the section titles + previews come back, retrievable via ctx_search
WHEN NOT:
- Single observational command whose entire short output you intend to consume verbatim (whoami, pwd, git status on a clean tree) \u2014 Bash is simpler
- File mutations (Edit/Write) or navigation (cd/ls) \u2014 Bash is the right surface
- You already know the output is one short fixed line and you want to read it as-is
RETURNS:
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.
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'))")
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(Bg,$.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'.
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=Hg(e,"execute");if(i)return i}else{let i=qT(e,t,"execute");if(i)return i}try{let i=e;(t==="javascript"||t==="typescript")&&(i=`
// FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
let __cm_fs=0;
process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
(function(){
try{
var f=typeof require!=='undefined'?require('fs'):null;
if(!f)return;
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;};
var orf=f.readFile;
if(orf)f.readFile=function(){var a=Array.from(arguments),cb=a.pop();orf.apply(this,a.concat([function(e,d){if(!e&&d){if(Buffer.isBuffer(d))__cm_fs+=d.length;else if(typeof d==='string')__cm_fs+=Buffer.byteLength(d);}cb(e,d);}]));};
}catch{}
})();
let __cm_net=0;
// Report network bytes on process exit \u2014 works with both promise and callback patterns.
// process.on('exit') fires after all I/O completes, unlike .finally() which fires
// when __cm_main() resolves (immediately for callback-based http.get without await).
process.on('exit',()=>{if(__cm_net>0)try{process.stderr.write('__CM_NET__:'+__cm_net+'\\n')}catch{}});
;(function(__cm_req){
// Intercept globalThis.fetch
const __cm_f=globalThis.fetch;
globalThis.fetch=async(...a)=>{const r=await __cm_f(...a);
try{const cl=r.clone();const b=await cl.arrayBuffer();__cm_net+=b.byteLength}catch{}
return r};
// Shadow CJS require with http/https network tracking.
const __cm_hc=new Map();
const __cm_hm=new Set(['http','https','node:http','node:https']);
function __cm_wf(m,origFn){return function(...a){
const li=a.length-1;
if(li>=0&&typeof a[li]==='function'){const oc=a[li];a[li]=function(res){
res.on('data',function(c){__cm_net+=c.length});oc(res);};}
const req=origFn.apply(m,a);
const oOn=req.on.bind(req);
req.on=function(ev,cb,...r){
if(ev==='response'){return oOn(ev,function(res){
res.on('data',function(c){__cm_net+=c.length});cb(res);
},...r);}
return oOn(ev,cb,...r);
};
return req;
}}
var require=__cm_req?function(id){
const m=__cm_req(id);
if(!__cm_hm.has(id))return m;
const k=id.replace('node:','');
if(__cm_hc.has(k))return __cm_hc.get(k);
const w=Object.create(m);
if(typeof m.get==='function')w.get=__cm_wf(m,m.get);
if(typeof m.request==='function')w.request=__cm_wf(m,m.request);
__cm_hc.set(k,w);return w;
}:__cm_req;
if(__cm_req){if(__cm_req.resolve)require.resolve=__cm_req.resolve;
if(__cm_req.cache)require.cache=__cm_req.cache;}
async function __cm_main(){
${e}
}
__cm_main().catch(e=>{console.error(e);process.exitCode=1});${r?`
setInterval(()=>{},2147483647);`:""}
})(typeof require!=='undefined'?require:null);`);let a=Ug(n),c=await sa.execute({language:t,code:i,timeout:a,background:r,cwd:o}),u=KT(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}
_(process backgrounded after ${a}ms \u2014 still running)_`}]}):m?W("ctx_execute",{content:[{type:"text",text:`${u}${m}
_(timed out after ${a}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`${u}Execution timed out after ${a}ms
stderr:
${c.stderr}`}],isError:!0})}if(c.exitCode!==0){let{isError:m,output:p}=xg({language:t,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return s&&s.trim().length>0&&Buffer.byteLength(p)>Gu?(un(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${vs(p,s,m?`execute:${t}:error`:`execute:${t}`)}`}],isError:m})):Buffer.byteLength(p)>Ju?(un(Buffer.byteLength(p)),W("ctx_execute",{content:[{type:"text",text:`${u}${vs(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)>Gu)return un(Buffer.byteLength(f)),W("ctx_execute",{content:[{type:"text",text:`${u}${vs(f,s,`execute:${t}`)}`}]});if(Buffer.byteLength(f)>Ju){let m=GT(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 GT(t,e){let n=En();un(Buffer.byteLength(t));let r=n.index({content:t,source:e,attribution:br()});return{content:[{type:"text",text:`Indexed ${r.totalChunks} sections (${r.codeChunks} with code) from: ${r.label}
Use ctx_search(queries: ["..."]) to query this content. Use source: "${r.label}" to scope results.`}]}}var Gu=5e3,Ju=102400;function vs(t,e,n,r=5){let o=t.split(`
`).length,s=Buffer.byteLength(t),i=En(),a=i.indexPlainText(t,n,void 0,br()),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(`
`)}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(`
`)[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(`
`)}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.
Think-in-Code applied to file-level analysis: Reading the whole file means every byte enters your conversation memory and costs reasoning capacity for the rest of the session. Running code over it here lets you keep the raw bytes out and only the derived answer in. Same principle as ctx_execute, scoped to one named file via the FILE_CONTENT variable.
WHEN:
- You want to KNOW SOMETHING ABOUT a file (line count, matches of a pattern, parsed structure, statistical aggregate) without needing to SEE all of it
- The file is structured (CSV, JSON, log, code) and a code-level derivation is cheaper than reading verbatim
- The file is large enough that reading the full content would burn meaningful conversation memory you need for the actual work
- The derivation may itself produce a large output you want recall-by-topic on later \u2014 pass an \`intent\` string; outputs over ~5KB are auto-indexed and only matching sections come back, retrievable via ctx_search
WHEN NOT:
- You intend to EDIT the file \u2014 use Read so the subsequent Edit can match the exact text
- You only need one specific line and you know its offset \u2014 Read with offset/limit is the simplest path
- The file is small AND you will consume all of it for understanding/editing \u2014 Read directly
RETURNS:
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.
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'))")
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=hU(t,"ctx_execute_file");if(s)return s;let i=Mg(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=Hg(n,"execute_file");if(a)return a}else{let a=qT(n,e,"execute_file");if(a)return a}try{let a=Ug(r),c=await sa.executeFile({path:t,language:e,code:n,timeout:a}),u=KT(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}=xg({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(f)>Gu?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${vs(f,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>Ju?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${vs(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)>Gu)return un(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${vs(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Ju){let d=GT(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.
WHEN:
- Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
- API references (endpoint details, parameter specs, response schemas)
- MCP tools/list output (exact tool signatures and descriptions)
- Skill prompts and instructions that are too large to keep verbatim in conversation
- README files, migration guides, changelog entries
- Any content with code examples you may need to reference precisely later
WHEN NOT:
- Log files, test output, CSV, or build output \u2014 use ctx_execute_file, which processes in-sandbox without persisting bytes
- Single-use ephemeral content you will not query later \u2014 keep it inline if it fits, or ctx_execute_file it
RETURNS:
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.
EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
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=Mg(e,"ctx_index");if(l)return l}try{let l=e?eU(e):void 0;if(l&&ze(l)&&zT(l).isSymbolicLink()){let p;try{p=HT(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=Mg(p,"ctx_index");if(h)return h}}if(l&&ze(l)&&LT(l).isDirectory()){let m=En(),p=wt(),h=Tu("Read",p),g=process.platform==="win32",y=O=>{try{return Gi(O,h,g,p).denied}catch{return!1}},_=m.indexDirectory({path:l,source:n??l,attribution:br(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),b=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",k=_.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}${b}${k}${v}
Use ctx_search(queries: ["..."]) to query this content.`}]})}if(t)un(Buffer.byteLength(t));else if(l)try{let m=await import("fs");un(m.readFileSync(l).byteLength)}catch{}let f=En().index({content:t,path:l,source:n??l,attribution:br()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
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 Fg(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var PU=Fg("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),Dg=Fg("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),qu=Fg("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),CU=new $u({windowMs:PU,softCapAfter:Dg,blockAfter:qu});function $U(){try{return br()?.sessionId??"__default__"}catch{return"__default__"}}function Zg(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 Bg(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function OU(t){let e=Zg(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:lT(Tg)},async t=>{try{let e=En(),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.
ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
\u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
\u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
\u2022 ctx_index(content, source) \u2014 manually index text content
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=dT(c,Tg,()=>wt()),l=Date.now(),d=CU.record($U(),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=Le(),D=wt(),V=Li({projectDir:D,sessionsDir:j});ze(V)&&(y=new on({dbPath:V}))}catch{}let b;if(typeof u=="string"&&y)try{b=new Set(y.getSessionIdsForProject(u))}catch{}let k=cn?.getConfigDir()??Ct();try{for(let j of o){if(h>p){g.push(`## ${j}
(output cap reached)
`);continue}let D;if(n==="timeline"?D=uT({query:j,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:wt(),configDir:k,adapter:cn??void 0,projectScope:u}):D=e.searchWithFallback(j,m,i,a,"like",b),D.length===0){g.push(`## ${j}
No results found.`);continue}let V=D.map((w,R)=>{let H=w.origin||"current-session",se=w.timestamp?w.timestamp.slice(0,16).replace("T"," "):"",mt=`--- [${H}${se?" | "+se:""} | ${w.source}] ---`,wn=`### ${w.title}`,Qu=VT(w.content,j,1500,w.highlighted);return`${mt}
${wn}
${Qu}`}).join(`
`);g.push(`## ${j}
${V}`),h+=V.length}}finally{try{y?.close()}catch{}}let v=g.join(`
---
`);e.lastRefreshCount>0&&(v=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
`+v);let O=Math.max(0,qu-f),P=Math.max(0,Dg-f);if(f>=Dg?v+=`
\u26A0 search call #${f}/${qu} 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+=`
> Throttle: call #${f}/${qu} in this window. ${P} 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(),D=j.length>0?`
Indexed sources: ${j.map(V=>`"${V.label}" (${V.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${D}`}]})}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 Rg=null,Pg=null;function IU(){return Rg||(Rg=MT(import.meta.url).resolve("turndown")),Rg}function AU(){return Pg||(Pg=MT(import.meta.url).resolve("turndown-plugin-gfm")),Pg}function NU(t,e){let n=JSON.stringify(IU()),r=JSON.stringify(AU()),o=JSON.stringify(e),s=Xu.toString(),i=Xu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
var classifyIp = ${i};`,c=jg.toString(),u=jg.name||"classifyExtraction",l=u==="classifyExtraction"?`var classifyExtraction = ${c};`:`var ${u} = ${c};
var classifyExtraction = ${u};`,d=process.env.CTX_FETCH_STRICT==="1";return`
const TurndownService = require(${n});
const { gfm } = require(${r});
const fs = require('fs');
const dns = require('no' + 'de:dns');
const dnsPromises = require('no' + 'de:dns/promises');
const url = ${JSON.stringify(t)};
const outputPath = ${o};
// Strip proxy env vars from this subprocess only. A configured outbound
// proxy (HTTP_PROXY / HTTPS_PROXY / ALL_PROXY) would route fetch through
// an arbitrary target \u2014 DNS resolution happens at the proxy and the
// in-subprocess DNS rebinding guard never sees the rebound IP. The
// sandbox fetch path has no legitimate need for an upstream proxy.
delete process.env.HTTP_PROXY;
delete process.env.HTTPS_PROXY;
delete process.env.ALL_PROXY;
delete process.env.http_proxy;
delete process.env.https_proxy;
delete process.env.all_proxy;
delete process.env.npm_config_proxy;
delete process.env.npm_config_https_proxy;
${a}
${l}
const STRICT = ${JSON.stringify(d)};
// SSRF rebinding defense: every dns.lookup call inside this subprocess
// (including the one undici performs to connect the fetch socket) is
// re-validated against the same policy ssrfGuard runs in the parent.
// Even if a hostname rebinds between the parent's pre-flight check and
// the subprocess's actual connect, the connect-time lookup re-classifies
// every returned record and aborts before TCP if any verdict is "block".
const _origLookup = dns.lookup;
dns.lookup = function patchedLookup(hostname, options, callback) {
if (typeof options === 'function') { callback = options; options = {}; }
if (typeof options === 'number') { options = { family: options }; }
const wantAll = options && options.all;
const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
_origLookup(hostname, opts, function(err, records) {
if (err) return callback(err);
if (!Array.isArray(records)) {
records = [{ address: records, family: (options && options.family) || 4 }];
}
for (var i = 0; i < records.length; i++) {
var verdict = classifyIp(records[i].address);
if (verdict === 'block' || (STRICT && verdict === 'private')) {
return callback(new Error(
'SSRF blocked at connect-time: ' + hostname +
' resolves to ' + records[i].address +
' (' + verdict + ')'
));
}
}
if (wantAll) callback(null, records);
else callback(null, records[0].address, records[0].family);
});
};
// dns/promises is a separate function reference. Patching dns.lookup does
// NOT affect dnsPromises.lookup. Today undici's connect path uses callback
// dns.lookup so default fetch is covered, but the invariant is fragile \u2014
// any future undici switch (or user code calling dnsPromises.lookup
// directly) would bypass the guard. Patch both to keep the contract.
const _origPromisesLookup = dnsPromises.lookup;
dnsPromises.lookup = async function patchedPromisesLookup(hostname, options) {
const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
const records = await _origPromisesLookup(hostname, opts);
const list = Array.isArray(records) ? records : [records];
for (var i = 0; i < list.length; i++) {
var verdict = classifyIp(list[i].address);
if (verdict === 'block' || (STRICT && verdict === 'private')) {
throw new Error(
'SSRF blocked at connect-time: ' + hostname +
' resolves to ' + list[i].address + ' (' + verdict + ')'
);
}
}
return options && options.all
? list
: { address: list[0].address, family: list[0].family };
};
// dns.resolve4 / dns.resolve6 use a different code path (no getaddrinfo,
// no /etc/hosts) than dns.lookup \u2014 they must be patched separately or the
// guard is trivially bypassed by any caller using dns.resolve* directly.
['resolve4', 'resolve6'].forEach(function patchResolve(name) {
const _origResolve = dns[name];
dns[name] = function patchedResolve(hostname, options, cb) {
if (typeof options === 'function') { cb = options; options = undefined; }
_origResolve.call(dns, hostname, options || {}, function(err, addrs) {
if (err) return cb(err);
var withTtl = options && options.ttl;
for (var i = 0; i < addrs.length; i++) {
var ip = withTtl ? addrs[i].address : addrs[i];
var v = classifyIp(ip);
if (v === 'block' || (STRICT && v === 'private')) {
return cb(new Error(
'SSRF blocked at connect-time: ' + hostname +
' resolves to ' + ip + ' (' + v + ')'
));
}
}
cb(null, addrs);
});
};
});
// Generic dns.resolve is a polymorphic dispatcher (rrtype-driven). Internally
// Node delegates to dns.resolve4/dns.resolve6 for A/AAAA, but the patches
// above hook the *exported* references \u2014 Node's internal dispatcher holds
// captured originals and bypasses our patch. Patch the wrapper explicitly:
// classify A/AAAA records the same way; pass through CNAME/MX/TXT/SRV/etc.
const _origResolveGeneric = dns.resolve;
dns.resolve = function patchedResolveGeneric(hostname, rrtype, cb) {
if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
_origResolveGeneric.call(dns, hostname, rrtype, function(err, records) {
if (err) return cb(err);
if ((rrtype === 'A' || rrtype === 'AAAA') && Array.isArray(records)) {
for (var i = 0; i < records.length; i++) {
var ip = records[i];
var v = classifyIp(ip);
if (v === 'block' || (STRICT && v === 'private')) {
return cb(new Error(
'SSRF blocked at connect-time: ' + hostname +
' resolves to ' + ip + ' (' + v + ')'
));
}
}
}
cb(null, records);
});
};
function emit(ct, content, sourceBytes, route, rung, tried) {
// Write content to file to bypass executor stdout truncation (100KB limit).
// Only the content-type marker goes to stdout.
fs.writeFileSync(outputPath, content);
console.log('__CM_CT__:' + ct);
// Line 2: bytes received off the wire, pre-conversion. Lets the parent
// compute extraction yield. Emitted unconditionally so "absent" means
// "old bundle", not "zero".
console.log(String(typeof sourceBytes === 'number' ? sourceBytes : 0));
// Line 3: which route produced the document. 'markdown' means the SITE
// served a machine-readable version of the page and no extraction is
// needed; 'html' means we converted it and the parent must classify it.
// A missing line 3 means "old bundle" and the parent assumes 'html'.
console.log(String(route || 'html'));
// Line 4: WHICH RUNG OF THE LADDER ANSWERED. The whole point of a ladder is
// that a reader can tell which step paid, so this is reported on every
// fetch, success or refusal \u2014 never inferred from byte counts.
console.log(String(rung || 'unknown'));
// Line 5: the rung-2 URLs actually requested, so a refusal can name them
// instead of telling the caller to go look for files we already looked for.
// Empty array when rung 2 never ran (the cheap rungs answered).
console.log(JSON.stringify(tried || []));
}
// Route 1 of the order of operations: ask for the machine-readable version of
// the page on the SAME request we were already making. Costs zero extra round
// trips. Measured 2026-08-12 \u2014 docs.stripe.com returns 1,846,885 B of HTML to
// a plain request and 11,744 B of pure article to this one; GitBook, Mintlify,
// Resend, Polygon, nextjs.org and developers.cloudflare.com behave the same.
// Sites that do not publish markdown (developer.mozilla.org) simply return
// HTML as before \u2014 the q-values keep the request a superset of the old one,
// so there is no site this can newly break.
const ACCEPT_HEADERS = {
'accept': 'text/markdown, text/x-markdown;q=0.9, text/html;q=0.8, application/xhtml+xml;q=0.8, */*;q=0.5',
};
// Manual redirect handling: a 3xx Location header can rebind the subprocess
// fetch to an alternate host the parent's pre-flight ssrfGuard never saw.
// Even with the connect-time DNS patch, a redirect target that is a literal
// IP (e.g. http://169.254.169.254/) skips getaddrinfo entirely. Walk the
// chain manually so every hop runs through classifyIp before the next fetch.
const MAX_REDIRECTS = 5;
async function fetchWithManualRedirect(initialUrl) {
let currentUrl = initialUrl;
for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
const resp = await fetch(currentUrl, { redirect: 'manual', headers: ACCEPT_HEADERS });
if (resp.status < 300 || resp.status >= 400) return resp;
const location = resp.headers.get('location') || resp.headers.get('Location');
if (!location) return resp;
if (redirectCount === MAX_REDIRECTS) {
throw new Error(
'redirect chain exceeded ' + MAX_REDIRECTS + ' hops, so the walk stopped before the ' +
'SSRF check could be re-run on another hop. A benign locale or consent redirect loop ' +
'produces this too (measured on Google devsite hosts, 2026-08-12); it is not by itself ' +
'evidence of an attack. Fetch the page from a host that does not bounce, or fetch its ' +
'raw source file directly.'
);
}
let nextParsed;
try { nextParsed = new URL(location, currentUrl); } catch (e) {
throw new Error('SSRF blocked: invalid redirect Location: ' + location);
}
if (nextParsed.protocol !== 'http:' && nextParsed.protocol !== 'https:') {
throw new Error('SSRF blocked: redirect to non-http(s) scheme ' + nextParsed.protocol);
}
// If the redirect target is a literal IP, classify it directly \u2014 no DNS
// lookup will fire and the connect-time guard would never see it.
const hostname = nextParsed.hostname.replace(/^[|]$/g, '');
const isIpLiteral = /^[0-9.]+$/.test(hostname) || hostname.includes(':');
if (isIpLiteral) {
const verdict = classifyIp(hostname);
if (verdict === 'block' || (STRICT && verdict === 'private')) {
throw new Error('SSRF blocked: redirect to ' + hostname + ' (' + verdict + ')');
}
} else {
// Hostname target: resolve and classify every record. The patched
// dns.lookup also fires on the next fetch's connect, but checking
// here gives a clearer error and short-circuits before TCP setup.
const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true });
for (const rec of records) {
const verdict = classifyIp(rec.address);
if (verdict === 'block' || (STRICT && verdict === 'private')) {
throw new Error(
'SSRF blocked: redirect target ' + hostname +
' resolves to ' + rec.address + ' (' + verdict + ')'
);
}
}
}
currentUrl = nextParsed.toString();
}
throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
}
// Subprocess response-body size cap. A malicious or unexpectedly large
// endpoint reachable through ctx_fetch_and_index would otherwise stream
// gigabytes into resp.text(), then into outputPath, then into the parent
// MCP server's heap via readFileSync. 50 MB is far above typical web
// page / API response sizes (~1-5 MB) but bounded enough to keep parent
// heap survivable. Cap both early via Content-Length and after the read.
const MAX_FETCH_BYTES = 50 * 1024 * 1024;
async function safeText(resp) {
const cl = parseInt(resp.headers.get('content-length') || '0', 10);
if (cl > MAX_FETCH_BYTES) {
throw new Error('Response too large: Content-Length ' + cl + ' exceeds ' + MAX_FETCH_BYTES);
}
const text = await resp.text();
if (text.length > MAX_FETCH_BYTES) {
throw new Error('Response too large: ' + text.length + ' bytes exceeds ' + MAX_FETCH_BYTES);
}
return text;
}
// \u2500\u2500 Rung 2 of the ladder: the site's own machine-readable files \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
//
// Reached ONLY when the cheaper rungs did not produce an article, so the happy
// path still costs exactly the one request it always did. Two sub-rungs, in
// cost order:
//
// 2a the '.md' sibling of the page path
// 2b the origin's llms.txt, followed only when it names a DIFFERENT url for
// this page than 2a already tried
//
// Measured 2026-08-12 over 36 documentation pages (scripts/measure-fetch-ladder.cjs):
// developer.apple.com/documentation/swiftui/view converts to 36 B of text from
// a 17,486 B shell \u2014 the hardest measured SPA \u2014 and its '.md' sibling returns
// 5,593 B of the real article. reactnative.dev/docs/view ignores the Accept
// header entirely and serves 30,318 B of markdown at '/docs/view.md'.
/** '.md' sibling candidates for a page path, most conventional first. */
function mdSiblingUrls(pageUrl) {
const p = new URL(pageUrl);
const pathname = p.pathname;
const dotHtml = '.html';
const out = [];
if (pathname.length > dotHtml.length && pathname.lastIndexOf(dotHtml) === pathname.length - dotHtml.length) {
out.push(pathname.substring(0, pathname.length - dotHtml.length) + '.md');
} else if (pathname.charAt(pathname.length - 1) === '/') {
out.push(pathname.substring(0, pathname.length - 1) + '.md');
out.push(pathname + 'index.md');
} else {
out.push(pathname + '.md');
out.push(pathname + '/index.md');
}
const urls = [];
for (let i = 0; i < out.length; i++) {
const full = p.origin + out[i];
if (urls.indexOf(full) < 0) urls.push(full);
}
return urls;
}
// A machine-readable sibling is accepted only when the server did not hand
// back an HTML page. The common failure is a soft 404: status 200 carrying the
// SPA shell. That is caught structurally, by looking for a document element,
// NOT by guessing at the body's shape \u2014 developer.apple.com serves its .md
// with an EMPTY Content-Type and an HTML comment as its first bytes, so a
// "starts with #" test would reject a real article (measured 2026-08-12).
function isMachineReadable(resp, body) {
if (resp.status !== 200) return false;
const ct = (resp.headers.get('content-type') || '').toLowerCase();
if (ct.indexOf('html') >= 0) return false;
const lower = body.toLowerCase();
if (lower.indexOf('<!doctype html') >= 0) return false;
if (lower.indexOf('<html') >= 0) return false;
return body.trim().length > 0;
}
// llms.txt is an INDEX, not the page. Following it blindly would re-fetch the
// url we just failed on, so it is only useful when it names this page at a
// location 2a did not already try \u2014 a site that publishes its markdown on
// another host is the case this covers.
function llmsTargetFor(body, pathname, alreadyTried, base) {
const lines = body.split('\\n');
for (let i = 0; i < lines.length; i++) {
const open = lines[i].indexOf('](');
if (open < 0) continue;
const close = lines[i].indexOf(')', open);
if (close < 0) continue;
const target = lines[i].substring(open + 2, close).trim();
if (target.length === 0) continue;
let abs;
try { abs = new URL(target, base).toString(); } catch (e) { continue; }
let entryPath;
try { entryPath = new URL(abs).pathname; } catch (e) { continue; }
const dotMd = '.md';
const bare = (entryPath.length > dotMd.length &&
entryPath.lastIndexOf(dotMd) === entryPath.length - dotMd.length)
? entryPath.substring(0, entryPath.length - dotMd.length)
: entryPath;
// The entry must name THIS page. A path suffix match is segment-safe
// because pathname always begins with '/', so the match can only start
// at a segment boundary.
const names = bare === pathname ||
bare + '/' === pathname ||
bare === pathname + '/' ||
(bare.length > pathname.length && bare.lastIndexOf(pathname) === bare.length - pathname.length);
if (!names) continue;
if (abs === base) continue;
if (alreadyTried.indexOf(abs) >= 0) continue;
return abs;
}
return '';
}
/** Climb rung 2. Returns the recovered document, or the urls it tried. */
async function climbRung2(pageUrl) {
const tried = [];
const siblings = mdSiblingUrls(pageUrl);
for (let i = 0; i < siblings.length; i++) {
tried.push(siblings[i]);
try {
const r = await fetchWithManualRedirect(siblings[i]);
const b = await safeText(r);
if (isMachineReadable(r, b)) {
return { body: b, url: siblings[i], rung: '2a-md-sibling', tried: tried };
}
} catch (e) { /* a missing sibling is the expected case, not an error */ }
}
const origin = new URL(pageUrl).origin;
const llmsUrl = origin + '/llms.txt';
tried.push(llmsUrl);
let llmsBody = '';
try {
const r = await fetchWithManualRedirect(llmsUrl);
const b = await safeText(r);
if (isMachineReadable(r, b)) llmsBody = b;
} catch (e) { /* no llms.txt on this host */ }
if (llmsBody.length > 0) {
let pathname = '/';
try { pathname = new URL(pageUrl).pathname; } catch (e) { pathname = '/'; }
const target = llmsTargetFor(llmsBody, pathname, tried, pageUrl);
if (target.length > 0) {
tried.push(target);
try {
const r2 = await fetchWithManualRedirect(target);
const b2 = await safeText(r2);
if (isMachineReadable(r2, b2)) {
return { body: b2, url: target, rung: '2b-llms-txt', tried: tried };
}
} catch (e) { /* the index named a url that does not serve */ }
}
}
return { body: '', url: '', rung: '', tried: tried };
}
async function main() {
const resp = await fetchWithManualRedirect(url);
if (!resp.ok) { console.error("HTTP " + resp.status); process.exit(1); }
const contentType = resp.headers.get('content-type') || '';
// --- Site-authored markdown (route 1 \u2014 the cheapest correct answer) ---
// The server honoured our Accept header and handed back the page as the
// author wrote it: article only, no nav, no CSS, nothing to extract. Emit
// it under the 'html' indexing strategy (heading-aware markdown chunking)
// and tell the parent the route so it skips classification entirely.
if (contentType.includes('text/markdown') || contentType.includes('text/x-markdown')) {
const md = await safeText(resp);
emit('html', md, Buffer.byteLength(md, 'utf-8'), 'markdown', '1-accept-markdown', []);
return;
}
// --- JSON responses ---
if (contentType.includes('application/json') || contentType.includes('+json')) {
const text = await safeText(resp);
const received = Buffer.byteLength(text, 'utf-8');
try {
const pretty = JSON.stringify(JSON.parse(text), null, 2);
emit('json', pretty, received, 'json', '1-json-passthrough', []);
} catch {
emit('text', text, received, 'text', '1-text-passthrough', []);
}
return;
}
// --- HTML responses (default for text/html, application/xhtml+xml) ---
if (contentType.includes('text/html') || contentType.includes('application/xhtml')) {
const html = await safeText(resp);
const sourceBytes = Buffer.byteLength(html, 'utf-8');
const td = new TurndownService({ headingStyle: 'atx', codeBlockStyle: 'fenced' });
td.use(gfm);
td.remove(['script', 'style', 'nav', 'header', 'footer', 'noscript']);
const converted = td.turndown(html);
// The site served HTML rather than markdown. If what came back converts to
// an article, that IS the answer and rung 2 is never requested. If it
// converts to a shell \u2014 the SPA case \u2014 climb to the site's own
// machine-readable files BEFORE giving up, using the same arithmetic the
// parent would have used to refuse.
if (classifyExtraction(converted.trim().length, sourceBytes).kind === 'shell') {
const climbed = await climbRung2(url);
if (climbed.body.length > 0) {
emit('html', climbed.body, Buffer.byteLength(climbed.body, 'utf-8'),
'markdown', climbed.rung, climbed.tried);
return;
}
// Ladder exhausted. Emit the shell anyway \u2014 the parent stores every
// byte it was served and refuses to INDEX it, and it now knows which
// urls were tried so the refusal can name them.
emit('html', converted, sourceBytes, 'html', 'ladder-exhausted', climbed.tried);
return;
}
emit('html', converted, sourceBytes, 'html', '1-html-converted', []);
return;
}
// --- Everything else: plain text, CSV, XML, etc. ---
const text = await safeText(resp);
// Some sites answer the markdown Accept with the markdown document but
// label it text/plain (measured 2026-08-12: cursor.com/docs/context/rules
// returns 16,636 B of "# Rules ..." as text/plain). Recognising an ATX H1
// on the first non-blank line is a structural check, not a threshold, and
// it only ever changes which chunker runs \u2014 the whole document is indexed
// either way, so a false positive cannot lose a byte.
if (contentType.includes('text/plain')) {
let firstLine = '';
for (const line of text.split('\\n')) {
if (line.trim().length > 0) { firstLine = line.trim(); break; }
}
if (firstLine.lastIndexOf('# ', 0) === 0) {
emit('html', text, Buffer.byteLength(text, 'utf-8'), 'markdown', '1-accept-markdown', []);
return;
}
}
emit('text', text, Buffer.byteLength(text, 'utf-8'), 'text', '1-text-passthrough', []);
}
main();
`}var MU=1440*60*1e3,AT=3072;function DU(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 jg(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 jU(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=Xu(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 Xu(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?Xu(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 LU(t,e,n,r){let o=await jU(t);if(o)return o;if(!n&&r!==0){let i=En(),a=Jm(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??MU;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:DU(d)}}}}let s=ft(Lg(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=NU(t,s),a=await sa.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(`
`),u=(c[0]||"").trim(),l=Number.parseInt((c[1]||"").trim(),10),d=zU((c[2]||"").trim()),f=(c[3]||"").trim()||"unreported",m=HU(c[4]||""),p;try{let y=LT(s).size;if(y>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${y} bytes exceeds cap 52428800`,reason:"read"};p=oa(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=jg(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{jT(s)}catch{}}}function zU(t){return t==="markdown"?"markdown":t==="json"?"json":t==="text"?"text":"html"}function HU(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 Fu(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 Cg=null;function UU(){return Cg||(Cg=new eu(ft(_o(ra()),"fetch-pages.db"))),Cg}function FU(t){let e=En(),n=Jm(t.source,t.url),r=br(),o=t.route??"html",s=t.rung??"unreported",i=t.markdown,a,c=[];if(!Ev(o))try{let d=wv({url:t.url,sourceLabel:n,document:t.markdown,route:o,store:UU()});if(d.kind==="refuse")return{label:n,totalChunks:0,totalBytes:d.storedBytes,preview:"",refusal:`${Fu(s)}; ${d.reason}`};i=d.indexText,c=d.relabelled,o==="markdown"?a=`${Fu(s)}; site-authored markdown (${d.storedBytes} B) \u2014 no extraction needed`:d.provisional?a=`${Fu(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=`${Fu(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`),un(Buffer.byteLength(t.markdown));let l=i.length>AT?Yw(i,AT)+`
\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.
Caching: every fetch is cached on disk and reused for repeat calls within the TTL window. The default TTL is 24 hours; override per-call with the \`ttl\` parameter (milliseconds, \`ttl: 0\` bypasses cache like \`force: true\`). Stored content older than 14 days is cleaned up on startup.
WHEN:
- You need web content (docs, changelogs, API references, spec pages) and the raw page bytes should NOT enter your conversation
- Multi-URL research (library evaluation, migration scans, doc comparisons): pass the \`requests\` array and a \`concurrency\` value 2-8 for parallel I/O
- You want repeat lookups against the same URL to be cheap (TTL cache hits return only a hint, no re-fetch)
- You want a long-lived cache window (override \`ttl\` upward for stable specs) or a guaranteed-fresh fetch (\`ttl: 0\` or \`force: true\`)
SPA pages: fetch them the same way. There is no headless browser, and measurement says none is needed \u2014 over 36 documentation pages, 4 had the article absent from the HTTP response and 4 of 4 were recovered without executing JavaScript. The fetch climbs a ladder in cost order and tells you which rung answered: (1) \`Accept: text/markdown\` on the request it was already making, (2a) the page's \`.md\` sibling, (2b) the host's llms.txt, (4) block classification against other pages of the same host, (5) a refusal naming the urls it already tried. Rungs past 1 cost a request only when the cheaper rung returned a JavaScript shell.
WHEN NOT:
- You already have the content locally \u2014 store it via the inline index tool
- The page is an application rather than a document (a whiteboard, a diagram editor, a dashboard) \u2014 there is no article to fetch, and the fetch will say so rather than index the shell
RETURNS:
Per-source preview windows extracted around indexable headings plus indexing metadata (chunk counts, source labels, cache state). Raw content is NOT echoed back \u2014 retrieve any section on-demand via ctx_search(source: "<label>"). Concurrency parallelizes the fetch phase up to your chosen value (capped by the host's logical CPU count); the FTS5 write phase always runs serially because SQLite is a single-writer store. Net latency = max(fetch latency across the pool) + sum(per-source index write time). Cache hits skip both phases and return a small freshness hint instead of re-fetching. Use 4-8 for stable I/O-bound batches; lower the value when the target host enforces a per-IP rate limit you cannot raise.
EXAMPLE: ctx_fetch_and_index(
requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
concurrency: 5
)`,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(Zg,$.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(Bg,$.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:()=>LU(w.url,w.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await zm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let w=0;w<l.length;w++){let R=l[w];if(R.status==="rejected"){let se=R.reason instanceof Error?R.reason.message:String(R.reason);m.push({kind:"job_error",url:i[w].url,error:se});continue}let H=R.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let se=H.estimatedBytes,mt=H.label;setImmediate(()=>nT({sessionDbPath:na(),source:mt,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=FU(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}).
To refresh: call ctx_fetch_and_index again with \`force: true\`.
You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
Use: ctx_search(queries: [...], source: "${w.label}")`}]});if(w.kind==="fetched"){let R=(w.indexed.totalBytes/1024).toFixed(1),H=[`Fetched and indexed **${w.indexed.totalChunks} sections** (${R}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(`
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:H}]})}if(w.kind==="fetch_error"){let R=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:R}],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,b=0,k=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"){b++,g+=w.indexed.totalChunks,y+=w.indexed.totalBytes;let R=(w.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${w.indexed.label} \u2014 ${w.indexed.totalChunks} sections (${R}KB)`);let H=w.indexed.preview.length>p?w.indexed.preview.slice(0,p).trimEnd()+"\u2026":w.indexed.preview;v.push(`### ${w.indexed.label}
${H}`)}else k++,h.push(`- [err] ${w.url}: ${w.error}`);let O=(y/1024).toFixed(1),P=f?` cap=${d}/${DH().length}cpu`:"",j=(w,R,H)=>`${w} ${w===1?R:H}`,V=[`fetched ${i.length} c=${d}${P}. ok=${b} cache=${_} err=${k}. ${j(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
`);return W("ctx_fetch_and_index",{content:[{type:"text",text:V}],isError:k===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.
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).
WHEN:
- You have 3+ related commands you would otherwise run sequentially (multi-issue lookups, git log + git diff + git blame, multi-file reads, multi-region cloud queries)
- You want to gather AND query in one round trip \u2014 pass \`queries\` so the matching sections come back inline
- You want to parallelize I/O-bound work \u2014 pass \`concurrency\` 2-8 (network calls, gh CLI, cloud APIs, multi-repo git reads)
- The combined output is large enough that piping it through ctx_search later would itself be expensive \u2014 let auto-index + inline queries do both in one shot
WHEN NOT:
- Single command with no follow-up query \u2014 run it in the sandbox tool directly
- CPU-bound or stateful commands \u2014 keep concurrency at 1 (npm test, build, lint, port-binding servers, lock-file holders, anything that races on the same resource)
RETURNS:
Auto-indexed section list per command label, plus top matches per query (when \`queries\` is passed). Raw output is NOT echoed in full \u2014 only the matched windows. Concurrency>1 switches each command to its own per-command timeout (no shared budget); concurrency=1 preserves the legacy shared-budget cascading-skip-on-timeout path. Use 4-8 for I/O-bound batches; keep at 1 for CPU work or shared-state commands; lower the value when target hosts enforce per-IP rate limits.
EXAMPLE: ctx_batch_execute(
commands: [
{label: "issue 1", command: "gh issue view 1"},
{label: "issue 2", command: "gh issue view 2"},
{label: "summarize", command: "echo done"}
],
queries: ["root cause", "proposed fix"],
concurrency: 2
)`,inputSchema:$.object({commands:$.preprocess(OU,$.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(Zg,$.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=Hg(i.command,"batch_execute");if(a)return a}try{let i=EU(yo.shell,Yu),a=Ug(n),{outputs:c,timedOut:u}=await RU(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:P=>{ne.bytesSandboxed+=P}},sa),l=c.join(`
`),d=Buffer.byteLength(l),f=l.split(`
`).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});un(d);let m=En(),p=`batch:${t.map(P=>P.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:br()}),g=["## Commands",""];for(let P of t)g.push(`- ${P.label}: \`${WT(P.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],b=[];for(let P of y){let j=Buffer.byteLength(P.content);_.push(`- ${P.title} (${(j/1024).toFixed(1)}KB)`),b.push(P.title)}let k=kU(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,"",..._,"",...k,v.length>0?`
Searchable terms for follow-up: ${v.join(", ")}`:""].join(`
`);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 $g(t,e){if(!ze(e))return;let n=0;try{for(let r of DT(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(oa(ft(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 NT(){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=wt(),n=Qe(e),r=Li({projectDir:e,sessionsDir:Le()});if(ze(r)){let o=Be(),s=new o(r,{readonly:!0});try{let i=new ks(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=Yi({sessionsDir:Le()}),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=vT({sessionId:p,sessionsDir:Le(),worktreeHash:n});let h=ra(),g;try{let k=Be(),v=(await import("node:fs")).readdirSync(Le()).filter(P=>P.endsWith(".db")&&(!n||P.startsWith(n))),O;for(let P of v)try{let j=new k((await import("node:path")).join(Le(),P),{readonly:!0});try{let D=j.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(D?.project_dir){O=D.project_dir;break}}finally{j.close()}}catch{}g=O?Qi({projectDir:O,sessionsDir:Le(),worktreeHash:n,contentDbPath:h}):Qi({sessionId:p,sessionsDir:Le(),worktreeHash:n,contentDbPath:h})}catch{g=Qi({sessionId:p,sessionsDir:Le(),worktreeHash:n,contentDbPath:h})}let y=Qi({sessionsDir:Le()}),_=ET(h),b={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:b}}}catch{}cn?.name==="Pi"&&$g(u,Le());let m;try{m=En().getIndexState()}catch{}t=Lu(a,Bn,qn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new ks(NT()).queryAll(ne),i=Yi({sessionsDir:Le()});cn?.name==="Pi"&&$g(i,Le());let a;try{a=ju()}catch{}let c;try{c=En().getIndexState()}catch{}t=Lu(s,Bn,qn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new ks(NT()).queryAll(ne),r;try{r=Yi({sessionsDir:Le()})}catch{}cn?.name==="Pi"&&r&&$g(r,Le());let o;try{o=ju()}catch{}t=Lu(n,Bn,qn,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=Et(Te.server.getClientVersion()??void 0).platform}catch{e=Et().platform}let n=FT(e),r=11,o=(Bu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Bu.length}/${r} (${o}%) \u2014 ${Bu.join(", ")}`),Kc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=ji(Ss),i=sh(Ss),a=ih(Ss);t.push(`[OK] Storage sessions: ${s.path} (${ru(s)})`),t.push(`[OK] Storage content: ${i.path} (${ru(i)})`),t.push(`[OK] Storage stats: ${a.path} (${ru(a)})`);{let u=new Ii({runtimes:yo});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=Be();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 YH();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=pT(c,n);u.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let l of u){let d=pt(n,l);ze(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${Bn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
`)}]})});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=Et(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=qc(u.platform)&&yo.javascript?{platform:u.platform,jsRuntime:yo.javascript}:void 0}catch{try{n=Et().platform}catch{}}let r=FT(n),o=pt(r,"cli.bundle.mjs"),s=pt(r,"build","cli.js");try{let c=Le(),u=ft(_o(c),"insight-cache");ze(u)&&(qU(4747),jT(u,{recursive:!0,force:!0}))}catch{}let i;if(ze(o))i=`${$i(o,e)} upgrade${t}`;else if(ze(s))i=`${$i(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/mksglu/context-mode.git",T],{stdio:"inherit"});','console.log("- [x] Cloned latest source");','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["install"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','execFileSync(process.platform==="win32"?"npm.cmd":"npm",["run","build"],{cwd:T,stdio:"inherit",shell:process.platform==="win32"});','console.log("- [x] Built from source");','const pkg=JSON.parse(readFileSync(join(T,"package.json"),"utf8"));','const items=[...(Array.isArray(pkg.files)?pkg.files:[]),"src","package.json"];',"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(`
`),l=pt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=$i(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(`
`);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.
WHEN:
- User explicitly asks to clear a specific session ('purge this session', 'wipe this conversation')
- User explicitly asks to reset the whole project ('reset everything', 'wipe the knowledge base')
WHEN NOT:
- User says 'reset', 'clear', or 'wipe' without naming a scope -> ask which scope before calling
- User wants to free memory or improve performance -> recommend ctx_stats first, do not purge
SCOPES (pass exactly one):
- Per-session: ctx_purge(confirm: true, sessionId: "<uuid>") deletes that session's events (auto-captured decisions, errors, plans, user prompts, rejected approaches, etc.) and per-session FTS5 chunks; sibling sessions and stats file are preserved.
- Per-project: ctx_purge(confirm: true, scope: "project") wipes FTS5 knowledge base, every session DB row, events markdown, and resets the stats file. Use ctx_stats first to preview category counts before purging.
CONTRACT:
- confirm:true is required; confirm:false returns 'purge cancelled'.
- sessionId and scope:'project' together return 'ambiguous - pick one'.
- scope:'session' without sessionId throws (sessionId required).
- Bare {confirm:true} is deprecated: maps to scope:'project' with a stderr warning; will hard-error in a future major.
RETURNS:
A summary of removed rows + the resolved scope.
EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(Bg,$.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=ra()}catch{}if(an){try{an.cleanup()}catch{}an=null}let s=o?_o(o):void 0,{deleted:i}=Qw({projectDir:wt(),sessionsDir:Le(),storePath:o,contentDir:s,legacyContentDir:ft(ws(),".context-mode","content"),contentHash:Ln(wt()),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=BT();ze(c)&&Es(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 ta=5e3;function ZU(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 BU(t,e=process.platform,n=Wu){let r=ZU(t,e),o=[];for(let{cmd:s,args:i}of r)try{let a=n(s,i,{stdio:"ignore",timeout:ta});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 qU(t,e=process.platform,n=Wu){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:ta});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:ta});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:ta});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:ta});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 Og="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=BU(Og),e=t.ok?`Opening Insight in your browser: ${Og}`:`Could not auto-open your browser (${t.reason}).
Open Insight manually: ${Og}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function VU(){let t=Km();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Lg():"/tmp",n=ft(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{sa.cleanupBackgrounded(),an&&an.close();try{Es(Yu)}catch{}try{Es(n)}catch{}r&&clearInterval(r)},s=async()=>{try{Ng=0,Ku()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),Xw({onShutdown:()=>s()});let i=new Zc;await Te.connect(i),Jw(i);try{Vu(n,String(process.pid))}catch{}r=setInterval(()=>{try{Vu(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(ys(),pg)),u=Te.server.getClientVersion(),l=a(u??void 0);cn=await c(l.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${l.platform}`)}catch{}try{let a=sT(na());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{}RT().then(a=>{a!=="unknown"&&(qn=a)}),setInterval(()=>{RT().then(a=>{a!=="unknown"&&(qn=a)})},3600*1e3).unref(),setInterval(()=>Ku(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Bn} running on stdio`),console.error(`Detected runtimes:
${JS(yo)}`),Kc()||(console.error(`
Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}GH();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&VU().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{wU as AGY_DEFAULT_EXEC_TIMEOUT_MS,HH as REGISTERED_CTX_TOOLS,d5 as __resetSuppressionDiagnosticForTests,ZU as browserOpenArgv,EU as buildBatchNodeOptionsPrefix,NU as buildFetchCode,jg as classifyExtraction,Xu as classifyIp,br as currentAttribution,Fu as describeRung,qH as emitSuppressionDiagnostic,VT as extractSnippet,kU as formatBatchQueryResults,wt as getProjectDir,GH as installStrictClientSchemaCompat,qU as killProcessOnPort,BU as openBrowserSync,HU as parseLadderTried,xU as positionsFromHighlight,VH as registerEmptyToolsListHandler,Ug as resolveExecTimeout,JH as resolveSessionIdFromSessionDB,RU as runBatchCommands,Ag as sanitizeSchemaForStrictClients,Te as server,UH as shouldSuppressMcpToolsForNativePluginHost,p5 as withProjectDirOverride};