context-mode 1.0.165 → 1.0.166

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.bundle.mjs CHANGED
@@ -3,10 +3,10 @@ var ZT=Object.create;var el=Object.defineProperty;var BT=Object.getOwnPropertyDe
3
3
  `:""},this._extScope=e,this._scope=new Qt.Scope({parent:e}),this._nodes=[new Vp]}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 Hp(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 oc(e,n,r))}add(e,n){return this._leafNode(new Up(e,te.operators.ADD,n))}code(e){return typeof e=="function"?e():e!==ce.nil&&this._leafNode(new qp(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,ce.addCodeArg)(n,o));return n.push("}"),new ce._Code(n)}if(e,n,r){if(this._blockNode(new Zr(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 Zr(e))}else(){return this._elseNode(new Do)}endIf(){return this._endBlockNode(Zr,Do)}_for(e,n){return this._blockNode(e),n&&this.code(n).endFor(),this}for(e,n){return this._for(new Wp(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 Kp(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 ce.Name?n:this.var("_arr",n);return this.forRange("_i",0,(0,ce._)`${i}.length`,a=>{this.var(s,(0,ce._)`${i}[${a}]`),r(s)})}return this._for(new sc("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,ce._)`Object.keys(${n})`,r);let s=this._scope.toName(e);return this._for(new sc("in",o,s,n),()=>r(s))}endFor(){return this._endBlockNode(Br)}label(e){return this._leafNode(new Fp(e))}break(e){return this._leafNode(new Zp(e))}return(e){let n=new ri;if(this._blockNode(n),this.code(e),n.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ri)}try(e,n,r){if(!n&&!r)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Gp;if(this._blockNode(o),this.code(e),n){let s=this.name("e");this._currNode=o.catch=new oi(s),n(s)}return r&&(this._currNode=o.finally=new si,this.code(r)),this._endBlockNode(oi,si)}throw(e){return this._leafNode(new Bp(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=ce.nil,r,o){return this._blockNode(new ni(e,n,r)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ni)}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 Zr))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=Jp;function qr(t,e){for(let n in e)t[n]=(t[n]||0)+(e[n]||0);return t}function ic(t,e){return e instanceof ce._CodeOrName?qr(t,e.names):t}function Mo(t,e,n){if(t instanceof ce.Name)return r(t);if(!o(t))return t;return new ce._Code(t._items.reduce((s,i)=>(i instanceof ce.Name&&(i=r(i)),i instanceof ce._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 ce._Code&&s._items.some(i=>i instanceof ce.Name&&e[i.str]===1&&n[i.str]!==void 0)}}function eO(t,e){for(let n in e)t[n]=(t[n]||0)-(e[n]||0)}function Hx(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ce._)`!${Xp(t)}`}te.not=Hx;var tO=Ux(te.operators.AND);function nO(...t){return t.reduce(tO)}te.and=nO;var rO=Ux(te.operators.OR);function oO(...t){return t.reduce(rO)}te.or=oO;function Ux(t){return(e,n)=>e===ce.nil?n:n===ce.nil?e:(0,ce._)`${Xp(e)} ${t} ${Xp(n)}`}function Xp(t){return t instanceof ce.Name?t:(0,ce._)`(${t})`}});var ue=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 _e=ee(),sO=ei();function iO(t){let e={};for(let n of t)e[n]=!0;return e}re.toHash=iO;function aO(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Bx(t,e),!qx(e,t.self.RULES.all))}re.alwaysValidSchema=aO;function Bx(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]||Kx(t,`unknown keyword: "${s}"`)}re.checkUnknownRules=Bx;function qx(t,e){if(typeof t=="boolean")return!t;for(let n in t)if(e[n])return!0;return!1}re.schemaHasRules=qx;function cO(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=cO;function uO({topSchemaRef:t,schemaPath:e},n,r,o){if(!o){if(typeof n=="number"||typeof n=="boolean")return n;if(typeof n=="string")return(0,_e._)`${n}`}return(0,_e._)`${t}${e}${(0,_e.getProperty)(r)}`}re.schemaRefOrVal=uO;function lO(t){return Vx(decodeURIComponent(t))}re.unescapeFragment=lO;function dO(t){return encodeURIComponent(Qp(t))}re.escapeFragment=dO;function Qp(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}re.escapeJsonPointer=Qp;function Vx(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}re.unescapeJsonPointer=Vx;function pO(t,e){if(Array.isArray(t))for(let n of t)e(n);else e(t)}re.eachItem=pO;function Fx({mergeNames:t,mergeToName:e,mergeValues:n,resultToName:r}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof _e.Name?(s instanceof _e.Name?t(o,s,i):e(o,s,i),i):s instanceof _e.Name?(e(o,i,s),s):n(s,i);return a===_e.Name&&!(c instanceof _e.Name)?r(o,c):c}}re.mergeEvaluated={props:Fx({mergeNames:(t,e,n)=>t.if((0,_e._)`${n} !== true && ${e} !== undefined`,()=>{t.if((0,_e._)`${e} === true`,()=>t.assign(n,!0),()=>t.assign(n,(0,_e._)`${n} || {}`).code((0,_e._)`Object.assign(${n}, ${e})`))}),mergeToName:(t,e,n)=>t.if((0,_e._)`${n} !== true`,()=>{e===!0?t.assign(n,!0):(t.assign(n,(0,_e._)`${n} || {}`),ef(t,n,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Wx}),items:Fx({mergeNames:(t,e,n)=>t.if((0,_e._)`${n} !== true && ${e} !== undefined`,()=>t.assign(n,(0,_e._)`${e} === true ? true : ${n} > ${e} ? ${n} : ${e}`)),mergeToName:(t,e,n)=>t.if((0,_e._)`${n} !== true`,()=>t.assign(n,e===!0?!0:(0,_e._)`${n} > ${e} ? ${n} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Wx(t,e){if(e===!0)return t.var("props",!0);let n=t.var("props",(0,_e._)`{}`);return e!==void 0&&ef(t,n,e),n}re.evaluatedPropsToName=Wx;function ef(t,e,n){Object.keys(n).forEach(r=>t.assign((0,_e._)`${e}${(0,_e.getProperty)(r)}`,!0))}re.setEvaluated=ef;var Zx={};function fO(t,e){return t.scopeValue("func",{ref:e,code:Zx[e.code]||(Zx[e.code]=new sO._Code(e.code))})}re.useFunc=fO;var Yp;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Yp||(re.Type=Yp={}));function mO(t,e,n){if(t instanceof _e.Name){let r=e===Yp.Num;return n?r?(0,_e._)`"[" + ${t} + "]"`:(0,_e._)`"['" + ${t} + "']"`:r?(0,_e._)`"/" + ${t}`:(0,_e._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return n?(0,_e.getProperty)(t).toString():"/"+Qp(t)}re.getErrorPath=mO;function Kx(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=Kx});var An=I(tf=>{"use strict";Object.defineProperty(tf,"__esModule",{value:!0});var rt=ee(),hO={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")};tf.default=hO});var ii=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 le=ee(),cc=ue(),ut=An();ot.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};ot.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function gO(t,e=ot.keywordError,n,r){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Xx(t,e,n);r??(i||a)?Gx(s,c):Jx(o,(0,le._)`[${c}]`)}ot.reportError=gO;function yO(t,e=ot.keywordError,n){let{it:r}=t,{gen:o,compositeRule:s,allErrors:i}=r,a=Xx(t,e,n);Gx(o,a),s||i||Jx(r,ut.default.vErrors)}ot.reportExtraError=yO;function _O(t,e){t.assign(ut.default.errors,e),t.if((0,le._)`${ut.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${ut.default.vErrors}.length`,e),()=>t.assign(ut.default.vErrors,null)))}ot.resetErrorsCount=_O;function xO({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,le._)`${ut.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(ut.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,n),t.assign((0,le._)`${i}.data`,r))})}ot.extendErrors=xO;function Gx(t,e){let n=t.const("err",e);t.if((0,le._)`${ut.default.vErrors} === null`,()=>t.assign(ut.default.vErrors,(0,le._)`[${n}]`),(0,le._)`${ut.default.vErrors}.push(${n})`),t.code((0,le._)`${ut.default.errors}++`)}function Jx(t,e){let{gen:n,validateName:r,schemaEnv:o}=t;o.$async?n.throw((0,le._)`new ${t.ValidationError}(${e})`):(n.assign((0,le._)`${r}.errors`,e),n.return(!1))}var Vr={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function Xx(t,e,n){let{createErrors:r}=t.it;return r===!1?(0,le._)`{}`:SO(t,e,n)}function SO(t,e,n={}){let{gen:r,it:o}=t,s=[bO(o,n),kO(t,n)];return vO(t,e,s),r.object(...s)}function bO({errorPath:t},{instancePath:e}){let n=e?(0,le.str)`${t}${(0,cc.getErrorPath)(e,cc.Type.Str)}`:t;return[ut.default.instancePath,(0,le.strConcat)(ut.default.instancePath,n)]}function kO({keyword:t,it:{errSchemaPath:e}},{schemaPath:n,parentSchema:r}){let o=r?e:(0,le.str)`${e}/${t}`;return n&&(o=(0,le.str)`${o}${(0,cc.getErrorPath)(n,cc.Type.Str)}`),[Vr.schemaPath,o]}function vO(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([Vr.keyword,o],[Vr.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&r.push([Vr.message,typeof n=="function"?n(t):n]),c.verbose&&r.push([Vr.schema,i],[Vr.parentSchema,(0,le._)`${l}${d}`],[ut.default.data,s]),u&&r.push([Vr.propertyName,u])}});var Qx=I(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.boolOrEmptySchema=jo.topBoolOrEmptySchema=void 0;var EO=ii(),wO=ee(),TO=An(),PO={message:"boolean schema is false"};function RO(t){let{gen:e,schema:n,validateName:r}=t;n===!1?Yx(t,!1):typeof n=="object"&&n.$async===!0?e.return(TO.default.data):(e.assign((0,wO._)`${r}.errors`,null),e.return(!0))}jo.topBoolOrEmptySchema=RO;function CO(t,e){let{gen:n,schema:r}=t;r===!1?(n.var(e,!1),Yx(t)):n.var(e,!0)}jo.boolOrEmptySchema=CO;function Yx(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,EO.reportError)(o,PO,void 0,e)}});var nf=I(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0});zo.getRules=zo.isJSONType=void 0;var $O=["string","number","integer","boolean","null","object","array"],OO=new Set($O);function IO(t){return typeof t=="string"&&OO.has(t)}zo.isJSONType=IO;function AO(){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:{}}}zo.getRules=AO});var rf=I(nr=>{"use strict";Object.defineProperty(nr,"__esModule",{value:!0});nr.shouldUseRule=nr.shouldUseGroup=nr.schemaHasRulesForType=void 0;function NO({schema:t,self:e},n){let r=e.RULES.types[n];return r&&r!==!0&&eS(t,r)}nr.schemaHasRulesForType=NO;function eS(t,e){return e.rules.some(n=>tS(t,n))}nr.shouldUseGroup=eS;function tS(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))}nr.shouldUseRule=tS});var ai=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 DO=nf(),MO=rf(),jO=ii(),Y=ee(),nS=ue(),Lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lo||(st.DataType=Lo={}));function zO(t){let e=rS(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=zO;function rS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(DO.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}st.getJSONTypes=rS;function LO(t,e){let{gen:n,data:r,opts:o}=t,s=HO(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,MO.schemaHasRulesForType)(t,e[0]));if(i){let a=sf(e,r,o.strictNumbers,Lo.Wrong);n.if(a,()=>{s.length?UO(t,e,s):af(t)})}return i}st.coerceAndCheckDataType=LO;var oS=new Set(["string","number","integer","boolean","null"]);function HO(t,e){return e?t.filter(n=>oS.has(n)||e==="array"&&n==="array"):[]}function UO(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(sf(e,o,s.strictNumbers),()=>r.assign(a,o))),r.if((0,Y._)`${a} !== undefined`);for(let u of n)(oS.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);r.else(),af(t),r.endIf(),r.if((0,Y._)`${a} !== undefined`,()=>{r.assign(o,a),FO(t,a)});function c(u){switch(u){case"string":r.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":r.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
4
4
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":r.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
5
5
  || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Y._)`+${o}`);return;case"boolean":r.elseIf((0,Y._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,Y._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":r.elseIf((0,Y._)`${o} === "" || ${o} === 0 || ${o} === false`),r.assign(a,null);return;case"array":r.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
6
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function FO({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function of(t,e,n,r=Lo.Correct){let o=r===Lo.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===Lo.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=of;function sf(t,e,n,r){if(t.length===1)return of(t[0],e,n,r);let o,s=(0,nS.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,of(i,e,n,r));return o}st.checkDataTypes=sf;var ZO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function af(t){let e=BO(t);(0,jO.reportError)(e,ZO)}st.reportTypeError=af;function BO(t){let{gen:e,data:n,schema:r}=t,o=(0,nS.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var iS=I(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.assignDefaults=void 0;var Ho=ee(),qO=ue();function VO(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)sS(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>sS(t,s,o.default))}uc.assignDefaults=VO;function sS(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Ho._)`${s}${(0,Ho.getProperty)(e)}`;if(o){(0,qO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ho._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ho._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ho._)`${a} = ${(0,Ho.stringify)(n)}`)}});var zt=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var ve=ee(),cf=ue(),rr=An(),WO=ue();function KO(t,e){let{gen:n,data:r,it:o}=t;n.if(lf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}he.checkReportMissingProp=KO;function GO({gen:t,data:e,it:{opts:n}},r,o){return(0,ve.or)(...r.map(s=>(0,ve.and)(lf(t,e,s,n.ownProperties),(0,ve._)`${o} = ${s}`)))}he.checkMissingProp=GO;function JO(t,e){t.setParams({missingProperty:e},!0),t.error()}he.reportMissingProp=JO;function aS(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=aS;function uf(t,e,n){return(0,ve._)`${aS(t)}.call(${e}, ${n})`}he.isOwnProperty=uf;function XO(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} !== undefined`;return r?(0,ve._)`${o} && ${uf(t,e,n)}`:o}he.propertyInData=XO;function lf(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} === undefined`;return r?(0,ve.or)(o,(0,ve.not)(uf(t,e,n))):o}he.noPropertyInData=lf;function cS(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=cS;function YO(t,e){return cS(e).filter(n=>!(0,cf.alwaysValidSchema)(t,e[n]))}he.schemaProperties=YO;function QO({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ve._)`${t}, ${e}, ${r}${o}`:e,d=[[rr.default.instancePath,(0,ve.strConcat)(rr.default.instancePath,s)],[rr.default.parentData,i.parentData],[rr.default.parentDataProperty,i.parentDataProperty],[rr.default.rootData,rr.default.rootData]];i.opts.dynamicRef&&d.push([rr.default.dynamicAnchors,rr.default.dynamicAnchors]);let f=(0,ve._)`${l}, ${n.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}he.callValidateCode=QO;var eI=(0,ve._)`new RegExp`;function tI({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,ve._)`${o.code==="new RegExp"?eI:(0,WO.useFunc)(t,o)}(${n}, ${r})`})}he.usePattern=tI;function nI(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,ve._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:cf.Type.Num},s),e.if((0,ve.not)(s),a)})}}he.validateArray=nI;function rI(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,cf.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,ve._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ve.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}he.validateUnion=rI});var dS=I(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.validateKeywordUsage=mn.validSchemaType=mn.funcKeywordCode=mn.macroKeywordCode=void 0;var lt=ee(),Wr=An(),oI=zt(),sI=ii();function iI(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=lS(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=iI;function aI(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;uI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=lS(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&&uS(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&uS(t),g(()=>cI(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?Wr.default.this:Wr.default.self,x=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,lt._)`${y}${(0,oI.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;r.if((0,lt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}mn.funcKeywordCode=aI;function uS(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,lt._)`${r.parentData}[${r.parentDataProperty}]`))}function cI(t,e){let{gen:n}=t;n.if((0,lt._)`Array.isArray(${e})`,()=>{n.assign(Wr.default.vErrors,(0,lt._)`${Wr.default.vErrors} === null ? ${e} : ${Wr.default.vErrors}.concat(${e})`).assign(Wr.default.errors,(0,lt._)`${Wr.default.vErrors}.length`),(0,sI.extendErrors)(t)},()=>t.error())}function uI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function lS(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 lI(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=lI;function dI({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=dI});var fS=I(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var hn=ee(),pS=ue();function pI(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,pS.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')}or.getSubschema=pI;function fI(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,pS.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]}}or.extendSubschemaData=fI;function mI(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}or.extendSubschemaMode=mI});var df=I((Z2,mS)=>{"use strict";mS.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 gS=I((B2,hS)=>{"use strict";var sr=hS.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(){};lc(e,r,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 lc(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 sr.arrayKeywords)for(var f=0;f<d.length;f++)lc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in sr.propsKeywords){if(d&&typeof d=="object")for(var m in d)lc(t,e,n,d[m],o+"/"+l+"/"+hI(m),s,o,l,r,m)}else(l in sr.keywords||t.allKeys&&!(l in sr.skipKeywords))&&lc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function hI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ci=I(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.getSchemaRefs=St.resolveUrl=St.normalizeId=St._getFullPath=St.getFullPath=St.inlineRef=void 0;var gI=ue(),yI=df(),_I=gS(),xI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function SI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!pf(t):e?yS(t)<=e:!1}St.inlineRef=SI;var bI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pf(t){for(let e in t){if(bI.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(pf)||typeof n=="object"&&pf(n))return!0}return!1}function yS(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!xI.has(n)&&(typeof t[n]=="object"&&(0,gI.eachItem)(t[n],r=>e+=yS(r)),e===1/0))return 1/0}return e}function _S(t,e="",n){n!==!1&&(e=Uo(e));let r=t.parse(e);return xS(t,r)}St.getFullPath=_S;function xS(t,e){return t.serialize(e).split("#")[0]+"#"}St._getFullPath=xS;var kI=/#\/?$/;function Uo(t){return t?t.replace(kI,""):""}St.normalizeId=Uo;function vI(t,e,n){return n=Uo(n),t.resolve(e,n)}St.resolveUrl=vI;var EI=/^[a-z_][-a-z0-9._]*$/i;function wI(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Uo(t[n]||e),s={"":o},i=_S(r,o,!1),a={},c=new Set;return _I(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(x){let b=this.opts.uriResolver.resolve;if(x=Uo(g?b(g,x):x),c.has(x))throw l(x);c.add(x);let v=this.refs[x];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,x):x!==Uo(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!EI.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,f,m){if(f!==void 0&&!yI(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}St.getSchemaRefs=wI});var di=I(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var ES=Qx(),SS=ai(),mf=rf(),dc=ai(),TI=iS(),li=dS(),ff=fS(),F=ee(),G=An(),PI=ci(),Nn=ue(),ui=ii();function RI(t){if(PS(t)&&(RS(t),TS(t))){OI(t);return}wS(t,()=>(0,ES.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=RI;function wS({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"; ${bS(n,o)}`),$I(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${CI(o)}`,r.$async,()=>t.code(bS(n,o)).code(s))}function CI(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 $I(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 OI(t){let{schema:e,opts:n,gen:r}=t;wS(t,()=>{n.$comment&&e.$comment&&$S(t),MI(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&II(t),CS(t),LI(t)})}function II(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 bS(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 AI(t,e){if(PS(t)&&(RS(t),TS(t))){NI(t,e);return}(0,ES.boolOrEmptySchema)(t,e)}function TS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function PS(t){return typeof t.schema!="boolean"}function NI(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&$S(t),jI(t),zI(t);let s=r.const("_errs",G.default.errors);CS(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function RS(t){(0,Nn.checkUnknownRules)(t),DI(t)}function CS(t,e){if(t.opts.jtd)return kS(t,[],!1,e);let n=(0,SS.getSchemaTypes)(t.schema),r=(0,SS.coerceAndCheckDataType)(t,n);kS(t,n,!r,e)}function DI(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Nn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function MI(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Nn.checkStrictMode)(t,"default is ignored in the schema root")}function jI(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,PI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zI(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function $S({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 LI(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&&HI(t),e.return((0,F._)`${G.default.errors} === 0`))}function HI({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 kS(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,Nn.schemaHasRulesButRef)(s,l))){o.block(()=>IS(t,"$ref",l.all.$ref.definition));return}c.jtd||UI(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,mf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,dc.checkDataType)(f.type,i,c.strictNumbers)),vS(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,dc.reportTypeError)(t)),o.endIf()):vS(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function vS(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,TI.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,mf.shouldUseRule)(r,s)&&IS(t,s.keyword,s.definition,e.type)})}function UI(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(FI(t,e),t.opts.allowUnionTypes||ZI(t,e),BI(t,t.dataTypes))}function FI(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{OS(t.dataTypes,n)||hf(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),VI(t,e)}}function ZI(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hf(t,"use allowUnionTypes to allow union type keyword")}function BI(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,mf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>qI(e,i))&&hf(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function qI(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function OS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function VI(t,e){let n=[];for(let r of t.dataTypes)OS(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function hf(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Nn.checkStrictMode)(t,e,t.opts.strictTypes)}var pc=class{constructor(e,n,r){if((0,li.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,Nn.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",AS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,li.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?ui.reportExtraError:ui.reportError)(this,this.def.error,n)}$dataError(){(0,ui.reportError)(this,this.def.$dataError||ui.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ui.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,dc.checkDataTypes)(c,n,s.opts.strictNumbers,dc.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,ff.getSubschema)(this.it,e);(0,ff.extendSubschemaData)(r,this.it,e),(0,ff.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return AI(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Nn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Nn.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}};ir.KeywordCxt=pc;function IS(t,e,n,r){let o=new pc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,li.funcKeywordCode)(o,n):"macro"in n?(0,li.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,li.funcKeywordCode)(o,n)}var WI=/^\/(?:[^~]|~0|~1)*$/,KI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function AS(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!WI.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=KI.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,Nn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}ir.getData=AS});var fc=I(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var gf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};yf.default=gf});var pi=I(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var _f=ci(),xf=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,_f.resolveUrl)(e,n,r),this.missingSchema=(0,_f.normalizeId)((0,_f.getFullPath)(e,this.missingRef))}};Sf.default=xf});var hc=I(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var en=ee(),GI=fc(),Kr=An(),tn=ci(),NS=ue(),JI=di(),Fo=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={}}};Lt.SchemaEnv=Fo;function kf(t){let e=DS.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:GI.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:Kr.default.data,parentData:Kr.default.parentData,parentDataProperty:Kr.default.parentDataProperty,dataNames:[Kr.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,JI.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Kr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Kr.default.self}`,`${Kr.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)}}Lt.compileSchema=kf;function XI(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=eA.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 Fo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=YI.call(this,s)}Lt.resolveRef=XI;function YI(t){return(0,tn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:kf.call(this,t)}function DS(t){for(let e of this._compilations)if(QI(e,t))return e}Lt.getCompilingSchema=DS;function QI(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function eA(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||mc.call(this,t,e)}function mc(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 bf.call(this,n,t);let s=(0,tn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=mc.call(this,t,i);return typeof a?.schema!="object"?void 0:bf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||kf.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 Fo({schema:a,schemaId:c,root:t,baseId:o})}return bf.call(this,n,i)}}Lt.resolveSchema=mc;var tA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bf(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,NS.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!tA.has(a)&&u&&(e=(0,tn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,NS.schemaHasRulesButRef)(n,this.RULES)){let a=(0,tn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=mc.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Fo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var MS=I((J2,nA)=>{nA.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 Ef=I((X2,HS)=>{"use strict";var rA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zS=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 vf(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 oA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jS(t){return t.length=0,!0}function sA(t,e,n){if(t.length){let r=vf(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function iA(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=sA;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=jS}else{o.push(u);continue}}return o.length&&(a===jS?n.zone=o.join(""):i?r.push(o.join("")):r.push(vf(o))),n.address=r.join(""),n}function LS(t){if(aA(t,":")<2)return{host:t,isIPV6:!1};let e=iA(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 aA(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function cA(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 uA(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 lA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!zS(n)){let r=LS(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}HS.exports={nonSimpleDomain:oA,recomposeAuthority:lA,normalizeComponentEncoding:uA,removeDotSegments:cA,isIPv4:zS,isUUID:rA,normalizeIPv6:LS,stringArrayToHexStripped:vf}});var qS=I((Y2,BS)=>{"use strict";var{isUUID:dA}=Ef(),pA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fA=["http","https","ws","wss","urn","urn:uuid"];function mA(t){return fA.indexOf(t)!==-1}function wf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function US(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function FS(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 hA(t){return t.secure=wf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gA(t){if((t.port===(wf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,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 yA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(pA);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=Tf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function _A(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=Tf(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 xA(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!dA(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function SA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ZS={scheme:"http",domainHost:!0,parse:US,serialize:FS},bA={scheme:"https",domainHost:ZS.domainHost,parse:US,serialize:FS},gc={scheme:"ws",domainHost:!0,parse:hA,serialize:gA},kA={scheme:"wss",domainHost:gc.domainHost,parse:gc.parse,serialize:gc.serialize},vA={scheme:"urn",parse:yA,serialize:_A,skipNormalize:!0},EA={scheme:"urn:uuid",parse:xA,serialize:SA,skipNormalize:!0},yc={http:ZS,https:bA,ws:gc,wss:kA,urn:vA,"urn:uuid":EA};Object.setPrototypeOf(yc,null);function Tf(t){return t&&(yc[t]||yc[t.toLowerCase()])||void 0}BS.exports={wsIsSecure:wf,SCHEMES:yc,isValidSchemeName:mA,getSchemeHandler:Tf}});var KS=I((Q2,xc)=>{"use strict";var{normalizeIPv6:wA,removeDotSegments:fi,recomposeAuthority:TA,normalizeComponentEncoding:_c,isIPv4:PA,nonSimpleDomain:RA}=Ef(),{SCHEMES:CA,getSchemeHandler:VS}=qS();function $A(t,e){return typeof t=="string"?t=gn(Dn(t,e),e):typeof t=="object"&&(t=Dn(gn(t,e),e)),t}function OA(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=WS(Dn(t,r),Dn(e,r),r,!0);return r.skipEscape=!0,gn(o,r)}function WS(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=fi(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=fi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=fi(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=fi(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 IA(t,e,n){return typeof t=="string"?(t=unescape(t),t=gn(_c(Dn(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=gn(_c(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=gn(_c(Dn(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=gn(_c(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=VS(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=TA(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=fi(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 AA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(AA);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(PA(r.host)===!1){let c=wA(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=VS(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&RA(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 Pf={SCHEMES:CA,normalize:$A,resolve:OA,resolveComponent:WS,equal:IA,serialize:gn,parse:Dn};xc.exports=Pf;xc.exports.default=Pf;xc.exports.fastUri=Pf});var JS=I(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var GS=KS();GS.code='require("ajv/dist/runtime/uri").default';Rf.default=GS});var ob=I(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.CodeGen=Je.Name=Je.nil=Je.stringify=Je.str=Je._=Je.KeywordCxt=void 0;var NA=di();Object.defineProperty(Je,"KeywordCxt",{enumerable:!0,get:function(){return NA.KeywordCxt}});var Zo=ee();Object.defineProperty(Je,"_",{enumerable:!0,get:function(){return Zo._}});Object.defineProperty(Je,"str",{enumerable:!0,get:function(){return Zo.str}});Object.defineProperty(Je,"stringify",{enumerable:!0,get:function(){return Zo.stringify}});Object.defineProperty(Je,"nil",{enumerable:!0,get:function(){return Zo.nil}});Object.defineProperty(Je,"Name",{enumerable:!0,get:function(){return Zo.Name}});Object.defineProperty(Je,"CodeGen",{enumerable:!0,get:function(){return Zo.CodeGen}});var DA=fc(),tb=pi(),MA=nf(),mi=hc(),jA=ee(),hi=ci(),Sc=ai(),$f=ue(),XS=MS(),zA=JS(),nb=(t,e)=>new RegExp(t,e);nb.code="new RegExp";var LA=["removeAdditional","useDefaults","coerceTypes"],HA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UA={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."},FA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},YS=200;function ZA(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,x,b,v,O,R,M,D;let V=t.strict,P=(e=t.code)===null||e===void 0?void 0:e.optimize,T=P===!0||P===void 0?1:P||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:nb,pe=(o=t.uriResolver)!==null&&o!==void 0?o:zA.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:T,regExp:H}:{optimize:T,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:YS,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:YS,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:pe}}var gi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...ZA(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new jA.ValueScope({scope:{},prefixes:HA,es5:n,lines:r}),this.logger=GA(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,MA.getRules)(),QS.call(this,UA,e,"NOT SUPPORTED"),QS.call(this,FA,e,"DEPRECATED","warn"),this._metaOpts=WA.call(this),e.formats&&qA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&VA.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),BA.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=XS;r==="id"&&(o={...XS},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 tb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,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,hi.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=eb.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new mi.SchemaEnv({schema:{},schemaId:r});if(n=mi.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=eb.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,hi.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(XA.call(this,r,n),!n)return(0,$f.eachItem)(r,s=>Cf.call(this,s)),this;QA.call(this,n);let o={...n,type:(0,Sc.getJSONTypes)(n.type),schemaType:(0,Sc.getJSONTypes)(n.schemaType)};return(0,$f.eachItem)(r,o.type.length===0?s=>Cf.call(this,s,o):s=>o.type.forEach(i=>Cf.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]=rb(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,hi.normalizeId)(i||r);let u=hi.getSchemaRefs.call(this,e,r);return c=new mi.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):mi.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{mi.compileSchema.call(this,e)}finally{this.opts=n}}};gi.ValidationError=DA.default;gi.MissingRefError=tb.default;Je.default=gi;function QS(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 eb(t){return t=(0,hi.normalizeId)(t),this.schemas[t]||this.refs[t]}function BA(){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 qA(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function VA(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 WA(){let t={...this.opts};for(let e of LA)delete t[e];return t}var KA={log(){},warn(){},error(){}};function GA(t){if(t===!1)return KA;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 JA=/^[a-z_$][a-z0-9_$:-]*$/i;function XA(t,e){let{RULES:n}=this;if((0,$f.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!JA.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 Cf(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,Sc.getJSONTypes)(e.type),schemaType:(0,Sc.getJSONTypes)(e.schemaType)}};e.before?YA.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 YA(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 QA(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rb(e)),t.validateSchema=this.compile(e,!0))}var eN={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rb(t){return{anyOf:[t,eN]}}});var sb=I(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Of.default=tN});var ub=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.callRef=Gr.getValidate=void 0;var nN=pi(),ib=zt(),bt=ee(),Bo=An(),ab=hc(),bc=ue(),rN={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=ab.resolveRef.call(c,u,o,n);if(l===void 0)throw new nN.default(r.opts.uriResolver,o,n);if(l instanceof ab.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return kc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return kc(t,(0,bt._)`${p}.validate`,u,u.$async)}function f(p){let h=cb(t,p);kc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,bt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:bt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function cb(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,bt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Gr.getValidate=cb;function kc(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Bo.default.this:bt.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,bt._)`await ${(0,ib.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,bt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,ib.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,bt._)`${p}.errors`;o.assign(Bo.default.vErrors,(0,bt._)`${Bo.default.vErrors} === null ? ${h} : ${Bo.default.vErrors}.concat(${h})`),o.assign(Bo.default.errors,(0,bt._)`${Bo.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=bc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,bt._)`${p}.evaluated.props`);s.props=bc.mergeEvaluated.props(o,y,s.props,bt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=bc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,bt._)`${p}.evaluated.items`);s.items=bc.mergeEvaluated.items(o,y,s.items,bt.Name)}}}Gr.callRef=kc;Gr.default=rN});var lb=I(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var oN=sb(),sN=ub(),iN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oN.default,sN.default];If.default=iN});var db=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var vc=ee(),ar=vc.operators,Ec={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},aN={message:({keyword:t,schemaCode:e})=>(0,vc.str)`must be ${Ec[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vc._)`{comparison: ${Ec[t].okStr}, limit: ${e}}`},cN={keyword:Object.keys(Ec),type:"number",schemaType:"number",$data:!0,error:aN,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,vc._)`${n} ${Ec[e].fail} ${r} || isNaN(${n})`)}};Af.default=cN});var pb=I(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var yi=ee(),uN={message:({schemaCode:t})=>(0,yi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,yi._)`{multipleOf: ${t}}`},lN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:uN,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,yi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,yi._)`${i} !== parseInt(${i})`;t.fail$data((0,yi._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Nf.default=lN});var mb=I(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});function fb(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}Df.default=fb;fb.code='require("ajv/dist/runtime/ucs2length").default'});var hb=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Jr=ee(),dN=ue(),pN=mb(),fN={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Jr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Jr._)`{limit: ${t}}`},mN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fN,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Jr.operators.GT:Jr.operators.LT,i=o.opts.unicode===!1?(0,Jr._)`${n}.length`:(0,Jr._)`${(0,dN.useFunc)(t.gen,pN.default)}(${n})`;t.fail$data((0,Jr._)`${i} ${s} ${r}`)}};Mf.default=mN});var gb=I(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var hN=zt(),gN=ue(),qo=ee(),yN={message:({schemaCode:t})=>(0,qo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qo._)`{pattern: ${t}}`},_N={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yN,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,qo._)`new RegExp`:(0,gN.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qo._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,qo._)`!${l}`)}else{let c=(0,hN.usePattern)(t,o);t.fail$data((0,qo._)`!${c}.test(${n})`)}}};jf.default=_N});var yb=I(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var _i=ee(),xN={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,_i.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,_i._)`{limit: ${t}}`},SN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:xN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?_i.operators.GT:_i.operators.LT;t.fail$data((0,_i._)`Object.keys(${n}).length ${o} ${r}`)}};zf.default=SN});var _b=I(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var xi=zt(),Si=ee(),bN=ue(),kN={message:({params:{missingProperty:t}})=>(0,Si.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Si._)`{missingProperty: ${t}}`},vN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kN,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,bN.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Si.nil,d);else for(let m of n)(0,xi.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,xi.checkMissingProp)(t,n,m)),(0,xi.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,xi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,xi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Si.not)(p),()=>{t.error(),e.break()})},Si.nil)}}};Lf.default=vN});var xb=I(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var bi=ee(),EN={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,bi.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,bi._)`{limit: ${t}}`},wN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?bi.operators.GT:bi.operators.LT;t.fail$data((0,bi._)`${n}.length ${o} ${r}`)}};Hf.default=wN});var wc=I(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Sb=df();Sb.code='require("ajv/dist/runtime/equal").default';Uf.default=Sb});var bb=I(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Ff=ai(),Xe=ee(),TN=ue(),PN=wc(),RN={message:({params:{i:t,j:e}})=>(0,Xe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Xe._)`{i: ${t}, j: ${e}}`},CN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RN,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,Ff.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Xe._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Xe._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Xe._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),y=(0,Ff.checkDataTypes)(u,g,a.opts.strictNumbers,Ff.DataType.Wrong),_=e.const("indices",(0,Xe._)`{}`);e.for((0,Xe._)`;${p}--;`,()=>{e.let(g,(0,Xe._)`${n}[${p}]`),e.if(y,(0,Xe._)`continue`),u.length>1&&e.if((0,Xe._)`typeof ${g} == "string"`,(0,Xe._)`${g} += "_"`),e.if((0,Xe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Xe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Xe._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,TN.useFunc)(e,PN.default),y=e.name("outer");e.label(y).for((0,Xe._)`;${p}--;`,()=>e.for((0,Xe._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Xe._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Zf.default=CN});var kb=I(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Bf=ee(),$N=ue(),ON=wc(),IN={message:"must be equal to constant",params:({schemaCode:t})=>(0,Bf._)`{allowedValue: ${t}}`},AN={keyword:"const",$data:!0,error:IN,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Bf._)`!${(0,$N.useFunc)(e,ON.default)}(${n}, ${o})`):t.fail((0,Bf._)`${s} !== ${n}`)}};qf.default=AN});var vb=I(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var ki=ee(),NN=ue(),DN=wc(),MN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ki._)`{allowedValues: ${t}}`},jN={keyword:"enum",schemaType:"array",$data:!0,error:MN,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,NN.useFunc)(e,DN.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,ki.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,ki._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,ki._)`${u()}(${n}, ${m}[${p}])`:(0,ki._)`${n} === ${h}`}}};Vf.default=jN});var Eb=I(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var zN=db(),LN=pb(),HN=hb(),UN=gb(),FN=yb(),ZN=_b(),BN=xb(),qN=bb(),VN=kb(),WN=vb(),KN=[zN.default,LN.default,HN.default,UN.default,FN.default,ZN.default,BN.default,qN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},VN.default,WN.default];Wf.default=KN});var Gf=I(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.validateAdditionalItems=void 0;var Xr=ee(),Kf=ue(),GN={message:({params:{len:t}})=>(0,Xr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xr._)`{limit: ${t}}`},JN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:GN,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Kf.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}wb(t,r)}};function wb(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Xr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Kf.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Xr._)`${a} <= ${e.length}`);n.if((0,Xr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Kf.Type.Num},u),i.allErrors||n.if((0,Xr.not)(u),()=>n.break())})}}vi.validateAdditionalItems=wb;vi.default=JN});var Jf=I(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.validateTuple=void 0;var Tb=ee(),Tc=ue(),XN=zt(),YN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Pb(t,"additionalItems",e);n.items=!0,!(0,Tc.alwaysValidSchema)(n,e)&&t.ok((0,XN.validateArray)(t))}};function Pb(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=Tc.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,Tb._)`${s}.length`);n.forEach((d,f)=>{(0,Tc.alwaysValidSchema)(a,d)||(r.if((0,Tb._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=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,Tc.checkStrictMode)(a,g,f.strictTuples)}}}Ei.validateTuple=Pb;Ei.default=YN});var Rb=I(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var QN=Jf(),eD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,QN.validateTuple)(t,"items")};Xf.default=eD});var $b=I(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var Cb=ee(),tD=ue(),nD=zt(),rD=Gf(),oD={message:({params:{len:t}})=>(0,Cb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Cb._)`{limit: ${t}}`},sD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oD,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,tD.alwaysValidSchema)(r,e)&&(o?(0,rD.validateAdditionalItems)(t,o):t.ok((0,nD.validateArray)(t)))}};Yf.default=sD});var Ob=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Ht=ee(),Pc=ue(),iD={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}}`},aD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iD,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)))}}};Qf.default=aD});var Nb=I(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateSchemaDeps=yn.validatePropertyDeps=yn.error=void 0;var em=ee(),cD=ue(),wi=zt();yn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,em.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,em._)`{property: ${t},
6
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function FO({gen:t,parentData:e,parentDataProperty:n},r){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${n}]`,r))}function of(t,e,n,r=Lo.Correct){let o=r===Lo.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===Lo.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=of;function sf(t,e,n,r){if(t.length===1)return of(t[0],e,n,r);let o,s=(0,nS.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,of(i,e,n,r));return o}st.checkDataTypes=sf;var ZO={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function af(t){let e=BO(t);(0,jO.reportError)(e,ZO)}st.reportTypeError=af;function BO(t){let{gen:e,data:n,schema:r}=t,o=(0,nS.schemaRefOrVal)(t,r,"type");return{gen:e,keyword:"type",data:n,schema:r.type,schemaCode:o,schemaValue:o,parentSchema:r,params:{},it:t}}});var iS=I(uc=>{"use strict";Object.defineProperty(uc,"__esModule",{value:!0});uc.assignDefaults=void 0;var Ho=ee(),qO=ue();function VO(t,e){let{properties:n,items:r}=t.schema;if(e==="object"&&n)for(let o in n)sS(t,o,n[o].default);else e==="array"&&Array.isArray(r)&&r.forEach((o,s)=>sS(t,s,o.default))}uc.assignDefaults=VO;function sS(t,e,n){let{gen:r,compositeRule:o,data:s,opts:i}=t;if(n===void 0)return;let a=(0,Ho._)`${s}${(0,Ho.getProperty)(e)}`;if(o){(0,qO.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Ho._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Ho._)`${c} || ${a} === null || ${a} === ""`),r.if(c,(0,Ho._)`${a} = ${(0,Ho.stringify)(n)}`)}});var zt=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.validateUnion=he.validateArray=he.usePattern=he.callValidateCode=he.schemaProperties=he.allSchemaProperties=he.noPropertyInData=he.propertyInData=he.isOwnProperty=he.hasPropFunc=he.reportMissingProp=he.checkMissingProp=he.checkReportMissingProp=void 0;var ve=ee(),cf=ue(),rr=An(),WO=ue();function KO(t,e){let{gen:n,data:r,it:o}=t;n.if(lf(n,r,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,ve._)`${e}`},!0),t.error()})}he.checkReportMissingProp=KO;function GO({gen:t,data:e,it:{opts:n}},r,o){return(0,ve.or)(...r.map(s=>(0,ve.and)(lf(t,e,s,n.ownProperties),(0,ve._)`${o} = ${s}`)))}he.checkMissingProp=GO;function JO(t,e){t.setParams({missingProperty:e},!0),t.error()}he.reportMissingProp=JO;function aS(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,ve._)`Object.prototype.hasOwnProperty`})}he.hasPropFunc=aS;function uf(t,e,n){return(0,ve._)`${aS(t)}.call(${e}, ${n})`}he.isOwnProperty=uf;function XO(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} !== undefined`;return r?(0,ve._)`${o} && ${uf(t,e,n)}`:o}he.propertyInData=XO;function lf(t,e,n,r){let o=(0,ve._)`${e}${(0,ve.getProperty)(n)} === undefined`;return r?(0,ve.or)(o,(0,ve.not)(uf(t,e,n))):o}he.noPropertyInData=lf;function cS(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}he.allSchemaProperties=cS;function YO(t,e){return cS(e).filter(n=>!(0,cf.alwaysValidSchema)(t,e[n]))}he.schemaProperties=YO;function QO({schemaCode:t,data:e,it:{gen:n,topSchemaRef:r,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,ve._)`${t}, ${e}, ${r}${o}`:e,d=[[rr.default.instancePath,(0,ve.strConcat)(rr.default.instancePath,s)],[rr.default.parentData,i.parentData],[rr.default.parentDataProperty,i.parentDataProperty],[rr.default.rootData,rr.default.rootData]];i.opts.dynamicRef&&d.push([rr.default.dynamicAnchors,rr.default.dynamicAnchors]);let f=(0,ve._)`${l}, ${n.object(...d)}`;return c!==ve.nil?(0,ve._)`${a}.call(${c}, ${f})`:(0,ve._)`${a}(${f})`}he.callValidateCode=QO;var eI=(0,ve._)`new RegExp`;function tI({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,ve._)`${o.code==="new RegExp"?eI:(0,WO.useFunc)(t,o)}(${n}, ${r})`})}he.usePattern=tI;function nI(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,ve._)`${n}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:r,dataProp:u,dataPropType:cf.Type.Num},s),e.if((0,ve.not)(s),a)})}}he.validateArray=nI;function rI(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,cf.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,ve._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,ve.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}he.validateUnion=rI});var dS=I(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.validateKeywordUsage=mn.validSchemaType=mn.funcKeywordCode=mn.macroKeywordCode=void 0;var lt=ee(),Wr=An(),oI=zt(),sI=ii();function iI(t,e){let{gen:n,keyword:r,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=lS(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=iI;function aI(t,e){var n;let{gen:r,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;uI(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=lS(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&&uS(t),g(()=>t.error());else{let y=e.async?m():p();e.modifying&&uS(t),g(()=>cI(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?Wr.default.this:Wr.default.self,x=!("compile"in e&&!a||e.schema===!1);r.assign(d,(0,lt._)`${y}${(0,oI.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;r.if((0,lt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}mn.funcKeywordCode=aI;function uS(t){let{gen:e,data:n,it:r}=t;e.if(r.parentData,()=>e.assign(n,(0,lt._)`${r.parentData}[${r.parentDataProperty}]`))}function cI(t,e){let{gen:n}=t;n.if((0,lt._)`Array.isArray(${e})`,()=>{n.assign(Wr.default.vErrors,(0,lt._)`${Wr.default.vErrors} === null ? ${e} : ${Wr.default.vErrors}.concat(${e})`).assign(Wr.default.errors,(0,lt._)`${Wr.default.vErrors}.length`),(0,sI.extendErrors)(t)},()=>t.error())}function uI({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function lS(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 lI(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=lI;function dI({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=dI});var fS=I(or=>{"use strict";Object.defineProperty(or,"__esModule",{value:!0});or.extendSubschemaMode=or.extendSubschemaData=or.getSubschema=void 0;var hn=ee(),pS=ue();function pI(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,pS.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')}or.getSubschema=pI;function fI(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,pS.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]}}or.extendSubschemaData=fI;function mI(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}or.extendSubschemaMode=mI});var df=I((B2,mS)=>{"use strict";mS.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 gS=I((q2,hS)=>{"use strict";var sr=hS.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(){};lc(e,r,o,t,"",t)};sr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};sr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};sr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};sr.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 lc(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 sr.arrayKeywords)for(var f=0;f<d.length;f++)lc(t,e,n,d[f],o+"/"+l+"/"+f,s,o,l,r,f)}else if(l in sr.propsKeywords){if(d&&typeof d=="object")for(var m in d)lc(t,e,n,d[m],o+"/"+l+"/"+hI(m),s,o,l,r,m)}else(l in sr.keywords||t.allKeys&&!(l in sr.skipKeywords))&&lc(t,e,n,d,o+"/"+l,s,o,l,r)}n(r,o,s,i,a,c,u)}}function hI(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ci=I(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.getSchemaRefs=St.resolveUrl=St.normalizeId=St._getFullPath=St.getFullPath=St.inlineRef=void 0;var gI=ue(),yI=df(),_I=gS(),xI=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function SI(t,e=!0){return typeof t=="boolean"?!0:e===!0?!pf(t):e?yS(t)<=e:!1}St.inlineRef=SI;var bI=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function pf(t){for(let e in t){if(bI.has(e))return!0;let n=t[e];if(Array.isArray(n)&&n.some(pf)||typeof n=="object"&&pf(n))return!0}return!1}function yS(t){let e=0;for(let n in t){if(n==="$ref")return 1/0;if(e++,!xI.has(n)&&(typeof t[n]=="object"&&(0,gI.eachItem)(t[n],r=>e+=yS(r)),e===1/0))return 1/0}return e}function _S(t,e="",n){n!==!1&&(e=Uo(e));let r=t.parse(e);return xS(t,r)}St.getFullPath=_S;function xS(t,e){return t.serialize(e).split("#")[0]+"#"}St._getFullPath=xS;var kI=/#\/?$/;function Uo(t){return t?t.replace(kI,""):""}St.normalizeId=Uo;function vI(t,e,n){return n=Uo(n),t.resolve(e,n)}St.resolveUrl=vI;var EI=/^[a-z_][-a-z0-9._]*$/i;function wI(t,e){if(typeof t=="boolean")return{};let{schemaId:n,uriResolver:r}=this.opts,o=Uo(t[n]||e),s={"":o},i=_S(r,o,!1),a={},c=new Set;return _I(t,{allKeys:!0},(d,f,m,p)=>{if(p===void 0)return;let h=i+f,g=s[p];typeof d[n]=="string"&&(g=y.call(this,d[n])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[f]=g;function y(x){let b=this.opts.uriResolver.resolve;if(x=Uo(g?b(g,x):x),c.has(x))throw l(x);c.add(x);let v=this.refs[x];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(d,v.schema,x):x!==Uo(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!EI.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,f,m){if(f!==void 0&&!yI(d,f))throw l(m)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}St.getSchemaRefs=wI});var di=I(ir=>{"use strict";Object.defineProperty(ir,"__esModule",{value:!0});ir.getData=ir.KeywordCxt=ir.validateFunctionCode=void 0;var ES=Qx(),SS=ai(),mf=rf(),dc=ai(),TI=iS(),li=dS(),ff=fS(),F=ee(),G=An(),PI=ci(),Nn=ue(),ui=ii();function RI(t){if(PS(t)&&(RS(t),TS(t))){OI(t);return}wS(t,()=>(0,ES.topBoolOrEmptySchema)(t))}ir.validateFunctionCode=RI;function wS({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"; ${bS(n,o)}`),$I(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${CI(o)}`,r.$async,()=>t.code(bS(n,o)).code(s))}function CI(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 $I(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 OI(t){let{schema:e,opts:n,gen:r}=t;wS(t,()=>{n.$comment&&e.$comment&&$S(t),MI(t),r.let(G.default.vErrors,null),r.let(G.default.errors,0),n.unevaluated&&II(t),CS(t),LI(t)})}function II(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 bS(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 AI(t,e){if(PS(t)&&(RS(t),TS(t))){NI(t,e);return}(0,ES.boolOrEmptySchema)(t,e)}function TS({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let n in t)if(e.RULES.all[n])return!0;return!1}function PS(t){return typeof t.schema!="boolean"}function NI(t,e){let{schema:n,gen:r,opts:o}=t;o.$comment&&n.$comment&&$S(t),jI(t),zI(t);let s=r.const("_errs",G.default.errors);CS(t,s),r.var(e,(0,F._)`${s} === ${G.default.errors}`)}function RS(t){(0,Nn.checkUnknownRules)(t),DI(t)}function CS(t,e){if(t.opts.jtd)return kS(t,[],!1,e);let n=(0,SS.getSchemaTypes)(t.schema),r=(0,SS.coerceAndCheckDataType)(t,n);kS(t,n,!r,e)}function DI(t){let{schema:e,errSchemaPath:n,opts:r,self:o}=t;e.$ref&&r.ignoreKeywordsWithRef&&(0,Nn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function MI(t){let{schema:e,opts:n}=t;e.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,Nn.checkStrictMode)(t,"default is ignored in the schema root")}function jI(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,PI.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function zI(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function $S({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 LI(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&&HI(t),e.return((0,F._)`${G.default.errors} === 0`))}function HI({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 kS(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,Nn.schemaHasRulesButRef)(s,l))){o.block(()=>IS(t,"$ref",l.all.$ref.definition));return}c.jtd||UI(t,e),o.block(()=>{for(let f of l.rules)d(f);d(l.post)});function d(f){(0,mf.shouldUseGroup)(s,f)&&(f.type?(o.if((0,dc.checkDataType)(f.type,i,c.strictNumbers)),vS(t,f),e.length===1&&e[0]===f.type&&n&&(o.else(),(0,dc.reportTypeError)(t)),o.endIf()):vS(t,f),a||o.if((0,F._)`${G.default.errors} === ${r||0}`))}}function vS(t,e){let{gen:n,schema:r,opts:{useDefaults:o}}=t;o&&(0,TI.assignDefaults)(t,e.type),n.block(()=>{for(let s of e.rules)(0,mf.shouldUseRule)(r,s)&&IS(t,s.keyword,s.definition,e.type)})}function UI(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(FI(t,e),t.opts.allowUnionTypes||ZI(t,e),BI(t,t.dataTypes))}function FI(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(n=>{OS(t.dataTypes,n)||hf(t,`type "${n}" not allowed by context "${t.dataTypes.join(",")}"`)}),VI(t,e)}}function ZI(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&hf(t,"use allowUnionTypes to allow union type keyword")}function BI(t,e){let n=t.self.RULES.all;for(let r in n){let o=n[r];if(typeof o=="object"&&(0,mf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>qI(e,i))&&hf(t,`missing type "${s.join(",")}" for keyword "${r}"`)}}}function qI(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function OS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function VI(t,e){let n=[];for(let r of t.dataTypes)OS(e,r)?n.push(r):e.includes("integer")&&r==="number"&&n.push("integer");t.dataTypes=n}function hf(t,e){let n=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${n}" (strictTypes)`,(0,Nn.checkStrictMode)(t,e,t.opts.strictTypes)}var pc=class{constructor(e,n,r){if((0,li.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,Nn.schemaRefOrVal)(e,this.schema,r,this.$data),this.schemaType=n.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=n,this.$data)this.schemaCode=e.gen.const("vSchema",AS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,li.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?ui.reportExtraError:ui.reportError)(this,this.def.error,n)}$dataError(){(0,ui.reportError)(this,this.def.$dataError||ui.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ui.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,dc.checkDataTypes)(c,n,s.opts.strictNumbers,dc.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,ff.getSubschema)(this.it,e);(0,ff.extendSubschemaData)(r,this.it,e),(0,ff.extendSubschemaMode)(r,e);let o={...this.it,...r,items:void 0,props:void 0};return AI(o,n),o}mergeEvaluated(e,n){let{it:r,gen:o}=this;r.opts.unevaluated&&(r.props!==!0&&e.props!==void 0&&(r.props=Nn.mergeEvaluated.props(o,e.props,r.props,n)),r.items!==!0&&e.items!==void 0&&(r.items=Nn.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}};ir.KeywordCxt=pc;function IS(t,e,n,r){let o=new pc(t,n,e);"code"in n?n.code(o,r):o.$data&&n.validate?(0,li.funcKeywordCode)(o,n):"macro"in n?(0,li.macroKeywordCode)(o,n):(n.compile||n.validate)&&(0,li.funcKeywordCode)(o,n)}var WI=/^\/(?:[^~]|~0|~1)*$/,KI=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function AS(t,{dataLevel:e,dataNames:n,dataPathArr:r}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!WI.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=KI.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,Nn.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}ir.getData=AS});var fc=I(yf=>{"use strict";Object.defineProperty(yf,"__esModule",{value:!0});var gf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};yf.default=gf});var pi=I(Sf=>{"use strict";Object.defineProperty(Sf,"__esModule",{value:!0});var _f=ci(),xf=class extends Error{constructor(e,n,r,o){super(o||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,_f.resolveUrl)(e,n,r),this.missingSchema=(0,_f.normalizeId)((0,_f.getFullPath)(e,this.missingRef))}};Sf.default=xf});var hc=I(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.resolveSchema=Lt.getCompilingSchema=Lt.resolveRef=Lt.compileSchema=Lt.SchemaEnv=void 0;var en=ee(),GI=fc(),Kr=An(),tn=ci(),NS=ue(),JI=di(),Fo=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={}}};Lt.SchemaEnv=Fo;function kf(t){let e=DS.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:GI.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:Kr.default.data,parentData:Kr.default.parentData,parentDataProperty:Kr.default.parentDataProperty,dataNames:[Kr.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,JI.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Kr.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let m=new Function(`${Kr.default.self}`,`${Kr.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)}}Lt.compileSchema=kf;function XI(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=eA.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 Fo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[n]=YI.call(this,s)}Lt.resolveRef=XI;function YI(t){return(0,tn.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:kf.call(this,t)}function DS(t){for(let e of this._compilations)if(QI(e,t))return e}Lt.getCompilingSchema=DS;function QI(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function eA(t,e){let n;for(;typeof(n=this.refs[e])=="string";)e=n;return n||this.schemas[e]||mc.call(this,t,e)}function mc(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 bf.call(this,n,t);let s=(0,tn.normalizeId)(r),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=mc.call(this,t,i);return typeof a?.schema!="object"?void 0:bf.call(this,n,a)}if(typeof i?.schema=="object"){if(i.validate||kf.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 Fo({schema:a,schemaId:c,root:t,baseId:o})}return bf.call(this,n,i)}}Lt.resolveSchema=mc;var tA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function bf(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,NS.unescapeFragment)(a)];if(c===void 0)return;n=c;let u=typeof n=="object"&&n[this.opts.schemaId];!tA.has(a)&&u&&(e=(0,tn.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof n!="boolean"&&n.$ref&&!(0,NS.schemaHasRulesButRef)(n,this.RULES)){let a=(0,tn.resolveUrl)(this.opts.uriResolver,e,n.$ref);s=mc.call(this,r,a)}let{schemaId:i}=this.opts;if(s=s||new Fo({schema:n,schemaId:i,root:r,baseId:e}),s.schema!==s.root.schema)return s}});var MS=I((X2,nA)=>{nA.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 Ef=I((Y2,HS)=>{"use strict";var rA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),zS=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 vf(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 oA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function jS(t){return t.length=0,!0}function sA(t,e,n){if(t.length){let r=vf(t);if(r!=="")e.push(r);else return n.error=!0,!1;t.length=0}return!0}function iA(t){let e=0,n={error:!1,address:"",zone:""},r=[],o=[],s=!1,i=!1,a=sA;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=jS}else{o.push(u);continue}}return o.length&&(a===jS?n.zone=o.join(""):i?r.push(o.join("")):r.push(vf(o))),n.address=r.join(""),n}function LS(t){if(aA(t,":")<2)return{host:t,isIPV6:!1};let e=iA(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 aA(t,e){let n=0;for(let r=0;r<t.length;r++)t[r]===e&&n++;return n}function cA(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 uA(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 lA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let n=unescape(t.host);if(!zS(n)){let r=LS(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}HS.exports={nonSimpleDomain:oA,recomposeAuthority:lA,normalizeComponentEncoding:uA,removeDotSegments:cA,isIPv4:zS,isUUID:rA,normalizeIPv6:LS,stringArrayToHexStripped:vf}});var qS=I((Q2,BS)=>{"use strict";var{isUUID:dA}=Ef(),pA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fA=["http","https","ws","wss","urn","urn:uuid"];function mA(t){return fA.indexOf(t)!==-1}function wf(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function US(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function FS(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 hA(t){return t.secure=wf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gA(t){if((t.port===(wf(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,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 yA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let n=t.path.match(pA);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=Tf(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function _A(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=Tf(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 xA(t,e){let n=t;return n.uuid=n.nss,n.nss=void 0,!e.tolerant&&(!n.uuid||!dA(n.uuid))&&(n.error=n.error||"UUID is not valid."),n}function SA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var ZS={scheme:"http",domainHost:!0,parse:US,serialize:FS},bA={scheme:"https",domainHost:ZS.domainHost,parse:US,serialize:FS},gc={scheme:"ws",domainHost:!0,parse:hA,serialize:gA},kA={scheme:"wss",domainHost:gc.domainHost,parse:gc.parse,serialize:gc.serialize},vA={scheme:"urn",parse:yA,serialize:_A,skipNormalize:!0},EA={scheme:"urn:uuid",parse:xA,serialize:SA,skipNormalize:!0},yc={http:ZS,https:bA,ws:gc,wss:kA,urn:vA,"urn:uuid":EA};Object.setPrototypeOf(yc,null);function Tf(t){return t&&(yc[t]||yc[t.toLowerCase()])||void 0}BS.exports={wsIsSecure:wf,SCHEMES:yc,isValidSchemeName:mA,getSchemeHandler:Tf}});var KS=I((e4,xc)=>{"use strict";var{normalizeIPv6:wA,removeDotSegments:fi,recomposeAuthority:TA,normalizeComponentEncoding:_c,isIPv4:PA,nonSimpleDomain:RA}=Ef(),{SCHEMES:CA,getSchemeHandler:VS}=qS();function $A(t,e){return typeof t=="string"?t=gn(Dn(t,e),e):typeof t=="object"&&(t=Dn(gn(t,e),e)),t}function OA(t,e,n){let r=n?Object.assign({scheme:"null"},n):{scheme:"null"},o=WS(Dn(t,r),Dn(e,r),r,!0);return r.skipEscape=!0,gn(o,r)}function WS(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=fi(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=fi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=fi(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=fi(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 IA(t,e,n){return typeof t=="string"?(t=unescape(t),t=gn(_c(Dn(t,n),!0),{...n,skipEscape:!0})):typeof t=="object"&&(t=gn(_c(t,!0),{...n,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=gn(_c(Dn(e,n),!0),{...n,skipEscape:!0})):typeof e=="object"&&(e=gn(_c(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=VS(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=TA(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=fi(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 AA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(AA);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(PA(r.host)===!1){let c=wA(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=VS(n.scheme||r.scheme);if(!n.unicodeSupport&&(!i||!i.unicodeSupport)&&r.host&&(n.domainHost||i&&i.domainHost)&&o===!1&&RA(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 Pf={SCHEMES:CA,normalize:$A,resolve:OA,resolveComponent:WS,equal:IA,serialize:gn,parse:Dn};xc.exports=Pf;xc.exports.default=Pf;xc.exports.fastUri=Pf});var JS=I(Rf=>{"use strict";Object.defineProperty(Rf,"__esModule",{value:!0});var GS=KS();GS.code='require("ajv/dist/runtime/uri").default';Rf.default=GS});var ob=I(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.CodeGen=Je.Name=Je.nil=Je.stringify=Je.str=Je._=Je.KeywordCxt=void 0;var NA=di();Object.defineProperty(Je,"KeywordCxt",{enumerable:!0,get:function(){return NA.KeywordCxt}});var Zo=ee();Object.defineProperty(Je,"_",{enumerable:!0,get:function(){return Zo._}});Object.defineProperty(Je,"str",{enumerable:!0,get:function(){return Zo.str}});Object.defineProperty(Je,"stringify",{enumerable:!0,get:function(){return Zo.stringify}});Object.defineProperty(Je,"nil",{enumerable:!0,get:function(){return Zo.nil}});Object.defineProperty(Je,"Name",{enumerable:!0,get:function(){return Zo.Name}});Object.defineProperty(Je,"CodeGen",{enumerable:!0,get:function(){return Zo.CodeGen}});var DA=fc(),tb=pi(),MA=nf(),mi=hc(),jA=ee(),hi=ci(),Sc=ai(),$f=ue(),XS=MS(),zA=JS(),nb=(t,e)=>new RegExp(t,e);nb.code="new RegExp";var LA=["removeAdditional","useDefaults","coerceTypes"],HA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),UA={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."},FA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},YS=200;function ZA(t){var e,n,r,o,s,i,a,c,u,l,d,f,m,p,h,g,y,_,x,b,v,O,R,M,D;let V=t.strict,P=(e=t.code)===null||e===void 0?void 0:e.optimize,T=P===!0||P===void 0?1:P||0,H=(r=(n=t.code)===null||n===void 0?void 0:n.regExp)!==null&&r!==void 0?r:nb,pe=(o=t.uriResolver)!==null&&o!==void 0?o:zA.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:T,regExp:H}:{optimize:T,regExp:H},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:YS,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:YS,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(b=t.schemaId)!==null&&b!==void 0?b:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(O=t.validateSchema)!==null&&O!==void 0?O:!0,validateFormats:(R=t.validateFormats)!==null&&R!==void 0?R:!0,unicodeRegExp:(M=t.unicodeRegExp)!==null&&M!==void 0?M:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:pe}}var gi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...ZA(e)};let{es5:n,lines:r}=this.opts.code;this.scope=new jA.ValueScope({scope:{},prefixes:HA,es5:n,lines:r}),this.logger=GA(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,MA.getRules)(),QS.call(this,UA,e,"NOT SUPPORTED"),QS.call(this,FA,e,"DEPRECATED","warn"),this._metaOpts=WA.call(this),e.formats&&qA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&VA.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),BA.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:n,schemaId:r}=this.opts,o=XS;r==="id"&&(o={...XS},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 tb.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,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,hi.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=eb.call(this,e))=="string";)e=n;if(n===void 0){let{schemaId:r}=this.opts,o=new mi.SchemaEnv({schema:{},schemaId:r});if(n=mi.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=eb.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,hi.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(XA.call(this,r,n),!n)return(0,$f.eachItem)(r,s=>Cf.call(this,s)),this;QA.call(this,n);let o={...n,type:(0,Sc.getJSONTypes)(n.type),schemaType:(0,Sc.getJSONTypes)(n.schemaType)};return(0,$f.eachItem)(r,o.type.length===0?s=>Cf.call(this,s,o):s=>o.type.forEach(i=>Cf.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]=rb(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,hi.normalizeId)(i||r);let u=hi.getSchemaRefs.call(this,e,r);return c=new mi.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):mi.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{mi.compileSchema.call(this,e)}finally{this.opts=n}}};gi.ValidationError=DA.default;gi.MissingRefError=tb.default;Je.default=gi;function QS(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 eb(t){return t=(0,hi.normalizeId)(t),this.schemas[t]||this.refs[t]}function BA(){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 qA(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function VA(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 WA(){let t={...this.opts};for(let e of LA)delete t[e];return t}var KA={log(){},warn(){},error(){}};function GA(t){if(t===!1)return KA;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 JA=/^[a-z_$][a-z0-9_$:-]*$/i;function XA(t,e){let{RULES:n}=this;if((0,$f.eachItem)(t,r=>{if(n.keywords[r])throw new Error(`Keyword ${r} is already defined`);if(!JA.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 Cf(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,Sc.getJSONTypes)(e.type),schemaType:(0,Sc.getJSONTypes)(e.schemaType)}};e.before?YA.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 YA(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 QA(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=rb(e)),t.validateSchema=this.compile(e,!0))}var eN={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function rb(t){return{anyOf:[t,eN]}}});var sb=I(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var tN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Of.default=tN});var ub=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.callRef=Gr.getValidate=void 0;var nN=pi(),ib=zt(),bt=ee(),Bo=An(),ab=hc(),bc=ue(),rN={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=ab.resolveRef.call(c,u,o,n);if(l===void 0)throw new nN.default(r.opts.uriResolver,o,n);if(l instanceof ab.SchemaEnv)return f(l);return m(l);function d(){if(s===u)return kc(t,i,s,s.$async);let p=e.scopeValue("root",{ref:u});return kc(t,(0,bt._)`${p}.validate`,u,u.$async)}function f(p){let h=cb(t,p);kc(t,h,p,p.$async)}function m(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,bt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:bt.nil,topSchemaRef:h,errSchemaPath:n},g);t.mergeEvaluated(y),t.ok(g)}}};function cb(t,e){let{gen:n}=t;return e.validate?n.scopeValue("validate",{ref:e.validate}):(0,bt._)`${n.scopeValue("wrapper",{ref:e})}.validate`}Gr.getValidate=cb;function kc(t,e,n,r){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?Bo.default.this:bt.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,bt._)`await ${(0,ib.callValidateCode)(t,e,u)}`),m(e),i||o.assign(p,!0)},h=>{o.if((0,bt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(p,!1)}),t.ok(p)}function d(){t.result((0,ib.callValidateCode)(t,e,u),()=>m(e),()=>f(e))}function f(p){let h=(0,bt._)`${p}.errors`;o.assign(Bo.default.vErrors,(0,bt._)`${Bo.default.vErrors} === null ? ${h} : ${Bo.default.vErrors}.concat(${h})`),o.assign(Bo.default.errors,(0,bt._)`${Bo.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=bc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,bt._)`${p}.evaluated.props`);s.props=bc.mergeEvaluated.props(o,y,s.props,bt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=bc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,bt._)`${p}.evaluated.items`);s.items=bc.mergeEvaluated.items(o,y,s.items,bt.Name)}}}Gr.callRef=kc;Gr.default=rN});var lb=I(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});var oN=sb(),sN=ub(),iN=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",oN.default,sN.default];If.default=iN});var db=I(Af=>{"use strict";Object.defineProperty(Af,"__esModule",{value:!0});var vc=ee(),ar=vc.operators,Ec={maximum:{okStr:"<=",ok:ar.LTE,fail:ar.GT},minimum:{okStr:">=",ok:ar.GTE,fail:ar.LT},exclusiveMaximum:{okStr:"<",ok:ar.LT,fail:ar.GTE},exclusiveMinimum:{okStr:">",ok:ar.GT,fail:ar.LTE}},aN={message:({keyword:t,schemaCode:e})=>(0,vc.str)`must be ${Ec[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,vc._)`{comparison: ${Ec[t].okStr}, limit: ${e}}`},cN={keyword:Object.keys(Ec),type:"number",schemaType:"number",$data:!0,error:aN,code(t){let{keyword:e,data:n,schemaCode:r}=t;t.fail$data((0,vc._)`${n} ${Ec[e].fail} ${r} || isNaN(${n})`)}};Af.default=cN});var pb=I(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var yi=ee(),uN={message:({schemaCode:t})=>(0,yi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,yi._)`{multipleOf: ${t}}`},lN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:uN,code(t){let{gen:e,data:n,schemaCode:r,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,yi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,yi._)`${i} !== parseInt(${i})`;t.fail$data((0,yi._)`(${r} === 0 || (${i} = ${n}/${r}, ${a}))`)}};Nf.default=lN});var mb=I(Df=>{"use strict";Object.defineProperty(Df,"__esModule",{value:!0});function fb(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}Df.default=fb;fb.code='require("ajv/dist/runtime/ucs2length").default'});var hb=I(Mf=>{"use strict";Object.defineProperty(Mf,"__esModule",{value:!0});var Jr=ee(),dN=ue(),pN=mb(),fN={message({keyword:t,schemaCode:e}){let n=t==="maxLength"?"more":"fewer";return(0,Jr.str)`must NOT have ${n} than ${e} characters`},params:({schemaCode:t})=>(0,Jr._)`{limit: ${t}}`},mN={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:fN,code(t){let{keyword:e,data:n,schemaCode:r,it:o}=t,s=e==="maxLength"?Jr.operators.GT:Jr.operators.LT,i=o.opts.unicode===!1?(0,Jr._)`${n}.length`:(0,Jr._)`${(0,dN.useFunc)(t.gen,pN.default)}(${n})`;t.fail$data((0,Jr._)`${i} ${s} ${r}`)}};Mf.default=mN});var gb=I(jf=>{"use strict";Object.defineProperty(jf,"__esModule",{value:!0});var hN=zt(),gN=ue(),qo=ee(),yN={message:({schemaCode:t})=>(0,qo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,qo._)`{pattern: ${t}}`},_N={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:yN,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,qo._)`new RegExp`:(0,gN.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,qo._)`${u}(${s}, ${a}).test(${n})`),()=>e.assign(l,!1)),t.fail$data((0,qo._)`!${l}`)}else{let c=(0,hN.usePattern)(t,o);t.fail$data((0,qo._)`!${c}.test(${n})`)}}};jf.default=_N});var yb=I(zf=>{"use strict";Object.defineProperty(zf,"__esModule",{value:!0});var _i=ee(),xN={message({keyword:t,schemaCode:e}){let n=t==="maxProperties"?"more":"fewer";return(0,_i.str)`must NOT have ${n} than ${e} properties`},params:({schemaCode:t})=>(0,_i._)`{limit: ${t}}`},SN={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:xN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxProperties"?_i.operators.GT:_i.operators.LT;t.fail$data((0,_i._)`Object.keys(${n}).length ${o} ${r}`)}};zf.default=SN});var _b=I(Lf=>{"use strict";Object.defineProperty(Lf,"__esModule",{value:!0});var xi=zt(),Si=ee(),bN=ue(),kN={message:({params:{missingProperty:t}})=>(0,Si.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Si._)`{missingProperty: ${t}}`},vN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:kN,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,bN.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(Si.nil,d);else for(let m of n)(0,xi.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,xi.checkMissingProp)(t,n,m)),(0,xi.reportMissingProp)(t,m),e.else()}function d(){e.forOf("prop",r,m=>{t.setParams({missingProperty:m}),e.if((0,xi.noPropertyInData)(e,o,m,a.ownProperties),()=>t.error())})}function f(m,p){t.setParams({missingProperty:m}),e.forOf(m,r,()=>{e.assign(p,(0,xi.propertyInData)(e,o,m,a.ownProperties)),e.if((0,Si.not)(p),()=>{t.error(),e.break()})},Si.nil)}}};Lf.default=vN});var xb=I(Hf=>{"use strict";Object.defineProperty(Hf,"__esModule",{value:!0});var bi=ee(),EN={message({keyword:t,schemaCode:e}){let n=t==="maxItems"?"more":"fewer";return(0,bi.str)`must NOT have ${n} than ${e} items`},params:({schemaCode:t})=>(0,bi._)`{limit: ${t}}`},wN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EN,code(t){let{keyword:e,data:n,schemaCode:r}=t,o=e==="maxItems"?bi.operators.GT:bi.operators.LT;t.fail$data((0,bi._)`${n}.length ${o} ${r}`)}};Hf.default=wN});var wc=I(Uf=>{"use strict";Object.defineProperty(Uf,"__esModule",{value:!0});var Sb=df();Sb.code='require("ajv/dist/runtime/equal").default';Uf.default=Sb});var bb=I(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var Ff=ai(),Xe=ee(),TN=ue(),PN=wc(),RN={message:({params:{i:t,j:e}})=>(0,Xe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Xe._)`{i: ${t}, j: ${e}}`},CN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:RN,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,Ff.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Xe._)`${i} === false`),t.ok(c);function l(){let p=e.let("i",(0,Xe._)`${n}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Xe._)`${p} > 1`,()=>(d()?f:m)(p,h))}function d(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function f(p,h){let g=e.name("item"),y=(0,Ff.checkDataTypes)(u,g,a.opts.strictNumbers,Ff.DataType.Wrong),_=e.const("indices",(0,Xe._)`{}`);e.for((0,Xe._)`;${p}--;`,()=>{e.let(g,(0,Xe._)`${n}[${p}]`),e.if(y,(0,Xe._)`continue`),u.length>1&&e.if((0,Xe._)`typeof ${g} == "string"`,(0,Xe._)`${g} += "_"`),e.if((0,Xe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Xe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Xe._)`${_}[${g}] = ${p}`)})}function m(p,h){let g=(0,TN.useFunc)(e,PN.default),y=e.name("outer");e.label(y).for((0,Xe._)`;${p}--;`,()=>e.for((0,Xe._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Xe._)`${g}(${n}[${p}], ${n}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Zf.default=CN});var kb=I(qf=>{"use strict";Object.defineProperty(qf,"__esModule",{value:!0});var Bf=ee(),$N=ue(),ON=wc(),IN={message:"must be equal to constant",params:({schemaCode:t})=>(0,Bf._)`{allowedValue: ${t}}`},AN={keyword:"const",$data:!0,error:IN,code(t){let{gen:e,data:n,$data:r,schemaCode:o,schema:s}=t;r||s&&typeof s=="object"?t.fail$data((0,Bf._)`!${(0,$N.useFunc)(e,ON.default)}(${n}, ${o})`):t.fail((0,Bf._)`${s} !== ${n}`)}};qf.default=AN});var vb=I(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var ki=ee(),NN=ue(),DN=wc(),MN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ki._)`{allowedValues: ${t}}`},jN={keyword:"enum",schemaType:"array",$data:!0,error:MN,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,NN.useFunc)(e,DN.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,ki.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,ki._)`${u()}(${n}, ${m})`,()=>e.assign(l,!0).break()))}function f(m,p){let h=o[p];return typeof h=="object"&&h!==null?(0,ki._)`${u()}(${n}, ${m}[${p}])`:(0,ki._)`${n} === ${h}`}}};Vf.default=jN});var Eb=I(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var zN=db(),LN=pb(),HN=hb(),UN=gb(),FN=yb(),ZN=_b(),BN=xb(),qN=bb(),VN=kb(),WN=vb(),KN=[zN.default,LN.default,HN.default,UN.default,FN.default,ZN.default,BN.default,qN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},VN.default,WN.default];Wf.default=KN});var Gf=I(vi=>{"use strict";Object.defineProperty(vi,"__esModule",{value:!0});vi.validateAdditionalItems=void 0;var Xr=ee(),Kf=ue(),GN={message:({params:{len:t}})=>(0,Xr.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Xr._)`{limit: ${t}}`},JN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:GN,code(t){let{parentSchema:e,it:n}=t,{items:r}=e;if(!Array.isArray(r)){(0,Kf.checkStrictMode)(n,'"additionalItems" is ignored when "items" is not an array of schemas');return}wb(t,r)}};function wb(t,e){let{gen:n,schema:r,data:o,keyword:s,it:i}=t;i.items=!0;let a=n.const("len",(0,Xr._)`${o}.length`);if(r===!1)t.setParams({len:e.length}),t.pass((0,Xr._)`${a} <= ${e.length}`);else if(typeof r=="object"&&!(0,Kf.alwaysValidSchema)(i,r)){let u=n.var("valid",(0,Xr._)`${a} <= ${e.length}`);n.if((0,Xr.not)(u),()=>c(u)),t.ok(u)}function c(u){n.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:Kf.Type.Num},u),i.allErrors||n.if((0,Xr.not)(u),()=>n.break())})}}vi.validateAdditionalItems=wb;vi.default=JN});var Jf=I(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.validateTuple=void 0;var Tb=ee(),Tc=ue(),XN=zt(),YN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:n}=t;if(Array.isArray(e))return Pb(t,"additionalItems",e);n.items=!0,!(0,Tc.alwaysValidSchema)(n,e)&&t.ok((0,XN.validateArray)(t))}};function Pb(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=Tc.mergeEvaluated.items(r,n.length,a.items));let c=r.name("valid"),u=r.const("len",(0,Tb._)`${s}.length`);n.forEach((d,f)=>{(0,Tc.alwaysValidSchema)(a,d)||(r.if((0,Tb._)`${u} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function l(d){let{opts:f,errSchemaPath:m}=a,p=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,Tc.checkStrictMode)(a,g,f.strictTuples)}}}Ei.validateTuple=Pb;Ei.default=YN});var Rb=I(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var QN=Jf(),eD={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,QN.validateTuple)(t,"items")};Xf.default=eD});var $b=I(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var Cb=ee(),tD=ue(),nD=zt(),rD=Gf(),oD={message:({params:{len:t}})=>(0,Cb.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Cb._)`{limit: ${t}}`},sD={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:oD,code(t){let{schema:e,parentSchema:n,it:r}=t,{prefixItems:o}=n;r.items=!0,!(0,tD.alwaysValidSchema)(r,e)&&(o?(0,rD.validateAdditionalItems)(t,o):t.ok((0,nD.validateArray)(t)))}};Yf.default=sD});var Ob=I(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var Ht=ee(),Pc=ue(),iD={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}}`},aD={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:iD,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)))}}};Qf.default=aD});var Nb=I(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.validateSchemaDeps=yn.validatePropertyDeps=yn.error=void 0;var em=ee(),cD=ue(),wi=zt();yn.error={message:({params:{property:t,depsCount:e,deps:n}})=>{let r=e===1?"property":"properties";return(0,em.str)`must have ${r} ${n} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:n,missingProperty:r}})=>(0,em._)`{property: ${t},
7
7
  missingProperty: ${r},
8
8
  depsCount: ${e},
9
- deps: ${n}}`};var uD={keyword:"dependencies",type:"object",schemaType:"object",error:yn.error,code(t){let[e,n]=lD(t);Ib(t,e),Ab(t,n)}};function lD({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 Ib(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,wi.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,wi.checkReportMissingProp)(t,u)}):(n.if((0,em._)`${c} && (${(0,wi.checkMissingProp)(t,a,s)})`),(0,wi.reportMissingProp)(t,s),n.else())}}yn.validatePropertyDeps=Ib;function Ab(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,cD.alwaysValidSchema)(s,e[a])||(n.if((0,wi.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=Ab;yn.default=uD});var Mb=I(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Db=ee(),dD=ue(),pD={message:"property name must be valid",params:({params:t})=>(0,Db._)`{propertyName: ${t.propertyName}}`},fD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pD,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,dD.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,Db.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tm.default=fD});var rm=I(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Rc=zt(),nn=ee(),mD=An(),Cc=ue(),hD={message:"must NOT have additional properties",params:({params:t})=>(0,nn._)`{additionalProperty: ${t.additionalProperty}}`},gD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hD,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,Cc.alwaysValidSchema)(i,n))return;let u=(0,Rc.allSchemaProperties)(r.properties),l=(0,Rc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,nn._)`${s} === ${mD.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,Cc.schemaRefOrVal)(i,r.properties,"properties");y=(0,Rc.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,Rc.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,Cc.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 x={keyword:"additionalProperties",dataProp:g,dataPropType:Cc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};nm.default=gD});var Lb=I(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var yD=di(),jb=zt(),om=ue(),zb=rm(),_D={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&&zb.default.code(new yD.KeywordCxt(s,zb.default,"additionalProperties"));let i=(0,jb.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=om.mergeEvaluated.props(e,(0,om.toHash)(i),s.props));let a=i.filter(d=>!(0,om.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,jb.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};sm.default=_D});var Zb=I(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Hb=zt(),$c=ee(),Ub=ue(),Fb=ue(),xD={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,Hb.allSchemaProperties)(n),c=a.filter(h=>(0,Ub.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 $c.Name)&&(s.props=(0,Fb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Ub.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,$c._)`${(0,Hb.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Fb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,$c._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,$c.not)(l),()=>e.break())})})}}};im.default=xD});var Bb=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var SD=ue(),bD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,SD.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"}};am.default=bD});var qb=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var kD=zt(),vD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kD.validateUnion,error:{message:"must match a schema in anyOf"}};cm.default=vD});var Vb=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var Oc=ee(),ED=ue(),wD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Oc._)`{passingSchemas: ${t.passing}}`},TD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wD,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,ED.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Oc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Oc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Oc.Name)})})}}};um.default=TD});var Wb=I(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var PD=ue(),RD={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,PD.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};lm.default=RD});var Jb=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var Ic=ee(),Gb=ue(),CD={message:({params:t})=>(0,Ic.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ic._)`{failingKeyword: ${t.ifClause}}`},$D={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CD,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Gb.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Kb(r,"then"),s=Kb(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,Ic.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,Ic._)`${l}`):t.setParams({ifClause:l})}}}};function Kb(t,e){let n=t.schema[e];return n!==void 0&&!(0,Gb.alwaysValidSchema)(t,n)}dm.default=$D});var Xb=I(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var OD=ue(),ID={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,OD.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};pm.default=ID});var Yb=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var AD=Gf(),ND=Rb(),DD=Jf(),MD=$b(),jD=Ob(),zD=Nb(),LD=Mb(),HD=rm(),UD=Lb(),FD=Zb(),ZD=Bb(),BD=qb(),qD=Vb(),VD=Wb(),WD=Jb(),KD=Xb();function GD(t=!1){let e=[ZD.default,BD.default,qD.default,VD.default,WD.default,KD.default,LD.default,HD.default,zD.default,UD.default,FD.default];return t?e.push(ND.default,MD.default):e.push(AD.default,DD.default),e.push(jD.default),e}fm.default=GD});var Qb=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Me=ee(),JD={message:({schemaCode:t})=>(0,Me.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Me._)`{format: ${t}}`},XD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:JD,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,Me._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Me._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Me._)`${h}.type || "string"`).assign(y,(0,Me._)`${h}.validate`),()=>n.assign(g,(0,Me._)`"string"`).assign(y,h)),t.fail$data((0,Me.or)(_(),x()));function _(){return c.strictSchema===!1?Me.nil:(0,Me._)`${i} && !${y}`}function x(){let b=l.$async?(0,Me._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Me._)`${y}(${r})`,v=(0,Me._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${r}))`;return(0,Me._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=x(p);h===e&&t.pass(b());function _(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(v){let O=v instanceof RegExp?(0,Me.regexpCode)(v):c.code.formats?(0,Me._)`${c.code.formats}${(0,Me.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Me._)`${R}.validate`]:["string",v,R]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Me._)`await ${y}(${r})`}return typeof g=="function"?(0,Me._)`${y}(${r})`:(0,Me._)`${y}.test(${r})`}}}};mm.default=XD});var ek=I(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var YD=Qb(),QD=[YD.default];hm.default=QD});var tk=I(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.contentVocabulary=Vo.metadataVocabulary=void 0;Vo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rk=I(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var eM=lb(),tM=Eb(),nM=Yb(),rM=ek(),nk=tk(),oM=[eM.default,tM.default,(0,nM.default)(),rM.default,nk.metadataVocabulary,nk.contentVocabulary];gm.default=oM});var sk=I(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.DiscrError=void 0;var ok;(function(t){t.Tag="tag",t.Mapping="mapping"})(ok||(Ac.DiscrError=ok={}))});var ak=I(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var Wo=ee(),ym=sk(),ik=hc(),sM=pi(),iM=ue(),aM={message:({params:{discrError:t,tagName:e}})=>t===ym.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Wo._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},cM={keyword:"discriminator",type:"object",schemaType:"object",error:aM,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,Wo._)`${n}${(0,Wo.getProperty)(a)}`);e.if((0,Wo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ym.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,Wo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:ym.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,Wo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let v=i[b];if(v?.$ref&&!(0,iM.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=ik.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof ik.SchemaEnv&&(v=v.schema),v===void 0)throw new sM.default(s.opts.uriResolver,s.baseId,R)}let O=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(v)),_(O,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function _(b,v){if(b.const)x(b.const,v);else if(b.enum)for(let O of b.enum)x(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(b,v){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=v}}}};_m.default=cM});var ck=I((U4,uM)=>{uM.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((Ee,xm)=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.MissingRefError=Ee.ValidationError=Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=Ee.Ajv=void 0;var lM=ob(),dM=rk(),pM=ak(),uk=ck(),fM=["/properties"],Nc="http://json-schema.org/draft-07/schema",Ko=class extends lM.default{_addVocabularies(){super._addVocabularies(),dM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(uk,fM):uk;this.addMetaSchema(e,Nc,!1),this.refs["http://json-schema.org/schema"]=Nc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Nc)?Nc:void 0)}};Ee.Ajv=Ko;xm.exports=Ee=Ko;xm.exports.Ajv=Ko;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Ko;var mM=di();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:function(){return mM.KeywordCxt}});var Go=ee();Object.defineProperty(Ee,"_",{enumerable:!0,get:function(){return Go._}});Object.defineProperty(Ee,"str",{enumerable:!0,get:function(){return Go.str}});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:function(){return Go.stringify}});Object.defineProperty(Ee,"nil",{enumerable:!0,get:function(){return Go.nil}});Object.defineProperty(Ee,"Name",{enumerable:!0,get:function(){return Go.Name}});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:function(){return Go.CodeGen}});var hM=fc();Object.defineProperty(Ee,"ValidationError",{enumerable:!0,get:function(){return hM.default}});var gM=pi();Object.defineProperty(Ee,"MissingRefError",{enumerable:!0,get:function(){return gM.default}})});var yk=I(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.formatNames=xn.fastFormats=xn.fullFormats=void 0;function _n(t,e){return{validate:t,compare:e}}xn.fullFormats={date:_n(fk,Em),time:_n(km(!0),wm),"date-time":_n(lk(!0),hk),"iso-time":_n(km(),mk),"iso-date-time":_n(lk(),gk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kM,"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:CM,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:vM,int32:{type:"number",validate:TM},int64:{type:"number",validate:PM},float:{type:"number",validate:pk},double:{type:"number",validate:pk},password:!0,binary:!0};xn.fastFormats={...xn.fullFormats,date:_n(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Em),time:_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wm),"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,hk),"iso-time":_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mk),"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,gk),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};xn.formatNames=Object.keys(xn.fullFormats);function yM(t){return t%4===0&&(t%100!==0||t%400===0)}var _M=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,xM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fk(t){let e=_M.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&&yM(n)?29:xM[r])}function Em(t,e){if(t&&e)return t>e?1:t<e?-1:0}var bm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function km(t){return function(n){let r=bm.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function wm(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function mk(t,e){if(!(t&&e))return;let n=bm.exec(t),r=bm.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var vm=/t|\s/i;function lk(t){let e=km(t);return function(r){let o=r.split(vm);return o.length===2&&fk(o[0])&&e(o[1])}}function hk(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function gk(t,e){if(!(t&&e))return;let[n,r]=t.split(vm),[o,s]=e.split(vm),i=Em(n,o);if(i!==void 0)return i||wm(r,s)}var SM=/\/|:/,bM=/^(?:[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 kM(t){return SM.test(t)&&bM.test(t)}var dk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vM(t){return dk.lastIndex=0,dk.test(t)}var EM=-(2**31),wM=2**31-1;function TM(t){return Number.isInteger(t)&&t<=wM&&t>=EM}function PM(t){return Number.isInteger(t)}function pk(){return!0}var RM=/[^\\]\\Z/;function CM(t){if(RM.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _k=I(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.formatLimitDefinition=void 0;var $M=Sm(),rn=ee(),cr=rn.operators,Dc={formatMaximum:{okStr:"<=",ok:cr.LTE,fail:cr.GT},formatMinimum:{okStr:">=",ok:cr.GTE,fail:cr.LT},formatExclusiveMaximum:{okStr:"<",ok:cr.LT,fail:cr.GTE},formatExclusiveMinimum:{okStr:">",ok:cr.GT,fail:cr.LTE}},OM={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}}`};Jo.formatLimitDefinition={keyword:Object.keys(Dc),type:"string",schemaType:"string",$data:!0,error:OM,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 $M.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 IM=t=>(t.addKeyword(Jo.formatLimitDefinition),t);Jo.default=IM});var kk=I((Ti,bk)=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var Xo=yk(),AM=_k(),Tm=ee(),xk=new Tm.Name("fullFormats"),NM=new Tm.Name("fastFormats"),Pm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sk(t,e,Xo.fullFormats,xk),t;let[n,r]=e.mode==="fast"?[Xo.fastFormats,NM]:[Xo.fullFormats,xk],o=e.formats||Xo.formatNames;return Sk(t,o,n,r),e.keywords&&(0,AM.default)(t),t};Pm.get=(t,e="full")=>{let r=(e==="fast"?Xo.fastFormats:Xo.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Sk(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Tm._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}bk.exports=Ti=Pm;Object.defineProperty(Ti,"__esModule",{value:!0});Ti.default=Pm});function Ri(t,e){let n=process.execPath.replace(/\\/g,"/");if(Bc(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Om.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function Le(t,e){if(Bc(e?.platform))return Ri(t,e);let r=Mk().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Zc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Bc(t){return!!t&&FM.has(t)}var Om,FM,Mn=X(()=>{"use strict";qc();Om=new Set(["node","bun","deno"]),FM=new Set(["opencode","kilo"])});import{execFileSync as Nm,execSync as Yo}from"node:child_process";import{existsSync as Qo}from"node:fs";function Am(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function BM(t){return ZM.test(Am(t))}function qM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function VM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function He(t){try{let e=Ci?`where ${t}`:`command -v ${t}`;return Yo(e,{stdio:"pipe"}),!0}catch{return!1}}function Im(t){if(Ci)try{let n=Yo(`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 Ci?Yo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Nm(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Dm(){if(He("bun"))return!0;for(let t of Lk())if(Qo(t))return!0;return!1}function zk(){for(let e of Lk())if(Qo(e))return e;if(He("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ci?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Lk(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ci){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 Hk(){let t;try{t=Yo("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 WM)if(Qo(r))return r;return e}}return null}function KM(t=Hk()){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 Yo(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Nm(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function GM(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??He,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Om.has(o)&&Qo(n)?n:r("node")?"node":null}function Vc(){let e=Dm()?zk():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Hk():null,s=n&&Qo(n)&&BM(n)&&!(r&&qM(n))&&!(r&&o&&VM(n))?n:null;return{javascript:GM(e),typescript:e||(He("tsx")?"tsx":He("ts-node")?"ts-node":null),python:Im("python3")?"python3":Im("python")?"python":Im("py")?"py":null,shell:s??(r?KM(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 Wc(){return Dm()}function JM(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 XM(){return Qo(process.execPath)?{path:process.execPath,isBun:!1}:He("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Mk(){if(Ft)return Ft;let t=XM();try{if(!Dm())return Ft=t,Ft;let e=zk(),n;try{if(process.platform==="win32"){let r=Yo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Nm(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return JM(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function Uk(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(`
9
+ deps: ${n}}`};var uD={keyword:"dependencies",type:"object",schemaType:"object",error:yn.error,code(t){let[e,n]=lD(t);Ib(t,e),Ab(t,n)}};function lD({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 Ib(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,wi.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,wi.checkReportMissingProp)(t,u)}):(n.if((0,em._)`${c} && (${(0,wi.checkMissingProp)(t,a,s)})`),(0,wi.reportMissingProp)(t,s),n.else())}}yn.validatePropertyDeps=Ib;function Ab(t,e=t.schema){let{gen:n,data:r,keyword:o,it:s}=t,i=n.name("valid");for(let a in e)(0,cD.alwaysValidSchema)(s,e[a])||(n.if((0,wi.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=Ab;yn.default=uD});var Mb=I(tm=>{"use strict";Object.defineProperty(tm,"__esModule",{value:!0});var Db=ee(),dD=ue(),pD={message:"property name must be valid",params:({params:t})=>(0,Db._)`{propertyName: ${t.propertyName}}`},fD={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pD,code(t){let{gen:e,schema:n,data:r,it:o}=t;if((0,dD.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,Db.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};tm.default=fD});var rm=I(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var Rc=zt(),nn=ee(),mD=An(),Cc=ue(),hD={message:"must NOT have additional properties",params:({params:t})=>(0,nn._)`{additionalProperty: ${t.additionalProperty}}`},gD={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:hD,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,Cc.alwaysValidSchema)(i,n))return;let u=(0,Rc.allSchemaProperties)(r.properties),l=(0,Rc.allSchemaProperties)(r.patternProperties);d(),t.ok((0,nn._)`${s} === ${mD.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,Cc.schemaRefOrVal)(i,r.properties,"properties");y=(0,Rc.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,Rc.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,Cc.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 x={keyword:"additionalProperties",dataProp:g,dataPropType:Cc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};nm.default=gD});var Lb=I(sm=>{"use strict";Object.defineProperty(sm,"__esModule",{value:!0});var yD=di(),jb=zt(),om=ue(),zb=rm(),_D={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&&zb.default.code(new yD.KeywordCxt(s,zb.default,"additionalProperties"));let i=(0,jb.allSchemaProperties)(n);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=om.mergeEvaluated.props(e,(0,om.toHash)(i),s.props));let a=i.filter(d=>!(0,om.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,jb.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&n[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};sm.default=_D});var Zb=I(im=>{"use strict";Object.defineProperty(im,"__esModule",{value:!0});var Hb=zt(),$c=ee(),Ub=ue(),Fb=ue(),xD={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,Hb.allSchemaProperties)(n),c=a.filter(h=>(0,Ub.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 $c.Name)&&(s.props=(0,Fb.evaluatedPropsToName)(e,s.props));let{props:d}=s;f();function f(){for(let h of a)u&&m(h),s.allErrors?p(h):(e.var(l,!0),p(h),e.if(l))}function m(h){for(let g in u)new RegExp(h).test(g)&&(0,Ub.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",r,g=>{e.if((0,$c._)`${(0,Hb.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:Fb.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,$c._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,$c.not)(l),()=>e.break())})})}}};im.default=xD});var Bb=I(am=>{"use strict";Object.defineProperty(am,"__esModule",{value:!0});var SD=ue(),bD={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:n,it:r}=t;if((0,SD.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"}};am.default=bD});var qb=I(cm=>{"use strict";Object.defineProperty(cm,"__esModule",{value:!0});var kD=zt(),vD={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:kD.validateUnion,error:{message:"must match a schema in anyOf"}};cm.default=vD});var Vb=I(um=>{"use strict";Object.defineProperty(um,"__esModule",{value:!0});var Oc=ee(),ED=ue(),wD={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Oc._)`{passingSchemas: ${t.passing}}`},TD={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wD,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,ED.alwaysValidSchema)(o,l)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Oc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Oc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),f&&t.mergeEvaluated(f,Oc.Name)})})}}};um.default=TD});var Wb=I(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});var PD=ue(),RD={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,PD.alwaysValidSchema)(r,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};lm.default=RD});var Jb=I(dm=>{"use strict";Object.defineProperty(dm,"__esModule",{value:!0});var Ic=ee(),Gb=ue(),CD={message:({params:t})=>(0,Ic.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Ic._)`{failingKeyword: ${t.ifClause}}`},$D={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:CD,code(t){let{gen:e,parentSchema:n,it:r}=t;n.then===void 0&&n.else===void 0&&(0,Gb.checkStrictMode)(r,'"if" without "then" and "else" is ignored');let o=Kb(r,"then"),s=Kb(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,Ic.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,Ic._)`${l}`):t.setParams({ifClause:l})}}}};function Kb(t,e){let n=t.schema[e];return n!==void 0&&!(0,Gb.alwaysValidSchema)(t,n)}dm.default=$D});var Xb=I(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});var OD=ue(),ID={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:n}){e.if===void 0&&(0,OD.checkStrictMode)(n,`"${t}" without "if" is ignored`)}};pm.default=ID});var Yb=I(fm=>{"use strict";Object.defineProperty(fm,"__esModule",{value:!0});var AD=Gf(),ND=Rb(),DD=Jf(),MD=$b(),jD=Ob(),zD=Nb(),LD=Mb(),HD=rm(),UD=Lb(),FD=Zb(),ZD=Bb(),BD=qb(),qD=Vb(),VD=Wb(),WD=Jb(),KD=Xb();function GD(t=!1){let e=[ZD.default,BD.default,qD.default,VD.default,WD.default,KD.default,LD.default,HD.default,zD.default,UD.default,FD.default];return t?e.push(ND.default,MD.default):e.push(AD.default,DD.default),e.push(jD.default),e}fm.default=GD});var Qb=I(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});var Me=ee(),JD={message:({schemaCode:t})=>(0,Me.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Me._)`{format: ${t}}`},XD={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:JD,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,Me._)`${p}[${i}]`),g=n.let("fType"),y=n.let("format");n.if((0,Me._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>n.assign(g,(0,Me._)`${h}.type || "string"`).assign(y,(0,Me._)`${h}.validate`),()=>n.assign(g,(0,Me._)`"string"`).assign(y,h)),t.fail$data((0,Me.or)(_(),x()));function _(){return c.strictSchema===!1?Me.nil:(0,Me._)`${i} && !${y}`}function x(){let b=l.$async?(0,Me._)`(${h}.async ? await ${y}(${r}) : ${y}(${r}))`:(0,Me._)`${y}(${r})`,v=(0,Me._)`(typeof ${y} == "function" ? ${b} : ${y}.test(${r}))`;return(0,Me._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function m(){let p=d.formats[s];if(!p){_();return}if(p===!0)return;let[h,g,y]=x(p);h===e&&t.pass(b());function _(){if(c.strictSchema===!1){d.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(v){let O=v instanceof RegExp?(0,Me.regexpCode)(v):c.code.formats?(0,Me._)`${c.code.formats}${(0,Me.getProperty)(s)}`:void 0,R=n.scopeValue("formats",{key:s,ref:v,code:O});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Me._)`${R}.validate`]:["string",v,R]}function b(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Me._)`await ${y}(${r})`}return typeof g=="function"?(0,Me._)`${y}(${r})`:(0,Me._)`${y}.test(${r})`}}}};mm.default=XD});var ek=I(hm=>{"use strict";Object.defineProperty(hm,"__esModule",{value:!0});var YD=Qb(),QD=[YD.default];hm.default=QD});var tk=I(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.contentVocabulary=Vo.metadataVocabulary=void 0;Vo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var rk=I(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});var eM=lb(),tM=Eb(),nM=Yb(),rM=ek(),nk=tk(),oM=[eM.default,tM.default,(0,nM.default)(),rM.default,nk.metadataVocabulary,nk.contentVocabulary];gm.default=oM});var sk=I(Ac=>{"use strict";Object.defineProperty(Ac,"__esModule",{value:!0});Ac.DiscrError=void 0;var ok;(function(t){t.Tag="tag",t.Mapping="mapping"})(ok||(Ac.DiscrError=ok={}))});var ak=I(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var Wo=ee(),ym=sk(),ik=hc(),sM=pi(),iM=ue(),aM={message:({params:{discrError:t,tagName:e}})=>t===ym.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:n}})=>(0,Wo._)`{error: ${t}, tag: ${n}, tagValue: ${e}}`},cM={keyword:"discriminator",type:"object",schemaType:"object",error:aM,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,Wo._)`${n}${(0,Wo.getProperty)(a)}`);e.if((0,Wo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:ym.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,Wo._)`${u} === ${p}`),e.assign(c,d(m[p]));e.else(),t.error(!1,{discrError:ym.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,Wo.Name),p}function f(){var m;let p={},h=y(o),g=!0;for(let b=0;b<i.length;b++){let v=i[b];if(v?.$ref&&!(0,iM.schemaHasRulesButRef)(v,s.self.RULES)){let R=v.$ref;if(v=ik.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,R),v instanceof ik.SchemaEnv&&(v=v.schema),v===void 0)throw new sM.default(s.opts.uriResolver,s.baseId,R)}let O=(m=v?.properties)===null||m===void 0?void 0:m[a];if(typeof O!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(v)),_(O,b)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:b}){return Array.isArray(b)&&b.includes(a)}function _(b,v){if(b.const)x(b.const,v);else if(b.enum)for(let O of b.enum)x(O,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(b,v){if(typeof b!="string"||b in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[b]=v}}}};_m.default=cM});var ck=I((F4,uM)=>{uM.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((Ee,xm)=>{"use strict";Object.defineProperty(Ee,"__esModule",{value:!0});Ee.MissingRefError=Ee.ValidationError=Ee.CodeGen=Ee.Name=Ee.nil=Ee.stringify=Ee.str=Ee._=Ee.KeywordCxt=Ee.Ajv=void 0;var lM=ob(),dM=rk(),pM=ak(),uk=ck(),fM=["/properties"],Nc="http://json-schema.org/draft-07/schema",Ko=class extends lM.default{_addVocabularies(){super._addVocabularies(),dM.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(pM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(uk,fM):uk;this.addMetaSchema(e,Nc,!1),this.refs["http://json-schema.org/schema"]=Nc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Nc)?Nc:void 0)}};Ee.Ajv=Ko;xm.exports=Ee=Ko;xm.exports.Ajv=Ko;Object.defineProperty(Ee,"__esModule",{value:!0});Ee.default=Ko;var mM=di();Object.defineProperty(Ee,"KeywordCxt",{enumerable:!0,get:function(){return mM.KeywordCxt}});var Go=ee();Object.defineProperty(Ee,"_",{enumerable:!0,get:function(){return Go._}});Object.defineProperty(Ee,"str",{enumerable:!0,get:function(){return Go.str}});Object.defineProperty(Ee,"stringify",{enumerable:!0,get:function(){return Go.stringify}});Object.defineProperty(Ee,"nil",{enumerable:!0,get:function(){return Go.nil}});Object.defineProperty(Ee,"Name",{enumerable:!0,get:function(){return Go.Name}});Object.defineProperty(Ee,"CodeGen",{enumerable:!0,get:function(){return Go.CodeGen}});var hM=fc();Object.defineProperty(Ee,"ValidationError",{enumerable:!0,get:function(){return hM.default}});var gM=pi();Object.defineProperty(Ee,"MissingRefError",{enumerable:!0,get:function(){return gM.default}})});var yk=I(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.formatNames=xn.fastFormats=xn.fullFormats=void 0;function _n(t,e){return{validate:t,compare:e}}xn.fullFormats={date:_n(fk,Em),time:_n(km(!0),wm),"date-time":_n(lk(!0),hk),"iso-time":_n(km(),mk),"iso-date-time":_n(lk(),gk),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:kM,"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:CM,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:vM,int32:{type:"number",validate:TM},int64:{type:"number",validate:PM},float:{type:"number",validate:pk},double:{type:"number",validate:pk},password:!0,binary:!0};xn.fastFormats={...xn.fullFormats,date:_n(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Em),time:_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,wm),"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,hk),"iso-time":_n(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,mk),"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,gk),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};xn.formatNames=Object.keys(xn.fullFormats);function yM(t){return t%4===0&&(t%100!==0||t%400===0)}var _M=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,xM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function fk(t){let e=_M.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&&yM(n)?29:xM[r])}function Em(t,e){if(t&&e)return t>e?1:t<e?-1:0}var bm=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function km(t){return function(n){let r=bm.exec(n);if(!r)return!1;let o=+r[1],s=+r[2],i=+r[3],a=r[4],c=r[5]==="-"?-1:1,u=+(r[6]||0),l=+(r[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,f=o-u*c-(d<0?1:0);return(f===23||f===-1)&&(d===59||d===-1)&&i<61}}function wm(t,e){if(!(t&&e))return;let n=new Date("2020-01-01T"+t).valueOf(),r=new Date("2020-01-01T"+e).valueOf();if(n&&r)return n-r}function mk(t,e){if(!(t&&e))return;let n=bm.exec(t),r=bm.exec(e);if(n&&r)return t=n[1]+n[2]+n[3],e=r[1]+r[2]+r[3],t>e?1:t<e?-1:0}var vm=/t|\s/i;function lk(t){let e=km(t);return function(r){let o=r.split(vm);return o.length===2&&fk(o[0])&&e(o[1])}}function hk(t,e){if(!(t&&e))return;let n=new Date(t).valueOf(),r=new Date(e).valueOf();if(n&&r)return n-r}function gk(t,e){if(!(t&&e))return;let[n,r]=t.split(vm),[o,s]=e.split(vm),i=Em(n,o);if(i!==void 0)return i||wm(r,s)}var SM=/\/|:/,bM=/^(?:[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 kM(t){return SM.test(t)&&bM.test(t)}var dk=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vM(t){return dk.lastIndex=0,dk.test(t)}var EM=-(2**31),wM=2**31-1;function TM(t){return Number.isInteger(t)&&t<=wM&&t>=EM}function PM(t){return Number.isInteger(t)}function pk(){return!0}var RM=/[^\\]\\Z/;function CM(t){if(RM.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var _k=I(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.formatLimitDefinition=void 0;var $M=Sm(),rn=ee(),cr=rn.operators,Dc={formatMaximum:{okStr:"<=",ok:cr.LTE,fail:cr.GT},formatMinimum:{okStr:">=",ok:cr.GTE,fail:cr.LT},formatExclusiveMaximum:{okStr:"<",ok:cr.LT,fail:cr.GTE},formatExclusiveMinimum:{okStr:">",ok:cr.GT,fail:cr.LTE}},OM={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}}`};Jo.formatLimitDefinition={keyword:Object.keys(Dc),type:"string",schemaType:"string",$data:!0,error:OM,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 $M.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 IM=t=>(t.addKeyword(Jo.formatLimitDefinition),t);Jo.default=IM});var kk=I((Ti,bk)=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var Xo=yk(),AM=_k(),Tm=ee(),xk=new Tm.Name("fullFormats"),NM=new Tm.Name("fastFormats"),Pm=(t,e={keywords:!0})=>{if(Array.isArray(e))return Sk(t,e,Xo.fullFormats,xk),t;let[n,r]=e.mode==="fast"?[Xo.fastFormats,NM]:[Xo.fullFormats,xk],o=e.formats||Xo.formatNames;return Sk(t,o,n,r),e.keywords&&(0,AM.default)(t),t};Pm.get=(t,e="full")=>{let r=(e==="fast"?Xo.fastFormats:Xo.fullFormats)[t];if(!r)throw new Error(`Unknown format "${t}"`);return r};function Sk(t,e,n,r){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Tm._)`require("ajv-formats/dist/formats").${r}`);for(let i of e)t.addFormat(i,n[i])}bk.exports=Ti=Pm;Object.defineProperty(Ti,"__esModule",{value:!0});Ti.default=Pm});function Ri(t,e){let n=process.execPath.replace(/\\/g,"/");if(Bc(e?.platform)){let o=n.split("/").pop().replace(/\.exe$/i,"");Om.has(o)||(n=e?.jsRuntime?.replace(/\\/g,"/")??"node")}let r=t.replace(/\\/g,"/");return`"${n}" "${r}"`}function Le(t,e){if(Bc(e?.platform))return Ri(t,e);let r=Mk().path.replace(/\\/g,"/"),o=t.replace(/\\/g,"/");return`"${r}" "${o}"`}function Zc(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}function Bc(t){return!!t&&FM.has(t)}var Om,FM,Mn=X(()=>{"use strict";qc();Om=new Set(["node","bun","deno"]),FM=new Set(["opencode","kilo"])});import{execFileSync as Nm,execSync as Yo}from"node:child_process";import{existsSync as Qo}from"node:fs";function Am(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function BM(t){return ZM.test(Am(t))}function qM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\bash\.exe$/.test(e)||/\\microsoft\\windowsapps\\bash\.exe$/.test(e)}function VM(t){let e=t.toLowerCase().replace(/\//g,"\\");return/\\windows\\(?:system32|sysnative)\\cmd\.exe$/.test(e)}function He(t){try{let e=Ci?`where ${t}`:`command -v ${t}`;return Yo(e,{stdio:"pipe"}),!0}catch{return!1}}function Im(t){if(Ci)try{let n=Yo(`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 Ci?Yo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):Nm(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function Dm(){if(He("bun"))return!0;for(let t of Lk())if(Qo(t))return!0;return!1}function zk(){for(let e of Lk())if(Qo(e))return e;if(He("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Ci?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Lk(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Ci){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 Hk(){let t;try{t=Yo("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 WM)if(Qo(r))return r;return e}}return null}function KM(t=Hk()){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 Yo(n,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return Nm(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function GM(t,e={}){if(t)return t;let n=e.execPath??process.execPath,r=e.commandExists??He,o=n.split(/[\\/]/).pop().replace(/\.exe$/i,"");return Om.has(o)&&Qo(n)?n:r("node")?"node":null}function Vc(){let e=Dm()?zk():null,n=process.env.SHELL,r=process.platform==="win32",o=r?Hk():null,s=n&&Qo(n)&&BM(n)&&!(r&&qM(n))&&!(r&&o&&VM(n))?n:null;return{javascript:GM(e),typescript:e||(He("tsx")?"tsx":He("ts-node")?"ts-node":null),python:Im("python3")?"python3":Im("python")?"python":Im("py")?"py":null,shell:s??(r?KM(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 Wc(){return Dm()}function JM(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 XM(){return Qo(process.execPath)?{path:process.execPath,isBun:!1}:He("node")?{path:"node",isBun:!1}:{path:process.execPath,isBun:!1}}function Mk(){if(Ft)return Ft;let t=XM();try{if(!Dm())return Ft=t,Ft;let e=zk(),n;try{if(process.platform==="win32"){let r=Yo(`"${e}" --version`,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}else{let r=Nm(e,["--version"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3});n=String(r)}}catch{return Ft=t,Ft}return JM(n)?(Ft={path:e,isBun:!0},Ft):(Ft=t,Ft)}catch{return Ft=t,Ft}}function Uk(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(`
10
10
  `)}function Fk(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 Zk(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 jk.test(Am(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 jk.test(Am(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 ZM,jk,Ci,WM,Ft,qc=X(()=>{"use strict";Mn();ZM=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,jk=/^bun(\.exe)?$/i;Ci=process.platform==="win32";WM=["C:\\Program Files\\Git\\usr\\bin\\bash.exe","C:\\Program Files (x86)\\Git\\usr\\bin\\bash.exe"];Ft=null});import{createRequire as pj}from"node:module";import{existsSync as fj,unlinkSync as Jk,renameSync as mj}from"node:fs";import{tmpdir as hj}from"node:os";import{join as gj}from"node:path";function yj(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 _j(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 Ye(){if(!es){let t=pj(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;es=function(r,o){let s=new e(r,{readonly:o?.readonly,create:!0}),i=new Lm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(_j()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&yj(e)?es=function(r,o){let s=new e(r,{readOnly:o?.readonly??!1}),i=new Hm(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}:es=t("better-sqlite3")}else es=t("better-sqlite3")}return es}function Ii(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Ai(t){if(!fj(t))for(let e of["-wal","-shm"])try{Jk(t+e)}catch{}}function Um(t){for(let e of["","-wal","-shm"])try{Jk(t+e)}catch{}}function Ni(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Xk(t="context-mode"){return gj(hj(),`${t}-${process.pid}.db`)}function Yr(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 Fm(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 xj(t){let e=Date.now();for(let n of["","-wal","-shm"])try{mj(t+n,`${t}${n}.corrupt-${e}`)}catch{}}var Lm,Hm,es,Oi,zm,Gc,ts=X(()=>{"use strict";Lm=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()}},Hm=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()}},es=null;Oi=Symbol.for("__context_mode_live_dbs_v3__"),zm=(()=>{let t=globalThis;return t[Oi]||(t[Oi]=new Set,process.on("exit",()=>{for(let e of t[Oi])Ni(e);t[Oi].clear()})),t[Oi]})(),Gc=class{#e;#t;constructor(e){let n=Ye();this.#e=e,Ai(e);let r;try{r=new n(e,{timeout:3e4}),Ii(r)}catch(o){let s=o instanceof Error?o.message:String(o);if(Fm(s)){xj(e),Ai(e);try{r=new n(e,{timeout:3e4}),Ii(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,zm.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){zm.delete(this.#t),Ni(this.#t)}withRetry(e){return Yr(e)}cleanup(){zm.delete(this.#t),Ni(this.#t),Um(this.#e)}}});var pv,fv=X(()=>{"use strict";pv={"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 Mi}from"node:crypto";import{execFileSync as Vj}from"node:child_process";import{accessSync as Wj,constants as Kj,existsSync as eu,mkdirSync as Gj,realpathSync as Jj,renameSync as Jm}from"node:fs";import{homedir as xv}from"node:os";import{dirname as Xj,isAbsolute as Sv,join as lr,resolve as rs}from"node:path";function Xm(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):lr(Yj(t.configDir,t.configDirEnv,e),"context-mode","sessions")}function Yj(t,e,n){let r=e?n[e]:void 0;return r&&r.trim()!==""?hv(r.trim()):hv(t,xv())}function hv(t,e){return t.startsWith("~")?rs(xv(),t.replace(/^~[/\\]?/,"")):Sv(t)?rs(t):e?rs(e,t):rs(t)}function Qj(t,e,n){return new dr(t,e,Sn,void 0,[`Invalid ${Sn} for context-mode ${t} directory: ${n}`,wv()].join(`
11
11
  `))}function kv(t){let e=process.env[Sn];if(e===void 0)return{kind:"unset"};let n=e.trim();if(!n)return{kind:"ignored-empty",ignoredEnvVar:Sn,ignoredReason:"empty"};if(!Sv(n))throw Qj(t,n,`${Sn} must be an absolute path.`);return{kind:"override",root:rs(n)}}function ez(t){return t.kind==="ignored-empty"?{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason}:{}}function vv(t,e){let n=kv(t);return n.kind!=="override"?null:{kind:t,path:lr(n.root,e),envVar:Sn,source:"override"}}function tz(t,e,n){return{kind:t,path:rs(e()),envVar:null,source:"default",...n}}function ji(t){let e=kv("session");return e.kind==="override"?{kind:"session",path:lr(e.root,bv),envVar:Sn,source:"override"}:tz("session",t,ez(e))}function Ym(t){let e=vv("content",mv);if(e)return e;let n=ji(t);return{kind:"content",path:lr(Xj(n.path),mv),envVar:n.envVar,source:n.source,ignoredEnvVar:n.ignoredEnvVar,ignoredReason:n.ignoredReason}}function Qm(t){let e=vv("stats",bv);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 Ev(t){return t.message}function tu(t){return t.source==="override"&&t.envVar?`via ${t.envVar}`:t.ignoredEnvVar&&t.ignoredReason==="empty"?`default; ignored empty ${t.ignoredEnvVar}`:"default"}function nu(t){let e=[t.kind,t.path,t.source,t.envVar??"",t.ignoredEnvVar??"",t.ignoredReason??""].join("\0"),n=Gm.get(e);if(n instanceof dr)throw n;if(n===t.path)return n;try{return Gj(t.path,{recursive:!0}),Wj(t.path,Kj.W_OK),Gm.set(e,t.path),t.path}catch(r){let o=new dr(t.kind,oz(r)??t.path,Sn,r,void 0,{ignoredEnvVar:t.ignoredEnvVar,ignoredReason:t.ignoredReason});throw Gm.set(e,o),o}}function nz(t,e,n={}){return[`context-mode ${t} directory is not writable: ${e}`,rz(n),wv()].filter(Boolean).join(`
12
12
  `)}function rz(t){return t.ignoredEnvVar&&t.ignoredReason==="empty"?`Ignored empty ${t.ignoredEnvVar}; using adapter default.`:null}function wv(){return`Set ${Sn} to a writable absolute path.`}function oz(t){if(!t||typeof t!="object")return null;let e=t.path;return typeof e=="string"&&e.length>0?e:null}function Qr(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function gv(t){let e=t;try{e=Jj.native(t)}catch{}let n=Qr(e);return process.platform==="win32"||process.platform==="darwin"?n.toLowerCase():n}function Tv(t,e){return Vj("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function sz(t){let e=Tv(t,["rev-parse","--show-toplevel"]);return e.length>0?Qr(e):null}function iz(t){let e=Tv(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(n=>n.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?Qr(e):null}function ru(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Di&&Di.projectDir===t&&Di.envSuffix===e)return Di.suffix;let n="";if(e!==void 0)n=e?`__${e}`:"";else try{let r=sz(t),o=iz(t);if(r&&o){let s=gv(r),i=gv(o);s!==i&&(n=`__${Mi("sha256").update(s).digest("hex").slice(0,8)}`)}}catch{}return Di={projectDir:t,envSuffix:e,suffix:n},n}function jn(t){return Mi("sha256").update(Qr(t)).digest("hex").slice(0,16)}function Qe(t){let e=Qr(t),n=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Mi("sha256").update(n).digest("hex").slice(0,16)}function Pv(t){let{projectDir:e,contentDir:n}=t,r=Qe(e),o=lr(n,`${r}.db`);if(eu(o))return o;let s=jn(e);if(s===r)return o;let i=lr(n,`${s}.db`);if(eu(i))try{Jm(i,o);for(let a of["-wal","-shm"])try{Jm(i+a,o+a)}catch{}}catch{}return o}function zi(t){return az({...t,ext:".db"})}function az(t){let{projectDir:e,sessionsDir:n,ext:r}=t,o=t.suffix??ru(e),s=Qe(e),i=lr(n,`${s}${o}${r}`);if(eu(i))return i;let a=jn(e);if(a===s)return i;let c=lr(n,`${a}${o}${r}`);if(eu(c))try{Jm(c,i)}catch{}return i}function Qc(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}function Rv(t){let e=t.pragma("table_xinfo(session_events)"),n=new Set(e.map(o=>o.name)),r=!1;for(let[o,s]of cz)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 Cv(t,e){let n=null;try{n=new e(t),Rv(n)}catch{}finally{try{n?.close()}catch{}}}var Sn,bv,mv,dr,Gm,Di,yv,_v,j,cz,on,bn=X(()=>{"use strict";ts();Sn="CONTEXT_MODE_DIR",bv="sessions",mv="content",dr=class extends Error{kind;path;overrideEnvVar;ignoredEnvVar;ignoredReason;constructor(e,n,r=Sn,o,s,i={}){super(s??nz(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}},Gm=new Map;yv=1e3,_v=5;j={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",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"},cz=[["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 Gc{constructor(e){super(e?.dbPath??Xk("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(`
@@ -150,15 +150,15 @@ var ZT=Object.create;var el=Object.defineProperty;var BT=Object.getOwnPropertyDe
150
150
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
151
151
  FROM session_events WHERE session_id = ?`)}insertEvent(e,n,r="PostToolUse",o,s){let i=Mi("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=Qc(s?.bytesAvoided),f=Qc(s?.bytesReturned),m=this.db.transaction(()=>{if(this.stmt(j.checkDuplicate).get(e,_v,n.type,i))return;this.stmt(j.getEventCount).get(e).cnt>=yv&&this.stmt(j.evictLowestPriority).run(e),this.stmt(j.insertEvent).run(e,n.type,n.category,n.priority,n.data,a,c,l,d,f,r,i),this.stmt(j.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=Mi("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===""?"":Qr(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],_=Qc(y?.bytesAvoided),x=Qc(y?.bytesReturned);return{event:c,dataHash:l,projectDir:m,attributionSource:p,attributionConfidence:g,bytesAvoided:_,bytesReturned:x}}),a=this.db.transaction(()=>{let c=this.stmt(j.getEventCount).get(e).cnt;for(let u of i)this.stmt(j.checkDuplicate).get(e,_v,u.event.type,u.dataHash)||(c>=yv?this.stmt(j.evictLowestPriority).run(e):c++,this.stmt(j.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(j.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(j.getEventsByTypeAndPriority).all(e,o,s,r):o?this.stmt(j.getEventsByType).all(e,o,r):s!==void 0?this.stmt(j.getEventsByPriority).all(e,s,r):this.stmt(j.getEvents).all(e,r)}getEventCount(e){return this.stmt(j.getEventCount).get(e).cnt}getEventBytesSummary(e){let n=this.stmt(j.getEventBytesSummary).get(e);return{bytesAvoided:Number(n?.bytes_avoided??0),bytesReturned:Number(n?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(j.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(j.searchEvents).all(r,s,s,i,i,n)}catch{return[]}}getSessionIdsForProject(e){try{let n=Qr(e);return this.db.prepare(`SELECT DISTINCT session_id
152
152
  FROM session_events
153
- WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(j.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(j.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(j.getSessionRollup).get(e),r=this.stmt(j.getMaxFileEdits).get(e),o=this.stmt(j.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(j.incrementCompactCount).run(e)}upsertResume(e,n,r){this.stmt(j.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(j.getResume).get(e)??null}markResumeConsumed(e){this.stmt(j.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(j.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(j.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(j.getToolCallTotals).get(e),r=this.stmt(j.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(j.deleteEvents).run(e),this.stmt(j.deleteResume).run(e),this.stmt(j.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(j.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 os,resolve as $v}from"node:path";import{accessSync as uz,copyFileSync as lz,constants as dz,mkdirSync as pz}from"node:fs";import{homedir as eh}from"node:os";function it(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?$v(eh(),e.replace(/^~[/\\]?/,"")):$v(e)}var ge,et=X(()=>{"use strict";bn();ge=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=it(),n=e?os(e,"context-mode","sessions"):os(eh(),...this.sessionDirSegments,"context-mode","sessions");return pz(n,{recursive:!0}),n}getConfigDir(e){return os(eh(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=it(),r=n?os(n,"context-mode","memory"):os(this.getConfigDir(),"memory");return e?os(r,Qe(e)):r}backupSettings(){let e=this.getSettingsPath();try{uz(e,dz.R_OK);let n=e+".bak";return lz(e,n),n}catch{return null}}}});var ss,th=X(()=>{"use strict";et();ss=class extends ge{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 nh}from"node:fs";import{join as rh}from"node:path";async function fz(){if(is)return is;if(as)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 is=r,is}catch(r){e=r}return as=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return as=t instanceof Error?t.message:String(t),null}}function mz(t){let e=[];return nh(rh(t,"start.mjs"))||e.push("start.mjs"),!nh(rh(t,"server.bundle.mjs"))&&!nh(rh(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Ov(t){if(is){let e=is.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(as){let e=mz(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${as}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${as}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var is,as,Iv=X(()=>{"use strict";is=null,as=null;fz()});function Li(t,e){let n=eo[e],r=sh(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function sh(t,e){if(e){let n=eo[t];return Le(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function ih(t){let e=Zc(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 Dv(t){let e=Object.values(eo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Zt,hz,oh,Av,gz,_V,eo,Nv,xV,Mv=X(()=>{"use strict";Mn();Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},hz="mcp__",oh=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",hz],Av=oh.join("|"),gz=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],_V=gz.join("|"),eo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Nv=[Zt.PRE_TOOL_USE,Zt.SESSION_START],xV=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT,Zt.USER_PROMPT_SUBMIT,Zt.STOP]});var ch={};De(ch,{ClaudeCodeAdapter:()=>ah});import{readFileSync as ou,writeFileSync as jv,existsSync as zv,readdirSync as yz,chmodSync as _z,accessSync as xz,mkdirSync as Sz,constants as bz}from"node:fs";import{resolve as su,join as pr}from"node:path";import{homedir as Lv}from"node:os";var ah,uh=X(()=>{"use strict";th();et();to();Iv();Mn();Mv();ah=class extends ss{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?pr(e,"context-mode","sessions"):pr(this.getConfigDir(),"context-mode","sessions");return Sz(n,{recursive:!0}),n}getSettingsPath(){return pr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=Le(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...oh].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=ou(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){jv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
153
+ WHERE RTRIM(REPLACE(project_dir, '\\', '/'), '/') = ?`).all(n).map(o=>o.session_id)}catch{return[]}}ensureSession(e,n){this.stmt(j.ensureSession).run(e,n)}getSessionStats(e){return this.stmt(j.getSessionStats).get(e)??null}getSessionRollup(e){let n=this.stmt(j.getSessionRollup).get(e),r=this.stmt(j.getMaxFileEdits).get(e),o=this.stmt(j.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(j.incrementCompactCount).run(e)}upsertResume(e,n,r){this.stmt(j.upsertResume).run(e,n,r??0)}getResume(e){return this.stmt(j.getResume).get(e)??null}markResumeConsumed(e){this.stmt(j.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let n=this.stmt(j.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(j.incrementToolCall).run(e,n,o)}catch{}}getToolCallStats(e){try{let n=this.stmt(j.getToolCallTotals).get(e),r=this.stmt(j.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(j.deleteEvents).run(e),this.stmt(j.deleteResume).run(e),this.stmt(j.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let n=`-${e}`,r=this.stmt(j.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 os,resolve as $v}from"node:path";import{accessSync as uz,copyFileSync as lz,constants as dz,mkdirSync as pz}from"node:fs";import{homedir as eh}from"node:os";function it(t=process.env){let e=t.CONTEXT_MODE_DATA_DIR;return!e||e.trim()===""?null:e.startsWith("~")?$v(eh(),e.replace(/^~[/\\]?/,"")):$v(e)}var ge,et=X(()=>{"use strict";bn();ge=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=it(),n=e?os(e,"context-mode","sessions"):os(eh(),...this.sessionDirSegments,"context-mode","sessions");return pz(n,{recursive:!0}),n}getConfigDir(e){return os(eh(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(e){let n=it(),r=n?os(n,"context-mode","memory"):os(this.getConfigDir(),"memory");return e?os(r,Qe(e)):r}backupSettings(){let e=this.getSettingsPath();try{uz(e,dz.R_OK);let n=e+".bak";return lz(e,n),n}catch{return null}}}});var ss,th=X(()=>{"use strict";et();ss=class extends ge{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 nh}from"node:fs";import{join as rh}from"node:path";async function fz(){if(is)return is;if(as)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 is=r,is}catch(r){e=r}return as=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return as=t instanceof Error?t.message:String(t),null}}function mz(t){let e=[];return nh(rh(t,"start.mjs"))||e.push("start.mjs"),!nh(rh(t,"server.bundle.mjs"))&&!nh(rh(t,"build","server.js"))&&e.push("server.bundle.mjs (or build/server.js)"),e}function Ov(t){if(is){let e=is.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}if(as){let e=mz(t);return e.length>0?{status:"FAIL",detail:`partial install \u2014 critical launch files missing: ${e.join(", ")} (integrity helper also missing: ${as}); the MCP server cannot start. Reinstall: npm install -g context-mode@latest`}:{status:"FAIL",detail:`integrity helper unavailable: ${as}`}}return{status:"FAIL",detail:"integrity helper not yet loaded"}}var is,as,Iv=X(()=>{"use strict";is=null,as=null;fz()});function Li(t,e){let n=eo[e],r=sh(e);return t.hooks?.some(o=>o.command?.includes(n)||o.command?.includes(r))??!1}function sh(t,e){if(e){let n=eo[t];return Le(`${e}/hooks/${n}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function ih(t){let e=Zc(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 Dv(t){let e=Object.values(eo);return t.hooks?.some(n=>n.command!=null&&(e.some(r=>n.command.includes(r))||n.command.includes("context-mode hook")))??!1}var Zt,hz,oh,Av,gz,xV,eo,Nv,SV,Mv=X(()=>{"use strict";Mn();Zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit",STOP:"Stop"},hz="mcp__",oh=["Bash","WebFetch","Read","Grep","Agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute",hz],Av=oh.join("|"),gz=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],xV=gz.join("|"),eo={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs",Stop:"stop.mjs"},Nv=[Zt.PRE_TOOL_USE,Zt.SESSION_START],SV=[Zt.POST_TOOL_USE,Zt.PRE_COMPACT,Zt.USER_PROMPT_SUBMIT,Zt.STOP]});var ch={};De(ch,{ClaudeCodeAdapter:()=>ah});import{readFileSync as ou,writeFileSync as jv,existsSync as zv,readdirSync as yz,chmodSync as _z,accessSync as xz,mkdirSync as Sz,constants as bz}from"node:fs";import{resolve as su,join as pr}from"node:path";import{homedir as Lv}from"node:os";var ah,uh=X(()=>{"use strict";th();et();to();Iv();Mn();Mv();ah=class extends ss{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?pr(e,"context-mode","sessions"):pr(this.getConfigDir(),"context-mode","sessions");return Sz(n,{recursive:!0}),n}getSettingsPath(){return pr(this.getConfigDir(),"settings.json")}generateHookConfig(e){let n=Le(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...oh].map(o=>({matcher:o,hooks:[{type:"command",command:n}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/sessionstart.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Le(`${e}/hooks/stop.mjs`)}]}]}}readSettings(){try{let e=ou(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){jv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
154
154
  `,"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(eo).map(([o,s])=>{let i=pr(e,"hooks",s);return{name:`Hook script: ${o} (${s})`,check:()=>zv(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),r={name:"Plugin cache integrity",check:()=>Ov(e)};return[...n,r]}readPluginHooks(e){let n=[pr(e,"hooks","hooks.json"),pr(e,".claude-plugin","hooks","hooks.json")];for(let r of n)try{let o=ou(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=>Li(i,r)))return!0;let s=n?.[r];return!!(s&&s.length>0&&s.some(i=>Li(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=pr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(ou(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(),su(Lv(),".claude"),su(Lv(),".config","claude")]));for(let n of e){let r=su(n,"plugins","cache","context-mode","context-mode");try{let s=yz(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(!Dv(p))return!0;let h=p.hooks??[];return h.every(y=>!y.command||!ih(y.command))?!0:h.every(y=>{let _=y.command?ih(y.command):null;return _?zv(_):!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&&Nv.every(l=>this.checkHookType(void 0,a,l))){let l=Object.values(eo),d=f=>f!=null&&(l.some(m=>f.includes(m))||f.includes("context-mode hook"));for(let f of Object.keys(r)){let m=r[f];if(!Array.isArray(m))continue;let p=0;for(let g of m){let y=g,_=y.hooks??[],x=_.length;y.hooks=_.filter(b=>!d(b.command)),p+=x-y.hooks.length}let h=m.filter(g=>{let y=g.hooks;return Array.isArray(y)&&y.length>0});(p>0||h.length!==m.length)&&(r[f]=h,p>0&&o.push(`Removed ${p} duplicate ${f} hook(s) \u2014 covered by plugin hooks.json`))}return n.hooks=r,this.writeSettings(n),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let c=[Zt.PRE_TOOL_USE,Zt.SESSION_START];for(let u of c){let l=sh(u,e);if(u===Zt.PRE_TOOL_USE){let d={matcher:Av,hooks:[{type:"command",command:l}]},f=r.PreToolUse;if(f&&Array.isArray(f)){let m=f.findIndex(p=>Li(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=>Li(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(eo)){let o=su(e,"hooks",r);try{xz(o,bz.R_OK),_z(o,493),n.push(o)}catch{}}return n}updatePluginRegistry(e,n){try{let r=pr(this.getConfigDir(),"plugins","installed_plugins.json"),o=JSON.parse(ou(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();jv(r,JSON.stringify(o,null,2)+`
155
- `,"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 no(t,e){let n=iu[t];return e&&n?Le(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var we,Hv,iu,OV,IV,Uv=X(()=>{"use strict";Mn();we={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Hv="mcp__(?!.*context-mode)",iu={[we.BEFORE_AGENT]:"beforeagent.mjs",[we.BEFORE_TOOL]:"beforetool.mjs",[we.AFTER_TOOL]:"aftertool.mjs",[we.PRE_COMPRESS]:"precompress.mjs",[we.SESSION_START]:"sessionstart.mjs"},OV=[we.BEFORE_TOOL,we.SESSION_START],IV=[we.AFTER_TOOL,we.PRE_COMPRESS]});var Bv={};De(Bv,{GeminiCLIAdapter:()=>dh});import{readFileSync as lh,writeFileSync as Fv,mkdirSync as kz,accessSync as vz,chmodSync as Ez,existsSync as wz,constants as Tz}from"node:fs";import{resolve as Hi,join as Zv}from"node:path";import{homedir as au}from"node:os";var dh,qv=X(()=>{"use strict";et();Uv();dh=class extends ge{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(au(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[we.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:no(we.BEFORE_AGENT,e)}]}],[we.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${Hv}`,hooks:[{type:"command",command:no(we.BEFORE_TOOL,e)}]}],[we.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:no(we.AFTER_TOOL,e)}]}],[we.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:no(we.PRE_COMPRESS,e)}]}],[we.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:no(we.SESSION_START,e)}]}]}}readSettings(){try{let e=lh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Hi(au(),".gemini");kz(n,{recursive:!0}),Fv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
155
+ `,"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 no(t,e){let n=iu[t];return e&&n?Le(`${e}/hooks/gemini-cli/${n}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var we,Hv,iu,IV,AV,Uv=X(()=>{"use strict";Mn();we={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Hv="mcp__(?!.*context-mode)",iu={[we.BEFORE_AGENT]:"beforeagent.mjs",[we.BEFORE_TOOL]:"beforetool.mjs",[we.AFTER_TOOL]:"aftertool.mjs",[we.PRE_COMPRESS]:"precompress.mjs",[we.SESSION_START]:"sessionstart.mjs"},IV=[we.BEFORE_TOOL,we.SESSION_START],AV=[we.AFTER_TOOL,we.PRE_COMPRESS]});var Bv={};De(Bv,{GeminiCLIAdapter:()=>dh});import{readFileSync as lh,writeFileSync as Fv,mkdirSync as kz,accessSync as vz,chmodSync as Ez,existsSync as wz,constants as Tz}from"node:fs";import{resolve as Hi,join as Zv}from"node:path";import{homedir as au}from"node:os";var dh,qv=X(()=>{"use strict";et();Uv();dh=class extends ge{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(au(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[we.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:no(we.BEFORE_AGENT,e)}]}],[we.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${Hv}`,hooks:[{type:"command",command:no(we.BEFORE_TOOL,e)}]}],[we.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:no(we.AFTER_TOOL,e)}]}],[we.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:no(we.PRE_COMPRESS,e)}]}],[we.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:no(we.SESSION_START,e)}]}]}}readSettings(){try{let e=lh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=Hi(au(),".gemini");kz(n,{recursive:!0}),Fv(this.getSettingsPath(),JSON.stringify(e,null,2)+`
156
156
  `,"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?.[we.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?.[we.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(iu).map(([n,r])=>{let o=Zv(e,"hooks","gemini-cli",r);return{name:`Hook script: ${n} (${r})`,check:()=>wz(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(au(),".gemini","extensions","context-mode","package.json"),n=JSON.parse(lh(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:we.BEFORE_AGENT},{name:we.BEFORE_TOOL},{name:we.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:no(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=Zv(e,"hooks","gemini-cli");for(let o of Object.values(iu)){let s=Hi(r,o);try{vz(s,Tz.R_OK),Ez(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){try{let r=Hi(au(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(lh(r,"utf-8"));o.version=n,o.installPath=e,o.lastUpdated=new Date().toISOString(),Fv(r,JSON.stringify(o,null,2)+`
157
157
  `,"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]!==`
158
158
  `;)c++;c<t.length&&(e+=`
159
159
  `);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]===`
160
- `);)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 ro,HV,UV,Vv=X(()=>{"use strict";ro={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},HV=[ro.BEFORE,ro.AFTER],UV=[ro.COMPACTING]});var Kv={};De(Kv,{OpenCodeAdapter:()=>ph});import{readFileSync as Wv,writeFileSync as Pz,mkdirSync as Rz,copyFileSync as Cz,accessSync as $z,existsSync as Oz,constants as Iz}from"node:fs";import{resolve as $t,join as Ln}from"node:path";import{homedir as fr}from"node:os";var ph,Gv=X(()=>{"use strict";et();Fi();Vv();ph=class extends ge{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 Oz(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"),Ln(fr(),".config","kilo","kilo.jsonc"),Ln(fr(),".config","kilo","kilo.json")]:[$t("opencode.jsonc"),$t("opencode.json"),$t(".opencode","opencode.jsonc"),$t(".opencode","opencode.json"),Ln(fr(),".config","opencode","opencode.jsonc"),Ln(fr(),".config","opencode","opencode.json")]}getSessionDir(){let e=it(),n=e?Ln(e,"context-mode","sessions"):Ln(this.getConfigDir(),"context-mode","sessions");return Rz(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Ln(fr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Ln(fr(),".config"),Ln(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[ro.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.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(fr()))),r=null,o;for(let s of e)try{let i=Wv(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){Pz(this.getSettingsPath(),JSON.stringify(e,null,2)+`
161
- `,"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(fr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Wv(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{$z(this.settingsPath,Iz.R_OK);let n=this.settingsPath+".bak";return Cz(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 oo,GV,JV,Jv=X(()=>{"use strict";oo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},GV=[oo.TOOL_CALL_BEFORE,oo.TOOL_CALL_AFTER],JV=[oo.COMMAND_NEW]});var Xv={};De(Xv,{OpenClawAdapter:()=>gh});import{readFileSync as fh,writeFileSync as Az,copyFileSync as Nz,accessSync as Dz,constants as Mz}from"node:fs";import{resolve as Hn,join as mh}from"node:path";import{homedir as hh}from"node:os";var gh,Yv=X(()=>{"use strict";et();Jv();gh=class extends ge{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 Hn("openclaw.json")}getConfigDir(e){return Hn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return mh(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[oo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Hn("openclaw.json"),Hn(".openclaw","openclaw.json"),mh(hh(),".openclaw","openclaw.json")];for(let n of e)try{let r=fh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Hn("openclaw.json");Az(n,JSON.stringify(e,null,2)+`
160
+ `);)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 ro,UV,FV,Vv=X(()=>{"use strict";ro={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},UV=[ro.BEFORE,ro.AFTER],FV=[ro.COMPACTING]});var Kv={};De(Kv,{OpenCodeAdapter:()=>ph});import{readFileSync as Wv,writeFileSync as Pz,mkdirSync as Rz,copyFileSync as Cz,accessSync as $z,existsSync as Oz,constants as Iz}from"node:fs";import{resolve as $t,join as Ln}from"node:path";import{homedir as fr}from"node:os";var ph,Gv=X(()=>{"use strict";et();Fi();Vv();ph=class extends ge{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 Oz(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"),Ln(fr(),".config","kilo","kilo.jsonc"),Ln(fr(),".config","kilo","kilo.json")]:[$t("opencode.jsonc"),$t("opencode.json"),$t(".opencode","opencode.jsonc"),$t(".opencode","opencode.json"),Ln(fr(),".config","opencode","opencode.jsonc"),Ln(fr(),".config","opencode","opencode.json")]}getSessionDir(){let e=it(),n=e?Ln(e,"context-mode","sessions"):Ln(this.getConfigDir(),"context-mode","sessions");return Rz(n,{recursive:!0}),n}getConfigDir(e){let n;return process.platform==="win32"?n=process.env.APPDATA||Ln(fr(),"AppData","Roaming"):n=process.env.XDG_CONFIG_HOME||Ln(fr(),".config"),Ln(n,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[ro.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[ro.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(fr()))),r=null,o;for(let s of e)try{let i=Wv(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){Pz(this.getSettingsPath(),JSON.stringify(e,null,2)+`
161
+ `,"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(fr(),".cache",this.platform,"node_modules","context-mode","package.json"),n=JSON.parse(Wv(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{$z(this.settingsPath,Iz.R_OK);let n=this.settingsPath+".bak";return Cz(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 oo,JV,XV,Jv=X(()=>{"use strict";oo={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},JV=[oo.TOOL_CALL_BEFORE,oo.TOOL_CALL_AFTER],XV=[oo.COMMAND_NEW]});var Xv={};De(Xv,{OpenClawAdapter:()=>gh});import{readFileSync as fh,writeFileSync as Az,copyFileSync as Nz,accessSync as Dz,constants as Mz}from"node:fs";import{resolve as Hn,join as mh}from"node:path";import{homedir as hh}from"node:os";var gh,Yv=X(()=>{"use strict";et();Jv();gh=class extends ge{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 Hn("openclaw.json")}getConfigDir(e){return Hn(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(e){return mh(this.getConfigDir(e),"memory")}generateHookConfig(e){return{[oo.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[oo.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Hn("openclaw.json"),Hn(".openclaw","openclaw.json"),mh(hh(),".openclaw","openclaw.json")];for(let n of e)try{let r=fh(n,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let n=Hn("openclaw.json");Az(n,JSON.stringify(e,null,2)+`
162
162
  `,"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=Hn(hh(),".openclaw","extensions","context-mode","package.json"),n=JSON.parse(fh(e,"utf-8"));if(typeof n.version=="string")return n.version}catch{}try{let e=Hn("node_modules","context-mode","package.json"),n=JSON.parse(fh(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=[Hn("openclaw.json"),Hn(".openclaw","openclaw.json"),mh(hh(),".openclaw","openclaw.json")];for(let n of e)try{Dz(n,Mz.R_OK);let r=n+".bak";return Nz(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 Qv}from"node:os";import{resolve as yh}from"node:path";function eE(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?yh(Qv(),t.replace(/^~[/\\]?/,"")):yh(t):yh(Qv(),".codex")}var tE=X(()=>{"use strict"});var uE={};De(uE,{CodexAdapter:()=>Sh,parseCodexContextModePluginRoot:()=>uu,probeCodexCliVersion:()=>aE});import{execFileSync as iE}from"node:child_process";import{existsSync as jz,readFileSync as cs,writeFileSync as nE,accessSync as zz,copyFileSync as Lz,constants as Hz,mkdirSync as _h}from"node:fs";import{resolve as cu,dirname as xh,join as Un}from"node:path";import{fileURLToPath as Uz}from"node:url";function aE(t=iE){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 uu(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 lu(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(`
163
163
  `):null}function cE(t){let e=lu(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function Bz(t){let e=lu(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function rE(t){let e=lu(t,'plugins."context-mode@context-mode"');return e!==null&&/^\s*enabled\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function oE(t){return lu(t,"mcp_servers.context-mode")!==null}function qz(t){if(cE(t))return{text:t,changed:!1};let e=t.includes(`\r
164
164
  `)?`\r
@@ -175,12 +175,12 @@ var ZT=Object.create;var el=Object.defineProperty;var BT=Object.getOwnPropertyDe
175
175
 
176
176
  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 Un(this.getConfigDir(),"hooks.json")}backupFile(e,n=""){let r=n?`${e}${n}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return Lz(e,r),r}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(cs(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();_h(xh(n),{recursive:!0}),nE(n,JSON.stringify(e,null,2)+`
177
177
  `,"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 jz(Un(e,".codex-plugin","hooks.json"))}getCodexPluginHookStatus(e,n,r){let o=r&&rE(n),s=cu(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 uu(String(e))}catch{return null}}samePath(e,n){return this.normalizeCommand(cu(e))===this.normalizeCommand(cu(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 sE(e,s=>{let i="hooks.state.";if(!s.startsWith(i))return!1;let a=Vz(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(so[e]??""),s=Zz[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 lE,writeFileSync as Wz,mkdirSync as Kz,accessSync as Gz,chmodSync as Jz,constants as Xz}from"node:fs";import{resolve as du,join as Yz}from"node:path";var mr,pu=X(()=>{"use strict";et();mr=class extends ge{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 du(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=lE(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=lE(du(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();Kz(du(".github","hooks"),{recursive:!0}),Wz(n,JSON.stringify(e,null,2)+`
178
- `,"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=du(r,o);try{Gz(s,Xz.R_OK),Jz(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function dE(t,e){if(!kh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Bt,kh,yW,_W,pE=X(()=>{"use strict";Bt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},kh={[Bt.PRE_TOOL_USE]:"pretooluse.mjs",[Bt.POST_TOOL_USE]:"posttooluse.mjs",[Bt.PRE_COMPACT]:"precompact.mjs",[Bt.SESSION_START]:"sessionstart.mjs"},yW=[Bt.PRE_TOOL_USE,Bt.SESSION_START],_W=[Bt.POST_TOOL_USE,Bt.PRE_COMPACT]});var mE={};De(mE,{VSCodeCopilotAdapter:()=>wh});import{readFileSync as vh,mkdirSync as fE,accessSync as Qz,existsSync as eL,constants as tL}from"node:fs";import{resolve as us,join as Zi}from"node:path";import{homedir as Eh}from"node:os";var wh,hE=X(()=>{"use strict";pu();et();pE();wh=class extends mr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Bt,HOOK_SCRIPTS:kh,buildHookCommand:dE};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 fE(s,{recursive:!0}),s}let n=us(".github","context-mode","sessions"),r=Zi(Eh(),".vscode","context-mode","sessions"),o=eL(us(".github"))?n:r;return fE(o,{recursive:!0}),o}getConfigDir(e){return us(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=us(".github","hooks");try{Qz(r,tL.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=us(r,"context-mode.json");try{let s=vh(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=us(".vscode","mcp.json"),n=vh(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(Eh(),".vscode","extensions"),Zi(Eh(),".vscode-insiders","extensions")];for(let n of e)try{let r=vh(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 gE(t,e){if(!Th[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,Th,TW,PW,yE=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"},Th={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},TW=[qt.PRE_TOOL_USE,qt.SESSION_START],PW=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var _E={};De(_E,{JetBrainsCopilotAdapter:()=>Ph});import{readFileSync as nL}from"node:fs";import{resolve as rL}from"node:path";var Ph,xE=X(()=>{"use strict";pu();yE();Ph=class extends mr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Th,buildHookCommand:gE};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 rL(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=nL(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 SE(t,e){let n=Rh[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var dt,Rh,NW,DW,bE=X(()=>{"use strict";dt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Rh={[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"},NW=[dt.PRE_TOOL_USE,dt.SESSION_START],DW=[dt.POST_TOOL_USE,dt.PRE_COMPACT,dt.USER_PROMPT_SUBMIT,dt.STOP]});var PE={};De(PE,{CopilotCliAdapter:()=>$h,copilotCliHome:()=>mu,copilotCliMcpConfigPath:()=>fu});import{existsSync as kE,mkdirSync as vE,readFileSync as Ch,writeFileSync as oL}from"node:fs";import{homedir as EE}from"node:os";import{dirname as sL,join as ls,resolve as TE}from"node:path";function wE(){return process.env[iL]==="1"}function aL(t){return TE(t,"configs","copilot-cli","hooks.json")}function cL(t){return zn(Ch(t,"utf-8"))??{}}function uL(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function mu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?ls(EE(),t.replace(/^~[/\\]?/,"")):TE(t):ls(EE(),".copilot")}function fu(){return ls(mu(),"mcp-config.json")}var iL,$h,RE=X(()=>{"use strict";pu();et();Fi();bE();iL="CONTEXT_MODE_COPILOT_PLUGIN";$h=class extends mr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:dt,HOOK_SCRIPTS:Rh,buildHookCommand:SE};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 ls(mu(),"hooks","context-mode.json")}getConfigDir(e){return mu()}getSessionDir(){let e=it(),n=e?ls(e,"context-mode","sessions"):ls(this.getConfigDir(),"context-mode","sessions");return vE(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();vE(sL(n),{recursive:!0}),oL(n,JSON.stringify(e,null,2)+`
178
+ `,"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=du(r,o);try{Gz(s,Xz.R_OK),Jz(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}}});function dE(t,e){if(!kh[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Bt,kh,_W,xW,pE=X(()=>{"use strict";Bt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},kh={[Bt.PRE_TOOL_USE]:"pretooluse.mjs",[Bt.POST_TOOL_USE]:"posttooluse.mjs",[Bt.PRE_COMPACT]:"precompact.mjs",[Bt.SESSION_START]:"sessionstart.mjs"},_W=[Bt.PRE_TOOL_USE,Bt.SESSION_START],xW=[Bt.POST_TOOL_USE,Bt.PRE_COMPACT]});var mE={};De(mE,{VSCodeCopilotAdapter:()=>wh});import{readFileSync as vh,mkdirSync as fE,accessSync as Qz,existsSync as eL,constants as tL}from"node:fs";import{resolve as us,join as Zi}from"node:path";import{homedir as Eh}from"node:os";var wh,hE=X(()=>{"use strict";pu();et();pE();wh=class extends mr{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Bt,HOOK_SCRIPTS:kh,buildHookCommand:dE};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 fE(s,{recursive:!0}),s}let n=us(".github","context-mode","sessions"),r=Zi(Eh(),".vscode","context-mode","sessions"),o=eL(us(".github"))?n:r;return fE(o,{recursive:!0}),o}getConfigDir(e){return us(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[],r=us(".github","hooks");try{Qz(r,tL.R_OK)}catch{return n.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),n}let o=us(r,"context-mode.json");try{let s=vh(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=us(".vscode","mcp.json"),n=vh(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(Eh(),".vscode","extensions"),Zi(Eh(),".vscode-insiders","extensions")];for(let n of e)try{let r=vh(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 gE(t,e){if(!Th[t])throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var qt,Th,PW,RW,yE=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"},Th={[qt.PRE_TOOL_USE]:"pretooluse.mjs",[qt.POST_TOOL_USE]:"posttooluse.mjs",[qt.PRE_COMPACT]:"precompact.mjs",[qt.SESSION_START]:"sessionstart.mjs"},PW=[qt.PRE_TOOL_USE,qt.SESSION_START],RW=[qt.POST_TOOL_USE,qt.PRE_COMPACT]});var _E={};De(_E,{JetBrainsCopilotAdapter:()=>Ph});import{readFileSync as nL}from"node:fs";import{resolve as rL}from"node:path";var Ph,xE=X(()=>{"use strict";pu();yE();Ph=class extends mr{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:qt,HOOK_SCRIPTS:Th,buildHookCommand:gE};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 rL(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let n=[];try{let r=nL(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 SE(t,e){let n=Rh[t];if(!n)throw new Error(`No script defined for hook type: ${t}`);return`context-mode hook copilot-cli ${n.replace(/\.mjs$/,"")}`}var dt,Rh,DW,MW,bE=X(()=>{"use strict";dt={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",PRE_COMPACT:"preCompact",SESSION_START:"sessionStart",USER_PROMPT_SUBMIT:"userPromptSubmitted",STOP:"agentStop"},Rh={[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"},DW=[dt.PRE_TOOL_USE,dt.SESSION_START],MW=[dt.POST_TOOL_USE,dt.PRE_COMPACT,dt.USER_PROMPT_SUBMIT,dt.STOP]});var PE={};De(PE,{CopilotCliAdapter:()=>$h,copilotCliHome:()=>mu,copilotCliMcpConfigPath:()=>fu});import{existsSync as kE,mkdirSync as vE,readFileSync as Ch,writeFileSync as oL}from"node:fs";import{homedir as EE}from"node:os";import{dirname as sL,join as ls,resolve as TE}from"node:path";function wE(){return process.env[iL]==="1"}function aL(t){return TE(t,"configs","copilot-cli","hooks.json")}function cL(t){return zn(Ch(t,"utf-8"))??{}}function uL(t,e){return Array.isArray(t?.[e])&&(t?.[e]).length>0}function mu(){let t=process.env.COPILOT_HOME;return t&&t.trim()!==""?t.startsWith("~")?ls(EE(),t.replace(/^~[/\\]?/,"")):TE(t):ls(EE(),".copilot")}function fu(){return ls(mu(),"mcp-config.json")}var iL,$h,RE=X(()=>{"use strict";pu();et();Fi();bE();iL="CONTEXT_MODE_COPILOT_PLUGIN";$h=class extends mr{constructor(){super([".copilot"])}name="GitHub Copilot CLI";hookModule={HOOK_TYPES:dt,HOOK_SCRIPTS:Rh,buildHookCommand:SE};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 ls(mu(),"hooks","context-mode.json")}getConfigDir(e){return mu()}getSessionDir(){let e=it(),n=e?ls(e,"context-mode","sessions"):ls(this.getConfigDir(),"context-mode","sessions");return vE(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();vE(sL(n),{recursive:!0}),oL(n,JSON.stringify(e,null,2)+`
179
179
  `,"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=Ch(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=wE(),o=r?aL(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=cL(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=uL(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(wE())return{check:"MCP registration",status:"pass",message:"context-mode loaded from the Copilot CLI plugin bundle"};try{let e=Ch(fu(),"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 ${fu()}`,fix:"copilot mcp add context-mode -- context-mode"}}}getInstalledVersion(){return kE(fu())||kE(this.getSettingsPath())?"standalone":"not installed"}}});function Bi(t,e){let n=Oh[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 ye,Oh,lL,dL,Ih,CE,$E,OE=X(()=>{"use strict";ye={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Oh={[ye.PRE_TOOL_USE]:"pretooluse.mjs",[ye.POST_TOOL_USE]:"posttooluse.mjs",[ye.SESSION_START]:"sessionstart.mjs",[ye.STOP]:"stop.mjs",[ye.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},lL="MCP:(?!ctx_)",dL=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",lL],Ih=dL.join("|"),CE=[ye.PRE_TOOL_USE],$E=[ye.POST_TOOL_USE]});var ME={};De(ME,{CursorAdapter:()=>Ah});import{readFileSync as hu,writeFileSync as pL,mkdirSync as fL,accessSync as IE,chmodSync as mL,constants as AE,existsSync as NE,readdirSync as hL}from"node:fs";import{execSync as gL}from"node:child_process";import{resolve as io,join as ao}from"node:path";import{homedir as gu}from"node:os";var DE,Ah,jE=X(()=>{"use strict";et();to();OE();DE="/Library/Application Support/Cursor/hooks.json",Ah=class extends ge{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 io(".cursor","hooks.json")}getConfigDir(e){return io(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ye.PRE_TOOL_USE]:[{type:"command",command:Vt(ye.PRE_TOOL_USE),matcher:Ih,loop_limit:null,failClosed:!1}],[ye.POST_TOOL_USE]:[{type:"command",command:Vt(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ye.SESSION_START]:[{type:"command",command:Vt(ye.SESSION_START),loop_limit:null,failClosed:!1}],[ye.STOP]:[{type:"command",command:Vt(ye.STOP),loop_limit:null,failClosed:!1}],[ye.AFTER_AGENT_RESPONSE]:[{type:"command",command:Vt(ye.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let n=hu(e,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let n=this.getSettingsPath();fL(io(".cursor"),{recursive:!0}),pL(n,JSON.stringify(e,null,2)+`
180
180
  `,"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 CE){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 $E){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`})}}NE(DE)&&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=[ao(gu(),".cursor","plugins","local"),ao(gu(),".cursor","plugins","cache")],n=[];for(let r of e){try{IE(r,AE.F_OK)}catch{continue}let o=[];try{o=hL(r)}catch{continue}for(let s of o){let i=ao(r,s,".cursor-plugin","plugin.json");try{let a=hu(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&n.push(i)}catch{continue}}}return n}checkPluginRegistration(){let e=[io(".cursor","mcp.json"),ao(gu(),".cursor","mcp.json")];for(let r of e)try{let o=hu(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 gL("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,ye.PRE_TOOL_USE,{type:"command",command:Vt(ye.PRE_TOOL_USE),matcher:Ih,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.POST_TOOL_USE,{type:"command",command:Vt(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.SESSION_START,{type:"command",command:Vt(ye.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.STOP,{type:"command",command:Vt(ye.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(r,ye.AFTER_AGENT_RESPONSE,{type:"command",command:Vt(ye.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=ao(e,"hooks","cursor");for(let o of Object.values(Oh)){let s=io(r,o);try{IE(s,AE.R_OK),mL(s,493),n.push(s)}catch{}}return n}updatePluginRegistry(e,n){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),ao(gu(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(DE),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=hu(e,"utf-8"),r=JSON.parse(n);if(r&&typeof r=="object")return{path:e,config:r}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[io(".claude","settings.json"),io(".claude","settings.local.json"),ao(Ct(),"settings.json")].some(n=>NE(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 LE={};De(LE,{AntigravityAdapter:()=>qi});import{readFileSync as yu,writeFileSync as yL,mkdirSync as _L}from"node:fs";import{resolve as _u,dirname as zE}from"node:path";import{fileURLToPath as xL}from"node:url";import{homedir as Nh}from"node:os";var qi,Dh=X(()=>{"use strict";et();qi=class extends ge{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 _u(Nh(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return _u(Nh(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=yu(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();_L(zE(n),{recursive:!0}),yL(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=yu(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=_u(Nh(),".gemini","extensions","context-mode","package.json");return JSON.parse(yu(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,n){}getRoutingInstructions(){let e=_u(zE(xL(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return yu(e,"utf-8")}catch{return`# context-mode
181
181
 
182
182
  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 KE={};De(KE,{AntigravityCliAdapter:()=>Uh,antigravityCliConfigDir:()=>VE,antigravityCliHooksPath:()=>jh,antigravityCliMcpConfigPath:()=>qE,antigravityCliPluginDir:()=>bu});import{mkdirSync as SL,readFileSync as xu,writeFileSync as bL}from"node:fs";import{dirname as kL,resolve as co}from"node:path";import{homedir as Su}from"node:os";function qE(){return co(Su(),".gemini","config","mcp_config.json")}function VE(){return co(Su(),".gemini","antigravity-cli")}function jh(){return co(Su(),".gemini","config","hooks.json")}function bu(){return co(Su(),".gemini","config","plugins","context-mode")}function vL(){return co(bu(),"mcp_config.json")}function EL(){return co(bu(),"hooks.json")}function HE(t){for(let e of t)try{if("context-mode"in((zn(xu(e,"utf-8"))??{})?.mcpServers??{}))return{ok:!0,where:e}}catch{}return{ok:!1}}function kn(t){return t&&typeof t=="object"?t:{}}function UE(t){let e=kn(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 FE(t){return typeof t.conversationId=="string"&&t.conversationId?t.conversationId:`pid-${process.ppid}`}function WE(t,e){let n=kn(t);return(Array.isArray(n.hooks)?n.hooks:[]).some(o=>kn(o).command===e)}function ZE(t,e){return JSON.stringify(t).includes(e)}function wL(t){return typeof t!="string"?!1:["run_command","view_file","grep_search","web_fetch","read_url_content"].every(e=>t.includes(e))}function BE(t,e){return Array.isArray(t)&&t.some(n=>WE(n,e))}function TL(t){return Array.isArray(t)&&t.some(e=>{let n=kn(e);return wL(n.matcher)&&WE(e,zh)})}function PL(t){let e={preOk:!1,postOk:!1,stopOk:!1,where:void 0};for(let n of t)try{let o=(zn(xu(n,"utf-8"))??{}).hooks??{},s=TL(o.PreToolUse),i=BE(o.PostToolUse,Lh),a=BE(o.Stop,Hh);(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 CL(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 Mh(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=>!ZE(a,r)||JSON.stringify(a)===s)?!1:(t[e]=[...o.filter(a=>!ZE(a,r)),n],!0)}var zh,RL,Lh,Hh,Uh,GE=X(()=>{"use strict";Dh();Fi();zh="context-mode hook antigravity-cli pretooluse",RL="run_command|view_file|grep_search|web_fetch|read_url_content",Lh="context-mode hook antigravity-cli posttooluse",Hh="context-mode hook antigravity-cli stop";Uh=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 qE()}getConfigDir(e){return VE()}parsePreToolUseInput(e){let n=kn(e),r=kn(n.toolCall);return{toolName:typeof r.name=="string"?r.name:"",toolInput:kn(r.args),sessionId:FE(n),projectDir:UE(n),raw:e}}parsePostToolUseInput(e){let n=kn(e),r=kn(n.toolCall),o=typeof n.error=="string"?n.error:"";return{toolName:typeof r.name=="string"?r.name:"",toolInput:kn(r.args),toolOutput:o,isError:o.length>0,sessionId:FE(n),projectDir:UE(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:CL(e.additionalContext)}:null}formatPostToolUseResponse(e){}checkPluginRegistration(){let{ok:e,where:n}=HE([vL(),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(xu(co(bu(),"plugin.json"),"utf-8"));if(e&&typeof e.version=="string"&&e.version)return e.version}catch{}return HE([this.getSettingsPath()]).ok?"standalone":"not installed"}configureAllHooks(e){let n=[],r=jh(),o={};try{o=zn(xu(r,"utf-8"))??{}}catch{}let s=o.hooks??{},i={matcher:RL,hooks:[{type:"command",command:zh}]},a={matcher:"",hooks:[{type:"command",command:Lh}]},c={matcher:"",hooks:[{type:"command",command:Hh}]},u=Mh(s,"PreToolUse",i,zh),l=Mh(s,"PostToolUse",a,Lh),d=Mh(s,"Stop",c,Hh);return(u||l||d)&&(o.hooks=s,SL(kL(r),{recursive:!0}),bL(r,JSON.stringify(o,null,2)+`
183
- `,"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}=PL([EL(),jh()]),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 ku(t,e){let n=JE[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ds(t,e){let n=JE[t];return e&&n?Le(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,JE,$L,OL,Fh,uK,lK,XE=X(()=>{"use strict";Mn();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},JE={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},$L="@(?!context-mode/)",OL=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",$L],Fh=OL.join("|"),uK=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],lK=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var tw={};De(tw,{KiroAdapter:()=>Zh});import{readFileSync as ps,writeFileSync as YE,mkdirSync as QE}from"node:fs";import{resolve as uo,dirname as ew}from"node:path";import{fileURLToPath as IL}from"node:url";import{homedir as vu}from"node:os";var Zh,nw=X(()=>{"use strict";et();XE();Zh=class extends ge{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 uo(vu(),".kiro","settings","mcp.json")}getConfigDir(e){return uo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:Fh,hooks:[{type:"command",command:ds(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ps(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();QE(ew(n),{recursive:!0}),YE(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=uo(vu(),".kiro","agents","default.json");try{let s=JSON.parse(ps(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>ku(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=>ku(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=ps(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=uo(vu(),".kiro","extensions","context-mode","package.json");return JSON.parse(ps(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=uo(vu(),".kiro","agents"),o=uo(r,"default.json");try{QE(r,{recursive:!0});let s={};try{s=JSON.parse(ps(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,Fh],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>ku(d,c))||(l.push({matcher:u,command:ds(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,YE(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=uo(ew(IL(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ps(e,"utf-8")}catch{return`# context-mode
183
+ `,"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}=PL([EL(),jh()]),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 ku(t,e){let n=JE[e];return n&&(t.command?.includes(n)||t.command?.includes("context-mode hook kiro"))||!1}function ds(t,e){let n=JE[t];return e&&n?Le(`${e}/hooks/kiro/${n}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ie,JE,$L,OL,Fh,lK,dK,XE=X(()=>{"use strict";Mn();Ie={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},JE={[Ie.PRE_TOOL_USE]:"pretooluse.mjs",[Ie.POST_TOOL_USE]:"posttooluse.mjs",[Ie.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ie.AGENT_SPAWN]:"agentspawn.mjs"},$L="@(?!context-mode/)",OL=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",$L],Fh=OL.join("|"),lK=[Ie.PRE_TOOL_USE,Ie.AGENT_SPAWN],dK=[Ie.POST_TOOL_USE,Ie.USER_PROMPT_SUBMIT]});var tw={};De(tw,{KiroAdapter:()=>Zh});import{readFileSync as ps,writeFileSync as YE,mkdirSync as QE}from"node:fs";import{resolve as uo,dirname as ew}from"node:path";import{fileURLToPath as IL}from"node:url";import{homedir as vu}from"node:os";var Zh,nw=X(()=>{"use strict";et();XE();Zh=class extends ge{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 uo(vu(),".kiro","settings","mcp.json")}getConfigDir(e){return uo(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ie.PRE_TOOL_USE]:[{matcher:Fh,hooks:[{type:"command",command:ds(Ie.PRE_TOOL_USE,e)}]}],[Ie.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.POST_TOOL_USE,e)}]}],[Ie.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.AGENT_SPAWN,e)}]}],[Ie.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ds(Ie.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=ps(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();QE(ew(n),{recursive:!0}),YE(n,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let n=[],r=uo(vu(),".kiro","agents","default.json");try{let s=JSON.parse(ps(r,"utf-8")).hooks??{};for(let i of[Ie.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>ku(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=>ku(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=ps(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=uo(vu(),".kiro","extensions","context-mode","package.json");return JSON.parse(ps(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let n=[],r=uo(vu(),".kiro","agents"),o=uo(r,"default.json");try{QE(r,{recursive:!0});let s={};try{s=JSON.parse(ps(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ie.PRE_TOOL_USE,Fh],[Ie.POST_TOOL_USE,"*"],[Ie.AGENT_SPAWN,"*"],[Ie.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>ku(d,c))||(l.push({matcher:u,command:ds(c,e)}),i[c]=l,n.push(`Added ${c} hook to ${o}`))}s.hooks=i,YE(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=uo(ew(IL(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return ps(e,"utf-8")}catch{return`# context-mode
184
184
 
185
185
  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 sw={};De(sw,{ZedAdapter:()=>qh});import{readFileSync as Bh,writeFileSync as AL,mkdirSync as NL}from"node:fs";import{resolve as rw,dirname as ow}from"node:path";import{fileURLToPath as DL}from"node:url";import{homedir as ML}from"node:os";var qh,iw=X(()=>{"use strict";et();qh=class extends ge{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 rw(ML(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Bh(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let n=this.getSettingsPath();NL(ow(n),{recursive:!0}),AL(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=Bh(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=rw(ow(DL(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Bh(e,"utf-8")}catch{return`# context-mode
186
186
 
@@ -219,13 +219,13 @@ Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_inde
219
219
  path: iss.path ? [${Nr(_)}, ...iss.path] : [${Nr(_)}]
220
220
  })));`),f.write(`newResult[${Nr(_)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let y=f.compile();return(_,x)=>y(d,_,x)},o,s=vo,i=!la.jitless,c=i&&ll.value,u=e.catchall,l;t._zod.parse=(d,f)=>{l??(l=n.value);let m=d.value;if(!s(m))return d.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),d;let p=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=r(e.shape)),d=o(d,f);else{d.value={};let x=l.shape;for(let b of l.keys){let v=x[b],O=v._zod.run({value:m[b],issues:[]},f),R=v._zod.optin==="optional"&&v._zod.optout==="optional";O instanceof Promise?p.push(O.then(M=>R?Gy(M,d,b,m):ya(M,d,b))):R?Gy(O,d,b,m):ya(O,d,b)}}if(!u)return p.length?Promise.all(p).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(m)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let b=y.run({value:m[x],issues:[]},f);b instanceof Promise?p.push(b.then(v=>ya(v,d,x))):ya(b,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:m,inst:t}),p.length?Promise.all(p).then(()=>d):d}});function Jy(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 Sa=k("$ZodUnion",(t,e)=>{me.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=>Os(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=>Jy(i,n,t,r)):Jy(s,n,t,r)}}),Ql=k("$ZodDiscriminatedUnion",(t,e)=>{Sa.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=Cs(()=>{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(!vo(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)}}),ed=k("$ZodIntersection",(t,e)=>{me.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])=>Xy(n,c,u)):Xy(n,s,i)}});function Pl(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(Eo(t)&&Eo(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=Pl(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=Pl(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 Xy(t,e,n){if(e.issues.length&&t.issues.push(...e.issues),n.issues.length&&t.issues.push(...n.issues),Dr(t))return t;let r=Pl(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 td=k("$ZodRecord",(t,e)=>{me.init(t,e),t._zod.parse=(n,r)=>{let o=n.value;if(!Eo(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 nd=k("$ZodEnum",(t,e)=>{me.init(t,e);let n=Rs(e.entries);t._zod.values=new Set(n),t._zod.pattern=new RegExp(`^(${n.filter(r=>dl.has(typeof r)).map(r=>typeof r=="string"?Gn(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}}),rd=k("$ZodLiteral",(t,e)=>{me.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(n=>typeof n=="string"?Gn(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 od=k("$ZodTransform",(t,e)=>{me.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 $n;return n.value=o,n}}),sd=k("$ZodOptional",(t,e)=>{me.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(`^(${Os(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)}),id=k("$ZodNullable",(t,e)=>{me.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(`^(${Os(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)}),ad=k("$ZodDefault",(t,e)=>{me.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=>Yy(s,e)):Yy(o,e)}});function Yy(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}var cd=k("$ZodPrefault",(t,e)=>{me.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))}),ud=k("$ZodNonOptional",(t,e)=>{me.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=>Qy(s,t)):Qy(o,t)}});function Qy(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 ld=k("$ZodCatch",(t,e)=>{me.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 dd=k("$ZodPipe",(t,e)=>{me.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=>e_(s,e,r)):e_(o,e,r)}});function e_(t,e,n){return Dr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},n)}var pd=k("$ZodReadonly",(t,e)=>{me.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(t_):t_(o)}});function t_(t){return t.value=Object.freeze(t.value),t}var fd=k("$ZodCustom",(t,e)=>{We.init(t,e),me.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=>n_(s,n,r,t));n_(o,n,r,t)}});function n_(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(ml(o))}}var PR=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},RR=()=>{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 ${PR(r.input)}`;case"invalid_value":return r.values.length===1?`Invalid input: expected ${fa(r.values[0])}`:`Invalid option: expected one of ${da(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":""}: ${da(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 c_(){return{localeError:RR()}}var Ms=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 u_(){return new Ms}var Jn=u_();function md(t,e){return new t({type:"string",...q(e)})}function hd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...q(e)})}function ba(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...q(e)})}function gd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...q(e)})}function yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...q(e)})}function _d(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...q(e)})}function xd(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 bd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...q(e)})}function kd(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...q(e)})}function vd(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...q(e)})}function Ed(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...q(e)})}function wd(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...q(e)})}function Td(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...q(e)})}function Pd(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...q(e)})}function Rd(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...q(e)})}function Cd(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...q(e)})}function $d(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...q(e)})}function Od(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...q(e)})}function Id(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...q(e)})}function Ad(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...q(e)})}function Nd(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...q(e)})}function Dd(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...q(e)})}function l_(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...q(e)})}function d_(t,e){return new t({type:"string",format:"date",check:"string_format",...q(e)})}function p_(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...q(e)})}function f_(t,e){return new t({type:"string",format:"duration",check:"string_format",...q(e)})}function Md(t,e){return new t({type:"number",checks:[],...q(e)})}function jd(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...q(e)})}function zd(t,e){return new t({type:"boolean",...q(e)})}function Ld(t,e){return new t({type:"null",...q(e)})}function Hd(t){return new t({type:"unknown"})}function Ud(t,e){return new t({type:"never",...q(e)})}function ka(t,e){return new wl({check:"less_than",...q(e),value:t,inclusive:!1})}function js(t,e){return new wl({check:"less_than",...q(e),value:t,inclusive:!0})}function va(t,e){return new Tl({check:"greater_than",...q(e),value:t,inclusive:!1})}function zs(t,e){return new Tl({check:"greater_than",...q(e),value:t,inclusive:!0})}function Ea(t,e){return new Ny({check:"multiple_of",...q(e),value:t})}function wa(t,e){return new My({check:"max_length",...q(e),maximum:t})}function wo(t,e){return new jy({check:"min_length",...q(e),minimum:t})}function Ta(t,e){return new zy({check:"length_equals",...q(e),length:t})}function Fd(t,e){return new Ly({check:"string_format",format:"regex",...q(e),pattern:t})}function Zd(t){return new Hy({check:"string_format",format:"lowercase",...q(t)})}function Bd(t){return new Uy({check:"string_format",format:"uppercase",...q(t)})}function qd(t,e){return new Fy({check:"string_format",format:"includes",...q(e),includes:t})}function Vd(t,e){return new Zy({check:"string_format",format:"starts_with",...q(e),prefix:t})}function Wd(t,e){return new By({check:"string_format",format:"ends_with",...q(e),suffix:t})}function zr(t){return new qy({check:"overwrite",tx:t})}function Kd(t){return zr(e=>e.normalize(t))}function Gd(){return zr(t=>t.trim())}function Jd(){return zr(t=>t.toLowerCase())}function Xd(){return zr(t=>t.toUpperCase())}function m_(t,e,n){return new t({type:"array",element:e,...q(n)})}function Yd(t,e,n){let r=q(n);return r.abort??(r.abort=!0),new t({type:"custom",check:"custom",fn:e,...r})}function Qd(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??Jn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,n={path:[],schemaPath:[]}){var r;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,n.schemaPath.includes(e)&&(i.cycle=n.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:n.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...n,schemaPath:[...n.schemaPath,e],path:n.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,d),this.seen.get(f).isParent=!0;else{let m=a.schema;switch(o.type){case"string":{let p=m;p.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=s[y]??y,p.format===""&&delete p.format),x&&(p.contentEncoding=x),_&&_.size>0){let b=[..._];b.length===1?p.pattern=b[0].source:b.length>1&&(a.schema.allOf=[...b.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=m,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:b}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof b=="number"&&(p.exclusiveMinimum=b),typeof h=="number"&&(p.minimum=h,typeof b=="number"&&(b>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=m;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{m.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{m.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=m,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let p=m;p.type="object",p.properties={};let h=o.shape;for(let _ in h)p.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(p.required=Array.from(y)),o.catchall?._zod.def.type==="never"?p.additionalProperties=!1:o.catchall?o.catchall&&(p.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=m;p.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let p=m,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=m;p.type="array";let h=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}o.rest&&(p.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=m;p.type="object",p.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let p=m,h=Rs(o.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=m,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=m,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(p,h)):p.anyOf=_.map(x=>({...h,contentMediaType:x})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(o.innerType,d);m.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let p=m;p.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,m.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(m._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let p;try{p=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}m.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=m,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(p,d),a.ref=p;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,m.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let p=e._zod.innerType;this.process(p,d),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&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>
221
221
 
222
- 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 ep(t,e){if(t instanceof Ms){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 u0=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");me.init(t,e),t.def=e,t.parse=(n,r)=>_l(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Mr(t,n,r),t.parseAsync=async(n,r)=>Sl(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>jr(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)=>Pt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var l0=k("ZodMiniObject",(t,e)=>{xa.init(t,e),u0.init(t,e),se.defineLazy(t,"shape",()=>e.shape)});function tp(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new l0(n)}function Nt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return tp({});let n=e.every(Nt),r=e.every(o=>!Nt(o));if(n)return tp(t);if(r)return ol(t);throw new Error("Mixed Zod versions detected in object shape.")}function Xn(t,e){return Nt(t)?Mr(t,e):t.safeParse(e)}async function Ra(t,e){return Nt(t)?await jr(t,e):await t.safeParseAsync(e)}function Yn(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 To(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 Hr(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 Ca(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 g_(t){return t.description}function y_(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 $a(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 Ls={};De(Ls,{ZodISODate:()=>x_,ZodISODateTime:()=>__,ZodISODuration:()=>b_,ZodISOTime:()=>S_,date:()=>rp,datetime:()=>np,duration:()=>sp,time:()=>op});var __=k("ZodISODateTime",(t,e)=>{r_.init(t,e),Pe.init(t,e)});function np(t){return l_(__,t)}var x_=k("ZodISODate",(t,e)=>{o_.init(t,e),Pe.init(t,e)});function rp(t){return d_(x_,t)}var S_=k("ZodISOTime",(t,e)=>{s_.init(t,e),Pe.init(t,e)});function op(t){return p_(S_,t)}var b_=k("ZodISODuration",(t,e)=>{i_.init(t,e),Pe.init(t,e)});function sp(t){return f_(b_,t)}var k_=(t,e)=>{ma.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>gl(t,n)},flatten:{value:n=>hl(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},rZ=k("ZodError",k_),Hs=k("ZodError",k_,{Parent:Error});var v_=yl(Hs),E_=xl(Hs),w_=bl(Hs),T_=kl(Hs);var Oe=k("ZodType",(t,e)=>(me.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)=>Pt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>v_(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>w_(t,n,r),t.parseAsync=async(n,r)=>E_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>T_(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(aC(n,r)),t.superRefine=n=>t.check(cC(n)),t.overwrite=n=>t.check(zr(n)),t.optional=()=>Ce(t),t.nullable=()=>C_(t),t.nullish=()=>Ce(C_(t)),t.nonoptional=n=>eC(t,n),t.array=()=>ie(t),t.or=n=>ke([t,n]),t.and=n=>Ia(t,n),t.transform=n=>ap(t,D_(n)),t.default=n=>X0(t,n),t.prefault=n=>Q0(t,n),t.catch=n=>nC(t,n),t.pipe=n=>ap(t,n),t.readonly=()=>sC(t),t.describe=n=>{let r=t.clone();return Jn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Jn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Jn.get(t);let r=t.clone();return Jn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),$_=k("_ZodString",(t,e)=>{Ds.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(Fd(...r)),t.includes=(...r)=>t.check(qd(...r)),t.startsWith=(...r)=>t.check(Vd(...r)),t.endsWith=(...r)=>t.check(Wd(...r)),t.min=(...r)=>t.check(wo(...r)),t.max=(...r)=>t.check(wa(...r)),t.length=(...r)=>t.check(Ta(...r)),t.nonempty=(...r)=>t.check(wo(1,...r)),t.lowercase=r=>t.check(Zd(r)),t.uppercase=r=>t.check(Bd(r)),t.trim=()=>t.check(Gd()),t.normalize=(...r)=>t.check(Kd(...r)),t.toLowerCase=()=>t.check(Jd()),t.toUpperCase=()=>t.check(Xd())}),x0=k("ZodString",(t,e)=>{Ds.init(t,e),$_.init(t,e),t.email=n=>t.check(hd(S0,n)),t.url=n=>t.check(Sd(b0,n)),t.jwt=n=>t.check(Dd(M0,n)),t.emoji=n=>t.check(bd(k0,n)),t.guid=n=>t.check(ba(P_,n)),t.uuid=n=>t.check(gd(Oa,n)),t.uuidv4=n=>t.check(yd(Oa,n)),t.uuidv6=n=>t.check(_d(Oa,n)),t.uuidv7=n=>t.check(xd(Oa,n)),t.nanoid=n=>t.check(kd(v0,n)),t.guid=n=>t.check(ba(P_,n)),t.cuid=n=>t.check(vd(E0,n)),t.cuid2=n=>t.check(Ed(w0,n)),t.ulid=n=>t.check(wd(T0,n)),t.base64=n=>t.check(Id(A0,n)),t.base64url=n=>t.check(Ad(N0,n)),t.xid=n=>t.check(Td(P0,n)),t.ksuid=n=>t.check(Pd(R0,n)),t.ipv4=n=>t.check(Rd(C0,n)),t.ipv6=n=>t.check(Cd($0,n)),t.cidrv4=n=>t.check($d(O0,n)),t.cidrv6=n=>t.check(Od(I0,n)),t.e164=n=>t.check(Nd(D0,n)),t.datetime=n=>t.check(np(n)),t.date=n=>t.check(rp(n)),t.time=n=>t.check(op(n)),t.duration=n=>t.check(sp(n))});function S(t){return md(x0,t)}var Pe=k("ZodStringFormat",(t,e)=>{Se.init(t,e),$_.init(t,e)}),S0=k("ZodEmail",(t,e)=>{$l.init(t,e),Pe.init(t,e)});var P_=k("ZodGUID",(t,e)=>{Rl.init(t,e),Pe.init(t,e)});var Oa=k("ZodUUID",(t,e)=>{Cl.init(t,e),Pe.init(t,e)});var b0=k("ZodURL",(t,e)=>{Ol.init(t,e),Pe.init(t,e)});var k0=k("ZodEmoji",(t,e)=>{Il.init(t,e),Pe.init(t,e)});var v0=k("ZodNanoID",(t,e)=>{Al.init(t,e),Pe.init(t,e)});var E0=k("ZodCUID",(t,e)=>{Nl.init(t,e),Pe.init(t,e)});var w0=k("ZodCUID2",(t,e)=>{Dl.init(t,e),Pe.init(t,e)});var T0=k("ZodULID",(t,e)=>{Ml.init(t,e),Pe.init(t,e)});var P0=k("ZodXID",(t,e)=>{jl.init(t,e),Pe.init(t,e)});var R0=k("ZodKSUID",(t,e)=>{zl.init(t,e),Pe.init(t,e)});var C0=k("ZodIPv4",(t,e)=>{Ll.init(t,e),Pe.init(t,e)});var $0=k("ZodIPv6",(t,e)=>{Hl.init(t,e),Pe.init(t,e)});var O0=k("ZodCIDRv4",(t,e)=>{Ul.init(t,e),Pe.init(t,e)});var I0=k("ZodCIDRv6",(t,e)=>{Fl.init(t,e),Pe.init(t,e)});var A0=k("ZodBase64",(t,e)=>{Zl.init(t,e),Pe.init(t,e)});var N0=k("ZodBase64URL",(t,e)=>{Bl.init(t,e),Pe.init(t,e)});var D0=k("ZodE164",(t,e)=>{ql.init(t,e),Pe.init(t,e)});var M0=k("ZodJWT",(t,e)=>{Vl.init(t,e),Pe.init(t,e)});var O_=k("ZodNumber",(t,e)=>{_a.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(va(r,o)),t.gte=(r,o)=>t.check(zs(r,o)),t.min=(r,o)=>t.check(zs(r,o)),t.lt=(r,o)=>t.check(ka(r,o)),t.lte=(r,o)=>t.check(js(r,o)),t.max=(r,o)=>t.check(js(r,o)),t.int=r=>t.check(R_(r)),t.safe=r=>t.check(R_(r)),t.positive=r=>t.check(va(0,r)),t.nonnegative=r=>t.check(zs(0,r)),t.negative=r=>t.check(ka(0,r)),t.nonpositive=r=>t.check(js(0,r)),t.multipleOf=(r,o)=>t.check(Ea(r,o)),t.step=(r,o)=>t.check(Ea(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 Md(O_,t)}var j0=k("ZodNumberFormat",(t,e)=>{Wl.init(t,e),O_.init(t,e)});function R_(t){return jd(j0,t)}var z0=k("ZodBoolean",(t,e)=>{Kl.init(t,e),Oe.init(t,e)});function qe(t){return zd(z0,t)}var L0=k("ZodNull",(t,e)=>{Gl.init(t,e),Oe.init(t,e)});function I_(t){return Ld(L0,t)}var H0=k("ZodUnknown",(t,e)=>{Jl.init(t,e),Oe.init(t,e)});function Re(){return Hd(H0)}var U0=k("ZodNever",(t,e)=>{Xl.init(t,e),Oe.init(t,e)});function F0(t){return Ud(U0,t)}var Z0=k("ZodArray",(t,e)=>{Yl.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(wo(n,r)),t.nonempty=n=>t.check(wo(1,n)),t.max=(n,r)=>t.check(wa(n,r)),t.length=(n,r)=>t.check(Ta(n,r)),t.unwrap=()=>t.element});function ie(t,e){return m_(Z0,t,e)}var A_=k("ZodObject",(t,e)=>{xa.init(t,e),Oe.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>yt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Re()}),t.loose=()=>t.clone({...t._zod.def,catchall:Re()}),t.strict=()=>t.clone({...t._zod.def,catchall:F0()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>se.extend(t,n),t.merge=n=>se.merge(t,n),t.pick=n=>se.pick(t,n),t.omit=n=>se.omit(t,n),t.partial=(...n)=>se.partial(M_,t,n[0]),t.required=(...n)=>se.required(j_,t,n[0])});function N(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new A_(n)}function at(t,e){return new A_({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:Re(),...se.normalizeParams(e)})}var N_=k("ZodUnion",(t,e)=>{Sa.init(t,e),Oe.init(t,e),t.options=e.options});function ke(t,e){return new N_({type:"union",options:t,...se.normalizeParams(e)})}var B0=k("ZodDiscriminatedUnion",(t,e)=>{N_.init(t,e),Ql.init(t,e)});function cp(t,e,n){return new B0({type:"union",options:e,discriminator:t,...se.normalizeParams(n)})}var q0=k("ZodIntersection",(t,e)=>{ed.init(t,e),Oe.init(t,e)});function Ia(t,e){return new q0({type:"intersection",left:t,right:e})}var V0=k("ZodRecord",(t,e)=>{td.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,n){return new V0({type:"record",keyType:t,valueType:e,...se.normalizeParams(n)})}var ip=k("ZodEnum",(t,e)=>{nd.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 ip({...e,checks:[],...se.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 ip({...e,checks:[],...se.normalizeParams(o),entries:s})}});function yt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ip({type:"enum",entries:n,...se.normalizeParams(e)})}var W0=k("ZodLiteral",(t,e)=>{rd.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 W0({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var K0=k("ZodTransform",(t,e)=>{od.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(se.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(se.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 D_(t){return new K0({type:"transform",transform:t})}var M_=k("ZodOptional",(t,e)=>{sd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new M_({type:"optional",innerType:t})}var G0=k("ZodNullable",(t,e)=>{id.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function C_(t){return new G0({type:"nullable",innerType:t})}var J0=k("ZodDefault",(t,e)=>{ad.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function X0(t,e){return new J0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Y0=k("ZodPrefault",(t,e)=>{cd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q0(t,e){return new Y0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var j_=k("ZodNonOptional",(t,e)=>{ud.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function eC(t,e){return new j_({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var tC=k("ZodCatch",(t,e)=>{ld.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function nC(t,e){return new tC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var rC=k("ZodPipe",(t,e)=>{dd.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function ap(t,e){return new rC({type:"pipe",in:t,out:e})}var oC=k("ZodReadonly",(t,e)=>{pd.init(t,e),Oe.init(t,e)});function sC(t){return new oC({type:"readonly",innerType:t})}var z_=k("ZodCustom",(t,e)=>{fd.init(t,e),Oe.init(t,e)});function iC(t){let e=new We({check:"custom"});return e._zod.check=t,e}function L_(t,e){return Yd(z_,t??(()=>!0),e)}function aC(t,e={}){return Qd(z_,t,e)}function cC(t){let e=iC(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(se.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(se.issue(o))}},t(n.value,n)));return e}function up(t,e){return ap(D_(t),e)}Tt(c_());var dp="2025-11-25";var H_=[dp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qn="io.modelcontextprotocol/related-task",Na="2.0",Ze=L_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),U_=ke([S(),fe().int()]),F_=S(),yZ=at({ttl:fe().optional(),pollInterval:fe().optional()}),uC=N({ttl:fe().optional()}),lC=N({taskId:S()}),pp=at({progressToken:U_.optional(),[Qn]:lC.optional()}),Rt=N({_meta:pp.optional()}),Us=Rt.extend({task:uC.optional()}),Z_=t=>Us.safeParse(t).success,Ke=N({method:S(),params:Rt.loose().optional()}),Dt=N({_meta:pp.optional()}),Mt=N({method:S(),params:Dt.loose().optional()}),Ge=at({_meta:pp.optional()}),Da=ke([S(),fe().int()]),B_=N({jsonrpc:U(Na),id:Da,...Ke.shape}).strict(),fp=t=>B_.safeParse(t).success,q_=N({jsonrpc:U(Na),...Mt.shape}).strict(),V_=t=>q_.safeParse(t).success,mp=N({jsonrpc:U(Na),id:Da,result:Ge}).strict(),Fs=t=>mp.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 hp=N({jsonrpc:U(Na),id:Da.optional(),error:N({code:fe().int(),message:S(),data:Re().optional()})}).strict();var W_=t=>hp.safeParse(t).success;var K_=ke([B_,q_,mp,hp]),_Z=ke([mp,hp]),Ma=Ge.strict(),dC=Dt.extend({requestId:Da.optional(),reason:S().optional()}),ja=Mt.extend({method:U("notifications/cancelled"),params:dC}),pC=N({src:S(),mimeType:S().optional(),sizes:ie(S()).optional(),theme:yt(["light","dark"]).optional()}),Zs=N({icons:ie(pC).optional()}),Po=N({name:S(),title:S().optional()}),G_=Po.extend({...Po.shape,...Zs.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),fC=Ia(N({applyDefaults:qe().optional()}),be(S(),Re())),mC=up(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ia(N({form:fC.optional(),url:Ze.optional()}),be(S(),Re()).optional())),hC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({sampling:at({createMessage:Ze.optional()}).optional(),elicitation:at({create:Ze.optional()}).optional()}).optional()}),gC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({tools:at({call:Ze.optional()}).optional()}).optional()}),yC=N({experimental:be(S(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:mC.optional(),roots:N({listChanged:qe().optional()}).optional(),tasks:hC.optional(),extensions:be(S(),Ze).optional()}),_C=Rt.extend({protocolVersion:S(),capabilities:yC,clientInfo:G_}),gp=Ke.extend({method:U("initialize"),params:_C});var xC=N({experimental:be(S(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:qe().optional()}).optional(),resources:N({subscribe:qe().optional(),listChanged:qe().optional()}).optional(),tools:N({listChanged:qe().optional()}).optional(),tasks:gC.optional(),extensions:be(S(),Ze).optional()}),SC=Ge.extend({protocolVersion:S(),capabilities:xC,serverInfo:G_,instructions:S().optional()}),yp=Mt.extend({method:U("notifications/initialized"),params:Dt.optional()});var za=Ke.extend({method:U("ping"),params:Rt.optional()}),bC=N({progress:fe(),total:Ce(fe()),message:Ce(S())}),kC=N({...Dt.shape,...bC.shape,progressToken:U_}),La=Mt.extend({method:U("notifications/progress"),params:kC}),vC=Rt.extend({cursor:F_.optional()}),Bs=Ke.extend({params:vC.optional()}),qs=Ge.extend({nextCursor:F_.optional()}),EC=yt(["working","input_required","completed","failed","cancelled"]),Vs=N({taskId:S(),status:EC,ttl:ke([fe(),I_()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ce(fe()),statusMessage:Ce(S())}),Ro=Ge.extend({task:Vs}),wC=Dt.merge(Vs),Ws=Mt.extend({method:U("notifications/tasks/status"),params:wC}),Ha=Ke.extend({method:U("tasks/get"),params:Rt.extend({taskId:S()})}),Ua=Ge.merge(Vs),Fa=Ke.extend({method:U("tasks/result"),params:Rt.extend({taskId:S()})}),xZ=Ge.loose(),Za=Bs.extend({method:U("tasks/list")}),Ba=qs.extend({tasks:ie(Vs)}),qa=Ke.extend({method:U("tasks/cancel"),params:Rt.extend({taskId:S()})}),J_=Ge.merge(Vs),X_=N({uri:S(),mimeType:Ce(S()),_meta:be(S(),Re()).optional()}),Y_=X_.extend({text:S()}),_p=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Q_=X_.extend({blob:_p}),Ks=yt(["user","assistant"]),Co=N({audience:ie(Ks).optional(),priority:fe().min(0).max(1).optional(),lastModified:Ls.datetime({offset:!0}).optional()}),ex=N({...Po.shape,...Zs.shape,uri:S(),description:Ce(S()),mimeType:Ce(S()),size:Ce(fe()),annotations:Co.optional(),_meta:Ce(at({}))}),TC=N({...Po.shape,...Zs.shape,uriTemplate:S(),description:Ce(S()),mimeType:Ce(S()),annotations:Co.optional(),_meta:Ce(at({}))}),$o=Bs.extend({method:U("resources/list")}),PC=qs.extend({resources:ie(ex)}),Oo=Bs.extend({method:U("resources/templates/list")}),RC=qs.extend({resourceTemplates:ie(TC)}),xp=Rt.extend({uri:S()}),CC=xp,Va=Ke.extend({method:U("resources/read"),params:CC}),$C=Ge.extend({contents:ie(ke([Y_,Q_]))}),OC=Mt.extend({method:U("notifications/resources/list_changed"),params:Dt.optional()}),IC=xp,AC=Ke.extend({method:U("resources/subscribe"),params:IC}),NC=xp,DC=Ke.extend({method:U("resources/unsubscribe"),params:NC}),MC=Dt.extend({uri:S()}),jC=Mt.extend({method:U("notifications/resources/updated"),params:MC}),zC=N({name:S(),description:Ce(S()),required:Ce(qe())}),LC=N({...Po.shape,...Zs.shape,description:Ce(S()),arguments:Ce(ie(zC)),_meta:Ce(at({}))}),Io=Bs.extend({method:U("prompts/list")}),HC=qs.extend({prompts:ie(LC)}),UC=Rt.extend({name:S(),arguments:be(S(),S()).optional()}),Wa=Ke.extend({method:U("prompts/get"),params:UC}),Sp=N({type:U("text"),text:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),bp=N({type:U("image"),data:_p,mimeType:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),kp=N({type:U("audio"),data:_p,mimeType:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),FC=N({type:U("tool_use"),name:S(),id:S(),input:be(S(),Re()),_meta:be(S(),Re()).optional()}),ZC=N({type:U("resource"),resource:ke([Y_,Q_]),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),BC=ex.extend({type:U("resource_link")}),vp=ke([Sp,bp,kp,BC,ZC]),qC=N({role:Ks,content:vp}),VC=Ge.extend({description:S().optional(),messages:ie(qC)}),WC=Mt.extend({method:U("notifications/prompts/list_changed"),params:Dt.optional()}),KC=N({title:S().optional(),readOnlyHint:qe().optional(),destructiveHint:qe().optional(),idempotentHint:qe().optional(),openWorldHint:qe().optional()}),GC=N({taskSupport:yt(["required","optional","forbidden"]).optional()}),tx=N({...Po.shape,...Zs.shape,description:S().optional(),inputSchema:N({type:U("object"),properties:be(S(),Ze).optional(),required:ie(S()).optional()}).catchall(Re()),outputSchema:N({type:U("object"),properties:be(S(),Ze).optional(),required:ie(S()).optional()}).catchall(Re()).optional(),annotations:KC.optional(),execution:GC.optional(),_meta:be(S(),Re()).optional()}),Ur=Bs.extend({method:U("tools/list")}),JC=qs.extend({tools:ie(tx)}),Ka=Ge.extend({content:ie(vp).default([]),structuredContent:be(S(),Re()).optional(),isError:qe().optional()}),SZ=Ka.or(Ge.extend({toolResult:Re()})),XC=Us.extend({name:S(),arguments:be(S(),Re()).optional()}),Ao=Ke.extend({method:U("tools/call"),params:XC}),YC=Mt.extend({method:U("notifications/tools/list_changed"),params:Dt.optional()}),bZ=N({autoRefresh:qe().default(!0),debounceMs:fe().int().nonnegative().default(300)}),Gs=yt(["debug","info","notice","warning","error","critical","alert","emergency"]),QC=Rt.extend({level:Gs}),Ep=Ke.extend({method:U("logging/setLevel"),params:QC}),e$=Dt.extend({level:Gs,logger:S().optional(),data:Re()}),t$=Mt.extend({method:U("notifications/message"),params:e$}),n$=N({name:S().optional()}),r$=N({hints:ie(n$).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),o$=N({mode:yt(["auto","required","none"]).optional()}),s$=N({type:U("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ie(vp).default([]),structuredContent:N({}).loose().optional(),isError:qe().optional(),_meta:be(S(),Re()).optional()}),i$=cp("type",[Sp,bp,kp]),Aa=cp("type",[Sp,bp,kp,FC,s$]),a$=N({role:Ks,content:ke([Aa,ie(Aa)]),_meta:be(S(),Re()).optional()}),c$=Us.extend({messages:ie(a$),modelPreferences:r$.optional(),systemPrompt:S().optional(),includeContext:yt(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ie(S()).optional(),metadata:Ze.optional(),tools:ie(tx).optional(),toolChoice:o$.optional()}),u$=Ke.extend({method:U("sampling/createMessage"),params:c$}),Js=Ge.extend({model:S(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens"]).or(S())),role:Ks,content:i$}),wp=Ge.extend({model:S(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:Ks,content:ke([Aa,ie(Aa)])}),l$=N({type:U("boolean"),title:S().optional(),description:S().optional(),default:qe().optional()}),d$=N({type:U("string"),title:S().optional(),description:S().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:yt(["email","uri","date","date-time"]).optional(),default:S().optional()}),p$=N({type:yt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),f$=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ie(S()),default:S().optional()}),m$=N({type:U("string"),title:S().optional(),description:S().optional(),oneOf:ie(N({const:S(),title:S()})),default:S().optional()}),h$=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ie(S()),enumNames:ie(S()).optional(),default:S().optional()}),g$=ke([f$,m$]),y$=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ie(S())}),default:ie(S()).optional()}),_$=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ie(N({const:S(),title:S()}))}),default:ie(S()).optional()}),x$=ke([y$,_$]),S$=ke([h$,g$,x$]),b$=ke([S$,l$,d$,p$]),k$=Us.extend({mode:U("form").optional(),message:S(),requestedSchema:N({type:U("object"),properties:be(S(),b$),required:ie(S()).optional()})}),v$=Us.extend({mode:U("url"),message:S(),elicitationId:S(),url:S().url()}),E$=ke([k$,v$]),w$=Ke.extend({method:U("elicitation/create"),params:E$}),T$=Dt.extend({elicitationId:S()}),P$=Mt.extend({method:U("notifications/elicitation/complete"),params:T$}),No=Ge.extend({action:yt(["accept","decline","cancel"]),content:up(t=>t===null?void 0:t,be(S(),ke([S(),fe(),qe(),ie(S())])).optional())}),R$=N({type:U("ref/resource"),uri:S()});var C$=N({type:U("ref/prompt"),name:S()}),$$=Rt.extend({ref:ke([C$,R$]),argument:N({name:S(),value:S()}),context:N({arguments:be(S(),S()).optional()}).optional()}),Ga=Ke.extend({method:U("completion/complete"),params:$$});function nx(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function rx(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var O$=Ge.extend({completion:at({values:ie(S()).max(100),total:Ce(fe().int()),hasMore:Ce(qe())})}),I$=N({uri:S().startsWith("file://"),name:S().optional(),_meta:be(S(),Re()).optional()}),A$=Ke.extend({method:U("roots/list"),params:Rt.optional()}),Tp=Ge.extend({roots:ie(I$)}),N$=Mt.extend({method:U("notifications/roots/list_changed"),params:Dt.optional()}),kZ=ke([za,gp,Ga,Ep,Wa,Io,$o,Oo,Va,AC,DC,Ao,Ur,Ha,Fa,Za,qa]),vZ=ke([ja,La,yp,N$,Ws]),EZ=ke([Ma,Js,wp,No,Tp,Ua,Ba,Ro]),wZ=ke([za,u$,w$,A$,Ha,Fa,Za,qa]),TZ=ke([ja,La,t$,jC,OC,YC,WC,Ws,P$]),PZ=ke([Ma,SC,O$,VC,HC,PC,RC,$C,Ka,JC,Ua,Ba,Ro]),L=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 lp(o.elicitations,n)}return new t(e,n,r)}},lp=class extends L{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function er(t){return t==="completed"||t==="failed"||t==="cancelled"}var sx=Symbol("Let zodToJsonSchema decide on which parser to use");var ox={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"},ix=t=>typeof t=="string"?{...ox,name:t}:{...ox,...t};var ax=t=>{let e=ix(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 Pp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,o){t[e]=n,Pp(t,e,r,o)}var Ja=(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"?Ja(e,t.currentPath):e.join("/")}}function cx(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==w.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ux(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?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}function lx(){return{type:"boolean"}}function Xa(t,e){return K(t.type._def,e)}var dx=(t,e)=>K(t.innerType._def,e);function Rp(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Rp(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 D$(t,e)}}var D$=(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":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n};function px(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function fx(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):$e(e)}function mx(t){return{type:"string",enum:Array.from(t.values)}}var M$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hx(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(M$(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 gx(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 Cp,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:()=>(Cp===void 0&&(Cp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cp),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 Ya(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(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(`^${$p(r.value,e)}`),r.message,e);break;case"endsWith":ct(n,RegExp(`${$p(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":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ct(n,RegExp($p(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":{ae(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 $p(t,e){return e.patternStrategy==="escape"?z$(t):t}var j$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z$(t){let e="";for(let n=0;n<t.length;n++)j$.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}}})):ae(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:yx(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",yx(e,r),n,r)}function yx(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
222
+ 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 ep(t,e){if(t instanceof Ms){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 u0=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");me.init(t,e),t.def=e,t.parse=(n,r)=>_l(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>Mr(t,n,r),t.parseAsync=async(n,r)=>Sl(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>jr(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)=>Pt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t))});var l0=k("ZodMiniObject",(t,e)=>{xa.init(t,e),u0.init(t,e),se.defineLazy(t,"shape",()=>e.shape)});function tp(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new l0(n)}function Nt(t){return!!t._zod}function Hr(t){let e=Object.values(t);if(e.length===0)return tp({});let n=e.every(Nt),r=e.every(o=>!Nt(o));if(n)return tp(t);if(r)return ol(t);throw new Error("Mixed Zod versions detected in object shape.")}function Xn(t,e){return Nt(t)?Mr(t,e):t.safeParse(e)}async function Ra(t,e){return Nt(t)?await jr(t,e):await t.safeParseAsync(e)}function Yn(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 To(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 Hr(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 Ca(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 g_(t){return t.description}function y_(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 $a(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 Ls={};De(Ls,{ZodISODate:()=>x_,ZodISODateTime:()=>__,ZodISODuration:()=>b_,ZodISOTime:()=>S_,date:()=>rp,datetime:()=>np,duration:()=>sp,time:()=>op});var __=k("ZodISODateTime",(t,e)=>{r_.init(t,e),Pe.init(t,e)});function np(t){return l_(__,t)}var x_=k("ZodISODate",(t,e)=>{o_.init(t,e),Pe.init(t,e)});function rp(t){return d_(x_,t)}var S_=k("ZodISOTime",(t,e)=>{s_.init(t,e),Pe.init(t,e)});function op(t){return p_(S_,t)}var b_=k("ZodISODuration",(t,e)=>{i_.init(t,e),Pe.init(t,e)});function sp(t){return f_(b_,t)}var k_=(t,e)=>{ma.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>gl(t,n)},flatten:{value:n=>hl(t,n)},addIssue:{value:n=>t.issues.push(n)},addIssues:{value:n=>t.issues.push(...n)},isEmpty:{get(){return t.issues.length===0}}})},oZ=k("ZodError",k_),Hs=k("ZodError",k_,{Parent:Error});var v_=yl(Hs),E_=xl(Hs),w_=bl(Hs),T_=kl(Hs);var Oe=k("ZodType",(t,e)=>(me.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)=>Pt(t,n,r),t.brand=()=>t,t.register=((n,r)=>(n.add(t,r),t)),t.parse=(n,r)=>v_(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>w_(t,n,r),t.parseAsync=async(n,r)=>E_(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>T_(t,n,r),t.spa=t.safeParseAsync,t.refine=(n,r)=>t.check(aC(n,r)),t.superRefine=n=>t.check(cC(n)),t.overwrite=n=>t.check(zr(n)),t.optional=()=>Ce(t),t.nullable=()=>C_(t),t.nullish=()=>Ce(C_(t)),t.nonoptional=n=>eC(t,n),t.array=()=>ie(t),t.or=n=>ke([t,n]),t.and=n=>Ia(t,n),t.transform=n=>ap(t,D_(n)),t.default=n=>X0(t,n),t.prefault=n=>Q0(t,n),t.catch=n=>nC(t,n),t.pipe=n=>ap(t,n),t.readonly=()=>sC(t),t.describe=n=>{let r=t.clone();return Jn.add(r,{description:n}),r},Object.defineProperty(t,"description",{get(){return Jn.get(t)?.description},configurable:!0}),t.meta=(...n)=>{if(n.length===0)return Jn.get(t);let r=t.clone();return Jn.add(r,n[0]),r},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),$_=k("_ZodString",(t,e)=>{Ds.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(Fd(...r)),t.includes=(...r)=>t.check(qd(...r)),t.startsWith=(...r)=>t.check(Vd(...r)),t.endsWith=(...r)=>t.check(Wd(...r)),t.min=(...r)=>t.check(wo(...r)),t.max=(...r)=>t.check(wa(...r)),t.length=(...r)=>t.check(Ta(...r)),t.nonempty=(...r)=>t.check(wo(1,...r)),t.lowercase=r=>t.check(Zd(r)),t.uppercase=r=>t.check(Bd(r)),t.trim=()=>t.check(Gd()),t.normalize=(...r)=>t.check(Kd(...r)),t.toLowerCase=()=>t.check(Jd()),t.toUpperCase=()=>t.check(Xd())}),x0=k("ZodString",(t,e)=>{Ds.init(t,e),$_.init(t,e),t.email=n=>t.check(hd(S0,n)),t.url=n=>t.check(Sd(b0,n)),t.jwt=n=>t.check(Dd(M0,n)),t.emoji=n=>t.check(bd(k0,n)),t.guid=n=>t.check(ba(P_,n)),t.uuid=n=>t.check(gd(Oa,n)),t.uuidv4=n=>t.check(yd(Oa,n)),t.uuidv6=n=>t.check(_d(Oa,n)),t.uuidv7=n=>t.check(xd(Oa,n)),t.nanoid=n=>t.check(kd(v0,n)),t.guid=n=>t.check(ba(P_,n)),t.cuid=n=>t.check(vd(E0,n)),t.cuid2=n=>t.check(Ed(w0,n)),t.ulid=n=>t.check(wd(T0,n)),t.base64=n=>t.check(Id(A0,n)),t.base64url=n=>t.check(Ad(N0,n)),t.xid=n=>t.check(Td(P0,n)),t.ksuid=n=>t.check(Pd(R0,n)),t.ipv4=n=>t.check(Rd(C0,n)),t.ipv6=n=>t.check(Cd($0,n)),t.cidrv4=n=>t.check($d(O0,n)),t.cidrv6=n=>t.check(Od(I0,n)),t.e164=n=>t.check(Nd(D0,n)),t.datetime=n=>t.check(np(n)),t.date=n=>t.check(rp(n)),t.time=n=>t.check(op(n)),t.duration=n=>t.check(sp(n))});function S(t){return md(x0,t)}var Pe=k("ZodStringFormat",(t,e)=>{Se.init(t,e),$_.init(t,e)}),S0=k("ZodEmail",(t,e)=>{$l.init(t,e),Pe.init(t,e)});var P_=k("ZodGUID",(t,e)=>{Rl.init(t,e),Pe.init(t,e)});var Oa=k("ZodUUID",(t,e)=>{Cl.init(t,e),Pe.init(t,e)});var b0=k("ZodURL",(t,e)=>{Ol.init(t,e),Pe.init(t,e)});var k0=k("ZodEmoji",(t,e)=>{Il.init(t,e),Pe.init(t,e)});var v0=k("ZodNanoID",(t,e)=>{Al.init(t,e),Pe.init(t,e)});var E0=k("ZodCUID",(t,e)=>{Nl.init(t,e),Pe.init(t,e)});var w0=k("ZodCUID2",(t,e)=>{Dl.init(t,e),Pe.init(t,e)});var T0=k("ZodULID",(t,e)=>{Ml.init(t,e),Pe.init(t,e)});var P0=k("ZodXID",(t,e)=>{jl.init(t,e),Pe.init(t,e)});var R0=k("ZodKSUID",(t,e)=>{zl.init(t,e),Pe.init(t,e)});var C0=k("ZodIPv4",(t,e)=>{Ll.init(t,e),Pe.init(t,e)});var $0=k("ZodIPv6",(t,e)=>{Hl.init(t,e),Pe.init(t,e)});var O0=k("ZodCIDRv4",(t,e)=>{Ul.init(t,e),Pe.init(t,e)});var I0=k("ZodCIDRv6",(t,e)=>{Fl.init(t,e),Pe.init(t,e)});var A0=k("ZodBase64",(t,e)=>{Zl.init(t,e),Pe.init(t,e)});var N0=k("ZodBase64URL",(t,e)=>{Bl.init(t,e),Pe.init(t,e)});var D0=k("ZodE164",(t,e)=>{ql.init(t,e),Pe.init(t,e)});var M0=k("ZodJWT",(t,e)=>{Vl.init(t,e),Pe.init(t,e)});var O_=k("ZodNumber",(t,e)=>{_a.init(t,e),Oe.init(t,e),t.gt=(r,o)=>t.check(va(r,o)),t.gte=(r,o)=>t.check(zs(r,o)),t.min=(r,o)=>t.check(zs(r,o)),t.lt=(r,o)=>t.check(ka(r,o)),t.lte=(r,o)=>t.check(js(r,o)),t.max=(r,o)=>t.check(js(r,o)),t.int=r=>t.check(R_(r)),t.safe=r=>t.check(R_(r)),t.positive=r=>t.check(va(0,r)),t.nonnegative=r=>t.check(zs(0,r)),t.negative=r=>t.check(ka(0,r)),t.nonpositive=r=>t.check(js(0,r)),t.multipleOf=(r,o)=>t.check(Ea(r,o)),t.step=(r,o)=>t.check(Ea(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 Md(O_,t)}var j0=k("ZodNumberFormat",(t,e)=>{Wl.init(t,e),O_.init(t,e)});function R_(t){return jd(j0,t)}var z0=k("ZodBoolean",(t,e)=>{Kl.init(t,e),Oe.init(t,e)});function qe(t){return zd(z0,t)}var L0=k("ZodNull",(t,e)=>{Gl.init(t,e),Oe.init(t,e)});function I_(t){return Ld(L0,t)}var H0=k("ZodUnknown",(t,e)=>{Jl.init(t,e),Oe.init(t,e)});function Re(){return Hd(H0)}var U0=k("ZodNever",(t,e)=>{Xl.init(t,e),Oe.init(t,e)});function F0(t){return Ud(U0,t)}var Z0=k("ZodArray",(t,e)=>{Yl.init(t,e),Oe.init(t,e),t.element=e.element,t.min=(n,r)=>t.check(wo(n,r)),t.nonempty=n=>t.check(wo(1,n)),t.max=(n,r)=>t.check(wa(n,r)),t.length=(n,r)=>t.check(Ta(n,r)),t.unwrap=()=>t.element});function ie(t,e){return m_(Z0,t,e)}var A_=k("ZodObject",(t,e)=>{xa.init(t,e),Oe.init(t,e),se.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>yt(Object.keys(t._zod.def.shape)),t.catchall=n=>t.clone({...t._zod.def,catchall:n}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Re()}),t.loose=()=>t.clone({...t._zod.def,catchall:Re()}),t.strict=()=>t.clone({...t._zod.def,catchall:F0()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=n=>se.extend(t,n),t.merge=n=>se.merge(t,n),t.pick=n=>se.pick(t,n),t.omit=n=>se.omit(t,n),t.partial=(...n)=>se.partial(M_,t,n[0]),t.required=(...n)=>se.required(j_,t,n[0])});function N(t,e){let n={type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},...se.normalizeParams(e)};return new A_(n)}function at(t,e){return new A_({type:"object",get shape(){return se.assignProp(this,"shape",{...t}),this.shape},catchall:Re(),...se.normalizeParams(e)})}var N_=k("ZodUnion",(t,e)=>{Sa.init(t,e),Oe.init(t,e),t.options=e.options});function ke(t,e){return new N_({type:"union",options:t,...se.normalizeParams(e)})}var B0=k("ZodDiscriminatedUnion",(t,e)=>{N_.init(t,e),Ql.init(t,e)});function cp(t,e,n){return new B0({type:"union",options:e,discriminator:t,...se.normalizeParams(n)})}var q0=k("ZodIntersection",(t,e)=>{ed.init(t,e),Oe.init(t,e)});function Ia(t,e){return new q0({type:"intersection",left:t,right:e})}var V0=k("ZodRecord",(t,e)=>{td.init(t,e),Oe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});function be(t,e,n){return new V0({type:"record",keyType:t,valueType:e,...se.normalizeParams(n)})}var ip=k("ZodEnum",(t,e)=>{nd.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 ip({...e,checks:[],...se.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 ip({...e,checks:[],...se.normalizeParams(o),entries:s})}});function yt(t,e){let n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new ip({type:"enum",entries:n,...se.normalizeParams(e)})}var W0=k("ZodLiteral",(t,e)=>{rd.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 W0({type:"literal",values:Array.isArray(t)?t:[t],...se.normalizeParams(e)})}var K0=k("ZodTransform",(t,e)=>{od.init(t,e),Oe.init(t,e),t._zod.parse=(n,r)=>{n.addIssue=s=>{if(typeof s=="string")n.issues.push(se.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(se.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 D_(t){return new K0({type:"transform",transform:t})}var M_=k("ZodOptional",(t,e)=>{sd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Ce(t){return new M_({type:"optional",innerType:t})}var G0=k("ZodNullable",(t,e)=>{id.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function C_(t){return new G0({type:"nullable",innerType:t})}var J0=k("ZodDefault",(t,e)=>{ad.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function X0(t,e){return new J0({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var Y0=k("ZodPrefault",(t,e)=>{cd.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function Q0(t,e){return new Y0({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}var j_=k("ZodNonOptional",(t,e)=>{ud.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType});function eC(t,e){return new j_({type:"nonoptional",innerType:t,...se.normalizeParams(e)})}var tC=k("ZodCatch",(t,e)=>{ld.init(t,e),Oe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function nC(t,e){return new tC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}var rC=k("ZodPipe",(t,e)=>{dd.init(t,e),Oe.init(t,e),t.in=e.in,t.out=e.out});function ap(t,e){return new rC({type:"pipe",in:t,out:e})}var oC=k("ZodReadonly",(t,e)=>{pd.init(t,e),Oe.init(t,e)});function sC(t){return new oC({type:"readonly",innerType:t})}var z_=k("ZodCustom",(t,e)=>{fd.init(t,e),Oe.init(t,e)});function iC(t){let e=new We({check:"custom"});return e._zod.check=t,e}function L_(t,e){return Yd(z_,t??(()=>!0),e)}function aC(t,e={}){return Qd(z_,t,e)}function cC(t){let e=iC(n=>(n.addIssue=r=>{if(typeof r=="string")n.issues.push(se.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(se.issue(o))}},t(n.value,n)));return e}function up(t,e){return ap(D_(t),e)}Tt(c_());var dp="2025-11-25";var H_=[dp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Qn="io.modelcontextprotocol/related-task",Na="2.0",Ze=L_(t=>t!==null&&(typeof t=="object"||typeof t=="function")),U_=ke([S(),fe().int()]),F_=S(),_Z=at({ttl:fe().optional(),pollInterval:fe().optional()}),uC=N({ttl:fe().optional()}),lC=N({taskId:S()}),pp=at({progressToken:U_.optional(),[Qn]:lC.optional()}),Rt=N({_meta:pp.optional()}),Us=Rt.extend({task:uC.optional()}),Z_=t=>Us.safeParse(t).success,Ke=N({method:S(),params:Rt.loose().optional()}),Dt=N({_meta:pp.optional()}),Mt=N({method:S(),params:Dt.loose().optional()}),Ge=at({_meta:pp.optional()}),Da=ke([S(),fe().int()]),B_=N({jsonrpc:U(Na),id:Da,...Ke.shape}).strict(),fp=t=>B_.safeParse(t).success,q_=N({jsonrpc:U(Na),...Mt.shape}).strict(),V_=t=>q_.safeParse(t).success,mp=N({jsonrpc:U(Na),id:Da,result:Ge}).strict(),Fs=t=>mp.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 hp=N({jsonrpc:U(Na),id:Da.optional(),error:N({code:fe().int(),message:S(),data:Re().optional()})}).strict();var W_=t=>hp.safeParse(t).success;var K_=ke([B_,q_,mp,hp]),xZ=ke([mp,hp]),Ma=Ge.strict(),dC=Dt.extend({requestId:Da.optional(),reason:S().optional()}),ja=Mt.extend({method:U("notifications/cancelled"),params:dC}),pC=N({src:S(),mimeType:S().optional(),sizes:ie(S()).optional(),theme:yt(["light","dark"]).optional()}),Zs=N({icons:ie(pC).optional()}),Po=N({name:S(),title:S().optional()}),G_=Po.extend({...Po.shape,...Zs.shape,version:S(),websiteUrl:S().optional(),description:S().optional()}),fC=Ia(N({applyDefaults:qe().optional()}),be(S(),Re())),mC=up(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ia(N({form:fC.optional(),url:Ze.optional()}),be(S(),Re()).optional())),hC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({sampling:at({createMessage:Ze.optional()}).optional(),elicitation:at({create:Ze.optional()}).optional()}).optional()}),gC=at({list:Ze.optional(),cancel:Ze.optional(),requests:at({tools:at({call:Ze.optional()}).optional()}).optional()}),yC=N({experimental:be(S(),Ze).optional(),sampling:N({context:Ze.optional(),tools:Ze.optional()}).optional(),elicitation:mC.optional(),roots:N({listChanged:qe().optional()}).optional(),tasks:hC.optional(),extensions:be(S(),Ze).optional()}),_C=Rt.extend({protocolVersion:S(),capabilities:yC,clientInfo:G_}),gp=Ke.extend({method:U("initialize"),params:_C});var xC=N({experimental:be(S(),Ze).optional(),logging:Ze.optional(),completions:Ze.optional(),prompts:N({listChanged:qe().optional()}).optional(),resources:N({subscribe:qe().optional(),listChanged:qe().optional()}).optional(),tools:N({listChanged:qe().optional()}).optional(),tasks:gC.optional(),extensions:be(S(),Ze).optional()}),SC=Ge.extend({protocolVersion:S(),capabilities:xC,serverInfo:G_,instructions:S().optional()}),yp=Mt.extend({method:U("notifications/initialized"),params:Dt.optional()});var za=Ke.extend({method:U("ping"),params:Rt.optional()}),bC=N({progress:fe(),total:Ce(fe()),message:Ce(S())}),kC=N({...Dt.shape,...bC.shape,progressToken:U_}),La=Mt.extend({method:U("notifications/progress"),params:kC}),vC=Rt.extend({cursor:F_.optional()}),Bs=Ke.extend({params:vC.optional()}),qs=Ge.extend({nextCursor:F_.optional()}),EC=yt(["working","input_required","completed","failed","cancelled"]),Vs=N({taskId:S(),status:EC,ttl:ke([fe(),I_()]),createdAt:S(),lastUpdatedAt:S(),pollInterval:Ce(fe()),statusMessage:Ce(S())}),Ro=Ge.extend({task:Vs}),wC=Dt.merge(Vs),Ws=Mt.extend({method:U("notifications/tasks/status"),params:wC}),Ha=Ke.extend({method:U("tasks/get"),params:Rt.extend({taskId:S()})}),Ua=Ge.merge(Vs),Fa=Ke.extend({method:U("tasks/result"),params:Rt.extend({taskId:S()})}),SZ=Ge.loose(),Za=Bs.extend({method:U("tasks/list")}),Ba=qs.extend({tasks:ie(Vs)}),qa=Ke.extend({method:U("tasks/cancel"),params:Rt.extend({taskId:S()})}),J_=Ge.merge(Vs),X_=N({uri:S(),mimeType:Ce(S()),_meta:be(S(),Re()).optional()}),Y_=X_.extend({text:S()}),_p=S().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Q_=X_.extend({blob:_p}),Ks=yt(["user","assistant"]),Co=N({audience:ie(Ks).optional(),priority:fe().min(0).max(1).optional(),lastModified:Ls.datetime({offset:!0}).optional()}),ex=N({...Po.shape,...Zs.shape,uri:S(),description:Ce(S()),mimeType:Ce(S()),size:Ce(fe()),annotations:Co.optional(),_meta:Ce(at({}))}),TC=N({...Po.shape,...Zs.shape,uriTemplate:S(),description:Ce(S()),mimeType:Ce(S()),annotations:Co.optional(),_meta:Ce(at({}))}),$o=Bs.extend({method:U("resources/list")}),PC=qs.extend({resources:ie(ex)}),Oo=Bs.extend({method:U("resources/templates/list")}),RC=qs.extend({resourceTemplates:ie(TC)}),xp=Rt.extend({uri:S()}),CC=xp,Va=Ke.extend({method:U("resources/read"),params:CC}),$C=Ge.extend({contents:ie(ke([Y_,Q_]))}),OC=Mt.extend({method:U("notifications/resources/list_changed"),params:Dt.optional()}),IC=xp,AC=Ke.extend({method:U("resources/subscribe"),params:IC}),NC=xp,DC=Ke.extend({method:U("resources/unsubscribe"),params:NC}),MC=Dt.extend({uri:S()}),jC=Mt.extend({method:U("notifications/resources/updated"),params:MC}),zC=N({name:S(),description:Ce(S()),required:Ce(qe())}),LC=N({...Po.shape,...Zs.shape,description:Ce(S()),arguments:Ce(ie(zC)),_meta:Ce(at({}))}),Io=Bs.extend({method:U("prompts/list")}),HC=qs.extend({prompts:ie(LC)}),UC=Rt.extend({name:S(),arguments:be(S(),S()).optional()}),Wa=Ke.extend({method:U("prompts/get"),params:UC}),Sp=N({type:U("text"),text:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),bp=N({type:U("image"),data:_p,mimeType:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),kp=N({type:U("audio"),data:_p,mimeType:S(),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),FC=N({type:U("tool_use"),name:S(),id:S(),input:be(S(),Re()),_meta:be(S(),Re()).optional()}),ZC=N({type:U("resource"),resource:ke([Y_,Q_]),annotations:Co.optional(),_meta:be(S(),Re()).optional()}),BC=ex.extend({type:U("resource_link")}),vp=ke([Sp,bp,kp,BC,ZC]),qC=N({role:Ks,content:vp}),VC=Ge.extend({description:S().optional(),messages:ie(qC)}),WC=Mt.extend({method:U("notifications/prompts/list_changed"),params:Dt.optional()}),KC=N({title:S().optional(),readOnlyHint:qe().optional(),destructiveHint:qe().optional(),idempotentHint:qe().optional(),openWorldHint:qe().optional()}),GC=N({taskSupport:yt(["required","optional","forbidden"]).optional()}),tx=N({...Po.shape,...Zs.shape,description:S().optional(),inputSchema:N({type:U("object"),properties:be(S(),Ze).optional(),required:ie(S()).optional()}).catchall(Re()),outputSchema:N({type:U("object"),properties:be(S(),Ze).optional(),required:ie(S()).optional()}).catchall(Re()).optional(),annotations:KC.optional(),execution:GC.optional(),_meta:be(S(),Re()).optional()}),Ur=Bs.extend({method:U("tools/list")}),JC=qs.extend({tools:ie(tx)}),Ka=Ge.extend({content:ie(vp).default([]),structuredContent:be(S(),Re()).optional(),isError:qe().optional()}),bZ=Ka.or(Ge.extend({toolResult:Re()})),XC=Us.extend({name:S(),arguments:be(S(),Re()).optional()}),Ao=Ke.extend({method:U("tools/call"),params:XC}),YC=Mt.extend({method:U("notifications/tools/list_changed"),params:Dt.optional()}),kZ=N({autoRefresh:qe().default(!0),debounceMs:fe().int().nonnegative().default(300)}),Gs=yt(["debug","info","notice","warning","error","critical","alert","emergency"]),QC=Rt.extend({level:Gs}),Ep=Ke.extend({method:U("logging/setLevel"),params:QC}),e$=Dt.extend({level:Gs,logger:S().optional(),data:Re()}),t$=Mt.extend({method:U("notifications/message"),params:e$}),n$=N({name:S().optional()}),r$=N({hints:ie(n$).optional(),costPriority:fe().min(0).max(1).optional(),speedPriority:fe().min(0).max(1).optional(),intelligencePriority:fe().min(0).max(1).optional()}),o$=N({mode:yt(["auto","required","none"]).optional()}),s$=N({type:U("tool_result"),toolUseId:S().describe("The unique identifier for the corresponding tool call."),content:ie(vp).default([]),structuredContent:N({}).loose().optional(),isError:qe().optional(),_meta:be(S(),Re()).optional()}),i$=cp("type",[Sp,bp,kp]),Aa=cp("type",[Sp,bp,kp,FC,s$]),a$=N({role:Ks,content:ke([Aa,ie(Aa)]),_meta:be(S(),Re()).optional()}),c$=Us.extend({messages:ie(a$),modelPreferences:r$.optional(),systemPrompt:S().optional(),includeContext:yt(["none","thisServer","allServers"]).optional(),temperature:fe().optional(),maxTokens:fe().int(),stopSequences:ie(S()).optional(),metadata:Ze.optional(),tools:ie(tx).optional(),toolChoice:o$.optional()}),u$=Ke.extend({method:U("sampling/createMessage"),params:c$}),Js=Ge.extend({model:S(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens"]).or(S())),role:Ks,content:i$}),wp=Ge.extend({model:S(),stopReason:Ce(yt(["endTurn","stopSequence","maxTokens","toolUse"]).or(S())),role:Ks,content:ke([Aa,ie(Aa)])}),l$=N({type:U("boolean"),title:S().optional(),description:S().optional(),default:qe().optional()}),d$=N({type:U("string"),title:S().optional(),description:S().optional(),minLength:fe().optional(),maxLength:fe().optional(),format:yt(["email","uri","date","date-time"]).optional(),default:S().optional()}),p$=N({type:yt(["number","integer"]),title:S().optional(),description:S().optional(),minimum:fe().optional(),maximum:fe().optional(),default:fe().optional()}),f$=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ie(S()),default:S().optional()}),m$=N({type:U("string"),title:S().optional(),description:S().optional(),oneOf:ie(N({const:S(),title:S()})),default:S().optional()}),h$=N({type:U("string"),title:S().optional(),description:S().optional(),enum:ie(S()),enumNames:ie(S()).optional(),default:S().optional()}),g$=ke([f$,m$]),y$=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({type:U("string"),enum:ie(S())}),default:ie(S()).optional()}),_$=N({type:U("array"),title:S().optional(),description:S().optional(),minItems:fe().optional(),maxItems:fe().optional(),items:N({anyOf:ie(N({const:S(),title:S()}))}),default:ie(S()).optional()}),x$=ke([y$,_$]),S$=ke([h$,g$,x$]),b$=ke([S$,l$,d$,p$]),k$=Us.extend({mode:U("form").optional(),message:S(),requestedSchema:N({type:U("object"),properties:be(S(),b$),required:ie(S()).optional()})}),v$=Us.extend({mode:U("url"),message:S(),elicitationId:S(),url:S().url()}),E$=ke([k$,v$]),w$=Ke.extend({method:U("elicitation/create"),params:E$}),T$=Dt.extend({elicitationId:S()}),P$=Mt.extend({method:U("notifications/elicitation/complete"),params:T$}),No=Ge.extend({action:yt(["accept","decline","cancel"]),content:up(t=>t===null?void 0:t,be(S(),ke([S(),fe(),qe(),ie(S())])).optional())}),R$=N({type:U("ref/resource"),uri:S()});var C$=N({type:U("ref/prompt"),name:S()}),$$=Rt.extend({ref:ke([C$,R$]),argument:N({name:S(),value:S()}),context:N({arguments:be(S(),S()).optional()}).optional()}),Ga=Ke.extend({method:U("completion/complete"),params:$$});function nx(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function rx(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var O$=Ge.extend({completion:at({values:ie(S()).max(100),total:Ce(fe().int()),hasMore:Ce(qe())})}),I$=N({uri:S().startsWith("file://"),name:S().optional(),_meta:be(S(),Re()).optional()}),A$=Ke.extend({method:U("roots/list"),params:Rt.optional()}),Tp=Ge.extend({roots:ie(I$)}),N$=Mt.extend({method:U("notifications/roots/list_changed"),params:Dt.optional()}),vZ=ke([za,gp,Ga,Ep,Wa,Io,$o,Oo,Va,AC,DC,Ao,Ur,Ha,Fa,Za,qa]),EZ=ke([ja,La,yp,N$,Ws]),wZ=ke([Ma,Js,wp,No,Tp,Ua,Ba,Ro]),TZ=ke([za,u$,w$,A$,Ha,Fa,Za,qa]),PZ=ke([ja,La,t$,jC,OC,YC,WC,Ws,P$]),RZ=ke([Ma,SC,O$,VC,HC,PC,RC,$C,Ka,JC,Ua,Ba,Ro]),L=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 lp(o.elicitations,n)}return new t(e,n,r)}},lp=class extends L{constructor(e,n=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,n,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function er(t){return t==="completed"||t==="failed"||t==="cancelled"}var sx=Symbol("Let zodToJsonSchema decide on which parser to use");var ox={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"},ix=t=>typeof t=="string"?{...ox,name:t}:{...ox,...t};var ax=t=>{let e=ix(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 Pp(t,e,n,r){r?.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ae(t,e,n,r,o){t[e]=n,Pp(t,e,r,o)}var Ja=(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"?Ja(e,t.currentPath):e.join("/")}}function cx(t,e){let n={type:"array"};return t.type?._def&&t.type?._def?.typeName!==w.ZodAny&&(n.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ae(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ae(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ae(n,"minItems",t.exactLength.value,t.exactLength.message,e),ae(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function ux(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?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}function lx(){return{type:"boolean"}}function Xa(t,e){return K(t.type._def,e)}var dx=(t,e)=>K(t.innerType._def,e);function Rp(t,e,n){let r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((o,s)=>Rp(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 D$(t,e)}}var D$=(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":ae(n,"minimum",r.value,r.message,e);break;case"max":ae(n,"maximum",r.value,r.message,e);break}return n};function px(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}function fx(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):$e(e)}function mx(t){return{type:"string",enum:Array.from(t.values)}}var M$=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function hx(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(M$(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 gx(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 Cp,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:()=>(Cp===void 0&&(Cp=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Cp),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 Ya(t,e){let n={type:"string"};if(t.checks)for(let r of t.checks)switch(r.kind){case"min":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ae(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(`^${$p(r.value,e)}`),r.message,e);break;case"endsWith":ct(n,RegExp(`${$p(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":ae(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ae(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":{ct(n,RegExp($p(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":{ae(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 $p(t,e){return e.patternStrategy==="escape"?z$(t):t}var j$=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function z$(t){let e="";for(let n=0;n<t.length;n++)j$.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}}})):ae(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:yx(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ae(t,"pattern",yx(e,r),n,r)}function yx(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<r.length;c++){if(s){o+=r[c],s=!1;continue}if(n.i){if(i){if(r[c].match(/[a-z]/)){a?(o+=r[c],o+=`${r[c-2]}-${r[c]}`.toUpperCase(),a=!1):r[c+1]==="-"&&r[c+2]?.match(/[a-z]/)?(o+=r[c],a=!0):o+=`${r[c]}${r[c].toUpperCase()}`;continue}}else if(r[c].match(/[a-z]/)){o+=`[${r[c]}${r[c].toUpperCase()}]`;continue}}if(n.m){if(r[c]==="^"){o+=`(^|(?<=[\r
223
223
  ]))`;continue}else if(r[c]==="$"){o+=`($|(?=[\r
224
224
  ]))`;continue}}if(n.s&&r[c]==="."){o+=i?`${r[c]}\r
225
225
  `:`[${r[c]}\r
226
226
  ]`;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 Qa(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===w.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((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===w.ZodString&&t.keyType._def.checks?.length){let{type:r,...o}=Ya(t.keyType._def,e);return{...n,propertyNames:o}}else{if(t.keyType?._def.typeName===w.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===w.ZodBranded&&t.keyType._def.type._def.typeName===w.ZodString&&t.keyType._def.type._def.checks?.length){let{type:r,...o}=Xa(t.keyType._def,e);return{...n,propertyNames:o}}}return n}function _x(t,e){if(e.mapStrategy==="record")return Qa(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 xx(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 Sx(t){return t.target==="openAi"?void 0:{not:$e({...t,currentPath:[...t.currentPath,"not"]})}}function bx(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Xs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function vx(t,e){if(e.target==="openApi3")return kx(t,e);let n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Xs&&(!r._def.checks||!r._def.checks.length))){let r=n.reduce((o,s)=>{let i=Xs[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 kx(t,e)}var kx=(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 Ex(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:Xs[t.innerType._def.typeName],nullable:!0}:{type:[Xs[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 wx(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",Pp(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ae(n,"minimum",r.value,r.message,e):ae(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ae(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ae(n,"maximum",r.value,r.message,e):ae(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ae(n,"maximum",r.value,r.message,e));break;case"multipleOf":ae(n,"multipleOf",r.value,r.message,e);break}return n}function Tx(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=H$(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=L$(t,e);return i!==void 0&&(r.additionalProperties=i),r}function L$(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 H$(t){try{return t.isOptional()}catch{return!0}}var Px=(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 Rx=(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 Cx(t,e){return K(t.type._def,e)}function $x(t,e){let r={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ae(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ae(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function Ox(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 Ix(t){return{not:$e(t)}}function Ax(t){return $e(t)}var Nx=(t,e)=>K(t.innerType._def,e);var Dx=(t,e,n)=>{switch(e){case w.ZodString:return Ya(t,n);case w.ZodNumber:return wx(t,n);case w.ZodObject:return Tx(t,n);case w.ZodBigInt:return ux(t,n);case w.ZodBoolean:return lx();case w.ZodDate:return Rp(t,n);case w.ZodUndefined:return Ix(n);case w.ZodNull:return bx(n);case w.ZodArray:return cx(t,n);case w.ZodUnion:case w.ZodDiscriminatedUnion:return vx(t,n);case w.ZodIntersection:return hx(t,n);case w.ZodTuple:return Ox(t,n);case w.ZodRecord:return Qa(t,n);case w.ZodLiteral:return gx(t,n);case w.ZodEnum:return mx(t);case w.ZodNativeEnum:return xx(t);case w.ZodNullable:return Ex(t,n);case w.ZodOptional:return Px(t,n);case w.ZodMap:return _x(t,n);case w.ZodSet:return $x(t,n);case w.ZodLazy:return()=>t.getter()._def;case w.ZodPromise:return Cx(t,n);case w.ZodNaN:case w.ZodNever:return Sx(n);case w.ZodEffects:return fx(t,n);case w.ZodAny:return $e(n);case w.ZodUnknown:return Ax(n);case w.ZodDefault:return px(t,n);case w.ZodBranded:return Xa(t,n);case w.ZodReadonly:return Nx(t,n);case w.ZodCatch:return dx(t,n);case w.ZodPipeline:return Rx(t,n);case w.ZodFunction:case w.ZodVoid:case w.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!==sx)return a}if(r&&!n){let a=U$(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=Dx(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&F$(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var U$=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ja(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}},F$=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n);var Op=(t,e)=>{let n=ax(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 Z$(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Ip(t,e){return Nt(t)?ep(t,{target:Z$(e?.target),io:e?.pipeStrategy??"input"}):Op(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ap(t){let n=Yn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=$a(n);if(typeof r!="string")throw new Error("Schema method literal must be a string");return r}function Np(t,e){let n=Xn(t,e);if(!n.success)throw n.error;return n.data}var B$=6e4,ec=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(ja,n=>{this._oncancel(n)}),this.setNotificationHandler(La,n=>{this._onprogress(n)}),this.setRequestHandler(za,n=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ha,async(n,r)=>{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new L(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Fa,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 L(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 L(Z.InvalidParams,`Task not found: ${s}`);if(!er(i.status))return await this._waitForTaskUpdate(s,r.signal),await o();if(er(i.status)){let a=await this._taskStore.getTaskResult(s,r.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Qn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Za,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 L(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(qa,async(n,r)=>{try{let o=await this._taskStore.getTask(n.params.taskId,r.sessionId);if(!o)throw new L(Z.InvalidParams,`Task not found: ${n.params.taskId}`);if(er(o.status))throw new L(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 L(Z.InvalidParams,`Task not found after cancellation: ${n.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof L?o:new L(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),L.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),Fs(s)||W_(s)?this._onresponse(s):fp(s)?this._onrequest(s,i):V_(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=L.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?.[Qn]?.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=Z_(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 L(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),Fs(e))r(e);else{let i=new L(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(Fs(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),Fs(e))o(e);else{let i=L.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 L?i:new L(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ro,r);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new L(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},r);if(yield{type:"taskStatus",task:a},er(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},n,r)}:a.status==="failed"?yield{type:"error",error:new L(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new L(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 L?i:new L(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||{},[Qn]:c}});let p=_=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>this._onerror(new Error(`Failed to send cancellation: ${b}`)));let x=_ instanceof L?_:new L(Z.RequestTimeout,String(_));l(x)};this._responseHandlers.set(f,_=>{if(!r?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Xn(n,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),r?.signal?.addEventListener("abort",()=>{p(r?.signal?.reason)});let h=r?.timeout??B$,g=()=>p(L.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 _=x=>{let b=this._responseHandlers.get(f);b?b(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,_),this._enqueueTaskMessage(y,{type:"request",message:m,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),l(x)})}else this._transport.send(m,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(f),l(_)})})}async getTask(e,n){return this.request({method:"tasks/get",params:e},Ua,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},Ba,n)}async cancelTask(e,n){return this.request({method:"tasks/cancel",params:e},J_,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||{},[Qn]: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||{},[Qn]: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||{},[Qn]:n.relatedTask}}}),await this._transport.send(i,n)}setRequestHandler(e,n){let r=Ap(e);this.assertRequestHandlerCapability(r),this._requestHandlers.set(r,(o,s)=>{let i=Np(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=Ap(e);this._notificationHandlers.set(r,o=>{let s=Np(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"&&fp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new L(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 L(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,r);n.addEventListener("abort",()=>{clearTimeout(i),s(new L(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 L(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=Ws.parse({method:"notifications/tasks/status",params:a});await this.notification(c),er(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 L(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(er(a.status))throw new L(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=Ws.parse({method:"notifications/tasks/status",params:c});await this.notification(u),er(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>r.listTasks(o,n)}}};function Mx(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function jx(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];Mx(i)&&Mx(s)?n[o]={...i,...s}:n[o]=s}return n}var vk=Fg(Sm(),1),Ek=Fg(kk(),1);function DM(){let t=new vk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,Ek.default)(t),t}var Mc=class{constructor(e){this._ajv=e??DM()}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 jc=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},Js,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},No,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 wk(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 Tk(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 ec{constructor(e,n){super(n),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Gs.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 Mc,this.setRequestHandler(gp,r=>this._oninitialize(r)),this.setNotificationHandler(yp,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ep,async(r,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=r.params,a=Gs.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new jc(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=jx(this._capabilities,e)}setRequestHandler(e,n){let o=Yn(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=Xn(Ao,c);if(!l.success){let p=l.error instanceof Error?l.error.message:String(l.error);throw new L(Z.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:d}=l.data,f=await Promise.resolve(n(c,u));if(d.task){let p=Xn(Ro,f);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new L(Z.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let m=Xn(Ka,f);if(!m.success){let p=m.error instanceof Error?m.error.message:String(m.error);throw new L(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){Tk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&wk(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:H_.includes(n)?n:dp,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"},Ma)}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},wp,n):this.request({method:"sampling/createMessage",params:e},Js,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},No,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},No,n);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new L(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof L?i:new L(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},Tp,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 Rk=Symbol.for("mcp.completable");function Rm(t){return!!t&&typeof t=="object"&&Rk in t}function Ck(t){return t[Rk]?.complete}var Pk;(function(t){t.Completable="McpCompletable"})(Pk||(Pk={}));var MM=/^[A-Za-z0-9._-]{1,128}$/;function jM(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"),!MM.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 zM(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 Cm(t){let e=jM(t);return zM(t,e.warnings),e.isValid}var Lc=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 Hc=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 Lc(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Ur)),this.server.assertCanSetRequestHandler(ur(Ao)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ur,()=>({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=To(n.inputSchema);return o?Ip(o,{strictUnions:!0,pipeStrategy:"input"}):LM})(),annotations:n.annotations,execution:n.execution,_meta:n._meta};if(n.outputSchema){let o=To(n.outputSchema);o&&(r.outputSchema=Ip(o,{strictUnions:!0,pipeStrategy:"output"}))}return r})})),this.server.setRequestHandler(Ao,async(e,n)=>{try{let r=this._registeredTools[e.params.name];if(!r)throw new L(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!r.enabled)throw new L(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 L(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new L(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 L&&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=To(e.inputSchema)??e.inputSchema,i=await Ra(s,n);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Ca(a);throw new L(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 L(Z.InvalidParams,`Output validation error: Tool ${r} has an output schema but no structured content was provided`);let o=To(e.outputSchema),s=await Ra(o,n.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Ca(i);throw new L(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 L(Z.InternalError,`Task ${c} not found during polling`);u=d}return await r.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ur(Ga)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Ga,async e=>{switch(e.params.ref.type){case"ref/prompt":return nx(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return rx(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(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 L(Z.InvalidParams,`Prompt ${n.name} not found`);if(!r.enabled)throw new L(Z.InvalidParams,`Prompt ${n.name} disabled`);if(!r.argsSchema)return Pi;let s=Yn(r.argsSchema)?.[e.params.argument.name];if(!Rm(s))return Pi;let i=Ck(s);if(!i)return Pi;let a=await i(e.params.argument.value,e.params.context);return Ok(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 Pi;throw new L(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=r.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Pi;let s=await o(e.params.argument.value,e.params.context);return Ok(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ur($o)),this.server.assertCanSetRequestHandler(ur(Oo)),this.server.assertCanSetRequestHandler(ur(Va)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler($o,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(Oo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([n,r])=>({name:n,uriTemplate:r.resourceTemplate.uriTemplate.toString(),...r.metadata}))})),this.server.setRequestHandler(Va,async(e,n)=>{let r=new URL(e.params.uri),o=this._registeredResources[r.toString()];if(o){if(!o.enabled)throw new L(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 L(Z.InvalidParams,`Resource ${r} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ur(Io)),this.server.assertCanSetRequestHandler(ur(Wa)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Io,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,n])=>({name:e,title:n.title,description:n.description,arguments:n.argsSchema?HM(n.argsSchema):void 0}))})),this.server.setRequestHandler(Wa,async(e,n)=>{let r=this._registeredPrompts[e.params.name];if(!r)throw new L(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!r.enabled)throw new L(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(r.argsSchema){let o=To(r.argsSchema),s=await Ra(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=Ca(c);throw new L(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:Hr(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=Hr(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 ht?c._def?.innerType:c;return Rm(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,n,r,o,s,i,a,c,u){Cm(e);let l={title:n,description:r,inputSchema:$k(o),outputSchema:$k(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"&&Cm(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=Hr(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Hr(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($m(c))o=n.shift(),n.length>1&&typeof n[0]=="object"&&n[0]!==null&&!$m(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 LM={type:"object",properties:{}};function Ik(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Ak(t){return"_def"in t||"_zod"in t||Ik(t)}function $m(t){return typeof t!="object"||t===null||Ak(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Ik)}function $k(t){if(t){if($m(t))return Hr(t);if(!Ak(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function HM(t){let e=Yn(t);return e?Object.entries(e).map(([n,r])=>{let o=g_(r),s=y_(r);return{name:n,description:o,required:!s}}):[]}function ur(t){let n=Yn(t)?.method;if(!n)throw new Error("Schema is missing a method literal");let r=$a(n);if(typeof r=="string")return r;throw new Error("Schema method literal must be a string")}function Ok(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Pi={completion:{values:[],hasMore:!1}};import Dk from"node:process";var Uc=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
227
227
  `);if(e===-1)return null;let n=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),UM(n)}clear(){this._buffer=void 0}};function UM(t){return K_.parse(JSON.parse(t))}function Nk(t){return JSON.stringify(t)+`
228
- `}var Fc=class{constructor(e=Dk.stdin,n=Dk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Uc,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=Nk(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as bT}from"node:module";import{existsSync as ze,unlinkSync as bs,readdirSync as kT,readFileSync as ra,writeFileSync as Zu,writeSync as uH,renameSync as lH,rmSync as vT,mkdirSync as dH,statSync as ET,symlinkSync as pH,lstatSync as wT,realpathSync as TT}from"node:fs";import{spawnSync as Bu}from"node:child_process";import{join as wt,dirname as vs,resolve as pt,sep as fH,isAbsolute as mH}from"node:path";import{fileURLToPath as hH}from"node:url";import{homedir as ks,tmpdir as Cg,cpus as gH}from"node:os";import{request as yH}from"node:https";import{AsyncLocalStorage as _H}from"node:async_hooks";qc();import{spawn as Bk,execSync as YM,execFileSync as Kk}from"node:child_process";import{mkdtempSync as QM,writeFileSync as qk,rmSync as ej,existsSync as Vk}from"node:fs";import{join as Kc,resolve as Gk}from"node:path";import{tmpdir as tj}from"node:os";var kt=process.platform==="win32",nj={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 rj(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.${nj[t]}`}function oj(t){return{windowsHide:t==="win32"}}function sj(t){return`'${t.replace(/'/g,"'\\''")}'`}function ij(t,e,n){return n==="win32"||!e?t:`export PATH=${sj(e)}
228
+ `}var Fc=class{constructor(e=Dk.stdin,n=Dk.stdout){this._stdin=e,this._stdout=n,this._readBuffer=new Uc,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=Nk(e);this._stdout.write(r)?n():this._stdout.once("drain",n)})}};import{createRequire as bT}from"node:module";import{existsSync as ze,unlinkSync as bs,readdirSync as kT,readFileSync as ra,writeFileSync as Zu,writeSync as lH,renameSync as dH,rmSync as vT,mkdirSync as pH,statSync as ET,symlinkSync as fH,lstatSync as wT,realpathSync as TT}from"node:fs";import{spawnSync as Bu}from"node:child_process";import{join as wt,dirname as vs,resolve as pt,sep as mH,isAbsolute as hH}from"node:path";import{fileURLToPath as gH}from"node:url";import{homedir as ks,tmpdir as Cg,cpus as yH}from"node:os";import{request as _H}from"node:https";import{AsyncLocalStorage as xH}from"node:async_hooks";qc();import{spawn as Bk,execSync as YM,execFileSync as Kk}from"node:child_process";import{mkdtempSync as QM,writeFileSync as qk,rmSync as ej,existsSync as Vk}from"node:fs";import{join as Kc,resolve as Gk}from"node:path";import{tmpdir as tj}from"node:os";var kt=process.platform==="win32",nj={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 rj(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.${nj[t]}`}function oj(t){return{windowsHide:t==="win32"}}function sj(t){return`'${t.replace(/'/g,"'\\''")}'`}function ij(t,e,n){return n==="win32"||!e?t:`export PATH=${sj(e)}
229
229
  ${t}`}function aj(t){let e=t?.toLowerCase()??"";return e.includes("powershell")||e.includes("pwsh")}function cj(t){return["\uFEFF[Console]::InputEncoding = [System.Text.UTF8Encoding]::new()","[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()","$OutputEncoding = [System.Text.UTF8Encoding]::new()",t].join(`
230
230
  `)}var uj=(()=>{if(kt)return process.env.TEMP??process.env.TMP??tj();try{let t=Kk(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:Gk(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();function lj(t,e){if(e!=="win32")return t;let n=new Set([";","&","|","(",`
231
231
  `]),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===`
@@ -573,20 +573,20 @@ stdout:
573
573
  ${r}
574
574
 
575
575
  stderr:
576
- ${o}`}}import{execFileSync as P1}from"node:child_process";function R1(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=P1("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 C1(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??R1,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var $1=C1();function O1(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 I1(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}var Ji=Date.now(),wu=0;function mg(){Ji=Date.now()}function Nw(){wu++,Ji=Date.now()}function Dw(){wu>0&&wu--,Ji=Date.now()}function Mw(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{mg()}catch{}return e(n,r)})}function jw(t){let e=t.checkIntervalMs??O1(),n=t.isParentAlive??$1,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??I1(),u;return c>0&&(Ji=Date.now(),u=setInterval(()=>{wu===0&&Date.now()-Ji>=c&&(process.stderr.write(`[context-mode] idle MCP bridge child self-shutdown after ${c}ms with no activity (#854)
577
- `),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 zw(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)}bn();ts();bn();import{existsSync as hg,unlinkSync as A1}from"node:fs";import{join as Xi}from"node:path";var N1=["","-wal","-shm"];function gg(t,e){try{return A1(t),e.push(t),!0}catch{return!1}}function Tu(t,e){let n=!1;for(let r of N1)gg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function Lw(t){let{projectDir:e,sessionsDir:n,storePath:r,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let x=ru(e),b=Qe(e),v=jn(e),O=b===v?[b]:[b,v],R=!1;for(let V of O){let P=Xi(n,`${V}${x}.db`);if(!hg(P))continue;let T=null;try{T=new on({dbPath:P});let H=T.getEvents(a).length;T.deleteSession(a),H>0&&(R=!0)}catch{}finally{try{T?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let M=[];if(r&&hg(r)&&M.push(r),o){let V=Qe(e),P=jn(e),T=V===P?[V]:[V,P];for(let H of T){let pe=Xi(o,`${H}.db`);hg(pe)&&!M.includes(pe)&&M.push(pe)}}let D=!1;for(let V of M)try{let P=Ye(),T=new P(V,{timeout:3e4});try{let H=T.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;T.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),T.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(D=!0)}finally{try{T.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Tu(r,l)&&(f=!0),o){let x=Qe(e),b=jn(e),v=x===b?[x]:[x,b];for(let O of v){let R=Xi(o,`${O}.db`);Tu(R,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let x=Xi(s,`${i}.db`);Tu(x,l)}let m=ru(e),p=Qe(e),h=jn(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let x of g){let b=Xi(n,`${x}${m}`);Tu(`${b}.db`,l)&&(y=!0),gg(`${b}-events.md`,l)&&(_=!0),gg(`${b}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}bn();import{existsSync as D1}from"node:fs";function yg(t,e){try{if(!D1(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 Hw(t){yg(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 Uw(t){yg(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 Fw(t){yg(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})})}bn();import{existsSync as Zw}from"node:fs";function Bw(t,e,n){try{if(!Zw(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 qw(t){try{if(!Zw(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}}to();bn();import{existsSync as _g,readFileSync as M1,readdirSync as j1,statSync as z1}from"node:fs";import{join as hs,isAbsolute as L1}from"node:path";var Vw=process.env.DEBUG?.includes("context-mode");function Kw(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?Ww(n,a):null)??r??Ct(),l=o?.getMemoryDir(n),d=hs(u,"memory"),f=n?hs(d,Qe(n)):d,m=l?Ww(n,l):f,p=[];if(n)for(let h of i){let g=hs(n,h);_g(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=hs(u,h);_g(g)&&p.push({path:g,label:`user/${h}`})}if(m&&_g(m))try{let h=j1(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:hs(m,g),label:`memory/${g}`})}catch(h){Vw&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
578
- `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=z1(h.path),g.size>1e6)continue}catch{continue}let y=M1(h.path,"utf-8"),_=y.toLowerCase();for(let x of t){if(s.length>=e)break;let v=x.toLowerCase().split(/\s+/).filter(R=>R.length>=3);if(v.some(R=>{try{return new RegExp(`\\b${R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(R)}})){let R=v.reduce((H,pe)=>{let ft=_.indexOf(pe);return ft>=0&&(H<0||ft<H)?ft:H},-1),M=Math.max(0,R-200),D=Math.min(y.length,R+500),V=y.lastIndexOf(`
576
+ ${o}`}}import{execFileSync as P1}from"node:child_process";function R1(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=P1("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 C1(t={}){let e=t.getPpid??(()=>process.ppid),n=t.readGrandparentPpid??R1,r=e(),o=n();return()=>{let s=e();return!(s!==r||s===0||s===1||!Number.isNaN(o)&&o>1&&n()===1)}}var $1=C1();function O1(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 I1(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 A1(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(),wu=0;function mg(){Ji=Date.now()}function Nw(){wu++,Ji=Date.now()}function Dw(){wu>0&&wu--,Ji=Date.now()}function Mw(t){if(!t)return;let e=typeof t.onmessage=="function"?t.onmessage.bind(t):null;e&&(t.onmessage=(n,r)=>{try{mg()}catch{}return e(n,r)})}function jw(t){let e=t.checkIntervalMs??O1(),n=t.isParentAlive??$1,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??I1(),u;return c>0&&(Ji=Date.now(),u=setInterval(()=>{wu===0&&Date.now()-Ji>=c&&(process.stderr.write(A1(c)+`
577
+ `),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 zw(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)}bn();ts();bn();import{existsSync as hg,unlinkSync as N1}from"node:fs";import{join as Xi}from"node:path";var D1=["","-wal","-shm"];function gg(t,e){try{return N1(t),e.push(t),!0}catch{return!1}}function Tu(t,e){let n=!1;for(let r of D1)gg(`${t}${r}`,e)&&r===""&&(n=!0);return n}function Lw(t){let{projectDir:e,sessionsDir:n,storePath:r,contentDir:o,legacyContentDir:s,contentHash:i,sessionId:a,scope:c}=t,u=[],l=[],d=c??(a?"session":"project");if(d==="session"&&!a)throw new TypeError("purgeSession: scope:'session' requires sessionId. Pass scope:'project' for the legacy whole-project wipe.");if(d==="session"&&a){let x=ru(e),b=Qe(e),v=jn(e),O=b===v?[b]:[b,v],R=!1;for(let V of O){let P=Xi(n,`${V}${x}.db`);if(!hg(P))continue;let T=null;try{T=new on({dbPath:P});let H=T.getEvents(a).length;T.deleteSession(a),H>0&&(R=!0)}catch{}finally{try{T?.close()}catch{}}}R&&u.push(`session rows for ${a}`);let M=[];if(r&&hg(r)&&M.push(r),o){let V=Qe(e),P=jn(e),T=V===P?[V]:[V,P];for(let H of T){let pe=Xi(o,`${H}.db`);hg(pe)&&!M.includes(pe)&&M.push(pe)}}let D=!1;for(let V of M)try{let P=Ye(),T=new P(V,{timeout:3e4});try{let H=T.prepare("SELECT COUNT(*) AS c FROM chunks WHERE session_id = ?").get(a).c;T.prepare("DELETE FROM chunks WHERE session_id = ?").run(a),T.prepare("DELETE FROM chunks_trigram WHERE session_id = ?").run(a),H>0&&(D=!0)}finally{try{T.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:l}}let f=!1;if(r&&Tu(r,l)&&(f=!0),o){let x=Qe(e),b=jn(e),v=x===b?[x]:[x,b];for(let O of v){let R=Xi(o,`${O}.db`);Tu(R,l)&&(f=!0)}}if(f&&u.push("knowledge base (FTS5)"),s){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let x=Xi(s,`${i}.db`);Tu(x,l)}let m=ru(e),p=Qe(e),h=jn(e),g=p===h?[p]:[p,h],y=!1,_=!1;for(let x of g){let b=Xi(n,`${x}${m}`);Tu(`${b}.db`,l)&&(y=!0),gg(`${b}-events.md`,l)&&(_=!0),gg(`${b}.cleanup`,l)}return y&&u.push("session events DB"),_&&u.push("session events markdown"),{deleted:u,wipedPaths:l}}bn();import{existsSync as M1}from"node:fs";function yg(t,e){try{if(!M1(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 Hw(t){yg(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 Uw(t){yg(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 Fw(t){yg(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})})}bn();import{existsSync as Zw}from"node:fs";function Bw(t,e,n){try{if(!Zw(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 qw(t){try{if(!Zw(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}}to();bn();import{existsSync as _g,readFileSync as j1,readdirSync as z1,statSync as L1}from"node:fs";import{join as hs,isAbsolute as H1}from"node:path";var Vw=process.env.DEBUG?.includes("context-mode");function Kw(t,e=5,n,r,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),u=(a?Ww(n,a):null)??r??Ct(),l=o?.getMemoryDir(n),d=hs(u,"memory"),f=n?hs(d,Qe(n)):d,m=l?Ww(n,l):f,p=[];if(n)for(let h of i){let g=hs(n,h);_g(g)&&p.push({path:g,label:`project/${h}`})}if(u&&u!==n)for(let h of i){let g=hs(u,h);_g(g)&&p.push({path:g,label:`user/${h}`})}if(m&&_g(m))try{let h=z1(m).filter(g=>g.endsWith(".md"));for(let g of h)p.push({path:hs(m,g),label:`memory/${g}`})}catch(h){Vw&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
578
+ `)}for(let h of p){if(s.length>=e)break;try{let g;try{if(g=L1(h.path),g.size>1e6)continue}catch{continue}let y=j1(h.path,"utf-8"),_=y.toLowerCase();for(let x of t){if(s.length>=e)break;let v=x.toLowerCase().split(/\s+/).filter(R=>R.length>=3);if(v.some(R=>{try{return new RegExp(`\\b${R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(y)}catch{return _.includes(R)}})){let R=v.reduce((H,pe)=>{let ft=_.indexOf(pe);return ft>=0&&(H<0||ft<H)?ft:H},-1),M=Math.max(0,R-200),D=Math.min(y.length,R+500),V=y.lastIndexOf(`
579
579
 
580
580
  `,M),P=y.indexOf(`
581
581
 
582
582
  `,D);V>=0&&(M=V+2),P>=0&&(D=P);let T=y.slice(M,D).trim();s.push({title:`[auto-memory] ${h.label}`,content:T,source:h.label,origin:"auto-memory",timestamp:g.mtime.toISOString()});break}}}catch(g){Vw&&process.stderr.write(`[ctx] auto-memory file read failed: ${g}
583
- `)}}return s.slice(0,e)}function Ww(t,e){return e?L1(e)||!t?e:hs(t,e):t??""}var Pu=process.env.DEBUG?.includes("context-mode");function Gw(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){Pu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
583
+ `)}}return s.slice(0,e)}function Ww(t,e){return e?H1(e)||!t?e:hs(t,e):t??""}var Pu=process.env.DEBUG?.includes("context-mode");function Gw(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){Pu&&process.stderr.write(`[ctx] getSessionIdsForProject failed: ${h}
584
584
  `)}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){Pu&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
585
585
  `)}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){Pu&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
586
586
  `)}try{let h=Kw([e],n,c,u,l);f.push(...h)}catch(h){Pu&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
587
- `)}}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 H1(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 Jw(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(H1,$.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 Xw(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var xg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var Ru=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)}};Mn();ms();bh();Mn();function U1(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 F1(t){let e=Zc(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 Yw(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 U1(s)){let a=F1(i);a&&n.add(a)}return[...n]}Fi();to();ms();import*as Ue from"node:fs";import*as Qw from"node:os";import*as gs from"node:path";var Z1=["CONTEXT_MODE_PROJECT_DIR"],B1=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Cu(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function q1(t){if(!Ue.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Ue.readdirSync(t.projectsRoot)){let o=gs.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=gs.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(`
588
- `).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 V1(t){let e=t?.codexHome??process.env.CODEX_HOME??gs.join(Qw.homedir(),".codex"),n=gs.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=gs.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(`
589
- `).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 Cu(h)?null:h}catch{return null}}finally{Ue.closeSync(u)}}catch{return null}return null}function eT(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...og(a),...Z1]:B1;for(let l of u){let d=e[l];if(d&&!Cu(d))return d}if(o){let l=q1({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Cu(l))return l}if(a==="codex"){let l=V1({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Cu(r)?r:n}ts();ts();bn();to();import{execFileSync as W1}from"node:child_process";import{existsSync as Fn,readdirSync as ys,statSync as K1}from"node:fs";import{homedir as Nu}from"node:os";import{join as Ot,sep as G1}from"node:path";function cT(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 Ou={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"},J1={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"},_s=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((T,H)=>T+H,0),s=Object.values(e.calls).reduce((T,H)=>T+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(T=>({tool:T,calls:e.calls[T]||0,context_kb:Math.round((e.bytesReturned[T]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[T]||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 T=a+e.cacheBytesSaved,H=T/Math.max(o,1),pe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ft=e.cacheHits+h,En=ft>0?e.cacheHits/ft:0;p={hits:e.cacheHits,misses:h,hit_rate:En,bytes_saved:e.cacheBytesSaved,ttl_hours_left:pe,total_with_cache:T,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,b=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=b?!b.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),R=new Map;for(let T of O){R.has(T.category)||R.set(T.category,new Set);let H=R.get(T.category);if(H.size<5){let pe=T.data;T.category==="file"?pe=T.data.split("/").pop()||T.data:(T.category==="prompt"||T.category==="user-prompt")&&(pe=pe.length>50?pe.slice(0,47)+"...":pe),pe.length>40&&(pe=pe.slice(0,37)+"..."),H.add(pe)}}let M=y.map(T=>({category:T.category,count:T.cnt,label:Ou[T.category]||T.category,preview:R.get(T.category)?Array.from(R.get(T.category)).join(", "):"",why:J1[T.category]||"Survives context resets"})),D=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),P=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(T=>T.cnt>0).map(T=>({category:T.category,count:T.cnt,label:Ou[T.category]||T.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:M,compact_count:x,resume_ready:v},projectMemory:{total_events:D.cnt,session_count:D.sessions,by_category:P}}}};function X1(t){let e=t?.home??Nu();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 Y1(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(Fn(n)){let m=[];try{m=ys(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Ye()}catch{}if(p)for(let h of m){let g=Ot(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of b)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let v=b.t.endsWith("Z")?b.t:b.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of b)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Fn(r)){let m=[];try{m=ys(r).filter(p=>{try{return K1(Ot(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Ot(r,p,"memory");if(!Fn(h))continue;let g=[];try{g=ys(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=Y1(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 uT(t){let e=t.sessionsDir??Ot(Nu(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Fn(e))return r;let o=[];try{o=ys(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():Ye()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=x=>Math.floor(x/864e5)*864e5;for(let x of o){let b=Ot(e,x),v=!1;try{let O=new s(b,{readonly:!0});try{let R=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let D of R)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.cnt??0,v=!0);let M=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(M?.mn){let D=Date.parse(M.mn+(M.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<d&&(d=D)}if(M?.mx){let D=Date.parse(M.mx+(M.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 P=parseInt(V.sec,10)*1e3;if(!Number.isFinite(P))continue;let T=h(P),H=p.get(T)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(T,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 P=h(V),T=p.get(P)??{count:0,rescueBytes:0};T.rescueBytes=Math.max(T.rescueBytes,D.bytes),p.set(P,T)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,b])=>({category:x,count:b,label:Ou[x]||x})).sort((x,b)=>b.count-x.count),_=[...p.entries()].sort((x,b)=>x[0]-b[0]).map(([x,b])=>({ms:x,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:m>0?m:void 0,byDay:_}}function Q1(t,e,n){if(!t||!e||!Fn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():Ye()}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
587
+ `)}}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 U1(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 Jw(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(U1,$.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 Xw(t,e,n){if(e)return t===void 0?n():t==="global"?null:t}var xg=!!process.env.CONTEXT_MODE_PROJECT_DIR;var Ru=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)}};Mn();ms();bh();Mn();function F1(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 Z1(t){let e=Zc(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 Yw(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 F1(s)){let a=Z1(i);a&&n.add(a)}return[...n]}Fi();to();ms();import*as Ue from"node:fs";import*as Qw from"node:os";import*as gs from"node:path";var B1=["CONTEXT_MODE_PROJECT_DIR"],q1=["CLAUDE_PROJECT_DIR","GEMINI_PROJECT_DIR","VSCODE_CWD","OPENCODE_PROJECT_DIR","PI_PROJECT_DIR","IDEA_INITIAL_DIRECTORY","CURSOR_CWD","CONTEXT_MODE_PROJECT_DIR"];function Cu(t){return t?/[/\\]\.(claude|codex)[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function V1(t){if(!Ue.existsSync(t.projectsRoot))return;let e,n=0;try{for(let r of Ue.readdirSync(t.projectsRoot)){let o=gs.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=gs.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(`
588
+ `).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 W1(t){let e=t?.codexHome??process.env.CODEX_HOME??gs.join(Qw.homedir(),".codex"),n=gs.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=gs.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(`
589
+ `).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 Cu(h)?null:h}catch{return null}}finally{Ue.closeSync(u)}}catch{return null}return null}function eT(t){let{env:e,cwd:n,pwd:r,transcriptsRoot:o,transcriptMaxAgeMs:s,nowMs:i,strictPlatform:a,codexHome:c}=t,u=a?[...og(a),...B1]:q1;for(let l of u){let d=e[l];if(d&&!Cu(d))return d}if(o){let l=V1({projectsRoot:o,maxAgeMs:s,nowMs:i});if(l&&!Cu(l))return l}if(a==="codex"){let l=W1({codexHome:c,transcriptMaxAgeMs:s,now:i});if(l)return l}return r&&!Cu(r)?r:n}ts();ts();bn();to();import{execFileSync as K1}from"node:child_process";import{existsSync as Fn,readdirSync as ys,statSync as G1}from"node:fs";import{homedir as Nu}from"node:os";import{join as Ot,sep as J1}from"node:path";function cT(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 Ou={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"},X1={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"},_s=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((T,H)=>T+H,0),s=Object.values(e.calls).reduce((T,H)=>T+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(T=>({tool:T,calls:e.calls[T]||0,context_kb:Math.round((e.bytesReturned[T]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[T]||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 T=a+e.cacheBytesSaved,H=T/Math.max(o,1),pe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3))),ft=e.cacheHits+h,En=ft>0?e.cacheHits/ft:0;p={hits:e.cacheHits,misses:h,hit_rate:En,bytes_saved:e.cacheBytesSaved,ttl_hours_left:pe,total_with_cache:T,total_savings_ratio:H}}let g=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(r).cnt,y=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(r),x=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(r)?.compact_count??0,b=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(r),v=b?!b.consumed:!1,O=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(r),R=new Map;for(let T of O){R.has(T.category)||R.set(T.category,new Set);let H=R.get(T.category);if(H.size<5){let pe=T.data;T.category==="file"?pe=T.data.split("/").pop()||T.data:(T.category==="prompt"||T.category==="user-prompt")&&(pe=pe.length>50?pe.slice(0,47)+"...":pe),pe.length>40&&(pe=pe.slice(0,37)+"..."),H.add(pe)}}let M=y.map(T=>({category:T.category,count:T.cnt,label:Ou[T.category]||T.category,preview:R.get(T.category)?Array.from(R.get(T.category)).join(", "):"",why:X1[T.category]||"Survives context resets"})),D=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),P=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(T=>T.cnt>0).map(T=>({category:T.category,count:T.cnt,label:Ou[T.category]||T.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:M,compact_count:x,resume_ready:v},projectMemory:{total_events:D.cnt,session_count:D.sessions,by_category:P}}}};function Y1(t){let e=t?.home??Nu();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 Q1(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(Fn(n)){let m=[];try{m=ys(n).filter(p=>p.endsWith(".db"))}catch{}if(m.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Ye()}catch{}if(p)for(let h of m){let g=Ot(n,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();o+=_?.cnt??0,s+=x?.cnt??0;try{let b=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of b)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let b=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();b?.bytes&&(i+=b.bytes)}catch{}try{let b=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(b?.t){let v=b.t.endsWith("Z")?b.t:b.t+"Z",O=Date.parse(v);Number.isFinite(O)&&O<a&&(a=O)}}catch{}try{let b=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of b)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let l=0,d=0,f={};if(Fn(r)){let m=[];try{m=ys(r).filter(p=>{try{return G1(Ot(r,p)).isDirectory()}catch{return!1}})}catch{}for(let p of m){let h=Ot(r,p,"memory");if(!Fn(h))continue;let g=[];try{g=ys(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){d++,l+=g.length;for(let y of g){let _=Q1(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 uT(t){let e=t.sessionsDir??Ot(Nu(),".claude","context-mode","sessions"),n=t.sessionId,r={sessionId:n,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!n||!Fn(e))return r;let o=[];try{o=ys(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return r}if(o.length===0)return r;let s=null;try{s=t.loadDatabase?t.loadDatabase():Ye()}catch{return r}if(!s)return r;let i={},a=0,c=0,u=0,l=0,d=Number.POSITIVE_INFINITY,f=0,m=0,p=new Map,h=x=>Math.floor(x/864e5)*864e5;for(let x of o){let b=Ot(e,x),v=!1;try{let O=new s(b,{readonly:!0});try{let R=O.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(n);for(let D of R)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.cnt??0,v=!0);let M=O.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(n);if(M?.mn){let D=Date.parse(M.mn+(M.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<d&&(d=D)}if(M?.mx){let D=Date.parse(M.mx+(M.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 P=parseInt(V.sec,10)*1e3;if(!Number.isFinite(P))continue;let T=h(P),H=p.get(T)??{count:0,rescueBytes:0};H.count+=V.cnt??0,p.set(T,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 P=h(V),T=p.get(P)??{count:0,rescueBytes:0};T.rescueBytes=Math.max(T.rescueBytes,D.bytes),p.set(P,T)}}}catch{}}finally{O.close()}}catch{}v&&c++}let g=d<f?(f-d)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,b])=>({category:x,count:b,label:Ou[x]||x})).sort((x,b)=>b.count-x.count),_=[...p.entries()].sort((x,b)=>x[0]-b[0]).map(([x,b])=>({ms:x,count:b.count,...b.rescueBytes>0?{rescueBytes:b.rescueBytes}:{}}));return{sessionId:n,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:l,byCategory:y,firstEventMs:Number.isFinite(d)?d:0,lastEventMs:f>0?f:0,lastRescueMs:m>0?m:void 0,byDay:_}}function eH(t,e,n){if(!t||!e||!Fn(e))return 0;let r=null;try{r=n?.loadDatabase?n.loadDatabase():Ye()}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
590
590
  FROM chunks WHERE session_id = ?`).get(t);return Number(s?.bytes??0)}finally{o.close()}}catch{return 0}}function lT(t,e){if(!t||!Fn(t))return 0;let n=null;try{n=e?.loadDatabase?e.loadDatabase():Ye()}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
591
591
  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(Nu(),".claude","context-mode","sessions");if(!Fn(n))return e;let r=[];try{r=ys(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():Ye()}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);Cv(f,o);try{let m=new o(f,{readonly:!0});try{if(t.sessionId){let p=m.prepare(`SELECT
592
592
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
@@ -607,25 +607,25 @@ ${o}`}}import{execFileSync as P1}from"node:child_process";function R1(){if(proce
607
607
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
608
608
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
609
609
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
610
- FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=Q1(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 eH={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function tH(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(!Fn(t.sessionsDir))return r;let o=[];try{o=ys(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 Du(t){let e=X1({home:t?.home}),n=t?.loadDatabase??Ye,r={...eH,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Fn(c.sessionsDir))continue;let u=tH(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 dT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},nH={"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 Iu(t){return nH[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 rH(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 $u(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function oH(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!$u(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=W1("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!$u(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!$u(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 $u(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function tT(t){let e=Nu();return e?t===e?"~":t.startsWith(e+G1)?"~"+t.slice(e.length):t:t}function sH(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 iH(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*iT,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*iT,_=Math.round((n?.rescueBytes??0)/4),x=y+_,b=o?.lifetime?.totalSavedTokens??0,v=Math.max(x,b),O=o?.lifetime?.bytesReturned??0,R=o?.lifetime?.bytesAvoided??0,M=O+R>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,P=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`,T=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=T>0?Math.max(1,Math.round((c-T)/864e5)):0,pe=r?.totalSessions??n?.totalSessions??1,ft=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,En;if(r&&ft>=2)En=`across ${ft} AI tools`;else if(r&&ft===1){let Ne=r.perAdapter.find(Wt=>Wt.isReal);En=`in ${Ne?Iu(Ne.name):"Claude Code"}`}else En="in Claude Code";H>0?d.push(` Across ${H} days you ran ${sn(pe)} conversations ${En}.`):d.push(` You ran ${sn(pe)} conversations ${En}.`);let Xu=H>0?D/H:0;d.push(` context-mode kept ${tt(D)} out of your context window \u2014 about ${tt(Xu)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Mg=e.firstEventMs&&e.firstEventMs>0?nT(e.firstEventMs,i,a):"";if(Mg?d.push(` This conversation started ${Mg} in ${tT(s)}.`):d.push(` This conversation lives in ${tT(s)}.`),d.push(` ${P}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?nT(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 jg=o?.conversation,zg=jg?.bytesAvoided??0,Yu=jg?.bytesReturned??0;if(zg+Yu===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=zg+Yu,Wt=Math.max(1,Yu),Kt=Math.max(1,Math.floor(Ne/4)),wn=Math.max(1,Math.floor(Wt/4)),Qu=gr(Kt,Kt,32),HT=gr(wn,Kt,32),UT=(1-wn/Kt)*100,FT=Math.max(1,Math.round(Kt/wn));d.push(` Without context-mode ${tt(Ne).padStart(8)} ${Qu} ${sn(Kt).padStart(7)} tokens`),d.push(` With context-mode ${tt(Wt).padStart(8)} ${HT} ${sn(wn).padStart(7)} tokens`),d.push(` ${UT.toFixed(0)}% kept out of context \xB7 your AI ran ${FT}\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(...cH(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 MT=e.byCategory.reduce((Ne,Wt)=>Ne+Wt.count,0).toLocaleString(i);d.push(` ${MT} things \u2014 files, errors, decisions, agent runs:`),d.push("");let jT=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${gr(Ne.count,jT,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Lg=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Hg=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Ug=n?.distinctProjects??0,zT=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${tt(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Lg?` \xB7 started ${Lg}`:""}.`),d.push(` All your work: ${tt(D)} kept out \xB7 ${zT.toLocaleString(i)} captures across ${Ug} project${Ug===1?"":"s"}${Hg?` \xB7 since ${Hg}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...sH(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,wn)=>wn[1]-Kt[1]),Wt=Ne.length>0?Ne[0][1]:1;for(let[Kt,wn]of Ne){let Qu=dT[Kt]??Kt;d.push(` ${Qu.padEnd(26)} ${String(wn).padStart(2)} ${gr(wn,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 LT=u?`v${u}`:"context-mode";return d.push(` ${LT}`),u&&l&&l!=="unknown"&&cT(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),aH(d)}function aH(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 cH(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 nT(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 B6=5/1e6;function Au(t){return`$${((Number.isFinite(t)&&t>0?t:0)*ea()).toFixed(2)}`}function gr(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 rT(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 ~${Au(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:Ou[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)} ${gr(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 oT(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=dT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${gr(s,r,20)}`)}return e}function sT(t,e){let n=[],r=Au(t),o=(e?.totalEvents??0)*256+t,s=Au(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 iT=256;function aT(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(` ${Iu(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=>Iu(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 Mu(t,e,n,r){let o=[],s=rH(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(O=>O.isReal).length??0;if(l&&d>0){let O=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,M=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,D=M>0?`Across ${M} day${M===1?"":"s"} `:"",V=O>0?`you ran ${sn(O)} conversation${O===1?"":"s"} `:"you ran ",P;if(d>=2)P=`across ${d} AI tools`;else{let T=l.perAdapter.find(H=>H.isReal);P=`in ${T?Iu(T.name):"Claude Code"}`}o.push(`${D}${V}${P}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=oH(),R=r?.cwd??process.cwd(),M=r?.now??Date.now(),D=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...iH({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:D,tz:V,now:M,version:e,latestVersion:n})),o.join(`
610
+ FROM session_events`).get();p&&(s+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let h=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();h?.bytes&&(c+=Number(h.bytes))}catch{}}}finally{m.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=eH(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 tH={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};function nH(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(!Fn(t.sessionsDir))return r;let o=[];try{o=ys(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 Du(t){let e=Y1({home:t?.home}),n=t?.loadDatabase??Ye,r={...tH,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},o=[],s=0,i=0,a=0;for(let c of e){if(!Fn(c.sessionsDir))continue;let u=nH(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 dT={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},rH={"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 Iu(t){return rH[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 oH(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 $u(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function sH(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!$u(e)&&(e=""),!e){if(process.platform==="darwin"){try{let r=K1("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();r&&(e=r.replace(/_/g,"-"))}catch{}e&&!$u(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let r=(t.LC_TIME||t.LANG||"").split(".")[0];r&&(e=r.replace(/_/g,"-")),e&&!$u(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 $u(e)||(e="en-US"),{locale:e,tz:n||"UTC"}}function tT(t){let e=Nu();return e?t===e?"~":t.startsWith(e+J1)?"~"+t.slice(e.length):t:t}function iH(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 aH(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*iT,m=Math.round((e.snapshotBytes??0)/4),p=f+m,h=o?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(n?.totalEvents??0)*iT,_=Math.round((n?.rescueBytes??0)/4),x=y+_,b=o?.lifetime?.totalSavedTokens??0,v=Math.max(x,b),O=o?.lifetime?.bytesReturned??0,R=o?.lifetime?.bytesAvoided??0,M=O+R>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,P=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`,T=n?.firstEventMs??r?.perAdapter?.[0]?.firstMs??0,H=T>0?Math.max(1,Math.round((c-T)/864e5)):0,pe=r?.totalSessions??n?.totalSessions??1,ft=r?.perAdapter.filter(Ne=>Ne.isReal).length??0,En;if(r&&ft>=2)En=`across ${ft} AI tools`;else if(r&&ft===1){let Ne=r.perAdapter.find(Wt=>Wt.isReal);En=`in ${Ne?Iu(Ne.name):"Claude Code"}`}else En="in Claude Code";H>0?d.push(` Across ${H} days you ran ${sn(pe)} conversations ${En}.`):d.push(` You ran ${sn(pe)} conversations ${En}.`);let Xu=H>0?D/H:0;d.push(` context-mode kept ${tt(D)} out of your context window \u2014 about ${tt(Xu)} every single day.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),d.push("");let Mg=e.firstEventMs&&e.firstEventMs>0?nT(e.firstEventMs,i,a):"";if(Mg?d.push(` This conversation started ${Mg} in ${tT(s)}.`):d.push(` This conversation lives in ${tT(s)}.`),d.push(` ${P}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ne=e.lastRescueMs&&e.lastRescueMs>0?nT(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 jg=o?.conversation,zg=jg?.bytesAvoided??0,Yu=jg?.bytesReturned??0;if(zg+Yu===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=zg+Yu,Wt=Math.max(1,Yu),Kt=Math.max(1,Math.floor(Ne/4)),wn=Math.max(1,Math.floor(Wt/4)),Qu=gr(Kt,Kt,32),HT=gr(wn,Kt,32),UT=(1-wn/Kt)*100,FT=Math.max(1,Math.round(Kt/wn));d.push(` Without context-mode ${tt(Ne).padStart(8)} ${Qu} ${sn(Kt).padStart(7)} tokens`),d.push(` With context-mode ${tt(Wt).padStart(8)} ${HT} ${sn(wn).padStart(7)} tokens`),d.push(` ${UT.toFixed(0)}% kept out of context \xB7 your AI ran ${FT}\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(...uH(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 MT=e.byCategory.reduce((Ne,Wt)=>Ne+Wt.count,0).toLocaleString(i);d.push(` ${MT} things \u2014 files, errors, decisions, agent runs:`),d.push("");let jT=e.byCategory[0]?.count??1;for(let Ne of e.byCategory)d.push(` ${Ne.label.padEnd(26)} ${String(Ne.count).padStart(5)} ${gr(Ne.count,jT,28)}`);d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),d.push("");let Lg=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",Hg=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Ug=n?.distinctProjects??0,zT=n?.totalEvents??r?.totalEvents??0;if(d.push(` This chat: ${tt(V)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Lg?` \xB7 started ${Lg}`:""}.`),d.push(` All your work: ${tt(D)} kept out \xB7 ${zT.toLocaleString(i)} captures across ${Ug} project${Ug===1?"":"s"}${Hg?` \xB7 since ${Hg}`:""}.`),d.push(""),d.push(""),d.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),d.push(""),d.push(...iH(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,wn)=>wn[1]-Kt[1]),Wt=Ne.length>0?Ne[0][1]:1;for(let[Kt,wn]of Ne){let Qu=dT[Kt]??Kt;d.push(` ${Qu.padEnd(26)} ${String(wn).padStart(2)} ${gr(wn,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 LT=u?`v${u}`:"context-mode";return d.push(` ${LT}`),u&&l&&l!=="unknown"&&cT(l,u)&&d.push(` Update available: v${u} -> v${l} | ctx_upgrade`),cH(d)}function cH(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 uH(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 nT(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 q6=5/1e6;function Au(t){return`$${((Number.isFinite(t)&&t>0?t:0)*ea()).toFixed(2)}`}function gr(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 rT(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 ~${Au(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:Ou[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)} ${gr(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 oT(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=dT[o]??o;e.push(` ${i.padEnd(26)} ${String(s).padStart(2)} ${gr(s,r,20)}`)}return e}function sT(t,e){let n=[],r=Au(t),o=(e?.totalEvents??0)*256+t,s=Au(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 iT=256;function aT(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(` ${Iu(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=>Iu(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 Mu(t,e,n,r){let o=[],s=oH(t.session.uptime_min),i=r?.lifetime,a=r?.mcpUsage,c=r?.conversation,u=r?.realBytes,l=r?.multiAdapter,d=l?.perAdapter.filter(O=>O.isReal).length??0;if(l&&d>0){let O=l.totalSessions||i?.totalSessions||0,R=i?.firstEventMs??0,M=R>0?Math.max(1,Math.round((Date.now()-R)/864e5)):0,D=M>0?`Across ${M} day${M===1?"":"s"} `:"",V=O>0?`you ran ${sn(O)} conversation${O===1?"":"s"} `:"you ran ",P;if(d>=2)P=`across ${d} AI tools`;else{let T=l.perAdapter.find(H=>H.isReal);P=`in ${T?Iu(T.name):"Claude Code"}`}o.push(`${D}${V}${P}.`),o.push("")}if(c&&c.events>0){o.length>0&&(o.length=0);let O=sH(),R=r?.cwd??process.cwd(),M=r?.now??Date.now(),D=r?.locale??O.locale,V=r?.tz??O.tz;return o.push(...aH({conversation:c,lifetime:i,multiAdapter:l,realBytes:u,cwd:R,locale:D,tz:V,now:M,version:e,latestVersion:n})),o.join(`
611
611
  `)}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(...rT(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:0})),o.push(...aT(l)),o.push(...oT(i)),o.push(...sT(0,i)),o.push("");let O=e?`v${e}`:"context-mode";return o.push(O),e&&n&&n!=="unknown"&&cT(n,e)&&o.push(`Update available: v${e} -> v${n} | ctx_upgrade`),o.join(`
612
612
  `)}o.push(`${sn(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${Au(y)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${gr(h,h)}| ${tt(h)}`),o.push(`With context-mode |${gr(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 x=[`${p} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${tt(t.cache.bytes_saved)})`),o.push(x.join(" \xB7 "));let b=t.savings.by_tool.filter(O=>O.calls>0);if(b.length>=2){o.push("");let O=b.map(R=>{let M=R.context_kb*1024,D=g<100?M/(1-g/100):M,V=Math.max(0,D-M);return{...R,returnedBytes:M,estimatedSaved:V}}).sort((R,M)=>M.estimatedSaved-R.estimatedSaved);for(let R of O){let M=R.tool.length>22?R.tool.slice(0,19)+"...":R.tool;o.push(` ${M.padEnd(22)} ${String(R.calls).padStart(4)} calls ${tt(R.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let O=a.filter(R=>R.median_concurrency!=null&&(R.max_concurrency??1)>1);if(O.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let R of O){let M=R.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${M.padEnd(22)} ${R.calls} batches \xB7 ${R.median_concurrency} typical, ${R.max_concurrency} peak`)}}}o.push(...rT(t.projectMemory,{lifetime:i,multiAdapter:l,sessionTokensSaved:y})),o.push(...aT(l)),o.push(...oT(i)),o.push(...sT(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(`
613
- `)}var Hu=vs(hH(import.meta.url)),Zn=(()=>{for(let t of["../package.json","./package.json"]){let e=pt(Hu,t);if(ze(e))try{return JSON.parse(ra(e,"utf8")).version}catch{}}return"unknown"})();function PT(){return ze(pt(Hu,"package.json"))?Hu:vs(Hu)}function xH(t){try{let e=process.platform==="win32"?Bu("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):Bu("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=uu(String(e.stdout));if(n&&ze(pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function RT(t){let e=PT();return t==="codex"?xH(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
614
- `)}),process.on("uncaughtException",t=>{try{uH(2,`[context-mode] uncaughtException: ${t?.message??t}
615
- `)}finally{process.exit(1)}}));var mo=Vc(),Uu=Fk(mo),Te=new Hc({name:"context-mode",version:Zn}),SH=[];function bH(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??vt().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??kH(n);return vH(r)&&EH(r)}function kH(t){let e=t==="kilo"?"kilo":"opencode",n=[pt(`${e}.json`),pt(`${e}.jsonc`),pt(`.${e}`,`${e}.json`),pt(`.${e}`,`${e}.jsonc`),wt(ks(),".config",e,`${e}.json`),wt(ks(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!ze(r))continue;return JSON.parse(Ui(ra(r,"utf8")))}catch{}return null}function vH(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function EH(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var CT=bH(),Eg=!1;function wH(t={}){if(Eg)return;Eg=!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).
616
- `)}function $3(){Eg=!1}function TH(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Ur,async()=>({tools:[]}))}var PH=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(CT){wH();return}let o=RH(e,r);return SH.push({name:e,config:n,handler:o}),t[2]=o,PH(...t)};function RH(t,e){return async n=>{Nw();try{return await e(n)}catch(r){let o=DH(r);if(o)try{return W(t,o)}catch(s){if(s instanceof dr)return o;throw s}throw r}finally{Dw()}}}CT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&TH(Te);var $g=new _H;async function O3(t,e){let n=typeof t=="string"?{projectDir:t}:t;return $g.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Io,async()=>({prompts:[]}));Te.server.setRequestHandler($o,async()=>({resources:[]}));Te.server.setRequestHandler(Oo,async()=>({resourceTemplates:[]}));function wg(t){if(Array.isArray(t))return t.map(wg);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]=wg(r)}return e}function CH(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Ur,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=wg(i.inputSchema)}catch{}}return s})}catch{}}var oa=new $i({runtimes:mo,projectRoot:()=>Et()}),Ju=wt(Cg(),`cm-fs-preload-${process.pid}.js`);Zu(Ju,`(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){}})();
617
- `);process.on("exit",()=>{try{bs(Ju)}catch{}});var an=null;function yr(){let t=$g.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??$H();if(e)return{sessionId:e}}var ju;function $H(t){let e=Date.now();if(!t?.bypassCache&&ju&&e-ju.checkedAt<2e3)return ju.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??je(),o=zi({projectDir:n,sessionsDir:r});if(!ze(o))return;let s=Ye(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(ju={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function OH(t){try{let e=je();if(!ze(e))return;let n=kT(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=wt(e,r);try{t.index({path:o,source:"session-events",attribution:yr()}),bs(o)}catch{}}}catch{}}var cn=null;async function IH(){if(cn)return cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(ms(),sg)),e=vt();return await t(e.platform)}catch{return null}}function xs(){if(cn)return cn.getSessionDir();try{let t=vt(),e=Wi(t.platform);if(e)return Xm({configDir:wt(...e),configDirEnv:AH(e)})}catch{}return Xm({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function AH(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function je(){return nu(ji(xs))}function Et(){let t=$g.getStore();if(t)return t.projectDir;let e,n,r;try{let o=vt().platform;n=o,o==="claude-code"&&(e=wt(ks(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??wt(ks(),".codex"))}catch{}return eT({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function NH(t){return mH(t)?t:pt(Et(),t)}function na(){return zi({projectDir:Et(),sessionsDir:je()})}function qu(){let t=nu(Ym(xs));return Pv({projectDir:Et(),contentDir:t})}function vn(){if(!an){let t=qu();an=new Yc(t),an.setDenyChecker(e=>{try{let n=Et(),r=Eu("Read",n);return Gi(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=vs(qu());Wm(e,14),an.cleanupStaleSources(14);let n=wt(ks(),".context-mode","content");ze(n)&&Wm(n,0)}catch{}Vm()}return OH(an),an}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function DH(t){return t instanceof dr?{content:[{type:"text",text:Ev(t)}],isError:!0}:null}var Bn=null,zu=0,pT=0,MH=3,jH=3600*1e3;async function fT(){return new Promise(t=>{let e=yH("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 zH(){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 LH(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 HH(){return!Bn||Bn==="unknown"?!1:LH(Bn,Zn)}function UH(){if(!HH())return!1;let t=Date.now();if(zu>=MH){if(t-pT<jH)return!1;zu=0}return zu===0&&(pT=t),zu++,!0}var mT=!1;function FH(){if(!mT){mT=!0;try{let t=Ct(),e=pt(t,"plugins","installed_plugins.json");if(!ze(e))return;let n=JSON.parse(ra(e,"utf-8")),r=pt(t,"plugins","cache"),o;try{o=TT(r)}catch{o=r}let s=PT();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+fH))continue;try{wT(u).isSymbolicLink()&&bs(u)}catch{}let l=vs(u);ze(l)||dH(l,{recursive:!0}),ze(s)&&pH(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(mg(),FH(),UH()&&e.content.length>0){let r=zH();e.content[0].text=`\u26A0\uFE0F context-mode v${Zn} outdated \u2192 v${Bn} available. Upgrade: ${r}
613
+ `)}var Hu=vs(gH(import.meta.url)),Zn=(()=>{for(let t of["../package.json","./package.json"]){let e=pt(Hu,t);if(ze(e))try{return JSON.parse(ra(e,"utf8")).version}catch{}}return"unknown"})();function PT(){return ze(pt(Hu,"package.json"))?Hu:vs(Hu)}function SH(t){try{let e=process.platform==="win32"?Bu("cmd.exe",["/d","/s","/c","codex plugin list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3}):Bu("codex",["plugin","list"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"],timeout:5e3});if(e.status!==0)return t;let n=uu(String(e.stdout));if(n&&ze(pt(n,".codex-plugin","hooks.json")))return n}catch{}return t}function RT(t){let e=PT();return t==="codex"?SH(e):e}process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&(process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
614
+ `)}),process.on("uncaughtException",t=>{try{lH(2,`[context-mode] uncaughtException: ${t?.message??t}
615
+ `)}finally{process.exit(1)}}));var mo=Vc(),Uu=Fk(mo),Te=new Hc({name:"context-mode",version:Zn}),bH=[];function kH(t={}){if((t.embedded??process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS)==="1")return!1;let n=t.platform??vt().platform;if(n!=="opencode"&&n!=="kilo")return!1;let r=t.settings??vH(n);return EH(r)&&wH(r)}function vH(t){let e=t==="kilo"?"kilo":"opencode",n=[pt(`${e}.json`),pt(`${e}.jsonc`),pt(`.${e}`,`${e}.json`),pt(`.${e}`,`${e}.jsonc`),wt(ks(),".config",e,`${e}.json`),wt(ks(),".config",e,`${e}.jsonc`)];for(let r of n)try{if(!ze(r))continue;return JSON.parse(Ui(ra(r,"utf8")))}catch{}return null}function EH(t){let e=t?.plugin;return Array.isArray(e)&&e.some(n=>typeof n=="string"&&n.includes("context-mode"))}function wH(t){let e=t?.mcp;return!!(e&&typeof e=="object"&&!Array.isArray(e)&&Object.prototype.hasOwnProperty.call(e,"context-mode"))}var CT=kH(),Eg=!1;function TH(t={}){if(Eg)return;Eg=!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).
616
+ `)}function O3(){Eg=!1}function PH(t=Te){t.server.registerCapabilities({tools:{listChanged:!1}}),t.server.setRequestHandler(Ur,async()=>({tools:[]}))}var RH=Te.registerTool.bind(Te);Te.registerTool=(...t)=>{let[e,n,r]=t;if(CT){TH();return}let o=CH(e,r);return bH.push({name:e,config:n,handler:o}),t[2]=o,RH(...t)};function CH(t,e){return async n=>{Nw();try{return await e(n)}catch(r){let o=MH(r);if(o)try{return W(t,o)}catch(s){if(s instanceof dr)return o;throw s}throw r}finally{Dw()}}}CT&&process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&PH(Te);var $g=new xH;async function I3(t,e){let n=typeof t=="string"?{projectDir:t}:t;return $g.run(n,e)}Te.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Te.server.setRequestHandler(Io,async()=>({prompts:[]}));Te.server.setRequestHandler($o,async()=>({resources:[]}));Te.server.setRequestHandler(Oo,async()=>({resourceTemplates:[]}));function wg(t){if(Array.isArray(t))return t.map(wg);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]=wg(r)}return e}function $H(t=Te){try{let n=t.server._requestHandlers?.get("tools/list");if(typeof n!="function")return;t.server.setRequestHandler(Ur,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=wg(i.inputSchema)}catch{}}return s})}catch{}}var oa=new $i({runtimes:mo,projectRoot:()=>Et()}),Ju=wt(Cg(),`cm-fs-preload-${process.pid}.js`);Zu(Ju,`(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){}})();
617
+ `);process.on("exit",()=>{try{bs(Ju)}catch{}});var an=null;function yr(){let t=$g.getStore();if(t?.sessionId)return{sessionId:t.sessionId};let e=process.env.CLAUDE_SESSION_ID??OH();if(e)return{sessionId:e}}var ju;function OH(t){let e=Date.now();if(!t?.bypassCache&&ju&&e-ju.checkedAt<2e3)return ju.sid;try{let n=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!n)return;let r=t?.sessionsDir??je(),o=zi({projectDir:n,sessionsDir:r});if(!ze(o))return;let s=Ye(),i=new s(o,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(ju={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function IH(t){try{let e=je();if(!ze(e))return;let n=kT(e).filter(r=>r.endsWith("-events.md"));for(let r of n){let o=wt(e,r);try{t.index({path:o,source:"session-events",attribution:yr()}),bs(o)}catch{}}}catch{}}var cn=null;async function AH(){if(cn)return cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(ms(),sg)),e=vt();return await t(e.platform)}catch{return null}}function xs(){if(cn)return cn.getSessionDir();try{let t=vt(),e=Wi(t.platform);if(e)return Xm({configDir:wt(...e),configDirEnv:NH(e)})}catch{}return Xm({configDir:".claude",configDirEnv:"CLAUDE_CONFIG_DIR"})}function NH(t){if(t.length===1&&t[0]===".claude")return"CLAUDE_CONFIG_DIR";if(t.length===1&&t[0]===".codex")return"CODEX_HOME"}function je(){return nu(ji(xs))}function Et(){let t=$g.getStore();if(t)return t.projectDir;let e,n,r;try{let o=vt().platform;n=o,o==="claude-code"&&(e=wt(ks(),".claude","projects")),o==="codex"&&(r=process.env.CODEX_HOME??wt(ks(),".codex"))}catch{}return eT({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:e,transcriptMaxAgeMs:300*1e3,strictPlatform:n,codexHome:r})}function DH(t){return hH(t)?t:pt(Et(),t)}function na(){return zi({projectDir:Et(),sessionsDir:je()})}function qu(){let t=nu(Ym(xs));return Pv({projectDir:Et(),contentDir:t})}function vn(){if(!an){let t=qu();an=new Yc(t),an.setDenyChecker(e=>{try{let n=Et(),r=Eu("Read",n);return Gi(e,r,process.platform==="win32",n).denied}catch{return!0}});try{let e=vs(qu());Wm(e,14),an.cleanupStaleSources(14);let n=wt(ks(),".context-mode","content");ze(n)&&Wm(n,0)}catch{}Vm()}return IH(an),an}var ne={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheMisses:0,cacheBytesSaved:0,sessionStart:Date.now()};function MH(t){return t instanceof dr?{content:[{type:"text",text:Ev(t)}],isError:!0}:null}var Bn=null,zu=0,pT=0,jH=3,zH=3600*1e3;async function fT(){return new Promise(t=>{let e=_H("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 LH(){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 HH(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 UH(){return!Bn||Bn==="unknown"?!1:HH(Bn,Zn)}function FH(){if(!UH())return!1;let t=Date.now();if(zu>=jH){if(t-pT<zH)return!1;zu=0}return zu===0&&(pT=t),zu++,!0}var mT=!1;function ZH(){if(!mT){mT=!0;try{let t=Ct(),e=pt(t,"plugins","installed_plugins.json");if(!ze(e))return;let n=JSON.parse(ra(e,"utf-8")),r=pt(t,"plugins","cache"),o;try{o=TT(r)}catch{o=r}let s=PT();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+mH))continue;try{wT(u).isSymbolicLink()&&bs(u)}catch{}let l=vs(u);ze(l)||pH(l,{recursive:!0}),ze(s)&&fH(s,u,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(mg(),ZH(),FH()&&e.content.length>0){let r=LH();e.content[0].text=`\u26A0\uFE0F context-mode v${Zn} outdated \u2192 v${Bn} available. Upgrade: ${r}
618
618
 
619
- `+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,Vu(),setImmediate(()=>Bw(na(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>Hw({sessionDbPath:na(),toolName:t,bytesReturned:n})),e}function un(t,e="unknown"){ne.bytesIndexed+=t,Vu(),t>0&&setImmediate(()=>Uw({sessionDbPath:na(),source:e,bytesAvoided:t}))}var ZH=500,BH=2,qH=3e4,VH=256,Tg=0,Lu,WH=/^[A-Za-z0-9._-]+$/;function KH(t){return WH.test(t)?t:`pid-${process.ppid}`}function $T(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=KH(t),n=nu(Qm(xs));return wt(n,`stats-${e}.json`)}function Vu(){let t=Date.now();if(!(t-Tg<ZH)){Tg=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=Lu?.tokens??0;if(!Lu||t-Lu.computedAt>qH)try{a=(Yi({sessionsDir:je()})?.totalEvents??0)*VH,Lu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:BH,version:Zn,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=$T(),l=`${u}.tmp`;Zu(l,JSON.stringify(c)),lH(l,u)}catch{}}}function Og(t,e){try{let n=lg(process.env.CLAUDE_PROJECT_DIR),r=pg(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 OT(t,e,n){try{let r=Aw(t,e);if(r.length===0)return null;let o=lg(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=pg(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 GH(t,e){try{let n=Et(),r=dg("Read","allow",n);return Iw(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 Pg(t,e){try{let n=Et(),r=Eu("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 JH=Uu.join(", "),XH=Wc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",YH="",QH="";function eU(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===YH){for(e.push(n),r++;r<t.length&&t[r]!==QH;)n++,r++;r<t.length&&r++}else n++,r++;return e}function IT(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of eU(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)+`
619
+ `+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,Vu(),setImmediate(()=>Bw(na(),t,n)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>Hw({sessionDbPath:na(),toolName:t,bytesReturned:n})),e}function un(t,e="unknown"){ne.bytesIndexed+=t,Vu(),t>0&&setImmediate(()=>Uw({sessionDbPath:na(),source:e,bytesAvoided:t}))}var BH=500,qH=2,VH=3e4,WH=256,Tg=0,Lu,KH=/^[A-Za-z0-9._-]+$/;function GH(t){return KH.test(t)?t:`pid-${process.ppid}`}function $T(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`,e=GH(t),n=nu(Qm(xs));return wt(n,`stats-${e}.json`)}function Vu(){let t=Date.now();if(!(t-Tg<BH)){Tg=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=Lu?.tokens??0;if(!Lu||t-Lu.computedAt>VH)try{a=(Yi({sessionsDir:je()})?.totalEvents??0)*WH,Lu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:qH,version:Zn,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=$T(),l=`${u}.tmp`;Zu(l,JSON.stringify(c)),dH(l,u)}catch{}}}function Og(t,e){try{let n=lg(process.env.CLAUDE_PROJECT_DIR),r=pg(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 OT(t,e,n){try{let r=Aw(t,e);if(r.length===0)return null;let o=lg(process.env.CLAUDE_PROJECT_DIR);for(let s of r){let i=pg(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 JH(t,e){try{let n=Et(),r=dg("Read","allow",n);return Iw(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 Pg(t,e){try{let n=Et(),r=Eu("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 XH=Uu.join(", "),YH=Wc()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",QH="",eU="";function tU(t){let e=[],n=0,r=0;for(;r<t.length;)if(t[r]===QH){for(e.push(n),r++;r<t.length&&t[r]!==eU;)n++,r++;r<t.length&&r++}else n++,r++;return e}function IT(t,e,n=1500,r){if(t.length<=n)return t;let o=[];if(r)for(let u of tU(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)+`
620
620
  \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(`
621
621
 
622
- `)}function tU(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}
622
+ `)}function nU(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}
623
623
  (output cap reached \u2014 use ctx_search(queries: ["${c}"]) for details)
624
624
  `);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=IT(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(`
625
- > **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 nU(t){return`'${t.replace(/'/g,"'\\''")}'`}function rU(t){return`'${t.replace(/'/g,"''")}'`}function oU(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${rU(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${nU(n)} `}var hT=500;function AT(t){let e=t.replace(/\s+/g," ").trim();return e.length<=hT?e:e.slice(0,hT)+"\u2026"}var sU=12e4;function Ig(t){if(t!==void 0)return t;if(vt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:sU}var gT=2e3;function iU(t){return t.length<=gT?t:t.slice(0,gT)+`
625
+ > **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 rU(t){return`'${t.replace(/'/g,"'\\''")}'`}function oU(t){return`'${t.replace(/'/g,"''")}'`}function sU(t,e){let n=`--require ${e}`,r=t.toLowerCase(),o=r.split(/[\\/]/).pop()??r;return r.includes("powershell")||r.includes("pwsh")?`$env:NODE_OPTIONS=${oU(n)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${n.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${rU(n)} `}var hT=500;function AT(t){let e=t.replace(/\s+/g," ").trim();return e.length<=hT?e:e.slice(0,hT)+"\u2026"}var iU=12e4;function Ig(t){if(t!==void 0)return t;if(vt().platform!=="antigravity-cli")return;let e=Number(process.env.CONTEXT_MODE_AGY_EXEC_TIMEOUT_MS);return Number.isFinite(e)&&e>0?e:iU}var gT=2e3;function aU(t){return t.length<=gT?t:t.slice(0,gT)+`
626
626
  \u2026 (truncated)`}function NT(t,e,n){let r=n?`path=${n}
627
627
  `:"",o=`\`\`\`${t}
628
- ${iU(e)}
628
+ ${aU(e)}
629
629
  \`\`\``;return`${r}${o}
630
630
 
631
631
  `}function yT(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=AT(e);return`# ${t}
@@ -635,7 +635,7 @@ $ ${a}
635
635
  ${o}
636
636
  `}function _T(t){let e=t.stdout||"",n=t.stderr||"";return n?e?`${e}${e.endsWith(`
637
637
  `)?"":`
638
- `}${n}`:n:e}async function aU(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let f=[],m=Date.now(),p=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let x=Date.now()-m,b=r-x;if(b<=0){f.push(`# ${g.label}
638
+ `}${n}`:n:e}async function cU(t,e,n){let{timeout:r,concurrency:o,nodeOptsPrefix:s,cwd:i,onFsBytes:a}=e;if(o<=1){let f=[],m=Date.now(),p=!1;for(let h=0;h<t.length;h++){let g=t[h],y;if(r!==void 0){let x=Date.now()-m,b=r-x;if(b<=0){f.push(`# ${g.label}
639
639
 
640
640
  (skipped \u2014 batch timeout exceeded)
641
641
  `),p=!0;continue}y=b}let _=await n.execute({language:"shell",code:`${s}${g.command}`,timeout:y,cwd:i});if(f.push(yT(g.label,g.command,_T(_),a)),_.timedOut){p=!0;for(let x=h+1;x<t.length;x++)f.push(`# ${t[x].label}
@@ -646,7 +646,7 @@ ${o}
646
646
  `:p,timedOut:!!m.timedOut}}})),{settled:u}=await jm(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}
647
647
 
648
648
  (executor error: ${p})
649
- `}}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.${XH} Languages: ${JH}.
649
+ `}}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.${YH} Languages: ${XH}.
650
650
 
651
651
  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.
652
652
 
@@ -769,7 +769,7 @@ RETURNS:
769
769
  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.
770
770
 
771
771
  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'))")
772
- 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=GH(t,"ctx_execute_file");if(s)return s;let i=Pg(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=Og(n,"execute_file");if(a)return a}else{let a=OT(n,e,"execute_file");if(a)return a}try{let a=Ig(r),c=await oa.executeFile({path:t,language:e,code:n,timeout:a}),u=NT(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}=fg({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(f)>Wu?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(f,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>Ku?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(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)>Wu)return un(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Ku){let d=DT(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.
772
+ 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=JH(t,"ctx_execute_file");if(s)return s;let i=Pg(t,"ctx_execute_file");if(i)return i;if(e==="shell"){let a=Og(n,"execute_file");if(a)return a}else{let a=OT(n,e,"execute_file");if(a)return a}try{let a=Ig(r),c=await oa.executeFile({path:t,language:e,code:n,timeout:a}),u=NT(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}=fg({language:e,exitCode:c.exitCode,stdout:c.stdout,stderr:c.stderr});return o&&o.trim().length>0&&Buffer.byteLength(f)>Wu?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(f,o,d?`file:${t}:error`:`file:${t}`)}`}],isError:d})):Buffer.byteLength(f)>Ku?(un(Buffer.byteLength(f)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(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)>Wu)return un(Buffer.byteLength(l)),W("ctx_execute_file",{content:[{type:"text",text:`${u}${Ss(l,o,`file:${t}`)}`}]});if(Buffer.byteLength(l)>Ku){let d=DT(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.
773
773
 
774
774
  WHEN:
775
775
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -787,16 +787,16 @@ RETURNS:
787
787
  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.
788
788
 
789
789
  EXAMPLE: ctx_index(content: "# React useEffect\\n\\nThe Effect Hook lets you ...", source: "react-useeffect-docs")
790
- 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=Pg(e,"ctx_index");if(l)return l}try{let l=e?NH(e):void 0;if(l&&ze(l)&&wT(l).isSymbolicLink()){let p;try{p=TT(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=Pg(p,"ctx_index");if(h)return h}}if(l&&ze(l)&&ET(l).isDirectory()){let m=vn(),p=Et(),h=Eu("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:yr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",b=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",v=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${b}${v}
790
+ 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=Pg(e,"ctx_index");if(l)return l}try{let l=e?DH(e):void 0;if(l&&ze(l)&&wT(l).isSymbolicLink()){let p;try{p=TT(l)}catch{return W("ctx_index",{content:[{type:"text",text:"Error: symlink target could not be resolved."}]})}if(p!==l){let h=Pg(p,"ctx_index");if(h)return h}}if(l&&ze(l)&&ET(l).isDirectory()){let m=vn(),p=Et(),h=Eu("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:yr(),perFileDeny:y,include:r,exclude:o,maxDepth:s,maxFiles:i,extensions:a,respectGitignore:c,followSymlinks:u}),x=_.capped?` (cap reached \u2014 only first ${_.filesIndexed} of ${_.totalSeen}+ files; raise maxFiles to index more)`:"",b=_.denied>0?` (${_.denied} file${_.denied===1?"":"s"} blocked by Read deny policy)`:"",v=_.failed>0?` (${_.failed} file${_.failed===1?"":"s"} failed to read)`:"";return W("ctx_index",{content:[{type:"text",text:`Indexed ${_.filesIndexed} file${_.filesIndexed===1?"":"s"} (${_.totalChunks} sections) from directory: ${_.label}${x}${b}${v}
791
791
  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=vn().index({content:t,path:l,source:n??l,attribution:yr()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${f.totalChunks} sections (${f.codeChunks} with code) from: ${f.label}
792
- 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 Ag(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var cU=Ag("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),Rg=Ag("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),Fu=Ag("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),uU=new Ru({windowMs:cU,softCapAfter:Rg,blockAfter:Fu});function lU(){try{return yr()?.sessionId??"__default__"}catch{return"__default__"}}function Ng(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 Dg(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function dU(t){let e=Ng(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:Jw(xg)},async t=>{try{let e=vn(),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.
792
+ 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 Ag(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var uU=Ag("CONTEXT_MODE_SEARCH_WINDOW_MS",6e4),Rg=Ag("CONTEXT_MODE_SEARCH_MAX_RESULTS_AFTER",3),Fu=Ag("CONTEXT_MODE_SEARCH_BLOCK_AFTER",8),lU=new Ru({windowMs:uU,softCapAfter:Rg,blockAfter:Fu});function dU(){try{return yr()?.sessionId??"__default__"}catch{return"__default__"}}function Ng(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 Dg(t){if(typeof t=="string"){let e=t.trim().toLowerCase();if(e==="true")return!0;if(e==="false")return!1}return t}function pU(t){let e=Ng(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:Jw(xg)},async t=>{try{let e=vn(),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.
793
793
 
794
794
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
795
795
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
796
796
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
797
797
  \u2022 ctx_index(content, source) \u2014 manually index text content
798
798
 
799
- 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=Xw(c,xg,()=>Et()),l=Date.now(),d=uU.record(lU(),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 M=je(),D=Et(),V=zi({projectDir:D,sessionsDir:M});ze(V)&&(y=new on({dbPath:V}))}catch{}let x;if(typeof u=="string"&&y)try{x=new Set(y.getSessionIdsForProject(u))}catch{}let b=cn?.getConfigDir()??Ct();try{for(let M of o){if(h>p){g.push(`## ${M}
799
+ 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=Xw(c,xg,()=>Et()),l=Date.now(),d=lU.record(dU(),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 M=je(),D=Et(),V=zi({projectDir:D,sessionsDir:M});ze(V)&&(y=new on({dbPath:V}))}catch{}let x;if(typeof u=="string"&&y)try{x=new Set(y.getSessionIdsForProject(u))}catch{}let b=cn?.getConfigDir()??Ct();try{for(let M of o){if(h>p){g.push(`## ${M}
800
800
  (output cap reached)
801
801
  `);continue}let D;if(n==="timeline"?D=Gw({query:M,limit:m,store:e,sort:n,source:i,contentType:a,sessionDB:y,projectDir:Et(),configDir:b,adapter:cn??void 0,projectScope:u}):D=e.searchWithFallback(M,m,i,a,"like",x),D.length===0){g.push(`## ${M}
802
802
  No results found.`);continue}let V=D.map((P,T)=>{let H=P.origin||"current-session",pe=P.timestamp?P.timestamp.slice(0,16).replace("T"," "):"",ft=`--- [${H}${pe?" | "+pe:""} | ${P.source}] ---`,En=`### ${P.title}`,Xu=IT(P.content,M,1500,P.highlighted);return`${ft}
@@ -817,7 +817,7 @@ ${V}`),h+=V.length}}finally{try{y?.close()}catch{}}let v=g.join(`
817
817
  \u26A0 search call #${f}/${Fu} 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+=`
818
818
 
819
819
  > Throttle: call #${f}/${Fu} in this window. ${R} call(s) before soft cap. Prefer ctx_search(queries: [...]) array form for multi-query workloads \u2014 it counts as a single call.`,v.trim().length===0){let M=e.listSources(),D=M.length>0?`
820
- Indexed sources: ${M.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 Sg=null,bg=null;function pU(){return Sg||(Sg=bT(import.meta.url).resolve("turndown")),Sg}function fU(){return bg||(bg=bT(import.meta.url).resolve("turndown-plugin-gfm")),bg}function mU(t,e){let n=JSON.stringify(pU()),r=JSON.stringify(fU()),o=JSON.stringify(e),s=Gu.toString(),i=Gu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
820
+ Indexed sources: ${M.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 Sg=null,bg=null;function fU(){return Sg||(Sg=bT(import.meta.url).resolve("turndown")),Sg}function mU(){return bg||(bg=bT(import.meta.url).resolve("turndown-plugin-gfm")),bg}function hU(t,e){let n=JSON.stringify(fU()),r=JSON.stringify(mU()),o=JSON.stringify(e),s=Gu.toString(),i=Gu.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${s};`:`var ${i} = ${s};
821
821
  var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
822
822
  const TurndownService = require(${n});
823
823
  const { gfm } = require(${r});
@@ -1062,7 +1062,7 @@ async function main() {
1062
1062
  emit('text', text);
1063
1063
  }
1064
1064
  main();
1065
- `}var hU=1440*60*1e3,xT=3072;function gU(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`}async function yU(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=Gu(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 Gu(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?Gu(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 _U(t,e,n,r){let o=await yU(t);if(o)return o;if(!n&&r!==0){let i=vn(),a=Km(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??hU;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:gU(d)}}}}let s=wt(Cg(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=mU(t,s),a=await oa.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",f=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${f}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=ET(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=ra(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{vT(s)}catch{}}}function xU(t){let e=vn(),n=Km(t.source,t.url),r=yr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),un(Buffer.byteLength(t.markdown));let s=t.markdown.length>xT?zw(t.markdown,xT)+`
1065
+ `}var gU=1440*60*1e3,xT=3072;function yU(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`}async function _U(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=Gu(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 Gu(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?Gu(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 xU(t,e,n,r){let o=await _U(t);if(o)return o;if(!n&&r!==0){let i=vn(),a=Km(e,t),c=i.getSourceMeta(a);if(c){let u=new Date(c.indexedAt+"Z"),l=Date.now()-u.getTime(),d=r??gU;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:yU(d)}}}}let s=wt(Cg(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let i=hU(t,s),a=await oa.execute({language:"javascript",code:i,timeout:3e4});if(a.exitCode!==0){let l=a.stderr||a.stdout||"unknown error",f=/\b(EAI_AGAIN|ETIMEDOUT|ETIMEOUT|ENETUNREACH|EPERM|getaddrinfo)\b/.test(l)?" \u2014 transient DNS error; retry once before falling back. If it keeps failing, the MCP host may be running under a network sandbox; restart the host with network access enabled.":"";return{kind:"fetch_error",url:t,error:`${l}${f}`,reason:"exit"}}let c=(a.stdout||"").trim(),u;try{let d=ET(s).size;if(d>52428800)return{kind:"fetch_error",url:t,error:`subprocess output ${d} bytes exceeds cap 52428800`,reason:"read"};u=ra(s,"utf-8").trim()}catch{return{kind:"fetch_error",url:t,error:"could not read subprocess output",reason:"read"}}return u.length===0?{kind:"fetch_error",url:t,error:"empty content",reason:"empty"}:{kind:"fetched",url:t,source:e,markdown:u,header:c}}catch(i){return{kind:"fetch_error",url:t,error:i instanceof Error?i.message:String(i),reason:"throw"}}finally{try{vT(s)}catch{}}}function SU(t){let e=vn(),n=Km(t.source,t.url),r=yr(),o;t.header==="__CM_CT__:json"?o=e.indexJSON(t.markdown,n,void 0,r):t.header==="__CM_CT__:text"?o=e.indexPlainText(t.markdown,n,void 0,r):o=e.index({content:t.markdown,source:n,attribution:r}),un(Buffer.byteLength(t.markdown));let s=t.markdown.length>xT?zw(t.markdown,xT)+`
1066
1066
 
1067
1067
  \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:o.label,totalChunks:o.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}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.
1068
1068
 
@@ -1084,14 +1084,14 @@ RETURNS:
1084
1084
  EXAMPLE: ctx_fetch_and_index(
1085
1085
  requests: [{url: "https://react.dev/...", source: "react"}, {url: "https://vuejs.org/...", source: "vue"}],
1086
1086
  concurrency: 5
1087
- )`,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(Ng,$.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(Dg,$.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(P=>({run:()=>_U(P.url,P.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await jm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let P=0;P<l.length;P++){let T=l[P];if(T.status==="rejected"){let pe=T.reason instanceof Error?T.reason.message:String(T.reason);m.push({kind:"job_error",url:i[P].url,error:pe});continue}let H=T.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let pe=H.estimatedBytes,ft=H.label;setImmediate(()=>Fw({sessionDbPath:na(),source:ft,bytesAvoided:pe})),m.push({kind:"cached",label:H.label,chunkCount:H.chunkCount,ageStr:H.ageStr,ttlStr:H.ttlStr})}else H.kind==="fetch_error"?m.push({kind:"fetch_error",url:H.url,error:H.error,reason:H.reason}):(ne.cacheMisses++,m.push({kind:"fetched",indexed:xU(H)}))}if(a){let P=m[0];if(P.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${P.label}** \u2014 ${P.chunkCount} sections, indexed ${P.ageStr} (fresh, TTL: ${P.ttlStr}).
1087
+ )`,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(Ng,$.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(Dg,$.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(P=>({run:()=>xU(P.url,P.source,o,s)})),{settled:l,effectiveConcurrency:d,capped:f}=await jm(u,{concurrency:c,capByCpuCount:!a&&c>1}),m=[];for(let P=0;P<l.length;P++){let T=l[P];if(T.status==="rejected"){let pe=T.reason instanceof Error?T.reason.message:String(T.reason);m.push({kind:"job_error",url:i[P].url,error:pe});continue}let H=T.value;if(H.kind==="cached"){ne.cacheHits++,ne.cacheBytesSaved+=H.estimatedBytes;let pe=H.estimatedBytes,ft=H.label;setImmediate(()=>Fw({sessionDbPath:na(),source:ft,bytesAvoided:pe})),m.push({kind:"cached",label:H.label,chunkCount:H.chunkCount,ageStr:H.ageStr,ttlStr:H.ttlStr})}else H.kind==="fetch_error"?m.push({kind:"fetch_error",url:H.url,error:H.error,reason:H.reason}):(ne.cacheMisses++,m.push({kind:"fetched",indexed:SU(H)}))}if(a){let P=m[0];if(P.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${P.label}** \u2014 ${P.chunkCount} sections, indexed ${P.ageStr} (fresh, TTL: ${P.ttlStr}).
1088
1088
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
1089
1089
 
1090
1090
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
1091
1091
  Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let T=(P.indexed.totalBytes/1024).toFixed(1),H=[`Fetched and indexed **${P.indexed.totalChunks} sections** (${T}KB) from: ${P.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${P.indexed.label}") for specific lookups.`,"","---","",P.indexed.preview].join(`
1092
1092
  `);return W("ctx_fetch_and_index",{content:[{type:"text",text:H}]})}if(P.kind==="fetch_error"){let T=P.reason==="empty"?`Fetched ${P.url} but got empty content`:P.reason==="read"?`Fetched ${P.url} but could not read subprocess output`:P.reason==="exit"?`Failed to fetch ${P.url}: ${P.error}`:`Fetch error: ${P.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:T}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let p=384,h=[],g=0,y=0,_=0,x=0,b=0,v=[];for(let P of m)if(P.kind==="cached")_++,h.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr}, TTL: ${P.ttlStr})`);else if(P.kind==="fetched"){x++,g+=P.indexed.totalChunks,y+=P.indexed.totalBytes;let T=(P.indexed.totalBytes/1024).toFixed(1);h.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${T}KB)`);let H=P.indexed.preview.length>p?P.indexed.preview.slice(0,p).trimEnd()+"\u2026":P.indexed.preview;v.push(`### ${P.indexed.label}
1093
1093
 
1094
- ${H}`)}else b++,h.push(`- [err] ${P.url}: ${P.error}`);let O=(y/1024).toFixed(1),R=f?` cap=${d}/${gH().length}cpu`:"",M=(P,T,H)=>`${P} ${P===1?T:H}`,V=[`fetched ${i.length} c=${d}${R}. ok=${x} cache=${_} err=${b}. ${M(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
1094
+ ${H}`)}else b++,h.push(`- [err] ${P.url}: ${P.error}`);let O=(y/1024).toFixed(1),R=f?` cap=${d}/${yH().length}cpu`:"",M=(P,T,H)=>`${P} ${P===1?T:H}`,V=[`fetched ${i.length} c=${d}${R}. ok=${x} cache=${_} err=${b}. ${M(g,"section","sections")} ${O}KB.`,"",...h,"",'ctx_search(queries: [...], source: "<label>") for full content.',...v.length>0?["","---","",...v]:[]].join(`
1095
1095
  `);return W("ctx_fetch_and_index",{content:[{type:"text",text:V}],isError:b===i.length})});Te.registerTool("ctx_batch_execute",{title:"Batch Execute & Search",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0},description:`Run multiple commands in ONE call. Every command's output is auto-indexed into the knowledge base; if you also pass \`queries\`, the matching sections come back in the same round trip so a follow-up search call is not needed.
1096
1096
 
1097
1097
  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).
@@ -1117,12 +1117,12 @@ EXAMPLE: ctx_batch_execute(
1117
1117
  ],
1118
1118
  queries: ["root cause", "proposed fix"],
1119
1119
  concurrency: 2
1120
- )`,inputSchema:$.object({commands:$.preprocess(dU,$.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(Ng,$.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=Og(i.command,"batch_execute");if(a)return a}try{let i=oU(mo.shell,Ju),a=Ig(n),{outputs:c,timedOut:u}=await aU(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:R=>{ne.bytesSandboxed+=R}},oa),l=c.join(`
1120
+ )`,inputSchema:$.object({commands:$.preprocess(pU,$.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(Ng,$.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=Og(i.command,"batch_execute");if(a)return a}try{let i=sU(mo.shell,Ju),a=Ig(n),{outputs:c,timedOut:u}=await cU(t,{timeout:a,concurrency:r,nodeOptsPrefix:i,cwd:o,onFsBytes:R=>{ne.bytesSandboxed+=R}},oa),l=c.join(`
1121
1121
  `),d=Buffer.byteLength(l),f=l.split(`
1122
- `).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=vn(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:yr()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${AT(R.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],x=[];for(let R of y){let M=Buffer.byteLength(R.content);_.push(`- ${R.title} (${(M/1024).toFixed(1)}KB)`),x.push(R.title)}let b=tU(m,e,p,void 0,s),v=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],O=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...b,v.length>0?`
1122
+ `).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=vn(),p=`batch:${t.map(R=>R.label).join(",").slice(0,80)}`,h=m.index({content:l,source:p,attribution:yr()}),g=["## Commands",""];for(let R of t)g.push(`- ${R.label}: \`${AT(R.command)}\``);let y=m.getChunksBySource(h.sourceId),_=["## Indexed Sections",""],x=[];for(let R of y){let M=Buffer.byteLength(R.content);_.push(`- ${R.title} (${(M/1024).toFixed(1)}KB)`),x.push(R.title)}let b=nU(m,e,p,void 0,s),v=m.getDistinctiveTerms?m.getDistinctiveTerms(h.sourceId):[],O=[`Executed ${t.length} commands (${f} lines, ${(d/1024).toFixed(1)}KB). Indexed ${h.totalChunks} sections. Searched ${e.length} queries.`,"",...g,"",..._,"",...b,v.length>0?`
1123
1123
  Searchable terms for follow-up: ${v.join(", ")}`:""].join(`
1124
- `);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 kg(t,e){if(!ze(e))return;let n=0;try{for(let r of kT(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ra(wt(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 ST(){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=Et(),n=Qe(e),r=zi({projectDir:e,sessionsDir:je()});if(ze(r)){let o=Ye(),s=new o(r,{readonly:!0});try{let i=new _s(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=Yi({sessionsDir:je()}),l;try{l=Du()}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=uT({sessionId:p,sessionsDir:je(),worktreeHash:n});let h=qu(),g;try{let b=Ye(),v=(await import("node:fs")).readdirSync(je()).filter(R=>R.endsWith(".db")&&(!n||R.startsWith(n))),O;for(let R of v)try{let M=new b((await import("node:path")).join(je(),R),{readonly:!0});try{let D=M.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(D?.project_dir){O=D.project_dir;break}}finally{M.close()}}catch{}g=O?Qi({projectDir:O,sessionsDir:je(),worktreeHash:n,contentDbPath:h}):Qi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}catch{g=Qi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}let y=Qi({sessionsDir:je()}),_=lT(h),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:x}}}catch{}cn?.name==="Pi"&&kg(u,je());let m;try{m=vn().getIndexState()}catch{}t=Mu(a,Zn,Bn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new _s(ST()).queryAll(ne),i=Yi({sessionsDir:je()});cn?.name==="Pi"&&kg(i,je());let a;try{a=Du()}catch{}let c;try{c=vn().getIndexState()}catch{}t=Mu(s,Zn,Bn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new _s(ST()).queryAll(ne),r;try{r=Yi({sessionsDir:je()})}catch{}cn?.name==="Pi"&&r&&kg(r,je());let o;try{o=Du()}catch{}t=Mu(n,Zn,Bn,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=vt(Te.server.getClientVersion()??void 0).platform}catch{e=vt().platform}let n=RT(e),r=11,o=(Uu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Uu.length}/${r} (${o}%) \u2014 ${Uu.join(", ")}`),Wc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=ji(xs),i=Ym(xs),a=Qm(xs);t.push(`[OK] Storage sessions: ${s.path} (${tu(s)})`),t.push(`[OK] Storage content: ${i.path} (${tu(i)})`),t.push(`[OK] Storage stats: ${a.path} (${tu(a)})`);{let u=new $i({runtimes:mo});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=Ye();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 IH();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=Yw(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${Zn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
1125
- `)}]})});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=vt(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=Bc(u.platform)&&mo.javascript?{platform:u.platform,jsRuntime:mo.javascript}:void 0}catch{try{n=vt().platform}catch{}}let r=RT(n),o=pt(r,"cli.bundle.mjs"),s=pt(r,"build","cli.js");try{let c=je(),u=wt(vs(c),"insight-cache");ze(u)&&(kU(4747),vT(u,{recursive:!0,force:!0}))}catch{}let i;if(ze(o))i=`${Ri(o,e)} upgrade${t}`;else if(ze(s))i=`${Ri(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(`
1124
+ `);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 kg(t,e){if(!ze(e))return;let n=0;try{for(let r of kT(e))if(!(!r.startsWith("stats-")||!r.endsWith(".json")))try{let o=JSON.parse(ra(wt(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 ST(){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=Et(),n=Qe(e),r=zi({projectDir:e,sessionsDir:je()});if(ze(r)){let o=Ye(),s=new o(r,{readonly:!0});try{let i=new _s(s),a=i.queryAll(ne),c=i.getMcpToolUsage(),u=Yi({sessionsDir:je()}),l;try{l=Du()}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=uT({sessionId:p,sessionsDir:je(),worktreeHash:n});let h=qu(),g;try{let b=Ye(),v=(await import("node:fs")).readdirSync(je()).filter(R=>R.endsWith(".db")&&(!n||R.startsWith(n))),O;for(let R of v)try{let M=new b((await import("node:path")).join(je(),R),{readonly:!0});try{let D=M.prepare("SELECT project_dir FROM session_meta WHERE session_id = ?").get(p);if(D?.project_dir){O=D.project_dir;break}}finally{M.close()}}catch{}g=O?Qi({projectDir:O,sessionsDir:je(),worktreeHash:n,contentDbPath:h}):Qi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}catch{g=Qi({sessionId:p,sessionsDir:je(),worktreeHash:n,contentDbPath:h})}let y=Qi({sessionsDir:je()}),_=lT(h),x={...y,contentBytes:y.contentBytes+_,bytesAvoided:y.bytesAvoided+_,totalSavedTokens:Math.floor((y.eventDataBytes+y.bytesAvoided+_+y.snapshotBytes)/4)};f={conversation:g,lifetime:x}}}catch{}cn?.name==="Pi"&&kg(u,je());let m;try{m=vn().getIndexState()}catch{}t=Mu(a,Zn,Bn,{lifetime:u,mcpUsage:c,multiAdapter:l,conversation:d,realBytes:f,indexState:m,cwd:e})}finally{s.close()}}else{let s=new _s(ST()).queryAll(ne),i=Yi({sessionsDir:je()});cn?.name==="Pi"&&kg(i,je());let a;try{a=Du()}catch{}let c;try{c=vn().getIndexState()}catch{}t=Mu(s,Zn,Bn,{lifetime:i,multiAdapter:a,indexState:c})}}catch{let n=new _s(ST()).queryAll(ne),r;try{r=Yi({sessionsDir:je()})}catch{}cn?.name==="Pi"&&r&&kg(r,je());let o;try{o=Du()}catch{}t=Mu(n,Zn,Bn,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=vt(Te.server.getClientVersion()??void 0).platform}catch{e=vt().platform}let n=RT(e),r=11,o=(Uu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Uu.length}/${r} (${o}%) \u2014 ${Uu.join(", ")}`),Wc()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");let s=ji(xs),i=Ym(xs),a=Qm(xs);t.push(`[OK] Storage sessions: ${s.path} (${tu(s)})`),t.push(`[OK] Storage content: ${i.path} (${tu(i)})`),t.push(`[OK] Storage stats: ${a.path} (${tu(a)})`);{let u=new $i({runtimes:mo});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=Ye();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 AH();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=Yw(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${Zn}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
1125
+ `)}]})});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=vt(c??void 0);n=u.platform,t=` --platform ${u.platform}`,e=Bc(u.platform)&&mo.javascript?{platform:u.platform,jsRuntime:mo.javascript}:void 0}catch{try{n=vt().platform}catch{}}let r=RT(n),o=pt(r,"cli.bundle.mjs"),s=pt(r,"build","cli.js");try{let c=je(),u=wt(vs(c),"insight-cache");ze(u)&&(vU(4747),vT(u,{recursive:!0,force:!0}))}catch{}let i;if(ze(o))i=`${Ri(o,e)} upgrade${t}`;else if(ze(s))i=`${Ri(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(`
1126
1126
  `),l=pt(r,".ctx-upgrade-inline.mjs"),{writeFileSync:d}=await import("node:fs");d(l,u),i=Ri(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(`
1127
1127
  `);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.
1128
1128
 
@@ -1148,7 +1148,7 @@ RETURNS:
1148
1148
  A summary of removed rows + the resolved scope.
1149
1149
 
1150
1150
  EXAMPLE: ctx_purge(confirm: true, sessionId: "7c8a-1234-5678-9abc-def012345678")
1151
- EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(Dg,$.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=qu()}catch{}if(an){try{an.cleanup()}catch{}an=null}let s=o?vs(o):void 0,{deleted:i}=Lw({projectDir:Et(),sessionsDir:je(),storePath:o,contentDir:s,legacyContentDir:wt(ks(),".context-mode","content"),contentHash:jn(Et()),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=$T();ze(c)&&bs(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 SU(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=Bu){let r=SU(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 kU(t,e=process.platform,n=Bu){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 vg="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(vg),e=t.ok?`Opening Insight in your browser: ${vg}`:`Could not auto-open your browser (${t.reason}).
1152
- Open Insight manually: ${vg}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function vU(){let t=Vm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Cg():"/tmp",n=wt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{oa.cleanupBackgrounded(),an&&an.close();try{bs(Ju)}catch{}try{bs(n)}catch{}r&&clearInterval(r)},s=async()=>{try{Tg=0,Vu()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),jw({onShutdown:()=>s()});let i=new Fc;await Te.connect(i),Mw(i);try{Zu(n,String(process.pid))}catch{}r=setInterval(()=>{try{Zu(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(ms(),sg)),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=qw(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{}fT().then(a=>{a!=="unknown"&&(Bn=a)}),setInterval(()=>{fT().then(a=>{a!=="unknown"&&(Bn=a)})},3600*1e3).unref(),setInterval(()=>Vu(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Zn} running on stdio`),console.error(`Detected runtimes:
1151
+ EXAMPLE: ctx_purge(confirm: true, scope: "project")`,inputSchema:$.object({confirm:$.preprocess(Dg,$.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=qu()}catch{}if(an){try{an.cleanup()}catch{}an=null}let s=o?vs(o):void 0,{deleted:i}=Lw({projectDir:Et(),sessionsDir:je(),storePath:o,contentDir:s,legacyContentDir:wt(ks(),".context-mode","content"),contentHash:jn(Et()),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=$T();ze(c)&&bs(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 bU(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 kU(t,e=process.platform,n=Bu){let r=bU(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 vU(t,e=process.platform,n=Bu){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 vg="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=kU(vg),e=t.ok?`Opening Insight in your browser: ${vg}`:`Could not auto-open your browser (${t.reason}).
1152
+ Open Insight manually: ${vg}`;return W("ctx_insight",{content:[{type:"text",text:e}]})});async function EU(){let t=Vm();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Cg():"/tmp",n=wt(e,`context-mode-mcp-ready-${process.pid}`),r,o=()=>{oa.cleanupBackgrounded(),an&&an.close();try{bs(Ju)}catch{}try{bs(n)}catch{}r&&clearInterval(r)},s=async()=>{try{Tg=0,Vu()}catch{}o(),process.exit(0)};process.on("exit",o),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),jw({onShutdown:()=>s()});let i=new Fc;await Te.connect(i),Mw(i);try{Zu(n,String(process.pid))}catch{}r=setInterval(()=>{try{Zu(n,String(process.pid))}catch{}},3e4),r.unref();try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(ms(),sg)),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=qw(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{}fT().then(a=>{a!=="unknown"&&(Bn=a)}),setInterval(()=>{fT().then(a=>{a!=="unknown"&&(Bn=a)})},3600*1e3).unref(),setInterval(()=>Vu(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Zn} running on stdio`),console.error(`Detected runtimes:
1153
1153
  ${Uk(mo)}`),Wc()||(console.error(`
1154
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}CH();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&vU().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{sU as AGY_DEFAULT_EXEC_TIMEOUT_MS,SH as REGISTERED_CTX_TOOLS,$3 as __resetSuppressionDiagnosticForTests,SU as browserOpenArgv,oU as buildBatchNodeOptionsPrefix,mU as buildFetchCode,Gu as classifyIp,yr as currentAttribution,wH as emitSuppressionDiagnostic,IT as extractSnippet,tU as formatBatchQueryResults,Et as getProjectDir,CH as installStrictClientSchemaCompat,kU as killProcessOnPort,bU as openBrowserSync,eU as positionsFromHighlight,TH as registerEmptyToolsListHandler,Ig as resolveExecTimeout,$H as resolveSessionIdFromSessionDB,aU as runBatchCommands,wg as sanitizeSchemaForStrictClients,Te as server,bH as shouldSuppressMcpToolsForNativePluginHost,O3 as withProjectDirOverride};
1154
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}$H();process.env.CONTEXT_MODE_EMBEDDED_PLUGIN_TOOLS!=="1"&&EU().catch(t=>{console.error("Fatal:",t),process.exit(1)});export{iU as AGY_DEFAULT_EXEC_TIMEOUT_MS,bH as REGISTERED_CTX_TOOLS,O3 as __resetSuppressionDiagnosticForTests,bU as browserOpenArgv,sU as buildBatchNodeOptionsPrefix,hU as buildFetchCode,Gu as classifyIp,yr as currentAttribution,TH as emitSuppressionDiagnostic,IT as extractSnippet,nU as formatBatchQueryResults,Et as getProjectDir,$H as installStrictClientSchemaCompat,vU as killProcessOnPort,kU as openBrowserSync,tU as positionsFromHighlight,PH as registerEmptyToolsListHandler,Ig as resolveExecTimeout,OH as resolveSessionIdFromSessionDB,cU as runBatchCommands,wg as sanitizeSchemaForStrictClients,Te as server,kH as shouldSuppressMcpToolsForNativePluginHost,I3 as withProjectDirOverride};