@mu-agent/mu 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,14 +1,25 @@
1
1
  // @bun
2
- var JK=Object.create;var{getPrototypeOf:KK,defineProperty:z4,getOwnPropertyNames:BK}=Object;var HK=Object.prototype.hasOwnProperty;function zK($){return this[$]}var VK,FK,a5=($,Z,W)=>{var Q=$!=null&&typeof $==="object";if(Q){var Y=Z?VK??=new WeakMap:FK??=new WeakMap,G=Y.get($);if(G)return G}W=$!=null?JK(KK($)):{};let X=Z||!$||!$.__esModule?z4(W,"default",{value:$,enumerable:!0}):W;for(let J of BK($))if(!HK.call(X,J))z4(X,J,{get:zK.bind($,J),enumerable:!0});if(Q)Y.set($,X);return X};var M=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var a0=import.meta.require;var p$=M((G9)=>{Object.defineProperty(G9,"__esModule",{value:!0});G9.regexpCode=G9.getEsmExportName=G9.getProperty=G9.safeStringify=G9.stringify=G9.strConcat=G9.addCodeArg=G9.str=G9._=G9.nil=G9._Code=G9.Name=G9.IDENTIFIER=G9._CodeOrName=void 0;class Y5{}G9._CodeOrName=Y5;G9.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class a1 extends Y5{constructor($){super();if(!G9.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}G9.Name=a1;class O0 extends Y5{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((Z,W)=>`${Z}${W}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((Z,W)=>{if(W instanceof a1)Z[W.str]=(Z[W.str]||0)+1;return Z},{})}}G9._Code=O0;G9.nil=new O0("");function Q9($,...Z){let W=[$[0]],Q=0;while(Q<Z.length)R8(W,Z[Q]),W.push($[++Q]);return new O0(W)}G9._=Q9;var E8=new O0("+");function Y9($,...Z){let W=[l$($[0])],Q=0;while(Q<Z.length)W.push(E8),R8(W,Z[Q]),W.push(E8,l$($[++Q]));return rz(W),new O0(W)}G9.str=Y9;function R8($,Z){if(Z instanceof O0)$.push(...Z._items);else if(Z instanceof a1)$.push(Z);else $.push(sz(Z))}G9.addCodeArg=R8;function rz($){let Z=1;while(Z<$.length-1){if($[Z]===E8){let W=tz($[Z-1],$[Z+1]);if(W!==void 0){$.splice(Z-1,3,W);continue}$[Z++]="+"}Z++}}function tz($,Z){if(Z==='""')return $;if($==='""')return Z;if(typeof $=="string"){if(Z instanceof a1||$[$.length-1]!=='"')return;if(typeof Z!="string")return`${$.slice(0,-1)}${Z}"`;if(Z[0]==='"')return $.slice(0,-1)+Z.slice(1);return}if(typeof Z=="string"&&Z[0]==='"'&&!($ instanceof a1))return`"${$}${Z.slice(1)}`;return}function oz($,Z){return Z.emptyStr()?$:$.emptyStr()?Z:Y9`${$}${Z}`}G9.strConcat=oz;function sz($){return typeof $=="number"||typeof $=="boolean"||$===null?$:l$(Array.isArray($)?$.join(","):$)}function ez($){return new O0(l$($))}G9.stringify=ez;function l$($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}G9.safeStringify=l$;function $V($){return typeof $=="string"&&G9.IDENTIFIER.test($)?new O0(`.${$}`):Q9`[${$}]`}G9.getProperty=$V;function ZV($){if(typeof $=="string"&&G9.IDENTIFIER.test($))return new O0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}G9.getEsmExportName=ZV;function WV($){return new O0($.toString())}G9.regexpCode=WV});var b8=M((B9)=>{Object.defineProperty(B9,"__esModule",{value:!0});B9.ValueScope=B9.ValueScopeName=B9.Scope=B9.varKinds=B9.UsedValueState=void 0;var W0=p$();class J9 extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var X5;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(X5||(B9.UsedValueState=X5={}));B9.varKinds={const:new W0.Name("const"),let:new W0.Name("let"),var:new W0.Name("var")};class C8{constructor({prefixes:$,parent:Z}={}){this._names={},this._prefixes=$,this._parent=Z}toName($){return $ instanceof W0.Name?$:this.name($)}name($){return new W0.Name(this._newName($))}_newName($){let Z=this._names[$]||this._nameGroup($);return`${$}${Z.index++}`}_nameGroup($){var Z,W;if(((W=(Z=this._parent)===null||Z===void 0?void 0:Z._prefixes)===null||W===void 0?void 0:W.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}B9.Scope=C8;class y8 extends W0.Name{constructor($,Z){super(Z);this.prefix=$}setValue($,{property:Z,itemIndex:W}){this.value=$,this.scopePath=W0._`.${new W0.Name(Z)}[${W}]`}}B9.ValueScopeName=y8;var LV=W0._`\n`;class K9 extends C8{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?LV:W0.nil}}get(){return this._scope}name($){return new y8($,this._newName($))}value($,Z){var W;if(Z.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Q=this.toName($),{prefix:Y}=Q,G=(W=Z.key)!==null&&W!==void 0?W:Z.ref,X=this._values[Y];if(X){let H=X.get(G);if(H)return H}else X=this._values[Y]=new Map;X.set(G,Q);let J=this._scope[Y]||(this._scope[Y]=[]),K=J.length;return J[K]=Z.ref,Q.setValue(Z,{property:Y,itemIndex:K}),Q}getValue($,Z){let W=this._values[$];if(!W)return;return W.get(Z)}scopeRefs($,Z=this._values){return this._reduceValues(Z,(W)=>{if(W.scopePath===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W0._`${$}${W.scopePath}`})}scopeCode($=this._values,Z,W){return this._reduceValues($,(Q)=>{if(Q.value===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return Q.value.code},Z,W)}_reduceValues($,Z,W={},Q){let Y=W0.nil;for(let G in $){let X=$[G];if(!X)continue;let J=W[G]=W[G]||new Map;X.forEach((K)=>{if(J.has(K))return;J.set(K,X5.Started);let H=Z(K);if(H){let V=this.opts.es5?B9.varKinds.var:B9.varKinds.const;Y=W0._`${Y}${V} ${K} = ${H};${this.opts._n}`}else if(H=Q===null||Q===void 0?void 0:Q(K))Y=W0._`${Y}${H}${this.opts._n}`;else throw new J9(K);J.set(K,X5.Completed)})}return Y}}B9.ValueScope=K9});var y=M((Q0)=>{Object.defineProperty(Q0,"__esModule",{value:!0});Q0.or=Q0.and=Q0.not=Q0.CodeGen=Q0.operators=Q0.varKinds=Q0.ValueScopeName=Q0.ValueScope=Q0.Scope=Q0.Name=Q0.regexpCode=Q0.stringify=Q0.getProperty=Q0.nil=Q0.strConcat=Q0.str=Q0._=void 0;var b=p$(),N0=b8(),G1=p$();Object.defineProperty(Q0,"_",{enumerable:!0,get:function(){return G1._}});Object.defineProperty(Q0,"str",{enumerable:!0,get:function(){return G1.str}});Object.defineProperty(Q0,"strConcat",{enumerable:!0,get:function(){return G1.strConcat}});Object.defineProperty(Q0,"nil",{enumerable:!0,get:function(){return G1.nil}});Object.defineProperty(Q0,"getProperty",{enumerable:!0,get:function(){return G1.getProperty}});Object.defineProperty(Q0,"stringify",{enumerable:!0,get:function(){return G1.stringify}});Object.defineProperty(Q0,"regexpCode",{enumerable:!0,get:function(){return G1.regexpCode}});Object.defineProperty(Q0,"Name",{enumerable:!0,get:function(){return G1.Name}});var V5=b8();Object.defineProperty(Q0,"Scope",{enumerable:!0,get:function(){return V5.Scope}});Object.defineProperty(Q0,"ValueScope",{enumerable:!0,get:function(){return V5.ValueScope}});Object.defineProperty(Q0,"ValueScopeName",{enumerable:!0,get:function(){return V5.ValueScopeName}});Object.defineProperty(Q0,"varKinds",{enumerable:!0,get:function(){return V5.varKinds}});Q0.operators={GT:new b._Code(">"),GTE:new b._Code(">="),LT:new b._Code("<"),LTE:new b._Code("<="),EQ:new b._Code("==="),NEQ:new b._Code("!=="),NOT:new b._Code("!"),OR:new b._Code("||"),AND:new b._Code("&&"),ADD:new b._Code("+")};class X1{optimizeNodes(){return this}optimizeNames($,Z){return this}}class z9 extends X1{constructor($,Z,W){super();this.varKind=$,this.name=Z,this.rhs=W}render({es5:$,_n:Z}){let W=$?N0.varKinds.var:this.varKind,Q=this.rhs===void 0?"":` = ${this.rhs}`;return`${W} ${this.name}${Q};`+Z}optimizeNames($,Z){if(!$[this.name.str])return;if(this.rhs)this.rhs=t1(this.rhs,$,Z);return this}get names(){return this.rhs instanceof b._CodeOrName?this.rhs.names:{}}}class x8 extends X1{constructor($,Z,W){super();this.lhs=$,this.rhs=Z,this.sideEffects=W}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,Z){if(this.lhs instanceof b.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=t1(this.rhs,$,Z),this}get names(){let $=this.lhs instanceof b.Name?{}:{...this.lhs.names};return z5($,this.rhs)}}class V9 extends x8{constructor($,Z,W,Q){super($,W,Q);this.op=Z}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class F9 extends X1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class D9 extends X1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class L9 extends X1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class U9 extends X1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,Z){return this.code=t1(this.code,$,Z),this}get names(){return this.code instanceof b._CodeOrName?this.code.names:{}}}class F5 extends X1{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((Z,W)=>Z+W.render($),"")}optimizeNodes(){let{nodes:$}=this,Z=$.length;while(Z--){let W=$[Z].optimizeNodes();if(Array.isArray(W))$.splice(Z,1,...W);else if(W)$[Z]=W;else $.splice(Z,1)}return $.length>0?this:void 0}optimizeNames($,Z){let{nodes:W}=this,Q=W.length;while(Q--){let Y=W[Q];if(Y.optimizeNames($,Z))continue;OV($,Y.names),W.splice(Q,1)}return W.length>0?this:void 0}get names(){return this.nodes.reduce(($,Z)=>P1($,Z.names),{})}}class J1 extends F5{render($){return"{"+$._n+super.render($)+"}"+$._n}}class A9 extends F5{}class c$ extends J1{}c$.kind="else";class c0 extends J1{constructor($,Z){super(Z);this.condition=$}render($){let Z=`if(${this.condition})`+super.render($);if(this.else)Z+="else "+this.else.render($);return Z}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let Z=this.else;if(Z){let W=Z.optimizeNodes();Z=this.else=Array.isArray(W)?new c$(W):W}if(Z){if($===!1)return Z instanceof c0?Z:Z.nodes;if(this.nodes.length)return this;return new c0(j9($),Z instanceof c0?[Z]:Z.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,Z){var W;if(this.else=(W=this.else)===null||W===void 0?void 0:W.optimizeNames($,Z),!(super.optimizeNames($,Z)||this.else))return;return this.condition=t1(this.condition,$,Z),this}get names(){let $=super.names;if(z5($,this.condition),this.else)P1($,this.else.names);return $}}c0.kind="if";class r1 extends J1{}r1.kind="for";class q9 extends r1{constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iteration=t1(this.iteration,$,Z),this}get names(){return P1(super.names,this.iteration.names)}}class O9 extends r1{constructor($,Z,W,Q){super();this.varKind=$,this.name=Z,this.from=W,this.to=Q}render($){let Z=$.es5?N0.varKinds.var:this.varKind,{name:W,from:Q,to:Y}=this;return`for(${Z} ${W}=${Q}; ${W}<${Y}; ${W}++)`+super.render($)}get names(){let $=z5(super.names,this.from);return z5($,this.to)}}class k8 extends r1{constructor($,Z,W,Q){super();this.loop=$,this.varKind=Z,this.name=W,this.iterable=Q}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iterable=t1(this.iterable,$,Z),this}get names(){return P1(super.names,this.iterable.names)}}class J5 extends J1{constructor($,Z,W){super();this.name=$,this.args=Z,this.async=W}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}J5.kind="func";class K5 extends F5{render($){return"return "+super.render($)}}K5.kind="return";class N9 extends J1{render($){let Z="try"+super.render($);if(this.catch)Z+=this.catch.render($);if(this.finally)Z+=this.finally.render($);return Z}optimizeNodes(){var $,Z;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(Z=this.finally)===null||Z===void 0||Z.optimizeNodes(),this}optimizeNames($,Z){var W,Q;return super.optimizeNames($,Z),(W=this.catch)===null||W===void 0||W.optimizeNames($,Z),(Q=this.finally)===null||Q===void 0||Q.optimizeNames($,Z),this}get names(){let $=super.names;if(this.catch)P1($,this.catch.names);if(this.finally)P1($,this.finally.names);return $}}class B5 extends J1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}B5.kind="catch";class H5 extends J1{render($){return"finally"+super.render($)}}H5.kind="finally";class M9{constructor($,Z={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Z,_n:Z.lines?`
3
- `:""},this._extScope=$,this._scope=new N0.Scope({parent:$}),this._nodes=[new A9]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,Z){let W=this._extScope.value($,Z);return(this._values[W.prefix]||(this._values[W.prefix]=new Set)).add(W),W}getScopeValue($,Z){return this._extScope.getValue($,Z)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,Z,W,Q){let Y=this._scope.toName(Z);if(W!==void 0&&Q)this._constants[Y.str]=W;return this._leafNode(new z9($,Y,W)),Y}const($,Z,W){return this._def(N0.varKinds.const,$,Z,W)}let($,Z,W){return this._def(N0.varKinds.let,$,Z,W)}var($,Z,W){return this._def(N0.varKinds.var,$,Z,W)}assign($,Z,W){return this._leafNode(new x8($,Z,W))}add($,Z){return this._leafNode(new V9($,Q0.operators.ADD,Z))}code($){if(typeof $=="function")$();else if($!==b.nil)this._leafNode(new U9($));return this}object(...$){let Z=["{"];for(let[W,Q]of $){if(Z.length>1)Z.push(",");if(Z.push(W),W!==Q||this.opts.es5)Z.push(":"),(0,b.addCodeArg)(Z,Q)}return Z.push("}"),new b._Code(Z)}if($,Z,W){if(this._blockNode(new c0($)),Z&&W)this.code(Z).else().code(W).endIf();else if(Z)this.code(Z).endIf();else if(W)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new c0($))}else(){return this._elseNode(new c$)}endIf(){return this._endBlockNode(c0,c$)}_for($,Z){if(this._blockNode($),Z)this.code(Z).endFor();return this}for($,Z){return this._for(new q9($),Z)}forRange($,Z,W,Q,Y=this.opts.es5?N0.varKinds.var:N0.varKinds.let){let G=this._scope.toName($);return this._for(new O9(Y,G,Z,W),()=>Q(G))}forOf($,Z,W,Q=N0.varKinds.const){let Y=this._scope.toName($);if(this.opts.es5){let G=Z instanceof b.Name?Z:this.var("_arr",Z);return this.forRange("_i",0,b._`${G}.length`,(X)=>{this.var(Y,b._`${G}[${X}]`),W(Y)})}return this._for(new k8("of",Q,Y,Z),()=>W(Y))}forIn($,Z,W,Q=this.opts.es5?N0.varKinds.var:N0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,b._`Object.keys(${Z})`,W);let Y=this._scope.toName($);return this._for(new k8("in",Q,Y,Z),()=>W(Y))}endFor(){return this._endBlockNode(r1)}label($){return this._leafNode(new F9($))}break($){return this._leafNode(new D9($))}return($){let Z=new K5;if(this._blockNode(Z),this.code($),Z.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(K5)}try($,Z,W){if(!Z&&!W)throw Error('CodeGen: "try" without "catch" and "finally"');let Q=new N9;if(this._blockNode(Q),this.code($),Z){let Y=this.name("e");this._currNode=Q.catch=new B5(Y),Z(Y)}if(W)this._currNode=Q.finally=new H5,this.code(W);return this._endBlockNode(B5,H5)}throw($){return this._leafNode(new L9($))}block($,Z){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(Z);return this}endBlock($){let Z=this._blockStarts.pop();if(Z===void 0)throw Error("CodeGen: not in self-balancing block");let W=this._nodes.length-Z;if(W<0||$!==void 0&&W!==$)throw Error(`CodeGen: wrong number of nodes: ${W} vs ${$} expected`);return this._nodes.length=Z,this}func($,Z=b.nil,W,Q){if(this._blockNode(new J5($,Z,W)),Q)this.code(Q).endFunc();return this}endFunc(){return this._endBlockNode(J5)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,Z){let W=this._currNode;if(W instanceof $||Z&&W instanceof Z)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Z?`${$.kind}/${Z.kind}`:$.kind}"`)}_elseNode($){let Z=this._currNode;if(!(Z instanceof c0))throw Error('CodeGen: "else" without "if"');return this._currNode=Z.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let Z=this._nodes;Z[Z.length-1]=$}}Q0.CodeGen=M9;function P1($,Z){for(let W in Z)$[W]=($[W]||0)+(Z[W]||0);return $}function z5($,Z){return Z instanceof b._CodeOrName?P1($,Z.names):$}function t1($,Z,W){if($ instanceof b.Name)return Q($);if(!Y($))return $;return new b._Code($._items.reduce((G,X)=>{if(X instanceof b.Name)X=Q(X);if(X instanceof b._Code)G.push(...X._items);else G.push(X);return G},[]));function Q(G){let X=W[G.str];if(X===void 0||Z[G.str]!==1)return G;return delete Z[G.str],X}function Y(G){return G instanceof b._Code&&G._items.some((X)=>X instanceof b.Name&&Z[X.str]===1&&W[X.str]!==void 0)}}function OV($,Z){for(let W in Z)$[W]=($[W]||0)-(Z[W]||0)}function j9($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:b._`!${_8($)}`}Q0.not=j9;var NV=P9(Q0.operators.AND);function MV(...$){return $.reduce(NV)}Q0.and=MV;var jV=P9(Q0.operators.OR);function PV(...$){return $.reduce(jV)}Q0.or=PV;function P9($){return(Z,W)=>Z===b.nil?W:W===b.nil?Z:b._`${_8(Z)} ${$} ${_8(W)}`}function _8($){return $ instanceof b.Name?$:b._`(${$})`}});var k=M((b9)=>{Object.defineProperty(b9,"__esModule",{value:!0});b9.checkStrictMode=b9.getErrorPath=b9.Type=b9.useFunc=b9.setEvaluated=b9.evaluatedPropsToName=b9.mergeEvaluated=b9.eachItem=b9.unescapeJsonPointer=b9.escapeJsonPointer=b9.escapeFragment=b9.unescapeFragment=b9.schemaRefOrVal=b9.schemaHasRulesButRef=b9.schemaHasRules=b9.checkUnknownRules=b9.alwaysValidSchema=b9.toHash=void 0;var g=y(),EV=p$();function RV($){let Z={};for(let W of $)Z[W]=!0;return Z}b9.toHash=RV;function SV($,Z){if(typeof Z=="boolean")return Z;if(Object.keys(Z).length===0)return!0;return E9($,Z),!R9(Z,$.self.RULES.all)}b9.alwaysValidSchema=SV;function E9($,Z=$.schema){let{opts:W,self:Q}=$;if(!W.strictSchema)return;if(typeof Z==="boolean")return;let Y=Q.RULES.keywords;for(let G in Z)if(!Y[G])y9($,`unknown keyword: "${G}"`)}b9.checkUnknownRules=E9;function R9($,Z){if(typeof $=="boolean")return!$;for(let W in $)if(Z[W])return!0;return!1}b9.schemaHasRules=R9;function CV($,Z){if(typeof $=="boolean")return!$;for(let W in $)if(W!=="$ref"&&Z.all[W])return!0;return!1}b9.schemaHasRulesButRef=CV;function yV({topSchemaRef:$,schemaPath:Z},W,Q,Y){if(!Y){if(typeof W=="number"||typeof W=="boolean")return W;if(typeof W=="string")return g._`${W}`}return g._`${$}${Z}${(0,g.getProperty)(Q)}`}b9.schemaRefOrVal=yV;function bV($){return S9(decodeURIComponent($))}b9.unescapeFragment=bV;function kV($){return encodeURIComponent(v8($))}b9.escapeFragment=kV;function v8($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}b9.escapeJsonPointer=v8;function S9($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}b9.unescapeJsonPointer=S9;function _V($,Z){if(Array.isArray($))for(let W of $)Z(W);else Z($)}b9.eachItem=_V;function T9({mergeNames:$,mergeToName:Z,mergeValues:W,resultToName:Q}){return(Y,G,X,J)=>{let K=X===void 0?G:X instanceof g.Name?(G instanceof g.Name?$(Y,G,X):Z(Y,G,X),X):G instanceof g.Name?(Z(Y,X,G),G):W(G,X);return J===g.Name&&!(K instanceof g.Name)?Q(Y,K):K}}b9.mergeEvaluated={props:T9({mergeNames:($,Z,W)=>$.if(g._`${W} !== true && ${Z} !== undefined`,()=>{$.if(g._`${Z} === true`,()=>$.assign(W,!0),()=>$.assign(W,g._`${W} || {}`).code(g._`Object.assign(${W}, ${Z})`))}),mergeToName:($,Z,W)=>$.if(g._`${W} !== true`,()=>{if(Z===!0)$.assign(W,!0);else $.assign(W,g._`${W} || {}`),g8($,W,Z)}),mergeValues:($,Z)=>$===!0?!0:{...$,...Z},resultToName:C9}),items:T9({mergeNames:($,Z,W)=>$.if(g._`${W} !== true && ${Z} !== undefined`,()=>$.assign(W,g._`${Z} === true ? true : ${W} > ${Z} ? ${W} : ${Z}`)),mergeToName:($,Z,W)=>$.if(g._`${W} !== true`,()=>$.assign(W,Z===!0?!0:g._`${W} > ${Z} ? ${W} : ${Z}`)),mergeValues:($,Z)=>$===!0?!0:Math.max($,Z),resultToName:($,Z)=>$.var("items",Z)})};function C9($,Z){if(Z===!0)return $.var("props",!0);let W=$.var("props",g._`{}`);if(Z!==void 0)g8($,W,Z);return W}b9.evaluatedPropsToName=C9;function g8($,Z,W){Object.keys(W).forEach((Q)=>$.assign(g._`${Z}${(0,g.getProperty)(Q)}`,!0))}b9.setEvaluated=g8;var I9={};function xV($,Z){return $.scopeValue("func",{ref:Z,code:I9[Z.code]||(I9[Z.code]=new EV._Code(Z.code))})}b9.useFunc=xV;var f8;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(f8||(b9.Type=f8={}));function fV($,Z,W){if($ instanceof g.Name){let Q=Z===f8.Num;return W?Q?g._`"[" + ${$} + "]"`:g._`"['" + ${$} + "']"`:Q?g._`"/" + ${$}`:g._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return W?(0,g.getProperty)($).toString():"/"+v8($)}b9.getErrorPath=fV;function y9($,Z,W=$.opts.strictSchema){if(!W)return;if(Z=`strict mode: ${Z}`,W===!0)throw Error(Z);$.self.logger.warn(Z)}b9.checkStrictMode=y9});var d0=M((_9)=>{Object.defineProperty(_9,"__esModule",{value:!0});var s=y(),$F={data:new s.Name("data"),valCxt:new s.Name("valCxt"),instancePath:new s.Name("instancePath"),parentData:new s.Name("parentData"),parentDataProperty:new s.Name("parentDataProperty"),rootData:new s.Name("rootData"),dynamicAnchors:new s.Name("dynamicAnchors"),vErrors:new s.Name("vErrors"),errors:new s.Name("errors"),this:new s.Name("this"),self:new s.Name("self"),scope:new s.Name("scope"),json:new s.Name("json"),jsonPos:new s.Name("jsonPos"),jsonLen:new s.Name("jsonLen"),jsonPart:new s.Name("jsonPart")};_9.default=$F});var d$=M((g9)=>{Object.defineProperty(g9,"__esModule",{value:!0});g9.extendErrors=g9.resetErrorsCount=g9.reportExtraError=g9.reportError=g9.keyword$DataError=g9.keywordError=void 0;var _=y(),L5=k(),e=d0();g9.keywordError={message:({keyword:$})=>_.str`must pass "${$}" keyword validation`};g9.keyword$DataError={message:({keyword:$,schemaType:Z})=>Z?_.str`"${$}" keyword must be ${Z} ($data)`:_.str`"${$}" keyword is invalid ($data)`};function WF($,Z=g9.keywordError,W,Q){let{it:Y}=$,{gen:G,compositeRule:X,allErrors:J}=Y,K=v9($,Z,W);if(Q!==null&&Q!==void 0?Q:X||J)x9(G,K);else f9(Y,_._`[${K}]`)}g9.reportError=WF;function QF($,Z=g9.keywordError,W){let{it:Q}=$,{gen:Y,compositeRule:G,allErrors:X}=Q,J=v9($,Z,W);if(x9(Y,J),!(G||X))f9(Q,e.default.vErrors)}g9.reportExtraError=QF;function YF($,Z){$.assign(e.default.errors,Z),$.if(_._`${e.default.vErrors} !== null`,()=>$.if(Z,()=>$.assign(_._`${e.default.vErrors}.length`,Z),()=>$.assign(e.default.vErrors,null)))}g9.resetErrorsCount=YF;function GF({gen:$,keyword:Z,schemaValue:W,data:Q,errsCount:Y,it:G}){if(Y===void 0)throw Error("ajv implementation error");let X=$.name("err");$.forRange("i",Y,e.default.errors,(J)=>{if($.const(X,_._`${e.default.vErrors}[${J}]`),$.if(_._`${X}.instancePath === undefined`,()=>$.assign(_._`${X}.instancePath`,(0,_.strConcat)(e.default.instancePath,G.errorPath))),$.assign(_._`${X}.schemaPath`,_.str`${G.errSchemaPath}/${Z}`),G.opts.verbose)$.assign(_._`${X}.schema`,W),$.assign(_._`${X}.data`,Q)})}g9.extendErrors=GF;function x9($,Z){let W=$.const("err",Z);$.if(_._`${e.default.vErrors} === null`,()=>$.assign(e.default.vErrors,_._`[${W}]`),_._`${e.default.vErrors}.push(${W})`),$.code(_._`${e.default.errors}++`)}function f9($,Z){let{gen:W,validateName:Q,schemaEnv:Y}=$;if(Y.$async)W.throw(_._`new ${$.ValidationError}(${Z})`);else W.assign(_._`${Q}.errors`,Z),W.return(!1)}var w1={keyword:new _.Name("keyword"),schemaPath:new _.Name("schemaPath"),params:new _.Name("params"),propertyName:new _.Name("propertyName"),message:new _.Name("message"),schema:new _.Name("schema"),parentSchema:new _.Name("parentSchema")};function v9($,Z,W){let{createErrors:Q}=$.it;if(Q===!1)return _._`{}`;return XF($,Z,W)}function XF($,Z,W={}){let{gen:Q,it:Y}=$,G=[JF(Y,W),KF($,W)];return BF($,Z,G),Q.object(...G)}function JF({errorPath:$},{instancePath:Z}){let W=Z?_.str`${$}${(0,L5.getErrorPath)(Z,L5.Type.Str)}`:$;return[e.default.instancePath,(0,_.strConcat)(e.default.instancePath,W)]}function KF({keyword:$,it:{errSchemaPath:Z}},{schemaPath:W,parentSchema:Q}){let Y=Q?Z:_.str`${Z}/${$}`;if(W)Y=_.str`${Y}${(0,L5.getErrorPath)(W,L5.Type.Str)}`;return[w1.schemaPath,Y]}function BF($,{params:Z,message:W},Q){let{keyword:Y,data:G,schemaValue:X,it:J}=$,{opts:K,propertyName:H,topSchemaRef:V,schemaPath:z}=J;if(Q.push([w1.keyword,Y],[w1.params,typeof Z=="function"?Z($):Z||_._`{}`]),K.messages)Q.push([w1.message,typeof W=="function"?W($):W]);if(K.verbose)Q.push([w1.schema,X],[w1.parentSchema,_._`${V}${z}`],[e.default.data,G]);if(H)Q.push([w1.propertyName,H])}});var p9=M((m9)=>{Object.defineProperty(m9,"__esModule",{value:!0});m9.boolOrEmptySchema=m9.topBoolOrEmptySchema=void 0;var DF=d$(),LF=y(),UF=d0(),AF={message:"boolean schema is false"};function qF($){let{gen:Z,schema:W,validateName:Q}=$;if(W===!1)u9($,!1);else if(typeof W=="object"&&W.$async===!0)Z.return(UF.default.data);else Z.assign(LF._`${Q}.errors`,null),Z.return(!0)}m9.topBoolOrEmptySchema=qF;function OF($,Z){let{gen:W,schema:Q}=$;if(Q===!1)W.var(Z,!1),u9($);else W.var(Z,!0)}m9.boolOrEmptySchema=OF;function u9($,Z){let{gen:W,data:Q}=$,Y={gen:W,keyword:"false schema",data:Q,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,DF.reportError)(Y,AF,void 0,Z)}});var u8=M((c9)=>{Object.defineProperty(c9,"__esModule",{value:!0});c9.getRules=c9.isJSONType=void 0;var MF=["string","number","integer","boolean","null","object","array"],jF=new Set(MF);function PF($){return typeof $=="string"&&jF.has($)}c9.isJSONType=PF;function wF(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}c9.getRules=wF});var m8=M((a9)=>{Object.defineProperty(a9,"__esModule",{value:!0});a9.shouldUseRule=a9.shouldUseGroup=a9.schemaHasRulesForType=void 0;function IF({schema:$,self:Z},W){let Q=Z.RULES.types[W];return Q&&Q!==!0&&i9($,Q)}a9.schemaHasRulesForType=IF;function i9($,Z){return Z.rules.some((W)=>n9($,W))}a9.shouldUseGroup=i9;function n9($,Z){var W;return $[Z.keyword]!==void 0||((W=Z.definition.implements)===null||W===void 0?void 0:W.some((Q)=>$[Q]!==void 0))}a9.shouldUseRule=n9});var i$=M((e9)=>{Object.defineProperty(e9,"__esModule",{value:!0});e9.reportTypeError=e9.checkDataTypes=e9.checkDataType=e9.coerceAndCheckDataType=e9.getJSONTypes=e9.getSchemaTypes=e9.DataType=void 0;var SF=u8(),CF=m8(),yF=d$(),C=y(),t9=k(),o1;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(o1||(e9.DataType=o1={}));function bF($){let Z=o9($.type);if(Z.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!Z.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)Z.push("null")}return Z}e9.getSchemaTypes=bF;function o9($){let Z=Array.isArray($)?$:$?[$]:[];if(Z.every(SF.isJSONType))return Z;throw Error("type must be JSONType or JSONType[]: "+Z.join(","))}e9.getJSONTypes=o9;function kF($,Z){let{gen:W,data:Q,opts:Y}=$,G=_F(Z,Y.coerceTypes),X=Z.length>0&&!(G.length===0&&Z.length===1&&(0,CF.schemaHasRulesForType)($,Z[0]));if(X){let J=p8(Z,Q,Y.strictNumbers,o1.Wrong);W.if(J,()=>{if(G.length)xF($,Z,G);else c8($)})}return X}e9.coerceAndCheckDataType=kF;var s9=new Set(["string","number","integer","boolean","null"]);function _F($,Z){return Z?$.filter((W)=>s9.has(W)||Z==="array"&&W==="array"):[]}function xF($,Z,W){let{gen:Q,data:Y,opts:G}=$,X=Q.let("dataType",C._`typeof ${Y}`),J=Q.let("coerced",C._`undefined`);if(G.coerceTypes==="array")Q.if(C._`${X} == 'object' && Array.isArray(${Y}) && ${Y}.length == 1`,()=>Q.assign(Y,C._`${Y}[0]`).assign(X,C._`typeof ${Y}`).if(p8(Z,Y,G.strictNumbers),()=>Q.assign(J,Y)));Q.if(C._`${J} !== undefined`);for(let H of W)if(s9.has(H)||H==="array"&&G.coerceTypes==="array")K(H);Q.else(),c8($),Q.endIf(),Q.if(C._`${J} !== undefined`,()=>{Q.assign(Y,J),fF($,J)});function K(H){switch(H){case"string":Q.elseIf(C._`${X} == "number" || ${X} == "boolean"`).assign(J,C._`"" + ${Y}`).elseIf(C._`${Y} === null`).assign(J,C._`""`);return;case"number":Q.elseIf(C._`${X} == "boolean" || ${Y} === null
4
- || (${X} == "string" && ${Y} && ${Y} == +${Y})`).assign(J,C._`+${Y}`);return;case"integer":Q.elseIf(C._`${X} === "boolean" || ${Y} === null
5
- || (${X} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(J,C._`+${Y}`);return;case"boolean":Q.elseIf(C._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(J,!1).elseIf(C._`${Y} === "true" || ${Y} === 1`).assign(J,!0);return;case"null":Q.elseIf(C._`${Y} === "" || ${Y} === 0 || ${Y} === false`),Q.assign(J,null);return;case"array":Q.elseIf(C._`${X} === "string" || ${X} === "number"
6
- || ${X} === "boolean" || ${Y} === null`).assign(J,C._`[${Y}]`)}}}function fF({gen:$,parentData:Z,parentDataProperty:W},Q){$.if(C._`${Z} !== undefined`,()=>$.assign(C._`${Z}[${W}]`,Q))}function l8($,Z,W,Q=o1.Correct){let Y=Q===o1.Correct?C.operators.EQ:C.operators.NEQ,G;switch($){case"null":return C._`${Z} ${Y} null`;case"array":G=C._`Array.isArray(${Z})`;break;case"object":G=C._`${Z} && typeof ${Z} == "object" && !Array.isArray(${Z})`;break;case"integer":G=X(C._`!(${Z} % 1) && !isNaN(${Z})`);break;case"number":G=X();break;default:return C._`typeof ${Z} ${Y} ${$}`}return Q===o1.Correct?G:(0,C.not)(G);function X(J=C.nil){return(0,C.and)(C._`typeof ${Z} == "number"`,J,W?C._`isFinite(${Z})`:C.nil)}}e9.checkDataType=l8;function p8($,Z,W,Q){if($.length===1)return l8($[0],Z,W,Q);let Y,G=(0,t9.toHash)($);if(G.array&&G.object){let X=C._`typeof ${Z} != "object"`;Y=G.null?X:C._`!${Z} || ${X}`,delete G.null,delete G.array,delete G.object}else Y=C.nil;if(G.number)delete G.integer;for(let X in G)Y=(0,C.and)(Y,l8(X,Z,W,Q));return Y}e9.checkDataTypes=p8;var vF={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:Z})=>typeof $=="string"?C._`{type: ${$}}`:C._`{type: ${Z}}`};function c8($){let Z=gF($);(0,yF.reportError)(Z,vF)}e9.reportTypeError=c8;function gF($){let{gen:Z,data:W,schema:Q}=$,Y=(0,t9.schemaRefOrVal)($,Q,"type");return{gen:Z,keyword:"type",data:W,schema:Q.type,schemaCode:Y,schemaValue:Y,parentSchema:Q,params:{},it:$}}});var Y7=M((W7)=>{Object.defineProperty(W7,"__esModule",{value:!0});W7.assignDefaults=void 0;var s1=y(),dF=k();function iF($,Z){let{properties:W,items:Q}=$.schema;if(Z==="object"&&W)for(let Y in W)Z7($,Y,W[Y].default);else if(Z==="array"&&Array.isArray(Q))Q.forEach((Y,G)=>Z7($,G,Y.default))}W7.assignDefaults=iF;function Z7($,Z,W){let{gen:Q,compositeRule:Y,data:G,opts:X}=$;if(W===void 0)return;let J=s1._`${G}${(0,s1.getProperty)(Z)}`;if(Y){(0,dF.checkStrictMode)($,`default is ignored for: ${J}`);return}let K=s1._`${J} === undefined`;if(X.useDefaults==="empty")K=s1._`${K} || ${J} === null || ${J} === ""`;Q.if(K,s1._`${J} = ${(0,s1.stringify)(W)}`)}});var F0=M((J7)=>{Object.defineProperty(J7,"__esModule",{value:!0});J7.validateUnion=J7.validateArray=J7.usePattern=J7.callValidateCode=J7.schemaProperties=J7.allSchemaProperties=J7.noPropertyInData=J7.propertyInData=J7.isOwnProperty=J7.hasPropFunc=J7.reportMissingProp=J7.checkMissingProp=J7.checkReportMissingProp=void 0;var u=y(),d8=k(),K1=d0(),nF=k();function aF($,Z){let{gen:W,data:Q,it:Y}=$;W.if(n8(W,Q,Z,Y.opts.ownProperties),()=>{$.setParams({missingProperty:u._`${Z}`},!0),$.error()})}J7.checkReportMissingProp=aF;function rF({gen:$,data:Z,it:{opts:W}},Q,Y){return(0,u.or)(...Q.map((G)=>(0,u.and)(n8($,Z,G,W.ownProperties),u._`${Y} = ${G}`)))}J7.checkMissingProp=rF;function tF($,Z){$.setParams({missingProperty:Z},!0),$.error()}J7.reportMissingProp=tF;function G7($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:u._`Object.prototype.hasOwnProperty`})}J7.hasPropFunc=G7;function i8($,Z,W){return u._`${G7($)}.call(${Z}, ${W})`}J7.isOwnProperty=i8;function oF($,Z,W,Q){let Y=u._`${Z}${(0,u.getProperty)(W)} !== undefined`;return Q?u._`${Y} && ${i8($,Z,W)}`:Y}J7.propertyInData=oF;function n8($,Z,W,Q){let Y=u._`${Z}${(0,u.getProperty)(W)} === undefined`;return Q?(0,u.or)(Y,(0,u.not)(i8($,Z,W))):Y}J7.noPropertyInData=n8;function X7($){return $?Object.keys($).filter((Z)=>Z!=="__proto__"):[]}J7.allSchemaProperties=X7;function sF($,Z){return X7(Z).filter((W)=>!(0,d8.alwaysValidSchema)($,Z[W]))}J7.schemaProperties=sF;function eF({schemaCode:$,data:Z,it:{gen:W,topSchemaRef:Q,schemaPath:Y,errorPath:G},it:X},J,K,H){let V=H?u._`${$}, ${Z}, ${Q}${Y}`:Z,z=[[K1.default.instancePath,(0,u.strConcat)(K1.default.instancePath,G)],[K1.default.parentData,X.parentData],[K1.default.parentDataProperty,X.parentDataProperty],[K1.default.rootData,K1.default.rootData]];if(X.opts.dynamicRef)z.push([K1.default.dynamicAnchors,K1.default.dynamicAnchors]);let F=u._`${V}, ${W.object(...z)}`;return K!==u.nil?u._`${J}.call(${K}, ${F})`:u._`${J}(${F})`}J7.callValidateCode=eF;var $D=u._`new RegExp`;function ZD({gen:$,it:{opts:Z}},W){let Q=Z.unicodeRegExp?"u":"",{regExp:Y}=Z.code,G=Y(W,Q);return $.scopeValue("pattern",{key:G.toString(),ref:G,code:u._`${Y.code==="new RegExp"?$D:(0,nF.useFunc)($,Y)}(${W}, ${Q})`})}J7.usePattern=ZD;function WD($){let{gen:Z,data:W,keyword:Q,it:Y}=$,G=Z.name("valid");if(Y.allErrors){let J=Z.let("valid",!0);return X(()=>Z.assign(J,!1)),J}return Z.var(G,!0),X(()=>Z.break()),G;function X(J){let K=Z.const("len",u._`${W}.length`);Z.forRange("i",0,K,(H)=>{$.subschema({keyword:Q,dataProp:H,dataPropType:d8.Type.Num},G),Z.if((0,u.not)(G),J)})}}J7.validateArray=WD;function QD($){let{gen:Z,schema:W,keyword:Q,it:Y}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(W.some((K)=>(0,d8.alwaysValidSchema)(Y,K))&&!Y.opts.unevaluated)return;let X=Z.let("valid",!1),J=Z.name("_valid");Z.block(()=>W.forEach((K,H)=>{let V=$.subschema({keyword:Q,schemaProp:H,compositeRule:!0},J);if(Z.assign(X,u._`${X} || ${J}`),!$.mergeValidEvaluated(V,J))Z.if((0,u.not)(X))})),$.result(X,()=>$.reset(),()=>$.error(!0))}J7.validateUnion=QD});var F7=M((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.validateKeywordUsage=z7.validSchemaType=z7.funcKeywordCode=z7.macroKeywordCode=void 0;var $0=y(),T1=d0(),UD=F0(),AD=d$();function qD($,Z){let{gen:W,keyword:Q,schema:Y,parentSchema:G,it:X}=$,J=Z.macro.call(X.self,Y,G,X),K=H7(W,Q,J);if(X.opts.validateSchema!==!1)X.self.validateSchema(J,!0);let H=W.name("valid");$.subschema({schema:J,schemaPath:$0.nil,errSchemaPath:`${X.errSchemaPath}/${Q}`,topSchemaRef:K,compositeRule:!0},H),$.pass(H,()=>$.error(!0))}z7.macroKeywordCode=qD;function OD($,Z){var W;let{gen:Q,keyword:Y,schema:G,parentSchema:X,$data:J,it:K}=$;MD(K,Z);let H=!J&&Z.compile?Z.compile.call(K.self,G,X,K):Z.validate,V=H7(Q,Y,H),z=Q.let("valid");$.block$data(z,F),$.ok((W=Z.valid)!==null&&W!==void 0?W:z);function F(){if(Z.errors===!1){if(U(),Z.modifying)B7($);A(()=>$.error())}else{let q=Z.async?D():L();if(Z.modifying)B7($);A(()=>ND($,q))}}function D(){let q=Q.let("ruleErrs",null);return Q.try(()=>U($0._`await `),(O)=>Q.assign(z,!1).if($0._`${O} instanceof ${K.ValidationError}`,()=>Q.assign(q,$0._`${O}.errors`),()=>Q.throw(O))),q}function L(){let q=$0._`${V}.errors`;return Q.assign(q,null),U($0.nil),q}function U(q=Z.async?$0._`await `:$0.nil){let O=K.opts.passContext?T1.default.this:T1.default.self,j=!(("compile"in Z)&&!J||Z.schema===!1);Q.assign(z,$0._`${q}${(0,UD.callValidateCode)($,V,O,j)}`,Z.modifying)}function A(q){var O;Q.if((0,$0.not)((O=Z.valid)!==null&&O!==void 0?O:z),q)}}z7.funcKeywordCode=OD;function B7($){let{gen:Z,data:W,it:Q}=$;Z.if(Q.parentData,()=>Z.assign(W,$0._`${Q.parentData}[${Q.parentDataProperty}]`))}function ND($,Z){let{gen:W}=$;W.if($0._`Array.isArray(${Z})`,()=>{W.assign(T1.default.vErrors,$0._`${T1.default.vErrors} === null ? ${Z} : ${T1.default.vErrors}.concat(${Z})`).assign(T1.default.errors,$0._`${T1.default.vErrors}.length`),(0,AD.extendErrors)($)},()=>$.error())}function MD({schemaEnv:$},Z){if(Z.async&&!$.$async)throw Error("async keyword in sync schema")}function H7($,Z,W){if(W===void 0)throw Error(`keyword "${Z}" failed to compile`);return $.scopeValue("keyword",typeof W=="function"?{ref:W}:{ref:W,code:(0,$0.stringify)(W)})}function jD($,Z,W=!1){return!Z.length||Z.some((Q)=>Q==="array"?Array.isArray($):Q==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Q||W&&typeof $>"u")}z7.validSchemaType=jD;function PD({schema:$,opts:Z,self:W,errSchemaPath:Q},Y,G){if(Array.isArray(Y.keyword)?!Y.keyword.includes(G):Y.keyword!==G)throw Error("ajv implementation error");let X=Y.dependencies;if(X===null||X===void 0?void 0:X.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${G}: ${X.join(",")}`);if(Y.validateSchema){if(!Y.validateSchema($[G])){let K=`keyword "${G}" value is invalid at path "${Q}": `+W.errorsText(Y.validateSchema.errors);if(Z.validateSchema==="log")W.logger.error(K);else throw Error(K)}}}z7.validateKeywordUsage=PD});var A7=M((L7)=>{Object.defineProperty(L7,"__esModule",{value:!0});L7.extendSubschemaMode=L7.extendSubschemaData=L7.getSubschema=void 0;var y0=y(),D7=k();function ED($,{keyword:Z,schemaProp:W,schema:Q,schemaPath:Y,errSchemaPath:G,topSchemaRef:X}){if(Z!==void 0&&Q!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(Z!==void 0){let J=$.schema[Z];return W===void 0?{schema:J,schemaPath:y0._`${$.schemaPath}${(0,y0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${Z}`}:{schema:J[W],schemaPath:y0._`${$.schemaPath}${(0,y0.getProperty)(Z)}${(0,y0.getProperty)(W)}`,errSchemaPath:`${$.errSchemaPath}/${Z}/${(0,D7.escapeFragment)(W)}`}}if(Q!==void 0){if(Y===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Q,schemaPath:Y,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}L7.getSubschema=ED;function RD($,Z,{dataProp:W,dataPropType:Q,data:Y,dataTypes:G,propertyName:X}){if(Y!==void 0&&W!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=Z;if(W!==void 0){let{errorPath:H,dataPathArr:V,opts:z}=Z,F=J.let("data",y0._`${Z.data}${(0,y0.getProperty)(W)}`,!0);K(F),$.errorPath=y0.str`${H}${(0,D7.getErrorPath)(W,Q,z.jsPropertySyntax)}`,$.parentDataProperty=y0._`${W}`,$.dataPathArr=[...V,$.parentDataProperty]}if(Y!==void 0){let H=Y instanceof y0.Name?Y:J.let("data",Y,!0);if(K(H),X!==void 0)$.propertyName=X}if(G)$.dataTypes=G;function K(H){$.data=H,$.dataLevel=Z.dataLevel+1,$.dataTypes=[],Z.definedProperties=new Set,$.parentData=Z.data,$.dataNames=[...Z.dataNames,H]}}L7.extendSubschemaData=RD;function SD($,{jtdDiscriminator:Z,jtdMetadata:W,compositeRule:Q,createErrors:Y,allErrors:G}){if(Q!==void 0)$.compositeRule=Q;if(Y!==void 0)$.createErrors=Y;if(G!==void 0)$.allErrors=G;$.jtdDiscriminator=Z,$.jtdMetadata=W}L7.extendSubschemaMode=SD});var a8=M((PS,q7)=>{q7.exports=function $(Z,W){if(Z===W)return!0;if(Z&&W&&typeof Z=="object"&&typeof W=="object"){if(Z.constructor!==W.constructor)return!1;var Q,Y,G;if(Array.isArray(Z)){if(Q=Z.length,Q!=W.length)return!1;for(Y=Q;Y--!==0;)if(!$(Z[Y],W[Y]))return!1;return!0}if(Z.constructor===RegExp)return Z.source===W.source&&Z.flags===W.flags;if(Z.valueOf!==Object.prototype.valueOf)return Z.valueOf()===W.valueOf();if(Z.toString!==Object.prototype.toString)return Z.toString()===W.toString();if(G=Object.keys(Z),Q=G.length,Q!==Object.keys(W).length)return!1;for(Y=Q;Y--!==0;)if(!Object.prototype.hasOwnProperty.call(W,G[Y]))return!1;for(Y=Q;Y--!==0;){var X=G[Y];if(!$(Z[X],W[X]))return!1}return!0}return Z!==Z&&W!==W}});var N7=M((wS,O7)=>{var B1=O7.exports=function($,Z,W){if(typeof Z=="function")W=Z,Z={};W=Z.cb||W;var Q=typeof W=="function"?W:W.pre||function(){},Y=W.post||function(){};U5(Z,Q,Y,$,"",$)};B1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};B1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};B1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};B1.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 U5($,Z,W,Q,Y,G,X,J,K,H){if(Q&&typeof Q=="object"&&!Array.isArray(Q)){Z(Q,Y,G,X,J,K,H);for(var V in Q){var z=Q[V];if(Array.isArray(z)){if(V in B1.arrayKeywords)for(var F=0;F<z.length;F++)U5($,Z,W,z[F],Y+"/"+V+"/"+F,G,Y,V,Q,F)}else if(V in B1.propsKeywords){if(z&&typeof z=="object")for(var D in z)U5($,Z,W,z[D],Y+"/"+V+"/"+bD(D),G,Y,V,Q,D)}else if(V in B1.keywords||$.allKeys&&!(V in B1.skipKeywords))U5($,Z,W,z,Y+"/"+V,G,Y,V,Q)}W(Q,Y,G,X,J,K,H)}}function bD($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var n$=M((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});w7.getSchemaRefs=w7.resolveUrl=w7.normalizeId=w7._getFullPath=w7.getFullPath=w7.inlineRef=void 0;var kD=k(),_D=a8(),xD=N7(),fD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vD($,Z=!0){if(typeof $=="boolean")return!0;if(Z===!0)return!r8($);if(!Z)return!1;return M7($)<=Z}w7.inlineRef=vD;var gD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function r8($){for(let Z in $){if(gD.has(Z))return!0;let W=$[Z];if(Array.isArray(W)&&W.some(r8))return!0;if(typeof W=="object"&&r8(W))return!0}return!1}function M7($){let Z=0;for(let W in $){if(W==="$ref")return 1/0;if(Z++,fD.has(W))continue;if(typeof $[W]=="object")(0,kD.eachItem)($[W],(Q)=>Z+=M7(Q));if(Z===1/0)return 1/0}return Z}function j7($,Z="",W){if(W!==!1)Z=e1(Z);let Q=$.parse(Z);return P7($,Q)}w7.getFullPath=j7;function P7($,Z){return $.serialize(Z).split("#")[0]+"#"}w7._getFullPath=P7;var hD=/#\/?$/;function e1($){return $?$.replace(hD,""):""}w7.normalizeId=e1;function uD($,Z,W){return W=e1(W),$.resolve(Z,W)}w7.resolveUrl=uD;var mD=/^[a-z_][-a-z0-9._]*$/i;function lD($,Z){if(typeof $=="boolean")return{};let{schemaId:W,uriResolver:Q}=this.opts,Y=e1($[W]||Z),G={"":Y},X=j7(Q,Y,!1),J={},K=new Set;return xD($,{allKeys:!0},(z,F,D,L)=>{if(L===void 0)return;let U=X+F,A=G[L];if(typeof z[W]=="string")A=q.call(this,z[W]);O.call(this,z.$anchor),O.call(this,z.$dynamicAnchor),G[F]=A;function q(j){let P=this.opts.uriResolver.resolve;if(j=e1(A?P(A,j):j),K.has(j))throw V(j);K.add(j);let N=this.refs[j];if(typeof N=="string")N=this.refs[N];if(typeof N=="object")H(z,N.schema,j);else if(j!==e1(U))if(j[0]==="#")H(z,J[j],j),J[j]=z;else this.refs[j]=U;return j}function O(j){if(typeof j=="string"){if(!mD.test(j))throw Error(`invalid anchor "${j}"`);q.call(this,`#${j}`)}}}),J;function H(z,F,D){if(F!==void 0&&!_D(z,F))throw V(D)}function V(z){return Error(`reference "${z}" resolves to more than one schema`)}}w7.getSchemaRefs=lD});var t$=M((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});u7.getData=u7.KeywordCxt=u7.validateFunctionCode=void 0;var C7=p9(),I7=i$(),o8=m8(),A5=i$(),aD=Y7(),r$=F7(),t8=A7(),T=y(),R=d0(),rD=n$(),i0=k(),a$=d$();function tD($){if(k7($)){if(_7($),b7($)){eD($);return}}y7($,()=>(0,C7.topBoolOrEmptySchema)($))}u7.validateFunctionCode=tD;function y7({gen:$,validateName:Z,schema:W,schemaEnv:Q,opts:Y},G){if(Y.code.es5)$.func(Z,T._`${R.default.data}, ${R.default.valCxt}`,Q.$async,()=>{$.code(T._`"use strict"; ${E7(W,Y)}`),sD($,Y),$.code(G)});else $.func(Z,T._`${R.default.data}, ${oD(Y)}`,Q.$async,()=>$.code(E7(W,Y)).code(G))}function oD($){return T._`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${$.dynamicRef?T._`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function sD($,Z){$.if(R.default.valCxt,()=>{if($.var(R.default.instancePath,T._`${R.default.valCxt}.${R.default.instancePath}`),$.var(R.default.parentData,T._`${R.default.valCxt}.${R.default.parentData}`),$.var(R.default.parentDataProperty,T._`${R.default.valCxt}.${R.default.parentDataProperty}`),$.var(R.default.rootData,T._`${R.default.valCxt}.${R.default.rootData}`),Z.dynamicRef)$.var(R.default.dynamicAnchors,T._`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{if($.var(R.default.instancePath,T._`""`),$.var(R.default.parentData,T._`undefined`),$.var(R.default.parentDataProperty,T._`undefined`),$.var(R.default.rootData,R.default.data),Z.dynamicRef)$.var(R.default.dynamicAnchors,T._`{}`)})}function eD($){let{schema:Z,opts:W,gen:Q}=$;y7($,()=>{if(W.$comment&&Z.$comment)f7($);if(YL($),Q.let(R.default.vErrors,null),Q.let(R.default.errors,0),W.unevaluated)$L($);x7($),JL($)});return}function $L($){let{gen:Z,validateName:W}=$;$.evaluated=Z.const("evaluated",T._`${W}.evaluated`),Z.if(T._`${$.evaluated}.dynamicProps`,()=>Z.assign(T._`${$.evaluated}.props`,T._`undefined`)),Z.if(T._`${$.evaluated}.dynamicItems`,()=>Z.assign(T._`${$.evaluated}.items`,T._`undefined`))}function E7($,Z){let W=typeof $=="object"&&$[Z.schemaId];return W&&(Z.code.source||Z.code.process)?T._`/*# sourceURL=${W} */`:T.nil}function ZL($,Z){if(k7($)){if(_7($),b7($)){WL($,Z);return}}(0,C7.boolOrEmptySchema)($,Z)}function b7({schema:$,self:Z}){if(typeof $=="boolean")return!$;for(let W in $)if(Z.RULES.all[W])return!0;return!1}function k7($){return typeof $.schema!="boolean"}function WL($,Z){let{schema:W,gen:Q,opts:Y}=$;if(Y.$comment&&W.$comment)f7($);GL($),XL($);let G=Q.const("_errs",R.default.errors);x7($,G),Q.var(Z,T._`${G} === ${R.default.errors}`)}function _7($){(0,i0.checkUnknownRules)($),QL($)}function x7($,Z){if($.opts.jtd)return R7($,[],!1,Z);let W=(0,I7.getSchemaTypes)($.schema),Q=(0,I7.coerceAndCheckDataType)($,W);R7($,W,!Q,Z)}function QL($){let{schema:Z,errSchemaPath:W,opts:Q,self:Y}=$;if(Z.$ref&&Q.ignoreKeywordsWithRef&&(0,i0.schemaHasRulesButRef)(Z,Y.RULES))Y.logger.warn(`$ref: keywords ignored in schema at path "${W}"`)}function YL($){let{schema:Z,opts:W}=$;if(Z.default!==void 0&&W.useDefaults&&W.strictSchema)(0,i0.checkStrictMode)($,"default is ignored in the schema root")}function GL($){let Z=$.schema[$.opts.schemaId];if(Z)$.baseId=(0,rD.resolveUrl)($.opts.uriResolver,$.baseId,Z)}function XL($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function f7({gen:$,schemaEnv:Z,schema:W,errSchemaPath:Q,opts:Y}){let G=W.$comment;if(Y.$comment===!0)$.code(T._`${R.default.self}.logger.log(${G})`);else if(typeof Y.$comment=="function"){let X=T.str`${Q}/$comment`,J=$.scopeValue("root",{ref:Z.root});$.code(T._`${R.default.self}.opts.$comment(${G}, ${X}, ${J}.schema)`)}}function JL($){let{gen:Z,schemaEnv:W,validateName:Q,ValidationError:Y,opts:G}=$;if(W.$async)Z.if(T._`${R.default.errors} === 0`,()=>Z.return(R.default.data),()=>Z.throw(T._`new ${Y}(${R.default.vErrors})`));else{if(Z.assign(T._`${Q}.errors`,R.default.vErrors),G.unevaluated)KL($);Z.return(T._`${R.default.errors} === 0`)}}function KL({gen:$,evaluated:Z,props:W,items:Q}){if(W instanceof T.Name)$.assign(T._`${Z}.props`,W);if(Q instanceof T.Name)$.assign(T._`${Z}.items`,Q)}function R7($,Z,W,Q){let{gen:Y,schema:G,data:X,allErrors:J,opts:K,self:H}=$,{RULES:V}=H;if(G.$ref&&(K.ignoreKeywordsWithRef||!(0,i0.schemaHasRulesButRef)(G,V))){Y.block(()=>g7($,"$ref",V.all.$ref.definition));return}if(!K.jtd)BL($,Z);Y.block(()=>{for(let F of V.rules)z(F);z(V.post)});function z(F){if(!(0,o8.shouldUseGroup)(G,F))return;if(F.type){if(Y.if((0,A5.checkDataType)(F.type,X,K.strictNumbers)),S7($,F),Z.length===1&&Z[0]===F.type&&W)Y.else(),(0,A5.reportTypeError)($);Y.endIf()}else S7($,F);if(!J)Y.if(T._`${R.default.errors} === ${Q||0}`)}}function S7($,Z){let{gen:W,schema:Q,opts:{useDefaults:Y}}=$;if(Y)(0,aD.assignDefaults)($,Z.type);W.block(()=>{for(let G of Z.rules)if((0,o8.shouldUseRule)(Q,G))g7($,G.keyword,G.definition,Z.type)})}function BL($,Z){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(HL($,Z),!$.opts.allowUnionTypes)zL($,Z);VL($,$.dataTypes)}function HL($,Z){if(!Z.length)return;if(!$.dataTypes.length){$.dataTypes=Z;return}Z.forEach((W)=>{if(!v7($.dataTypes,W))s8($,`type "${W}" not allowed by context "${$.dataTypes.join(",")}"`)}),DL($,Z)}function zL($,Z){if(Z.length>1&&!(Z.length===2&&Z.includes("null")))s8($,"use allowUnionTypes to allow union type keyword")}function VL($,Z){let W=$.self.RULES.all;for(let Q in W){let Y=W[Q];if(typeof Y=="object"&&(0,o8.shouldUseRule)($.schema,Y)){let{type:G}=Y.definition;if(G.length&&!G.some((X)=>FL(Z,X)))s8($,`missing type "${G.join(",")}" for keyword "${Q}"`)}}}function FL($,Z){return $.includes(Z)||Z==="number"&&$.includes("integer")}function v7($,Z){return $.includes(Z)||Z==="integer"&&$.includes("number")}function DL($,Z){let W=[];for(let Q of $.dataTypes)if(v7(Z,Q))W.push(Q);else if(Z.includes("integer")&&Q==="number")W.push("integer");$.dataTypes=W}function s8($,Z){let W=$.schemaEnv.baseId+$.errSchemaPath;Z+=` at "${W}" (strictTypes)`,(0,i0.checkStrictMode)($,Z,$.opts.strictTypes)}class e8{constructor($,Z,W){if((0,r$.validateKeywordUsage)($,Z,W),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=W,this.data=$.data,this.schema=$.schema[W],this.$data=Z.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,i0.schemaRefOrVal)($,this.schema,W,this.$data),this.schemaType=Z.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=Z,this.$data)this.schemaCode=$.gen.const("vSchema",h7(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,r$.validSchemaType)(this.schema,Z.schemaType,Z.allowUndefined))throw Error(`${W} value must be ${JSON.stringify(Z.schemaType)}`);if("code"in Z?Z.trackErrors:Z.errors!==!1)this.errsCount=$.gen.const("_errs",R.default.errors)}result($,Z,W){this.failResult((0,T.not)($),Z,W)}failResult($,Z,W){if(this.gen.if($),W)W();else this.error();if(Z){if(this.gen.else(),Z(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,Z){this.failResult((0,T.not)($),void 0,Z)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:Z}=this;this.fail(T._`${Z} !== undefined && (${(0,T.or)(this.invalid$data(),$)})`)}error($,Z,W){if(Z){this.setParams(Z),this._error($,W),this.setParams({});return}this._error($,W)}_error($,Z){($?a$.reportExtraError:a$.reportError)(this,this.def.error,Z)}$dataError(){(0,a$.reportError)(this,this.def.$dataError||a$.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,a$.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,Z){if(Z)Object.assign(this.params,$);else this.params=$}block$data($,Z,W=T.nil){this.gen.block(()=>{this.check$data($,W),Z()})}check$data($=T.nil,Z=T.nil){if(!this.$data)return;let{gen:W,schemaCode:Q,schemaType:Y,def:G}=this;if(W.if((0,T.or)(T._`${Q} === undefined`,Z)),$!==T.nil)W.assign($,!0);if(Y.length||G.validateSchema){if(W.elseIf(this.invalid$data()),this.$dataError(),$!==T.nil)W.assign($,!1)}W.else()}invalid$data(){let{gen:$,schemaCode:Z,schemaType:W,def:Q,it:Y}=this;return(0,T.or)(G(),X());function G(){if(W.length){if(!(Z instanceof T.Name))throw Error("ajv implementation error");let J=Array.isArray(W)?W:[W];return T._`${(0,A5.checkDataTypes)(J,Z,Y.opts.strictNumbers,A5.DataType.Wrong)}`}return T.nil}function X(){if(Q.validateSchema){let J=$.scopeValue("validate$data",{ref:Q.validateSchema});return T._`!${J}(${Z})`}return T.nil}}subschema($,Z){let W=(0,t8.getSubschema)(this.it,$);(0,t8.extendSubschemaData)(W,this.it,$),(0,t8.extendSubschemaMode)(W,$);let Q={...this.it,...W,items:void 0,props:void 0};return ZL(Q,Z),Q}mergeEvaluated($,Z){let{it:W,gen:Q}=this;if(!W.opts.unevaluated)return;if(W.props!==!0&&$.props!==void 0)W.props=i0.mergeEvaluated.props(Q,$.props,W.props,Z);if(W.items!==!0&&$.items!==void 0)W.items=i0.mergeEvaluated.items(Q,$.items,W.items,Z)}mergeValidEvaluated($,Z){let{it:W,gen:Q}=this;if(W.opts.unevaluated&&(W.props!==!0||W.items!==!0))return Q.if(Z,()=>this.mergeEvaluated($,T.Name)),!0}}u7.KeywordCxt=e8;function g7($,Z,W,Q){let Y=new e8($,W,Z);if("code"in W)W.code(Y,Q);else if(Y.$data&&W.validate)(0,r$.funcKeywordCode)(Y,W);else if("macro"in W)(0,r$.macroKeywordCode)(Y,W);else if(W.compile||W.validate)(0,r$.funcKeywordCode)(Y,W)}var LL=/^\/(?:[^~]|~0|~1)*$/,UL=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function h7($,{dataLevel:Z,dataNames:W,dataPathArr:Q}){let Y,G;if($==="")return R.default.rootData;if($[0]==="/"){if(!LL.test($))throw Error(`Invalid JSON-pointer: ${$}`);Y=$,G=R.default.rootData}else{let H=UL.exec($);if(!H)throw Error(`Invalid JSON-pointer: ${$}`);let V=+H[1];if(Y=H[2],Y==="#"){if(V>=Z)throw Error(K("property/index",V));return Q[Z-V]}if(V>Z)throw Error(K("data",V));if(G=W[Z-V],!Y)return G}let X=G,J=Y.split("/");for(let H of J)if(H)G=T._`${G}${(0,T.getProperty)((0,i0.unescapeJsonPointer)(H))}`,X=T._`${X} && ${G}`;return X;function K(H,V){return`Cannot access ${H} ${V} levels up, current level is ${Z}`}}u7.getData=h7});var q5=M((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});class l7 extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}p7.default=l7});var o$=M((d7)=>{Object.defineProperty(d7,"__esModule",{value:!0});var $W=n$();class c7 extends Error{constructor($,Z,W,Q){super(Q||`can't resolve reference ${W} from id ${Z}`);this.missingRef=(0,$W.resolveUrl)($,Z,W),this.missingSchema=(0,$W.normalizeId)((0,$W.getFullPath)($,this.missingRef))}}d7.default=c7});var N5=M((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});a7.resolveSchema=a7.getCompilingSchema=a7.resolveRef=a7.compileSchema=a7.SchemaEnv=void 0;var M0=y(),ML=q5(),I1=d0(),j0=n$(),i7=k(),jL=t$();class s${constructor($){var Z;this.refs={},this.dynamicAnchors={};let W;if(typeof $.schema=="object")W=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(Z=$.baseId)!==null&&Z!==void 0?Z:(0,j0.normalizeId)(W===null||W===void 0?void 0:W[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=W===null||W===void 0?void 0:W.$async,this.refs={}}}a7.SchemaEnv=s$;function WW($){let Z=n7.call(this,$);if(Z)return Z;let W=(0,j0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Q,lines:Y}=this.opts.code,{ownProperties:G}=this.opts,X=new M0.CodeGen(this.scope,{es5:Q,lines:Y,ownProperties:G}),J;if($.$async)J=X.scopeValue("Error",{ref:ML.default,code:M0._`require("ajv/dist/runtime/validation_error").default`});let K=X.scopeName("validate");$.validateName=K;let H={gen:X,allErrors:this.opts.allErrors,data:I1.default.data,parentData:I1.default.parentData,parentDataProperty:I1.default.parentDataProperty,dataNames:[I1.default.data],dataPathArr:[M0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,M0.stringify)($.schema)}:{ref:$.schema}),validateName:K,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:W,baseId:$.baseId||W,schemaPath:M0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:M0._`""`,opts:this.opts,self:this},V;try{this._compilations.add($),(0,jL.validateFunctionCode)(H),X.optimize(this.opts.code.optimize);let z=X.toString();if(V=`${X.scopeRefs(I1.default.scope)}return ${z}`,this.opts.code.process)V=this.opts.code.process(V,$);let D=Function(`${I1.default.self}`,`${I1.default.scope}`,V)(this,this.scope.get());if(this.scope.value(K,{ref:D}),D.errors=null,D.schema=$.schema,D.schemaEnv=$,$.$async)D.$async=!0;if(this.opts.code.source===!0)D.source={validateName:K,validateCode:z,scopeValues:X._values};if(this.opts.unevaluated){let{props:L,items:U}=H;if(D.evaluated={props:L instanceof M0.Name?void 0:L,items:U instanceof M0.Name?void 0:U,dynamicProps:L instanceof M0.Name,dynamicItems:U instanceof M0.Name},D.source)D.source.evaluated=(0,M0.stringify)(D.evaluated)}return $.validate=D,$}catch(z){if(delete $.validate,delete $.validateName,V)this.logger.error("Error compiling schema, function code:",V);throw z}finally{this._compilations.delete($)}}a7.compileSchema=WW;function PL($,Z,W){var Q;W=(0,j0.resolveUrl)(this.opts.uriResolver,Z,W);let Y=$.refs[W];if(Y)return Y;let G=IL.call(this,$,W);if(G===void 0){let X=(Q=$.localRefs)===null||Q===void 0?void 0:Q[W],{schemaId:J}=this.opts;if(X)G=new s$({schema:X,schemaId:J,root:$,baseId:Z})}if(G===void 0)return;return $.refs[W]=wL.call(this,G)}a7.resolveRef=PL;function wL($){if((0,j0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:WW.call(this,$)}function n7($){for(let Z of this._compilations)if(TL(Z,$))return Z}a7.getCompilingSchema=n7;function TL($,Z){return $.schema===Z.schema&&$.root===Z.root&&$.baseId===Z.baseId}function IL($,Z){let W;while(typeof(W=this.refs[Z])=="string")Z=W;return W||this.schemas[Z]||O5.call(this,$,Z)}function O5($,Z){let W=this.opts.uriResolver.parse(Z),Q=(0,j0._getFullPath)(this.opts.uriResolver,W),Y=(0,j0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Q===Y)return ZW.call(this,W,$);let G=(0,j0.normalizeId)(Q),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let J=O5.call(this,$,X);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return ZW.call(this,W,J)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)WW.call(this,X);if(G===(0,j0.normalizeId)(Z)){let{schema:J}=X,{schemaId:K}=this.opts,H=J[K];if(H)Y=(0,j0.resolveUrl)(this.opts.uriResolver,Y,H);return new s$({schema:J,schemaId:K,root:$,baseId:Y})}return ZW.call(this,W,X)}a7.resolveSchema=O5;var EL=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function ZW($,{baseId:Z,schema:W,root:Q}){var Y;if(((Y=$.fragment)===null||Y===void 0?void 0:Y[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof W==="boolean")return;let K=W[(0,i7.unescapeFragment)(J)];if(K===void 0)return;W=K;let H=typeof W==="object"&&W[this.opts.schemaId];if(!EL.has(J)&&H)Z=(0,j0.resolveUrl)(this.opts.uriResolver,Z,H)}let G;if(typeof W!="boolean"&&W.$ref&&!(0,i7.schemaHasRulesButRef)(W,this.RULES)){let J=(0,j0.resolveUrl)(this.opts.uriResolver,Z,W.$ref);G=O5.call(this,Q,J)}let{schemaId:X}=this.opts;if(G=G||new s$({schema:W,schemaId:X,root:Q,baseId:Z}),G.schema!==G.root.schema)return G;return}});var t7=M((CS,bL)=>{bL.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 GW=M((yS,WY)=>{var kL=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),s7=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),QW=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),e7=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),_L=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function YW($){let Z="",W=0,Q=0;for(Q=0;Q<$.length;Q++){if(W=$[Q].charCodeAt(0),W===48)continue;if(!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";Z+=$[Q];break}for(Q+=1;Q<$.length;Q++){if(W=$[Q].charCodeAt(0),!(W>=48&&W<=57||W>=65&&W<=70||W>=97&&W<=102))return"";Z+=$[Q]}return Z}var xL=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o7($){return $.length=0,!0}function fL($,Z,W){if($.length){let Q=YW($);if(Q!=="")Z.push(Q);else return W.error=!0,!1;$.length=0}return!0}function vL($){let Z=0,W={error:!1,address:"",zone:""},Q=[],Y=[],G=!1,X=!1,J=fL;for(let K=0;K<$.length;K++){let H=$[K];if(H==="["||H==="]")continue;if(H===":"){if(G===!0)X=!0;if(!J(Y,Q,W))break;if(++Z>7){W.error=!0;break}if(K>0&&$[K-1]===":")G=!0;Q.push(":");continue}else if(H==="%"){if(!J(Y,Q,W))break;J=o7}else{Y.push(H);continue}}if(Y.length)if(J===o7)W.zone=Y.join("");else if(X)Q.push(Y.join(""));else Q.push(YW(Y));return W.address=Q.join(""),W}function $Y($){if(gL($,":")<2)return{host:$,isIPV6:!1};let Z=vL($);if(!Z.error){let{address:W,address:Q}=Z;if(Z.zone)W+="%"+Z.zone,Q+="%25"+Z.zone;return{host:W,isIPV6:!0,escapedHost:Q}}else return{host:$,isIPV6:!1}}function gL($,Z){let W=0;for(let Q=0;Q<$.length;Q++)if($[Q]===Z)W++;return W}function hL($){let Z=$,W=[],Q=-1,Y=0;while(Y=Z.length){if(Y===1)if(Z===".")break;else if(Z==="/"){W.push("/");break}else{W.push(Z);break}else if(Y===2){if(Z[0]==="."){if(Z[1]===".")break;else if(Z[1]==="/"){Z=Z.slice(2);continue}}else if(Z[0]==="/"){if(Z[1]==="."||Z[1]==="/"){W.push("/");break}}}else if(Y===3){if(Z==="/.."){if(W.length!==0)W.pop();W.push("/");break}}if(Z[0]==="."){if(Z[1]==="."){if(Z[2]==="/"){Z=Z.slice(3);continue}}else if(Z[1]==="/"){Z=Z.slice(2);continue}}else if(Z[0]==="/"){if(Z[1]==="."){if(Z[2]==="/"){Z=Z.slice(2);continue}else if(Z[2]==="."){if(Z[3]==="/"){if(Z=Z.slice(3),W.length!==0)W.pop();continue}}}}if((Q=Z.indexOf("/",1))===-1){W.push(Z);break}else W.push(Z.slice(0,Q)),Z=Z.slice(Q)}return W.join("")}var uL={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},mL=/[@/?#:]/g,lL=/[@/?#]/g;function ZY($,Z){let W=Z?lL:mL;return W.lastIndex=0,$.replace(W,(Q)=>uL[Q])}function pL($,Z=!1){if($.indexOf("%")===-1)return $;let W="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let Y=$.slice(Q+1,Q+3);if(QW(Y)){let G=Y.toUpperCase(),X=String.fromCharCode(parseInt(G,16));if(Z&&e7(X))W+=X;else W+="%"+G;Q+=2;continue}}W+=$[Q]}return W}function cL($){let Z="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Q=$.slice(W+1,W+3);if(QW(Q)){let Y=Q.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&e7(G))Z+=G;else Z+="%"+Y;W+=2;continue}}if(_L($[W]))Z+=$[W];else Z+=escape($[W])}return Z}function dL($){let Z="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Q=$.slice(W+1,W+3);if(QW(Q)){Z+="%"+Q.toUpperCase(),W+=2;continue}}Z+=escape($[W])}return Z}function iL($){let Z=[];if($.userinfo!==void 0)Z.push($.userinfo),Z.push("@");if($.host!==void 0){let W=unescape($.host);if(!s7(W)){let Q=$Y(W);if(Q.isIPV6===!0)W=`[${Q.escapedHost}]`;else W=ZY(W,!1)}Z.push(W)}if(typeof $.port==="number"||typeof $.port==="string")Z.push(":"),Z.push(String($.port));return Z.length?Z.join(""):void 0}WY.exports={nonSimpleDomain:xL,recomposeAuthority:iL,reescapeHostDelimiters:ZY,normalizePercentEncoding:pL,normalizePathEncoding:cL,escapePreservingEscapes:dL,removeDotSegments:hL,isIPv4:s7,isUUID:kL,normalizeIPv6:$Y,stringArrayToHexStripped:YW}});var JY=M((bS,XY)=>{var{isUUID:nL}=GW(),aL=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,rL=["http","https","ws","wss","urn","urn:uuid"];function tL($){return rL.indexOf($)!==-1}function XW($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function QY($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function YY($){let Z=String($.scheme).toLowerCase()==="https";if($.port===(Z?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function oL($){return $.secure=XW($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function sL($){if($.port===(XW($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[Z,W]=$.resourceName.split("?");$.path=Z&&Z!=="/"?Z:void 0,$.query=W,$.resourceName=void 0}return $.fragment=void 0,$}function eL($,Z){if(!$.path)return $.error="URN can not be parsed",$;let W=$.path.match(aL);if(W){let Q=Z.scheme||$.scheme||"urn";$.nid=W[1].toLowerCase(),$.nss=W[2];let Y=`${Q}:${Z.nid||$.nid}`,G=JW(Y);if($.path=void 0,G)$=G.parse($,Z)}else $.error=$.error||"URN can not be parsed.";return $}function $U($,Z){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let W=Z.scheme||$.scheme||"urn",Q=$.nid.toLowerCase(),Y=`${W}:${Z.nid||Q}`,G=JW(Y);if(G)$=G.serialize($,Z);let X=$,J=$.nss;return X.path=`${Q||Z.nid}:${J}`,Z.skipEscape=!0,X}function ZU($,Z){let W=$;if(W.uuid=W.nss,W.nss=void 0,!Z.tolerant&&(!W.uuid||!nL(W.uuid)))W.error=W.error||"UUID is not valid.";return W}function WU($){let Z=$;return Z.nss=($.uuid||"").toLowerCase(),Z}var GY={scheme:"http",domainHost:!0,parse:QY,serialize:YY},QU={scheme:"https",domainHost:GY.domainHost,parse:QY,serialize:YY},M5={scheme:"ws",domainHost:!0,parse:oL,serialize:sL},YU={scheme:"wss",domainHost:M5.domainHost,parse:M5.parse,serialize:M5.serialize},GU={scheme:"urn",parse:eL,serialize:$U,skipNormalize:!0},XU={scheme:"urn:uuid",parse:ZU,serialize:WU,skipNormalize:!0},j5={http:GY,https:QU,ws:M5,wss:YU,urn:GU,"urn:uuid":XU};Object.setPrototypeOf(j5,null);function JW($){return $&&(j5[$]||j5[$.toLowerCase()])||void 0}XY.exports={wsIsSecure:XW,SCHEMES:j5,isValidSchemeName:tL,getSchemeHandler:JW}});var FY=M((kS,P5)=>{var{normalizeIPv6:JU,removeDotSegments:e$,recomposeAuthority:KU,normalizePercentEncoding:BU,normalizePathEncoding:HU,escapePreservingEscapes:zU,reescapeHostDelimiters:VU,isIPv4:FU,nonSimpleDomain:DU}=GW(),{SCHEMES:LU,getSchemeHandler:BY}=JY();function UU($,Z){if(typeof $==="string")$=jU($,Z);else if(typeof $==="object")$=$$(E1($,Z),Z);return $}function AU($,Z,W){let Q=W?Object.assign({scheme:"null"},W):{scheme:"null"},Y=HY($$($,Q),$$(Z,Q),Q,!0);return Q.skipEscape=!0,E1(Y,Q)}function HY($,Z,W,Q){let Y={};if(!Q)$=$$(E1($,W),W),Z=$$(E1(Z,W),W);if(W=W||{},!W.tolerant&&Z.scheme)Y.scheme=Z.scheme,Y.userinfo=Z.userinfo,Y.host=Z.host,Y.port=Z.port,Y.path=e$(Z.path||""),Y.query=Z.query;else{if(Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)Y.userinfo=Z.userinfo,Y.host=Z.host,Y.port=Z.port,Y.path=e$(Z.path||""),Y.query=Z.query;else{if(!Z.path)if(Y.path=$.path,Z.query!==void 0)Y.query=Z.query;else Y.query=$.query;else{if(Z.path[0]==="/")Y.path=e$(Z.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)Y.path="/"+Z.path;else if(!$.path)Y.path=Z.path;else Y.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+Z.path;Y.path=e$(Y.path)}Y.query=Z.query}Y.userinfo=$.userinfo,Y.host=$.host,Y.port=$.port}Y.scheme=$.scheme}return Y.fragment=Z.fragment,Y}function qU($,Z,W){let Q=KY($,W),Y=KY(Z,W);return Q!==void 0&&Y!==void 0&&Q.toLowerCase()===Y.toLowerCase()}function E1($,Z){let W={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},Q=Object.assign({},Z),Y=[],G=BY(Q.scheme||W.scheme);if(G&&G.serialize)G.serialize(W,Q);if(W.path!==void 0)if(!Q.skipEscape){if(W.path=zU(W.path),W.scheme!==void 0)W.path=W.path.split("%3A").join(":")}else W.path=BU(W.path);if(Q.reference!=="suffix"&&W.scheme)Y.push(W.scheme,":");let X=KU(W);if(X!==void 0){if(Q.reference!=="suffix")Y.push("//");if(Y.push(X),W.path&&W.path[0]!=="/")Y.push("/")}if(W.path!==void 0){let J=W.path;if(!Q.absolutePath&&(!G||!G.absolutePath))J=e$(J);if(X===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);Y.push(J)}if(W.query!==void 0)Y.push("?",W.query);if(W.fragment!==void 0)Y.push("#",W.fragment);return Y.join("")}var OU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,NU=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function MU($,Z){if(Z[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function zY($,Z){let W=Object.assign({},Z),Q={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Y=!1,G=!1;if(W.reference==="suffix")if(W.scheme)$=W.scheme+":"+$;else $="//"+$;let X=$.match(NU);if(X!==null&&X[1].indexOf("\\")!==-1)Q.error="URI authority must not contain a literal backslash.",Y=!0;let J=$.match(OU);if(J){if(Q.scheme=J[1],Q.userinfo=J[3],Q.host=J[4],Q.port=parseInt(J[5],10),Q.path=J[6]||"",Q.query=J[7],Q.fragment=J[8],isNaN(Q.port))Q.port=J[5];let K=MU(Q,J);if(K!==void 0)Q.error=Q.error||K,Y=!0;if(Q.host)if(FU(Q.host)===!1){let z=JU(Q.host);Q.host=z.host.toLowerCase(),G=z.isIPV6}else G=!0;if(Q.scheme===void 0&&Q.userinfo===void 0&&Q.host===void 0&&Q.port===void 0&&Q.query===void 0&&!Q.path)Q.reference="same-document";else if(Q.scheme===void 0)Q.reference="relative";else if(Q.fragment===void 0)Q.reference="absolute";else Q.reference="uri";if(W.reference&&W.reference!=="suffix"&&W.reference!==Q.reference)Q.error=Q.error||"URI is not a "+W.reference+" reference.";let H=BY(W.scheme||Q.scheme);if(!W.unicodeSupport&&(!H||!H.unicodeSupport)){if(Q.host&&(W.domainHost||H&&H.domainHost)&&G===!1&&DU(Q.host))try{Q.host=new URL("http://"+Q.host).hostname}catch(V){Q.error=Q.error||"Host's domain name can not be converted to ASCII: "+V}}if(!H||H&&!H.skipNormalize){if($.indexOf("%")!==-1){if(Q.scheme!==void 0)Q.scheme=unescape(Q.scheme);if(Q.host!==void 0)Q.host=VU(unescape(Q.host),G)}if(Q.path)Q.path=HU(Q.path);if(Q.fragment)try{Q.fragment=encodeURI(decodeURIComponent(Q.fragment))}catch{Q.error=Q.error||"URI malformed"}}if(H&&H.parse)H.parse(Q,W)}else Q.error=Q.error||"URI can not be parsed.";return{parsed:Q,malformedAuthorityOrPort:Y}}function $$($,Z){return zY($,Z).parsed}function jU($,Z){return VY($,Z).normalized}function VY($,Z){let{parsed:W,malformedAuthorityOrPort:Q}=zY($,Z);return{normalized:Q?$:E1(W,Z),malformedAuthorityOrPort:Q}}function KY($,Z){if(typeof $==="string"){let{normalized:W,malformedAuthorityOrPort:Q}=VY($,Z);return Q?void 0:W}if(typeof $==="object")return E1($,Z)}var KW={SCHEMES:LU,normalize:UU,resolve:AU,resolveComponent:HY,equal:qU,serialize:E1,parse:$$};P5.exports=KW;P5.exports.default=KW;P5.exports.fastUri=KW});var UY=M((LY)=>{Object.defineProperty(LY,"__esModule",{value:!0});var DY=FY();DY.code='require("ajv/dist/runtime/uri").default';LY.default=DY});var wY=M((n0)=>{Object.defineProperty(n0,"__esModule",{value:!0});n0.CodeGen=n0.Name=n0.nil=n0.stringify=n0.str=n0._=n0.KeywordCxt=void 0;var wU=t$();Object.defineProperty(n0,"KeywordCxt",{enumerable:!0,get:function(){return wU.KeywordCxt}});var Z$=y();Object.defineProperty(n0,"_",{enumerable:!0,get:function(){return Z$._}});Object.defineProperty(n0,"str",{enumerable:!0,get:function(){return Z$.str}});Object.defineProperty(n0,"stringify",{enumerable:!0,get:function(){return Z$.stringify}});Object.defineProperty(n0,"nil",{enumerable:!0,get:function(){return Z$.nil}});Object.defineProperty(n0,"Name",{enumerable:!0,get:function(){return Z$.Name}});Object.defineProperty(n0,"CodeGen",{enumerable:!0,get:function(){return Z$.CodeGen}});var TU=q5(),MY=o$(),IU=u8(),$Z=N5(),EU=y(),ZZ=n$(),w5=i$(),HW=k(),AY=t7(),RU=UY(),jY=($,Z)=>new RegExp($,Z);jY.code="new RegExp";var SU=["removeAdditional","useDefaults","coerceTypes"],CU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),yU={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."},bU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qY=200;function kU($){var Z,W,Q,Y,G,X,J,K,H,V,z,F,D,L,U,A,q,O,j,P,N,x,m,w,f;let i=$.strict,v=(Z=$.code)===null||Z===void 0?void 0:Z.optimize,L0=v===!0||v===void 0?1:v||0,H$=(Q=(W=$.code)===null||W===void 0?void 0:W.regExp)!==null&&Q!==void 0?Q:jY,R0=(Y=$.uriResolver)!==null&&Y!==void 0?Y:RU.default;return{strictSchema:(X=(G=$.strictSchema)!==null&&G!==void 0?G:i)!==null&&X!==void 0?X:!0,strictNumbers:(K=(J=$.strictNumbers)!==null&&J!==void 0?J:i)!==null&&K!==void 0?K:!0,strictTypes:(V=(H=$.strictTypes)!==null&&H!==void 0?H:i)!==null&&V!==void 0?V:"log",strictTuples:(F=(z=$.strictTuples)!==null&&z!==void 0?z:i)!==null&&F!==void 0?F:"log",strictRequired:(L=(D=$.strictRequired)!==null&&D!==void 0?D:i)!==null&&L!==void 0?L:!1,code:$.code?{...$.code,optimize:L0,regExp:H$}:{optimize:L0,regExp:H$},loopRequired:(U=$.loopRequired)!==null&&U!==void 0?U:qY,loopEnum:(A=$.loopEnum)!==null&&A!==void 0?A:qY,meta:(q=$.meta)!==null&&q!==void 0?q:!0,messages:(O=$.messages)!==null&&O!==void 0?O:!0,inlineRefs:(j=$.inlineRefs)!==null&&j!==void 0?j:!0,schemaId:(P=$.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(N=$.addUsedSchema)!==null&&N!==void 0?N:!0,validateSchema:(x=$.validateSchema)!==null&&x!==void 0?x:!0,validateFormats:(m=$.validateFormats)!==null&&m!==void 0?m:!0,unicodeRegExp:(w=$.unicodeRegExp)!==null&&w!==void 0?w:!0,int32range:(f=$.int32range)!==null&&f!==void 0?f:!0,uriResolver:R0}}class T5{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...kU($)};let{es5:Z,lines:W}=this.opts.code;this.scope=new EU.ValueScope({scope:{},prefixes:CU,es5:Z,lines:W}),this.logger=hU($.logger);let Q=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,IU.getRules)(),OY.call(this,yU,$,"NOT SUPPORTED"),OY.call(this,bU,$,"DEPRECATED","warn"),this._metaOpts=vU.call(this),$.formats)xU.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)fU.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);_U.call(this),$.validateFormats=Q}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:Z,schemaId:W}=this.opts,Q=AY;if(W==="id")Q={...AY},Q.id=Q.$id,delete Q.$id;if(Z&&$)this.addMetaSchema(Q,Q[W],!1)}defaultMeta(){let{meta:$,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[Z]||$:void 0}validate($,Z){let W;if(typeof $=="string"){if(W=this.getSchema($),!W)throw Error(`no schema with key or ref "${$}"`)}else W=this.compile($);let Q=W(Z);if(!("$async"in W))this.errors=W.errors;return Q}compile($,Z){let W=this._addSchema($,Z);return W.validate||this._compileSchemaEnv(W)}compileAsync($,Z){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:W}=this.opts;return Q.call(this,$,Z);async function Q(H,V){await Y.call(this,H.$schema);let z=this._addSchema(H,V);return z.validate||G.call(this,z)}async function Y(H){if(H&&!this.getSchema(H))await Q.call(this,{$ref:H},!0)}async function G(H){try{return this._compileSchemaEnv(H)}catch(V){if(!(V instanceof MY.default))throw V;return X.call(this,V),await J.call(this,V.missingSchema),G.call(this,H)}}function X({missingSchema:H,missingRef:V}){if(this.refs[H])throw Error(`AnySchema ${H} is loaded but ${V} cannot be resolved`)}async function J(H){let V=await K.call(this,H);if(!this.refs[H])await Y.call(this,V.$schema);if(!this.refs[H])this.addSchema(V,H,Z)}async function K(H){let V=this._loading[H];if(V)return V;try{return await(this._loading[H]=W(H))}finally{delete this._loading[H]}}}addSchema($,Z,W,Q=this.opts.validateSchema){if(Array.isArray($)){for(let G of $)this.addSchema(G,void 0,W,Q);return this}let Y;if(typeof $==="object"){let{schemaId:G}=this.opts;if(Y=$[G],Y!==void 0&&typeof Y!="string")throw Error(`schema ${G} must be string`)}return Z=(0,ZZ.normalizeId)(Z||Y),this._checkUnique(Z),this.schemas[Z]=this._addSchema($,W,Z,Q,!0),this}addMetaSchema($,Z,W=this.opts.validateSchema){return this.addSchema($,Z,!0,W),this}validateSchema($,Z){if(typeof $=="boolean")return!0;let W;if(W=$.$schema,W!==void 0&&typeof W!="string")throw Error("$schema must be a string");if(W=W||this.opts.defaultMeta||this.defaultMeta(),!W)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let Q=this.validate(W,$);if(!Q&&Z){let Y="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Y);else throw Error(Y)}return Q}getSchema($){let Z;while(typeof(Z=NY.call(this,$))=="string")$=Z;if(Z===void 0){let{schemaId:W}=this.opts,Q=new $Z.SchemaEnv({schema:{},schemaId:W});if(Z=$Z.resolveSchema.call(this,Q,$),!Z)return;this.refs[$]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let Z=NY.call(this,$);if(typeof Z=="object")this._cache.delete(Z.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let Z=$;this._cache.delete(Z);let W=$[this.opts.schemaId];if(W)W=(0,ZZ.normalizeId)(W),delete this.schemas[W],delete this.refs[W];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let Z of $)this.addKeyword(Z);return this}addKeyword($,Z){let W;if(typeof $=="string"){if(W=$,typeof Z=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=W}else if(typeof $=="object"&&Z===void 0){if(Z=$,W=Z.keyword,Array.isArray(W)&&!W.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(mU.call(this,W,Z),!Z)return(0,HW.eachItem)(W,(Y)=>BW.call(this,Y)),this;pU.call(this,Z);let Q={...Z,type:(0,w5.getJSONTypes)(Z.type),schemaType:(0,w5.getJSONTypes)(Z.schemaType)};return(0,HW.eachItem)(W,Q.type.length===0?(Y)=>BW.call(this,Y,Q):(Y)=>Q.type.forEach((G)=>BW.call(this,Y,Q,G))),this}getKeyword($){let Z=this.RULES.all[$];return typeof Z=="object"?Z.definition:!!Z}removeKeyword($){let{RULES:Z}=this;delete Z.keywords[$],delete Z.all[$];for(let W of Z.rules){let Q=W.rules.findIndex((Y)=>Y.keyword===$);if(Q>=0)W.rules.splice(Q,1)}return this}addFormat($,Z){if(typeof Z=="string")Z=new RegExp(Z);return this.formats[$]=Z,this}errorsText($=this.errors,{separator:Z=", ",dataVar:W="data"}={}){if(!$||$.length===0)return"No errors";return $.map((Q)=>`${W}${Q.instancePath} ${Q.message}`).reduce((Q,Y)=>Q+Z+Y)}$dataMetaSchema($,Z){let W=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Q of Z){let Y=Q.split("/").slice(1),G=$;for(let X of Y)G=G[X];for(let X in W){let J=W[X];if(typeof J!="object")continue;let{$data:K}=J.definition,H=G[X];if(K&&H)G[X]=PY(H)}}return $}_removeAllSchemas($,Z){for(let W in $){let Q=$[W];if(!Z||Z.test(W)){if(typeof Q=="string")delete $[W];else if(Q&&!Q.meta)this._cache.delete(Q.schema),delete $[W]}}}_addSchema($,Z,W,Q=this.opts.validateSchema,Y=this.opts.addUsedSchema){let G,{schemaId:X}=this.opts;if(typeof $=="object")G=$[X];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get($);if(J!==void 0)return J;W=(0,ZZ.normalizeId)(G||W);let K=ZZ.getSchemaRefs.call(this,$,W);if(J=new $Z.SchemaEnv({schema:$,schemaId:X,meta:Z,baseId:W,localRefs:K}),this._cache.set(J.schema,J),Y&&!W.startsWith("#")){if(W)this._checkUnique(W);this.refs[W]=J}if(Q)this.validateSchema($,!0);return J}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else $Z.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let Z=this.opts;this.opts=this._metaOpts;try{$Z.compileSchema.call(this,$)}finally{this.opts=Z}}}T5.ValidationError=TU.default;T5.MissingRefError=MY.default;n0.default=T5;function OY($,Z,W,Q="error"){for(let Y in $){let G=Y;if(G in Z)this.logger[Q](`${W}: option ${Y}. ${$[G]}`)}}function NY($){return $=(0,ZZ.normalizeId)($),this.schemas[$]||this.refs[$]}function _U(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let Z in $)this.addSchema($[Z],Z)}function xU(){for(let $ in this.opts.formats){let Z=this.opts.formats[$];if(Z)this.addFormat($,Z)}}function fU($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let Z in $){let W=$[Z];if(!W.keyword)W.keyword=Z;this.addKeyword(W)}}function vU(){let $={...this.opts};for(let Z of SU)delete $[Z];return $}var gU={log(){},warn(){},error(){}};function hU($){if($===!1)return gU;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var uU=/^[a-z_$][a-z0-9_$:-]*$/i;function mU($,Z){let{RULES:W}=this;if((0,HW.eachItem)($,(Q)=>{if(W.keywords[Q])throw Error(`Keyword ${Q} is already defined`);if(!uU.test(Q))throw Error(`Keyword ${Q} has invalid name`)}),!Z)return;if(Z.$data&&!(("code"in Z)||("validate"in Z)))throw Error('$data keyword must have "code" or "validate" function')}function BW($,Z,W){var Q;let Y=Z===null||Z===void 0?void 0:Z.post;if(W&&Y)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=Y?G.post:G.rules.find(({type:K})=>K===W);if(!X)X={type:W,rules:[]},G.rules.push(X);if(G.keywords[$]=!0,!Z)return;let J={keyword:$,definition:{...Z,type:(0,w5.getJSONTypes)(Z.type),schemaType:(0,w5.getJSONTypes)(Z.schemaType)}};if(Z.before)lU.call(this,X,J,Z.before);else X.rules.push(J);G.all[$]=J,(Q=Z.implements)===null||Q===void 0||Q.forEach((K)=>this.addKeyword(K))}function lU($,Z,W){let Q=$.rules.findIndex((Y)=>Y.keyword===W);if(Q>=0)$.rules.splice(Q,0,Z);else $.rules.push(Z),this.logger.warn(`rule ${W} is not defined`)}function pU($){let{metaSchema:Z}=$;if(Z===void 0)return;if($.$data&&this.opts.$data)Z=PY(Z);$.validateSchema=this.compile(Z,!0)}var cU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function PY($){return{anyOf:[$,cU]}}});var IY=M((TY)=>{Object.defineProperty(TY,"__esModule",{value:!0});var nU={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};TY.default=nU});var bY=M((CY)=>{Object.defineProperty(CY,"__esModule",{value:!0});CY.callRef=CY.getValidate=void 0;var rU=o$(),EY=F0(),Y0=y(),W$=d0(),RY=N5(),I5=k(),tU={keyword:"$ref",schemaType:"string",code($){let{gen:Z,schema:W,it:Q}=$,{baseId:Y,schemaEnv:G,validateName:X,opts:J,self:K}=Q,{root:H}=G;if((W==="#"||W==="#/")&&Y===H.baseId)return z();let V=RY.resolveRef.call(K,H,Y,W);if(V===void 0)throw new rU.default(Q.opts.uriResolver,Y,W);if(V instanceof RY.SchemaEnv)return F(V);return D(V);function z(){if(G===H)return E5($,X,G,G.$async);let L=Z.scopeValue("root",{ref:H});return E5($,Y0._`${L}.validate`,H,H.$async)}function F(L){let U=SY($,L);E5($,U,L,L.$async)}function D(L){let U=Z.scopeValue("schema",J.code.source===!0?{ref:L,code:(0,Y0.stringify)(L)}:{ref:L}),A=Z.name("valid"),q=$.subschema({schema:L,dataTypes:[],schemaPath:Y0.nil,topSchemaRef:U,errSchemaPath:W},A);$.mergeEvaluated(q),$.ok(A)}}};function SY($,Z){let{gen:W}=$;return Z.validate?W.scopeValue("validate",{ref:Z.validate}):Y0._`${W.scopeValue("wrapper",{ref:Z})}.validate`}CY.getValidate=SY;function E5($,Z,W,Q){let{gen:Y,it:G}=$,{allErrors:X,schemaEnv:J,opts:K}=G,H=K.passContext?W$.default.this:Y0.nil;if(Q)V();else z();function V(){if(!J.$async)throw Error("async schema referenced by sync schema");let L=Y.let("valid");Y.try(()=>{if(Y.code(Y0._`await ${(0,EY.callValidateCode)($,Z,H)}`),D(Z),!X)Y.assign(L,!0)},(U)=>{if(Y.if(Y0._`!(${U} instanceof ${G.ValidationError})`,()=>Y.throw(U)),F(U),!X)Y.assign(L,!1)}),$.ok(L)}function z(){$.result((0,EY.callValidateCode)($,Z,H),()=>D(Z),()=>F(Z))}function F(L){let U=Y0._`${L}.errors`;Y.assign(W$.default.vErrors,Y0._`${W$.default.vErrors} === null ? ${U} : ${W$.default.vErrors}.concat(${U})`),Y.assign(W$.default.errors,Y0._`${W$.default.vErrors}.length`)}function D(L){var U;if(!G.opts.unevaluated)return;let A=(U=W===null||W===void 0?void 0:W.validate)===null||U===void 0?void 0:U.evaluated;if(G.props!==!0)if(A&&!A.dynamicProps){if(A.props!==void 0)G.props=I5.mergeEvaluated.props(Y,A.props,G.props)}else{let q=Y.var("props",Y0._`${L}.evaluated.props`);G.props=I5.mergeEvaluated.props(Y,q,G.props,Y0.Name)}if(G.items!==!0)if(A&&!A.dynamicItems){if(A.items!==void 0)G.items=I5.mergeEvaluated.items(Y,A.items,G.items)}else{let q=Y.var("items",Y0._`${L}.evaluated.items`);G.items=I5.mergeEvaluated.items(Y,q,G.items,Y0.Name)}}}CY.callRef=E5;CY.default=tU});var _Y=M((kY)=>{Object.defineProperty(kY,"__esModule",{value:!0});var eU=IY(),$A=bY(),ZA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",eU.default,$A.default];kY.default=ZA});var fY=M((xY)=>{Object.defineProperty(xY,"__esModule",{value:!0});var R5=y(),H1=R5.operators,S5={maximum:{okStr:"<=",ok:H1.LTE,fail:H1.GT},minimum:{okStr:">=",ok:H1.GTE,fail:H1.LT},exclusiveMaximum:{okStr:"<",ok:H1.LT,fail:H1.GTE},exclusiveMinimum:{okStr:">",ok:H1.GT,fail:H1.LTE}},QA={message:({keyword:$,schemaCode:Z})=>R5.str`must be ${S5[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>R5._`{comparison: ${S5[$].okStr}, limit: ${Z}}`},YA={keyword:Object.keys(S5),type:"number",schemaType:"number",$data:!0,error:QA,code($){let{keyword:Z,data:W,schemaCode:Q}=$;$.fail$data(R5._`${W} ${S5[Z].fail} ${Q} || isNaN(${W})`)}};xY.default=YA});var gY=M((vY)=>{Object.defineProperty(vY,"__esModule",{value:!0});var WZ=y(),XA={message:({schemaCode:$})=>WZ.str`must be multiple of ${$}`,params:({schemaCode:$})=>WZ._`{multipleOf: ${$}}`},JA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:XA,code($){let{gen:Z,data:W,schemaCode:Q,it:Y}=$,G=Y.opts.multipleOfPrecision,X=Z.let("res"),J=G?WZ._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:WZ._`${X} !== parseInt(${X})`;$.fail$data(WZ._`(${Q} === 0 || (${X} = ${W}/${Q}, ${J}))`)}};vY.default=JA});var mY=M((uY)=>{Object.defineProperty(uY,"__esModule",{value:!0});function hY($){let Z=$.length,W=0,Q=0,Y;while(Q<Z)if(W++,Y=$.charCodeAt(Q++),Y>=55296&&Y<=56319&&Q<Z){if(Y=$.charCodeAt(Q),(Y&64512)===56320)Q++}return W}uY.default=hY;hY.code='require("ajv/dist/runtime/ucs2length").default'});var pY=M((lY)=>{Object.defineProperty(lY,"__esModule",{value:!0});var R1=y(),HA=k(),zA=mY(),VA={message({keyword:$,schemaCode:Z}){let W=$==="maxLength"?"more":"fewer";return R1.str`must NOT have ${W} than ${Z} characters`},params:({schemaCode:$})=>R1._`{limit: ${$}}`},FA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:VA,code($){let{keyword:Z,data:W,schemaCode:Q,it:Y}=$,G=Z==="maxLength"?R1.operators.GT:R1.operators.LT,X=Y.opts.unicode===!1?R1._`${W}.length`:R1._`${(0,HA.useFunc)($.gen,zA.default)}(${W})`;$.fail$data(R1._`${X} ${G} ${Q}`)}};lY.default=FA});var dY=M((cY)=>{Object.defineProperty(cY,"__esModule",{value:!0});var LA=F0(),UA=k(),Q$=y(),AA={message:({schemaCode:$})=>Q$.str`must match pattern "${$}"`,params:({schemaCode:$})=>Q$._`{pattern: ${$}}`},qA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:AA,code($){let{gen:Z,data:W,$data:Q,schema:Y,schemaCode:G,it:X}=$,J=X.opts.unicodeRegExp?"u":"";if(Q){let{regExp:K}=X.opts.code,H=K.code==="new RegExp"?Q$._`new RegExp`:(0,UA.useFunc)(Z,K),V=Z.let("valid");Z.try(()=>Z.assign(V,Q$._`${H}(${G}, ${J}).test(${W})`),()=>Z.assign(V,!1)),$.fail$data(Q$._`!${V}`)}else{let K=(0,LA.usePattern)($,Y);$.fail$data(Q$._`!${K}.test(${W})`)}}};cY.default=qA});var nY=M((iY)=>{Object.defineProperty(iY,"__esModule",{value:!0});var QZ=y(),NA={message({keyword:$,schemaCode:Z}){let W=$==="maxProperties"?"more":"fewer";return QZ.str`must NOT have ${W} than ${Z} properties`},params:({schemaCode:$})=>QZ._`{limit: ${$}}`},MA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:NA,code($){let{keyword:Z,data:W,schemaCode:Q}=$,Y=Z==="maxProperties"?QZ.operators.GT:QZ.operators.LT;$.fail$data(QZ._`Object.keys(${W}).length ${Y} ${Q}`)}};iY.default=MA});var rY=M((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});var YZ=F0(),GZ=y(),PA=k(),wA={message:({params:{missingProperty:$}})=>GZ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>GZ._`{missingProperty: ${$}}`},TA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:wA,code($){let{gen:Z,schema:W,schemaCode:Q,data:Y,$data:G,it:X}=$,{opts:J}=X;if(!G&&W.length===0)return;let K=W.length>=J.loopRequired;if(X.allErrors)H();else V();if(J.strictRequired){let D=$.parentSchema.properties,{definedProperties:L}=$.it;for(let U of W)if((D===null||D===void 0?void 0:D[U])===void 0&&!L.has(U)){let A=X.schemaEnv.baseId+X.errSchemaPath,q=`required property "${U}" is not defined at "${A}" (strictRequired)`;(0,PA.checkStrictMode)(X,q,X.opts.strictRequired)}}function H(){if(K||G)$.block$data(GZ.nil,z);else for(let D of W)(0,YZ.checkReportMissingProp)($,D)}function V(){let D=Z.let("missing");if(K||G){let L=Z.let("valid",!0);$.block$data(L,()=>F(D,L)),$.ok(L)}else Z.if((0,YZ.checkMissingProp)($,W,D)),(0,YZ.reportMissingProp)($,D),Z.else()}function z(){Z.forOf("prop",Q,(D)=>{$.setParams({missingProperty:D}),Z.if((0,YZ.noPropertyInData)(Z,Y,D,J.ownProperties),()=>$.error())})}function F(D,L){$.setParams({missingProperty:D}),Z.forOf(D,Q,()=>{Z.assign(L,(0,YZ.propertyInData)(Z,Y,D,J.ownProperties)),Z.if((0,GZ.not)(L),()=>{$.error(),Z.break()})},GZ.nil)}}};aY.default=TA});var oY=M((tY)=>{Object.defineProperty(tY,"__esModule",{value:!0});var XZ=y(),EA={message({keyword:$,schemaCode:Z}){let W=$==="maxItems"?"more":"fewer";return XZ.str`must NOT have ${W} than ${Z} items`},params:({schemaCode:$})=>XZ._`{limit: ${$}}`},RA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:EA,code($){let{keyword:Z,data:W,schemaCode:Q}=$,Y=Z==="maxItems"?XZ.operators.GT:XZ.operators.LT;$.fail$data(XZ._`${W}.length ${Y} ${Q}`)}};tY.default=RA});var C5=M((eY)=>{Object.defineProperty(eY,"__esModule",{value:!0});var sY=a8();sY.code='require("ajv/dist/runtime/equal").default';eY.default=sY});var ZG=M(($G)=>{Object.defineProperty($G,"__esModule",{value:!0});var zW=i$(),t=y(),yA=k(),bA=C5(),kA={message:({params:{i:$,j:Z}})=>t.str`must NOT have duplicate items (items ## ${Z} and ${$} are identical)`,params:({params:{i:$,j:Z}})=>t._`{i: ${$}, j: ${Z}}`},_A={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:kA,code($){let{gen:Z,data:W,$data:Q,schema:Y,parentSchema:G,schemaCode:X,it:J}=$;if(!Q&&!Y)return;let K=Z.let("valid"),H=G.items?(0,zW.getSchemaTypes)(G.items):[];$.block$data(K,V,t._`${X} === false`),$.ok(K);function V(){let L=Z.let("i",t._`${W}.length`),U=Z.let("j");$.setParams({i:L,j:U}),Z.assign(K,!0),Z.if(t._`${L} > 1`,()=>(z()?F:D)(L,U))}function z(){return H.length>0&&!H.some((L)=>L==="object"||L==="array")}function F(L,U){let A=Z.name("item"),q=(0,zW.checkDataTypes)(H,A,J.opts.strictNumbers,zW.DataType.Wrong),O=Z.const("indices",t._`{}`);Z.for(t._`;${L}--;`,()=>{if(Z.let(A,t._`${W}[${L}]`),Z.if(q,t._`continue`),H.length>1)Z.if(t._`typeof ${A} == "string"`,t._`${A} += "_"`);Z.if(t._`typeof ${O}[${A}] == "number"`,()=>{Z.assign(U,t._`${O}[${A}]`),$.error(),Z.assign(K,!1).break()}).code(t._`${O}[${A}] = ${L}`)})}function D(L,U){let A=(0,yA.useFunc)(Z,bA.default),q=Z.name("outer");Z.label(q).for(t._`;${L}--;`,()=>Z.for(t._`${U} = ${L}; ${U}--;`,()=>Z.if(t._`${A}(${W}[${L}], ${W}[${U}])`,()=>{$.error(),Z.assign(K,!1).break(q)})))}}};$G.default=_A});var QG=M((WG)=>{Object.defineProperty(WG,"__esModule",{value:!0});var VW=y(),fA=k(),vA=C5(),gA={message:"must be equal to constant",params:({schemaCode:$})=>VW._`{allowedValue: ${$}}`},hA={keyword:"const",$data:!0,error:gA,code($){let{gen:Z,data:W,$data:Q,schemaCode:Y,schema:G}=$;if(Q||G&&typeof G=="object")$.fail$data(VW._`!${(0,fA.useFunc)(Z,vA.default)}(${W}, ${Y})`);else $.fail(VW._`${G} !== ${W}`)}};WG.default=hA});var GG=M((YG)=>{Object.defineProperty(YG,"__esModule",{value:!0});var JZ=y(),mA=k(),lA=C5(),pA={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>JZ._`{allowedValues: ${$}}`},cA={keyword:"enum",schemaType:"array",$data:!0,error:pA,code($){let{gen:Z,data:W,$data:Q,schema:Y,schemaCode:G,it:X}=$;if(!Q&&Y.length===0)throw Error("enum must have non-empty array");let J=Y.length>=X.opts.loopEnum,K,H=()=>K!==null&&K!==void 0?K:K=(0,mA.useFunc)(Z,lA.default),V;if(J||Q)V=Z.let("valid"),$.block$data(V,z);else{if(!Array.isArray(Y))throw Error("ajv implementation error");let D=Z.const("vSchema",G);V=(0,JZ.or)(...Y.map((L,U)=>F(D,U)))}$.pass(V);function z(){Z.assign(V,!1),Z.forOf("v",G,(D)=>Z.if(JZ._`${H()}(${W}, ${D})`,()=>Z.assign(V,!0).break()))}function F(D,L){let U=Y[L];return typeof U==="object"&&U!==null?JZ._`${H()}(${W}, ${D}[${L}])`:JZ._`${W} === ${U}`}}};YG.default=cA});var JG=M((XG)=>{Object.defineProperty(XG,"__esModule",{value:!0});var iA=fY(),nA=gY(),aA=pY(),rA=dY(),tA=nY(),oA=rY(),sA=oY(),eA=ZG(),$q=QG(),Zq=GG(),Wq=[iA.default,nA.default,aA.default,rA.default,tA.default,oA.default,sA.default,eA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},$q.default,Zq.default];XG.default=Wq});var DW=M((BG)=>{Object.defineProperty(BG,"__esModule",{value:!0});BG.validateAdditionalItems=void 0;var S1=y(),FW=k(),Yq={message:({params:{len:$}})=>S1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>S1._`{limit: ${$}}`},Gq={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Yq,code($){let{parentSchema:Z,it:W}=$,{items:Q}=Z;if(!Array.isArray(Q)){(0,FW.checkStrictMode)(W,'"additionalItems" is ignored when "items" is not an array of schemas');return}KG($,Q)}};function KG($,Z){let{gen:W,schema:Q,data:Y,keyword:G,it:X}=$;X.items=!0;let J=W.const("len",S1._`${Y}.length`);if(Q===!1)$.setParams({len:Z.length}),$.pass(S1._`${J} <= ${Z.length}`);else if(typeof Q=="object"&&!(0,FW.alwaysValidSchema)(X,Q)){let H=W.var("valid",S1._`${J} <= ${Z.length}`);W.if((0,S1.not)(H),()=>K(H)),$.ok(H)}function K(H){W.forRange("i",Z.length,J,(V)=>{if($.subschema({keyword:G,dataProp:V,dataPropType:FW.Type.Num},H),!X.allErrors)W.if((0,S1.not)(H),()=>W.break())})}}BG.validateAdditionalItems=KG;BG.default=Gq});var LW=M((FG)=>{Object.defineProperty(FG,"__esModule",{value:!0});FG.validateTuple=void 0;var zG=y(),y5=k(),Jq=F0(),Kq={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:Z,it:W}=$;if(Array.isArray(Z))return VG($,"additionalItems",Z);if(W.items=!0,(0,y5.alwaysValidSchema)(W,Z))return;$.ok((0,Jq.validateArray)($))}};function VG($,Z,W=$.schema){let{gen:Q,parentSchema:Y,data:G,keyword:X,it:J}=$;if(V(Y),J.opts.unevaluated&&W.length&&J.items!==!0)J.items=y5.mergeEvaluated.items(Q,W.length,J.items);let K=Q.name("valid"),H=Q.const("len",zG._`${G}.length`);W.forEach((z,F)=>{if((0,y5.alwaysValidSchema)(J,z))return;Q.if(zG._`${H} > ${F}`,()=>$.subschema({keyword:X,schemaProp:F,dataProp:F},K)),$.ok(K)});function V(z){let{opts:F,errSchemaPath:D}=J,L=W.length,U=L===z.minItems&&(L===z.maxItems||z[Z]===!1);if(F.strictTuples&&!U){let A=`"${X}" is ${L}-tuple, but minItems or maxItems/${Z} are not specified or different at path "${D}"`;(0,y5.checkStrictMode)(J,A,F.strictTuples)}}}FG.validateTuple=VG;FG.default=Kq});var UG=M((LG)=>{Object.defineProperty(LG,"__esModule",{value:!0});var Hq=LW(),zq={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,Hq.validateTuple)($,"items")};LG.default=zq});var OG=M((qG)=>{Object.defineProperty(qG,"__esModule",{value:!0});var AG=y(),Fq=k(),Dq=F0(),Lq=DW(),Uq={message:({params:{len:$}})=>AG.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>AG._`{limit: ${$}}`},Aq={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Uq,code($){let{schema:Z,parentSchema:W,it:Q}=$,{prefixItems:Y}=W;if(Q.items=!0,(0,Fq.alwaysValidSchema)(Q,Z))return;if(Y)(0,Lq.validateAdditionalItems)($,Y);else $.ok((0,Dq.validateArray)($))}};qG.default=Aq});var MG=M((NG)=>{Object.defineProperty(NG,"__esModule",{value:!0});var D0=y(),b5=k(),Oq={message:({params:{min:$,max:Z}})=>Z===void 0?D0.str`must contain at least ${$} valid item(s)`:D0.str`must contain at least ${$} and no more than ${Z} valid item(s)`,params:({params:{min:$,max:Z}})=>Z===void 0?D0._`{minContains: ${$}}`:D0._`{minContains: ${$}, maxContains: ${Z}}`},Nq={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Oq,code($){let{gen:Z,schema:W,parentSchema:Q,data:Y,it:G}=$,X,J,{minContains:K,maxContains:H}=Q;if(G.opts.next)X=K===void 0?1:K,J=H;else X=1;let V=Z.const("len",D0._`${Y}.length`);if($.setParams({min:X,max:J}),J===void 0&&X===0){(0,b5.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&X>J){(0,b5.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,b5.alwaysValidSchema)(G,W)){let U=D0._`${V} >= ${X}`;if(J!==void 0)U=D0._`${U} && ${V} <= ${J}`;$.pass(U);return}G.items=!0;let z=Z.name("valid");if(J===void 0&&X===1)D(z,()=>Z.if(z,()=>Z.break()));else if(X===0){if(Z.let(z,!0),J!==void 0)Z.if(D0._`${Y}.length > 0`,F)}else Z.let(z,!1),F();$.result(z,()=>$.reset());function F(){let U=Z.name("_valid"),A=Z.let("count",0);D(U,()=>Z.if(U,()=>L(A)))}function D(U,A){Z.forRange("i",0,V,(q)=>{$.subschema({keyword:"contains",dataProp:q,dataPropType:b5.Type.Num,compositeRule:!0},U),A()})}function L(U){if(Z.code(D0._`${U}++`),J===void 0)Z.if(D0._`${U} >= ${X}`,()=>Z.assign(z,!0).break());else if(Z.if(D0._`${U} > ${J}`,()=>Z.assign(z,!1).break()),X===1)Z.assign(z,!0);else Z.if(D0._`${U} >= ${X}`,()=>Z.assign(z,!0))}}};NG.default=Nq});var EG=M((wG)=>{Object.defineProperty(wG,"__esModule",{value:!0});wG.validateSchemaDeps=wG.validatePropertyDeps=wG.error=void 0;var UW=y(),jq=k(),KZ=F0();wG.error={message:({params:{property:$,depsCount:Z,deps:W}})=>{let Q=Z===1?"property":"properties";return UW.str`must have ${Q} ${W} when property ${$} is present`},params:({params:{property:$,depsCount:Z,deps:W,missingProperty:Q}})=>UW._`{property: ${$},
7
- missingProperty: ${Q},
2
+ var g3=Object.create;var{getPrototypeOf:h3,defineProperty:CQ,getOwnPropertyNames:u3}=Object;var m3=Object.prototype.hasOwnProperty;function l3($){return this[$]}var p3,c3,V6=($,Z,Q)=>{var W=$!=null&&typeof $==="object";if(W){var Y=Z?p3??=new WeakMap:c3??=new WeakMap,G=Y.get($);if(G)return G}Q=$!=null?g3(h3($)):{};let X=Z||!$||!$.__esModule?CQ(Q,"default",{value:$,enumerable:!0}):Q;for(let J of u3($))if(!m3.call(X,J))CQ(X,J,{get:l3.bind($,J),enumerable:!0});if(W)Y.set($,X);return X};var M=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var $1=import.meta.require;var ZZ=M((E9)=>{Object.defineProperty(E9,"__esModule",{value:!0});E9.regexpCode=E9.getEsmExportName=E9.getProperty=E9.safeStringify=E9.stringify=E9.strConcat=E9.addCodeArg=E9.str=E9._=E9.nil=E9._Code=E9.Name=E9.IDENTIFIER=E9._CodeOrName=void 0;class A5{}E9._CodeOrName=A5;E9.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class Q$ extends A5{constructor($){super();if(!E9.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}E9.Name=Q$;class j0 extends A5{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((Z,Q)=>`${Z}${Q}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((Z,Q)=>{if(Q instanceof Q$)Z[Q.str]=(Z[Q.str]||0)+1;return Z},{})}}E9._Code=j0;E9.nil=new j0("");function T9($,...Z){let Q=[$[0]],W=0;while(W<Z.length)i8(Q,Z[W]),Q.push($[++W]);return new j0(Q)}E9._=T9;var d8=new j0("+");function I9($,...Z){let Q=[$Z($[0])],W=0;while(W<Z.length)Q.push(d8),i8(Q,Z[W]),Q.push(d8,$Z($[++W]));return fz(Q),new j0(Q)}E9.str=I9;function i8($,Z){if(Z instanceof j0)$.push(...Z._items);else if(Z instanceof Q$)$.push(Z);else $.push(hz(Z))}E9.addCodeArg=i8;function fz($){let Z=1;while(Z<$.length-1){if($[Z]===d8){let Q=vz($[Z-1],$[Z+1]);if(Q!==void 0){$.splice(Z-1,3,Q);continue}$[Z++]="+"}Z++}}function vz($,Z){if(Z==='""')return $;if($==='""')return Z;if(typeof $=="string"){if(Z instanceof Q$||$[$.length-1]!=='"')return;if(typeof Z!="string")return`${$.slice(0,-1)}${Z}"`;if(Z[0]==='"')return $.slice(0,-1)+Z.slice(1);return}if(typeof Z=="string"&&Z[0]==='"'&&!($ instanceof Q$))return`"${$}${Z.slice(1)}`;return}function gz($,Z){return Z.emptyStr()?$:$.emptyStr()?Z:I9`${$}${Z}`}E9.strConcat=gz;function hz($){return typeof $=="number"||typeof $=="boolean"||$===null?$:$Z(Array.isArray($)?$.join(","):$)}function uz($){return new j0($Z($))}E9.stringify=uz;function $Z($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}E9.safeStringify=$Z;function mz($){return typeof $=="string"&&E9.IDENTIFIER.test($)?new j0(`.${$}`):T9`[${$}]`}E9.getProperty=mz;function lz($){if(typeof $=="string"&&E9.IDENTIFIER.test($))return new j0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}E9.getEsmExportName=lz;function pz($){return new j0($.toString())}E9.regexpCode=pz});var t8=M((y9)=>{Object.defineProperty(y9,"__esModule",{value:!0});y9.ValueScope=y9.ValueScopeName=y9.Scope=y9.varKinds=y9.UsedValueState=void 0;var X0=ZZ();class C9 extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var O5;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(O5||(y9.UsedValueState=O5={}));y9.varKinds={const:new X0.Name("const"),let:new X0.Name("let"),var:new X0.Name("var")};class a8{constructor({prefixes:$,parent:Z}={}){this._names={},this._prefixes=$,this._parent=Z}toName($){return $ instanceof X0.Name?$:this.name($)}name($){return new X0.Name(this._newName($))}_newName($){let Z=this._names[$]||this._nameGroup($);return`${$}${Z.index++}`}_nameGroup($){var Z,Q;if(((Q=(Z=this._parent)===null||Z===void 0?void 0:Z._prefixes)===null||Q===void 0?void 0:Q.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}y9.Scope=a8;class r8 extends X0.Name{constructor($,Z){super(Z);this.prefix=$}setValue($,{property:Z,itemIndex:Q}){this.value=$,this.scopePath=X0._`.${new X0.Name(Z)}[${Q}]`}}y9.ValueScopeName=r8;var QF=X0._`\n`;class S9 extends a8{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?QF:X0.nil}}get(){return this._scope}name($){return new r8($,this._newName($))}value($,Z){var Q;if(Z.ref===void 0)throw Error("CodeGen: ref must be passed in value");let W=this.toName($),{prefix:Y}=W,G=(Q=Z.key)!==null&&Q!==void 0?Q:Z.ref,X=this._values[Y];if(X){let B=X.get(G);if(B)return B}else X=this._values[Y]=new Map;X.set(G,W);let J=this._scope[Y]||(this._scope[Y]=[]),K=J.length;return J[K]=Z.ref,W.setValue(Z,{property:Y,itemIndex:K}),W}getValue($,Z){let Q=this._values[$];if(!Q)return;return Q.get(Z)}scopeRefs($,Z=this._values){return this._reduceValues(Z,(Q)=>{if(Q.scopePath===void 0)throw Error(`CodeGen: name "${Q}" has no value`);return X0._`${$}${Q.scopePath}`})}scopeCode($=this._values,Z,Q){return this._reduceValues($,(W)=>{if(W.value===void 0)throw Error(`CodeGen: name "${W}" has no value`);return W.value.code},Z,Q)}_reduceValues($,Z,Q={},W){let Y=X0.nil;for(let G in $){let X=$[G];if(!X)continue;let J=Q[G]=Q[G]||new Map;X.forEach((K)=>{if(J.has(K))return;J.set(K,O5.Started);let B=Z(K);if(B){let z=this.opts.es5?y9.varKinds.var:y9.varKinds.const;Y=X0._`${Y}${z} ${K} = ${B};${this.opts._n}`}else if(B=W===null||W===void 0?void 0:W(K))Y=X0._`${Y}${B}${this.opts._n}`;else throw new C9(K);J.set(K,O5.Completed)})}return Y}}y9.ValueScope=S9});var b=M((J0)=>{Object.defineProperty(J0,"__esModule",{value:!0});J0.or=J0.and=J0.not=J0.CodeGen=J0.operators=J0.varKinds=J0.ValueScopeName=J0.ValueScope=J0.Scope=J0.Name=J0.regexpCode=J0.stringify=J0.getProperty=J0.nil=J0.strConcat=J0.str=J0._=void 0;var k=ZZ(),P0=t8(),V1=ZZ();Object.defineProperty(J0,"_",{enumerable:!0,get:function(){return V1._}});Object.defineProperty(J0,"str",{enumerable:!0,get:function(){return V1.str}});Object.defineProperty(J0,"strConcat",{enumerable:!0,get:function(){return V1.strConcat}});Object.defineProperty(J0,"nil",{enumerable:!0,get:function(){return V1.nil}});Object.defineProperty(J0,"getProperty",{enumerable:!0,get:function(){return V1.getProperty}});Object.defineProperty(J0,"stringify",{enumerable:!0,get:function(){return V1.stringify}});Object.defineProperty(J0,"regexpCode",{enumerable:!0,get:function(){return V1.regexpCode}});Object.defineProperty(J0,"Name",{enumerable:!0,get:function(){return V1.Name}});var I5=t8();Object.defineProperty(J0,"Scope",{enumerable:!0,get:function(){return I5.Scope}});Object.defineProperty(J0,"ValueScope",{enumerable:!0,get:function(){return I5.ValueScope}});Object.defineProperty(J0,"ValueScopeName",{enumerable:!0,get:function(){return I5.ValueScopeName}});Object.defineProperty(J0,"varKinds",{enumerable:!0,get:function(){return I5.varKinds}});J0.operators={GT:new k._Code(">"),GTE:new k._Code(">="),LT:new k._Code("<"),LTE:new k._Code("<="),EQ:new k._Code("==="),NEQ:new k._Code("!=="),NOT:new k._Code("!"),OR:new k._Code("||"),AND:new k._Code("&&"),ADD:new k._Code("+")};class z1{optimizeNodes(){return this}optimizeNames($,Z){return this}}class _9 extends z1{constructor($,Z,Q){super();this.varKind=$,this.name=Z,this.rhs=Q}render({es5:$,_n:Z}){let Q=$?P0.varKinds.var:this.varKind,W=this.rhs===void 0?"":` = ${this.rhs}`;return`${Q} ${this.name}${W};`+Z}optimizeNames($,Z){if(!$[this.name.str])return;if(this.rhs)this.rhs=Y$(this.rhs,$,Z);return this}get names(){return this.rhs instanceof k._CodeOrName?this.rhs.names:{}}}class e8 extends z1{constructor($,Z,Q){super();this.lhs=$,this.rhs=Z,this.sideEffects=Q}render({_n:$}){return`${this.lhs} = ${this.rhs};`+$}optimizeNames($,Z){if(this.lhs instanceof k.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=Y$(this.rhs,$,Z),this}get names(){let $=this.lhs instanceof k.Name?{}:{...this.lhs.names};return T5($,this.rhs)}}class k9 extends e8{constructor($,Z,Q,W){super($,Q,W);this.op=Z}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class x9 extends z1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class f9 extends z1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class v9 extends z1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class g9 extends z1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,Z){return this.code=Y$(this.code,$,Z),this}get names(){return this.code instanceof k._CodeOrName?this.code.names:{}}}class E5 extends z1{constructor($=[]){super();this.nodes=$}render($){return this.nodes.reduce((Z,Q)=>Z+Q.render($),"")}optimizeNodes(){let{nodes:$}=this,Z=$.length;while(Z--){let Q=$[Z].optimizeNodes();if(Array.isArray(Q))$.splice(Z,1,...Q);else if(Q)$[Z]=Q;else $.splice(Z,1)}return $.length>0?this:void 0}optimizeNames($,Z){let{nodes:Q}=this,W=Q.length;while(W--){let Y=Q[W];if(Y.optimizeNames($,Z))continue;XF($,Y.names),Q.splice(W,1)}return Q.length>0?this:void 0}get names(){return this.nodes.reduce(($,Z)=>y1($,Z.names),{})}}class F1 extends E5{render($){return"{"+$._n+super.render($)+"}"+$._n}}class h9 extends E5{}class QZ extends F1{}QZ.kind="else";class r0 extends F1{constructor($,Z){super(Z);this.condition=$}render($){let Z=`if(${this.condition})`+super.render($);if(this.else)Z+="else "+this.else.render($);return Z}optimizeNodes(){super.optimizeNodes();let $=this.condition;if($===!0)return this.nodes;let Z=this.else;if(Z){let Q=Z.optimizeNodes();Z=this.else=Array.isArray(Q)?new QZ(Q):Q}if(Z){if($===!1)return Z instanceof r0?Z:Z.nodes;if(this.nodes.length)return this;return new r0(c9($),Z instanceof r0?[Z]:Z.nodes)}if($===!1||!this.nodes.length)return;return this}optimizeNames($,Z){var Q;if(this.else=(Q=this.else)===null||Q===void 0?void 0:Q.optimizeNames($,Z),!(super.optimizeNames($,Z)||this.else))return;return this.condition=Y$(this.condition,$,Z),this}get names(){let $=super.names;if(T5($,this.condition),this.else)y1($,this.else.names);return $}}r0.kind="if";class W$ extends F1{}W$.kind="for";class u9 extends W${constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iteration=Y$(this.iteration,$,Z),this}get names(){return y1(super.names,this.iteration.names)}}class m9 extends W${constructor($,Z,Q,W){super();this.varKind=$,this.name=Z,this.from=Q,this.to=W}render($){let Z=$.es5?P0.varKinds.var:this.varKind,{name:Q,from:W,to:Y}=this;return`for(${Z} ${Q}=${W}; ${Q}<${Y}; ${Q}++)`+super.render($)}get names(){let $=T5(super.names,this.from);return T5($,this.to)}}class o8 extends W${constructor($,Z,Q,W){super();this.loop=$,this.varKind=Z,this.name=Q,this.iterable=W}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iterable=Y$(this.iterable,$,Z),this}get names(){return y1(super.names,this.iterable.names)}}class M5 extends F1{constructor($,Z,Q){super();this.name=$,this.args=Z,this.async=Q}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}M5.kind="func";class j5 extends E5{render($){return"return "+super.render($)}}j5.kind="return";class l9 extends F1{render($){let Z="try"+super.render($);if(this.catch)Z+=this.catch.render($);if(this.finally)Z+=this.finally.render($);return Z}optimizeNodes(){var $,Z;return super.optimizeNodes(),($=this.catch)===null||$===void 0||$.optimizeNodes(),(Z=this.finally)===null||Z===void 0||Z.optimizeNodes(),this}optimizeNames($,Z){var Q,W;return super.optimizeNames($,Z),(Q=this.catch)===null||Q===void 0||Q.optimizeNames($,Z),(W=this.finally)===null||W===void 0||W.optimizeNames($,Z),this}get names(){let $=super.names;if(this.catch)y1($,this.catch.names);if(this.finally)y1($,this.finally.names);return $}}class P5 extends F1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}P5.kind="catch";class w5 extends F1{render($){return"finally"+super.render($)}}w5.kind="finally";class p9{constructor($,Z={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Z,_n:Z.lines?`
3
+ `:""},this._extScope=$,this._scope=new P0.Scope({parent:$}),this._nodes=[new h9]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,Z){let Q=this._extScope.value($,Z);return(this._values[Q.prefix]||(this._values[Q.prefix]=new Set)).add(Q),Q}getScopeValue($,Z){return this._extScope.getValue($,Z)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,Z,Q,W){let Y=this._scope.toName(Z);if(Q!==void 0&&W)this._constants[Y.str]=Q;return this._leafNode(new _9($,Y,Q)),Y}const($,Z,Q){return this._def(P0.varKinds.const,$,Z,Q)}let($,Z,Q){return this._def(P0.varKinds.let,$,Z,Q)}var($,Z,Q){return this._def(P0.varKinds.var,$,Z,Q)}assign($,Z,Q){return this._leafNode(new e8($,Z,Q))}add($,Z){return this._leafNode(new k9($,J0.operators.ADD,Z))}code($){if(typeof $=="function")$();else if($!==k.nil)this._leafNode(new g9($));return this}object(...$){let Z=["{"];for(let[Q,W]of $){if(Z.length>1)Z.push(",");if(Z.push(Q),Q!==W||this.opts.es5)Z.push(":"),(0,k.addCodeArg)(Z,W)}return Z.push("}"),new k._Code(Z)}if($,Z,Q){if(this._blockNode(new r0($)),Z&&Q)this.code(Z).else().code(Q).endIf();else if(Z)this.code(Z).endIf();else if(Q)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new r0($))}else(){return this._elseNode(new QZ)}endIf(){return this._endBlockNode(r0,QZ)}_for($,Z){if(this._blockNode($),Z)this.code(Z).endFor();return this}for($,Z){return this._for(new u9($),Z)}forRange($,Z,Q,W,Y=this.opts.es5?P0.varKinds.var:P0.varKinds.let){let G=this._scope.toName($);return this._for(new m9(Y,G,Z,Q),()=>W(G))}forOf($,Z,Q,W=P0.varKinds.const){let Y=this._scope.toName($);if(this.opts.es5){let G=Z instanceof k.Name?Z:this.var("_arr",Z);return this.forRange("_i",0,k._`${G}.length`,(X)=>{this.var(Y,k._`${G}[${X}]`),Q(Y)})}return this._for(new o8("of",W,Y,Z),()=>Q(Y))}forIn($,Z,Q,W=this.opts.es5?P0.varKinds.var:P0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,k._`Object.keys(${Z})`,Q);let Y=this._scope.toName($);return this._for(new o8("in",W,Y,Z),()=>Q(Y))}endFor(){return this._endBlockNode(W$)}label($){return this._leafNode(new x9($))}break($){return this._leafNode(new f9($))}return($){let Z=new j5;if(this._blockNode(Z),this.code($),Z.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(j5)}try($,Z,Q){if(!Z&&!Q)throw Error('CodeGen: "try" without "catch" and "finally"');let W=new l9;if(this._blockNode(W),this.code($),Z){let Y=this.name("e");this._currNode=W.catch=new P5(Y),Z(Y)}if(Q)this._currNode=W.finally=new w5,this.code(Q);return this._endBlockNode(P5,w5)}throw($){return this._leafNode(new v9($))}block($,Z){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(Z);return this}endBlock($){let Z=this._blockStarts.pop();if(Z===void 0)throw Error("CodeGen: not in self-balancing block");let Q=this._nodes.length-Z;if(Q<0||$!==void 0&&Q!==$)throw Error(`CodeGen: wrong number of nodes: ${Q} vs ${$} expected`);return this._nodes.length=Z,this}func($,Z=k.nil,Q,W){if(this._blockNode(new M5($,Z,Q)),W)this.code(W).endFunc();return this}endFunc(){return this._endBlockNode(M5)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,Z){let Q=this._currNode;if(Q instanceof $||Z&&Q instanceof Z)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${Z?`${$.kind}/${Z.kind}`:$.kind}"`)}_elseNode($){let Z=this._currNode;if(!(Z instanceof r0))throw Error('CodeGen: "else" without "if"');return this._currNode=Z.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let Z=this._nodes;Z[Z.length-1]=$}}J0.CodeGen=p9;function y1($,Z){for(let Q in Z)$[Q]=($[Q]||0)+(Z[Q]||0);return $}function T5($,Z){return Z instanceof k._CodeOrName?y1($,Z.names):$}function Y$($,Z,Q){if($ instanceof k.Name)return W($);if(!Y($))return $;return new k._Code($._items.reduce((G,X)=>{if(X instanceof k.Name)X=W(X);if(X instanceof k._Code)G.push(...X._items);else G.push(X);return G},[]));function W(G){let X=Q[G.str];if(X===void 0||Z[G.str]!==1)return G;return delete Z[G.str],X}function Y(G){return G instanceof k._Code&&G._items.some((X)=>X instanceof k.Name&&Z[X.str]===1&&Q[X.str]!==void 0)}}function XF($,Z){for(let Q in Z)$[Q]=($[Q]||0)-(Z[Q]||0)}function c9($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:k._`!${s8($)}`}J0.not=c9;var JF=d9(J0.operators.AND);function KF(...$){return $.reduce(JF)}J0.and=KF;var BF=d9(J0.operators.OR);function HF(...$){return $.reduce(BF)}J0.or=HF;function d9($){return(Z,Q)=>Z===k.nil?Q:Q===k.nil?Z:k._`${s8(Z)} ${$} ${s8(Q)}`}function s8($){return $ instanceof k.Name?$:k._`(${$})`}});var x=M(($7)=>{Object.defineProperty($7,"__esModule",{value:!0});$7.checkStrictMode=$7.getErrorPath=$7.Type=$7.useFunc=$7.setEvaluated=$7.evaluatedPropsToName=$7.mergeEvaluated=$7.eachItem=$7.unescapeJsonPointer=$7.escapeJsonPointer=$7.escapeFragment=$7.unescapeFragment=$7.schemaRefOrVal=$7.schemaHasRulesButRef=$7.schemaHasRules=$7.checkUnknownRules=$7.alwaysValidSchema=$7.toHash=void 0;var h=b(),DF=ZZ();function LF($){let Z={};for(let Q of $)Z[Q]=!0;return Z}$7.toHash=LF;function UF($,Z){if(typeof Z=="boolean")return Z;if(Object.keys(Z).length===0)return!0;return r9($,Z),!t9(Z,$.self.RULES.all)}$7.alwaysValidSchema=UF;function r9($,Z=$.schema){let{opts:Q,self:W}=$;if(!Q.strictSchema)return;if(typeof Z==="boolean")return;let Y=W.RULES.keywords;for(let G in Z)if(!Y[G])e9($,`unknown keyword: "${G}"`)}$7.checkUnknownRules=r9;function t9($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Z[Q])return!0;return!1}$7.schemaHasRules=t9;function qF($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Q!=="$ref"&&Z.all[Q])return!0;return!1}$7.schemaHasRulesButRef=qF;function AF({topSchemaRef:$,schemaPath:Z},Q,W,Y){if(!Y){if(typeof Q=="number"||typeof Q=="boolean")return Q;if(typeof Q=="string")return h._`${Q}`}return h._`${$}${Z}${(0,h.getProperty)(W)}`}$7.schemaRefOrVal=AF;function NF($){return o9(decodeURIComponent($))}$7.unescapeFragment=NF;function OF($){return encodeURIComponent(Z4($))}$7.escapeFragment=OF;function Z4($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}$7.escapeJsonPointer=Z4;function o9($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}$7.unescapeJsonPointer=o9;function MF($,Z){if(Array.isArray($))for(let Q of $)Z(Q);else Z($)}$7.eachItem=MF;function n9({mergeNames:$,mergeToName:Z,mergeValues:Q,resultToName:W}){return(Y,G,X,J)=>{let K=X===void 0?G:X instanceof h.Name?(G instanceof h.Name?$(Y,G,X):Z(Y,G,X),X):G instanceof h.Name?(Z(Y,X,G),G):Q(G,X);return J===h.Name&&!(K instanceof h.Name)?W(Y,K):K}}$7.mergeEvaluated={props:n9({mergeNames:($,Z,Q)=>$.if(h._`${Q} !== true && ${Z} !== undefined`,()=>{$.if(h._`${Z} === true`,()=>$.assign(Q,!0),()=>$.assign(Q,h._`${Q} || {}`).code(h._`Object.assign(${Q}, ${Z})`))}),mergeToName:($,Z,Q)=>$.if(h._`${Q} !== true`,()=>{if(Z===!0)$.assign(Q,!0);else $.assign(Q,h._`${Q} || {}`),Q4($,Q,Z)}),mergeValues:($,Z)=>$===!0?!0:{...$,...Z},resultToName:s9}),items:n9({mergeNames:($,Z,Q)=>$.if(h._`${Q} !== true && ${Z} !== undefined`,()=>$.assign(Q,h._`${Z} === true ? true : ${Q} > ${Z} ? ${Q} : ${Z}`)),mergeToName:($,Z,Q)=>$.if(h._`${Q} !== true`,()=>$.assign(Q,Z===!0?!0:h._`${Q} > ${Z} ? ${Q} : ${Z}`)),mergeValues:($,Z)=>$===!0?!0:Math.max($,Z),resultToName:($,Z)=>$.var("items",Z)})};function s9($,Z){if(Z===!0)return $.var("props",!0);let Q=$.var("props",h._`{}`);if(Z!==void 0)Q4($,Q,Z);return Q}$7.evaluatedPropsToName=s9;function Q4($,Z,Q){Object.keys(Q).forEach((W)=>$.assign(h._`${Z}${(0,h.getProperty)(W)}`,!0))}$7.setEvaluated=Q4;var a9={};function jF($,Z){return $.scopeValue("func",{ref:Z,code:a9[Z.code]||(a9[Z.code]=new DF._Code(Z.code))})}$7.useFunc=jF;var $4;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})($4||($7.Type=$4={}));function PF($,Z,Q){if($ instanceof h.Name){let W=Z===$4.Num;return Q?W?h._`"[" + ${$} + "]"`:h._`"['" + ${$} + "']"`:W?h._`"/" + ${$}`:h._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Q?(0,h.getProperty)($).toString():"/"+Z4($)}$7.getErrorPath=PF;function e9($,Z,Q=$.opts.strictSchema){if(!Q)return;if(Z=`strict mode: ${Z}`,Q===!0)throw Error(Z);$.self.logger.warn(Z)}$7.checkStrictMode=e9});var t0=M((Q7)=>{Object.defineProperty(Q7,"__esModule",{value:!0});var Z0=b(),mF={data:new Z0.Name("data"),valCxt:new Z0.Name("valCxt"),instancePath:new Z0.Name("instancePath"),parentData:new Z0.Name("parentData"),parentDataProperty:new Z0.Name("parentDataProperty"),rootData:new Z0.Name("rootData"),dynamicAnchors:new Z0.Name("dynamicAnchors"),vErrors:new Z0.Name("vErrors"),errors:new Z0.Name("errors"),this:new Z0.Name("this"),self:new Z0.Name("self"),scope:new Z0.Name("scope"),json:new Z0.Name("json"),jsonPos:new Z0.Name("jsonPos"),jsonLen:new Z0.Name("jsonLen"),jsonPart:new Z0.Name("jsonPart")};Q7.default=mF});var WZ=M((X7)=>{Object.defineProperty(X7,"__esModule",{value:!0});X7.extendErrors=X7.resetErrorsCount=X7.reportExtraError=X7.reportError=X7.keyword$DataError=X7.keywordError=void 0;var f=b(),C5=x(),Y0=t0();X7.keywordError={message:({keyword:$})=>f.str`must pass "${$}" keyword validation`};X7.keyword$DataError={message:({keyword:$,schemaType:Z})=>Z?f.str`"${$}" keyword must be ${Z} ($data)`:f.str`"${$}" keyword is invalid ($data)`};function pF($,Z=X7.keywordError,Q,W){let{it:Y}=$,{gen:G,compositeRule:X,allErrors:J}=Y,K=G7($,Z,Q);if(W!==null&&W!==void 0?W:X||J)W7(G,K);else Y7(Y,f._`[${K}]`)}X7.reportError=pF;function cF($,Z=X7.keywordError,Q){let{it:W}=$,{gen:Y,compositeRule:G,allErrors:X}=W,J=G7($,Z,Q);if(W7(Y,J),!(G||X))Y7(W,Y0.default.vErrors)}X7.reportExtraError=cF;function dF($,Z){$.assign(Y0.default.errors,Z),$.if(f._`${Y0.default.vErrors} !== null`,()=>$.if(Z,()=>$.assign(f._`${Y0.default.vErrors}.length`,Z),()=>$.assign(Y0.default.vErrors,null)))}X7.resetErrorsCount=dF;function iF({gen:$,keyword:Z,schemaValue:Q,data:W,errsCount:Y,it:G}){if(Y===void 0)throw Error("ajv implementation error");let X=$.name("err");$.forRange("i",Y,Y0.default.errors,(J)=>{if($.const(X,f._`${Y0.default.vErrors}[${J}]`),$.if(f._`${X}.instancePath === undefined`,()=>$.assign(f._`${X}.instancePath`,(0,f.strConcat)(Y0.default.instancePath,G.errorPath))),$.assign(f._`${X}.schemaPath`,f.str`${G.errSchemaPath}/${Z}`),G.opts.verbose)$.assign(f._`${X}.schema`,Q),$.assign(f._`${X}.data`,W)})}X7.extendErrors=iF;function W7($,Z){let Q=$.const("err",Z);$.if(f._`${Y0.default.vErrors} === null`,()=>$.assign(Y0.default.vErrors,f._`[${Q}]`),f._`${Y0.default.vErrors}.push(${Q})`),$.code(f._`${Y0.default.errors}++`)}function Y7($,Z){let{gen:Q,validateName:W,schemaEnv:Y}=$;if(Y.$async)Q.throw(f._`new ${$.ValidationError}(${Z})`);else Q.assign(f._`${W}.errors`,Z),Q.return(!1)}var b1={keyword:new f.Name("keyword"),schemaPath:new f.Name("schemaPath"),params:new f.Name("params"),propertyName:new f.Name("propertyName"),message:new f.Name("message"),schema:new f.Name("schema"),parentSchema:new f.Name("parentSchema")};function G7($,Z,Q){let{createErrors:W}=$.it;if(W===!1)return f._`{}`;return nF($,Z,Q)}function nF($,Z,Q={}){let{gen:W,it:Y}=$,G=[aF(Y,Q),rF($,Q)];return tF($,Z,G),W.object(...G)}function aF({errorPath:$},{instancePath:Z}){let Q=Z?f.str`${$}${(0,C5.getErrorPath)(Z,C5.Type.Str)}`:$;return[Y0.default.instancePath,(0,f.strConcat)(Y0.default.instancePath,Q)]}function rF({keyword:$,it:{errSchemaPath:Z}},{schemaPath:Q,parentSchema:W}){let Y=W?Z:f.str`${Z}/${$}`;if(Q)Y=f.str`${Y}${(0,C5.getErrorPath)(Q,C5.Type.Str)}`;return[b1.schemaPath,Y]}function tF($,{params:Z,message:Q},W){let{keyword:Y,data:G,schemaValue:X,it:J}=$,{opts:K,propertyName:B,topSchemaRef:z,schemaPath:V}=J;if(W.push([b1.keyword,Y],[b1.params,typeof Z=="function"?Z($):Z||f._`{}`]),K.messages)W.push([b1.message,typeof Q=="function"?Q($):Q]);if(K.verbose)W.push([b1.schema,X],[b1.parentSchema,f._`${z}${V}`],[Y0.default.data,G]);if(B)W.push([b1.propertyName,B])}});var V7=M((B7)=>{Object.defineProperty(B7,"__esModule",{value:!0});B7.boolOrEmptySchema=B7.topBoolOrEmptySchema=void 0;var ZD=WZ(),QD=b(),WD=t0(),YD={message:"boolean schema is false"};function GD($){let{gen:Z,schema:Q,validateName:W}=$;if(Q===!1)K7($,!1);else if(typeof Q=="object"&&Q.$async===!0)Z.return(WD.default.data);else Z.assign(QD._`${W}.errors`,null),Z.return(!0)}B7.topBoolOrEmptySchema=GD;function XD($,Z){let{gen:Q,schema:W}=$;if(W===!1)Q.var(Z,!1),K7($);else Q.var(Z,!0)}B7.boolOrEmptySchema=XD;function K7($,Z){let{gen:Q,data:W}=$,Y={gen:Q,keyword:"false schema",data:W,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,ZD.reportError)(Y,YD,void 0,Z)}});var Y4=M((z7)=>{Object.defineProperty(z7,"__esModule",{value:!0});z7.getRules=z7.isJSONType=void 0;var KD=["string","number","integer","boolean","null","object","array"],BD=new Set(KD);function HD($){return typeof $=="string"&&BD.has($)}z7.isJSONType=HD;function VD(){let $={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...$,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},$.number,$.string,$.array,$.object],post:{rules:[]},all:{},keywords:{}}}z7.getRules=VD});var G4=M((U7)=>{Object.defineProperty(U7,"__esModule",{value:!0});U7.shouldUseRule=U7.shouldUseGroup=U7.schemaHasRulesForType=void 0;function FD({schema:$,self:Z},Q){let W=Z.RULES.types[Q];return W&&W!==!0&&D7($,W)}U7.schemaHasRulesForType=FD;function D7($,Z){return Z.rules.some((Q)=>L7($,Q))}U7.shouldUseGroup=D7;function L7($,Z){var Q;return $[Z.keyword]!==void 0||((Q=Z.definition.implements)===null||Q===void 0?void 0:Q.some((W)=>$[W]!==void 0))}U7.shouldUseRule=L7});var YZ=M((M7)=>{Object.defineProperty(M7,"__esModule",{value:!0});M7.reportTypeError=M7.checkDataTypes=M7.checkDataType=M7.coerceAndCheckDataType=M7.getJSONTypes=M7.getSchemaTypes=M7.DataType=void 0;var UD=Y4(),qD=G4(),AD=WZ(),S=b(),A7=x(),G$;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(G$||(M7.DataType=G$={}));function ND($){let Z=N7($.type);if(Z.includes("null")){if($.nullable===!1)throw Error("type: null contradicts nullable: false")}else{if(!Z.length&&$.nullable!==void 0)throw Error('"nullable" cannot be used without "type"');if($.nullable===!0)Z.push("null")}return Z}M7.getSchemaTypes=ND;function N7($){let Z=Array.isArray($)?$:$?[$]:[];if(Z.every(UD.isJSONType))return Z;throw Error("type must be JSONType or JSONType[]: "+Z.join(","))}M7.getJSONTypes=N7;function OD($,Z){let{gen:Q,data:W,opts:Y}=$,G=MD(Z,Y.coerceTypes),X=Z.length>0&&!(G.length===0&&Z.length===1&&(0,qD.schemaHasRulesForType)($,Z[0]));if(X){let J=J4(Z,W,Y.strictNumbers,G$.Wrong);Q.if(J,()=>{if(G.length)jD($,Z,G);else K4($)})}return X}M7.coerceAndCheckDataType=OD;var O7=new Set(["string","number","integer","boolean","null"]);function MD($,Z){return Z?$.filter((Q)=>O7.has(Q)||Z==="array"&&Q==="array"):[]}function jD($,Z,Q){let{gen:W,data:Y,opts:G}=$,X=W.let("dataType",S._`typeof ${Y}`),J=W.let("coerced",S._`undefined`);if(G.coerceTypes==="array")W.if(S._`${X} == 'object' && Array.isArray(${Y}) && ${Y}.length == 1`,()=>W.assign(Y,S._`${Y}[0]`).assign(X,S._`typeof ${Y}`).if(J4(Z,Y,G.strictNumbers),()=>W.assign(J,Y)));W.if(S._`${J} !== undefined`);for(let B of Q)if(O7.has(B)||B==="array"&&G.coerceTypes==="array")K(B);W.else(),K4($),W.endIf(),W.if(S._`${J} !== undefined`,()=>{W.assign(Y,J),PD($,J)});function K(B){switch(B){case"string":W.elseIf(S._`${X} == "number" || ${X} == "boolean"`).assign(J,S._`"" + ${Y}`).elseIf(S._`${Y} === null`).assign(J,S._`""`);return;case"number":W.elseIf(S._`${X} == "boolean" || ${Y} === null
4
+ || (${X} == "string" && ${Y} && ${Y} == +${Y})`).assign(J,S._`+${Y}`);return;case"integer":W.elseIf(S._`${X} === "boolean" || ${Y} === null
5
+ || (${X} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(J,S._`+${Y}`);return;case"boolean":W.elseIf(S._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(J,!1).elseIf(S._`${Y} === "true" || ${Y} === 1`).assign(J,!0);return;case"null":W.elseIf(S._`${Y} === "" || ${Y} === 0 || ${Y} === false`),W.assign(J,null);return;case"array":W.elseIf(S._`${X} === "string" || ${X} === "number"
6
+ || ${X} === "boolean" || ${Y} === null`).assign(J,S._`[${Y}]`)}}}function PD({gen:$,parentData:Z,parentDataProperty:Q},W){$.if(S._`${Z} !== undefined`,()=>$.assign(S._`${Z}[${Q}]`,W))}function X4($,Z,Q,W=G$.Correct){let Y=W===G$.Correct?S.operators.EQ:S.operators.NEQ,G;switch($){case"null":return S._`${Z} ${Y} null`;case"array":G=S._`Array.isArray(${Z})`;break;case"object":G=S._`${Z} && typeof ${Z} == "object" && !Array.isArray(${Z})`;break;case"integer":G=X(S._`!(${Z} % 1) && !isNaN(${Z})`);break;case"number":G=X();break;default:return S._`typeof ${Z} ${Y} ${$}`}return W===G$.Correct?G:(0,S.not)(G);function X(J=S.nil){return(0,S.and)(S._`typeof ${Z} == "number"`,J,Q?S._`isFinite(${Z})`:S.nil)}}M7.checkDataType=X4;function J4($,Z,Q,W){if($.length===1)return X4($[0],Z,Q,W);let Y,G=(0,A7.toHash)($);if(G.array&&G.object){let X=S._`typeof ${Z} != "object"`;Y=G.null?X:S._`!${Z} || ${X}`,delete G.null,delete G.array,delete G.object}else Y=S.nil;if(G.number)delete G.integer;for(let X in G)Y=(0,S.and)(Y,X4(X,Z,Q,W));return Y}M7.checkDataTypes=J4;var wD={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:Z})=>typeof $=="string"?S._`{type: ${$}}`:S._`{type: ${Z}}`};function K4($){let Z=TD($);(0,AD.reportError)(Z,wD)}M7.reportTypeError=K4;function TD($){let{gen:Z,data:Q,schema:W}=$,Y=(0,A7.schemaRefOrVal)($,W,"type");return{gen:Z,keyword:"type",data:Q,schema:W.type,schemaCode:Y,schemaValue:Y,parentSchema:W,params:{},it:$}}});var I7=M((w7)=>{Object.defineProperty(w7,"__esModule",{value:!0});w7.assignDefaults=void 0;var X$=b(),bD=x();function _D($,Z){let{properties:Q,items:W}=$.schema;if(Z==="object"&&Q)for(let Y in Q)P7($,Y,Q[Y].default);else if(Z==="array"&&Array.isArray(W))W.forEach((Y,G)=>P7($,G,Y.default))}w7.assignDefaults=_D;function P7($,Z,Q){let{gen:W,compositeRule:Y,data:G,opts:X}=$;if(Q===void 0)return;let J=X$._`${G}${(0,X$.getProperty)(Z)}`;if(Y){(0,bD.checkStrictMode)($,`default is ignored for: ${J}`);return}let K=X$._`${J} === undefined`;if(X.useDefaults==="empty")K=X$._`${K} || ${J} === null || ${J} === ""`;W.if(K,X$._`${J} = ${(0,X$.stringify)(Q)}`)}});var q0=M((C7)=>{Object.defineProperty(C7,"__esModule",{value:!0});C7.validateUnion=C7.validateArray=C7.usePattern=C7.callValidateCode=C7.schemaProperties=C7.allSchemaProperties=C7.noPropertyInData=C7.propertyInData=C7.isOwnProperty=C7.hasPropFunc=C7.reportMissingProp=C7.checkMissingProp=C7.checkReportMissingProp=void 0;var u=b(),B4=x(),D1=t0(),kD=x();function xD($,Z){let{gen:Q,data:W,it:Y}=$;Q.if(V4(Q,W,Z,Y.opts.ownProperties),()=>{$.setParams({missingProperty:u._`${Z}`},!0),$.error()})}C7.checkReportMissingProp=xD;function fD({gen:$,data:Z,it:{opts:Q}},W,Y){return(0,u.or)(...W.map((G)=>(0,u.and)(V4($,Z,G,Q.ownProperties),u._`${Y} = ${G}`)))}C7.checkMissingProp=fD;function vD($,Z){$.setParams({missingProperty:Z},!0),$.error()}C7.reportMissingProp=vD;function E7($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:u._`Object.prototype.hasOwnProperty`})}C7.hasPropFunc=E7;function H4($,Z,Q){return u._`${E7($)}.call(${Z}, ${Q})`}C7.isOwnProperty=H4;function gD($,Z,Q,W){let Y=u._`${Z}${(0,u.getProperty)(Q)} !== undefined`;return W?u._`${Y} && ${H4($,Z,Q)}`:Y}C7.propertyInData=gD;function V4($,Z,Q,W){let Y=u._`${Z}${(0,u.getProperty)(Q)} === undefined`;return W?(0,u.or)(Y,(0,u.not)(H4($,Z,Q))):Y}C7.noPropertyInData=V4;function R7($){return $?Object.keys($).filter((Z)=>Z!=="__proto__"):[]}C7.allSchemaProperties=R7;function hD($,Z){return R7(Z).filter((Q)=>!(0,B4.alwaysValidSchema)($,Z[Q]))}C7.schemaProperties=hD;function uD({schemaCode:$,data:Z,it:{gen:Q,topSchemaRef:W,schemaPath:Y,errorPath:G},it:X},J,K,B){let z=B?u._`${$}, ${Z}, ${W}${Y}`:Z,V=[[D1.default.instancePath,(0,u.strConcat)(D1.default.instancePath,G)],[D1.default.parentData,X.parentData],[D1.default.parentDataProperty,X.parentDataProperty],[D1.default.rootData,D1.default.rootData]];if(X.opts.dynamicRef)V.push([D1.default.dynamicAnchors,D1.default.dynamicAnchors]);let F=u._`${z}, ${Q.object(...V)}`;return K!==u.nil?u._`${J}.call(${K}, ${F})`:u._`${J}(${F})`}C7.callValidateCode=uD;var mD=u._`new RegExp`;function lD({gen:$,it:{opts:Z}},Q){let W=Z.unicodeRegExp?"u":"",{regExp:Y}=Z.code,G=Y(Q,W);return $.scopeValue("pattern",{key:G.toString(),ref:G,code:u._`${Y.code==="new RegExp"?mD:(0,kD.useFunc)($,Y)}(${Q}, ${W})`})}C7.usePattern=lD;function pD($){let{gen:Z,data:Q,keyword:W,it:Y}=$,G=Z.name("valid");if(Y.allErrors){let J=Z.let("valid",!0);return X(()=>Z.assign(J,!1)),J}return Z.var(G,!0),X(()=>Z.break()),G;function X(J){let K=Z.const("len",u._`${Q}.length`);Z.forRange("i",0,K,(B)=>{$.subschema({keyword:W,dataProp:B,dataPropType:B4.Type.Num},G),Z.if((0,u.not)(G),J)})}}C7.validateArray=pD;function cD($){let{gen:Z,schema:Q,keyword:W,it:Y}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Q.some((K)=>(0,B4.alwaysValidSchema)(Y,K))&&!Y.opts.unevaluated)return;let X=Z.let("valid",!1),J=Z.name("_valid");Z.block(()=>Q.forEach((K,B)=>{let z=$.subschema({keyword:W,schemaProp:B,compositeRule:!0},J);if(Z.assign(X,u._`${X} || ${J}`),!$.mergeValidEvaluated(z,J))Z.if((0,u.not)(X))})),$.result(X,()=>$.reset(),()=>$.error(!0))}C7.validateUnion=cD});var x7=M((_7)=>{Object.defineProperty(_7,"__esModule",{value:!0});_7.validateKeywordUsage=_7.validSchemaType=_7.funcKeywordCode=_7.macroKeywordCode=void 0;var G0=b(),_1=t0(),WL=q0(),YL=WZ();function GL($,Z){let{gen:Q,keyword:W,schema:Y,parentSchema:G,it:X}=$,J=Z.macro.call(X.self,Y,G,X),K=b7(Q,W,J);if(X.opts.validateSchema!==!1)X.self.validateSchema(J,!0);let B=Q.name("valid");$.subschema({schema:J,schemaPath:G0.nil,errSchemaPath:`${X.errSchemaPath}/${W}`,topSchemaRef:K,compositeRule:!0},B),$.pass(B,()=>$.error(!0))}_7.macroKeywordCode=GL;function XL($,Z){var Q;let{gen:W,keyword:Y,schema:G,parentSchema:X,$data:J,it:K}=$;KL(K,Z);let B=!J&&Z.compile?Z.compile.call(K.self,G,X,K):Z.validate,z=b7(W,Y,B),V=W.let("valid");$.block$data(V,F),$.ok((Q=Z.valid)!==null&&Q!==void 0?Q:V);function F(){if(Z.errors===!1){if(U(),Z.modifying)y7($);q(()=>$.error())}else{let A=Z.async?D():L();if(Z.modifying)y7($);q(()=>JL($,A))}}function D(){let A=W.let("ruleErrs",null);return W.try(()=>U(G0._`await `),(N)=>W.assign(V,!1).if(G0._`${N} instanceof ${K.ValidationError}`,()=>W.assign(A,G0._`${N}.errors`),()=>W.throw(N))),A}function L(){let A=G0._`${z}.errors`;return W.assign(A,null),U(G0.nil),A}function U(A=Z.async?G0._`await `:G0.nil){let N=K.opts.passContext?_1.default.this:_1.default.self,j=!(("compile"in Z)&&!J||Z.schema===!1);W.assign(V,G0._`${A}${(0,WL.callValidateCode)($,z,N,j)}`,Z.modifying)}function q(A){var N;W.if((0,G0.not)((N=Z.valid)!==null&&N!==void 0?N:V),A)}}_7.funcKeywordCode=XL;function y7($){let{gen:Z,data:Q,it:W}=$;Z.if(W.parentData,()=>Z.assign(Q,G0._`${W.parentData}[${W.parentDataProperty}]`))}function JL($,Z){let{gen:Q}=$;Q.if(G0._`Array.isArray(${Z})`,()=>{Q.assign(_1.default.vErrors,G0._`${_1.default.vErrors} === null ? ${Z} : ${_1.default.vErrors}.concat(${Z})`).assign(_1.default.errors,G0._`${_1.default.vErrors}.length`),(0,YL.extendErrors)($)},()=>$.error())}function KL({schemaEnv:$},Z){if(Z.async&&!$.$async)throw Error("async keyword in sync schema")}function b7($,Z,Q){if(Q===void 0)throw Error(`keyword "${Z}" failed to compile`);return $.scopeValue("keyword",typeof Q=="function"?{ref:Q}:{ref:Q,code:(0,G0.stringify)(Q)})}function BL($,Z,Q=!1){return!Z.length||Z.some((W)=>W==="array"?Array.isArray($):W==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==W||Q&&typeof $>"u")}_7.validSchemaType=BL;function HL({schema:$,opts:Z,self:Q,errSchemaPath:W},Y,G){if(Array.isArray(Y.keyword)?!Y.keyword.includes(G):Y.keyword!==G)throw Error("ajv implementation error");let X=Y.dependencies;if(X===null||X===void 0?void 0:X.some((J)=>!Object.prototype.hasOwnProperty.call($,J)))throw Error(`parent schema must have dependencies of ${G}: ${X.join(",")}`);if(Y.validateSchema){if(!Y.validateSchema($[G])){let K=`keyword "${G}" value is invalid at path "${W}": `+Q.errorsText(Y.validateSchema.errors);if(Z.validateSchema==="log")Q.logger.error(K);else throw Error(K)}}}_7.validateKeywordUsage=HL});var h7=M((v7)=>{Object.defineProperty(v7,"__esModule",{value:!0});v7.extendSubschemaMode=v7.extendSubschemaData=v7.getSubschema=void 0;var k0=b(),f7=x();function DL($,{keyword:Z,schemaProp:Q,schema:W,schemaPath:Y,errSchemaPath:G,topSchemaRef:X}){if(Z!==void 0&&W!==void 0)throw Error('both "keyword" and "schema" passed, only one allowed');if(Z!==void 0){let J=$.schema[Z];return Q===void 0?{schema:J,schemaPath:k0._`${$.schemaPath}${(0,k0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${Z}`}:{schema:J[Q],schemaPath:k0._`${$.schemaPath}${(0,k0.getProperty)(Z)}${(0,k0.getProperty)(Q)}`,errSchemaPath:`${$.errSchemaPath}/${Z}/${(0,f7.escapeFragment)(Q)}`}}if(W!==void 0){if(Y===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:W,schemaPath:Y,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}v7.getSubschema=DL;function LL($,Z,{dataProp:Q,dataPropType:W,data:Y,dataTypes:G,propertyName:X}){if(Y!==void 0&&Q!==void 0)throw Error('both "data" and "dataProp" passed, only one allowed');let{gen:J}=Z;if(Q!==void 0){let{errorPath:B,dataPathArr:z,opts:V}=Z,F=J.let("data",k0._`${Z.data}${(0,k0.getProperty)(Q)}`,!0);K(F),$.errorPath=k0.str`${B}${(0,f7.getErrorPath)(Q,W,V.jsPropertySyntax)}`,$.parentDataProperty=k0._`${Q}`,$.dataPathArr=[...z,$.parentDataProperty]}if(Y!==void 0){let B=Y instanceof k0.Name?Y:J.let("data",Y,!0);if(K(B),X!==void 0)$.propertyName=X}if(G)$.dataTypes=G;function K(B){$.data=B,$.dataLevel=Z.dataLevel+1,$.dataTypes=[],Z.definedProperties=new Set,$.parentData=Z.data,$.dataNames=[...Z.dataNames,B]}}v7.extendSubschemaData=LL;function UL($,{jtdDiscriminator:Z,jtdMetadata:Q,compositeRule:W,createErrors:Y,allErrors:G}){if(W!==void 0)$.compositeRule=W;if(Y!==void 0)$.createErrors=Y;if(G!==void 0)$.allErrors=G;$.jtdDiscriminator=Z,$.jtdMetadata=Q}v7.extendSubschemaMode=UL});var z4=M((_S,u7)=>{u7.exports=function $(Z,Q){if(Z===Q)return!0;if(Z&&Q&&typeof Z=="object"&&typeof Q=="object"){if(Z.constructor!==Q.constructor)return!1;var W,Y,G;if(Array.isArray(Z)){if(W=Z.length,W!=Q.length)return!1;for(Y=W;Y--!==0;)if(!$(Z[Y],Q[Y]))return!1;return!0}if(Z.constructor===RegExp)return Z.source===Q.source&&Z.flags===Q.flags;if(Z.valueOf!==Object.prototype.valueOf)return Z.valueOf()===Q.valueOf();if(Z.toString!==Object.prototype.toString)return Z.toString()===Q.toString();if(G=Object.keys(Z),W=G.length,W!==Object.keys(Q).length)return!1;for(Y=W;Y--!==0;)if(!Object.prototype.hasOwnProperty.call(Q,G[Y]))return!1;for(Y=W;Y--!==0;){var X=G[Y];if(!$(Z[X],Q[X]))return!1}return!0}return Z!==Z&&Q!==Q}});var l7=M((kS,m7)=>{var L1=m7.exports=function($,Z,Q){if(typeof Z=="function")Q=Z,Z={};Q=Z.cb||Q;var W=typeof Q=="function"?Q:Q.pre||function(){},Y=Q.post||function(){};S5(Z,W,Y,$,"",$)};L1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};L1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};L1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};L1.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 S5($,Z,Q,W,Y,G,X,J,K,B){if(W&&typeof W=="object"&&!Array.isArray(W)){Z(W,Y,G,X,J,K,B);for(var z in W){var V=W[z];if(Array.isArray(V)){if(z in L1.arrayKeywords)for(var F=0;F<V.length;F++)S5($,Z,Q,V[F],Y+"/"+z+"/"+F,G,Y,z,W,F)}else if(z in L1.propsKeywords){if(V&&typeof V=="object")for(var D in V)S5($,Z,Q,V[D],Y+"/"+z+"/"+NL(D),G,Y,z,W,D)}else if(z in L1.keywords||$.allKeys&&!(z in L1.skipKeywords))S5($,Z,Q,V,Y+"/"+z,G,Y,z,W)}Q(W,Y,G,X,J,K,B)}}function NL($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var GZ=M((i7)=>{Object.defineProperty(i7,"__esModule",{value:!0});i7.getSchemaRefs=i7.resolveUrl=i7.normalizeId=i7._getFullPath=i7.getFullPath=i7.inlineRef=void 0;var OL=x(),ML=z4(),jL=l7(),PL=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wL($,Z=!0){if(typeof $=="boolean")return!0;if(Z===!0)return!F4($);if(!Z)return!1;return p7($)<=Z}i7.inlineRef=wL;var TL=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function F4($){for(let Z in $){if(TL.has(Z))return!0;let Q=$[Z];if(Array.isArray(Q)&&Q.some(F4))return!0;if(typeof Q=="object"&&F4(Q))return!0}return!1}function p7($){let Z=0;for(let Q in $){if(Q==="$ref")return 1/0;if(Z++,PL.has(Q))continue;if(typeof $[Q]=="object")(0,OL.eachItem)($[Q],(W)=>Z+=p7(W));if(Z===1/0)return 1/0}return Z}function c7($,Z="",Q){if(Q!==!1)Z=J$(Z);let W=$.parse(Z);return d7($,W)}i7.getFullPath=c7;function d7($,Z){return $.serialize(Z).split("#")[0]+"#"}i7._getFullPath=d7;var IL=/#\/?$/;function J$($){return $?$.replace(IL,""):""}i7.normalizeId=J$;function EL($,Z,Q){return Q=J$(Q),$.resolve(Z,Q)}i7.resolveUrl=EL;var RL=/^[a-z_][-a-z0-9._]*$/i;function CL($,Z){if(typeof $=="boolean")return{};let{schemaId:Q,uriResolver:W}=this.opts,Y=J$($[Q]||Z),G={"":Y},X=c7(W,Y,!1),J={},K=new Set;return jL($,{allKeys:!0},(V,F,D,L)=>{if(L===void 0)return;let U=X+F,q=G[L];if(typeof V[Q]=="string")q=A.call(this,V[Q]);N.call(this,V.$anchor),N.call(this,V.$dynamicAnchor),G[F]=q;function A(j){let P=this.opts.uriResolver.resolve;if(j=J$(q?P(q,j):j),K.has(j))throw z(j);K.add(j);let O=this.refs[j];if(typeof O=="string")O=this.refs[O];if(typeof O=="object")B(V,O.schema,j);else if(j!==J$(U))if(j[0]==="#")B(V,J[j],j),J[j]=V;else this.refs[j]=U;return j}function N(j){if(typeof j=="string"){if(!RL.test(j))throw Error(`invalid anchor "${j}"`);A.call(this,`#${j}`)}}}),J;function B(V,F,D){if(F!==void 0&&!ML(V,F))throw z(D)}function z(V){return Error(`reference "${V}" resolves to more than one schema`)}}i7.getSchemaRefs=CL});var KZ=M((KY)=>{Object.defineProperty(KY,"__esModule",{value:!0});KY.getData=KY.KeywordCxt=KY.validateFunctionCode=void 0;var s7=V7(),a7=YZ(),L4=G4(),y5=YZ(),xL=I7(),JZ=x7(),D4=h7(),T=b(),R=t0(),fL=GZ(),o0=x(),XZ=WZ();function vL($){if(ZY($)){if(QY($),$Y($)){uL($);return}}e7($,()=>(0,s7.topBoolOrEmptySchema)($))}KY.validateFunctionCode=vL;function e7({gen:$,validateName:Z,schema:Q,schemaEnv:W,opts:Y},G){if(Y.code.es5)$.func(Z,T._`${R.default.data}, ${R.default.valCxt}`,W.$async,()=>{$.code(T._`"use strict"; ${r7(Q,Y)}`),hL($,Y),$.code(G)});else $.func(Z,T._`${R.default.data}, ${gL(Y)}`,W.$async,()=>$.code(r7(Q,Y)).code(G))}function gL($){return T._`{${R.default.instancePath}="", ${R.default.parentData}, ${R.default.parentDataProperty}, ${R.default.rootData}=${R.default.data}${$.dynamicRef?T._`, ${R.default.dynamicAnchors}={}`:T.nil}}={}`}function hL($,Z){$.if(R.default.valCxt,()=>{if($.var(R.default.instancePath,T._`${R.default.valCxt}.${R.default.instancePath}`),$.var(R.default.parentData,T._`${R.default.valCxt}.${R.default.parentData}`),$.var(R.default.parentDataProperty,T._`${R.default.valCxt}.${R.default.parentDataProperty}`),$.var(R.default.rootData,T._`${R.default.valCxt}.${R.default.rootData}`),Z.dynamicRef)$.var(R.default.dynamicAnchors,T._`${R.default.valCxt}.${R.default.dynamicAnchors}`)},()=>{if($.var(R.default.instancePath,T._`""`),$.var(R.default.parentData,T._`undefined`),$.var(R.default.parentDataProperty,T._`undefined`),$.var(R.default.rootData,R.default.data),Z.dynamicRef)$.var(R.default.dynamicAnchors,T._`{}`)})}function uL($){let{schema:Z,opts:Q,gen:W}=$;e7($,()=>{if(Q.$comment&&Z.$comment)YY($);if(dL($),W.let(R.default.vErrors,null),W.let(R.default.errors,0),Q.unevaluated)mL($);WY($),aL($)});return}function mL($){let{gen:Z,validateName:Q}=$;$.evaluated=Z.const("evaluated",T._`${Q}.evaluated`),Z.if(T._`${$.evaluated}.dynamicProps`,()=>Z.assign(T._`${$.evaluated}.props`,T._`undefined`)),Z.if(T._`${$.evaluated}.dynamicItems`,()=>Z.assign(T._`${$.evaluated}.items`,T._`undefined`))}function r7($,Z){let Q=typeof $=="object"&&$[Z.schemaId];return Q&&(Z.code.source||Z.code.process)?T._`/*# sourceURL=${Q} */`:T.nil}function lL($,Z){if(ZY($)){if(QY($),$Y($)){pL($,Z);return}}(0,s7.boolOrEmptySchema)($,Z)}function $Y({schema:$,self:Z}){if(typeof $=="boolean")return!$;for(let Q in $)if(Z.RULES.all[Q])return!0;return!1}function ZY($){return typeof $.schema!="boolean"}function pL($,Z){let{schema:Q,gen:W,opts:Y}=$;if(Y.$comment&&Q.$comment)YY($);iL($),nL($);let G=W.const("_errs",R.default.errors);WY($,G),W.var(Z,T._`${G} === ${R.default.errors}`)}function QY($){(0,o0.checkUnknownRules)($),cL($)}function WY($,Z){if($.opts.jtd)return t7($,[],!1,Z);let Q=(0,a7.getSchemaTypes)($.schema),W=(0,a7.coerceAndCheckDataType)($,Q);t7($,Q,!W,Z)}function cL($){let{schema:Z,errSchemaPath:Q,opts:W,self:Y}=$;if(Z.$ref&&W.ignoreKeywordsWithRef&&(0,o0.schemaHasRulesButRef)(Z,Y.RULES))Y.logger.warn(`$ref: keywords ignored in schema at path "${Q}"`)}function dL($){let{schema:Z,opts:Q}=$;if(Z.default!==void 0&&Q.useDefaults&&Q.strictSchema)(0,o0.checkStrictMode)($,"default is ignored in the schema root")}function iL($){let Z=$.schema[$.opts.schemaId];if(Z)$.baseId=(0,fL.resolveUrl)($.opts.uriResolver,$.baseId,Z)}function nL($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function YY({gen:$,schemaEnv:Z,schema:Q,errSchemaPath:W,opts:Y}){let G=Q.$comment;if(Y.$comment===!0)$.code(T._`${R.default.self}.logger.log(${G})`);else if(typeof Y.$comment=="function"){let X=T.str`${W}/$comment`,J=$.scopeValue("root",{ref:Z.root});$.code(T._`${R.default.self}.opts.$comment(${G}, ${X}, ${J}.schema)`)}}function aL($){let{gen:Z,schemaEnv:Q,validateName:W,ValidationError:Y,opts:G}=$;if(Q.$async)Z.if(T._`${R.default.errors} === 0`,()=>Z.return(R.default.data),()=>Z.throw(T._`new ${Y}(${R.default.vErrors})`));else{if(Z.assign(T._`${W}.errors`,R.default.vErrors),G.unevaluated)rL($);Z.return(T._`${R.default.errors} === 0`)}}function rL({gen:$,evaluated:Z,props:Q,items:W}){if(Q instanceof T.Name)$.assign(T._`${Z}.props`,Q);if(W instanceof T.Name)$.assign(T._`${Z}.items`,W)}function t7($,Z,Q,W){let{gen:Y,schema:G,data:X,allErrors:J,opts:K,self:B}=$,{RULES:z}=B;if(G.$ref&&(K.ignoreKeywordsWithRef||!(0,o0.schemaHasRulesButRef)(G,z))){Y.block(()=>XY($,"$ref",z.all.$ref.definition));return}if(!K.jtd)tL($,Z);Y.block(()=>{for(let F of z.rules)V(F);V(z.post)});function V(F){if(!(0,L4.shouldUseGroup)(G,F))return;if(F.type){if(Y.if((0,y5.checkDataType)(F.type,X,K.strictNumbers)),o7($,F),Z.length===1&&Z[0]===F.type&&Q)Y.else(),(0,y5.reportTypeError)($);Y.endIf()}else o7($,F);if(!J)Y.if(T._`${R.default.errors} === ${W||0}`)}}function o7($,Z){let{gen:Q,schema:W,opts:{useDefaults:Y}}=$;if(Y)(0,xL.assignDefaults)($,Z.type);Q.block(()=>{for(let G of Z.rules)if((0,L4.shouldUseRule)(W,G))XY($,G.keyword,G.definition,Z.type)})}function tL($,Z){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(oL($,Z),!$.opts.allowUnionTypes)sL($,Z);eL($,$.dataTypes)}function oL($,Z){if(!Z.length)return;if(!$.dataTypes.length){$.dataTypes=Z;return}Z.forEach((Q)=>{if(!GY($.dataTypes,Q))U4($,`type "${Q}" not allowed by context "${$.dataTypes.join(",")}"`)}),ZU($,Z)}function sL($,Z){if(Z.length>1&&!(Z.length===2&&Z.includes("null")))U4($,"use allowUnionTypes to allow union type keyword")}function eL($,Z){let Q=$.self.RULES.all;for(let W in Q){let Y=Q[W];if(typeof Y=="object"&&(0,L4.shouldUseRule)($.schema,Y)){let{type:G}=Y.definition;if(G.length&&!G.some((X)=>$U(Z,X)))U4($,`missing type "${G.join(",")}" for keyword "${W}"`)}}}function $U($,Z){return $.includes(Z)||Z==="number"&&$.includes("integer")}function GY($,Z){return $.includes(Z)||Z==="integer"&&$.includes("number")}function ZU($,Z){let Q=[];for(let W of $.dataTypes)if(GY(Z,W))Q.push(W);else if(Z.includes("integer")&&W==="number")Q.push("integer");$.dataTypes=Q}function U4($,Z){let Q=$.schemaEnv.baseId+$.errSchemaPath;Z+=` at "${Q}" (strictTypes)`,(0,o0.checkStrictMode)($,Z,$.opts.strictTypes)}class q4{constructor($,Z,Q){if((0,JZ.validateKeywordUsage)($,Z,Q),this.gen=$.gen,this.allErrors=$.allErrors,this.keyword=Q,this.data=$.data,this.schema=$.schema[Q],this.$data=Z.$data&&$.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,o0.schemaRefOrVal)($,this.schema,Q,this.$data),this.schemaType=Z.schemaType,this.parentSchema=$.schema,this.params={},this.it=$,this.def=Z,this.$data)this.schemaCode=$.gen.const("vSchema",JY(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,JZ.validSchemaType)(this.schema,Z.schemaType,Z.allowUndefined))throw Error(`${Q} value must be ${JSON.stringify(Z.schemaType)}`);if("code"in Z?Z.trackErrors:Z.errors!==!1)this.errsCount=$.gen.const("_errs",R.default.errors)}result($,Z,Q){this.failResult((0,T.not)($),Z,Q)}failResult($,Z,Q){if(this.gen.if($),Q)Q();else this.error();if(Z){if(this.gen.else(),Z(),this.allErrors)this.gen.endIf()}else if(this.allErrors)this.gen.endIf();else this.gen.else()}pass($,Z){this.failResult((0,T.not)($),void 0,Z)}fail($){if($===void 0){if(this.error(),!this.allErrors)this.gen.if(!1);return}if(this.gen.if($),this.error(),this.allErrors)this.gen.endIf();else this.gen.else()}fail$data($){if(!this.$data)return this.fail($);let{schemaCode:Z}=this;this.fail(T._`${Z} !== undefined && (${(0,T.or)(this.invalid$data(),$)})`)}error($,Z,Q){if(Z){this.setParams(Z),this._error($,Q),this.setParams({});return}this._error($,Q)}_error($,Z){($?XZ.reportExtraError:XZ.reportError)(this,this.def.error,Z)}$dataError(){(0,XZ.reportError)(this,this.def.$dataError||XZ.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,XZ.resetErrorsCount)(this.gen,this.errsCount)}ok($){if(!this.allErrors)this.gen.if($)}setParams($,Z){if(Z)Object.assign(this.params,$);else this.params=$}block$data($,Z,Q=T.nil){this.gen.block(()=>{this.check$data($,Q),Z()})}check$data($=T.nil,Z=T.nil){if(!this.$data)return;let{gen:Q,schemaCode:W,schemaType:Y,def:G}=this;if(Q.if((0,T.or)(T._`${W} === undefined`,Z)),$!==T.nil)Q.assign($,!0);if(Y.length||G.validateSchema){if(Q.elseIf(this.invalid$data()),this.$dataError(),$!==T.nil)Q.assign($,!1)}Q.else()}invalid$data(){let{gen:$,schemaCode:Z,schemaType:Q,def:W,it:Y}=this;return(0,T.or)(G(),X());function G(){if(Q.length){if(!(Z instanceof T.Name))throw Error("ajv implementation error");let J=Array.isArray(Q)?Q:[Q];return T._`${(0,y5.checkDataTypes)(J,Z,Y.opts.strictNumbers,y5.DataType.Wrong)}`}return T.nil}function X(){if(W.validateSchema){let J=$.scopeValue("validate$data",{ref:W.validateSchema});return T._`!${J}(${Z})`}return T.nil}}subschema($,Z){let Q=(0,D4.getSubschema)(this.it,$);(0,D4.extendSubschemaData)(Q,this.it,$),(0,D4.extendSubschemaMode)(Q,$);let W={...this.it,...Q,items:void 0,props:void 0};return lL(W,Z),W}mergeEvaluated($,Z){let{it:Q,gen:W}=this;if(!Q.opts.unevaluated)return;if(Q.props!==!0&&$.props!==void 0)Q.props=o0.mergeEvaluated.props(W,$.props,Q.props,Z);if(Q.items!==!0&&$.items!==void 0)Q.items=o0.mergeEvaluated.items(W,$.items,Q.items,Z)}mergeValidEvaluated($,Z){let{it:Q,gen:W}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return W.if(Z,()=>this.mergeEvaluated($,T.Name)),!0}}KY.KeywordCxt=q4;function XY($,Z,Q,W){let Y=new q4($,Q,Z);if("code"in Q)Q.code(Y,W);else if(Y.$data&&Q.validate)(0,JZ.funcKeywordCode)(Y,Q);else if("macro"in Q)(0,JZ.macroKeywordCode)(Y,Q);else if(Q.compile||Q.validate)(0,JZ.funcKeywordCode)(Y,Q)}var QU=/^\/(?:[^~]|~0|~1)*$/,WU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function JY($,{dataLevel:Z,dataNames:Q,dataPathArr:W}){let Y,G;if($==="")return R.default.rootData;if($[0]==="/"){if(!QU.test($))throw Error(`Invalid JSON-pointer: ${$}`);Y=$,G=R.default.rootData}else{let B=WU.exec($);if(!B)throw Error(`Invalid JSON-pointer: ${$}`);let z=+B[1];if(Y=B[2],Y==="#"){if(z>=Z)throw Error(K("property/index",z));return W[Z-z]}if(z>Z)throw Error(K("data",z));if(G=Q[Z-z],!Y)return G}let X=G,J=Y.split("/");for(let B of J)if(B)G=T._`${G}${(0,T.getProperty)((0,o0.unescapeJsonPointer)(B))}`,X=T._`${X} && ${G}`;return X;function K(B,z){return`Cannot access ${B} ${z} levels up, current level is ${Z}`}}KY.getData=JY});var b5=M((VY)=>{Object.defineProperty(VY,"__esModule",{value:!0});class HY extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}VY.default=HY});var BZ=M((FY)=>{Object.defineProperty(FY,"__esModule",{value:!0});var A4=GZ();class zY extends Error{constructor($,Z,Q,W){super(W||`can't resolve reference ${Q} from id ${Z}`);this.missingRef=(0,A4.resolveUrl)($,Z,Q),this.missingSchema=(0,A4.normalizeId)((0,A4.getFullPath)($,this.missingRef))}}FY.default=zY});var k5=M((UY)=>{Object.defineProperty(UY,"__esModule",{value:!0});UY.resolveSchema=UY.getCompilingSchema=UY.resolveRef=UY.compileSchema=UY.SchemaEnv=void 0;var w0=b(),KU=b5(),k1=t0(),T0=GZ(),DY=x(),BU=KZ();class HZ{constructor($){var Z;this.refs={},this.dynamicAnchors={};let Q;if(typeof $.schema=="object")Q=$.schema;this.schema=$.schema,this.schemaId=$.schemaId,this.root=$.root||this,this.baseId=(Z=$.baseId)!==null&&Z!==void 0?Z:(0,T0.normalizeId)(Q===null||Q===void 0?void 0:Q[$.schemaId||"$id"]),this.schemaPath=$.schemaPath,this.localRefs=$.localRefs,this.meta=$.meta,this.$async=Q===null||Q===void 0?void 0:Q.$async,this.refs={}}}UY.SchemaEnv=HZ;function O4($){let Z=LY.call(this,$);if(Z)return Z;let Q=(0,T0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:W,lines:Y}=this.opts.code,{ownProperties:G}=this.opts,X=new w0.CodeGen(this.scope,{es5:W,lines:Y,ownProperties:G}),J;if($.$async)J=X.scopeValue("Error",{ref:KU.default,code:w0._`require("ajv/dist/runtime/validation_error").default`});let K=X.scopeName("validate");$.validateName=K;let B={gen:X,allErrors:this.opts.allErrors,data:k1.default.data,parentData:k1.default.parentData,parentDataProperty:k1.default.parentDataProperty,dataNames:[k1.default.data],dataPathArr:[w0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,w0.stringify)($.schema)}:{ref:$.schema}),validateName:K,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:Q,baseId:$.baseId||Q,schemaPath:w0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:w0._`""`,opts:this.opts,self:this},z;try{this._compilations.add($),(0,BU.validateFunctionCode)(B),X.optimize(this.opts.code.optimize);let V=X.toString();if(z=`${X.scopeRefs(k1.default.scope)}return ${V}`,this.opts.code.process)z=this.opts.code.process(z,$);let D=Function(`${k1.default.self}`,`${k1.default.scope}`,z)(this,this.scope.get());if(this.scope.value(K,{ref:D}),D.errors=null,D.schema=$.schema,D.schemaEnv=$,$.$async)D.$async=!0;if(this.opts.code.source===!0)D.source={validateName:K,validateCode:V,scopeValues:X._values};if(this.opts.unevaluated){let{props:L,items:U}=B;if(D.evaluated={props:L instanceof w0.Name?void 0:L,items:U instanceof w0.Name?void 0:U,dynamicProps:L instanceof w0.Name,dynamicItems:U instanceof w0.Name},D.source)D.source.evaluated=(0,w0.stringify)(D.evaluated)}return $.validate=D,$}catch(V){if(delete $.validate,delete $.validateName,z)this.logger.error("Error compiling schema, function code:",z);throw V}finally{this._compilations.delete($)}}UY.compileSchema=O4;function HU($,Z,Q){var W;Q=(0,T0.resolveUrl)(this.opts.uriResolver,Z,Q);let Y=$.refs[Q];if(Y)return Y;let G=FU.call(this,$,Q);if(G===void 0){let X=(W=$.localRefs)===null||W===void 0?void 0:W[Q],{schemaId:J}=this.opts;if(X)G=new HZ({schema:X,schemaId:J,root:$,baseId:Z})}if(G===void 0)return;return $.refs[Q]=VU.call(this,G)}UY.resolveRef=HU;function VU($){if((0,T0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:O4.call(this,$)}function LY($){for(let Z of this._compilations)if(zU(Z,$))return Z}UY.getCompilingSchema=LY;function zU($,Z){return $.schema===Z.schema&&$.root===Z.root&&$.baseId===Z.baseId}function FU($,Z){let Q;while(typeof(Q=this.refs[Z])=="string")Z=Q;return Q||this.schemas[Z]||_5.call(this,$,Z)}function _5($,Z){let Q=this.opts.uriResolver.parse(Z),W=(0,T0._getFullPath)(this.opts.uriResolver,Q),Y=(0,T0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&W===Y)return N4.call(this,Q,$);let G=(0,T0.normalizeId)(W),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let J=_5.call(this,$,X);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return N4.call(this,Q,J)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)O4.call(this,X);if(G===(0,T0.normalizeId)(Z)){let{schema:J}=X,{schemaId:K}=this.opts,B=J[K];if(B)Y=(0,T0.resolveUrl)(this.opts.uriResolver,Y,B);return new HZ({schema:J,schemaId:K,root:$,baseId:Y})}return N4.call(this,Q,X)}UY.resolveSchema=_5;var DU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function N4($,{baseId:Z,schema:Q,root:W}){var Y;if(((Y=$.fragment)===null||Y===void 0?void 0:Y[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof Q==="boolean")return;let K=Q[(0,DY.unescapeFragment)(J)];if(K===void 0)return;Q=K;let B=typeof Q==="object"&&Q[this.opts.schemaId];if(!DU.has(J)&&B)Z=(0,T0.resolveUrl)(this.opts.uriResolver,Z,B)}let G;if(typeof Q!="boolean"&&Q.$ref&&!(0,DY.schemaHasRulesButRef)(Q,this.RULES)){let J=(0,T0.resolveUrl)(this.opts.uriResolver,Z,Q.$ref);G=_5.call(this,W,J)}let{schemaId:X}=this.opts;if(G=G||new HZ({schema:Q,schemaId:X,root:W,baseId:Z}),G.schema!==G.root.schema)return G;return}});var AY=M((uS,NU)=>{NU.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 P4=M((mS,wY)=>{var OU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),OY=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),M4=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),MY=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),MU=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function j4($){let Z="",Q=0,W=0;for(W=0;W<$.length;W++){if(Q=$[W].charCodeAt(0),Q===48)continue;if(!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[W];break}for(W+=1;W<$.length;W++){if(Q=$[W].charCodeAt(0),!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[W]}return Z}var jU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function NY($){return $.length=0,!0}function PU($,Z,Q){if($.length){let W=j4($);if(W!=="")Z.push(W);else return Q.error=!0,!1;$.length=0}return!0}function wU($){let Z=0,Q={error:!1,address:"",zone:""},W=[],Y=[],G=!1,X=!1,J=PU;for(let K=0;K<$.length;K++){let B=$[K];if(B==="["||B==="]")continue;if(B===":"){if(G===!0)X=!0;if(!J(Y,W,Q))break;if(++Z>7){Q.error=!0;break}if(K>0&&$[K-1]===":")G=!0;W.push(":");continue}else if(B==="%"){if(!J(Y,W,Q))break;J=NY}else{Y.push(B);continue}}if(Y.length)if(J===NY)Q.zone=Y.join("");else if(X)W.push(Y.join(""));else W.push(j4(Y));return Q.address=W.join(""),Q}function jY($){if(TU($,":")<2)return{host:$,isIPV6:!1};let Z=wU($);if(!Z.error){let{address:Q,address:W}=Z;if(Z.zone)Q+="%"+Z.zone,W+="%25"+Z.zone;return{host:Q,isIPV6:!0,escapedHost:W}}else return{host:$,isIPV6:!1}}function TU($,Z){let Q=0;for(let W=0;W<$.length;W++)if($[W]===Z)Q++;return Q}function IU($){let Z=$,Q=[],W=-1,Y=0;while(Y=Z.length){if(Y===1)if(Z===".")break;else if(Z==="/"){Q.push("/");break}else{Q.push(Z);break}else if(Y===2){if(Z[0]==="."){if(Z[1]===".")break;else if(Z[1]==="/"){Z=Z.slice(2);continue}}else if(Z[0]==="/"){if(Z[1]==="."||Z[1]==="/"){Q.push("/");break}}}else if(Y===3){if(Z==="/.."){if(Q.length!==0)Q.pop();Q.push("/");break}}if(Z[0]==="."){if(Z[1]==="."){if(Z[2]==="/"){Z=Z.slice(3);continue}}else if(Z[1]==="/"){Z=Z.slice(2);continue}}else if(Z[0]==="/"){if(Z[1]==="."){if(Z[2]==="/"){Z=Z.slice(2);continue}else if(Z[2]==="."){if(Z[3]==="/"){if(Z=Z.slice(3),Q.length!==0)Q.pop();continue}}}}if((W=Z.indexOf("/",1))===-1){Q.push(Z);break}else Q.push(Z.slice(0,W)),Z=Z.slice(W)}return Q.join("")}var EU={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},RU=/[@/?#:]/g,CU=/[@/?#]/g;function PY($,Z){let Q=Z?CU:RU;return Q.lastIndex=0,$.replace(Q,(W)=>EU[W])}function SU($,Z=!1){if($.indexOf("%")===-1)return $;let Q="";for(let W=0;W<$.length;W++){if($[W]==="%"&&W+2<$.length){let Y=$.slice(W+1,W+3);if(M4(Y)){let G=Y.toUpperCase(),X=String.fromCharCode(parseInt(G,16));if(Z&&MY(X))Q+=X;else Q+="%"+G;W+=2;continue}}Q+=$[W]}return Q}function yU($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let W=$.slice(Q+1,Q+3);if(M4(W)){let Y=W.toUpperCase(),G=String.fromCharCode(parseInt(Y,16));if(G!=="."&&MY(G))Z+=G;else Z+="%"+Y;Q+=2;continue}}if(MU($[Q]))Z+=$[Q];else Z+=escape($[Q])}return Z}function bU($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let W=$.slice(Q+1,Q+3);if(M4(W)){Z+="%"+W.toUpperCase(),Q+=2;continue}}Z+=escape($[Q])}return Z}function _U($){let Z=[];if($.userinfo!==void 0)Z.push($.userinfo),Z.push("@");if($.host!==void 0){let Q=unescape($.host);if(!OY(Q)){let W=jY(Q);if(W.isIPV6===!0)Q=`[${W.escapedHost}]`;else Q=PY(Q,!1)}Z.push(Q)}if(typeof $.port==="number"||typeof $.port==="string")Z.push(":"),Z.push(String($.port));return Z.length?Z.join(""):void 0}wY.exports={nonSimpleDomain:jU,recomposeAuthority:_U,reescapeHostDelimiters:PY,normalizePercentEncoding:SU,normalizePathEncoding:yU,escapePreservingEscapes:bU,removeDotSegments:IU,isIPv4:OY,isUUID:OU,normalizeIPv6:jY,stringArrayToHexStripped:j4}});var CY=M((lS,RY)=>{var{isUUID:kU}=P4(),xU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fU=["http","https","ws","wss","urn","urn:uuid"];function vU($){return fU.indexOf($)!==-1}function w4($){if($.secure===!0)return!0;else if($.secure===!1)return!1;else if($.scheme)return $.scheme.length===3&&($.scheme[0]==="w"||$.scheme[0]==="W")&&($.scheme[1]==="s"||$.scheme[1]==="S")&&($.scheme[2]==="s"||$.scheme[2]==="S");else return!1}function TY($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function IY($){let Z=String($.scheme).toLowerCase()==="https";if($.port===(Z?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function gU($){return $.secure=w4($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function hU($){if($.port===(w4($)?443:80)||$.port==="")$.port=void 0;if(typeof $.secure==="boolean")$.scheme=$.secure?"wss":"ws",$.secure=void 0;if($.resourceName){let[Z,Q]=$.resourceName.split("?");$.path=Z&&Z!=="/"?Z:void 0,$.query=Q,$.resourceName=void 0}return $.fragment=void 0,$}function uU($,Z){if(!$.path)return $.error="URN can not be parsed",$;let Q=$.path.match(xU);if(Q){let W=Z.scheme||$.scheme||"urn";$.nid=Q[1].toLowerCase(),$.nss=Q[2];let Y=`${W}:${Z.nid||$.nid}`,G=T4(Y);if($.path=void 0,G)$=G.parse($,Z)}else $.error=$.error||"URN can not be parsed.";return $}function mU($,Z){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Q=Z.scheme||$.scheme||"urn",W=$.nid.toLowerCase(),Y=`${Q}:${Z.nid||W}`,G=T4(Y);if(G)$=G.serialize($,Z);let X=$,J=$.nss;return X.path=`${W||Z.nid}:${J}`,Z.skipEscape=!0,X}function lU($,Z){let Q=$;if(Q.uuid=Q.nss,Q.nss=void 0,!Z.tolerant&&(!Q.uuid||!kU(Q.uuid)))Q.error=Q.error||"UUID is not valid.";return Q}function pU($){let Z=$;return Z.nss=($.uuid||"").toLowerCase(),Z}var EY={scheme:"http",domainHost:!0,parse:TY,serialize:IY},cU={scheme:"https",domainHost:EY.domainHost,parse:TY,serialize:IY},x5={scheme:"ws",domainHost:!0,parse:gU,serialize:hU},dU={scheme:"wss",domainHost:x5.domainHost,parse:x5.parse,serialize:x5.serialize},iU={scheme:"urn",parse:uU,serialize:mU,skipNormalize:!0},nU={scheme:"urn:uuid",parse:lU,serialize:pU,skipNormalize:!0},f5={http:EY,https:cU,ws:x5,wss:dU,urn:iU,"urn:uuid":nU};Object.setPrototypeOf(f5,null);function T4($){return $&&(f5[$]||f5[$.toLowerCase()])||void 0}RY.exports={wsIsSecure:w4,SCHEMES:f5,isValidSchemeName:vU,getSchemeHandler:T4}});var xY=M((pS,v5)=>{var{normalizeIPv6:aU,removeDotSegments:VZ,recomposeAuthority:rU,normalizePercentEncoding:tU,normalizePathEncoding:oU,escapePreservingEscapes:sU,reescapeHostDelimiters:eU,isIPv4:$q,nonSimpleDomain:Zq}=P4(),{SCHEMES:Qq,getSchemeHandler:yY}=CY();function Wq($,Z){if(typeof $==="string")$=Bq($,Z);else if(typeof $==="object")$=K$(x1($,Z),Z);return $}function Yq($,Z,Q){let W=Q?Object.assign({scheme:"null"},Q):{scheme:"null"},Y=bY(K$($,W),K$(Z,W),W,!0);return W.skipEscape=!0,x1(Y,W)}function bY($,Z,Q,W){let Y={};if(!W)$=K$(x1($,Q),Q),Z=K$(x1(Z,Q),Q);if(Q=Q||{},!Q.tolerant&&Z.scheme)Y.scheme=Z.scheme,Y.userinfo=Z.userinfo,Y.host=Z.host,Y.port=Z.port,Y.path=VZ(Z.path||""),Y.query=Z.query;else{if(Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)Y.userinfo=Z.userinfo,Y.host=Z.host,Y.port=Z.port,Y.path=VZ(Z.path||""),Y.query=Z.query;else{if(!Z.path)if(Y.path=$.path,Z.query!==void 0)Y.query=Z.query;else Y.query=$.query;else{if(Z.path[0]==="/")Y.path=VZ(Z.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)Y.path="/"+Z.path;else if(!$.path)Y.path=Z.path;else Y.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+Z.path;Y.path=VZ(Y.path)}Y.query=Z.query}Y.userinfo=$.userinfo,Y.host=$.host,Y.port=$.port}Y.scheme=$.scheme}return Y.fragment=Z.fragment,Y}function Gq($,Z,Q){let W=SY($,Q),Y=SY(Z,Q);return W!==void 0&&Y!==void 0&&W.toLowerCase()===Y.toLowerCase()}function x1($,Z){let Q={host:$.host,scheme:$.scheme,userinfo:$.userinfo,port:$.port,path:$.path,query:$.query,nid:$.nid,nss:$.nss,uuid:$.uuid,fragment:$.fragment,reference:$.reference,resourceName:$.resourceName,secure:$.secure,error:""},W=Object.assign({},Z),Y=[],G=yY(W.scheme||Q.scheme);if(G&&G.serialize)G.serialize(Q,W);if(Q.path!==void 0)if(!W.skipEscape){if(Q.path=sU(Q.path),Q.scheme!==void 0)Q.path=Q.path.split("%3A").join(":")}else Q.path=tU(Q.path);if(W.reference!=="suffix"&&Q.scheme)Y.push(Q.scheme,":");let X=rU(Q);if(X!==void 0){if(W.reference!=="suffix")Y.push("//");if(Y.push(X),Q.path&&Q.path[0]!=="/")Y.push("/")}if(Q.path!==void 0){let J=Q.path;if(!W.absolutePath&&(!G||!G.absolutePath))J=VZ(J);if(X===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);Y.push(J)}if(Q.query!==void 0)Y.push("?",Q.query);if(Q.fragment!==void 0)Y.push("#",Q.fragment);return Y.join("")}var Xq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,Jq=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function Kq($,Z){if(Z[2]!==void 0&&$.path&&$.path[0]!=="/")return'URI path must start with "/" when authority is present.';if(typeof $.port==="number"&&($.port<0||$.port>65535))return"URI port is malformed.";return}function _Y($,Z){let Q=Object.assign({},Z),W={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},Y=!1,G=!1;if(Q.reference==="suffix")if(Q.scheme)$=Q.scheme+":"+$;else $="//"+$;let X=$.match(Jq);if(X!==null&&X[1].indexOf("\\")!==-1)W.error="URI authority must not contain a literal backslash.",Y=!0;let J=$.match(Xq);if(J){if(W.scheme=J[1],W.userinfo=J[3],W.host=J[4],W.port=parseInt(J[5],10),W.path=J[6]||"",W.query=J[7],W.fragment=J[8],isNaN(W.port))W.port=J[5];let K=Kq(W,J);if(K!==void 0)W.error=W.error||K,Y=!0;if(W.host)if($q(W.host)===!1){let V=aU(W.host);W.host=V.host.toLowerCase(),G=V.isIPV6}else G=!0;if(W.scheme===void 0&&W.userinfo===void 0&&W.host===void 0&&W.port===void 0&&W.query===void 0&&!W.path)W.reference="same-document";else if(W.scheme===void 0)W.reference="relative";else if(W.fragment===void 0)W.reference="absolute";else W.reference="uri";if(Q.reference&&Q.reference!=="suffix"&&Q.reference!==W.reference)W.error=W.error||"URI is not a "+Q.reference+" reference.";let B=yY(Q.scheme||W.scheme);if(!Q.unicodeSupport&&(!B||!B.unicodeSupport)){if(W.host&&(Q.domainHost||B&&B.domainHost)&&G===!1&&Zq(W.host))try{W.host=new URL("http://"+W.host).hostname}catch(z){W.error=W.error||"Host's domain name can not be converted to ASCII: "+z}}if(!B||B&&!B.skipNormalize){if($.indexOf("%")!==-1){if(W.scheme!==void 0)W.scheme=unescape(W.scheme);if(W.host!==void 0)W.host=eU(unescape(W.host),G)}if(W.path)W.path=oU(W.path);if(W.fragment)try{W.fragment=encodeURI(decodeURIComponent(W.fragment))}catch{W.error=W.error||"URI malformed"}}if(B&&B.parse)B.parse(W,Q)}else W.error=W.error||"URI can not be parsed.";return{parsed:W,malformedAuthorityOrPort:Y}}function K$($,Z){return _Y($,Z).parsed}function Bq($,Z){return kY($,Z).normalized}function kY($,Z){let{parsed:Q,malformedAuthorityOrPort:W}=_Y($,Z);return{normalized:W?$:x1(Q,Z),malformedAuthorityOrPort:W}}function SY($,Z){if(typeof $==="string"){let{normalized:Q,malformedAuthorityOrPort:W}=kY($,Z);return W?void 0:Q}if(typeof $==="object")return x1($,Z)}var I4={SCHEMES:Qq,normalize:Wq,resolve:Yq,resolveComponent:bY,equal:Gq,serialize:x1,parse:K$};v5.exports=I4;v5.exports.default=I4;v5.exports.fastUri=I4});var gY=M((vY)=>{Object.defineProperty(vY,"__esModule",{value:!0});var fY=xY();fY.code='require("ajv/dist/runtime/uri").default';vY.default=fY});var iY=M((s0)=>{Object.defineProperty(s0,"__esModule",{value:!0});s0.CodeGen=s0.Name=s0.nil=s0.stringify=s0.str=s0._=s0.KeywordCxt=void 0;var Vq=KZ();Object.defineProperty(s0,"KeywordCxt",{enumerable:!0,get:function(){return Vq.KeywordCxt}});var B$=b();Object.defineProperty(s0,"_",{enumerable:!0,get:function(){return B$._}});Object.defineProperty(s0,"str",{enumerable:!0,get:function(){return B$.str}});Object.defineProperty(s0,"stringify",{enumerable:!0,get:function(){return B$.stringify}});Object.defineProperty(s0,"nil",{enumerable:!0,get:function(){return B$.nil}});Object.defineProperty(s0,"Name",{enumerable:!0,get:function(){return B$.Name}});Object.defineProperty(s0,"CodeGen",{enumerable:!0,get:function(){return B$.CodeGen}});var zq=b5(),pY=BZ(),Fq=Y4(),zZ=k5(),Dq=b(),FZ=GZ(),g5=YZ(),R4=x(),hY=AY(),Lq=gY(),cY=($,Z)=>new RegExp($,Z);cY.code="new RegExp";var Uq=["removeAdditional","useDefaults","coerceTypes"],qq=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Aq={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."},Nq={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},uY=200;function Oq($){var Z,Q,W,Y,G,X,J,K,B,z,V,F,D,L,U,q,A,N,j,P,O,C,v,d,w;let _=$.strict,r=(Z=$.code)===null||Z===void 0?void 0:Z.optimize,g=r===!0||r===void 0?1:r||0,a=(W=(Q=$.code)===null||Q===void 0?void 0:Q.regExp)!==null&&W!==void 0?W:cY,RZ=(Y=$.uriResolver)!==null&&Y!==void 0?Y:Lq.default;return{strictSchema:(X=(G=$.strictSchema)!==null&&G!==void 0?G:_)!==null&&X!==void 0?X:!0,strictNumbers:(K=(J=$.strictNumbers)!==null&&J!==void 0?J:_)!==null&&K!==void 0?K:!0,strictTypes:(z=(B=$.strictTypes)!==null&&B!==void 0?B:_)!==null&&z!==void 0?z:"log",strictTuples:(F=(V=$.strictTuples)!==null&&V!==void 0?V:_)!==null&&F!==void 0?F:"log",strictRequired:(L=(D=$.strictRequired)!==null&&D!==void 0?D:_)!==null&&L!==void 0?L:!1,code:$.code?{...$.code,optimize:g,regExp:a}:{optimize:g,regExp:a},loopRequired:(U=$.loopRequired)!==null&&U!==void 0?U:uY,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:uY,meta:(A=$.meta)!==null&&A!==void 0?A:!0,messages:(N=$.messages)!==null&&N!==void 0?N:!0,inlineRefs:(j=$.inlineRefs)!==null&&j!==void 0?j:!0,schemaId:(P=$.schemaId)!==null&&P!==void 0?P:"$id",addUsedSchema:(O=$.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(C=$.validateSchema)!==null&&C!==void 0?C:!0,validateFormats:(v=$.validateFormats)!==null&&v!==void 0?v:!0,unicodeRegExp:(d=$.unicodeRegExp)!==null&&d!==void 0?d:!0,int32range:(w=$.int32range)!==null&&w!==void 0?w:!0,uriResolver:RZ}}class h5{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...Oq($)};let{es5:Z,lines:Q}=this.opts.code;this.scope=new Dq.ValueScope({scope:{},prefixes:qq,es5:Z,lines:Q}),this.logger=Iq($.logger);let W=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,Fq.getRules)(),mY.call(this,Aq,$,"NOT SUPPORTED"),mY.call(this,Nq,$,"DEPRECATED","warn"),this._metaOpts=wq.call(this),$.formats)jq.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)Pq.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);Mq.call(this),$.validateFormats=W}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:Z,schemaId:Q}=this.opts,W=hY;if(Q==="id")W={...hY},W.id=W.$id,delete W.$id;if(Z&&$)this.addMetaSchema(W,W[Q],!1)}defaultMeta(){let{meta:$,schemaId:Z}=this.opts;return this.opts.defaultMeta=typeof $=="object"?$[Z]||$:void 0}validate($,Z){let Q;if(typeof $=="string"){if(Q=this.getSchema($),!Q)throw Error(`no schema with key or ref "${$}"`)}else Q=this.compile($);let W=Q(Z);if(!("$async"in Q))this.errors=Q.errors;return W}compile($,Z){let Q=this._addSchema($,Z);return Q.validate||this._compileSchemaEnv(Q)}compileAsync($,Z){if(typeof this.opts.loadSchema!="function")throw Error("options.loadSchema should be a function");let{loadSchema:Q}=this.opts;return W.call(this,$,Z);async function W(B,z){await Y.call(this,B.$schema);let V=this._addSchema(B,z);return V.validate||G.call(this,V)}async function Y(B){if(B&&!this.getSchema(B))await W.call(this,{$ref:B},!0)}async function G(B){try{return this._compileSchemaEnv(B)}catch(z){if(!(z instanceof pY.default))throw z;return X.call(this,z),await J.call(this,z.missingSchema),G.call(this,B)}}function X({missingSchema:B,missingRef:z}){if(this.refs[B])throw Error(`AnySchema ${B} is loaded but ${z} cannot be resolved`)}async function J(B){let z=await K.call(this,B);if(!this.refs[B])await Y.call(this,z.$schema);if(!this.refs[B])this.addSchema(z,B,Z)}async function K(B){let z=this._loading[B];if(z)return z;try{return await(this._loading[B]=Q(B))}finally{delete this._loading[B]}}}addSchema($,Z,Q,W=this.opts.validateSchema){if(Array.isArray($)){for(let G of $)this.addSchema(G,void 0,Q,W);return this}let Y;if(typeof $==="object"){let{schemaId:G}=this.opts;if(Y=$[G],Y!==void 0&&typeof Y!="string")throw Error(`schema ${G} must be string`)}return Z=(0,FZ.normalizeId)(Z||Y),this._checkUnique(Z),this.schemas[Z]=this._addSchema($,Q,Z,W,!0),this}addMetaSchema($,Z,Q=this.opts.validateSchema){return this.addSchema($,Z,!0,Q),this}validateSchema($,Z){if(typeof $=="boolean")return!0;let Q;if(Q=$.$schema,Q!==void 0&&typeof Q!="string")throw Error("$schema must be a string");if(Q=Q||this.opts.defaultMeta||this.defaultMeta(),!Q)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let W=this.validate(Q,$);if(!W&&Z){let Y="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(Y);else throw Error(Y)}return W}getSchema($){let Z;while(typeof(Z=lY.call(this,$))=="string")$=Z;if(Z===void 0){let{schemaId:Q}=this.opts,W=new zZ.SchemaEnv({schema:{},schemaId:Q});if(Z=zZ.resolveSchema.call(this,W,$),!Z)return;this.refs[$]=Z}return Z.validate||this._compileSchemaEnv(Z)}removeSchema($){if($ instanceof RegExp)return this._removeAllSchemas(this.schemas,$),this._removeAllSchemas(this.refs,$),this;switch(typeof $){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let Z=lY.call(this,$);if(typeof Z=="object")this._cache.delete(Z.schema);return delete this.schemas[$],delete this.refs[$],this}case"object":{let Z=$;this._cache.delete(Z);let Q=$[this.opts.schemaId];if(Q)Q=(0,FZ.normalizeId)(Q),delete this.schemas[Q],delete this.refs[Q];return this}default:throw Error("ajv.removeSchema: invalid parameter")}}addVocabulary($){for(let Z of $)this.addKeyword(Z);return this}addKeyword($,Z){let Q;if(typeof $=="string"){if(Q=$,typeof Z=="object")this.logger.warn("these parameters are deprecated, see docs for addKeyword"),Z.keyword=Q}else if(typeof $=="object"&&Z===void 0){if(Z=$,Q=Z.keyword,Array.isArray(Q)&&!Q.length)throw Error("addKeywords: keyword must be string or non-empty array")}else throw Error("invalid addKeywords parameters");if(Rq.call(this,Q,Z),!Z)return(0,R4.eachItem)(Q,(Y)=>E4.call(this,Y)),this;Sq.call(this,Z);let W={...Z,type:(0,g5.getJSONTypes)(Z.type),schemaType:(0,g5.getJSONTypes)(Z.schemaType)};return(0,R4.eachItem)(Q,W.type.length===0?(Y)=>E4.call(this,Y,W):(Y)=>W.type.forEach((G)=>E4.call(this,Y,W,G))),this}getKeyword($){let Z=this.RULES.all[$];return typeof Z=="object"?Z.definition:!!Z}removeKeyword($){let{RULES:Z}=this;delete Z.keywords[$],delete Z.all[$];for(let Q of Z.rules){let W=Q.rules.findIndex((Y)=>Y.keyword===$);if(W>=0)Q.rules.splice(W,1)}return this}addFormat($,Z){if(typeof Z=="string")Z=new RegExp(Z);return this.formats[$]=Z,this}errorsText($=this.errors,{separator:Z=", ",dataVar:Q="data"}={}){if(!$||$.length===0)return"No errors";return $.map((W)=>`${Q}${W.instancePath} ${W.message}`).reduce((W,Y)=>W+Z+Y)}$dataMetaSchema($,Z){let Q=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let W of Z){let Y=W.split("/").slice(1),G=$;for(let X of Y)G=G[X];for(let X in Q){let J=Q[X];if(typeof J!="object")continue;let{$data:K}=J.definition,B=G[X];if(K&&B)G[X]=dY(B)}}return $}_removeAllSchemas($,Z){for(let Q in $){let W=$[Q];if(!Z||Z.test(Q)){if(typeof W=="string")delete $[Q];else if(W&&!W.meta)this._cache.delete(W.schema),delete $[Q]}}}_addSchema($,Z,Q,W=this.opts.validateSchema,Y=this.opts.addUsedSchema){let G,{schemaId:X}=this.opts;if(typeof $=="object")G=$[X];else if(this.opts.jtd)throw Error("schema must be object");else if(typeof $!="boolean")throw Error("schema must be object or boolean");let J=this._cache.get($);if(J!==void 0)return J;Q=(0,FZ.normalizeId)(G||Q);let K=FZ.getSchemaRefs.call(this,$,Q);if(J=new zZ.SchemaEnv({schema:$,schemaId:X,meta:Z,baseId:Q,localRefs:K}),this._cache.set(J.schema,J),Y&&!Q.startsWith("#")){if(Q)this._checkUnique(Q);this.refs[Q]=J}if(W)this.validateSchema($,!0);return J}_checkUnique($){if(this.schemas[$]||this.refs[$])throw Error(`schema with key or id "${$}" already exists`)}_compileSchemaEnv($){if($.meta)this._compileMetaSchema($);else zZ.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let Z=this.opts;this.opts=this._metaOpts;try{zZ.compileSchema.call(this,$)}finally{this.opts=Z}}}h5.ValidationError=zq.default;h5.MissingRefError=pY.default;s0.default=h5;function mY($,Z,Q,W="error"){for(let Y in $){let G=Y;if(G in Z)this.logger[W](`${Q}: option ${Y}. ${$[G]}`)}}function lY($){return $=(0,FZ.normalizeId)($),this.schemas[$]||this.refs[$]}function Mq(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let Z in $)this.addSchema($[Z],Z)}function jq(){for(let $ in this.opts.formats){let Z=this.opts.formats[$];if(Z)this.addFormat($,Z)}}function Pq($){if(Array.isArray($)){this.addVocabulary($);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let Z in $){let Q=$[Z];if(!Q.keyword)Q.keyword=Z;this.addKeyword(Q)}}function wq(){let $={...this.opts};for(let Z of Uq)delete $[Z];return $}var Tq={log(){},warn(){},error(){}};function Iq($){if($===!1)return Tq;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var Eq=/^[a-z_$][a-z0-9_$:-]*$/i;function Rq($,Z){let{RULES:Q}=this;if((0,R4.eachItem)($,(W)=>{if(Q.keywords[W])throw Error(`Keyword ${W} is already defined`);if(!Eq.test(W))throw Error(`Keyword ${W} has invalid name`)}),!Z)return;if(Z.$data&&!(("code"in Z)||("validate"in Z)))throw Error('$data keyword must have "code" or "validate" function')}function E4($,Z,Q){var W;let Y=Z===null||Z===void 0?void 0:Z.post;if(Q&&Y)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=Y?G.post:G.rules.find(({type:K})=>K===Q);if(!X)X={type:Q,rules:[]},G.rules.push(X);if(G.keywords[$]=!0,!Z)return;let J={keyword:$,definition:{...Z,type:(0,g5.getJSONTypes)(Z.type),schemaType:(0,g5.getJSONTypes)(Z.schemaType)}};if(Z.before)Cq.call(this,X,J,Z.before);else X.rules.push(J);G.all[$]=J,(W=Z.implements)===null||W===void 0||W.forEach((K)=>this.addKeyword(K))}function Cq($,Z,Q){let W=$.rules.findIndex((Y)=>Y.keyword===Q);if(W>=0)$.rules.splice(W,0,Z);else $.rules.push(Z),this.logger.warn(`rule ${Q} is not defined`)}function Sq($){let{metaSchema:Z}=$;if(Z===void 0)return;if($.$data&&this.opts.$data)Z=dY(Z);$.validateSchema=this.compile(Z,!0)}var yq={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function dY($){return{anyOf:[$,yq]}}});var aY=M((nY)=>{Object.defineProperty(nY,"__esModule",{value:!0});var kq={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};nY.default=kq});var $G=M((sY)=>{Object.defineProperty(sY,"__esModule",{value:!0});sY.callRef=sY.getValidate=void 0;var fq=BZ(),rY=q0(),K0=b(),H$=t0(),tY=k5(),u5=x(),vq={keyword:"$ref",schemaType:"string",code($){let{gen:Z,schema:Q,it:W}=$,{baseId:Y,schemaEnv:G,validateName:X,opts:J,self:K}=W,{root:B}=G;if((Q==="#"||Q==="#/")&&Y===B.baseId)return V();let z=tY.resolveRef.call(K,B,Y,Q);if(z===void 0)throw new fq.default(W.opts.uriResolver,Y,Q);if(z instanceof tY.SchemaEnv)return F(z);return D(z);function V(){if(G===B)return m5($,X,G,G.$async);let L=Z.scopeValue("root",{ref:B});return m5($,K0._`${L}.validate`,B,B.$async)}function F(L){let U=oY($,L);m5($,U,L,L.$async)}function D(L){let U=Z.scopeValue("schema",J.code.source===!0?{ref:L,code:(0,K0.stringify)(L)}:{ref:L}),q=Z.name("valid"),A=$.subschema({schema:L,dataTypes:[],schemaPath:K0.nil,topSchemaRef:U,errSchemaPath:Q},q);$.mergeEvaluated(A),$.ok(q)}}};function oY($,Z){let{gen:Q}=$;return Z.validate?Q.scopeValue("validate",{ref:Z.validate}):K0._`${Q.scopeValue("wrapper",{ref:Z})}.validate`}sY.getValidate=oY;function m5($,Z,Q,W){let{gen:Y,it:G}=$,{allErrors:X,schemaEnv:J,opts:K}=G,B=K.passContext?H$.default.this:K0.nil;if(W)z();else V();function z(){if(!J.$async)throw Error("async schema referenced by sync schema");let L=Y.let("valid");Y.try(()=>{if(Y.code(K0._`await ${(0,rY.callValidateCode)($,Z,B)}`),D(Z),!X)Y.assign(L,!0)},(U)=>{if(Y.if(K0._`!(${U} instanceof ${G.ValidationError})`,()=>Y.throw(U)),F(U),!X)Y.assign(L,!1)}),$.ok(L)}function V(){$.result((0,rY.callValidateCode)($,Z,B),()=>D(Z),()=>F(Z))}function F(L){let U=K0._`${L}.errors`;Y.assign(H$.default.vErrors,K0._`${H$.default.vErrors} === null ? ${U} : ${H$.default.vErrors}.concat(${U})`),Y.assign(H$.default.errors,K0._`${H$.default.vErrors}.length`)}function D(L){var U;if(!G.opts.unevaluated)return;let q=(U=Q===null||Q===void 0?void 0:Q.validate)===null||U===void 0?void 0:U.evaluated;if(G.props!==!0)if(q&&!q.dynamicProps){if(q.props!==void 0)G.props=u5.mergeEvaluated.props(Y,q.props,G.props)}else{let A=Y.var("props",K0._`${L}.evaluated.props`);G.props=u5.mergeEvaluated.props(Y,A,G.props,K0.Name)}if(G.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)G.items=u5.mergeEvaluated.items(Y,q.items,G.items)}else{let A=Y.var("items",K0._`${L}.evaluated.items`);G.items=u5.mergeEvaluated.items(Y,A,G.items,K0.Name)}}}sY.callRef=m5;sY.default=vq});var QG=M((ZG)=>{Object.defineProperty(ZG,"__esModule",{value:!0});var uq=aY(),mq=$G(),lq=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",uq.default,mq.default];ZG.default=lq});var YG=M((WG)=>{Object.defineProperty(WG,"__esModule",{value:!0});var l5=b(),U1=l5.operators,p5={maximum:{okStr:"<=",ok:U1.LTE,fail:U1.GT},minimum:{okStr:">=",ok:U1.GTE,fail:U1.LT},exclusiveMaximum:{okStr:"<",ok:U1.LT,fail:U1.GTE},exclusiveMinimum:{okStr:">",ok:U1.GT,fail:U1.LTE}},cq={message:({keyword:$,schemaCode:Z})=>l5.str`must be ${p5[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>l5._`{comparison: ${p5[$].okStr}, limit: ${Z}}`},dq={keyword:Object.keys(p5),type:"number",schemaType:"number",$data:!0,error:cq,code($){let{keyword:Z,data:Q,schemaCode:W}=$;$.fail$data(l5._`${Q} ${p5[Z].fail} ${W} || isNaN(${Q})`)}};WG.default=dq});var XG=M((GG)=>{Object.defineProperty(GG,"__esModule",{value:!0});var DZ=b(),nq={message:({schemaCode:$})=>DZ.str`must be multiple of ${$}`,params:({schemaCode:$})=>DZ._`{multipleOf: ${$}}`},aq={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:nq,code($){let{gen:Z,data:Q,schemaCode:W,it:Y}=$,G=Y.opts.multipleOfPrecision,X=Z.let("res"),J=G?DZ._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:DZ._`${X} !== parseInt(${X})`;$.fail$data(DZ._`(${W} === 0 || (${X} = ${Q}/${W}, ${J}))`)}};GG.default=aq});var BG=M((KG)=>{Object.defineProperty(KG,"__esModule",{value:!0});function JG($){let Z=$.length,Q=0,W=0,Y;while(W<Z)if(Q++,Y=$.charCodeAt(W++),Y>=55296&&Y<=56319&&W<Z){if(Y=$.charCodeAt(W),(Y&64512)===56320)W++}return Q}KG.default=JG;JG.code='require("ajv/dist/runtime/ucs2length").default'});var VG=M((HG)=>{Object.defineProperty(HG,"__esModule",{value:!0});var f1=b(),oq=x(),sq=BG(),eq={message({keyword:$,schemaCode:Z}){let Q=$==="maxLength"?"more":"fewer";return f1.str`must NOT have ${Q} than ${Z} characters`},params:({schemaCode:$})=>f1._`{limit: ${$}}`},$A={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:eq,code($){let{keyword:Z,data:Q,schemaCode:W,it:Y}=$,G=Z==="maxLength"?f1.operators.GT:f1.operators.LT,X=Y.opts.unicode===!1?f1._`${Q}.length`:f1._`${(0,oq.useFunc)($.gen,sq.default)}(${Q})`;$.fail$data(f1._`${X} ${G} ${W}`)}};HG.default=$A});var FG=M((zG)=>{Object.defineProperty(zG,"__esModule",{value:!0});var QA=q0(),WA=x(),V$=b(),YA={message:({schemaCode:$})=>V$.str`must match pattern "${$}"`,params:({schemaCode:$})=>V$._`{pattern: ${$}}`},GA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:YA,code($){let{gen:Z,data:Q,$data:W,schema:Y,schemaCode:G,it:X}=$,J=X.opts.unicodeRegExp?"u":"";if(W){let{regExp:K}=X.opts.code,B=K.code==="new RegExp"?V$._`new RegExp`:(0,WA.useFunc)(Z,K),z=Z.let("valid");Z.try(()=>Z.assign(z,V$._`${B}(${G}, ${J}).test(${Q})`),()=>Z.assign(z,!1)),$.fail$data(V$._`!${z}`)}else{let K=(0,QA.usePattern)($,Y);$.fail$data(V$._`!${K}.test(${Q})`)}}};zG.default=GA});var LG=M((DG)=>{Object.defineProperty(DG,"__esModule",{value:!0});var LZ=b(),JA={message({keyword:$,schemaCode:Z}){let Q=$==="maxProperties"?"more":"fewer";return LZ.str`must NOT have ${Q} than ${Z} properties`},params:({schemaCode:$})=>LZ._`{limit: ${$}}`},KA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:JA,code($){let{keyword:Z,data:Q,schemaCode:W}=$,Y=Z==="maxProperties"?LZ.operators.GT:LZ.operators.LT;$.fail$data(LZ._`Object.keys(${Q}).length ${Y} ${W}`)}};DG.default=KA});var qG=M((UG)=>{Object.defineProperty(UG,"__esModule",{value:!0});var UZ=q0(),qZ=b(),HA=x(),VA={message:({params:{missingProperty:$}})=>qZ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>qZ._`{missingProperty: ${$}}`},zA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:VA,code($){let{gen:Z,schema:Q,schemaCode:W,data:Y,$data:G,it:X}=$,{opts:J}=X;if(!G&&Q.length===0)return;let K=Q.length>=J.loopRequired;if(X.allErrors)B();else z();if(J.strictRequired){let D=$.parentSchema.properties,{definedProperties:L}=$.it;for(let U of Q)if((D===null||D===void 0?void 0:D[U])===void 0&&!L.has(U)){let q=X.schemaEnv.baseId+X.errSchemaPath,A=`required property "${U}" is not defined at "${q}" (strictRequired)`;(0,HA.checkStrictMode)(X,A,X.opts.strictRequired)}}function B(){if(K||G)$.block$data(qZ.nil,V);else for(let D of Q)(0,UZ.checkReportMissingProp)($,D)}function z(){let D=Z.let("missing");if(K||G){let L=Z.let("valid",!0);$.block$data(L,()=>F(D,L)),$.ok(L)}else Z.if((0,UZ.checkMissingProp)($,Q,D)),(0,UZ.reportMissingProp)($,D),Z.else()}function V(){Z.forOf("prop",W,(D)=>{$.setParams({missingProperty:D}),Z.if((0,UZ.noPropertyInData)(Z,Y,D,J.ownProperties),()=>$.error())})}function F(D,L){$.setParams({missingProperty:D}),Z.forOf(D,W,()=>{Z.assign(L,(0,UZ.propertyInData)(Z,Y,D,J.ownProperties)),Z.if((0,qZ.not)(L),()=>{$.error(),Z.break()})},qZ.nil)}}};UG.default=zA});var NG=M((AG)=>{Object.defineProperty(AG,"__esModule",{value:!0});var AZ=b(),DA={message({keyword:$,schemaCode:Z}){let Q=$==="maxItems"?"more":"fewer";return AZ.str`must NOT have ${Q} than ${Z} items`},params:({schemaCode:$})=>AZ._`{limit: ${$}}`},LA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:DA,code($){let{keyword:Z,data:Q,schemaCode:W}=$,Y=Z==="maxItems"?AZ.operators.GT:AZ.operators.LT;$.fail$data(AZ._`${Q}.length ${Y} ${W}`)}};AG.default=LA});var c5=M((MG)=>{Object.defineProperty(MG,"__esModule",{value:!0});var OG=z4();OG.code='require("ajv/dist/runtime/equal").default';MG.default=OG});var PG=M((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});var C4=YZ(),e=b(),AA=x(),NA=c5(),OA={message:({params:{i:$,j:Z}})=>e.str`must NOT have duplicate items (items ## ${Z} and ${$} are identical)`,params:({params:{i:$,j:Z}})=>e._`{i: ${$}, j: ${Z}}`},MA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:OA,code($){let{gen:Z,data:Q,$data:W,schema:Y,parentSchema:G,schemaCode:X,it:J}=$;if(!W&&!Y)return;let K=Z.let("valid"),B=G.items?(0,C4.getSchemaTypes)(G.items):[];$.block$data(K,z,e._`${X} === false`),$.ok(K);function z(){let L=Z.let("i",e._`${Q}.length`),U=Z.let("j");$.setParams({i:L,j:U}),Z.assign(K,!0),Z.if(e._`${L} > 1`,()=>(V()?F:D)(L,U))}function V(){return B.length>0&&!B.some((L)=>L==="object"||L==="array")}function F(L,U){let q=Z.name("item"),A=(0,C4.checkDataTypes)(B,q,J.opts.strictNumbers,C4.DataType.Wrong),N=Z.const("indices",e._`{}`);Z.for(e._`;${L}--;`,()=>{if(Z.let(q,e._`${Q}[${L}]`),Z.if(A,e._`continue`),B.length>1)Z.if(e._`typeof ${q} == "string"`,e._`${q} += "_"`);Z.if(e._`typeof ${N}[${q}] == "number"`,()=>{Z.assign(U,e._`${N}[${q}]`),$.error(),Z.assign(K,!1).break()}).code(e._`${N}[${q}] = ${L}`)})}function D(L,U){let q=(0,AA.useFunc)(Z,NA.default),A=Z.name("outer");Z.label(A).for(e._`;${L}--;`,()=>Z.for(e._`${U} = ${L}; ${U}--;`,()=>Z.if(e._`${q}(${Q}[${L}], ${Q}[${U}])`,()=>{$.error(),Z.assign(K,!1).break(A)})))}}};jG.default=MA});var TG=M((wG)=>{Object.defineProperty(wG,"__esModule",{value:!0});var S4=b(),PA=x(),wA=c5(),TA={message:"must be equal to constant",params:({schemaCode:$})=>S4._`{allowedValue: ${$}}`},IA={keyword:"const",$data:!0,error:TA,code($){let{gen:Z,data:Q,$data:W,schemaCode:Y,schema:G}=$;if(W||G&&typeof G=="object")$.fail$data(S4._`!${(0,PA.useFunc)(Z,wA.default)}(${Q}, ${Y})`);else $.fail(S4._`${G} !== ${Q}`)}};wG.default=IA});var EG=M((IG)=>{Object.defineProperty(IG,"__esModule",{value:!0});var NZ=b(),RA=x(),CA=c5(),SA={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>NZ._`{allowedValues: ${$}}`},yA={keyword:"enum",schemaType:"array",$data:!0,error:SA,code($){let{gen:Z,data:Q,$data:W,schema:Y,schemaCode:G,it:X}=$;if(!W&&Y.length===0)throw Error("enum must have non-empty array");let J=Y.length>=X.opts.loopEnum,K,B=()=>K!==null&&K!==void 0?K:K=(0,RA.useFunc)(Z,CA.default),z;if(J||W)z=Z.let("valid"),$.block$data(z,V);else{if(!Array.isArray(Y))throw Error("ajv implementation error");let D=Z.const("vSchema",G);z=(0,NZ.or)(...Y.map((L,U)=>F(D,U)))}$.pass(z);function V(){Z.assign(z,!1),Z.forOf("v",G,(D)=>Z.if(NZ._`${B()}(${Q}, ${D})`,()=>Z.assign(z,!0).break()))}function F(D,L){let U=Y[L];return typeof U==="object"&&U!==null?NZ._`${B()}(${Q}, ${D}[${L}])`:NZ._`${Q} === ${U}`}}};IG.default=yA});var CG=M((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});var _A=YG(),kA=XG(),xA=VG(),fA=FG(),vA=LG(),gA=qG(),hA=NG(),uA=PG(),mA=TG(),lA=EG(),pA=[_A.default,kA.default,xA.default,fA.default,vA.default,gA.default,hA.default,uA.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},mA.default,lA.default];RG.default=pA});var b4=M((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});yG.validateAdditionalItems=void 0;var v1=b(),y4=x(),dA={message:({params:{len:$}})=>v1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>v1._`{limit: ${$}}`},iA={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:dA,code($){let{parentSchema:Z,it:Q}=$,{items:W}=Z;if(!Array.isArray(W)){(0,y4.checkStrictMode)(Q,'"additionalItems" is ignored when "items" is not an array of schemas');return}SG($,W)}};function SG($,Z){let{gen:Q,schema:W,data:Y,keyword:G,it:X}=$;X.items=!0;let J=Q.const("len",v1._`${Y}.length`);if(W===!1)$.setParams({len:Z.length}),$.pass(v1._`${J} <= ${Z.length}`);else if(typeof W=="object"&&!(0,y4.alwaysValidSchema)(X,W)){let B=Q.var("valid",v1._`${J} <= ${Z.length}`);Q.if((0,v1.not)(B),()=>K(B)),$.ok(B)}function K(B){Q.forRange("i",Z.length,J,(z)=>{if($.subschema({keyword:G,dataProp:z,dataPropType:y4.Type.Num},B),!X.allErrors)Q.if((0,v1.not)(B),()=>Q.break())})}}yG.validateAdditionalItems=SG;yG.default=iA});var _4=M((xG)=>{Object.defineProperty(xG,"__esModule",{value:!0});xG.validateTuple=void 0;var _G=b(),d5=x(),aA=q0(),rA={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:Z,it:Q}=$;if(Array.isArray(Z))return kG($,"additionalItems",Z);if(Q.items=!0,(0,d5.alwaysValidSchema)(Q,Z))return;$.ok((0,aA.validateArray)($))}};function kG($,Z,Q=$.schema){let{gen:W,parentSchema:Y,data:G,keyword:X,it:J}=$;if(z(Y),J.opts.unevaluated&&Q.length&&J.items!==!0)J.items=d5.mergeEvaluated.items(W,Q.length,J.items);let K=W.name("valid"),B=W.const("len",_G._`${G}.length`);Q.forEach((V,F)=>{if((0,d5.alwaysValidSchema)(J,V))return;W.if(_G._`${B} > ${F}`,()=>$.subschema({keyword:X,schemaProp:F,dataProp:F},K)),$.ok(K)});function z(V){let{opts:F,errSchemaPath:D}=J,L=Q.length,U=L===V.minItems&&(L===V.maxItems||V[Z]===!1);if(F.strictTuples&&!U){let q=`"${X}" is ${L}-tuple, but minItems or maxItems/${Z} are not specified or different at path "${D}"`;(0,d5.checkStrictMode)(J,q,F.strictTuples)}}}xG.validateTuple=kG;xG.default=rA});var gG=M((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});var oA=_4(),sA={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,oA.validateTuple)($,"items")};vG.default=sA});var mG=M((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});var hG=b(),$N=x(),ZN=q0(),QN=b4(),WN={message:({params:{len:$}})=>hG.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>hG._`{limit: ${$}}`},YN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:WN,code($){let{schema:Z,parentSchema:Q,it:W}=$,{prefixItems:Y}=Q;if(W.items=!0,(0,$N.alwaysValidSchema)(W,Z))return;if(Y)(0,QN.validateAdditionalItems)($,Y);else $.ok((0,ZN.validateArray)($))}};uG.default=YN});var pG=M((lG)=>{Object.defineProperty(lG,"__esModule",{value:!0});var A0=b(),i5=x(),XN={message:({params:{min:$,max:Z}})=>Z===void 0?A0.str`must contain at least ${$} valid item(s)`:A0.str`must contain at least ${$} and no more than ${Z} valid item(s)`,params:({params:{min:$,max:Z}})=>Z===void 0?A0._`{minContains: ${$}}`:A0._`{minContains: ${$}, maxContains: ${Z}}`},JN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:XN,code($){let{gen:Z,schema:Q,parentSchema:W,data:Y,it:G}=$,X,J,{minContains:K,maxContains:B}=W;if(G.opts.next)X=K===void 0?1:K,J=B;else X=1;let z=Z.const("len",A0._`${Y}.length`);if($.setParams({min:X,max:J}),J===void 0&&X===0){(0,i5.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&X>J){(0,i5.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,i5.alwaysValidSchema)(G,Q)){let U=A0._`${z} >= ${X}`;if(J!==void 0)U=A0._`${U} && ${z} <= ${J}`;$.pass(U);return}G.items=!0;let V=Z.name("valid");if(J===void 0&&X===1)D(V,()=>Z.if(V,()=>Z.break()));else if(X===0){if(Z.let(V,!0),J!==void 0)Z.if(A0._`${Y}.length > 0`,F)}else Z.let(V,!1),F();$.result(V,()=>$.reset());function F(){let U=Z.name("_valid"),q=Z.let("count",0);D(U,()=>Z.if(U,()=>L(q)))}function D(U,q){Z.forRange("i",0,z,(A)=>{$.subschema({keyword:"contains",dataProp:A,dataPropType:i5.Type.Num,compositeRule:!0},U),q()})}function L(U){if(Z.code(A0._`${U}++`),J===void 0)Z.if(A0._`${U} >= ${X}`,()=>Z.assign(V,!0).break());else if(Z.if(A0._`${U} > ${J}`,()=>Z.assign(V,!1).break()),X===1)Z.assign(V,!0);else Z.if(A0._`${U} >= ${X}`,()=>Z.assign(V,!0))}}};lG.default=JN});var rG=M((iG)=>{Object.defineProperty(iG,"__esModule",{value:!0});iG.validateSchemaDeps=iG.validatePropertyDeps=iG.error=void 0;var k4=b(),BN=x(),OZ=q0();iG.error={message:({params:{property:$,depsCount:Z,deps:Q}})=>{let W=Z===1?"property":"properties";return k4.str`must have ${W} ${Q} when property ${$} is present`},params:({params:{property:$,depsCount:Z,deps:Q,missingProperty:W}})=>k4._`{property: ${$},
7
+ missingProperty: ${W},
8
8
  depsCount: ${Z},
9
- deps: ${W}}`};var Pq={keyword:"dependencies",type:"object",schemaType:"object",error:wG.error,code($){let[Z,W]=wq($);jG($,Z),PG($,W)}};function wq({schema:$}){let Z={},W={};for(let Q in $){if(Q==="__proto__")continue;let Y=Array.isArray($[Q])?Z:W;Y[Q]=$[Q]}return[Z,W]}function jG($,Z=$.schema){let{gen:W,data:Q,it:Y}=$;if(Object.keys(Z).length===0)return;let G=W.let("missing");for(let X in Z){let J=Z[X];if(J.length===0)continue;let K=(0,KZ.propertyInData)(W,Q,X,Y.opts.ownProperties);if($.setParams({property:X,depsCount:J.length,deps:J.join(", ")}),Y.allErrors)W.if(K,()=>{for(let H of J)(0,KZ.checkReportMissingProp)($,H)});else W.if(UW._`${K} && (${(0,KZ.checkMissingProp)($,J,G)})`),(0,KZ.reportMissingProp)($,G),W.else()}}wG.validatePropertyDeps=jG;function PG($,Z=$.schema){let{gen:W,data:Q,keyword:Y,it:G}=$,X=W.name("valid");for(let J in Z){if((0,jq.alwaysValidSchema)(G,Z[J]))continue;W.if((0,KZ.propertyInData)(W,Q,J,G.opts.ownProperties),()=>{let K=$.subschema({keyword:Y,schemaProp:J},X);$.mergeValidEvaluated(K,X)},()=>W.var(X,!0)),$.ok(X)}}wG.validateSchemaDeps=PG;wG.default=Pq});var CG=M((SG)=>{Object.defineProperty(SG,"__esModule",{value:!0});var RG=y(),Eq=k(),Rq={message:"property name must be valid",params:({params:$})=>RG._`{propertyName: ${$.propertyName}}`},Sq={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Rq,code($){let{gen:Z,schema:W,data:Q,it:Y}=$;if((0,Eq.alwaysValidSchema)(Y,W))return;let G=Z.name("valid");Z.forIn("key",Q,(X)=>{$.setParams({propertyName:X}),$.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),Z.if((0,RG.not)(G),()=>{if($.error(!0),!Y.allErrors)Z.break()})}),$.ok(G)}};SG.default=Sq});var AW=M((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});var k5=F0(),P0=y(),yq=d0(),_5=k(),bq={message:"must NOT have additional properties",params:({params:$})=>P0._`{additionalProperty: ${$.additionalProperty}}`},kq={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:bq,code($){let{gen:Z,schema:W,parentSchema:Q,data:Y,errsCount:G,it:X}=$;if(!G)throw Error("ajv implementation error");let{allErrors:J,opts:K}=X;if(X.props=!0,K.removeAdditional!=="all"&&(0,_5.alwaysValidSchema)(X,W))return;let H=(0,k5.allSchemaProperties)(Q.properties),V=(0,k5.allSchemaProperties)(Q.patternProperties);z(),$.ok(P0._`${G} === ${yq.default.errors}`);function z(){Z.forIn("key",Y,(A)=>{if(!H.length&&!V.length)L(A);else Z.if(F(A),()=>L(A))})}function F(A){let q;if(H.length>8){let O=(0,_5.schemaRefOrVal)(X,Q.properties,"properties");q=(0,k5.isOwnProperty)(Z,O,A)}else if(H.length)q=(0,P0.or)(...H.map((O)=>P0._`${A} === ${O}`));else q=P0.nil;if(V.length)q=(0,P0.or)(q,...V.map((O)=>P0._`${(0,k5.usePattern)($,O)}.test(${A})`));return(0,P0.not)(q)}function D(A){Z.code(P0._`delete ${Y}[${A}]`)}function L(A){if(K.removeAdditional==="all"||K.removeAdditional&&W===!1){D(A);return}if(W===!1){if($.setParams({additionalProperty:A}),$.error(),!J)Z.break();return}if(typeof W=="object"&&!(0,_5.alwaysValidSchema)(X,W)){let q=Z.name("valid");if(K.removeAdditional==="failing")U(A,q,!1),Z.if((0,P0.not)(q),()=>{$.reset(),D(A)});else if(U(A,q),!J)Z.if((0,P0.not)(q),()=>Z.break())}}function U(A,q,O){let j={keyword:"additionalProperties",dataProp:A,dataPropType:_5.Type.Str};if(O===!1)Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(j,q)}}};yG.default=kq});var xG=M((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});var xq=t$(),bG=F0(),qW=k(),kG=AW(),fq={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Z,schema:W,parentSchema:Q,data:Y,it:G}=$;if(G.opts.removeAdditional==="all"&&Q.additionalProperties===void 0)kG.default.code(new xq.KeywordCxt(G,kG.default,"additionalProperties"));let X=(0,bG.allSchemaProperties)(W);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=qW.mergeEvaluated.props(Z,(0,qW.toHash)(X),G.props);let J=X.filter((z)=>!(0,qW.alwaysValidSchema)(G,W[z]));if(J.length===0)return;let K=Z.name("valid");for(let z of J){if(H(z))V(z);else{if(Z.if((0,bG.propertyInData)(Z,Y,z,G.opts.ownProperties)),V(z),!G.allErrors)Z.else().var(K,!0);Z.endIf()}$.it.definedProperties.add(z),$.ok(K)}function H(z){return G.opts.useDefaults&&!G.compositeRule&&W[z].default!==void 0}function V(z){$.subschema({keyword:"properties",schemaProp:z,dataProp:z},K)}}};_G.default=fq});var uG=M((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});var fG=F0(),x5=y(),vG=k(),gG=k(),gq={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Z,schema:W,data:Q,parentSchema:Y,it:G}=$,{opts:X}=G,J=(0,fG.allSchemaProperties)(W),K=J.filter((U)=>(0,vG.alwaysValidSchema)(G,W[U]));if(J.length===0||K.length===J.length&&(!G.opts.unevaluated||G.props===!0))return;let H=X.strictSchema&&!X.allowMatchingProperties&&Y.properties,V=Z.name("valid");if(G.props!==!0&&!(G.props instanceof x5.Name))G.props=(0,gG.evaluatedPropsToName)(Z,G.props);let{props:z}=G;F();function F(){for(let U of J){if(H)D(U);if(G.allErrors)L(U);else Z.var(V,!0),L(U),Z.if(V)}}function D(U){for(let A in H)if(new RegExp(U).test(A))(0,vG.checkStrictMode)(G,`property ${A} matches pattern ${U} (use allowMatchingProperties)`)}function L(U){Z.forIn("key",Q,(A)=>{Z.if(x5._`${(0,fG.usePattern)($,U)}.test(${A})`,()=>{let q=K.includes(U);if(!q)$.subschema({keyword:"patternProperties",schemaProp:U,dataProp:A,dataPropType:gG.Type.Str},V);if(G.opts.unevaluated&&z!==!0)Z.assign(x5._`${z}[${A}]`,!0);else if(!q&&!G.allErrors)Z.if((0,x5.not)(V),()=>Z.break())})})}}};hG.default=gq});var lG=M((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var uq=k(),mq={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:Z,schema:W,it:Q}=$;if((0,uq.alwaysValidSchema)(Q,W)){$.fail();return}let Y=Z.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Y),$.failResult(Y,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};mG.default=mq});var cG=M((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var pq=F0(),cq={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:pq.validateUnion,error:{message:"must match a schema in anyOf"}};pG.default=cq});var iG=M((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});var f5=y(),iq=k(),nq={message:"must match exactly one schema in oneOf",params:({params:$})=>f5._`{passingSchemas: ${$.passing}}`},aq={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:nq,code($){let{gen:Z,schema:W,parentSchema:Q,it:Y}=$;if(!Array.isArray(W))throw Error("ajv implementation error");if(Y.opts.discriminator&&Q.discriminator)return;let G=W,X=Z.let("valid",!1),J=Z.let("passing",null),K=Z.name("_valid");$.setParams({passing:J}),Z.block(H),$.result(X,()=>$.reset(),()=>$.error(!0));function H(){G.forEach((V,z)=>{let F;if((0,iq.alwaysValidSchema)(Y,V))Z.var(K,!0);else F=$.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},K);if(z>0)Z.if(f5._`${K} && ${X}`).assign(X,!1).assign(J,f5._`[${J}, ${z}]`).else();Z.if(K,()=>{if(Z.assign(X,!0),Z.assign(J,z),F)$.mergeEvaluated(F,f5.Name)})})}}};dG.default=aq});var aG=M((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});var tq=k(),oq={keyword:"allOf",schemaType:"array",code($){let{gen:Z,schema:W,it:Q}=$;if(!Array.isArray(W))throw Error("ajv implementation error");let Y=Z.name("valid");W.forEach((G,X)=>{if((0,tq.alwaysValidSchema)(Q,G))return;let J=$.subschema({keyword:"allOf",schemaProp:X},Y);$.ok(Y),$.mergeEvaluated(J)})}};nG.default=oq});var sG=M((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});var v5=y(),tG=k(),eq={message:({params:$})=>v5.str`must match "${$.ifClause}" schema`,params:({params:$})=>v5._`{failingKeyword: ${$.ifClause}}`},$O={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:eq,code($){let{gen:Z,parentSchema:W,it:Q}=$;if(W.then===void 0&&W.else===void 0)(0,tG.checkStrictMode)(Q,'"if" without "then" and "else" is ignored');let Y=rG(Q,"then"),G=rG(Q,"else");if(!Y&&!G)return;let X=Z.let("valid",!0),J=Z.name("_valid");if(K(),$.reset(),Y&&G){let V=Z.let("ifClause");$.setParams({ifClause:V}),Z.if(J,H("then",V),H("else",V))}else if(Y)Z.if(J,H("then"));else Z.if((0,v5.not)(J),H("else"));$.pass(X,()=>$.error(!0));function K(){let V=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(V)}function H(V,z){return()=>{let F=$.subschema({keyword:V},J);if(Z.assign(X,J),$.mergeValidEvaluated(F,X),z)Z.assign(z,v5._`${V}`);else $.setParams({ifClause:V})}}}};function rG($,Z){let W=$.schema[Z];return W!==void 0&&!(0,tG.alwaysValidSchema)($,W)}oG.default=$O});var $X=M((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var WO=k(),QO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:Z,it:W}){if(Z.if===void 0)(0,WO.checkStrictMode)(W,`"${$}" without "if" is ignored`)}};eG.default=QO});var WX=M((ZX)=>{Object.defineProperty(ZX,"__esModule",{value:!0});var GO=DW(),XO=UG(),JO=LW(),KO=OG(),BO=MG(),HO=EG(),zO=CG(),VO=AW(),FO=xG(),DO=uG(),LO=lG(),UO=cG(),AO=iG(),qO=aG(),OO=sG(),NO=$X();function MO($=!1){let Z=[LO.default,UO.default,AO.default,qO.default,OO.default,NO.default,zO.default,VO.default,HO.default,FO.default,DO.default];if($)Z.push(XO.default,KO.default);else Z.push(GO.default,JO.default);return Z.push(BO.default),Z}ZX.default=MO});var YX=M((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});var p=y(),PO={message:({schemaCode:$})=>p.str`must match format "${$}"`,params:({schemaCode:$})=>p._`{format: ${$}}`},wO={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:PO,code($,Z){let{gen:W,data:Q,$data:Y,schema:G,schemaCode:X,it:J}=$,{opts:K,errSchemaPath:H,schemaEnv:V,self:z}=J;if(!K.validateFormats)return;if(Y)F();else D();function F(){let L=W.scopeValue("formats",{ref:z.formats,code:K.code.formats}),U=W.const("fDef",p._`${L}[${X}]`),A=W.let("fType"),q=W.let("format");W.if(p._`typeof ${U} == "object" && !(${U} instanceof RegExp)`,()=>W.assign(A,p._`${U}.type || "string"`).assign(q,p._`${U}.validate`),()=>W.assign(A,p._`"string"`).assign(q,U)),$.fail$data((0,p.or)(O(),j()));function O(){if(K.strictSchema===!1)return p.nil;return p._`${X} && !${q}`}function j(){let P=V.$async?p._`(${U}.async ? await ${q}(${Q}) : ${q}(${Q}))`:p._`${q}(${Q})`,N=p._`(typeof ${q} == "function" ? ${P} : ${q}.test(${Q}))`;return p._`${q} && ${q} !== true && ${A} === ${Z} && !${N}`}}function D(){let L=z.formats[G];if(!L){O();return}if(L===!0)return;let[U,A,q]=j(L);if(U===Z)$.pass(P());function O(){if(K.strictSchema===!1){z.logger.warn(N());return}throw Error(N());function N(){return`unknown format "${G}" ignored in schema at path "${H}"`}}function j(N){let x=N instanceof RegExp?(0,p.regexpCode)(N):K.code.formats?p._`${K.code.formats}${(0,p.getProperty)(G)}`:void 0,m=W.scopeValue("formats",{key:G,ref:N,code:x});if(typeof N=="object"&&!(N instanceof RegExp))return[N.type||"string",N.validate,p._`${m}.validate`];return["string",N,m]}function P(){if(typeof L=="object"&&!(L instanceof RegExp)&&L.async){if(!V.$async)throw Error("async format in sync schema");return p._`await ${q}(${Q})`}return typeof A=="function"?p._`${q}(${Q})`:p._`${q}.test(${Q})`}}}};QX.default=wO});var XX=M((GX)=>{Object.defineProperty(GX,"__esModule",{value:!0});var IO=YX(),EO=[IO.default];GX.default=EO});var BX=M((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});JX.contentVocabulary=JX.metadataVocabulary=void 0;JX.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];JX.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var VX=M((zX)=>{Object.defineProperty(zX,"__esModule",{value:!0});var CO=_Y(),yO=JG(),bO=WX(),kO=XX(),HX=BX(),_O=[CO.default,yO.default,(0,bO.default)(),kO.default,HX.metadataVocabulary,HX.contentVocabulary];zX.default=_O});var UX=M((DX)=>{Object.defineProperty(DX,"__esModule",{value:!0});DX.DiscrError=void 0;var FX;(function($){$.Tag="tag",$.Mapping="mapping"})(FX||(DX.DiscrError=FX={}))});var OX=M((qX)=>{Object.defineProperty(qX,"__esModule",{value:!0});var Y$=y(),OW=UX(),AX=N5(),fO=o$(),vO=k(),gO={message:({params:{discrError:$,tagName:Z}})=>$===OW.DiscrError.Tag?`tag "${Z}" must be string`:`value of tag "${Z}" must be in oneOf`,params:({params:{discrError:$,tag:Z,tagName:W}})=>Y$._`{error: ${$}, tag: ${W}, tagValue: ${Z}}`},hO={keyword:"discriminator",type:"object",schemaType:"object",error:gO,code($){let{gen:Z,data:W,schema:Q,parentSchema:Y,it:G}=$,{oneOf:X}=Y;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=Q.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(Q.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let K=Z.let("valid",!1),H=Z.const("tag",Y$._`${W}${(0,Y$.getProperty)(J)}`);Z.if(Y$._`typeof ${H} == "string"`,()=>V(),()=>$.error(!1,{discrError:OW.DiscrError.Tag,tag:H,tagName:J})),$.ok(K);function V(){let D=F();Z.if(!1);for(let L in D)Z.elseIf(Y$._`${H} === ${L}`),Z.assign(K,z(D[L]));Z.else(),$.error(!1,{discrError:OW.DiscrError.Mapping,tag:H,tagName:J}),Z.endIf()}function z(D){let L=Z.name("valid"),U=$.subschema({keyword:"oneOf",schemaProp:D},L);return $.mergeEvaluated(U,Y$.Name),L}function F(){var D;let L={},U=q(Y),A=!0;for(let P=0;P<X.length;P++){let N=X[P];if((N===null||N===void 0?void 0:N.$ref)&&!(0,vO.schemaHasRulesButRef)(N,G.self.RULES)){let m=N.$ref;if(N=AX.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,m),N instanceof AX.SchemaEnv)N=N.schema;if(N===void 0)throw new fO.default(G.opts.uriResolver,G.baseId,m)}let x=(D=N===null||N===void 0?void 0:N.properties)===null||D===void 0?void 0:D[J];if(typeof x!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);A=A&&(U||q(N)),O(x,P)}if(!A)throw Error(`discriminator: "${J}" must be required`);return L;function q({required:P}){return Array.isArray(P)&&P.includes(J)}function O(P,N){if(P.const)j(P.const,N);else if(P.enum)for(let x of P.enum)j(x,N);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function j(P,N){if(typeof P!="string"||P in L)throw Error(`discriminator: "${J}" values must be unique strings`);L[P]=N}}}};qX.default=hO});var NX=M((EC,mO)=>{mO.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 MW=M((G0,NW)=>{Object.defineProperty(G0,"__esModule",{value:!0});G0.MissingRefError=G0.ValidationError=G0.CodeGen=G0.Name=G0.nil=G0.stringify=G0.str=G0._=G0.KeywordCxt=G0.Ajv=void 0;var lO=wY(),pO=VX(),cO=OX(),MX=NX(),dO=["/properties"],g5="http://json-schema.org/draft-07/schema";class BZ extends lO.default{_addVocabularies(){if(super._addVocabularies(),pO.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(cO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(MX,dO):MX;this.addMetaSchema($,g5,!1),this.refs["http://json-schema.org/schema"]=g5}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(g5)?g5:void 0)}}G0.Ajv=BZ;NW.exports=G0=BZ;NW.exports.Ajv=BZ;Object.defineProperty(G0,"__esModule",{value:!0});G0.default=BZ;var iO=t$();Object.defineProperty(G0,"KeywordCxt",{enumerable:!0,get:function(){return iO.KeywordCxt}});var G$=y();Object.defineProperty(G0,"_",{enumerable:!0,get:function(){return G$._}});Object.defineProperty(G0,"str",{enumerable:!0,get:function(){return G$.str}});Object.defineProperty(G0,"stringify",{enumerable:!0,get:function(){return G$.stringify}});Object.defineProperty(G0,"nil",{enumerable:!0,get:function(){return G$.nil}});Object.defineProperty(G0,"Name",{enumerable:!0,get:function(){return G$.Name}});Object.defineProperty(G0,"CodeGen",{enumerable:!0,get:function(){return G$.CodeGen}});var nO=q5();Object.defineProperty(G0,"ValidationError",{enumerable:!0,get:function(){return nO.default}});var aO=o$();Object.defineProperty(G0,"MissingRefError",{enumerable:!0,get:function(){return aO.default}})});var yX=M((SX)=>{Object.defineProperty(SX,"__esModule",{value:!0});SX.formatNames=SX.fastFormats=SX.fullFormats=void 0;function b0($,Z){return{validate:$,compare:Z}}SX.fullFormats={date:b0(TX,TW),time:b0(PW(!0),IW),"date-time":b0(jX(!0),EX),"iso-time":b0(PW(),IX),"iso-date-time":b0(jX(),RX),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:WN,"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:BN,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:QN,int32:{type:"number",validate:XN},int64:{type:"number",validate:JN},float:{type:"number",validate:wX},double:{type:"number",validate:wX},password:!0,binary:!0};SX.fastFormats={...SX.fullFormats,date:b0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,TW),time:b0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,IW),"date-time":b0(/^\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,EX),"iso-time":b0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,IX),"iso-date-time":b0(/^\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,RX),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};SX.formatNames=Object.keys(SX.fullFormats);function oO($){return $%4===0&&($%100!==0||$%400===0)}var sO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function TX($){let Z=sO.exec($);if(!Z)return!1;let W=+Z[1],Q=+Z[2],Y=+Z[3];return Q>=1&&Q<=12&&Y>=1&&Y<=(Q===2&&oO(W)?29:eO[Q])}function TW($,Z){if(!($&&Z))return;if($>Z)return 1;if($<Z)return-1;return 0}var jW=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function PW($){return function(W){let Q=jW.exec(W);if(!Q)return!1;let Y=+Q[1],G=+Q[2],X=+Q[3],J=Q[4],K=Q[5]==="-"?-1:1,H=+(Q[6]||0),V=+(Q[7]||0);if(H>23||V>59||$&&!J)return!1;if(Y<=23&&G<=59&&X<60)return!0;let z=G-V*K,F=Y-H*K-(z<0?1:0);return(F===23||F===-1)&&(z===59||z===-1)&&X<61}}function IW($,Z){if(!($&&Z))return;let W=new Date("2020-01-01T"+$).valueOf(),Q=new Date("2020-01-01T"+Z).valueOf();if(!(W&&Q))return;return W-Q}function IX($,Z){if(!($&&Z))return;let W=jW.exec($),Q=jW.exec(Z);if(!(W&&Q))return;if($=W[1]+W[2]+W[3],Z=Q[1]+Q[2]+Q[3],$>Z)return 1;if($<Z)return-1;return 0}var wW=/t|\s/i;function jX($){let Z=PW($);return function(Q){let Y=Q.split(wW);return Y.length===2&&TX(Y[0])&&Z(Y[1])}}function EX($,Z){if(!($&&Z))return;let W=new Date($).valueOf(),Q=new Date(Z).valueOf();if(!(W&&Q))return;return W-Q}function RX($,Z){if(!($&&Z))return;let[W,Q]=$.split(wW),[Y,G]=Z.split(wW),X=TW(W,Y);if(X===void 0)return;return X||IW(Q,G)}var $N=/\/|:/,ZN=/^(?:[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 WN($){return $N.test($)&&ZN.test($)}var PX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function QN($){return PX.lastIndex=0,PX.test($)}var YN=-2147483648,GN=2147483647;function XN($){return Number.isInteger($)&&$<=GN&&$>=YN}function JN($){return Number.isInteger($)}function wX(){return!0}var KN=/[^\\]\\Z/;function BN($){if(KN.test($))return!1;try{return new RegExp($),!0}catch(Z){return!1}}});var kX=M((bX)=>{Object.defineProperty(bX,"__esModule",{value:!0});bX.formatLimitDefinition=void 0;var zN=MW(),w0=y(),z1=w0.operators,h5={formatMaximum:{okStr:"<=",ok:z1.LTE,fail:z1.GT},formatMinimum:{okStr:">=",ok:z1.GTE,fail:z1.LT},formatExclusiveMaximum:{okStr:"<",ok:z1.LT,fail:z1.GTE},formatExclusiveMinimum:{okStr:">",ok:z1.GT,fail:z1.LTE}},VN={message:({keyword:$,schemaCode:Z})=>w0.str`should be ${h5[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>w0._`{comparison: ${h5[$].okStr}, limit: ${Z}}`};bX.formatLimitDefinition={keyword:Object.keys(h5),type:"string",schemaType:"string",$data:!0,error:VN,code($){let{gen:Z,data:W,schemaCode:Q,keyword:Y,it:G}=$,{opts:X,self:J}=G;if(!X.validateFormats)return;let K=new zN.KeywordCxt(G,J.RULES.all.format.definition,"format");if(K.$data)H();else V();function H(){let F=Z.scopeValue("formats",{ref:J.formats,code:X.code.formats}),D=Z.const("fmt",w0._`${F}[${K.schemaCode}]`);$.fail$data((0,w0.or)(w0._`typeof ${D} != "object"`,w0._`${D} instanceof RegExp`,w0._`typeof ${D}.compare != "function"`,z(D)))}function V(){let F=K.schema,D=J.formats[F];if(!D||D===!0)return;if(typeof D!="object"||D instanceof RegExp||typeof D.compare!="function")throw Error(`"${Y}": format "${F}" does not define "compare" function`);let L=Z.scopeValue("formats",{key:F,ref:D,code:X.code.formats?w0._`${X.code.formats}${(0,w0.getProperty)(F)}`:void 0});$.fail$data(z(L))}function z(F){return w0._`${F}.compare(${W}, ${Q}) ${h5[Y].fail} 0`}},dependencies:["format"]};var FN=($)=>{return $.addKeyword(bX.formatLimitDefinition),$};bX.default=FN});var vX=M((HZ,fX)=>{Object.defineProperty(HZ,"__esModule",{value:!0});var X$=yX(),LN=kX(),SW=y(),_X=new SW.Name("fullFormats"),UN=new SW.Name("fastFormats"),CW=($,Z={keywords:!0})=>{if(Array.isArray(Z))return xX($,Z,X$.fullFormats,_X),$;let[W,Q]=Z.mode==="fast"?[X$.fastFormats,UN]:[X$.fullFormats,_X],Y=Z.formats||X$.formatNames;if(xX($,Y,W,Q),Z.keywords)(0,LN.default)($);return $};CW.get=($,Z="full")=>{let Q=(Z==="fast"?X$.fastFormats:X$.fullFormats)[$];if(!Q)throw Error(`Unknown format "${$}"`);return Q};function xX($,Z,W,Q){var Y,G;(Y=(G=$.opts.code).formats)!==null&&Y!==void 0||(G.formats=SW._`require("ajv-formats/dist/formats").${Q}`);for(let X of Z)$.addFormat(X,W[X])}fX.exports=HZ=CW;Object.defineProperty(HZ,"__esModule",{value:!0});HZ.default=CW});var iX=M((rC,dX)=>{dX.exports=cX;cX.sync=NN;var lX=a0("fs");function ON($,Z){var W=Z.pathExt!==void 0?Z.pathExt:process.env.PATHEXT;if(!W)return!0;if(W=W.split(";"),W.indexOf("")!==-1)return!0;for(var Q=0;Q<W.length;Q++){var Y=W[Q].toLowerCase();if(Y&&$.substr(-Y.length).toLowerCase()===Y)return!0}return!1}function pX($,Z,W){if(!$.isSymbolicLink()&&!$.isFile())return!1;return ON(Z,W)}function cX($,Z,W){lX.stat($,function(Q,Y){W(Q,Q?!1:pX(Y,$,Z))})}function NN($,Z){return pX(lX.statSync($),$,Z)}});var oX=M((tC,tX)=>{tX.exports=aX;aX.sync=MN;var nX=a0("fs");function aX($,Z,W){nX.stat($,function(Q,Y){W(Q,Q?!1:rX(Y,Z))})}function MN($,Z){return rX(nX.statSync($),Z)}function rX($,Z){return $.isFile()&&jN($,Z)}function jN($,Z){var{mode:W,uid:Q,gid:Y}=$,G=Z.uid!==void 0?Z.uid:process.getuid&&process.getuid(),X=Z.gid!==void 0?Z.gid:process.getgid&&process.getgid(),J=parseInt("100",8),K=parseInt("010",8),H=parseInt("001",8),V=J|K,z=W&H||W&K&&Y===X||W&J&&Q===G||W&V&&G===0;return z}});var eX=M((sC,sX)=>{var oC=a0("fs"),m5;if(process.platform==="win32"||global.TESTING_WINDOWS)m5=iX();else m5=oX();sX.exports=_W;_W.sync=PN;function _W($,Z,W){if(typeof Z==="function")W=Z,Z={};if(!W){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(Q,Y){_W($,Z||{},function(G,X){if(G)Y(G);else Q(X)})})}m5($,Z||{},function(Q,Y){if(Q){if(Q.code==="EACCES"||Z&&Z.ignoreErrors)Q=null,Y=!1}W(Q,Y)})}function PN($,Z){try{return m5.sync($,Z||{})}catch(W){if(Z&&Z.ignoreErrors||W.code==="EACCES")return!1;else throw W}}});var XJ=M((eC,GJ)=>{var J$=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",$J=a0("path"),wN=J$?";":":",ZJ=eX(),WJ=($)=>Object.assign(Error(`not found: ${$}`),{code:"ENOENT"}),QJ=($,Z)=>{let W=Z.colon||wN,Q=$.match(/\//)||J$&&$.match(/\\/)?[""]:[...J$?[process.cwd()]:[],...(Z.path||process.env.PATH||"").split(W)],Y=J$?Z.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",G=J$?Y.split(W):[""];if(J$){if($.indexOf(".")!==-1&&G[0]!=="")G.unshift("")}return{pathEnv:Q,pathExt:G,pathExtExe:Y}},YJ=($,Z,W)=>{if(typeof Z==="function")W=Z,Z={};if(!Z)Z={};let{pathEnv:Q,pathExt:Y,pathExtExe:G}=QJ($,Z),X=[],J=(H)=>new Promise((V,z)=>{if(H===Q.length)return Z.all&&X.length?V(X):z(WJ($));let F=Q[H],D=/^".*"$/.test(F)?F.slice(1,-1):F,L=$J.join(D,$),U=!D&&/^\.[\\\/]/.test($)?$.slice(0,2)+L:L;V(K(U,H,0))}),K=(H,V,z)=>new Promise((F,D)=>{if(z===Y.length)return F(J(V+1));let L=Y[z];ZJ(H+L,{pathExt:G},(U,A)=>{if(!U&&A)if(Z.all)X.push(H+L);else return F(H+L);return F(K(H,V,z+1))})});return W?J(0).then((H)=>W(null,H),W):J(0)},TN=($,Z)=>{Z=Z||{};let{pathEnv:W,pathExt:Q,pathExtExe:Y}=QJ($,Z),G=[];for(let X=0;X<W.length;X++){let J=W[X],K=/^".*"$/.test(J)?J.slice(1,-1):J,H=$J.join(K,$),V=!K&&/^\.[\\\/]/.test($)?$.slice(0,2)+H:H;for(let z=0;z<Q.length;z++){let F=V+Q[z];try{if(ZJ.sync(F,{pathExt:Y}))if(Z.all)G.push(F);else return F}catch(D){}}}if(Z.all&&G.length)return G;if(Z.nothrow)return null;throw WJ($)};GJ.exports=YJ;YJ.sync=TN});var KJ=M(($2,xW)=>{var JJ=($={})=>{let Z=$.env||process.env;if(($.platform||process.platform)!=="win32")return"PATH";return Object.keys(Z).reverse().find((Q)=>Q.toUpperCase()==="PATH")||"Path"};xW.exports=JJ;xW.exports.default=JJ});var VJ=M((Z2,zJ)=>{var BJ=a0("path"),IN=XJ(),EN=KJ();function HJ($,Z){let W=$.options.env||process.env,Q=process.cwd(),Y=$.options.cwd!=null,G=Y&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir($.options.cwd)}catch(J){}let X;try{X=IN.sync($.command,{path:W[EN({env:W})],pathExt:Z?BJ.delimiter:void 0})}catch(J){}finally{if(G)process.chdir(Q)}if(X)X=BJ.resolve(Y?$.options.cwd:"",X);return X}function RN($){return HJ($)||HJ($,!0)}zJ.exports=RN});var FJ=M((yN,vW)=>{var fW=/([()\][%!^"`<>&|;, *?])/g;function SN($){return $=$.replace(fW,"^$1"),$}function CN($,Z){if($=`${$}`,$=$.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),$=$.replace(/(?=(\\+?)?)\1$/,"$1$1"),$=`"${$}"`,$=$.replace(fW,"^$1"),Z)$=$.replace(fW,"^$1");return $}yN.command=SN;yN.argument=CN});var LJ=M((W2,DJ)=>{DJ.exports=/^#!(.*)/});var AJ=M((Q2,UJ)=>{var _N=LJ();UJ.exports=($="")=>{let Z=$.match(_N);if(!Z)return null;let[W,Q]=Z[0].replace(/#! ?/,"").split(" "),Y=W.split("/").pop();if(Y==="env")return Q;return Q?`${Y} ${Q}`:Y}});var OJ=M((Y2,qJ)=>{var gW=a0("fs"),xN=AJ();function fN($){let W=Buffer.alloc(150),Q;try{Q=gW.openSync($,"r"),gW.readSync(Q,W,0,150,0),gW.closeSync(Q)}catch(Y){}return xN(W.toString())}qJ.exports=fN});var PJ=M((G2,jJ)=>{var vN=a0("path"),NJ=VJ(),MJ=FJ(),gN=OJ(),hN=process.platform==="win32",uN=/\.(?:com|exe)$/i,mN=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function lN($){$.file=NJ($);let Z=$.file&&gN($.file);if(Z)return $.args.unshift($.file),$.command=Z,NJ($);return $.file}function pN($){if(!hN)return $;let Z=lN($),W=!uN.test(Z);if($.options.forceShell||W){let Q=mN.test(Z);$.command=vN.normalize($.command),$.command=MJ.command($.command),$.args=$.args.map((G)=>MJ.argument(G,Q));let Y=[$.command].concat($.args).join(" ");$.args=["/d","/s","/c",`"${Y}"`],$.command=process.env.comspec||"cmd.exe",$.options.windowsVerbatimArguments=!0}return $}function cN($,Z,W){if(Z&&!Array.isArray(Z))W=Z,Z=null;Z=Z?Z.slice(0):[],W=Object.assign({},W);let Q={command:$,args:Z,options:W,file:void 0,original:{command:$,args:Z}};return W.shell?Q:pN(Q)}jJ.exports=cN});var IJ=M((X2,TJ)=>{var hW=process.platform==="win32";function uW($,Z){return Object.assign(Error(`${Z} ${$.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Z} ${$.command}`,path:$.command,spawnargs:$.args})}function dN($,Z){if(!hW)return;let W=$.emit;$.emit=function(Q,Y){if(Q==="exit"){let G=wJ(Y,Z);if(G)return W.call($,"error",G)}return W.apply($,arguments)}}function wJ($,Z){if(hW&&$===1&&!Z.file)return uW(Z.original,"spawn");return null}function iN($,Z){if(hW&&$===1&&!Z.file)return uW(Z.original,"spawnSync");return null}TJ.exports={hookChildProcess:dN,verifyENOENT:wJ,verifyENOENTSync:iN,notFoundError:uW}});var SJ=M((J2,K$)=>{var EJ=a0("child_process"),mW=PJ(),lW=IJ();function RJ($,Z,W){let Q=mW($,Z,W),Y=EJ.spawn(Q.command,Q.args,Q.options);return lW.hookChildProcess(Y,Q),Y}function nN($,Z,W){let Q=mW($,Z,W),Y=EJ.spawnSync(Q.command,Q.args,Q.options);return Y.error=Y.error||lW.verifyENOENTSync(Y.status,Q),Y}K$.exports=RJ;K$.exports.spawn=RJ;K$.exports.sync=nN;K$.exports._parse=mW;K$.exports._enoent=lW});import{readFile as cM}from"fs/promises";import{homedir as dM}from"os";import{join as iM,resolve as GK}from"path";class UZ{done=[];undone=[];record($){this.done.push($),this.undone=[]}get canUndo(){return this.done.length>0}get canRedo(){return this.undone.length>0}peekUndo(){return this.done[this.done.length-1]}commitUndo($,Z){if(this.peekUndo()?.id!==$.id)throw Error("Checkpoint history changed during undo");this.done.pop(),this.undone.push({...$,...Z?{redoRef:Z}:{}})}peekRedo(){return this.undone[this.undone.length-1]}commitRedo($){if(this.peekRedo()?.id!==$.id)throw Error("Checkpoint history changed during redo");this.undone.pop();let{redoRef:Z,...W}=$;this.done.push(W)}restore($,Z=[]){this.done=[...$],this.undone=[...Z]}state(){return{done:[...this.done],undone:[...this.undone]}}all(){return[...this.done]}first(){return this.done[0]}last(){return this.done[this.done.length-1]}}class L1{commands=new Map;register($){this.commands.set($.name,$)}get($){return this.commands.get($)}list(){return[...this.commands.values()].sort(($,Z)=>$.name.localeCompare(Z.name))}has($){return this.commands.has($)}parse($){if(!$.startsWith("/"))return;let Z=$.slice(1),W=Z.search(/\s/);return W===-1?{name:Z,args:""}:{name:Z.slice(0,W),args:Z.slice(W+1).trim()}}async execute($,Z){let W=this.parse($);if(!W)return{handled:!1};let Q=this.commands.get(W.name);if(!Q)return{handled:!0,message:`Unknown command: /${W.name}`};return await Q.run({...Z,args:W.args})??{handled:!0}}}function V4($){let Z=$.customType,W=[];for(let Q of $.content)W.push(Q.type==="text"?{type:"text",text:`<${Z}>
10
- ${Q.text}
11
- </${Z}>`}:Q);return{role:"user",content:W,timestamp:$.timestamp}}function F$($){return $.map((Z)=>Z.role==="custom"?V4(Z):Z)}function x1($){return{role:"user",content:[{type:"text",text:$}],timestamp:Date.now()}}function D$($,Z,W=!1){return{role:"custom",customType:$,content:[{type:"text",text:Z}],display:W,timestamp:Date.now()}}var DK=3.5;function S0($){let Z=0;for(let W of $)if(W.role==="toolResult"||W.role==="user"||W.role==="custom")for(let Q of W.content)Z+=Q.type==="text"?Q.text.length:1500;else for(let Q of W.content)if(Q.type==="text")Z+=Q.text.length;else if(Q.type==="thinking")Z+=Q.thinking.length;else Z+=JSON.stringify(Q.arguments).length+Q.name.length;return Math.ceil(Z/DK)}function t5($,Z,W,Q){let Y=S0(Z),G=W?W.inputTokens+W.cacheReadTokens+W.cacheWriteTokens:0,X=W&&Q!==void 0?Math.max(0,Y-Q):0,J=Math.max(G+X,Y),K=$.contextWindow;return{tokens:J,limit:K,percent:K>0?J/K:0}}var L$=0.85;function o5($,Z=L$){return $.percent>=Z}class x0 extends Error{usage;constructor($,Z){super($);this.usage=Z;this.name="CompactionError"}}function F4($,Z=0.3){if($.length<=4)return{keepFromIndex:$.length};let W=Math.max(2,Math.floor($.length*Z)),Q=$.length-W;while(Q>0&&$[Q]?.role==="toolResult")Q--;return{keepFromIndex:Q}}var D4=`Summarize the conversation so far so that work can continue without the original transcript.
9
+ deps: ${Q}}`};var HN={keyword:"dependencies",type:"object",schemaType:"object",error:iG.error,code($){let[Z,Q]=VN($);cG($,Z),dG($,Q)}};function VN({schema:$}){let Z={},Q={};for(let W in $){if(W==="__proto__")continue;let Y=Array.isArray($[W])?Z:Q;Y[W]=$[W]}return[Z,Q]}function cG($,Z=$.schema){let{gen:Q,data:W,it:Y}=$;if(Object.keys(Z).length===0)return;let G=Q.let("missing");for(let X in Z){let J=Z[X];if(J.length===0)continue;let K=(0,OZ.propertyInData)(Q,W,X,Y.opts.ownProperties);if($.setParams({property:X,depsCount:J.length,deps:J.join(", ")}),Y.allErrors)Q.if(K,()=>{for(let B of J)(0,OZ.checkReportMissingProp)($,B)});else Q.if(k4._`${K} && (${(0,OZ.checkMissingProp)($,J,G)})`),(0,OZ.reportMissingProp)($,G),Q.else()}}iG.validatePropertyDeps=cG;function dG($,Z=$.schema){let{gen:Q,data:W,keyword:Y,it:G}=$,X=Q.name("valid");for(let J in Z){if((0,BN.alwaysValidSchema)(G,Z[J]))continue;Q.if((0,OZ.propertyInData)(Q,W,J,G.opts.ownProperties),()=>{let K=$.subschema({keyword:Y,schemaProp:J},X);$.mergeValidEvaluated(K,X)},()=>Q.var(X,!0)),$.ok(X)}}iG.validateSchemaDeps=dG;iG.default=HN});var sG=M((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});var tG=b(),DN=x(),LN={message:"property name must be valid",params:({params:$})=>tG._`{propertyName: ${$.propertyName}}`},UN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:LN,code($){let{gen:Z,schema:Q,data:W,it:Y}=$;if((0,DN.alwaysValidSchema)(Y,Q))return;let G=Z.name("valid");Z.forIn("key",W,(X)=>{$.setParams({propertyName:X}),$.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),Z.if((0,tG.not)(G),()=>{if($.error(!0),!Y.allErrors)Z.break()})}),$.ok(G)}};oG.default=UN});var x4=M((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var n5=q0(),I0=b(),AN=t0(),a5=x(),NN={message:"must NOT have additional properties",params:({params:$})=>I0._`{additionalProperty: ${$.additionalProperty}}`},ON={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:NN,code($){let{gen:Z,schema:Q,parentSchema:W,data:Y,errsCount:G,it:X}=$;if(!G)throw Error("ajv implementation error");let{allErrors:J,opts:K}=X;if(X.props=!0,K.removeAdditional!=="all"&&(0,a5.alwaysValidSchema)(X,Q))return;let B=(0,n5.allSchemaProperties)(W.properties),z=(0,n5.allSchemaProperties)(W.patternProperties);V(),$.ok(I0._`${G} === ${AN.default.errors}`);function V(){Z.forIn("key",Y,(q)=>{if(!B.length&&!z.length)L(q);else Z.if(F(q),()=>L(q))})}function F(q){let A;if(B.length>8){let N=(0,a5.schemaRefOrVal)(X,W.properties,"properties");A=(0,n5.isOwnProperty)(Z,N,q)}else if(B.length)A=(0,I0.or)(...B.map((N)=>I0._`${q} === ${N}`));else A=I0.nil;if(z.length)A=(0,I0.or)(A,...z.map((N)=>I0._`${(0,n5.usePattern)($,N)}.test(${q})`));return(0,I0.not)(A)}function D(q){Z.code(I0._`delete ${Y}[${q}]`)}function L(q){if(K.removeAdditional==="all"||K.removeAdditional&&Q===!1){D(q);return}if(Q===!1){if($.setParams({additionalProperty:q}),$.error(),!J)Z.break();return}if(typeof Q=="object"&&!(0,a5.alwaysValidSchema)(X,Q)){let A=Z.name("valid");if(K.removeAdditional==="failing")U(q,A,!1),Z.if((0,I0.not)(A),()=>{$.reset(),D(q)});else if(U(q,A),!J)Z.if((0,I0.not)(A),()=>Z.break())}}function U(q,A,N){let j={keyword:"additionalProperties",dataProp:q,dataPropType:a5.Type.Str};if(N===!1)Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(j,A)}}};eG.default=ON});var WX=M((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});var jN=KZ(),$X=q0(),f4=x(),ZX=x4(),PN={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,parentSchema:W,data:Y,it:G}=$;if(G.opts.removeAdditional==="all"&&W.additionalProperties===void 0)ZX.default.code(new jN.KeywordCxt(G,ZX.default,"additionalProperties"));let X=(0,$X.allSchemaProperties)(Q);for(let V of X)G.definedProperties.add(V);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=f4.mergeEvaluated.props(Z,(0,f4.toHash)(X),G.props);let J=X.filter((V)=>!(0,f4.alwaysValidSchema)(G,Q[V]));if(J.length===0)return;let K=Z.name("valid");for(let V of J){if(B(V))z(V);else{if(Z.if((0,$X.propertyInData)(Z,Y,V,G.opts.ownProperties)),z(V),!G.allErrors)Z.else().var(K,!0);Z.endIf()}$.it.definedProperties.add(V),$.ok(K)}function B(V){return G.opts.useDefaults&&!G.compositeRule&&Q[V].default!==void 0}function z(V){$.subschema({keyword:"properties",schemaProp:V,dataProp:V},K)}}};QX.default=PN});var KX=M((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});var YX=q0(),r5=b(),GX=x(),XX=x(),TN={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,data:W,parentSchema:Y,it:G}=$,{opts:X}=G,J=(0,YX.allSchemaProperties)(Q),K=J.filter((U)=>(0,GX.alwaysValidSchema)(G,Q[U]));if(J.length===0||K.length===J.length&&(!G.opts.unevaluated||G.props===!0))return;let B=X.strictSchema&&!X.allowMatchingProperties&&Y.properties,z=Z.name("valid");if(G.props!==!0&&!(G.props instanceof r5.Name))G.props=(0,XX.evaluatedPropsToName)(Z,G.props);let{props:V}=G;F();function F(){for(let U of J){if(B)D(U);if(G.allErrors)L(U);else Z.var(z,!0),L(U),Z.if(z)}}function D(U){for(let q in B)if(new RegExp(U).test(q))(0,GX.checkStrictMode)(G,`property ${q} matches pattern ${U} (use allowMatchingProperties)`)}function L(U){Z.forIn("key",W,(q)=>{Z.if(r5._`${(0,YX.usePattern)($,U)}.test(${q})`,()=>{let A=K.includes(U);if(!A)$.subschema({keyword:"patternProperties",schemaProp:U,dataProp:q,dataPropType:XX.Type.Str},z);if(G.opts.unevaluated&&V!==!0)Z.assign(r5._`${V}[${q}]`,!0);else if(!A&&!G.allErrors)Z.if((0,r5.not)(z),()=>Z.break())})})}}};JX.default=TN});var HX=M((BX)=>{Object.defineProperty(BX,"__esModule",{value:!0});var EN=x(),RN={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:Z,schema:Q,it:W}=$;if((0,EN.alwaysValidSchema)(W,Q)){$.fail();return}let Y=Z.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},Y),$.failResult(Y,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};BX.default=RN});var zX=M((VX)=>{Object.defineProperty(VX,"__esModule",{value:!0});var SN=q0(),yN={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:SN.validateUnion,error:{message:"must match a schema in anyOf"}};VX.default=yN});var DX=M((FX)=>{Object.defineProperty(FX,"__esModule",{value:!0});var t5=b(),_N=x(),kN={message:"must match exactly one schema in oneOf",params:({params:$})=>t5._`{passingSchemas: ${$.passing}}`},xN={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:kN,code($){let{gen:Z,schema:Q,parentSchema:W,it:Y}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Y.opts.discriminator&&W.discriminator)return;let G=Q,X=Z.let("valid",!1),J=Z.let("passing",null),K=Z.name("_valid");$.setParams({passing:J}),Z.block(B),$.result(X,()=>$.reset(),()=>$.error(!0));function B(){G.forEach((z,V)=>{let F;if((0,_N.alwaysValidSchema)(Y,z))Z.var(K,!0);else F=$.subschema({keyword:"oneOf",schemaProp:V,compositeRule:!0},K);if(V>0)Z.if(t5._`${K} && ${X}`).assign(X,!1).assign(J,t5._`[${J}, ${V}]`).else();Z.if(K,()=>{if(Z.assign(X,!0),Z.assign(J,V),F)$.mergeEvaluated(F,t5.Name)})})}}};FX.default=xN});var UX=M((LX)=>{Object.defineProperty(LX,"__esModule",{value:!0});var vN=x(),gN={keyword:"allOf",schemaType:"array",code($){let{gen:Z,schema:Q,it:W}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");let Y=Z.name("valid");Q.forEach((G,X)=>{if((0,vN.alwaysValidSchema)(W,G))return;let J=$.subschema({keyword:"allOf",schemaProp:X},Y);$.ok(Y),$.mergeEvaluated(J)})}};LX.default=gN});var OX=M((NX)=>{Object.defineProperty(NX,"__esModule",{value:!0});var o5=b(),AX=x(),uN={message:({params:$})=>o5.str`must match "${$.ifClause}" schema`,params:({params:$})=>o5._`{failingKeyword: ${$.ifClause}}`},mN={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uN,code($){let{gen:Z,parentSchema:Q,it:W}=$;if(Q.then===void 0&&Q.else===void 0)(0,AX.checkStrictMode)(W,'"if" without "then" and "else" is ignored');let Y=qX(W,"then"),G=qX(W,"else");if(!Y&&!G)return;let X=Z.let("valid",!0),J=Z.name("_valid");if(K(),$.reset(),Y&&G){let z=Z.let("ifClause");$.setParams({ifClause:z}),Z.if(J,B("then",z),B("else",z))}else if(Y)Z.if(J,B("then"));else Z.if((0,o5.not)(J),B("else"));$.pass(X,()=>$.error(!0));function K(){let z=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(z)}function B(z,V){return()=>{let F=$.subschema({keyword:z},J);if(Z.assign(X,J),$.mergeValidEvaluated(F,X),V)Z.assign(V,o5._`${z}`);else $.setParams({ifClause:z})}}}};function qX($,Z){let Q=$.schema[Z];return Q!==void 0&&!(0,AX.alwaysValidSchema)($,Q)}NX.default=mN});var jX=M((MX)=>{Object.defineProperty(MX,"__esModule",{value:!0});var pN=x(),cN={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:Z,it:Q}){if(Z.if===void 0)(0,pN.checkStrictMode)(Q,`"${$}" without "if" is ignored`)}};MX.default=cN});var wX=M((PX)=>{Object.defineProperty(PX,"__esModule",{value:!0});var iN=b4(),nN=gG(),aN=_4(),rN=mG(),tN=pG(),oN=rG(),sN=sG(),eN=x4(),$O=WX(),ZO=KX(),QO=HX(),WO=zX(),YO=DX(),GO=UX(),XO=OX(),JO=jX();function KO($=!1){let Z=[QO.default,WO.default,YO.default,GO.default,XO.default,JO.default,sN.default,eN.default,oN.default,$O.default,ZO.default];if($)Z.push(nN.default,rN.default);else Z.push(iN.default,aN.default);return Z.push(tN.default),Z}PX.default=KO});var IX=M((TX)=>{Object.defineProperty(TX,"__esModule",{value:!0});var c=b(),HO={message:({schemaCode:$})=>c.str`must match format "${$}"`,params:({schemaCode:$})=>c._`{format: ${$}}`},VO={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:HO,code($,Z){let{gen:Q,data:W,$data:Y,schema:G,schemaCode:X,it:J}=$,{opts:K,errSchemaPath:B,schemaEnv:z,self:V}=J;if(!K.validateFormats)return;if(Y)F();else D();function F(){let L=Q.scopeValue("formats",{ref:V.formats,code:K.code.formats}),U=Q.const("fDef",c._`${L}[${X}]`),q=Q.let("fType"),A=Q.let("format");Q.if(c._`typeof ${U} == "object" && !(${U} instanceof RegExp)`,()=>Q.assign(q,c._`${U}.type || "string"`).assign(A,c._`${U}.validate`),()=>Q.assign(q,c._`"string"`).assign(A,U)),$.fail$data((0,c.or)(N(),j()));function N(){if(K.strictSchema===!1)return c.nil;return c._`${X} && !${A}`}function j(){let P=z.$async?c._`(${U}.async ? await ${A}(${W}) : ${A}(${W}))`:c._`${A}(${W})`,O=c._`(typeof ${A} == "function" ? ${P} : ${A}.test(${W}))`;return c._`${A} && ${A} !== true && ${q} === ${Z} && !${O}`}}function D(){let L=V.formats[G];if(!L){N();return}if(L===!0)return;let[U,q,A]=j(L);if(U===Z)$.pass(P());function N(){if(K.strictSchema===!1){V.logger.warn(O());return}throw Error(O());function O(){return`unknown format "${G}" ignored in schema at path "${B}"`}}function j(O){let C=O instanceof RegExp?(0,c.regexpCode)(O):K.code.formats?c._`${K.code.formats}${(0,c.getProperty)(G)}`:void 0,v=Q.scopeValue("formats",{key:G,ref:O,code:C});if(typeof O=="object"&&!(O instanceof RegExp))return[O.type||"string",O.validate,c._`${v}.validate`];return["string",O,v]}function P(){if(typeof L=="object"&&!(L instanceof RegExp)&&L.async){if(!z.$async)throw Error("async format in sync schema");return c._`await ${A}(${W})`}return typeof q=="function"?c._`${A}(${W})`:c._`${A}.test(${W})`}}}};TX.default=VO});var RX=M((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});var FO=IX(),DO=[FO.default];EX.default=DO});var yX=M((CX)=>{Object.defineProperty(CX,"__esModule",{value:!0});CX.contentVocabulary=CX.metadataVocabulary=void 0;CX.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];CX.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var kX=M((_X)=>{Object.defineProperty(_X,"__esModule",{value:!0});var qO=QG(),AO=CG(),NO=wX(),OO=RX(),bX=yX(),MO=[qO.default,AO.default,(0,NO.default)(),OO.default,bX.metadataVocabulary,bX.contentVocabulary];_X.default=MO});var gX=M((fX)=>{Object.defineProperty(fX,"__esModule",{value:!0});fX.DiscrError=void 0;var xX;(function($){$.Tag="tag",$.Mapping="mapping"})(xX||(fX.DiscrError=xX={}))});var mX=M((uX)=>{Object.defineProperty(uX,"__esModule",{value:!0});var z$=b(),v4=gX(),hX=k5(),PO=BZ(),wO=x(),TO={message:({params:{discrError:$,tagName:Z}})=>$===v4.DiscrError.Tag?`tag "${Z}" must be string`:`value of tag "${Z}" must be in oneOf`,params:({params:{discrError:$,tag:Z,tagName:Q}})=>z$._`{error: ${$}, tag: ${Q}, tagValue: ${Z}}`},IO={keyword:"discriminator",type:"object",schemaType:"object",error:TO,code($){let{gen:Z,data:Q,schema:W,parentSchema:Y,it:G}=$,{oneOf:X}=Y;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=W.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(W.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let K=Z.let("valid",!1),B=Z.const("tag",z$._`${Q}${(0,z$.getProperty)(J)}`);Z.if(z$._`typeof ${B} == "string"`,()=>z(),()=>$.error(!1,{discrError:v4.DiscrError.Tag,tag:B,tagName:J})),$.ok(K);function z(){let D=F();Z.if(!1);for(let L in D)Z.elseIf(z$._`${B} === ${L}`),Z.assign(K,V(D[L]));Z.else(),$.error(!1,{discrError:v4.DiscrError.Mapping,tag:B,tagName:J}),Z.endIf()}function V(D){let L=Z.name("valid"),U=$.subschema({keyword:"oneOf",schemaProp:D},L);return $.mergeEvaluated(U,z$.Name),L}function F(){var D;let L={},U=A(Y),q=!0;for(let P=0;P<X.length;P++){let O=X[P];if((O===null||O===void 0?void 0:O.$ref)&&!(0,wO.schemaHasRulesButRef)(O,G.self.RULES)){let v=O.$ref;if(O=hX.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,v),O instanceof hX.SchemaEnv)O=O.schema;if(O===void 0)throw new PO.default(G.opts.uriResolver,G.baseId,v)}let C=(D=O===null||O===void 0?void 0:O.properties)===null||D===void 0?void 0:D[J];if(typeof C!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(U||A(O)),N(C,P)}if(!q)throw Error(`discriminator: "${J}" must be required`);return L;function A({required:P}){return Array.isArray(P)&&P.includes(J)}function N(P,O){if(P.const)j(P.const,O);else if(P.enum)for(let C of P.enum)j(C,O);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function j(P,O){if(typeof P!="string"||P in L)throw Error(`discriminator: "${J}" values must be unique strings`);L[P]=O}}}};uX.default=IO});var lX=M((v2,RO)=>{RO.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 h4=M((B0,g4)=>{Object.defineProperty(B0,"__esModule",{value:!0});B0.MissingRefError=B0.ValidationError=B0.CodeGen=B0.Name=B0.nil=B0.stringify=B0.str=B0._=B0.KeywordCxt=B0.Ajv=void 0;var CO=iY(),SO=kX(),yO=mX(),pX=lX(),bO=["/properties"],s5="http://json-schema.org/draft-07/schema";class MZ extends CO.default{_addVocabularies(){if(super._addVocabularies(),SO.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(yO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(pX,bO):pX;this.addMetaSchema($,s5,!1),this.refs["http://json-schema.org/schema"]=s5}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s5)?s5:void 0)}}B0.Ajv=MZ;g4.exports=B0=MZ;g4.exports.Ajv=MZ;Object.defineProperty(B0,"__esModule",{value:!0});B0.default=MZ;var _O=KZ();Object.defineProperty(B0,"KeywordCxt",{enumerable:!0,get:function(){return _O.KeywordCxt}});var F$=b();Object.defineProperty(B0,"_",{enumerable:!0,get:function(){return F$._}});Object.defineProperty(B0,"str",{enumerable:!0,get:function(){return F$.str}});Object.defineProperty(B0,"stringify",{enumerable:!0,get:function(){return F$.stringify}});Object.defineProperty(B0,"nil",{enumerable:!0,get:function(){return F$.nil}});Object.defineProperty(B0,"Name",{enumerable:!0,get:function(){return F$.Name}});Object.defineProperty(B0,"CodeGen",{enumerable:!0,get:function(){return F$.CodeGen}});var kO=b5();Object.defineProperty(B0,"ValidationError",{enumerable:!0,get:function(){return kO.default}});var xO=BZ();Object.defineProperty(B0,"MissingRefError",{enumerable:!0,get:function(){return xO.default}})});var eX=M((oX)=>{Object.defineProperty(oX,"__esModule",{value:!0});oX.formatNames=oX.fastFormats=oX.fullFormats=void 0;function x0($,Z){return{validate:$,compare:Z}}oX.fullFormats={date:x0(nX,p4),time:x0(m4(!0),c4),"date-time":x0(cX(!0),rX),"iso-time":x0(m4(),aX),"iso-date-time":x0(cX(),tX),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:pO,"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:tO,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:cO,int32:{type:"number",validate:nO},int64:{type:"number",validate:aO},float:{type:"number",validate:iX},double:{type:"number",validate:iX},password:!0,binary:!0};oX.fastFormats={...oX.fullFormats,date:x0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,p4),time:x0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,c4),"date-time":x0(/^\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,rX),"iso-time":x0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,aX),"iso-date-time":x0(/^\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,tX),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};oX.formatNames=Object.keys(oX.fullFormats);function gO($){return $%4===0&&($%100!==0||$%400===0)}var hO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,uO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function nX($){let Z=hO.exec($);if(!Z)return!1;let Q=+Z[1],W=+Z[2],Y=+Z[3];return W>=1&&W<=12&&Y>=1&&Y<=(W===2&&gO(Q)?29:uO[W])}function p4($,Z){if(!($&&Z))return;if($>Z)return 1;if($<Z)return-1;return 0}var u4=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function m4($){return function(Q){let W=u4.exec(Q);if(!W)return!1;let Y=+W[1],G=+W[2],X=+W[3],J=W[4],K=W[5]==="-"?-1:1,B=+(W[6]||0),z=+(W[7]||0);if(B>23||z>59||$&&!J)return!1;if(Y<=23&&G<=59&&X<60)return!0;let V=G-z*K,F=Y-B*K-(V<0?1:0);return(F===23||F===-1)&&(V===59||V===-1)&&X<61}}function c4($,Z){if(!($&&Z))return;let Q=new Date("2020-01-01T"+$).valueOf(),W=new Date("2020-01-01T"+Z).valueOf();if(!(Q&&W))return;return Q-W}function aX($,Z){if(!($&&Z))return;let Q=u4.exec($),W=u4.exec(Z);if(!(Q&&W))return;if($=Q[1]+Q[2]+Q[3],Z=W[1]+W[2]+W[3],$>Z)return 1;if($<Z)return-1;return 0}var l4=/t|\s/i;function cX($){let Z=m4($);return function(W){let Y=W.split(l4);return Y.length===2&&nX(Y[0])&&Z(Y[1])}}function rX($,Z){if(!($&&Z))return;let Q=new Date($).valueOf(),W=new Date(Z).valueOf();if(!(Q&&W))return;return Q-W}function tX($,Z){if(!($&&Z))return;let[Q,W]=$.split(l4),[Y,G]=Z.split(l4),X=p4(Q,Y);if(X===void 0)return;return X||c4(W,G)}var mO=/\/|:/,lO=/^(?:[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 pO($){return mO.test($)&&lO.test($)}var dX=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function cO($){return dX.lastIndex=0,dX.test($)}var dO=-2147483648,iO=2147483647;function nO($){return Number.isInteger($)&&$<=iO&&$>=dO}function aO($){return Number.isInteger($)}function iX(){return!0}var rO=/[^\\]\\Z/;function tO($){if(rO.test($))return!1;try{return new RegExp($),!0}catch(Z){return!1}}});var ZJ=M(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});$J.formatLimitDefinition=void 0;var sO=h4(),E0=b(),q1=E0.operators,e5={formatMaximum:{okStr:"<=",ok:q1.LTE,fail:q1.GT},formatMinimum:{okStr:">=",ok:q1.GTE,fail:q1.LT},formatExclusiveMaximum:{okStr:"<",ok:q1.LT,fail:q1.GTE},formatExclusiveMinimum:{okStr:">",ok:q1.GT,fail:q1.LTE}},eO={message:({keyword:$,schemaCode:Z})=>E0.str`should be ${e5[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>E0._`{comparison: ${e5[$].okStr}, limit: ${Z}}`};$J.formatLimitDefinition={keyword:Object.keys(e5),type:"string",schemaType:"string",$data:!0,error:eO,code($){let{gen:Z,data:Q,schemaCode:W,keyword:Y,it:G}=$,{opts:X,self:J}=G;if(!X.validateFormats)return;let K=new sO.KeywordCxt(G,J.RULES.all.format.definition,"format");if(K.$data)B();else z();function B(){let F=Z.scopeValue("formats",{ref:J.formats,code:X.code.formats}),D=Z.const("fmt",E0._`${F}[${K.schemaCode}]`);$.fail$data((0,E0.or)(E0._`typeof ${D} != "object"`,E0._`${D} instanceof RegExp`,E0._`typeof ${D}.compare != "function"`,V(D)))}function z(){let F=K.schema,D=J.formats[F];if(!D||D===!0)return;if(typeof D!="object"||D instanceof RegExp||typeof D.compare!="function")throw Error(`"${Y}": format "${F}" does not define "compare" function`);let L=Z.scopeValue("formats",{key:F,ref:D,code:X.code.formats?E0._`${X.code.formats}${(0,E0.getProperty)(F)}`:void 0});$.fail$data(V(L))}function V(F){return E0._`${F}.compare(${Q}, ${W}) ${e5[Y].fail} 0`}},dependencies:["format"]};var $M=($)=>{return $.addKeyword($J.formatLimitDefinition),$};$J.default=$M});var GJ=M((jZ,YJ)=>{Object.defineProperty(jZ,"__esModule",{value:!0});var D$=eX(),QM=ZJ(),n4=b(),QJ=new n4.Name("fullFormats"),WM=new n4.Name("fastFormats"),a4=($,Z={keywords:!0})=>{if(Array.isArray(Z))return WJ($,Z,D$.fullFormats,QJ),$;let[Q,W]=Z.mode==="fast"?[D$.fastFormats,WM]:[D$.fullFormats,QJ],Y=Z.formats||D$.formatNames;if(WJ($,Y,Q,W),Z.keywords)(0,QM.default)($);return $};a4.get=($,Z="full")=>{let W=(Z==="fast"?D$.fastFormats:D$.fullFormats)[$];if(!W)throw Error(`Unknown format "${$}"`);return W};function WJ($,Z,Q,W){var Y,G;(Y=(G=$.opts.code).formats)!==null&&Y!==void 0||(G.formats=n4._`require("ajv-formats/dist/formats").${W}`);for(let X of Z)$.addFormat(X,Q[X])}YJ.exports=jZ=a4;Object.defineProperty(jZ,"__esModule",{value:!0});jZ.default=a4});var DJ=M((Gy,FJ)=>{FJ.exports=zJ;zJ.sync=JM;var HJ=$1("fs");function XM($,Z){var Q=Z.pathExt!==void 0?Z.pathExt:process.env.PATHEXT;if(!Q)return!0;if(Q=Q.split(";"),Q.indexOf("")!==-1)return!0;for(var W=0;W<Q.length;W++){var Y=Q[W].toLowerCase();if(Y&&$.substr(-Y.length).toLowerCase()===Y)return!0}return!1}function VJ($,Z,Q){if(!$.isSymbolicLink()&&!$.isFile())return!1;return XM(Z,Q)}function zJ($,Z,Q){HJ.stat($,function(W,Y){Q(W,W?!1:VJ(Y,$,Z))})}function JM($,Z){return VJ(HJ.statSync($),$,Z)}});var NJ=M((Xy,AJ)=>{AJ.exports=UJ;UJ.sync=KM;var LJ=$1("fs");function UJ($,Z,Q){LJ.stat($,function(W,Y){Q(W,W?!1:qJ(Y,Z))})}function KM($,Z){return qJ(LJ.statSync($),Z)}function qJ($,Z){return $.isFile()&&BM($,Z)}function BM($,Z){var{mode:Q,uid:W,gid:Y}=$,G=Z.uid!==void 0?Z.uid:process.getuid&&process.getuid(),X=Z.gid!==void 0?Z.gid:process.getgid&&process.getgid(),J=parseInt("100",8),K=parseInt("010",8),B=parseInt("001",8),z=J|K,V=Q&B||Q&K&&Y===X||Q&J&&W===G||Q&z&&G===0;return V}});var MJ=M((Ky,OJ)=>{var Jy=$1("fs"),Z6;if(process.platform==="win32"||global.TESTING_WINDOWS)Z6=DJ();else Z6=NJ();OJ.exports=s4;s4.sync=HM;function s4($,Z,Q){if(typeof Z==="function")Q=Z,Z={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(W,Y){s4($,Z||{},function(G,X){if(G)Y(G);else W(X)})})}Z6($,Z||{},function(W,Y){if(W){if(W.code==="EACCES"||Z&&Z.ignoreErrors)W=null,Y=!1}Q(W,Y)})}function HM($,Z){try{return Z6.sync($,Z||{})}catch(Q){if(Z&&Z.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var RJ=M((By,EJ)=>{var L$=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",jJ=$1("path"),VM=L$?";":":",PJ=MJ(),wJ=($)=>Object.assign(Error(`not found: ${$}`),{code:"ENOENT"}),TJ=($,Z)=>{let Q=Z.colon||VM,W=$.match(/\//)||L$&&$.match(/\\/)?[""]:[...L$?[process.cwd()]:[],...(Z.path||process.env.PATH||"").split(Q)],Y=L$?Z.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",G=L$?Y.split(Q):[""];if(L$){if($.indexOf(".")!==-1&&G[0]!=="")G.unshift("")}return{pathEnv:W,pathExt:G,pathExtExe:Y}},IJ=($,Z,Q)=>{if(typeof Z==="function")Q=Z,Z={};if(!Z)Z={};let{pathEnv:W,pathExt:Y,pathExtExe:G}=TJ($,Z),X=[],J=(B)=>new Promise((z,V)=>{if(B===W.length)return Z.all&&X.length?z(X):V(wJ($));let F=W[B],D=/^".*"$/.test(F)?F.slice(1,-1):F,L=jJ.join(D,$),U=!D&&/^\.[\\\/]/.test($)?$.slice(0,2)+L:L;z(K(U,B,0))}),K=(B,z,V)=>new Promise((F,D)=>{if(V===Y.length)return F(J(z+1));let L=Y[V];PJ(B+L,{pathExt:G},(U,q)=>{if(!U&&q)if(Z.all)X.push(B+L);else return F(B+L);return F(K(B,z,V+1))})});return Q?J(0).then((B)=>Q(null,B),Q):J(0)},zM=($,Z)=>{Z=Z||{};let{pathEnv:Q,pathExt:W,pathExtExe:Y}=TJ($,Z),G=[];for(let X=0;X<Q.length;X++){let J=Q[X],K=/^".*"$/.test(J)?J.slice(1,-1):J,B=jJ.join(K,$),z=!K&&/^\.[\\\/]/.test($)?$.slice(0,2)+B:B;for(let V=0;V<W.length;V++){let F=z+W[V];try{if(PJ.sync(F,{pathExt:Y}))if(Z.all)G.push(F);else return F}catch(D){}}}if(Z.all&&G.length)return G;if(Z.nothrow)return null;throw wJ($)};EJ.exports=IJ;IJ.sync=zM});var SJ=M((Hy,e4)=>{var CJ=($={})=>{let Z=$.env||process.env;if(($.platform||process.platform)!=="win32")return"PATH";return Object.keys(Z).reverse().find((W)=>W.toUpperCase()==="PATH")||"Path"};e4.exports=CJ;e4.exports.default=CJ});var kJ=M((Vy,_J)=>{var yJ=$1("path"),FM=RJ(),DM=SJ();function bJ($,Z){let Q=$.options.env||process.env,W=process.cwd(),Y=$.options.cwd!=null,G=Y&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir($.options.cwd)}catch(J){}let X;try{X=FM.sync($.command,{path:Q[DM({env:Q})],pathExt:Z?yJ.delimiter:void 0})}catch(J){}finally{if(G)process.chdir(W)}if(X)X=yJ.resolve(Y?$.options.cwd:"",X);return X}function LM($){return bJ($)||bJ($,!0)}_J.exports=LM});var xJ=M((AM,ZQ)=>{var $Q=/([()\][%!^"`<>&|;, *?])/g;function UM($){return $=$.replace($Q,"^$1"),$}function qM($,Z){if($=`${$}`,$=$.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),$=$.replace(/(?=(\\+?)?)\1$/,"$1$1"),$=`"${$}"`,$=$.replace($Q,"^$1"),Z)$=$.replace($Q,"^$1");return $}AM.command=UM;AM.argument=qM});var vJ=M((zy,fJ)=>{fJ.exports=/^#!(.*)/});var hJ=M((Fy,gJ)=>{var MM=vJ();gJ.exports=($="")=>{let Z=$.match(MM);if(!Z)return null;let[Q,W]=Z[0].replace(/#! ?/,"").split(" "),Y=Q.split("/").pop();if(Y==="env")return W;return W?`${Y} ${W}`:Y}});var mJ=M((Dy,uJ)=>{var QQ=$1("fs"),jM=hJ();function PM($){let Q=Buffer.alloc(150),W;try{W=QQ.openSync($,"r"),QQ.readSync(W,Q,0,150,0),QQ.closeSync(W)}catch(Y){}return jM(Q.toString())}uJ.exports=PM});var dJ=M((Ly,cJ)=>{var wM=$1("path"),lJ=kJ(),pJ=xJ(),TM=mJ(),IM=process.platform==="win32",EM=/\.(?:com|exe)$/i,RM=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function CM($){$.file=lJ($);let Z=$.file&&TM($.file);if(Z)return $.args.unshift($.file),$.command=Z,lJ($);return $.file}function SM($){if(!IM)return $;let Z=CM($),Q=!EM.test(Z);if($.options.forceShell||Q){let W=RM.test(Z);$.command=wM.normalize($.command),$.command=pJ.command($.command),$.args=$.args.map((G)=>pJ.argument(G,W));let Y=[$.command].concat($.args).join(" ");$.args=["/d","/s","/c",`"${Y}"`],$.command=process.env.comspec||"cmd.exe",$.options.windowsVerbatimArguments=!0}return $}function yM($,Z,Q){if(Z&&!Array.isArray(Z))Q=Z,Z=null;Z=Z?Z.slice(0):[],Q=Object.assign({},Q);let W={command:$,args:Z,options:Q,file:void 0,original:{command:$,args:Z}};return Q.shell?W:SM(W)}cJ.exports=yM});var aJ=M((Uy,nJ)=>{var WQ=process.platform==="win32";function YQ($,Z){return Object.assign(Error(`${Z} ${$.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Z} ${$.command}`,path:$.command,spawnargs:$.args})}function bM($,Z){if(!WQ)return;let Q=$.emit;$.emit=function(W,Y){if(W==="exit"){let G=iJ(Y,Z);if(G)return Q.call($,"error",G)}return Q.apply($,arguments)}}function iJ($,Z){if(WQ&&$===1&&!Z.file)return YQ(Z.original,"spawn");return null}function _M($,Z){if(WQ&&$===1&&!Z.file)return YQ(Z.original,"spawnSync");return null}nJ.exports={hookChildProcess:bM,verifyENOENT:iJ,verifyENOENTSync:_M,notFoundError:YQ}});var oJ=M((qy,U$)=>{var rJ=$1("child_process"),GQ=dJ(),XQ=aJ();function tJ($,Z,Q){let W=GQ($,Z,Q),Y=rJ.spawn(W.command,W.args,W.options);return XQ.hookChildProcess(Y,W),Y}function kM($,Z,Q){let W=GQ($,Z,Q),Y=rJ.spawnSync(W.command,W.args,W.options);return Y.error=Y.error||XQ.verifyENOENTSync(Y.status,W),Y}U$.exports=tJ;U$.exports.spawn=tJ;U$.exports.sync=kM;U$.exports._parse=GQ;U$.exports._enoent=XQ});import{readFile as oj}from"fs/promises";import{homedir as sj}from"os";import{join as ej,resolve as f3}from"path";class SZ{done=[];undone=[];record($){this.done.push($),this.undone=[]}get canUndo(){return this.done.length>0}get canRedo(){return this.undone.length>0}peekUndo(){return this.done[this.done.length-1]}commitUndo($,Z){if(this.peekUndo()?.id!==$.id)throw Error("Checkpoint history changed during undo");this.done.pop(),this.undone.push({...$,...Z?{redoRef:Z}:{}})}peekRedo(){return this.undone[this.undone.length-1]}commitRedo($){if(this.peekRedo()?.id!==$.id)throw Error("Checkpoint history changed during redo");this.undone.pop();let{redoRef:Z,...Q}=$;this.done.push(Q)}restore($,Z=[]){this.done=[...$],this.undone=[...Z]}state(){return{done:[...this.done],undone:[...this.undone]}}all(){return[...this.done]}first(){return this.done[0]}last(){return this.done[this.done.length-1]}}class M1{commands=new Map;register($){this.commands.set($.name,$)}get($){return this.commands.get($)}list(){return[...this.commands.values()].sort(($,Z)=>$.name.localeCompare(Z.name))}has($){return this.commands.has($)}parse($){if(!$.startsWith("/"))return;let Z=$.slice(1),Q=Z.search(/\s/);return Q===-1?{name:Z,args:""}:{name:Z.slice(0,Q),args:Z.slice(Q+1).trim()}}async execute($,Z){let Q=this.parse($);if(!Q)return{handled:!1};let W=this.commands.get(Q.name);if(!W)return{handled:!0,message:`Unknown command: /${Q.name}`};return await W.run({...Z,args:Q.args})??{handled:!0}}}var d3=new Set(["rate_limit","overloaded","network"]);class l extends Error{kind;status;retryAfterMs;constructor($,Z,Q){super(Z);if(this.name="AiError",this.kind=$,Q?.status!==void 0)this.status=Q.status;if(Q?.retryAfterMs!==void 0)this.retryAfterMs=Q.retryAfterMs}get retryable(){return d3.has(this.kind)}}var i3=[/prompt is too long/i,/context window/i,/context[_ ]length[_ ]exceeded/i,/exceeds the maximum number of tokens/i,/input token count.*exceeds/i,/too many total text bytes/i];function yZ($){return i3.some((Z)=>Z.test($))}function n3($){let Z=$.get("retry-after-ms");if(Z){let W=Number.parseFloat(Z);if(!Number.isNaN(W))return W}let Q=$.get("retry-after");if(Q){let W=Number.parseFloat(Q);if(!Number.isNaN(W))return W*1000;let Y=Date.parse(Q);if(!Number.isNaN(Y))return Y-Date.now()}return}function j$($,Z,Q){let W={status:$,retryAfterMs:n3(Q)};if($===401||$===403)return new l("auth",Z,W);if($===404)return new l("not_found",Z,W);if($===429)return new l("rate_limit",Z,W);if($===529||$===503)return new l("overloaded",Z,W);if($>=500)return new l("api",Z,W);if(yZ(Z))return new l("context_too_long",Z,W);return new l("bad_request",Z,W)}var SQ={models:[{provider:"anthropic",id:"claude-opus-5",name:"Claude Opus 5",contextWindow:1e6,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingMode:"adaptive",pricing:{input:5,output:25,cacheRead:0.5,cacheWrite:6.25}},{provider:"anthropic",id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindow:1e6,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingMode:"adaptive",pricing:{input:3,output:15,cacheRead:0.3,cacheWrite:3.75}},{provider:"anthropic",id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:200000,maxOutput:64000,modalities:["text","image"],thinking:!0,thinkingMode:"budget",pricing:{input:1,output:5,cacheRead:0.1,cacheWrite:1.25}},{provider:"openai",id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:5,output:30,cacheRead:0.5,cacheWrite:6.25}},{provider:"openai",id:"gpt-5.1",name:"GPT-5.1",contextWindow:400000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:1.25,output:10,cacheRead:0.125,cacheWrite:0}},{provider:"openai",id:"gpt-5-mini",name:"GPT-5 mini",contextWindow:400000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:0.25,output:2,cacheRead:0.025,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingLevels:["low","medium","high","xhigh","max","ultra"],defaultThinkingLevel:"low",pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingLevels:["low","medium","high","xhigh","max","ultra"],defaultThinkingLevel:"medium",pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingLevels:["low","medium","high","xhigh","max"],defaultThinkingLevel:"medium",pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"google",id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",contextWindow:1048576,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:{input:1.25,output:10,cacheRead:0.31,cacheWrite:0}},{provider:"google",id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:{input:0.3,output:2.5,cacheRead:0.075,cacheWrite:0}}]};var r3=[{id:"amazon-bedrock",name:"Amazon Bedrock",api:"openai-responses",env:["AWS_BEARER_TOKEN_BEDROCK"]},{id:"anthropic",name:"Anthropic",api:"anthropic-messages",baseUrl:"https://api.anthropic.com",env:["ANTHROPIC_API_KEY"],auth:"anthropic"},{id:"azure-openai-responses",name:"Azure OpenAI",api:"openai-responses",env:["AZURE_OPENAI_API_KEY"],auth:"azure"},{id:"cerebras",name:"Cerebras",api:"openai-completions",baseUrl:"https://api.cerebras.ai/v1",env:["CEREBRAS_API_KEY"]},{id:"cloudflare-ai-gateway",name:"Cloudflare AI Gateway",api:"openai-completions",env:["CLOUDFLARE_API_KEY"],auth:"cloudflare"},{id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",api:"openai-completions",env:["CLOUDFLARE_API_KEY"]},{id:"deepseek",name:"DeepSeek",api:"openai-completions",baseUrl:"https://api.deepseek.com",env:["DEEPSEEK_API_KEY"]},{id:"fireworks",name:"Fireworks",api:"anthropic-messages",baseUrl:"https://api.fireworks.ai/inference",env:["FIREWORKS_API_KEY"],auth:"anthropic"},{id:"github-copilot",name:"GitHub Copilot",api:"openai-responses",baseUrl:"https://api.individual.githubcopilot.com",env:["COPILOT_GITHUB_TOKEN"],headers:{"user-agent":"GitHubCopilotChat/0.35.0","editor-version":"vscode/1.107.0","editor-plugin-version":"copilot-chat/0.35.0","copilot-integration-id":"vscode-chat"}},{id:"google",name:"Google",api:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",env:["GEMINI_API_KEY"],auth:"google"},{id:"google-vertex",name:"Google Vertex AI",api:"google-vertex",env:["GOOGLE_CLOUD_API_KEY"],auth:"google"},{id:"groq",name:"Groq",api:"openai-completions",baseUrl:"https://api.groq.com/openai/v1",env:["GROQ_API_KEY"]},{id:"huggingface",name:"Hugging Face",api:"openai-completions",baseUrl:"https://router.huggingface.co/v1",env:["HF_TOKEN"]},{id:"kimi-coding",name:"Kimi For Coding",api:"anthropic-messages",baseUrl:"https://api.kimi.com/coding",env:["KIMI_API_KEY"],auth:"anthropic",headers:{"user-agent":"KimiCLI/1.5"}},{id:"minimax",name:"MiniMax",api:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",env:["MINIMAX_API_KEY"],auth:"anthropic"},{id:"mistral",name:"Mistral",api:"openai-completions",baseUrl:"https://api.mistral.ai/v1",env:["MISTRAL_API_KEY"]},{id:"moonshotai",name:"Moonshot AI",api:"openai-completions",baseUrl:"https://api.moonshot.ai/v1",env:["MOONSHOT_API_KEY"]},{id:"nvidia",name:"NVIDIA NIM",api:"openai-completions",baseUrl:"https://integrate.api.nvidia.com/v1",env:["NVIDIA_API_KEY"],headers:{"nvcf-poll-seconds":"3600"}},{id:"openai",name:"OpenAI",api:"openai-responses",baseUrl:"https://api.openai.com/v1",env:["OPENAI_API_KEY"]},{id:"openai-codex",name:"OpenAI Codex",api:"openai-responses",baseUrl:"https://chatgpt.com/backend-api/codex",env:[]},{id:"opencode",name:"OpenCode Zen",api:"openai-completions",baseUrl:"https://opencode.ai/zen/v1",env:["OPENCODE_API_KEY"]},{id:"opencode-go",name:"OpenCode Go",api:"openai-completions",baseUrl:"https://opencode.ai/zen/go/v1",env:["OPENCODE_API_KEY"]},{id:"openrouter",name:"OpenRouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",env:["OPENROUTER_API_KEY"]},{id:"qwen-token-plan",name:"Qwen Token Plan",api:"openai-completions",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",env:["QWEN_TOKEN_PLAN_API_KEY"]},{id:"vercel-ai-gateway",name:"Vercel AI Gateway",api:"anthropic-messages",baseUrl:"https://ai-gateway.vercel.sh",env:["AI_GATEWAY_API_KEY"],auth:"anthropic"},{id:"xai",name:"xAI",api:"openai-completions",baseUrl:"https://api.x.ai/v1",env:["XAI_API_KEY"]},{id:"zai",name:"Z.AI Coding Plan",api:"openai-completions",baseUrl:"https://api.z.ai/api/coding/paas/v4",env:["ZAI_API_KEY"]}],u0=new Map(r3.map(($)=>[$.id,$]));function m1($){return u0.get($)}function P$($){return $.api??m1($.provider)?.api??"openai-completions"}function z6($){return $.baseUrl??m1($.provider)?.baseUrl}function l1($){return m1($)?.env??[]}var t3=new Set(['"',"\\","/","b","f","n","r","t","u"]),o3={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function F6($){let Z="",Q=!1;for(let W=0;W<$.length;W++){let Y=$[W];if(!Q){if(Z+=Y,Y==='"')Q=!0;continue}if(Y==='"'){Z+=Y,Q=!1;continue}if(Y==="\\"){let X=$[W+1];if(X===void 0){Z+="\\\\";continue}if(X==="u"&&/^[0-9a-fA-F]{4}$/.test($.slice(W+2,W+6))){Z+=$.slice(W,W+6),W+=5;continue}if(X!=="u"&&t3.has(X)){Z+=`\\${X}`,W+=1;continue}Z+="\\\\";continue}let G=Y.codePointAt(0)??0;if(G<=31)Z+=o3[Y]??`\\u${G.toString(16).padStart(4,"0")}`;else Z+=Y}return Z}function yQ($){try{return JSON.parse($)}catch(Z){let Q=F6($);if(Q!==$)return JSON.parse(Q);throw Z}}class bQ{text;pos=0;constructor($){this.text=$}ws(){while(this.pos<this.text.length&&/\s/.test(this.text[this.pos]))this.pos++}peek(){return this.text[this.pos]}value(){this.ws();let $=this.peek();if($===void 0)return;if($==="{")return this.object();if($==="[")return this.array();if($==='"')return this.string();if($==="t"||$==="f"||$==="n")return this.literal();if($==="-"||/[0-9]/.test($))return this.number();return}object(){let $={};this.pos++;for(;;){if(this.ws(),this.peek()===void 0)return $;if(this.peek()==="}")return this.pos++,$;if(this.peek()===","){this.pos++;continue}if(this.peek()!=='"')return $;let Z=this.pos,Q=this.string();if(this.pos>=this.text.length&&!this.closedString(Z))return $;if(this.ws(),this.peek()!==":")return $;if(this.pos++,this.ws(),this.peek()===void 0)return $;let W=this.pos,Y=this.value();if(Y!==void 0||this.consumedNull(W))$[Q]=Y??null}}array(){let $=[];this.pos++;for(;;){if(this.ws(),this.peek()===void 0)return $;if(this.peek()==="]")return this.pos++,$;if(this.peek()===","){this.pos++;continue}let Z=this.pos,Q=this.value();if(Q===void 0&&!this.consumedNull(Z))return $;$.push(Q??null)}}closedString($){let Z=$+1;while(Z<this.text.length)if(this.text[Z]==="\\")Z+=2;else if(this.text[Z]==='"')return!0;else Z+=1;return!1}consumedNull($){return this.text.slice($,this.pos).trim().startsWith("null")}string(){this.pos++;let $="";while(this.pos<this.text.length){let Z=this.text[this.pos];if(Z==='"')return this.pos++,$;if(Z==="\\"){let Q=this.text[this.pos+1];if(Q===void 0)return this.pos++,$;if(Q==="u"){let Y=this.text.slice(this.pos+2,this.pos+6);if(/^[0-9a-fA-F]{4}$/.test(Y))$+=String.fromCharCode(Number.parseInt(Y,16)),this.pos+=6;else return this.pos=this.text.length,$;continue}$+={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
10
+ `,r:"\r",t:"\t"}[Q]??Q,this.pos+=2;continue}$+=Z,this.pos++}return $}literal(){for(let[$,Z]of[["true",!0],["false",!1],["null",null]])if($.startsWith(this.text.slice(this.pos,this.pos+$.length))){let Q=this.text.slice(this.pos);if($.startsWith(Q))return this.pos=this.text.length,Z;if(Q.startsWith($))return this.pos+=$.length,Z}this.pos=this.text.length;return}number(){let Z=/^-?[0-9]*\.?[0-9]*(?:[eE][+-]?[0-9]*)?/.exec(this.text.slice(this.pos))?.[0]??"";this.pos+=Z.length;let Q=Number(Z);return Number.isNaN(Q)?void 0:Q}}function _Q($){return new bQ($).value()}function b0($){if(!$||$.trim()==="")return{};try{let Z=yQ($);if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z))return Z;return{}}catch{for(let Z of[$,F6($)])try{let Q=_Q(Z);if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return{}}}var s3=60000;function D6(){let $=Error("Request aborted");return $.name="AbortError",$}function e3($,Z){return new Promise((Q,W)=>{if(Z?.aborted){W(D6());return}let Y=()=>{clearTimeout(G),W(D6())},G=setTimeout(()=>{Z?.removeEventListener("abort",Y),Q()},Math.max(0,$));Z?.addEventListener("abort",Y,{once:!0})})}function $K($,Z,Q){if($.retryAfterMs!==void 0&&$.retryAfterMs>0)return Math.min($.retryAfterMs,Q);return Math.min(0.5*2**Z,8)*1000*(1-Math.random()*0.25)}async function m0($,Z={}){let Q=Z.maxRetries??2,W=Z.maxRetryDelayMs??s3,Y=Q;for(;;)try{return await $()}catch(G){if(Z.signal?.aborted)throw D6();if(Y<=0||!(G instanceof l)||!G.retryable)throw G;let X=Q-Y;Y--,await e3($K(G,X,W),Z.signal)}}function xQ($){if(!$.event&&$.data.length===0)return null;let Z={event:$.event,data:$.data.join(`
11
+ `)};return $.event=null,$.data=[],Z}function kQ($,Z){if($==="")return xQ(Z);if($.startsWith(":"))return null;let Q=$.indexOf(":"),W=Q===-1?$:$.slice(0,Q),Y=Q===-1?"":$.slice(Q+1);if(Y.startsWith(" "))Y=Y.slice(1);if(W==="event")Z.event=Y;else if(W==="data")Z.data.push(Y);return null}async function*l0($,Z){let Q=$.getReader(),W=new TextDecoder,Y={event:null,data:[]},G="",X=function*(){let J=G.search(/[\r\n]/);while(J!==-1){let K=G.slice(0,J),B=J+1;if(G[J]==="\r"&&G[B]===`
12
+ `)B+=1;G=G.slice(B);let z=kQ(K,Y);if(z)yield z;J=G.search(/[\r\n]/)}};try{while(!0){if(Z?.aborted)throw Error("Request was aborted");let{value:K,done:B}=await Q.read();if(B)break;G+=W.decode(K,{stream:!0}),yield*X()}if(G+=W.decode(),yield*X(),G.length>0){let K=kQ(G,Y);if(K)yield K}let J=xQ(Y);if(J)yield J}finally{Q.releaseLock()}}function p0($){return $.replace(/\/+$/,"")}function ZK($){for(let Z of $){let Q=process.env[Z];if(Q)return Q}return}async function Z1($,Z){let Q=await Z?.getCredentials?.();if(Q){if($.provider==="anthropic"&&Q.type==="oauth")throw new l("auth","Anthropic account-plan authentication is not supported");return Q}let W=Z?.apiKey??ZK(l1($.provider));if(!W){let Y=l1($.provider),G=Y.length>0?`set ${Y.join(" or ")} or run /login`:"run /login";throw new l("auth",`No credentials for provider "${$.provider}" (${G})`)}return{type:"apiKey",apiKey:W}}function QK($){let Z=process.env.CLOUDFLARE_ACCOUNT_ID;if(!Z)return;if($.provider==="cloudflare-workers-ai")return`https://api.cloudflare.com/client/v4/accounts/${Z}/ai/v1`;let Q=process.env.CLOUDFLARE_GATEWAY_ID;if(!Q)return;let W=`https://gateway.ai.cloudflare.com/v1/${Z}/${Q}`;if($.api==="anthropic-messages")return`${W}/anthropic`;if($.api==="openai-responses")return`${W}/openai`;return`${W}/compat`}function WK(){let $=process.env.AZURE_OPENAI_BASE_URL,Z=process.env.AZURE_OPENAI_RESOURCE_NAME;if(!$&&!Z)return;let Q=p0($??`https://${Z}.openai.azure.com`);return Q.endsWith("/openai/v1")?Q:`${Q}/openai/v1`}function YK(){let $=process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT,Z=process.env.GOOGLE_CLOUD_LOCATION;if(!$||!Z)return"https://aiplatform.googleapis.com/v1/publishers/google";return`https://${Z}-aiplatform.googleapis.com/v1/projects/${$}/locations/${Z}/publishers/google`}function GK(){return`https://bedrock-runtime.${process.env.AWS_REGION??process.env.AWS_DEFAULT_REGION??"us-east-1"}.amazonaws.com/openai/v1`}function XK($,Z){if(Z?.baseUrl)return p0(Z.baseUrl);if($.provider.startsWith("cloudflare-")){let Q=QK($);if(Q)return p0(Q)}if($.provider==="azure-openai-responses"){let Q=WK();if(Q)return p0(Q)}if($.provider==="google-vertex"){let Q=YK();if(Q)return p0(Q)}if($.provider==="amazon-bedrock")return GK();return p0(z6($)??"")}function p1($,Z){let Q=p0($),W=Z.startsWith("/")?Z:`/${Z}`;if(!Q)return W;if(W.startsWith("/v1/")&&Q.endsWith("/v1"))return`${Q}${W.slice(3)}`;return`${Q}${W}`}function Q1($,Z){let Q=m1($.provider),W={...Q?.headers,...$.headers};if(Z.type==="oauth")return{...W,authorization:`Bearer ${Z.accessToken}`,...Z.headers};if(Q?.auth==="anthropic")return{...W,"x-api-key":Z.apiKey};if(Q?.auth==="google")return{...W,"x-goog-api-key":Z.apiKey};if(Q?.auth==="azure")return{...W,"api-key":Z.apiKey};if(Q?.auth==="cloudflare")return{...W,"cf-aig-authorization":`Bearer ${Z.apiKey}`};return{...W,authorization:`Bearer ${Z.apiKey}`}}function W1($,Z,Q){if(Q?.baseUrl)return p0(Q.baseUrl);if(Z.type==="oauth"&&Z.baseUrl)return p0(Z.baseUrl);return XK($,Q)}function L6($,Z){return(Z.inputTokens*$.input+Z.outputTokens*$.output+Z.cacheReadTokens*$.cacheRead+Z.cacheWriteTokens*$.cacheWrite)/1e6}function w$(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0}}function j1($,Z){return{inputTokens:$.inputTokens+Z.inputTokens,outputTokens:$.outputTokens+Z.outputTokens,cacheReadTokens:$.cacheReadTokens+Z.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens+Z.cacheWriteTokens,costUsd:($.costUsd??0)+(Z.costUsd??0)}}class bZ{isComplete;extractResult;queue=[];waiting=[];done=!1;finalResult;resolveFinal;constructor($,Z){this.isComplete=$;this.extractResult=Z;this.finalResult=new Promise((Q)=>{this.resolveFinal=Q})}push($){if(this.done)return;if(this.isComplete($))this.done=!0,this.resolveFinal(this.extractResult($));let Z=this.waiting.shift();if(Z)Z({value:$,done:!1});else this.queue.push($)}end(){this.done=!0;while(this.waiting.length>0)this.waiting.shift()?.({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let $=await new Promise((Z)=>this.waiting.push(Z));if($.done)return;yield $.value}}result(){return this.finalResult}}class _Z extends bZ{constructor(){super(($)=>$.type==="done"||$.type==="error",($)=>{if($.type==="done")return $.message;if($.type==="error")return $.error;throw Error("unexpected final event")})}}function JK($){return{role:"assistant",content:[],model:`${$.provider}/${$.id}`,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0},stopReason:"end",timestamp:Date.now()}}function c0($,Z){Z.usage.costUsd=L6($.pricing,Z.usage)}function Y1($,Z,Q){let W=new _Z,Y=JK($);return(async()=>{try{if(await Q(W,Y),Z?.signal?.aborted)throw Error("Request was aborted");if(Y.stopReason==="error")throw new l("api",Y.errorMessage??"provider reported an error");W.push({type:"done",message:Y})}catch(G){Y.stopReason=Z?.signal?.aborted?"aborted":"error",Y.errorMessage=G instanceof Error?G.message:JSON.stringify(G),W.push({type:"error",reason:Y.stopReason,...G instanceof l?{errorKind:G.kind}:{},error:Y})}finally{W.end()}})(),W}async function G1($,Z,Q,W){let Y=W?.fetch??fetch,G;try{G=await Y($,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...Z},body:JSON.stringify(Q),...W?.signal?{signal:W.signal}:{}})}catch(X){if(W?.signal?.aborted)throw X;let J=X instanceof Error?X.message:String(X);throw new l("network",J)}if(!G.ok){let X=await G.text();throw j$(G.status,X,G.headers)}if(!G.body)throw new l("api","response has no body");return G}var KK="2023-06-01",U6={type:"ephemeral"};function fQ($){return $.filter((Z)=>Z.type!=="text"||Z.text.trim().length>0).map((Z)=>Z.type==="text"?{type:"text",text:Z.text}:{type:"image",source:{type:"base64",media_type:Z.mimeType,data:Z.data}})}function BK($){let Z=[];for(let Q of $)if(Q.type==="text"){if(Q.text.trim().length===0)continue;Z.push({type:"text",text:Q.text})}else if(Q.type==="thinking"){if(Q.redacted)Z.push({type:"redacted_thinking",data:Q.signature??""});else if(Q.signature)Z.push({type:"thinking",thinking:Q.thinking,signature:Q.signature});else if(Q.thinking.trim().length>0)Z.push({type:"text",text:Q.thinking})}else Z.push({type:"tool_use",id:Q.id,name:Q.name,input:Q.arguments??{}});return Z}function HK($,Z){let Q=[];for(let Y=0;Y<$.length;Y++){let G=$[Y];if(G.role==="user"){let X=fQ(G.content);if(X.length>0)Q.push({role:"user",content:X})}else if(G.role==="assistant"){let X=BK(G.content);if(X.length>0)Q.push({role:"assistant",content:X})}else{let X=[];while(Y<$.length){let J=$[Y];if(!J||J.role!=="toolResult")break;X.push({type:"tool_result",tool_use_id:J.toolCallId,content:fQ(J.content),is_error:J.isError}),Y++}Y--,Q.push({role:"user",content:X})}}let W=Q[Q.length-1];if(Z&&W&&W.role==="user"){let Y=W.content,G=Y[Y.length-1];if(G)G.cache_control=U6}return Q}function VK($,Z,Q){if(!$.thinking||Z===void 0)return;if(Z==="off"){Q.thinking={type:"disabled"};return}if($.thinkingMode==="budget"){let W={low:4096,medium:8192,high:16384};Q.thinking={type:"enabled",budget_tokens:W[Z]??8192,display:"summarized"};return}Q.thinking={type:"adaptive",display:"summarized"},Q.output_config={effort:Z}}function zK($,Z,Q){let W=$.provider==="anthropic",Y={model:$.id,max_tokens:Q?.maxTokens??$.maxOutput,messages:HK(Z.messages,W),stream:!0};if(Z.systemPrompt&&Z.systemPrompt.length>0){let G=Z.systemPrompt.reduce((X,J,K)=>J.dynamic?X:K,-1);Y.system=Z.systemPrompt.map((X,J)=>({type:"text",text:X.text,...W&&J===G?{cache_control:U6}:{}}))}if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((G,X)=>({name:G.name,description:G.description,input_schema:G.inputSchema,...W&&X===(Z.tools?.length??0)-1?{cache_control:U6}:{}}));if(Q?.temperature!==void 0)Y.temperature=Q.temperature;return VK($,Q?.thinkingLevel,Y),Y}function FK($){switch($){case"end_turn":case"stop_sequence":case"pause_turn":return{stopReason:"end"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:"The model refused to complete the request"};case"model_context_window_exceeded":return{stopReason:"error",errorMessage:"Context window exceeded"};default:return{stopReason:"end"}}}function vQ($,Z,Q){return Y1($,Q,async(W,Y)=>{let G=zK($,Z,Q),X=await m0(async()=>{let B=await Z1($,Q),z=W1($,B,Q),V={"anthropic-version":KK,...Q1($,B),...Q?.headers};return G1(p1(z,"/v1/messages"),V,G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});W.push({type:"start",partial:Y});let J=new Map,K=X.body;for await(let B of l0(K,Q?.signal)){if(B.event==="error")throw Error(B.data);if(!B.data)continue;let z=JSON.parse(B.data),V=z.type;if(V==="message_start"){let F=z.message?.usage;if(F)Y.usage.inputTokens=F.input_tokens??0,Y.usage.outputTokens=F.output_tokens??0,Y.usage.cacheReadTokens=F.cache_read_input_tokens??0,Y.usage.cacheWriteTokens=F.cache_creation_input_tokens??0,c0($,Y)}else if(V==="content_block_start"){let{index:F,content_block:D}=z,L=Y.content.length;J.set(F,{contentIndex:L,partialJson:""});let U=D.type;if(U==="text")Y.content.push({type:"text",text:""}),W.push({type:"text_start",contentIndex:L,partial:Y});else if(U==="thinking")Y.content.push({type:"thinking",thinking:"",signature:""}),W.push({type:"thinking_start",contentIndex:L,partial:Y});else if(U==="redacted_thinking")Y.content.push({type:"thinking",thinking:"[reasoning redacted]",signature:D.data??"",redacted:!0}),W.push({type:"thinking_start",contentIndex:L,partial:Y});else if(U==="tool_use")Y.content.push({type:"toolCall",id:D.id,name:D.name,arguments:D.input??{}}),W.push({type:"toolcall_start",contentIndex:L,partial:Y});else J.delete(F)}else if(V==="content_block_delta"){let F=J.get(z.index);if(!F)continue;let D=Y.content[F.contentIndex],L=z.delta,U=L.type;if(U==="text_delta"&&D?.type==="text")D.text+=L.text,W.push({type:"text_delta",contentIndex:F.contentIndex,delta:L.text,partial:Y});else if(U==="thinking_delta"&&D?.type==="thinking")D.thinking+=L.thinking,W.push({type:"thinking_delta",contentIndex:F.contentIndex,delta:L.thinking,partial:Y});else if(U==="input_json_delta"&&D?.type==="toolCall")F.partialJson+=L.partial_json,D.arguments=b0(F.partialJson),W.push({type:"toolcall_delta",contentIndex:F.contentIndex,delta:L.partial_json,partial:Y});else if(U==="signature_delta"&&D?.type==="thinking")D.signature=(D.signature??"")+L.signature}else if(V==="content_block_stop"){let F=J.get(z.index);if(!F)continue;let D=Y.content[F.contentIndex];if(D?.type==="text")W.push({type:"text_end",contentIndex:F.contentIndex,content:D.text,partial:Y});else if(D?.type==="thinking")W.push({type:"thinking_end",contentIndex:F.contentIndex,content:D.thinking,partial:Y});else if(D?.type==="toolCall")D.arguments=b0(F.partialJson),W.push({type:"toolcall_end",contentIndex:F.contentIndex,toolCall:D,partial:Y})}else if(V==="message_delta"){let F=z.delta;if(F?.stop_reason){let L=FK(F.stop_reason);if(Y.stopReason=L.stopReason,L.errorMessage)Y.errorMessage=L.errorMessage}let D=z.usage;if(D){if(D.input_tokens!=null)Y.usage.inputTokens=D.input_tokens;if(D.output_tokens!=null)Y.usage.outputTokens=D.output_tokens;if(D.cache_read_input_tokens!=null)Y.usage.cacheReadTokens=D.cache_read_input_tokens;if(D.cache_creation_input_tokens!=null)Y.usage.cacheWriteTokens=D.cache_creation_input_tokens;c0($,Y)}}}})}var T$={id:"anthropic",stream:vQ};function DK($){let Z=[],Q=new Map,W=(Y,G)=>{if(G.length===0)return;let X=Z[Z.length-1];if(X&&X.role===Y)X.parts.push(...G);else Z.push({role:Y,parts:G})};for(let Y of $)if(Y.role==="user")W("user",Y.content.map((G)=>G.type==="text"?{text:G.text}:{inlineData:{mimeType:G.mimeType,data:G.data}}));else if(Y.role==="assistant"){let G=[];for(let X of Y.content)if(X.type==="text"){if(X.text.trim().length>0)G.push({text:X.text})}else if(X.type==="thinking");else Q.set(X.id,X.name),G.push({functionCall:{name:X.name,args:X.arguments??{}},...X.signature?{thoughtSignature:X.signature}:{}});W("model",G)}else{let G=Q.get(Y.toolCallId)??Y.toolName,X=Y.content.filter((K)=>K.type==="text").map((K)=>K.text).join(`
13
+ `),J=[{functionResponse:{name:G,response:Y.isError?{error:X}:{output:X}}}];for(let K of Y.content)if(K.type==="image")J.push({inlineData:{mimeType:K.mimeType,data:K.data}});W("user",J)}return{contents:Z,toolNames:Q}}function LK($){switch($){case"off":case"none":return 0;case"minimal":return 512;case"low":return 2048;case"medium":return 8192;case"high":return 24576;case"xhigh":return 32768;case"max":return 49152;case"ultra":return 65536;default:return 8192}}function UK($,Z,Q){let W={contents:DK(Z.messages).contents};if(Z.systemPrompt&&Z.systemPrompt.length>0)W.systemInstruction={parts:Z.systemPrompt.map((G)=>({text:G.text}))};if(Z.tools&&Z.tools.length>0)W.tools=[{functionDeclarations:Z.tools.map((G)=>({name:G.name,description:G.description,parameters:G.inputSchema}))}];let Y={maxOutputTokens:Q?.maxTokens??$.maxOutput};if(Q?.temperature!==void 0)Y.temperature=Q.temperature;if($.thinking&&Q?.thinkingLevel)Y.thinkingConfig={thinkingBudget:LK(Q.thinkingLevel),includeThoughts:Q.thinkingLevel!=="off"&&Q.thinkingLevel!=="none"};return W.generationConfig=Y,W}function qK($,Z){switch($){case"STOP":return{stopReason:Z?"toolUse":"end"};case"MAX_TOKENS":return{stopReason:"length"};case"SAFETY":case"RECITATION":case"PROHIBITED_CONTENT":case"BLOCKLIST":return{stopReason:"error",errorMessage:`Generation stopped: ${$}`};default:return{stopReason:Z?"toolUse":"end"}}}function gQ($,Z,Q){return Y1($,Q,async(W,Y)=>{let G=UK($,Z,Q),X=await m0(async()=>{let U=await Z1($,Q);if(U.type!=="apiKey")throw new l("auth",`${$.provider} requires API-key auth`);let q=W1($,U,Q).replace(/\/+$/,""),A=$.provider==="google-vertex"?`/models/${$.id}:streamGenerateContent?alt=sse`:`/models/${$.id}:streamGenerateContent?alt=sse`,N=`${q}${A}`;return G1(N,{...Q1($,U),...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});W.push({type:"start",partial:Y});let J=-1,K=-1,B=0,z=!1,V,F=X.body,D=()=>{if(J!==-1){let U=Y.content[J];if(U?.type==="text")W.push({type:"text_end",contentIndex:J,content:U.text,partial:Y});J=-1}if(K!==-1){let U=Y.content[K];if(U?.type==="thinking")W.push({type:"thinking_end",contentIndex:K,content:U.thinking,partial:Y});K=-1}};for await(let U of l0(F,Q?.signal)){if(!U.data)continue;let q=JSON.parse(U.data),A=q.candidates?.[0],N=q.usageMetadata;if(N){let P=N.cachedContentTokenCount??0;Y.usage.inputTokens=(N.promptTokenCount??0)-P,Y.usage.cacheReadTokens=P,Y.usage.outputTokens=(N.candidatesTokenCount??0)+(N.thoughtsTokenCount??0),c0($,Y)}if(!A)continue;let j=A.content?.parts??[];for(let P of j)if(typeof P.text==="string")if(P.thought===!0){if(K===-1)K=Y.content.length,Y.content.push({type:"thinking",thinking:""}),W.push({type:"thinking_start",contentIndex:K,partial:Y});let O=Y.content[K];if(O?.type==="thinking"){if(O.thinking+=P.text,typeof P.thoughtSignature==="string")O.signature=P.thoughtSignature;W.push({type:"thinking_delta",contentIndex:K,delta:P.text,partial:Y})}}else{if(J===-1)J=Y.content.length,Y.content.push({type:"text",text:""}),W.push({type:"text_start",contentIndex:J,partial:Y});let O=Y.content[J];if(O?.type==="text")O.text+=P.text,W.push({type:"text_delta",contentIndex:J,delta:P.text,partial:Y})}else if(P.functionCall){z=!0;let O=P.functionCall,C=Y.content.length,v={type:"toolCall",id:`call_${B++}_${O.name}`,name:O.name,arguments:O.args??{},...typeof P.thoughtSignature==="string"?{signature:P.thoughtSignature}:{}};Y.content.push(v),W.push({type:"toolcall_start",contentIndex:C,partial:Y}),W.push({type:"toolcall_end",contentIndex:C,toolCall:v,partial:Y})}if(typeof A.finishReason==="string")V=A.finishReason}D();let L=qK(V??"STOP",z);if(Y.stopReason=L.stopReason,L.errorMessage)Y.errorMessage=L.errorMessage})}var I$={id:"google",stream:gQ};async function q6($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||Z.availableModelIds===void 0)return;let Q=new Set(Z.availableModelIds);return $.currentModels.filter((W)=>W.provider==="github-copilot"&&Q.has(W.id))}var mQ="https://chatgpt.com/backend-api/codex",AK=64,NK=128000,OK={input:0,output:0,cacheRead:0,cacheWrite:0};function lQ($){let Z=$?.trim();return Z?Z.slice(0,AK):void 0}function hQ($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function MK($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function uQ($){return typeof $==="string"&&$.length>0?$:void 0}function jK($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return;let Q=$;if(typeof Q.slug!=="string"||Q.slug.length===0||Q.supported_in_api===!1||typeof Q.visibility==="string"&&Q.visibility!=="list")return;let W=Z.find((F)=>F.provider==="openai-codex"&&F.id===Q.slug),Y=hQ(Q.context_window)??hQ(Q.max_context_window)??W?.contextWindow;if(!Y)return;let G=Array.isArray(Q.input_modalities)?Q.input_modalities.filter((F)=>typeof F==="string"):[],X=["text"];if(G.includes("image")||W?.modalities.includes("image"))X.push("image");let J=Array.isArray(Q.supported_reasoning_levels)?Q.supported_reasoning_levels.map((F)=>typeof F==="object"&&F!==null?uQ(F.effort):void 0).filter((F)=>F!==void 0):[],K=W?.thinkingLevels,B=J.length>0?J:K,z=uQ(Q.default_reasoning_level)??W?.defaultThinkingLevel,V=z&&(!B||B.includes(z))?z:void 0;return{provider:"openai-codex",id:Q.slug,...typeof Q.display_name==="string"?{name:Q.display_name}:{},contextWindow:Y,maxOutput:W?.maxOutput??NK,modalities:X,...B?.length||V||W?.thinking?{thinking:!0}:{},...B&&B.length>0?{thinkingLevels:B}:{},...V?{defaultThinkingLevel:V}:{},pricing:W?.pricing??OK,priority:MK(Q.priority)??Number.MAX_SAFE_INTEGER}}async function pQ($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||!Z.accountId)return;let Q=new URL(`${mQ}/models`);Q.searchParams.set("client_version",$.clientVersion??"0.0.0");let W=await($.fetch??fetch)(Q,{headers:{accept:"application/json",authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId,originator:"mu"},...$.signal?{signal:$.signal}:{}});if(!W.ok)throw j$(W.status,await W.text(),W.headers);let Y=await W.json();if(typeof Y!=="object"||Y===null||!Array.isArray(Y.models))throw Error("Could not discover ChatGPT models: invalid catalog response");let G=Y.models;if(G.length===0)return;let X=G.map((J)=>jK(J,$.currentModels)).filter((J)=>J!==void 0).sort((J,K)=>J.priority-K.priority).map(({priority:J,...K})=>K);if(X.length===0)throw Error("Could not discover ChatGPT models: catalog contained no compatible models");return X}function PK($,Z,Q){if(Q?.provider==="openai-codex"){if($.type!=="oauth"||!$.accountId)throw Error("OpenAI Codex requires a ChatGPT account credential");let Y=(Z?.baseUrl??mQ).replace(/\/+$/,""),G=lQ(Z?.sessionId);return{url:`${Y}/responses`,headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId,originator:"mu","openai-beta":"responses=experimental",...G?{"session-id":G,"x-client-request-id":G}:{}}}}if(!Q)throw Error("A model is required");let W=W1(Q,$,Z);return{url:p1(W,"/responses"),headers:Q1(Q,$)}}function wK($){let Z=[];for(let Q of $)if(Q.role==="user")Z.push({role:"user",content:Q.content.map((W)=>W.type==="text"?{type:"input_text",text:W.text}:{type:"input_image",image_url:`data:${W.mimeType};base64,${W.data}`})});else if(Q.role==="assistant")for(let W of Q.content)if(W.type==="text"){if(W.text.trim().length===0)continue;Z.push({role:"assistant",content:[{type:"output_text",text:W.text}]})}else if(W.type==="thinking"){if(!W.signature)continue;try{let Y=JSON.parse(W.signature);Z.push({type:"reasoning",id:Y.id,summary:[],...Y.encrypted_content?{encrypted_content:Y.encrypted_content}:{}})}catch{}}else Z.push({type:"function_call",call_id:W.id,name:W.name,arguments:JSON.stringify(W.arguments??{})});else{let W=Q.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
14
+ `);Z.push({type:"function_call_output",call_id:Q.toolCallId,output:W})}return Z}function TK($,Z,Q){let W=$.provider==="openai-codex",Y={model:$.id,input:wK(Z.messages),stream:!0,store:!1};if(!W)Y.max_output_tokens=Q?.maxTokens??$.maxOutput;if(Z.systemPrompt&&Z.systemPrompt.length>0)Y.instructions=Z.systemPrompt.map((G)=>G.text).join(`
15
+
16
+ `);else if(W)Y.instructions="You are a helpful assistant.";if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((G)=>({type:"function",name:G.name,description:G.description,parameters:G.inputSchema,strict:W?null:!1}));if(W){Y.text={verbosity:"low"},Y.include=["reasoning.encrypted_content"],Y.tool_choice="auto",Y.parallel_tool_calls=!0;let G=lQ(Q?.sessionId);if(G)Y.prompt_cache_key=G}if(Q?.temperature!==void 0)Y.temperature=Q.temperature;if($.thinking&&Q?.thinkingLevel&&Q.thinkingLevel!=="off"){if(Y.reasoning={effort:Q.thinkingLevel,summary:"auto"},!W)Y.include=["reasoning.encrypted_content"]}return Y}function A6($,Z,Q){return Y1($,Q,async(W,Y)=>{let G=TK($,Z,Q),X=await m0(async()=>{let z=await Z1($,Q),{url:V,headers:F}=PK(z,Q,$);return G1(V,{...F,...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});W.push({type:"start",partial:Y});let J=new Map,K=!1,B=X.body;for await(let z of l0(B,Q?.signal)){if(!z.data||z.data==="[DONE]")continue;let V=JSON.parse(z.data),F=V.type;if(F==="response.output_item.added"){let{item:D,output_index:L}=V,U=D.type,q=Y.content.length;if(U==="message")J.set(L,{contentIndex:q,kind:"text",partialJson:""}),Y.content.push({type:"text",text:""}),W.push({type:"text_start",contentIndex:q,partial:Y});else if(U==="reasoning")J.set(L,{contentIndex:q,kind:"reasoning",partialJson:""}),Y.content.push({type:"thinking",thinking:"",signature:JSON.stringify({id:D.id})}),W.push({type:"thinking_start",contentIndex:q,partial:Y});else if(U==="function_call")K=!0,J.set(L,{contentIndex:q,kind:"function_call",partialJson:""}),Y.content.push({type:"toolCall",id:D.call_id??D.id,name:D.name,arguments:{}}),W.push({type:"toolcall_start",contentIndex:q,partial:Y})}else if(F==="response.output_text.delta"){let D=J.get(V.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="text")L.text+=V.delta,W.push({type:"text_delta",contentIndex:D.contentIndex,delta:V.delta,partial:Y})}else if(F==="response.reasoning_summary_text.delta"){let D=J.get(V.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="thinking")L.thinking+=V.delta,W.push({type:"thinking_delta",contentIndex:D.contentIndex,delta:V.delta,partial:Y})}else if(F==="response.function_call_arguments.delta"){let D=J.get(V.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="toolCall")D.partialJson+=V.delta,L.arguments=b0(D.partialJson),W.push({type:"toolcall_delta",contentIndex:D.contentIndex,delta:V.delta,partial:Y})}else if(F==="response.output_item.done"){let D=J.get(V.output_index);if(!D)continue;let L=V.item,U=Y.content[D.contentIndex];if(U?.type==="text")W.push({type:"text_end",contentIndex:D.contentIndex,content:U.text,partial:Y});else if(U?.type==="thinking")U.signature=JSON.stringify({id:L.id,...L.encrypted_content?{encrypted_content:L.encrypted_content}:{}}),W.push({type:"thinking_end",contentIndex:D.contentIndex,content:U.thinking,partial:Y});else if(U?.type==="toolCall"){let q=L.arguments??D.partialJson;U.arguments=b0(q),W.push({type:"toolcall_end",contentIndex:D.contentIndex,toolCall:U,partial:Y})}}else if(F==="response.completed"||F==="response.incomplete"||F==="response.failed"){let D=V.response,L=D.usage;if(L){let q=L.input_tokens_details?.cached_tokens??0;Y.usage.inputTokens=(L.input_tokens??0)-q,Y.usage.cacheReadTokens=q,Y.usage.outputTokens=L.output_tokens??0,c0($,Y)}if(F==="response.completed")Y.stopReason=K?"toolUse":"end";else if(F==="response.incomplete"){let U=D.incomplete_details?.reason;Y.stopReason=U==="max_output_tokens"?"length":"end"}else{let U=D.error;Y.stopReason="error",Y.errorMessage=U?.message??"response failed"}}else if(F==="error")throw Error(V.message??z.data)}})}var E$={id:"openai",stream:A6},c1={id:"openai-codex",stream:A6,discoverModels:pQ};function IK($){return $.content.map((Z)=>Z.type==="text"?Z.text:`data:${Z.mimeType};base64,${Z.data}`).join(`
17
+ `)}function EK($){if($.content.every((Z)=>Z.type==="text"))return $.content.map((Z)=>Z.text).join(`
18
+ `);return $.content.map((Z)=>Z.type==="text"?{type:"text",text:Z.text}:{type:"image_url",image_url:{url:`data:${Z.mimeType};base64,${Z.data}`}})}function RK($,Z){let Q=[];if(Z&&Z.length>0)Q.push({role:"system",content:Z.map((W)=>W.text).join(`
19
+
20
+ `)});for(let W of $){if(W.role==="user"){Q.push({role:"user",content:EK(W)});continue}if(W.role==="toolResult"){Q.push({role:"tool",tool_call_id:W.toolCallId,content:IK(W)});continue}let Y=W.content.filter((J)=>J.type==="text").map((J)=>J.text).join(`
21
+ `),G=W.content.filter((J)=>J.type==="thinking").map((J)=>J.thinking).join(`
22
+ `),X=W.content.filter((J)=>J.type==="toolCall").map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:JSON.stringify(J.arguments??{})}}));if(!Y&&!G&&X.length===0)continue;Q.push({role:"assistant",content:Y||null,...G?{reasoning_content:G}:{},...X.length>0?{tool_calls:X}:{}})}return Q}function P1($){return $!==void 0&&$!=="off"}function CK($,Z,Q){if(!Z.thinking||Q===void 0)return;if(Z.provider==="zai"){if($.thinking={type:P1(Q)?"enabled":"disabled"},P1(Q)&&Z.id==="glm-5.2")$.reasoning_effort=Q;return}if(Z.provider.startsWith("qwen-token-plan")){$.enable_thinking=P1(Q);return}if(Z.provider==="deepseek"||Z.provider==="moonshotai"){if($.thinking={type:P1(Q)?"enabled":"disabled"},P1(Q))$.reasoning_effort=Q;return}if(Z.provider==="openrouter"){if(P1(Q))$.reasoning={effort:Q};return}if(P1(Q))$.reasoning_effort=Q}function SK($,Z,Q){let W={model:$.id,messages:RK(Z.messages,Z.systemPrompt),stream:!0,stream_options:{include_usage:!0},max_tokens:Q?.maxTokens??$.maxOutput};if(Z.tools&&Z.tools.length>0)W.tools=Z.tools.map((Y)=>({type:"function",function:{name:Y.name,description:Y.description,parameters:Y.inputSchema}})),W.tool_choice="auto";if(Q?.temperature!==void 0)W.temperature=Q.temperature;if(Q?.sessionId)if($.provider==="openrouter")W.user=Q.sessionId;else W.prompt_cache_key=Q.sessionId;return CK(W,$,Q?.thinkingLevel),W}function kZ($){return typeof $==="number"&&Number.isFinite($)?$:0}function N6($,Z,Q){return Y1($,Q,async(W,Y)=>{let G=SK($,Z,Q),X=await m0(async()=>{let V=await Z1($,Q),F=W1($,V,Q);return G1(p1(F,"/chat/completions"),{...Q1($,V),...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});W.push({type:"start",partial:Y});let J=-1,K=-1,B=new Map,z=X.body;for await(let V of l0(z,Q?.signal)){if(!V.data||V.data==="[DONE]")continue;let F=JSON.parse(V.data),D=F.usage;if(D){let N=D.prompt_tokens_details,j=kZ(N?.cached_tokens);Y.usage.inputTokens=Math.max(0,kZ(D.prompt_tokens)-j),Y.usage.cacheReadTokens=j,Y.usage.outputTokens=kZ(D.completion_tokens),c0($,Y)}let L=F.choices?.[0];if(!L)continue;let U=L.delta??{},q=typeof U.reasoning_content==="string"?U.reasoning_content:typeof U.reasoning==="string"?U.reasoning:"";if(q){if(K===-1)K=Y.content.length,Y.content.push({type:"thinking",thinking:""}),W.push({type:"thinking_start",contentIndex:K,partial:Y});let N=Y.content[K];if(N?.type==="thinking")N.thinking+=q,W.push({type:"thinking_delta",contentIndex:K,delta:q,partial:Y})}if(typeof U.content==="string"&&U.content){if(J===-1)J=Y.content.length,Y.content.push({type:"text",text:""}),W.push({type:"text_start",contentIndex:J,partial:Y});let N=Y.content[J];if(N?.type==="text")N.text+=U.content,W.push({type:"text_delta",contentIndex:J,delta:U.content,partial:Y})}for(let N of U.tool_calls??[]){let j=kZ(N.index),P=B.get(j),O=N.function??{};if(!P){let v=Y.content.length;P={contentIndex:v,partialJson:""},B.set(j,P),Y.content.push({type:"toolCall",id:String(N.id??`call_${j}`),name:String(O.name??""),arguments:{}}),W.push({type:"toolcall_start",contentIndex:v,partial:Y})}let C=Y.content[P.contentIndex];if(C?.type!=="toolCall")continue;if(typeof N.id==="string")C.id=N.id;if(typeof O.name==="string"&&O.name)C.name+=O.name;if(typeof O.arguments==="string")P.partialJson+=O.arguments,C.arguments=b0(P.partialJson),W.push({type:"toolcall_delta",contentIndex:P.contentIndex,delta:O.arguments,partial:Y})}let A=L.finish_reason;if(typeof A==="string")Y.stopReason=A==="length"?"length":A==="tool_calls"||B.size>0?"toolUse":"end"}if(K!==-1){let V=Y.content[K];if(V?.type==="thinking")W.push({type:"thinking_end",contentIndex:K,content:V.thinking,partial:Y})}if(J!==-1){let V=Y.content[J];if(V?.type==="text")W.push({type:"text_end",contentIndex:J,content:V.text,partial:Y})}for(let V of B.values()){let F=Y.content[V.contentIndex];if(F?.type!=="toolCall")continue;F.arguments=b0(V.partialJson),W.push({type:"toolcall_end",contentIndex:V.contentIndex,toolCall:F,partial:Y})}if(B.size>0&&Y.stopReason==="end")Y.stopReason="toolUse"})}var yK=new Map([[T$.id,T$],[E$.id,E$],[c1.id,c1],[I$.id,I$]]);function bK($){let Z=yK.get($);if(Z)return Z;return{id:$,stream:(Q,W,Y)=>{switch(P$(Q)){case"anthropic-messages":return T$.stream(Q,W,Y);case"google-generative-ai":case"google-vertex":return I$.stream(Q,W,Y);case"openai-responses":return E$.stream(Q,W,Y);default:return N6(Q,W,Y)}},...$==="github-copilot"?{discoverModels:q6}:{}}}var d1=new Map([...u0.keys()].map(($)=>[$,bK($)]));d1.set(c1.id,c1);function O6($){let Z=d1.get($);if(!Z)throw Error(`Unknown provider: ${$}`);return Z}function cQ($){d1.set($.id,$)}var _K="https://models.dev/api.json",kK=15000,i1={input:0,output:0,cacheRead:0,cacheWrite:0},xK=[{source:"amazon-bedrock",providers:["amazon-bedrock"]},{source:"anthropic",providers:["anthropic"]},{source:"cerebras",providers:["cerebras"]},{source:"cloudflare-ai-gateway",providers:["cloudflare-ai-gateway"]},{source:"cloudflare-workers-ai",providers:["cloudflare-workers-ai"]},{source:"deepseek",providers:["deepseek"]},{source:"fireworks-ai",providers:["fireworks"]},{source:"github-copilot",providers:["github-copilot"]},{source:"google",providers:["google"]},{source:"google-vertex",providers:["google-vertex"]},{source:"groq",providers:["groq"]},{source:"huggingface",providers:["huggingface"]},{source:"kimi-for-coding",providers:["kimi-coding"]},{source:"minimax",providers:["minimax"]},{source:"mistral",providers:["mistral"]},{source:"moonshotai",providers:["moonshotai"]},{source:"nvidia",providers:["nvidia"]},{source:"openai",providers:["openai","azure-openai-responses"]},{source:"opencode",providers:["opencode"]},{source:"opencode-go",providers:["opencode-go"]},{source:"openrouter",providers:["openrouter"]},{source:"alibaba-token-plan",providers:["qwen-token-plan"]},{source:"vercel-ai-gateway",providers:["vercel-ai-gateway"]},{source:"xai",providers:["xai"]},{source:"zai-coding-plan",providers:["zai"]}],fK=[{provider:"github-copilot",id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",contextWindow:128000,maxOutput:32000,modalities:["text","image"],thinking:!0,pricing:i1},{provider:"kimi-coding",id:"kimi-for-coding",name:"Kimi For Coding",api:"anthropic-messages",contextWindow:262144,maxOutput:65536,modalities:["text"],thinking:!0,pricing:i1},{provider:"openrouter",id:"auto",name:"OpenRouter Auto",api:"openai-completions",contextWindow:2000000,maxOutput:30000,modalities:["text","image"],thinking:!0,pricing:i1},{provider:"xai",id:"grok-4.3",name:"Grok 4.3",api:"openai-completions",contextWindow:256000,maxOutput:64000,modalities:["text","image"],thinking:!0,pricing:i1},{provider:"zai",id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",contextWindow:202752,maxOutput:65536,modalities:["text"],thinking:!0,pricing:i1},{provider:"qwen-token-plan",id:"qwen3.7-max",name:"Qwen3.7 Max",api:"openai-completions",contextWindow:1e6,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:i1}],j6=[...SQ.models,...fK],H0=[...j6],iQ=new Set;function F0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function X1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function M6($){return Array.isArray($)?$.filter((Z)=>typeof Z==="string"):[]}function vK($){if($.tool_call!==!0||$.status==="deprecated")return!1;let Z=F0($.limit)?$.limit:{};if((X1(Z.context)??0)<=0||(X1(Z.output)??0)<=0)return!1;if(!F0($.modalities))return!0;let Q=M6($.modalities.input),W=M6($.modalities.output);return Q.includes("text")&&W.includes("text")}function gK($){if(!Array.isArray($.reasoning_options))return"budget";return $.reasoning_options.some((Z)=>F0(Z)&&Z.type==="effort")?"adaptive":"budget"}function hK($){if(!Array.isArray($.reasoning_options))return;let Z=[];for(let Q of $.reasoning_options){if(!F0(Q)||Q.type!=="effort"||!Array.isArray(Q.values))continue;for(let W of Q.values){if(typeof W!=="string"||W.length===0||W==="default")continue;if(!Z.includes(W))Z.push(W)}}return Z.length>0?Z:void 0}function uK($,Z){if($==="cloudflare-ai-gateway"&&typeof Z.id==="string"){if(Z.id.startsWith("openai/"))return"openai-responses";if(Z.id.startsWith("anthropic/"))return"anthropic-messages";return"openai-completions"}if($==="fireworks"&&typeof Z.id==="string"&&Z.id.includes("glm-5p2"))return"openai-completions";if($==="github-copilot"){if(typeof Z.id==="string"&&/^claude-(haiku|sonnet|opus)-[45](?=[.-]|$)/.test(Z.id))return"anthropic-messages";if(typeof Z.id==="string"&&(Z.id.startsWith("gpt-5")||Z.id.startsWith("oswe")||Z.id.startsWith("mai-")))return"openai-responses";return"openai-completions"}if($==="xai"&&Z.id==="grok-4.5")return"openai-responses";if($==="opencode"||$==="opencode-go"){let Q=F0(Z.provider)?Z.provider.npm:void 0;if(Q==="@ai-sdk/openai")return"openai-responses";if(Q==="@ai-sdk/anthropic")return"anthropic-messages";if(Q==="@ai-sdk/google")return"google-generative-ai";return"openai-completions"}return P$({provider:$,id:"",contextWindow:1,maxOutput:1,modalities:["text"],pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}})}function nQ($,Z){if(typeof Z.id!=="string")return;let Q=uK($,Z),W=Z.id,Y=u0.get($)?.baseUrl;if($==="cloudflare-ai-gateway"){let G=W.indexOf("/"),X=G===-1?"":W.slice(0,G);if(X==="openai"||X==="anthropic")W=W.slice(G+1)}else if($==="fireworks"&&Q==="openai-completions")Y="https://api.fireworks.ai/inference/v1";else if(($==="opencode"||$==="opencode-go")&&Q==="anthropic-messages")Y=Y?.replace(/\/v1$/,"");return{id:W,api:Q,...Y?{baseUrl:Y}:{}}}function mK($,Z){if(!vK(Z)||typeof Z.id!=="string")return;let Q=F0(Z.limit)?Z.limit:{},W=X1(Q.context),Y=X1(Q.output);if(W===void 0||Y===void 0)return;let G=F0(Z.cost)?Z.cost:{},X=F0(Z.modalities)?M6(Z.modalities.input):["text"],J=["text"];if(X.includes("image"))J.push("image");let K=Z.reasoning===!0,B=K?hK(Z):void 0,z=nQ($,Z);if(!z)return;return{provider:$,id:z.id,...typeof Z.name==="string"?{name:Z.name}:{},api:z.api,...z.baseUrl?{baseUrl:z.baseUrl}:{},contextWindow:W,maxOutput:Y,modalities:J,...K?{thinking:!0}:{},...B?{thinkingLevels:B}:{},...K&&$==="anthropic"?{thinkingMode:gK(Z)}:{},pricing:{input:X1(G.input)??0,output:X1(G.output)??0,cacheRead:X1(G.cache_read)??0,cacheWrite:X1(G.cache_write)??0}}}async function lK($){let Z=await($.fetch??fetch)($.url??_K,{headers:{accept:"application/json"},signal:$.signal??AbortSignal.timeout(kK)});if(!Z.ok)throw Error(`Could not discover models: ${Z.status} ${Z.statusText}`.trim());let Q=await Z.json();if(!F0(Q))throw Error("Could not discover models: invalid catalog response");let W=[],Y=new Set;for(let G of xK){let X=Q[G.source];if(!F0(X)||!F0(X.models))continue;for(let J of G.providers){let K=0;for(let[B,z]of Object.entries(X.models)){if(!F0(z))continue;let V=typeof z.id==="string"?z:{...z,id:B},F=mK(J,V);if(F)W.push(F),K++}if(K>0)Y.add(J)}}if(W.length===0)throw Error("Could not discover models: catalog contained no compatible models");return{models:W,authoritativeProviders:Y}}function dQ($){return $ instanceof Error?$.message:String($)}async function aQ($){let Z=[],Q=new Set,W=[],Y=H0;try{let K=await lK($);Z.push(...K.models);for(let z of K.authoritativeProviders)Q.add(z);let B=new Map(H0.map((z)=>[`${z.provider}/${z.id}`,z]));for(let z of K.models)B.set(`${z.provider}/${z.id}`,z);Y=[...B.values()]}catch(K){W.push(dQ(K))}let G=[],X=$.getCredentials;for(let K of $.providers??d1.values()){if(!K.discoverModels)continue;G.push(K.discoverModels({...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{},...X?{getCredentials:()=>X(K.id)}:{},...$.clientVersion?{clientVersion:$.clientVersion}:{},currentModels:Y}).then((B)=>{if(B===void 0)return;if(B.length===0)throw Error(`Could not discover ${K.id} models: catalog returned no models`);return{models:B,authoritativeProviders:new Set([K.id])}}))}let J=await Promise.allSettled(G);for(let K of J){if(K.status==="rejected"){W.push(dQ(K.reason));continue}if(!K.value)continue;for(let B of K.value.authoritativeProviders){for(let z=Z.length-1;z>=0;z--)if(Z[z]?.provider===B)Z.splice(z,1);Q.add(B)}Z.push(...K.value.models)}if(Q.size===0)throw Error(W[0]??"Could not discover models: no discovery source was available");for(let K of W)$.onWarning?.(K);return{models:Z,authoritativeProviders:Q}}async function rQ($={}){return(await aQ($)).models}async function tQ($={}){let Z=await aQ($);for(let W of Z.authoritativeProviders)iQ.add(W);let Q=H0.filter((W)=>!Z.authoritativeProviders.has(W.provider));for(let W of j6){if(Z.authoritativeProviders.has(W.provider))continue;if(!Q.some((Y)=>Y.provider===W.provider&&Y.id===W.id))Q.push(W)}for(let W of Z.models){let Y=Q.findIndex((G)=>G.provider===W.provider&&G.id===W.id);if(Y===-1)Q.push(W);else Q[Y]=W}return H0=Q,R$()}function R$(){return[...H0]}function oQ($){for(let Z of $){let Q=H0.findIndex((W)=>W.provider===Z.provider&&W.id===Z.id);if(Q===-1)H0.push(Z);else H0[Q]=Z}}function w1($){let Z=$.indexOf("/");if(Z!==-1){let Q=$.slice(0,Z),W=$.slice(Z+1),Y=H0.find((J)=>J.provider===Q&&J.id===W);if(Y)return Y;if(iQ.has(Q))return;if(!u0.get(Q)||!W)return;let X=nQ(Q,{id:W});if(!X)return;return{provider:Q,id:X.id,name:X.id,api:X.api,...X.baseUrl?{baseUrl:X.baseUrl}:{},contextWindow:128000,maxOutput:32000,modalities:["text","image"],thinking:!0,pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}}}return H0.find((Q)=>Q.id===$)}function sQ($){return`${$.provider}/${$.id}`}function P6($,Z=process.env){if($==="openai-codex")return!1;let Q=l1($);return Q.length===0||Q.some((W)=>Boolean(Z[W]))}var pK={"openai-codex":"gpt-5.6-sol",openai:"gpt-5.6-sol",anthropic:"claude-opus-5",google:"gemini-2.5-pro"};function cK($){for(let Z of $){let Q=H0.filter((G)=>G.provider===Z);if(Q.length===0)continue;let W=pK[Z];return(W?Q.find((G)=>G.id===W):void 0)??Q[0]}return}function n1($=process.env,Z){let Q=Z?[...Z]:[...new Set(H0.map((Y)=>Y.provider))].filter((Y)=>P6(Y,$)),W=cK(Q)??w1("openai-codex/gpt-5.6-sol")??H0[0]??j6[0];if(!W)throw Error("No models are available");return sQ(W)}var dK=["off","low","medium","high"];function a1($){if(!$.thinking)return["off"];if($.thinkingLevels&&$.thinkingLevels.length>0)return[...new Set($.thinkingLevels)];return[...dK]}function w6($){let Z=a1($);if($.defaultThinkingLevel&&Z.includes($.defaultThinkingLevel))return $.defaultThinkingLevel;return Z[0]??"off"}function d0($,Z){let Q=a1($);if(Z&&Q.includes(Z))return Z;return w6($)}function C$($){if($.stopReason!=="error")return!1;return yZ($.errorMessage??"")}var iK=3.5;function p($){let Z=0;for(let Q of $)if(Q.role==="toolResult"||Q.role==="user"||Q.role==="custom")for(let W of Q.content)Z+=W.type==="text"?W.text.length:1500;else for(let W of Q.content)if(W.type==="text")Z+=W.text.length;else if(W.type==="thinking")Z+=W.thinking.length;else Z+=JSON.stringify(W.arguments).length+W.name.length;return Math.ceil(Z/iK)}function y$($,Z,Q,W){let Y=p(Z),G=Q?Q.inputTokens+Q.cacheReadTokens+Q.cacheWriteTokens:0,X=Q&&W!==void 0?Math.max(0,Y-W):0,J=Math.max(G+X,Y),K=$.contextWindow;return{tokens:J,limit:K,percent:K>0?J/K:0}}var T1=0.85;function E6($,Z=T1){return $.percent>=Z}class _0 extends Error{usage;constructor($,Z){super($);this.usage=Z;this.name="CompactionError"}}var r1=20000;function nK($,Z){for(let Q=Math.min(Z,$.length-1);Q>=0;Q--)if($[Q]?.role==="user")return Q;return null}function $W($,Z=r1){if($.length<=4&&p($)<=Z)return{keepFromIndex:$.length,keptTokens:0,isSplitTurn:!1,turnStartIndex:null};let Q=0,W=$.length;while(W>0&&Q<Z){let X=W-1,J=p([$[X]]);if(Q>0&&Q+J>Z)break;W=X,Q+=J}while(W>0&&$[W]?.role==="toolResult")W--,Q+=p([$[W]]);if(W===0){if($.length===1)W=$.length;else if(W=$.findIndex((X,J)=>J>0&&X.role!=="toolResult"),W<0)W=$.length;Q=p($.slice(W))}let Y=W<$.length?nK($,W):null,G=Y!==null&&Y<W;return{keepFromIndex:W,keptTokens:Q,isSplitTurn:G,turnStartIndex:Y}}var T6=`Summarize the conversation so far so that work can continue without the original transcript.
12
23
 
13
24
  Preserve, in this order:
14
25
  1. What the user asked for \u2014 the goal, in their terms, including any constraints they stated.
@@ -17,59 +28,71 @@ Preserve, in this order:
17
28
  4. Concrete facts discovered that would be expensive to rediscover (file locations, API shapes, error messages, command invocations that work).
18
29
  5. Anything the user corrected you on.
19
30
 
20
- Be specific and factual. Do not include pleasantries or narration. This summary replaces the transcript, so anything you omit is lost.`;async function s5($,Z){let{keepFromIndex:W}=F4($,Z.keepRatio),Q=$.slice(0,W),Y=$.slice(W);if(Q.length===0)return{summary:"",keptMessages:$,tokensFreed:0,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0}};let G=Z.carryoverExtractor?.(Q);if(G!==void 0)AZ(G);let X={systemPrompt:[{text:D4}],messages:[...F$(Q),{role:"user",content:[{type:"text",text:"Produce the summary now."}],timestamp:Date.now()}]},K=await Z.provider.stream(Z.model,X,{...Z.streamOpts,...Z.signal?{signal:Z.signal}:{}}).result();if(K.stopReason!=="end")throw new x0(`Compaction failed: ${K.errorMessage??`incomplete response (${K.stopReason})`}`,K.usage);let H=K.content.filter((z)=>z.type==="text").map((z)=>z.text).join("").trim();if(H.length===0)throw new x0("Compaction failed: the provider returned no usable summary",K.usage);let V={summary:H,...G!==void 0?{carryover:G}:{},keptMessages:Y,tokensFreed:0,usage:K.usage};return V.tokensFreed=Math.max(0,S0($)-S0(qZ(V))),V}function qZ($){if($.summary.length===0)return $.keptMessages;return[U$($.summary,$.carryover),...$.keptMessages]}function U$($,Z,W=Date.now()){let Q=Z===void 0?"":`
31
+ Be specific and factual. Do not include pleasantries or narration. This summary replaces the transcript, so anything you omit is lost.`,aK="The retained transcript begins part-way through a large user turn. Preserve the original request and the early progress needed to understand the retained suffix. Do not imply that the retained suffix starts a new task.",rK=2000,tK=4000,oK=3;function eQ($,Z){if($.length<=Z)return $;return`${$.slice(0,Z)}
32
+ [... ${$.length-Z} characters omitted]`}function S$($){return $.content.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
33
+ `)}function ZW($){let Z=[];for(let Q of $){if(Q.role==="user"){let X=S$(Q);if(X)Z.push(`[User]
34
+ ${X}`);if(Q.content.some((J)=>J.type==="image"))Z.push("[User image omitted from compaction input]");continue}if(Q.role==="custom"){let X=S$(Q);if(X)Z.push(`[Injected context: ${Q.customType}]
35
+ ${X}`);continue}if(Q.role==="toolResult"){let X=eQ(S$(Q),rK);Z.push(`[Tool result: ${Q.toolName}${Q.isError?" (error)":""}]
36
+ ${X||"(non-text output omitted)"}`);continue}let W=Q.content.filter((X)=>X.type==="thinking").map((X)=>X.thinking).join(`
37
+ `),Y=S$(Q),G=Q.content.filter((X)=>X.type==="toolCall").map((X)=>`${X.name}(${eQ(JSON.stringify(X.arguments),tK)})`).join(`
38
+ `);if(W)Z.push(`[Assistant thinking]
39
+ ${W}`);if(Y)Z.push(`[Assistant]
40
+ ${Y}`);if(G)Z.push(`[Assistant tool calls]
41
+ ${G}`)}return Z.join(`
21
42
 
22
- Carried forward:
23
- ${L4(Z)}`;return{role:"custom",customType:"compaction-summary",content:[{type:"text",text:`Summary of the earlier conversation:
43
+ `)}async function fZ($,Z){let Q=Z.keepRecentTokens??Math.min(r1,Math.max(2,Math.floor(Z.model.contextWindow*0.2))),W=$W($,Q),{keepFromIndex:Y}=W,G=$.slice(0,Y),X=$.slice(Y);if(G.length===0)return{summary:"",keptMessages:$,tokensFreed:0,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0}};let J=Z.carryoverExtractor?.(G);if(J!==void 0)xZ(J);let K=G.findIndex((U)=>U.role==="custom"&&U.customType==="compaction-summary"),B=K===-1?void 0:S$(G[K]),z=G.filter((U,q)=>q!==K),V,F=0;for(;;){let U=[T6,B?"Update the previous summary with the newly summarized conversation.":"",W.isSplitTurn?aK:"",Z.customInstructions?`Additional focus from the user: ${Z.customInstructions}`:""].filter(Boolean).join(`
24
44
 
25
- ${$}${Q}`}],display:!1,timestamp:W}}function L4($){if(typeof $==="string")return $;return AZ($),JSON.stringify(r5($),null,2)}function AZ($,Z=new Set){if($===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return;if(typeof $!=="object")throw new x0("Compaction failed: carryover must be JSON-serializable");let W=Object.getPrototypeOf($);if(!Array.isArray($)&&W!==Object.prototype&&W!==null)throw new x0("Compaction failed: carryover must contain only plain objects");if(Z.has($))throw new x0("Compaction failed: carryover must not contain cycles");if(Z.add($),Array.isArray($))for(let Q of $)AZ(Q,Z);else for(let Q of Object.values($))AZ(Q,Z);Z.delete($)}function r5($){if(Array.isArray($))return $.map(r5);if($&&typeof $==="object")return Object.fromEntries(Object.entries($).sort(([Z],[W])=>Z<W?-1:Z>W?1:0).map(([Z,W])=>[Z,r5(W)]));return $}class e5{tools=new Map;commands=new L1;providers=new Map;models=new Map;renderers=new Map;logs=[];extensions=[];eventHandlers=new Map;toolCallHooks=[];toolResultHooks=[];contextHooks=[];inputHooks=[];async register($){let Z={on:(W,Q)=>{let Y=this.eventHandlers.get(W)??[];Y.push(Q),this.eventHandlers.set(W,Y)},onToolCall:(W)=>void this.toolCallHooks.push(W),onToolResult:(W)=>void this.toolResultHooks.push(W),onContext:(W)=>void this.contextHooks.push(W),onInput:(W)=>void this.inputHooks.push(W),registerTool:(W)=>void this.tools.set(W.name,W),registerCommand:(W)=>this.commands.register(W),registerProvider:(W)=>void this.providers.set(W.id,W),registerModels:(W)=>{for(let Q of W)this.models.set(`${Q.provider}/${Q.id}`,Q)},registerRenderer:(W,Q)=>void this.renderers.set(W,Q),log:(W)=>void this.logs.push(`[${$.name}] ${W}`)};await $.activate(Z),this.extensions.push($)}async shutdown(){for(let $ of this.extensions)await $.deactivate?.();this.extensions=[]}emit($){for(let Z of this.eventHandlers.get($.type)??[])Z($)}emitLifecycle($){for(let Z of this.eventHandlers.get($.type)??[])Z($)}findModel($){if($.indexOf("/")!==-1)return this.models.get($);return[...this.models.values()].find((W)=>W.id===$)}async runToolCallHooks($){let Z=$.args;for(let W of this.toolCallHooks){let Q=await W({...$,args:Z});if(Q?.block)return Q;if(Q?.args)Z=Q.args}return Z===$.args?void 0:{args:Z}}async runToolResultHooks($){let Z=$.result.content,W=$.isError,Q=!1;for(let Y of this.toolResultHooks){let G=await Y({...$,result:{...$.result,content:Z},isError:W});if(!G)continue;if(G.content)Z=G.content,Q=!0;if(G.isError!==void 0)W=G.isError,Q=!0}return Q?{content:Z,isError:W}:void 0}async runContextHooks($){let Z=$;for(let W of this.contextHooks)Z=await W(Z);return Z}async runInputHooks($){let Z=$;for(let W of this.inputHooks){let Q=await W(Z);if(Q?.consume)return{consume:!0,...Q.text!==void 0?{text:Q.text}:{}};if(Q?.text!==void 0)Z=Q.text}return Z===$?void 0:{text:Z}}get hasContextHooks(){return this.contextHooks.length>0}}var LK=new Set(["rate_limit","overloaded","network"]);class l extends Error{kind;status;retryAfterMs;constructor($,Z,W){super(Z);if(this.name="AiError",this.kind=$,W?.status!==void 0)this.status=W.status;if(W?.retryAfterMs!==void 0)this.retryAfterMs=W.retryAfterMs}get retryable(){return LK.has(this.kind)}}var UK=[/prompt is too long/i,/context window/i,/context[_ ]length[_ ]exceeded/i,/exceeds the maximum number of tokens/i,/input token count.*exceeds/i,/too many total text bytes/i];function OZ($){return UK.some((Z)=>Z.test($))}function AK($){let Z=$.get("retry-after-ms");if(Z){let Q=Number.parseFloat(Z);if(!Number.isNaN(Q))return Q}let W=$.get("retry-after");if(W){let Q=Number.parseFloat(W);if(!Number.isNaN(Q))return Q*1000;let Y=Date.parse(W);if(!Number.isNaN(Y))return Y-Date.now()}return}function A$($,Z,W){let Q={status:$,retryAfterMs:AK(W)};if($===401||$===403)return new l("auth",Z,Q);if($===404)return new l("not_found",Z,Q);if($===429)return new l("rate_limit",Z,Q);if($===529||$===503)return new l("overloaded",Z,Q);if($>=500)return new l("api",Z,Q);if(OZ(Z))return new l("context_too_long",Z,Q);return new l("bad_request",Z,Q)}var U4={models:[{provider:"anthropic",id:"claude-opus-5",name:"Claude Opus 5",contextWindow:1e6,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingMode:"adaptive",pricing:{input:5,output:25,cacheRead:0.5,cacheWrite:6.25}},{provider:"anthropic",id:"claude-sonnet-5",name:"Claude Sonnet 5",contextWindow:1e6,maxOutput:128000,modalities:["text","image"],thinking:!0,thinkingMode:"adaptive",pricing:{input:3,output:15,cacheRead:0.3,cacheWrite:3.75}},{provider:"anthropic",id:"claude-haiku-4-5",name:"Claude Haiku 4.5",contextWindow:200000,maxOutput:64000,modalities:["text","image"],thinking:!0,thinkingMode:"budget",pricing:{input:1,output:5,cacheRead:0.1,cacheWrite:1.25}},{provider:"openai",id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:5,output:30,cacheRead:0.5,cacheWrite:6.25}},{provider:"openai",id:"gpt-5.1",name:"GPT-5.1",contextWindow:400000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:1.25,output:10,cacheRead:0.125,cacheWrite:0}},{provider:"openai",id:"gpt-5-mini",name:"GPT-5 mini",contextWindow:400000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:0.25,output:2,cacheRead:0.025,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-sol",name:"GPT-5.6 Sol",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-terra",name:"GPT-5.6 Terra",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"openai-codex",id:"gpt-5.6-luna",name:"GPT-5.6 Luna",contextWindow:272000,maxOutput:128000,modalities:["text","image"],thinking:!0,pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}},{provider:"google",id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",contextWindow:1048576,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:{input:1.25,output:10,cacheRead:0.31,cacheWrite:0}},{provider:"google",id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",contextWindow:1048576,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:{input:0.3,output:2.5,cacheRead:0.075,cacheWrite:0}}]};var OK=[{id:"amazon-bedrock",name:"Amazon Bedrock",api:"openai-responses",env:["AWS_BEARER_TOKEN_BEDROCK"]},{id:"anthropic",name:"Anthropic",api:"anthropic-messages",baseUrl:"https://api.anthropic.com",env:["ANTHROPIC_API_KEY"],auth:"anthropic"},{id:"azure-openai-responses",name:"Azure OpenAI",api:"openai-responses",env:["AZURE_OPENAI_API_KEY"],auth:"azure"},{id:"cerebras",name:"Cerebras",api:"openai-completions",baseUrl:"https://api.cerebras.ai/v1",env:["CEREBRAS_API_KEY"]},{id:"cloudflare-ai-gateway",name:"Cloudflare AI Gateway",api:"openai-completions",env:["CLOUDFLARE_API_KEY"],auth:"cloudflare"},{id:"cloudflare-workers-ai",name:"Cloudflare Workers AI",api:"openai-completions",env:["CLOUDFLARE_API_KEY"]},{id:"deepseek",name:"DeepSeek",api:"openai-completions",baseUrl:"https://api.deepseek.com",env:["DEEPSEEK_API_KEY"]},{id:"fireworks",name:"Fireworks",api:"anthropic-messages",baseUrl:"https://api.fireworks.ai/inference",env:["FIREWORKS_API_KEY"],auth:"anthropic"},{id:"github-copilot",name:"GitHub Copilot",api:"openai-responses",baseUrl:"https://api.individual.githubcopilot.com",env:["COPILOT_GITHUB_TOKEN"],headers:{"user-agent":"GitHubCopilotChat/0.35.0","editor-version":"vscode/1.107.0","editor-plugin-version":"copilot-chat/0.35.0","copilot-integration-id":"vscode-chat"}},{id:"google",name:"Google",api:"google-generative-ai",baseUrl:"https://generativelanguage.googleapis.com/v1beta",env:["GEMINI_API_KEY"],auth:"google"},{id:"google-vertex",name:"Google Vertex AI",api:"google-vertex",env:["GOOGLE_CLOUD_API_KEY"],auth:"google"},{id:"groq",name:"Groq",api:"openai-completions",baseUrl:"https://api.groq.com/openai/v1",env:["GROQ_API_KEY"]},{id:"huggingface",name:"Hugging Face",api:"openai-completions",baseUrl:"https://router.huggingface.co/v1",env:["HF_TOKEN"]},{id:"kimi-coding",name:"Kimi For Coding",api:"anthropic-messages",baseUrl:"https://api.kimi.com/coding",env:["KIMI_API_KEY"],auth:"anthropic",headers:{"user-agent":"KimiCLI/1.5"}},{id:"minimax",name:"MiniMax",api:"anthropic-messages",baseUrl:"https://api.minimax.io/anthropic",env:["MINIMAX_API_KEY"],auth:"anthropic"},{id:"mistral",name:"Mistral",api:"openai-completions",baseUrl:"https://api.mistral.ai/v1",env:["MISTRAL_API_KEY"]},{id:"moonshotai",name:"Moonshot AI",api:"openai-completions",baseUrl:"https://api.moonshot.ai/v1",env:["MOONSHOT_API_KEY"]},{id:"nvidia",name:"NVIDIA NIM",api:"openai-completions",baseUrl:"https://integrate.api.nvidia.com/v1",env:["NVIDIA_API_KEY"],headers:{"nvcf-poll-seconds":"3600"}},{id:"openai",name:"OpenAI",api:"openai-responses",baseUrl:"https://api.openai.com/v1",env:["OPENAI_API_KEY"]},{id:"openai-codex",name:"OpenAI Codex",api:"openai-responses",baseUrl:"https://chatgpt.com/backend-api/codex",env:[]},{id:"opencode",name:"OpenCode Zen",api:"openai-completions",baseUrl:"https://opencode.ai/zen/v1",env:["OPENCODE_API_KEY"]},{id:"opencode-go",name:"OpenCode Go",api:"openai-completions",baseUrl:"https://opencode.ai/zen/go/v1",env:["OPENCODE_API_KEY"]},{id:"openrouter",name:"OpenRouter",api:"openai-completions",baseUrl:"https://openrouter.ai/api/v1",env:["OPENROUTER_API_KEY"]},{id:"qwen-token-plan",name:"Qwen Token Plan",api:"openai-completions",baseUrl:"https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",env:["QWEN_TOKEN_PLAN_API_KEY"]},{id:"vercel-ai-gateway",name:"Vercel AI Gateway",api:"anthropic-messages",baseUrl:"https://ai-gateway.vercel.sh",env:["AI_GATEWAY_API_KEY"],auth:"anthropic"},{id:"xai",name:"xAI",api:"openai-completions",baseUrl:"https://api.x.ai/v1",env:["XAI_API_KEY"]},{id:"zai",name:"Z.AI Coding Plan",api:"openai-completions",baseUrl:"https://api.z.ai/api/coding/paas/v4",env:["ZAI_API_KEY"]}],f0=new Map(OK.map(($)=>[$.id,$]));function f1($){return f0.get($)}function q$($){return $.api??f1($.provider)?.api??"openai-completions"}function $6($){return $.baseUrl??f1($.provider)?.baseUrl}function v1($){return f1($)?.env??[]}var NK=new Set(['"',"\\","/","b","f","n","r","t","u"]),MK={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function Z6($){let Z="",W=!1;for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(!W){if(Z+=Y,Y==='"')W=!0;continue}if(Y==='"'){Z+=Y,W=!1;continue}if(Y==="\\"){let X=$[Q+1];if(X===void 0){Z+="\\\\";continue}if(X==="u"&&/^[0-9a-fA-F]{4}$/.test($.slice(Q+2,Q+6))){Z+=$.slice(Q,Q+6),Q+=5;continue}if(X!=="u"&&NK.has(X)){Z+=`\\${X}`,Q+=1;continue}Z+="\\\\";continue}let G=Y.codePointAt(0)??0;if(G<=31)Z+=MK[Y]??`\\u${G.toString(16).padStart(4,"0")}`;else Z+=Y}return Z}function A4($){try{return JSON.parse($)}catch(Z){let W=Z6($);if(W!==$)return JSON.parse(W);throw Z}}class q4{text;pos=0;constructor($){this.text=$}ws(){while(this.pos<this.text.length&&/\s/.test(this.text[this.pos]))this.pos++}peek(){return this.text[this.pos]}value(){this.ws();let $=this.peek();if($===void 0)return;if($==="{")return this.object();if($==="[")return this.array();if($==='"')return this.string();if($==="t"||$==="f"||$==="n")return this.literal();if($==="-"||/[0-9]/.test($))return this.number();return}object(){let $={};this.pos++;for(;;){if(this.ws(),this.peek()===void 0)return $;if(this.peek()==="}")return this.pos++,$;if(this.peek()===","){this.pos++;continue}if(this.peek()!=='"')return $;let Z=this.pos,W=this.string();if(this.pos>=this.text.length&&!this.closedString(Z))return $;if(this.ws(),this.peek()!==":")return $;if(this.pos++,this.ws(),this.peek()===void 0)return $;let Q=this.pos,Y=this.value();if(Y!==void 0||this.consumedNull(Q))$[W]=Y??null}}array(){let $=[];this.pos++;for(;;){if(this.ws(),this.peek()===void 0)return $;if(this.peek()==="]")return this.pos++,$;if(this.peek()===","){this.pos++;continue}let Z=this.pos,W=this.value();if(W===void 0&&!this.consumedNull(Z))return $;$.push(W??null)}}closedString($){let Z=$+1;while(Z<this.text.length)if(this.text[Z]==="\\")Z+=2;else if(this.text[Z]==='"')return!0;else Z+=1;return!1}consumedNull($){return this.text.slice($,this.pos).trim().startsWith("null")}string(){this.pos++;let $="";while(this.pos<this.text.length){let Z=this.text[this.pos];if(Z==='"')return this.pos++,$;if(Z==="\\"){let W=this.text[this.pos+1];if(W===void 0)return this.pos++,$;if(W==="u"){let Y=this.text.slice(this.pos+2,this.pos+6);if(/^[0-9a-fA-F]{4}$/.test(Y))$+=String.fromCharCode(Number.parseInt(Y,16)),this.pos+=6;else return this.pos=this.text.length,$;continue}$+={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
26
- `,r:"\r",t:"\t"}[W]??W,this.pos+=2;continue}$+=Z,this.pos++}return $}literal(){for(let[$,Z]of[["true",!0],["false",!1],["null",null]])if($.startsWith(this.text.slice(this.pos,this.pos+$.length))){let W=this.text.slice(this.pos);if($.startsWith(W))return this.pos=this.text.length,Z;if(W.startsWith($))return this.pos+=$.length,Z}this.pos=this.text.length;return}number(){let Z=/^-?[0-9]*\.?[0-9]*(?:[eE][+-]?[0-9]*)?/.exec(this.text.slice(this.pos))?.[0]??"";this.pos+=Z.length;let W=Number(Z);return Number.isNaN(W)?void 0:W}}function O4($){return new q4($).value()}function C0($){if(!$||$.trim()==="")return{};try{let Z=A4($);if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z))return Z;return{}}catch{for(let Z of[$,Z6($)])try{let W=O4(Z);if(W!==null&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return{}}}var jK=60000;function W6(){let $=Error("Request aborted");return $.name="AbortError",$}function PK($,Z){return new Promise((W,Q)=>{if(Z?.aborted){Q(W6());return}let Y=()=>{clearTimeout(G),Q(W6())},G=setTimeout(()=>{Z?.removeEventListener("abort",Y),W()},Math.max(0,$));Z?.addEventListener("abort",Y,{once:!0})})}function wK($,Z,W){if($.retryAfterMs!==void 0&&$.retryAfterMs>0)return Math.min($.retryAfterMs,W);return Math.min(0.5*2**Z,8)*1000*(1-Math.random()*0.25)}async function v0($,Z={}){let W=Z.maxRetries??2,Q=Z.maxRetryDelayMs??jK,Y=W;for(;;)try{return await $()}catch(G){if(Z.signal?.aborted)throw W6();if(Y<=0||!(G instanceof l)||!G.retryable)throw G;let X=W-Y;Y--,await PK(wK(G,X,Q),Z.signal)}}function M4($){if(!$.event&&$.data.length===0)return null;let Z={event:$.event,data:$.data.join(`
27
- `)};return $.event=null,$.data=[],Z}function N4($,Z){if($==="")return M4(Z);if($.startsWith(":"))return null;let W=$.indexOf(":"),Q=W===-1?$:$.slice(0,W),Y=W===-1?"":$.slice(W+1);if(Y.startsWith(" "))Y=Y.slice(1);if(Q==="event")Z.event=Y;else if(Q==="data")Z.data.push(Y);return null}async function*g0($,Z){let W=$.getReader(),Q=new TextDecoder,Y={event:null,data:[]},G="",X=function*(){let J=G.search(/[\r\n]/);while(J!==-1){let K=G.slice(0,J),H=J+1;if(G[J]==="\r"&&G[H]===`
28
- `)H+=1;G=G.slice(H);let V=N4(K,Y);if(V)yield V;J=G.search(/[\r\n]/)}};try{while(!0){if(Z?.aborted)throw Error("Request was aborted");let{value:K,done:H}=await W.read();if(H)break;G+=Q.decode(K,{stream:!0}),yield*X()}if(G+=Q.decode(),yield*X(),G.length>0){let K=N4(G,Y);if(K)yield K}let J=M4(Y);if(J)yield J}finally{W.releaseLock()}}function h0($){return $.replace(/\/+$/,"")}function TK($){for(let Z of $){let W=process.env[Z];if(W)return W}return}async function r0($,Z){let W=await Z?.getCredentials?.();if(W){if($.provider==="anthropic"&&W.type==="oauth")throw new l("auth","Anthropic account-plan authentication is not supported");return W}let Q=Z?.apiKey??TK(v1($.provider));if(!Q){let Y=v1($.provider),G=Y.length>0?`set ${Y.join(" or ")} or run /login`:"run /login";throw new l("auth",`No credentials for provider "${$.provider}" (${G})`)}return{type:"apiKey",apiKey:Q}}function IK($){let Z=process.env.CLOUDFLARE_ACCOUNT_ID;if(!Z)return;if($.provider==="cloudflare-workers-ai")return`https://api.cloudflare.com/client/v4/accounts/${Z}/ai/v1`;let W=process.env.CLOUDFLARE_GATEWAY_ID;if(!W)return;let Q=`https://gateway.ai.cloudflare.com/v1/${Z}/${W}`;if($.api==="anthropic-messages")return`${Q}/anthropic`;if($.api==="openai-responses")return`${Q}/openai`;return`${Q}/compat`}function EK(){let $=process.env.AZURE_OPENAI_BASE_URL,Z=process.env.AZURE_OPENAI_RESOURCE_NAME;if(!$&&!Z)return;let W=h0($??`https://${Z}.openai.azure.com`);return W.endsWith("/openai/v1")?W:`${W}/openai/v1`}function RK(){let $=process.env.GOOGLE_CLOUD_PROJECT??process.env.GCLOUD_PROJECT,Z=process.env.GOOGLE_CLOUD_LOCATION;if(!$||!Z)return"https://aiplatform.googleapis.com/v1/publishers/google";return`https://${Z}-aiplatform.googleapis.com/v1/projects/${$}/locations/${Z}/publishers/google`}function SK(){return`https://bedrock-runtime.${process.env.AWS_REGION??process.env.AWS_DEFAULT_REGION??"us-east-1"}.amazonaws.com/openai/v1`}function CK($,Z){if(Z?.baseUrl)return h0(Z.baseUrl);if($.provider.startsWith("cloudflare-")){let W=IK($);if(W)return h0(W)}if($.provider==="azure-openai-responses"){let W=EK();if(W)return h0(W)}if($.provider==="google-vertex"){let W=RK();if(W)return h0(W)}if($.provider==="amazon-bedrock")return SK();return h0($6($)??"")}function g1($,Z){let W=h0($),Q=Z.startsWith("/")?Z:`/${Z}`;if(!W)return Q;if(Q.startsWith("/v1/")&&W.endsWith("/v1"))return`${W}${Q.slice(3)}`;return`${W}${Q}`}function t0($,Z){let W=f1($.provider),Q={...W?.headers,...$.headers};if(Z.type==="oauth")return{...Q,authorization:`Bearer ${Z.accessToken}`,...Z.headers};if(W?.auth==="anthropic")return{...Q,"x-api-key":Z.apiKey};if(W?.auth==="google")return{...Q,"x-goog-api-key":Z.apiKey};if(W?.auth==="azure")return{...Q,"api-key":Z.apiKey};if(W?.auth==="cloudflare")return{...Q,"cf-aig-authorization":`Bearer ${Z.apiKey}`};return{...Q,authorization:`Bearer ${Z.apiKey}`}}function o0($,Z,W){if(W?.baseUrl)return h0(W.baseUrl);if(Z.type==="oauth"&&Z.baseUrl)return h0(Z.baseUrl);return CK($,W)}function Q6($,Z){return(Z.inputTokens*$.input+Z.outputTokens*$.output+Z.cacheReadTokens*$.cacheRead+Z.cacheWriteTokens*$.cacheWrite)/1e6}function O$(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0}}function Y6($,Z){return{inputTokens:$.inputTokens+Z.inputTokens,outputTokens:$.outputTokens+Z.outputTokens,cacheReadTokens:$.cacheReadTokens+Z.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens+Z.cacheWriteTokens,costUsd:($.costUsd??0)+(Z.costUsd??0)}}class NZ{isComplete;extractResult;queue=[];waiting=[];done=!1;finalResult;resolveFinal;constructor($,Z){this.isComplete=$;this.extractResult=Z;this.finalResult=new Promise((W)=>{this.resolveFinal=W})}push($){if(this.done)return;if(this.isComplete($))this.done=!0,this.resolveFinal(this.extractResult($));let Z=this.waiting.shift();if(Z)Z({value:$,done:!1});else this.queue.push($)}end(){this.done=!0;while(this.waiting.length>0)this.waiting.shift()?.({value:void 0,done:!0})}async*[Symbol.asyncIterator](){while(!0)if(this.queue.length>0)yield this.queue.shift();else if(this.done)return;else{let $=await new Promise((Z)=>this.waiting.push(Z));if($.done)return;yield $.value}}result(){return this.finalResult}}class MZ extends NZ{constructor(){super(($)=>$.type==="done"||$.type==="error",($)=>{if($.type==="done")return $.message;if($.type==="error")return $.error;throw Error("unexpected final event")})}}function yK($){return{role:"assistant",content:[],model:`${$.provider}/${$.id}`,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0},stopReason:"end",timestamp:Date.now()}}function u0($,Z){Z.usage.costUsd=Q6($.pricing,Z.usage)}function s0($,Z,W){let Q=new MZ,Y=yK($);return(async()=>{try{if(await W(Q,Y),Z?.signal?.aborted)throw Error("Request was aborted");if(Y.stopReason==="error")throw new l("api",Y.errorMessage??"provider reported an error");Q.push({type:"done",message:Y})}catch(G){Y.stopReason=Z?.signal?.aborted?"aborted":"error",Y.errorMessage=G instanceof Error?G.message:JSON.stringify(G),Q.push({type:"error",reason:Y.stopReason,...G instanceof l?{errorKind:G.kind}:{},error:Y})}finally{Q.end()}})(),Q}async function e0($,Z,W,Q){let Y=Q?.fetch??fetch,G;try{G=await Y($,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...Z},body:JSON.stringify(W),...Q?.signal?{signal:Q.signal}:{}})}catch(X){if(Q?.signal?.aborted)throw X;let J=X instanceof Error?X.message:String(X);throw new l("network",J)}if(!G.ok){let X=await G.text();throw A$(G.status,X,G.headers)}if(!G.body)throw new l("api","response has no body");return G}var bK="2023-06-01",G6={type:"ephemeral"};function j4($){return $.filter((Z)=>Z.type!=="text"||Z.text.trim().length>0).map((Z)=>Z.type==="text"?{type:"text",text:Z.text}:{type:"image",source:{type:"base64",media_type:Z.mimeType,data:Z.data}})}function kK($){let Z=[];for(let W of $)if(W.type==="text"){if(W.text.trim().length===0)continue;Z.push({type:"text",text:W.text})}else if(W.type==="thinking"){if(W.redacted)Z.push({type:"redacted_thinking",data:W.signature??""});else if(W.signature)Z.push({type:"thinking",thinking:W.thinking,signature:W.signature});else if(W.thinking.trim().length>0)Z.push({type:"text",text:W.thinking})}else Z.push({type:"tool_use",id:W.id,name:W.name,input:W.arguments??{}});return Z}function _K($,Z){let W=[];for(let Y=0;Y<$.length;Y++){let G=$[Y];if(G.role==="user"){let X=j4(G.content);if(X.length>0)W.push({role:"user",content:X})}else if(G.role==="assistant"){let X=kK(G.content);if(X.length>0)W.push({role:"assistant",content:X})}else{let X=[];while(Y<$.length){let J=$[Y];if(!J||J.role!=="toolResult")break;X.push({type:"tool_result",tool_use_id:J.toolCallId,content:j4(J.content),is_error:J.isError}),Y++}Y--,W.push({role:"user",content:X})}}let Q=W[W.length-1];if(Z&&Q&&Q.role==="user"){let Y=Q.content,G=Y[Y.length-1];if(G)G.cache_control=G6}return W}function xK($,Z,W){if(!$.thinking||Z===void 0)return;if(Z==="off"){W.thinking={type:"disabled"};return}if($.thinkingMode==="budget"){let Q={low:4096,medium:8192,high:16384};W.thinking={type:"enabled",budget_tokens:Q[Z]??8192,display:"summarized"};return}W.thinking={type:"adaptive",display:"summarized"},W.output_config={effort:Z}}function fK($,Z,W){let Q=$.provider==="anthropic",Y={model:$.id,max_tokens:W?.maxTokens??$.maxOutput,messages:_K(Z.messages,Q),stream:!0};if(Z.systemPrompt&&Z.systemPrompt.length>0){let G=Z.systemPrompt.reduce((X,J,K)=>J.dynamic?X:K,-1);Y.system=Z.systemPrompt.map((X,J)=>({type:"text",text:X.text,...Q&&J===G?{cache_control:G6}:{}}))}if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((G,X)=>({name:G.name,description:G.description,input_schema:G.inputSchema,...Q&&X===(Z.tools?.length??0)-1?{cache_control:G6}:{}}));if(W?.temperature!==void 0)Y.temperature=W.temperature;return xK($,W?.thinkingLevel,Y),Y}function vK($){switch($){case"end_turn":case"stop_sequence":case"pause_turn":return{stopReason:"end"};case"max_tokens":return{stopReason:"length"};case"tool_use":return{stopReason:"toolUse"};case"refusal":return{stopReason:"error",errorMessage:"The model refused to complete the request"};case"model_context_window_exceeded":return{stopReason:"error",errorMessage:"Context window exceeded"};default:return{stopReason:"end"}}}function P4($,Z,W){return s0($,W,async(Q,Y)=>{let G=fK($,Z,W),X=await v0(async()=>{let H=await r0($,W),V=o0($,H,W),z={"anthropic-version":bK,...t0($,H),...W?.headers};return e0(g1(V,"/v1/messages"),z,G,W)},{...W?.maxRetries!==void 0?{maxRetries:W.maxRetries}:{},...W?.signal?{signal:W.signal}:{}});Q.push({type:"start",partial:Y});let J=new Map,K=X.body;for await(let H of g0(K,W?.signal)){if(H.event==="error")throw Error(H.data);if(!H.data)continue;let V=JSON.parse(H.data),z=V.type;if(z==="message_start"){let F=V.message?.usage;if(F)Y.usage.inputTokens=F.input_tokens??0,Y.usage.outputTokens=F.output_tokens??0,Y.usage.cacheReadTokens=F.cache_read_input_tokens??0,Y.usage.cacheWriteTokens=F.cache_creation_input_tokens??0,u0($,Y)}else if(z==="content_block_start"){let{index:F,content_block:D}=V,L=Y.content.length;J.set(F,{contentIndex:L,partialJson:""});let U=D.type;if(U==="text")Y.content.push({type:"text",text:""}),Q.push({type:"text_start",contentIndex:L,partial:Y});else if(U==="thinking")Y.content.push({type:"thinking",thinking:"",signature:""}),Q.push({type:"thinking_start",contentIndex:L,partial:Y});else if(U==="redacted_thinking")Y.content.push({type:"thinking",thinking:"[reasoning redacted]",signature:D.data??"",redacted:!0}),Q.push({type:"thinking_start",contentIndex:L,partial:Y});else if(U==="tool_use")Y.content.push({type:"toolCall",id:D.id,name:D.name,arguments:D.input??{}}),Q.push({type:"toolcall_start",contentIndex:L,partial:Y});else J.delete(F)}else if(z==="content_block_delta"){let F=J.get(V.index);if(!F)continue;let D=Y.content[F.contentIndex],L=V.delta,U=L.type;if(U==="text_delta"&&D?.type==="text")D.text+=L.text,Q.push({type:"text_delta",contentIndex:F.contentIndex,delta:L.text,partial:Y});else if(U==="thinking_delta"&&D?.type==="thinking")D.thinking+=L.thinking,Q.push({type:"thinking_delta",contentIndex:F.contentIndex,delta:L.thinking,partial:Y});else if(U==="input_json_delta"&&D?.type==="toolCall")F.partialJson+=L.partial_json,D.arguments=C0(F.partialJson),Q.push({type:"toolcall_delta",contentIndex:F.contentIndex,delta:L.partial_json,partial:Y});else if(U==="signature_delta"&&D?.type==="thinking")D.signature=(D.signature??"")+L.signature}else if(z==="content_block_stop"){let F=J.get(V.index);if(!F)continue;let D=Y.content[F.contentIndex];if(D?.type==="text")Q.push({type:"text_end",contentIndex:F.contentIndex,content:D.text,partial:Y});else if(D?.type==="thinking")Q.push({type:"thinking_end",contentIndex:F.contentIndex,content:D.thinking,partial:Y});else if(D?.type==="toolCall")D.arguments=C0(F.partialJson),Q.push({type:"toolcall_end",contentIndex:F.contentIndex,toolCall:D,partial:Y})}else if(z==="message_delta"){let F=V.delta;if(F?.stop_reason){let L=vK(F.stop_reason);if(Y.stopReason=L.stopReason,L.errorMessage)Y.errorMessage=L.errorMessage}let D=V.usage;if(D){if(D.input_tokens!=null)Y.usage.inputTokens=D.input_tokens;if(D.output_tokens!=null)Y.usage.outputTokens=D.output_tokens;if(D.cache_read_input_tokens!=null)Y.usage.cacheReadTokens=D.cache_read_input_tokens;if(D.cache_creation_input_tokens!=null)Y.usage.cacheWriteTokens=D.cache_creation_input_tokens;u0($,Y)}}}})}var N$={id:"anthropic",stream:P4};function gK($){let Z=[],W=new Map,Q=(Y,G)=>{if(G.length===0)return;let X=Z[Z.length-1];if(X&&X.role===Y)X.parts.push(...G);else Z.push({role:Y,parts:G})};for(let Y of $)if(Y.role==="user")Q("user",Y.content.map((G)=>G.type==="text"?{text:G.text}:{inlineData:{mimeType:G.mimeType,data:G.data}}));else if(Y.role==="assistant"){let G=[];for(let X of Y.content)if(X.type==="text"){if(X.text.trim().length>0)G.push({text:X.text})}else if(X.type==="thinking");else W.set(X.id,X.name),G.push({functionCall:{name:X.name,args:X.arguments??{}},...X.signature?{thoughtSignature:X.signature}:{}});Q("model",G)}else{let G=W.get(Y.toolCallId)??Y.toolName,X=Y.content.filter((K)=>K.type==="text").map((K)=>K.text).join(`
29
- `),J=[{functionResponse:{name:G,response:Y.isError?{error:X}:{output:X}}}];for(let K of Y.content)if(K.type==="image")J.push({inlineData:{mimeType:K.mimeType,data:K.data}});Q("user",J)}return{contents:Z,toolNames:W}}function hK($){switch($){case"off":return 0;case"low":return 2048;case"medium":return 8192;case"high":return 24576}}function uK($,Z,W){let Q={contents:gK(Z.messages).contents};if(Z.systemPrompt&&Z.systemPrompt.length>0)Q.systemInstruction={parts:Z.systemPrompt.map((G)=>({text:G.text}))};if(Z.tools&&Z.tools.length>0)Q.tools=[{functionDeclarations:Z.tools.map((G)=>({name:G.name,description:G.description,parameters:G.inputSchema}))}];let Y={maxOutputTokens:W?.maxTokens??$.maxOutput};if(W?.temperature!==void 0)Y.temperature=W.temperature;if($.thinking&&W?.thinkingLevel)Y.thinkingConfig={thinkingBudget:hK(W.thinkingLevel),includeThoughts:W.thinkingLevel!=="off"};return Q.generationConfig=Y,Q}function mK($,Z){switch($){case"STOP":return{stopReason:Z?"toolUse":"end"};case"MAX_TOKENS":return{stopReason:"length"};case"SAFETY":case"RECITATION":case"PROHIBITED_CONTENT":case"BLOCKLIST":return{stopReason:"error",errorMessage:`Generation stopped: ${$}`};default:return{stopReason:Z?"toolUse":"end"}}}function w4($,Z,W){return s0($,W,async(Q,Y)=>{let G=uK($,Z,W),X=await v0(async()=>{let U=await r0($,W);if(U.type!=="apiKey")throw new l("auth",`${$.provider} requires API-key auth`);let A=o0($,U,W).replace(/\/+$/,""),q=$.provider==="google-vertex"?`/models/${$.id}:streamGenerateContent?alt=sse`:`/models/${$.id}:streamGenerateContent?alt=sse`,O=`${A}${q}`;return e0(O,{...t0($,U),...W?.headers},G,W)},{...W?.maxRetries!==void 0?{maxRetries:W.maxRetries}:{},...W?.signal?{signal:W.signal}:{}});Q.push({type:"start",partial:Y});let J=-1,K=-1,H=0,V=!1,z,F=X.body,D=()=>{if(J!==-1){let U=Y.content[J];if(U?.type==="text")Q.push({type:"text_end",contentIndex:J,content:U.text,partial:Y});J=-1}if(K!==-1){let U=Y.content[K];if(U?.type==="thinking")Q.push({type:"thinking_end",contentIndex:K,content:U.thinking,partial:Y});K=-1}};for await(let U of g0(F,W?.signal)){if(!U.data)continue;let A=JSON.parse(U.data),q=A.candidates?.[0],O=A.usageMetadata;if(O){let P=O.cachedContentTokenCount??0;Y.usage.inputTokens=(O.promptTokenCount??0)-P,Y.usage.cacheReadTokens=P,Y.usage.outputTokens=(O.candidatesTokenCount??0)+(O.thoughtsTokenCount??0),u0($,Y)}if(!q)continue;let j=q.content?.parts??[];for(let P of j)if(typeof P.text==="string")if(P.thought===!0){if(K===-1)K=Y.content.length,Y.content.push({type:"thinking",thinking:""}),Q.push({type:"thinking_start",contentIndex:K,partial:Y});let N=Y.content[K];if(N?.type==="thinking"){if(N.thinking+=P.text,typeof P.thoughtSignature==="string")N.signature=P.thoughtSignature;Q.push({type:"thinking_delta",contentIndex:K,delta:P.text,partial:Y})}}else{if(J===-1)J=Y.content.length,Y.content.push({type:"text",text:""}),Q.push({type:"text_start",contentIndex:J,partial:Y});let N=Y.content[J];if(N?.type==="text")N.text+=P.text,Q.push({type:"text_delta",contentIndex:J,delta:P.text,partial:Y})}else if(P.functionCall){V=!0;let N=P.functionCall,x=Y.content.length,m={type:"toolCall",id:`call_${H++}_${N.name}`,name:N.name,arguments:N.args??{},...typeof P.thoughtSignature==="string"?{signature:P.thoughtSignature}:{}};Y.content.push(m),Q.push({type:"toolcall_start",contentIndex:x,partial:Y}),Q.push({type:"toolcall_end",contentIndex:x,toolCall:m,partial:Y})}if(typeof q.finishReason==="string")z=q.finishReason}D();let L=mK(z??"STOP",V);if(Y.stopReason=L.stopReason,L.errorMessage)Y.errorMessage=L.errorMessage})}var M$={id:"google",stream:w4};async function X6($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||Z.availableModelIds===void 0)return;let W=new Set(Z.availableModelIds);return $.currentModels.filter((Q)=>Q.provider==="github-copilot"&&W.has(Q.id))}var I4="https://chatgpt.com/backend-api/codex",lK=64,pK=128000,cK={input:0,output:0,cacheRead:0,cacheWrite:0};function E4($){let Z=$?.trim();return Z?Z.slice(0,lK):void 0}function T4($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function dK($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function iK($,Z){if(typeof $!=="object"||$===null||Array.isArray($))return;let W=$;if(typeof W.slug!=="string"||W.slug.length===0||W.supported_in_api===!1||typeof W.visibility==="string"&&W.visibility!=="list")return;let Q=Z.find((K)=>K.provider==="openai-codex"&&K.id===W.slug),Y=T4(W.context_window)??T4(W.max_context_window)??Q?.contextWindow;if(!Y)return;let G=Array.isArray(W.input_modalities)?W.input_modalities.filter((K)=>typeof K==="string"):[],X=["text"];if(G.includes("image")||Q?.modalities.includes("image"))X.push("image");let J=Array.isArray(W.supported_reasoning_levels)?W.supported_reasoning_levels:[];return{provider:"openai-codex",id:W.slug,...typeof W.display_name==="string"?{name:W.display_name}:{},contextWindow:Y,maxOutput:Q?.maxOutput??pK,modalities:X,...J.length>0||Q?.thinking?{thinking:!0}:{},pricing:Q?.pricing??cK,priority:dK(W.priority)??Number.MAX_SAFE_INTEGER}}async function R4($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||!Z.accountId)return;let W=new URL(`${I4}/models`);W.searchParams.set("client_version",$.clientVersion??"0.0.0");let Q=await($.fetch??fetch)(W,{headers:{accept:"application/json",authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId,originator:"mu"},...$.signal?{signal:$.signal}:{}});if(!Q.ok)throw A$(Q.status,await Q.text(),Q.headers);let Y=await Q.json();if(typeof Y!=="object"||Y===null||!Array.isArray(Y.models))throw Error("Could not discover ChatGPT models: invalid catalog response");let G=Y.models;if(G.length===0)return;let X=G.map((J)=>iK(J,$.currentModels)).filter((J)=>J!==void 0).sort((J,K)=>J.priority-K.priority).map(({priority:J,...K})=>K);if(X.length===0)throw Error("Could not discover ChatGPT models: catalog contained no compatible models");return X}function nK($,Z,W){if(W?.provider==="openai-codex"){if($.type!=="oauth"||!$.accountId)throw Error("OpenAI Codex requires a ChatGPT account credential");let Y=(Z?.baseUrl??I4).replace(/\/+$/,""),G=E4(Z?.sessionId);return{url:`${Y}/responses`,headers:{authorization:`Bearer ${$.accessToken}`,"chatgpt-account-id":$.accountId,originator:"mu","openai-beta":"responses=experimental",...G?{"session-id":G,"x-client-request-id":G}:{}}}}if(!W)throw Error("A model is required");let Q=o0(W,$,Z);return{url:g1(Q,"/responses"),headers:t0(W,$)}}function aK($){let Z=[];for(let W of $)if(W.role==="user")Z.push({role:"user",content:W.content.map((Q)=>Q.type==="text"?{type:"input_text",text:Q.text}:{type:"input_image",image_url:`data:${Q.mimeType};base64,${Q.data}`})});else if(W.role==="assistant")for(let Q of W.content)if(Q.type==="text"){if(Q.text.trim().length===0)continue;Z.push({role:"assistant",content:[{type:"output_text",text:Q.text}]})}else if(Q.type==="thinking"){if(!Q.signature)continue;try{let Y=JSON.parse(Q.signature);Z.push({type:"reasoning",id:Y.id,summary:[],...Y.encrypted_content?{encrypted_content:Y.encrypted_content}:{}})}catch{}}else Z.push({type:"function_call",call_id:Q.id,name:Q.name,arguments:JSON.stringify(Q.arguments??{})});else{let Q=W.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join(`
30
- `);Z.push({type:"function_call_output",call_id:W.toolCallId,output:Q})}return Z}function rK($,Z,W){let Q=$.provider==="openai-codex",Y={model:$.id,input:aK(Z.messages),stream:!0,store:!1};if(!Q)Y.max_output_tokens=W?.maxTokens??$.maxOutput;if(Z.systemPrompt&&Z.systemPrompt.length>0)Y.instructions=Z.systemPrompt.map((G)=>G.text).join(`
45
+ `),q=[`<conversation>
46
+ ${ZW(z)}
47
+ </conversation>`,...B?[`<previous-summary>
48
+ ${B}
49
+ </previous-summary>`]:[],U,"Produce the summary now."].join(`
31
50
 
32
- `);else if(Q)Y.instructions="You are a helpful assistant.";if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((G)=>({type:"function",name:G.name,description:G.description,parameters:G.inputSchema,strict:Q?null:!1}));if(Q){Y.text={verbosity:"low"},Y.include=["reasoning.encrypted_content"],Y.tool_choice="auto",Y.parallel_tool_calls=!0;let G=E4(W?.sessionId);if(G)Y.prompt_cache_key=G}if(W?.temperature!==void 0)Y.temperature=W.temperature;if($.thinking&&W?.thinkingLevel&&W.thinkingLevel!=="off"){if(Y.reasoning={effort:W.thinkingLevel,summary:"auto"},!Q)Y.include=["reasoning.encrypted_content"]}return Y}function J6($,Z,W){return s0($,W,async(Q,Y)=>{let G=rK($,Z,W),X=await v0(async()=>{let V=await r0($,W),{url:z,headers:F}=nK(V,W,$);return e0(z,{...F,...W?.headers},G,W)},{...W?.maxRetries!==void 0?{maxRetries:W.maxRetries}:{},...W?.signal?{signal:W.signal}:{}});Q.push({type:"start",partial:Y});let J=new Map,K=!1,H=X.body;for await(let V of g0(H,W?.signal)){if(!V.data||V.data==="[DONE]")continue;let z=JSON.parse(V.data),F=z.type;if(F==="response.output_item.added"){let{item:D,output_index:L}=z,U=D.type,A=Y.content.length;if(U==="message")J.set(L,{contentIndex:A,kind:"text",partialJson:""}),Y.content.push({type:"text",text:""}),Q.push({type:"text_start",contentIndex:A,partial:Y});else if(U==="reasoning")J.set(L,{contentIndex:A,kind:"reasoning",partialJson:""}),Y.content.push({type:"thinking",thinking:"",signature:JSON.stringify({id:D.id})}),Q.push({type:"thinking_start",contentIndex:A,partial:Y});else if(U==="function_call")K=!0,J.set(L,{contentIndex:A,kind:"function_call",partialJson:""}),Y.content.push({type:"toolCall",id:D.call_id??D.id,name:D.name,arguments:{}}),Q.push({type:"toolcall_start",contentIndex:A,partial:Y})}else if(F==="response.output_text.delta"){let D=J.get(z.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="text")L.text+=z.delta,Q.push({type:"text_delta",contentIndex:D.contentIndex,delta:z.delta,partial:Y})}else if(F==="response.reasoning_summary_text.delta"){let D=J.get(z.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="thinking")L.thinking+=z.delta,Q.push({type:"thinking_delta",contentIndex:D.contentIndex,delta:z.delta,partial:Y})}else if(F==="response.function_call_arguments.delta"){let D=J.get(z.output_index),L=D&&Y.content[D.contentIndex];if(D&&L?.type==="toolCall")D.partialJson+=z.delta,L.arguments=C0(D.partialJson),Q.push({type:"toolcall_delta",contentIndex:D.contentIndex,delta:z.delta,partial:Y})}else if(F==="response.output_item.done"){let D=J.get(z.output_index);if(!D)continue;let L=z.item,U=Y.content[D.contentIndex];if(U?.type==="text")Q.push({type:"text_end",contentIndex:D.contentIndex,content:U.text,partial:Y});else if(U?.type==="thinking")U.signature=JSON.stringify({id:L.id,...L.encrypted_content?{encrypted_content:L.encrypted_content}:{}}),Q.push({type:"thinking_end",contentIndex:D.contentIndex,content:U.thinking,partial:Y});else if(U?.type==="toolCall"){let A=L.arguments??D.partialJson;U.arguments=C0(A),Q.push({type:"toolcall_end",contentIndex:D.contentIndex,toolCall:U,partial:Y})}}else if(F==="response.completed"||F==="response.incomplete"||F==="response.failed"){let D=z.response,L=D.usage;if(L){let A=L.input_tokens_details?.cached_tokens??0;Y.usage.inputTokens=(L.input_tokens??0)-A,Y.usage.cacheReadTokens=A,Y.usage.outputTokens=L.output_tokens??0,u0($,Y)}if(F==="response.completed")Y.stopReason=K?"toolUse":"end";else if(F==="response.incomplete"){let U=D.incomplete_details?.reason;Y.stopReason=U==="max_output_tokens"?"length":"end"}else{let U=D.error;Y.stopReason="error",Y.errorMessage=U?.message??"response failed"}}else if(F==="error")throw Error(z.message??V.data)}})}var j$={id:"openai",stream:J6},h1={id:"openai-codex",stream:J6,discoverModels:R4};function tK($){return $.content.map((Z)=>Z.type==="text"?Z.text:`data:${Z.mimeType};base64,${Z.data}`).join(`
33
- `)}function oK($){if($.content.every((Z)=>Z.type==="text"))return $.content.map((Z)=>Z.text).join(`
34
- `);return $.content.map((Z)=>Z.type==="text"?{type:"text",text:Z.text}:{type:"image_url",image_url:{url:`data:${Z.mimeType};base64,${Z.data}`}})}function sK($,Z){let W=[];if(Z&&Z.length>0)W.push({role:"system",content:Z.map((Q)=>Q.text).join(`
51
+ `),A={systemPrompt:[{text:`You are a context summarization assistant. Do not continue the conversation. Output only the requested handoff summary.
35
52
 
36
- `)});for(let Q of $){if(Q.role==="user"){W.push({role:"user",content:oK(Q)});continue}if(Q.role==="toolResult"){W.push({role:"tool",tool_call_id:Q.toolCallId,content:tK(Q)});continue}let Y=Q.content.filter((J)=>J.type==="text").map((J)=>J.text).join(`
37
- `),G=Q.content.filter((J)=>J.type==="thinking").map((J)=>J.thinking).join(`
38
- `),X=Q.content.filter((J)=>J.type==="toolCall").map((J)=>({id:J.id,type:"function",function:{name:J.name,arguments:JSON.stringify(J.arguments??{})}}));if(!Y&&!G&&X.length===0)continue;W.push({role:"assistant",content:Y||null,...G?{reasoning_content:G}:{},...X.length>0?{tool_calls:X}:{}})}return W}function U1($){return $!==void 0&&$!=="off"}function eK($,Z,W){if(!Z.thinking||W===void 0)return;if(Z.provider==="zai"){if($.thinking={type:U1(W)?"enabled":"disabled"},U1(W)&&Z.id==="glm-5.2")$.reasoning_effort=W;return}if(Z.provider.startsWith("qwen-token-plan")){$.enable_thinking=U1(W);return}if(Z.provider==="deepseek"||Z.provider==="moonshotai"){if($.thinking={type:U1(W)?"enabled":"disabled"},U1(W))$.reasoning_effort=W;return}if(Z.provider==="openrouter"){if(U1(W))$.reasoning={effort:W};return}if(U1(W))$.reasoning_effort=W}function $3($,Z,W){let Q={model:$.id,messages:sK(Z.messages,Z.systemPrompt),stream:!0,stream_options:{include_usage:!0},max_tokens:W?.maxTokens??$.maxOutput};if(Z.tools&&Z.tools.length>0)Q.tools=Z.tools.map((Y)=>({type:"function",function:{name:Y.name,description:Y.description,parameters:Y.inputSchema}})),Q.tool_choice="auto";if(W?.temperature!==void 0)Q.temperature=W.temperature;if(W?.sessionId)if($.provider==="openrouter")Q.user=W.sessionId;else Q.prompt_cache_key=W.sessionId;return eK(Q,$,W?.thinkingLevel),Q}function jZ($){return typeof $==="number"&&Number.isFinite($)?$:0}function K6($,Z,W){return s0($,W,async(Q,Y)=>{let G=$3($,Z,W),X=await v0(async()=>{let z=await r0($,W),F=o0($,z,W);return e0(g1(F,"/chat/completions"),{...t0($,z),...W?.headers},G,W)},{...W?.maxRetries!==void 0?{maxRetries:W.maxRetries}:{},...W?.signal?{signal:W.signal}:{}});Q.push({type:"start",partial:Y});let J=-1,K=-1,H=new Map,V=X.body;for await(let z of g0(V,W?.signal)){if(!z.data||z.data==="[DONE]")continue;let F=JSON.parse(z.data),D=F.usage;if(D){let O=D.prompt_tokens_details,j=jZ(O?.cached_tokens);Y.usage.inputTokens=Math.max(0,jZ(D.prompt_tokens)-j),Y.usage.cacheReadTokens=j,Y.usage.outputTokens=jZ(D.completion_tokens),u0($,Y)}let L=F.choices?.[0];if(!L)continue;let U=L.delta??{},A=typeof U.reasoning_content==="string"?U.reasoning_content:typeof U.reasoning==="string"?U.reasoning:"";if(A){if(K===-1)K=Y.content.length,Y.content.push({type:"thinking",thinking:""}),Q.push({type:"thinking_start",contentIndex:K,partial:Y});let O=Y.content[K];if(O?.type==="thinking")O.thinking+=A,Q.push({type:"thinking_delta",contentIndex:K,delta:A,partial:Y})}if(typeof U.content==="string"&&U.content){if(J===-1)J=Y.content.length,Y.content.push({type:"text",text:""}),Q.push({type:"text_start",contentIndex:J,partial:Y});let O=Y.content[J];if(O?.type==="text")O.text+=U.content,Q.push({type:"text_delta",contentIndex:J,delta:U.content,partial:Y})}for(let O of U.tool_calls??[]){let j=jZ(O.index),P=H.get(j),N=O.function??{};if(!P){let m=Y.content.length;P={contentIndex:m,partialJson:""},H.set(j,P),Y.content.push({type:"toolCall",id:String(O.id??`call_${j}`),name:String(N.name??""),arguments:{}}),Q.push({type:"toolcall_start",contentIndex:m,partial:Y})}let x=Y.content[P.contentIndex];if(x?.type!=="toolCall")continue;if(typeof O.id==="string")x.id=O.id;if(typeof N.name==="string"&&N.name)x.name+=N.name;if(typeof N.arguments==="string")P.partialJson+=N.arguments,x.arguments=C0(P.partialJson),Q.push({type:"toolcall_delta",contentIndex:P.contentIndex,delta:N.arguments,partial:Y})}let q=L.finish_reason;if(typeof q==="string")Y.stopReason=q==="length"?"length":q==="tool_calls"||H.size>0?"toolUse":"end"}if(K!==-1){let z=Y.content[K];if(z?.type==="thinking")Q.push({type:"thinking_end",contentIndex:K,content:z.thinking,partial:Y})}if(J!==-1){let z=Y.content[J];if(z?.type==="text")Q.push({type:"text_end",contentIndex:J,content:z.text,partial:Y})}for(let z of H.values()){let F=Y.content[z.contentIndex];if(F?.type!=="toolCall")continue;F.arguments=C0(z.partialJson),Q.push({type:"toolcall_end",contentIndex:z.contentIndex,toolCall:F,partial:Y})}if(H.size>0&&Y.stopReason==="end")Y.stopReason="toolUse"})}var Z3=new Map([[N$.id,N$],[j$.id,j$],[h1.id,h1],[M$.id,M$]]);function W3($){let Z=Z3.get($);if(Z)return Z;return{id:$,stream:(W,Q,Y)=>{switch(q$(W)){case"anthropic-messages":return N$.stream(W,Q,Y);case"google-generative-ai":case"google-vertex":return M$.stream(W,Q,Y);case"openai-responses":return j$.stream(W,Q,Y);default:return K6(W,Q,Y)}},...$==="github-copilot"?{discoverModels:X6}:{}}}var u1=new Map([...f0.keys()].map(($)=>[$,W3($)]));u1.set(h1.id,h1);function B6($){let Z=u1.get($);if(!Z)throw Error(`Unknown provider: ${$}`);return Z}function S4($){u1.set($.id,$)}var Q3="https://models.dev/api.json",Y3=15000,m1={input:0,output:0,cacheRead:0,cacheWrite:0},G3=[{source:"amazon-bedrock",providers:["amazon-bedrock"]},{source:"anthropic",providers:["anthropic"]},{source:"cerebras",providers:["cerebras"]},{source:"cloudflare-ai-gateway",providers:["cloudflare-ai-gateway"]},{source:"cloudflare-workers-ai",providers:["cloudflare-workers-ai"]},{source:"deepseek",providers:["deepseek"]},{source:"fireworks-ai",providers:["fireworks"]},{source:"github-copilot",providers:["github-copilot"]},{source:"google",providers:["google"]},{source:"google-vertex",providers:["google-vertex"]},{source:"groq",providers:["groq"]},{source:"huggingface",providers:["huggingface"]},{source:"kimi-for-coding",providers:["kimi-coding"]},{source:"minimax",providers:["minimax"]},{source:"mistral",providers:["mistral"]},{source:"moonshotai",providers:["moonshotai"]},{source:"nvidia",providers:["nvidia"]},{source:"openai",providers:["openai","azure-openai-responses"]},{source:"opencode",providers:["opencode"]},{source:"opencode-go",providers:["opencode-go"]},{source:"openrouter",providers:["openrouter"]},{source:"alibaba-token-plan",providers:["qwen-token-plan"]},{source:"vercel-ai-gateway",providers:["vercel-ai-gateway"]},{source:"xai",providers:["xai"]},{source:"zai-coding-plan",providers:["zai"]}],X3=[{provider:"github-copilot",id:"gpt-5.3-codex",name:"GPT-5.3 Codex",api:"openai-responses",contextWindow:128000,maxOutput:32000,modalities:["text","image"],thinking:!0,pricing:m1},{provider:"kimi-coding",id:"kimi-for-coding",name:"Kimi For Coding",api:"anthropic-messages",contextWindow:262144,maxOutput:65536,modalities:["text"],thinking:!0,pricing:m1},{provider:"openrouter",id:"auto",name:"OpenRouter Auto",api:"openai-completions",contextWindow:2000000,maxOutput:30000,modalities:["text","image"],thinking:!0,pricing:m1},{provider:"xai",id:"grok-4.3",name:"Grok 4.3",api:"openai-completions",contextWindow:256000,maxOutput:64000,modalities:["text","image"],thinking:!0,pricing:m1},{provider:"zai",id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",contextWindow:202752,maxOutput:65536,modalities:["text"],thinking:!0,pricing:m1},{provider:"qwen-token-plan",id:"qwen3.7-max",name:"Qwen3.7 Max",api:"openai-completions",contextWindow:1e6,maxOutput:65536,modalities:["text","image"],thinking:!0,pricing:m1}],z6=[...U4.models,...X3],K0=[...z6],y4=new Set;function U0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function $1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function H6($){return Array.isArray($)?$.filter((Z)=>typeof Z==="string"):[]}function J3($){if($.tool_call!==!0||$.status==="deprecated")return!1;let Z=U0($.limit)?$.limit:{};if(($1(Z.context)??0)<=0||($1(Z.output)??0)<=0)return!1;if(!U0($.modalities))return!0;let W=H6($.modalities.input),Q=H6($.modalities.output);return W.includes("text")&&Q.includes("text")}function K3($){if(!Array.isArray($.reasoning_options))return"budget";return $.reasoning_options.some((Z)=>U0(Z)&&Z.type==="effort")?"adaptive":"budget"}function B3($,Z){if($==="cloudflare-ai-gateway"&&typeof Z.id==="string"){if(Z.id.startsWith("openai/"))return"openai-responses";if(Z.id.startsWith("anthropic/"))return"anthropic-messages";return"openai-completions"}if($==="fireworks"&&typeof Z.id==="string"&&Z.id.includes("glm-5p2"))return"openai-completions";if($==="github-copilot"){if(typeof Z.id==="string"&&/^claude-(haiku|sonnet|opus)-[45](?=[.-]|$)/.test(Z.id))return"anthropic-messages";if(typeof Z.id==="string"&&(Z.id.startsWith("gpt-5")||Z.id.startsWith("oswe")||Z.id.startsWith("mai-")))return"openai-responses";return"openai-completions"}if($==="xai"&&Z.id==="grok-4.5")return"openai-responses";if($==="opencode"||$==="opencode-go"){let W=U0(Z.provider)?Z.provider.npm:void 0;if(W==="@ai-sdk/openai")return"openai-responses";if(W==="@ai-sdk/anthropic")return"anthropic-messages";if(W==="@ai-sdk/google")return"google-generative-ai";return"openai-completions"}return q$({provider:$,id:"",contextWindow:1,maxOutput:1,modalities:["text"],pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}})}function b4($,Z){if(typeof Z.id!=="string")return;let W=B3($,Z),Q=Z.id,Y=f0.get($)?.baseUrl;if($==="cloudflare-ai-gateway"){let G=Q.indexOf("/"),X=G===-1?"":Q.slice(0,G);if(X==="openai"||X==="anthropic")Q=Q.slice(G+1)}else if($==="fireworks"&&W==="openai-completions")Y="https://api.fireworks.ai/inference/v1";else if(($==="opencode"||$==="opencode-go")&&W==="anthropic-messages")Y=Y?.replace(/\/v1$/,"");return{id:Q,api:W,...Y?{baseUrl:Y}:{}}}function H3($,Z){if(!J3(Z)||typeof Z.id!=="string")return;let W=U0(Z.limit)?Z.limit:{},Q=$1(W.context),Y=$1(W.output);if(Q===void 0||Y===void 0)return;let G=U0(Z.cost)?Z.cost:{},X=U0(Z.modalities)?H6(Z.modalities.input):["text"],J=["text"];if(X.includes("image"))J.push("image");let K=Z.reasoning===!0,H=b4($,Z);if(!H)return;return{provider:$,id:H.id,...typeof Z.name==="string"?{name:Z.name}:{},api:H.api,...H.baseUrl?{baseUrl:H.baseUrl}:{},contextWindow:Q,maxOutput:Y,modalities:J,...K?{thinking:!0}:{},...K&&$==="anthropic"?{thinkingMode:K3(Z)}:{},pricing:{input:$1(G.input)??0,output:$1(G.output)??0,cacheRead:$1(G.cache_read)??0,cacheWrite:$1(G.cache_write)??0}}}async function z3($){let Z=await($.fetch??fetch)($.url??Q3,{headers:{accept:"application/json"},signal:$.signal??AbortSignal.timeout(Y3)});if(!Z.ok)throw Error(`Could not discover models: ${Z.status} ${Z.statusText}`.trim());let W=await Z.json();if(!U0(W))throw Error("Could not discover models: invalid catalog response");let Q=[],Y=new Set;for(let G of G3){let X=W[G.source];if(!U0(X)||!U0(X.models))continue;for(let J of G.providers){let K=0;for(let[H,V]of Object.entries(X.models)){if(!U0(V))continue;let z=typeof V.id==="string"?V:{...V,id:H},F=H3(J,z);if(F)Q.push(F),K++}if(K>0)Y.add(J)}}if(Q.length===0)throw Error("Could not discover models: catalog contained no compatible models");return{models:Q,authoritativeProviders:Y}}function C4($){return $ instanceof Error?$.message:String($)}async function k4($){let Z=[],W=new Set,Q=[],Y=K0;try{let K=await z3($);Z.push(...K.models);for(let V of K.authoritativeProviders)W.add(V);let H=new Map(K0.map((V)=>[`${V.provider}/${V.id}`,V]));for(let V of K.models)H.set(`${V.provider}/${V.id}`,V);Y=[...H.values()]}catch(K){Q.push(C4(K))}let G=[],X=$.getCredentials;for(let K of $.providers??u1.values()){if(!K.discoverModels)continue;G.push(K.discoverModels({...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{},...X?{getCredentials:()=>X(K.id)}:{},...$.clientVersion?{clientVersion:$.clientVersion}:{},currentModels:Y}).then((H)=>{if(H===void 0)return;if(H.length===0)throw Error(`Could not discover ${K.id} models: catalog returned no models`);return{models:H,authoritativeProviders:new Set([K.id])}}))}let J=await Promise.allSettled(G);for(let K of J){if(K.status==="rejected"){Q.push(C4(K.reason));continue}if(!K.value)continue;for(let H of K.value.authoritativeProviders){for(let V=Z.length-1;V>=0;V--)if(Z[V]?.provider===H)Z.splice(V,1);W.add(H)}Z.push(...K.value.models)}if(W.size===0)throw Error(Q[0]??"Could not discover models: no discovery source was available");for(let K of Q)$.onWarning?.(K);return{models:Z,authoritativeProviders:W}}async function _4($={}){return(await k4($)).models}async function x4($={}){let Z=await k4($);for(let Q of Z.authoritativeProviders)y4.add(Q);let W=K0.filter((Q)=>!Z.authoritativeProviders.has(Q.provider));for(let Q of z6){if(Z.authoritativeProviders.has(Q.provider))continue;if(!W.some((Y)=>Y.provider===Q.provider&&Y.id===Q.id))W.push(Q)}for(let Q of Z.models){let Y=W.findIndex((G)=>G.provider===Q.provider&&G.id===Q.id);if(Y===-1)W.push(Q);else W[Y]=Q}return K0=W,P$()}function P$(){return[...K0]}function f4($){for(let Z of $){let W=K0.findIndex((Q)=>Q.provider===Z.provider&&Q.id===Z.id);if(W===-1)K0.push(Z);else K0[W]=Z}}function A1($){let Z=$.indexOf("/");if(Z!==-1){let W=$.slice(0,Z),Q=$.slice(Z+1),Y=K0.find((J)=>J.provider===W&&J.id===Q);if(Y)return Y;if(y4.has(W))return;if(!f0.get(W)||!Q)return;let X=b4(W,{id:Q});if(!X)return;return{provider:W,id:X.id,name:X.id,api:X.api,...X.baseUrl?{baseUrl:X.baseUrl}:{},contextWindow:128000,maxOutput:32000,modalities:["text","image"],thinking:!0,pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}}}return K0.find((W)=>W.id===$)}function v4($){return`${$.provider}/${$.id}`}function V6($,Z=process.env){if($==="openai-codex")return!1;let W=v1($);return W.length===0||W.some((Q)=>Boolean(Z[Q]))}var V3={"openai-codex":"gpt-5.6-sol",openai:"gpt-5.6-sol",anthropic:"claude-opus-5",google:"gemini-2.5-pro"};function F3($){for(let Z of $){let W=K0.filter((G)=>G.provider===Z);if(W.length===0)continue;let Q=V3[Z];return(Q?W.find((G)=>G.id===Q):void 0)??W[0]}return}function l1($=process.env,Z){let W=Z?[...Z]:[...new Set(K0.map((Y)=>Y.provider))].filter((Y)=>V6(Y,$)),Q=F3(W)??A1("openai-codex/gpt-5.6-sol")??K0[0]??z6[0];if(!Q)throw Error("No models are available");return v4(Q)}function S($){return{content:[{type:"text",text:$}],isError:!0}}function g4($){return{content:[{type:"text",text:$}]}}function PZ($,Z){if($.executionMode==="sequential")return!1;if(!$.isConcurrencySafe)return!1;try{return $.isConcurrencySafe(Z)===!0}catch{return!1}}var D3=10,h4=3;function L3($){return $.content.filter((Z)=>Z.type==="toolCall")}function U3($){return`${$.name}:${JSON.stringify($.arguments)}`}async function F6($,Z,W,Q,Y){let G=Y??new AbortController().signal,X=[...$],J={...Z,messages:[...Z.messages,...$]},K=W,H=0,V=[],z=async(D)=>{return await Q({type:"agent_end",messages:X,reason:D}),{messages:X,reason:D}};await Q({type:"agent_start"});for(let D of $)await Q({type:"message_start",message:D}),await Q({type:"message_end",message:D});let F=await K.getSteeringMessages?.()??[];for(;;){let D=!0;while(D||F.length>0){if(G.aborted)return z("aborted");if(K.maxTurns!==void 0&&H>=K.maxTurns)return z("maxTurns");H++,await Q({type:"turn_start"});for(let N of F)await Q({type:"message_start",message:N}),await Q({type:"message_end",message:N}),J.messages.push(N),X.push(N);if(F=[],K.prepareContext){let N=await K.prepareContext(J.messages),x=Array.isArray(N)?{messages:N}:N;if(J={...J,messages:x.messages},x.stop)return z("budget")}let U=await O3(J,K,Q,G),A=U.message;if(J.messages.push(A),X.push(A),A.stopReason==="error"||A.stopReason==="aborted"){if(await Q({type:"turn_end",message:A,toolResults:[]}),A.stopReason==="error"&&await K.recoverFromError?.(A)===!0){D=!0;continue}return z(A.stopReason==="aborted"?"aborted":"error")}let q=L3(A),O=[];if(D=!1,q.length>0){let N=A.stopReason==="length"?await N3(q,Q):await w3(q,A,J,K,Q,G);O.push(...N.results),F.push(...N.steering),D=!N.terminate;for(let m of N.results)J.messages.push(m),X.push(m);let x=A3(q,V);if(x)J.messages.push(x),X.push(x),await Q({type:"message_start",message:x}),await Q({type:"message_end",message:x})}await Q({type:"turn_end",message:A,toolResults:O});let j={message:A,toolResults:O,context:J,requestMessages:U.messages,newMessages:X},P=await K.prepareNextTurn?.(j);if(P){if(P.context)J=P.context;K={...K,...P.model?{model:P.model}:{},...P.thinkingLevel!==void 0?{thinkingLevel:P.thinkingLevel}:{}}}if(await K.shouldStopAfterTurn?.(j))return z("done");F.push(...await K.getSteeringMessages?.()??[])}let L=await K.getFollowUpMessages?.()??[];if(L.length>0){F=L;continue}break}return z("done")}function A3($,Z){for(let Q of $){let Y=U3(Q);if(Z[Z.length-1]===Y)Z.push(Y);else Z.length=0,Z.push(Y)}if(Z.length<h4)return;let W=$[$.length-1]?.name??"the tool";return Z.length=0,{role:"custom",customType:"system-reminder",content:[{type:"text",text:`You have called ${W} with identical arguments ${h4} times in a row and the result is not changing. Stop repeating it \u2014 try a different approach, or explain what is blocking you.`}],display:!0,timestamp:Date.now()}}function q3($){let Z=$.contentIndex??0;switch($.type){case"text_start":return{kind:"text_start",contentIndex:Z};case"text_delta":return{kind:"text_delta",contentIndex:Z,text:$.delta??""};case"text_end":return{kind:"text_end",contentIndex:Z};case"thinking_start":return{kind:"thinking_start",contentIndex:Z};case"thinking_delta":return{kind:"thinking_delta",contentIndex:Z,text:$.delta??""};case"thinking_end":return{kind:"thinking_end",contentIndex:Z};case"toolcall_start":return{kind:"toolcall_start",contentIndex:Z};case"toolcall_delta":return{kind:"toolcall_delta",contentIndex:Z,argsFragment:$.delta??""};case"toolcall_end":return{kind:"toolcall_end",contentIndex:Z,toolCallId:$.toolCall?.id??""};default:return}}async function O3($,Z,W,Q){let Y=Z.transformContext?await Z.transformContext($.messages):$.messages,G={...$.systemPrompt?{systemPrompt:$.systemPrompt}:{},messages:F$(Y),...$.tools?{tools:$.tools.map((H)=>({name:H.name,description:H.description,inputSchema:H.inputSchema}))}:{}},X=Z.provider.stream(Z.model,G,{...Z.streamOpts,...Z.thinkingLevel!==void 0?{thinkingLevel:Z.thinkingLevel}:{},signal:Q}),J=!1;for await(let H of X){if(H.type==="start"){J=!0,await W({type:"message_start",message:{...H.partial}});continue}if(H.type==="done"||H.type==="error")break;let V=q3(H);if(V)await W({type:"message_update",message:{...H.partial},delta:V})}let K=await X.result();if(!J)await W({type:"message_start",message:{...K}});return await W({type:"message_end",message:K}),{message:K,messages:Y}}function D6($,Z,W){return{role:"toolResult",toolCallId:$.id,toolName:$.name,content:Z.content??[],...Z.details!==void 0?{details:Z.details}:{},isError:W,timestamp:Date.now()}}async function wZ($,Z){await Z({type:"tool_execution_end",toolCallId:$.toolCallId,result:$}),await Z({type:"message_start",message:$}),await Z({type:"message_end",message:$})}async function N3($,Z){let W=[];for(let Q of $){await Z({type:"tool_execution_start",toolCallId:Q.id,toolName:Q.name,args:Q.arguments});let Y=D6(Q,S(`Tool call "${Q.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),!0);await wZ(Y,Z),W.push(Y)}return{results:W,terminate:!1,steering:[]}}async function M3($,Z){let W=[];for(let Q of $){await Z({type:"tool_execution_start",toolCallId:Q.id,toolName:Q.name,args:Q.arguments});let Y=D6(Q,S(`Tool call "${Q.name}" was not executed because a steering message interrupted the remaining tool calls. Re-evaluate the plan before re-issuing it.`),!0);await wZ(Y,Z),W.push(Y)}return W}async function j3($,Z,W,Q,Y){let G=W.tools?.find((X)=>X.name===$.name);if(!G)return{kind:"immediate",result:S(`Tool ${$.name} not found`)};try{let X=$.arguments,J=await Q.beforeToolCall?.({assistantMessage:Z,toolCall:$,args:X,context:W},Y);if(Y.aborted)return{kind:"immediate",result:S("Operation aborted")};if(J?.block)return{kind:"immediate",result:S(J.reason||"Tool execution was blocked")};if(J?.rewrittenArgs)X=J.rewrittenArgs;return{kind:"prepared",prepared:{call:$,tool:G,args:X}}}catch(X){return{kind:"immediate",result:S(X instanceof Error?X.message:String(X))}}}async function P3($,Z,W,Q,Y,G){let X,J;try{X=await $.tool.execute($.call.id,$.args,G,(K)=>{Y({type:"tool_execution_update",toolCallId:$.call.id,partial:K})}),J=X.isError===!0}catch(K){X=S(K instanceof Error?K.message:String(K)),J=!0}if(Q.afterToolCall)try{let K=await Q.afterToolCall({assistantMessage:Z,toolCall:$.call,args:$.args,context:W,result:X,isError:J},G);if(K)X=K,J=K.isError??J}catch(K){X=S(K instanceof Error?K.message:String(K)),J=!0}return{result:X,isError:J}}async function w3($,Z,W,Q,Y,G){let X=[],J=[],K=[],H=async(z)=>{await Y({type:"tool_execution_start",toolCallId:z.id,toolName:z.name,args:z.arguments});let F=await j3(z,Z,W,Q,G),D=F.kind==="immediate"?{result:F.result,isError:!0}:await P3(F.prepared,Z,W,Q,Y,G);return J.push(D.result.terminate===!0),D6(z,D.result,D.isError)},V=0;while(V<$.length){let z=$[V],F=W.tools?.find((A)=>A.name===z.name);if(!(F?PZ(F,z.arguments):!1)){let A=await H(z);if(await wZ(A,Y),X.push(A),V++,G.aborted)break;if(K=await Q.getSteeringMessages?.()??[],K.length>0)break;continue}let L=[];while(V<$.length&&L.length<D3){let A=$[V],q=W.tools?.find((O)=>O.name===A.name);if(!q||!PZ(q,A.arguments))break;L.push(A),V++}let U=await Promise.all(L.map(H));for(let A of U)await wZ(A,Y),X.push(A);if(G.aborted)break;if(K=await Q.getSteeringMessages?.()??[],K.length>0)break}if(K.length>0&&V<$.length)X.push(...await M3($.slice(V),Y));return{results:X,terminate:J.length>0&&J.every(Boolean),steering:K}}var L6="[output cleared to save context \u2014 re-run the tool if you need it]",m4="[image cleared to save context]";function u4($){return $.type==="image"&&$.evictable!==!1}function U6($,Z={}){let W=Z.keepRecent??6,Q=S0($),Y=Z.targetTokens,G=[...$],X=Math.max(0,G.length-W),J=0,K=()=>Y!==void 0&&S0(G)<=Y;for(let H=0;H<X;H++){let V=G[H];if(!V||V.role!=="toolResult"||V.evicted)continue;if(K())break;if(!V.content.some(u4))continue;G[H]={...V,content:V.content.map((F)=>u4(F)?{type:"text",text:m4}:F)},J++}for(let H=0;H<X;H++){let V=G[H];if(!V||V.role!=="toolResult"||V.evicted)continue;if(K())break;if(V.isError)continue;if(V.content.filter((F)=>F.type==="text").map((F)=>F.text).join("").length<L6.length)continue;G[H]={...V,content:[{type:"text",text:L6}],evicted:!0},J++}return{messages:G,evicted:J,tokensFreed:Math.max(0,Q-S0(G))}}var A6=0.6;function l4($,Z){if($==="*")return!0;let W=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${W}$`,"s").test(Z)}function q6($,Z,W){let Q="ask";for(let Y of $)if(l4(Y.permission,Z)&&l4(Y.pattern,W))Q=Y.action;return Q}var T3=new TextEncoder,q1=new TextDecoder;function p4($,Z){if($.length===0)return Z.slice();if(Z.length===0)return $;let W=new Uint8Array($.length+Z.length);return W.set($),W.set(Z,$.length),W}function I3($,Z){let W=Math.min($.length,Math.max(0,Z));while(W>0&&($[W]??0)>=128&&($[W]??0)<192)W-=1;if(W===$.length)return W;let Q=$[W]??0,Y=Q<128?1:Q<224?2:Q<240?3:4;return W+Y<=Z?W+Y:W}function E3($,Z){let W=Math.max(0,Z);while(W<$.length&&($[W]??0)>=128&&($[W]??0)<192)W+=1;return W}class O6{headLimit;tailLimit;head=new Uint8Array;tail=new Uint8Array;headComplete=!1;total=0;constructor($=8000,Z=8000){this.headLimit=$;this.tailLimit=Z}append($){let Z=T3.encode($);if(this.total+=Z.length,!this.headComplete&&this.head.length<this.headLimit){let W=this.headLimit-this.head.length,Q=I3(Z,W);if(this.head=p4(this.head,Z.subarray(0,Q)),Z=Z.subarray(Q),Z.length===0)return;this.headComplete=!0}if(this.tail=p4(this.tail,Z),this.tail.length>this.tailLimit){let W=this.tail.length-this.tailLimit;this.tail=this.tail.slice(E3(this.tail,W))}}get bytes(){return this.total}get truncated(){return this.droppedBytes>0}read(){let $=q1.decode(this.head),Z=q1.decode(this.tail);if(this.droppedBytes===0)return $+Z;return`${$}
53
+ ${T6}`}],messages:[{role:"user",content:[{type:"text",text:q}],timestamp:Date.now()}]};if(V=await Z.provider.stream(Z.model,A,{...Z.streamOpts,sessionId:`${Z.streamOpts?.sessionId??"mu"}:compact:${Date.now().toString(36)}:${F}`,maxTokens:Math.min(Z.model.maxOutput,8192),...Z.signal?{signal:Z.signal}:{}}).result(),!C$(V)||z.length<=1||F+1>=oK)break;z=z.slice(Math.max(1,Math.floor(z.length/2))),F++}if(V.stopReason!=="end")throw new _0(`Compaction failed: ${V.errorMessage??`incomplete response (${V.stopReason})`}`,V.usage);let D=V.content.filter((U)=>U.type==="text").map((U)=>U.text).join("").trim();if(D.length===0)throw new _0("Compaction failed: the provider returned no usable summary",V.usage);let L={summary:D,...J!==void 0?{carryover:J}:{},keptMessages:X,tokensFreed:0,usage:V.usage};return L.tokensFreed=Math.max(0,p($)-p(b$(L))),L}function b$($){if($.summary.length===0)return $.keptMessages;return[_$($.summary,$.carryover),...$.keptMessages]}function _$($,Z,Q=Date.now()){let W=Z===void 0?"":`
54
+
55
+ Carried forward:
56
+ ${QW(Z)}`;return{role:"custom",customType:"compaction-summary",content:[{type:"text",text:`Summary of the earlier conversation:
57
+
58
+ ${$}${W}`}],display:!1,timestamp:Q}}function QW($){if(typeof $==="string")return $;return xZ($),JSON.stringify(I6($),null,2)}function xZ($,Z=new Set){if($===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return;if(typeof $!=="object")throw new _0("Compaction failed: carryover must be JSON-serializable");let Q=Object.getPrototypeOf($);if(!Array.isArray($)&&Q!==Object.prototype&&Q!==null)throw new _0("Compaction failed: carryover must contain only plain objects");if(Z.has($))throw new _0("Compaction failed: carryover must not contain cycles");if(Z.add($),Array.isArray($))for(let W of $)xZ(W,Z);else for(let W of Object.values($))xZ(W,Z);Z.delete($)}function I6($){if(Array.isArray($))return $.map(I6);if($&&typeof $==="object")return Object.fromEntries(Object.entries($).sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0).map(([Z,Q])=>[Z,I6(Q)]));return $}class R6{tools=new Map;commands=new M1;providers=new Map;models=new Map;renderers=new Map;logs=[];extensions=[];eventHandlers=new Map;toolCallHooks=[];toolResultHooks=[];contextHooks=[];inputHooks=[];async register($){let Z={on:(Q,W)=>{let Y=this.eventHandlers.get(Q)??[];Y.push(W),this.eventHandlers.set(Q,Y)},onToolCall:(Q)=>void this.toolCallHooks.push(Q),onToolResult:(Q)=>void this.toolResultHooks.push(Q),onContext:(Q)=>void this.contextHooks.push(Q),onInput:(Q)=>void this.inputHooks.push(Q),registerTool:(Q)=>void this.tools.set(Q.name,Q),registerCommand:(Q)=>this.commands.register(Q),registerProvider:(Q)=>void this.providers.set(Q.id,Q),registerModels:(Q)=>{for(let W of Q)this.models.set(`${W.provider}/${W.id}`,W)},registerRenderer:(Q,W)=>void this.renderers.set(Q,W),log:(Q)=>void this.logs.push(`[${$.name}] ${Q}`)};await $.activate(Z),this.extensions.push($)}async shutdown(){for(let $ of this.extensions)await $.deactivate?.();this.extensions=[]}emit($){for(let Z of this.eventHandlers.get($.type)??[])Z($)}emitLifecycle($){for(let Z of this.eventHandlers.get($.type)??[])Z($)}findModel($){if($.indexOf("/")!==-1)return this.models.get($);return[...this.models.values()].find((Q)=>Q.id===$)}async runToolCallHooks($){let Z=$.args;for(let Q of this.toolCallHooks){let W=await Q({...$,args:Z});if(W?.block)return W;if(W?.args)Z=W.args}return Z===$.args?void 0:{args:Z}}async runToolResultHooks($){let Z=$.result.content,Q=$.isError,W=!1;for(let Y of this.toolResultHooks){let G=await Y({...$,result:{...$.result,content:Z},isError:Q});if(!G)continue;if(G.content)Z=G.content,W=!0;if(G.isError!==void 0)Q=G.isError,W=!0}return W?{content:Z,isError:Q}:void 0}async runContextHooks($){let Z=$;for(let Q of this.contextHooks)Z=await Q(Z);return Z}async runInputHooks($){let Z=$;for(let Q of this.inputHooks){let W=await Q(Z);if(W?.consume)return{consume:!0,...W.text!==void 0?{text:W.text}:{}};if(W?.text!==void 0)Z=W.text}return Z===$?void 0:{text:Z}}get hasContextHooks(){return this.contextHooks.length>0}}function WW($){let Z=$.customType,Q=[];for(let W of $.content)Q.push(W.type==="text"?{type:"text",text:`<${Z}>
59
+ ${W.text}
60
+ </${Z}>`}:W);return{role:"user",content:Q,timestamp:$.timestamp}}function C6($){return $.map((Z)=>Z.role==="custom"?WW(Z):Z)}function t1($){return{role:"user",content:[{type:"text",text:$}],timestamp:Date.now()}}function k$($,Z,Q=!1){return{role:"custom",customType:$,content:[{type:"text",text:Z}],display:Q,timestamp:Date.now()}}function y($){return{content:[{type:"text",text:$}],isError:!0}}function YW($){return{content:[{type:"text",text:$}]}}function vZ($,Z){if($.executionMode==="sequential")return!1;if(!$.isConcurrencySafe)return!1;try{return $.isConcurrencySafe(Z)===!0}catch{return!1}}var sK=10,GW=3;function eK($){return $.content.filter((Z)=>Z.type==="toolCall")}function $B($){return`${$.name}:${JSON.stringify($.arguments)}`}async function S6($,Z,Q,W,Y){let G=Y??new AbortController().signal,X=[...$],J={...Z,messages:[...Z.messages,...$]},K=Q,B=0,z=[],V=async(D)=>{return await W({type:"agent_end",messages:X,reason:D}),{messages:X,reason:D}};await W({type:"agent_start"});for(let D of $)await W({type:"message_start",message:D}),await W({type:"message_end",message:D});let F=await K.getSteeringMessages?.()??[];for(;;){let D=!0;while(D||F.length>0){if(G.aborted)return V("aborted");if(K.maxTurns!==void 0&&B>=K.maxTurns)return V("maxTurns");B++,await W({type:"turn_start"});for(let O of F)await W({type:"message_start",message:O}),await W({type:"message_end",message:O}),J.messages.push(O),X.push(O);if(F=[],K.prepareContext){let O=await K.prepareContext(J.messages),C=Array.isArray(O)?{messages:O}:O;if(J={...J,messages:C.messages},C.stop)return V("budget")}let U=await WB(J,K,W,G),q=U.message;if(J.messages.push(q),X.push(q),q.stopReason==="error"||q.stopReason==="aborted"){if(await W({type:"turn_end",message:q,toolResults:[]}),q.stopReason==="error"&&await K.recoverFromError?.(q)===!0){D=!0;continue}return V(q.stopReason==="aborted"?"aborted":"error")}let A=eK(q),N=[];if(D=!1,A.length>0){let O=q.stopReason==="length"?await YB(A,W):await KB(A,q,J,K,W,G);N.push(...O.results),F.push(...O.steering),D=!O.terminate;for(let v of O.results)J.messages.push(v),X.push(v);let C=ZB(A,z);if(C)J.messages.push(C),X.push(C),await W({type:"message_start",message:C}),await W({type:"message_end",message:C})}await W({type:"turn_end",message:q,toolResults:N});let j={message:q,toolResults:N,context:J,requestMessages:U.messages,newMessages:X},P=await K.prepareNextTurn?.(j);if(P){if(P.context)J=P.context;K={...K,...P.model?{model:P.model}:{},...P.thinkingLevel!==void 0?{thinkingLevel:P.thinkingLevel}:{}}}if(await K.shouldStopAfterTurn?.(j))return V("done");F.push(...await K.getSteeringMessages?.()??[])}let L=await K.getFollowUpMessages?.()??[];if(L.length>0){F=L;continue}break}return V("done")}function ZB($,Z){for(let W of $){let Y=$B(W);if(Z[Z.length-1]===Y)Z.push(Y);else Z.length=0,Z.push(Y)}if(Z.length<GW)return;let Q=$[$.length-1]?.name??"the tool";return Z.length=0,{role:"custom",customType:"system-reminder",content:[{type:"text",text:`You have called ${Q} with identical arguments ${GW} times in a row and the result is not changing. Stop repeating it \u2014 try a different approach, or explain what is blocking you.`}],display:!0,timestamp:Date.now()}}function QB($){let Z=$.contentIndex??0;switch($.type){case"text_start":return{kind:"text_start",contentIndex:Z};case"text_delta":return{kind:"text_delta",contentIndex:Z,text:$.delta??""};case"text_end":return{kind:"text_end",contentIndex:Z};case"thinking_start":return{kind:"thinking_start",contentIndex:Z};case"thinking_delta":return{kind:"thinking_delta",contentIndex:Z,text:$.delta??""};case"thinking_end":return{kind:"thinking_end",contentIndex:Z};case"toolcall_start":return{kind:"toolcall_start",contentIndex:Z};case"toolcall_delta":return{kind:"toolcall_delta",contentIndex:Z,argsFragment:$.delta??""};case"toolcall_end":return{kind:"toolcall_end",contentIndex:Z,toolCallId:$.toolCall?.id??""};default:return}}async function WB($,Z,Q,W){let Y=Z.transformContext?await Z.transformContext($.messages):$.messages,G={...$.systemPrompt?{systemPrompt:$.systemPrompt}:{},messages:C6(Y),...$.tools?{tools:$.tools.map((B)=>({name:B.name,description:B.description,inputSchema:B.inputSchema}))}:{}},X=Z.provider.stream(Z.model,G,{...Z.streamOpts,...Z.thinkingLevel!==void 0?{thinkingLevel:Z.thinkingLevel}:{},signal:W}),J=!1;for await(let B of X){if(B.type==="start"){J=!0,await Q({type:"message_start",message:{...B.partial}});continue}if(B.type==="done"||B.type==="error")break;let z=QB(B);if(z)await Q({type:"message_update",message:{...B.partial},delta:z})}let K=await X.result();if(!J)await Q({type:"message_start",message:{...K}});return await Q({type:"message_end",message:K}),{message:K,messages:Y}}function y6($,Z,Q){return{role:"toolResult",toolCallId:$.id,toolName:$.name,content:Z.content??[],...Z.details!==void 0?{details:Z.details}:{},isError:Q,timestamp:Date.now()}}async function gZ($,Z){await Z({type:"tool_execution_end",toolCallId:$.toolCallId,result:$}),await Z({type:"message_start",message:$}),await Z({type:"message_end",message:$})}async function YB($,Z){let Q=[];for(let W of $){await Z({type:"tool_execution_start",toolCallId:W.id,toolName:W.name,args:W.arguments});let Y=y6(W,y(`Tool call "${W.name}" was not executed: the response hit the output token limit, so its arguments may be truncated. Re-issue the tool call with complete arguments.`),!0);await gZ(Y,Z),Q.push(Y)}return{results:Q,terminate:!1,steering:[]}}async function GB($,Z){let Q=[];for(let W of $){await Z({type:"tool_execution_start",toolCallId:W.id,toolName:W.name,args:W.arguments});let Y=y6(W,y(`Tool call "${W.name}" was not executed because a steering message interrupted the remaining tool calls. Re-evaluate the plan before re-issuing it.`),!0);await gZ(Y,Z),Q.push(Y)}return Q}async function XB($,Z,Q,W,Y){let G=Q.tools?.find((X)=>X.name===$.name);if(!G)return{kind:"immediate",result:y(`Tool ${$.name} not found`)};try{let X=$.arguments,J=await W.beforeToolCall?.({assistantMessage:Z,toolCall:$,args:X,context:Q},Y);if(Y.aborted)return{kind:"immediate",result:y("Operation aborted")};if(J?.block)return{kind:"immediate",result:y(J.reason||"Tool execution was blocked")};if(J?.rewrittenArgs)X=J.rewrittenArgs;return{kind:"prepared",prepared:{call:$,tool:G,args:X}}}catch(X){return{kind:"immediate",result:y(X instanceof Error?X.message:String(X))}}}async function JB($,Z,Q,W,Y,G){let X,J;try{X=await $.tool.execute($.call.id,$.args,G,(K)=>{Y({type:"tool_execution_update",toolCallId:$.call.id,partial:K})}),J=X.isError===!0}catch(K){X=y(K instanceof Error?K.message:String(K)),J=!0}if(W.afterToolCall)try{let K=await W.afterToolCall({assistantMessage:Z,toolCall:$.call,args:$.args,context:Q,result:X,isError:J},G);if(K)X=K,J=K.isError??J}catch(K){X=y(K instanceof Error?K.message:String(K)),J=!0}return{result:X,isError:J}}async function KB($,Z,Q,W,Y,G){let X=[],J=[],K=[],B=async(V)=>{await Y({type:"tool_execution_start",toolCallId:V.id,toolName:V.name,args:V.arguments});let F=await XB(V,Z,Q,W,G),D=F.kind==="immediate"?{result:F.result,isError:!0}:await JB(F.prepared,Z,Q,W,Y,G);return J.push(D.result.terminate===!0),y6(V,D.result,D.isError)},z=0;while(z<$.length){let V=$[z],F=Q.tools?.find((q)=>q.name===V.name);if(!(F?vZ(F,V.arguments):!1)){let q=await B(V);if(await gZ(q,Y),X.push(q),z++,G.aborted)break;if(K=await W.getSteeringMessages?.()??[],K.length>0)break;continue}let L=[];while(z<$.length&&L.length<sK){let q=$[z],A=Q.tools?.find((N)=>N.name===q.name);if(!A||!vZ(A,q.arguments))break;L.push(q),z++}let U=await Promise.all(L.map(B));for(let q of U)await gZ(q,Y),X.push(q);if(G.aborted)break;if(K=await W.getSteeringMessages?.()??[],K.length>0)break}if(K.length>0&&z<$.length)X.push(...await GB($.slice(z),Y));return{results:X,terminate:J.length>0&&J.every(Boolean),steering:K}}var b6="[output cleared to save context \u2014 re-run the tool if you need it]",JW="[image cleared to save context]";function XW($){return $.type==="image"&&$.evictable!==!1}function hZ($,Z={}){let Q=Z.keepRecent??6,W=p($),Y=Z.targetTokens,G=[...$],X=Math.max(0,G.length-Q),J=0,K=()=>Y!==void 0&&p(G)<=Y;for(let B=0;B<X;B++){let z=G[B];if(!z||z.role!=="toolResult"||z.evicted)continue;if(K())break;if(!z.content.some(XW))continue;G[B]={...z,content:z.content.map((F)=>XW(F)?{type:"text",text:JW}:F)},J++}for(let B=0;B<X;B++){let z=G[B];if(!z||z.role!=="toolResult"||z.evicted)continue;if(K())break;if(z.isError)continue;if(z.content.filter((F)=>F.type==="text").map((F)=>F.text).join("").length<b6.length)continue;G[B]={...z,content:[{type:"text",text:b6}],evicted:!0},J++}return{messages:G,evicted:J,tokensFreed:Math.max(0,W-p(G))}}var _6=0.6;function KW($,Z){if($==="*")return!0;let Q=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${Q}$`,"s").test(Z)}function k6($,Z,Q){let W=typeof Z==="string"?[Z]:Z,Y="ask";for(let G of $)if(W.some((X)=>KW(G.permission,X))&&KW(G.pattern,Q))Y=G.action;return Y}var BB=new TextEncoder,I1=new TextDecoder;function BW($,Z){if($.length===0)return Z.slice();if(Z.length===0)return $;let Q=new Uint8Array($.length+Z.length);return Q.set($),Q.set(Z,$.length),Q}function HB($,Z){let Q=Math.min($.length,Math.max(0,Z));while(Q>0&&($[Q]??0)>=128&&($[Q]??0)<192)Q-=1;if(Q===$.length)return Q;let W=$[Q]??0,Y=W<128?1:W<224?2:W<240?3:4;return Q+Y<=Z?Q+Y:Q}function VB($,Z){let Q=Math.max(0,Z);while(Q<$.length&&($[Q]??0)>=128&&($[Q]??0)<192)Q+=1;return Q}class x6{headLimit;tailLimit;head=new Uint8Array;tail=new Uint8Array;headComplete=!1;total=0;constructor($=8000,Z=8000){this.headLimit=$;this.tailLimit=Z}append($){let Z=BB.encode($);if(this.total+=Z.length,!this.headComplete&&this.head.length<this.headLimit){let Q=this.headLimit-this.head.length,W=HB(Z,Q);if(this.head=BW(this.head,Z.subarray(0,W)),Z=Z.subarray(W),Z.length===0)return;this.headComplete=!0}if(this.tail=BW(this.tail,Z),this.tail.length>this.tailLimit){let Q=this.tail.length-this.tailLimit;this.tail=this.tail.slice(VB(this.tail,Q))}}get bytes(){return this.total}get truncated(){return this.droppedBytes>0}read(){let $=I1.decode(this.head),Z=I1.decode(this.tail);if(this.droppedBytes===0)return $+Z;return`${$}
39
61
 
40
62
  \u2026 [${this.droppedBytes} bytes omitted] \u2026
41
63
 
42
- ${Z}`}readSince($){if($>=this.total)return{text:"",offset:this.total,gap:!1};let Z=this.total-this.tail.length;if($<this.head.length){let W=q1.decode(this.head.slice($)),Q=Z>this.head.length;return{text:Q?`${W}
64
+ ${Z}`}readSince($){if($>=this.total)return{text:"",offset:this.total,gap:!1};let Z=this.total-this.tail.length;if($<this.head.length){let Q=I1.decode(this.head.slice($)),W=Z>this.head.length;return{text:W?`${Q}
43
65
 
44
66
  \u2026 [output omitted] \u2026
45
67
 
46
- ${q1.decode(this.tail)}`:W+q1.decode(this.tail),offset:this.total,gap:Q}}if($<Z)return{text:`\u2026 [output omitted] \u2026
68
+ ${I1.decode(this.tail)}`:Q+I1.decode(this.tail),offset:this.total,gap:W}}if($<Z)return{text:`\u2026 [output omitted] \u2026
47
69
 
48
- ${q1.decode(this.tail)}`,offset:this.total,gap:!0};return{text:q1.decode(this.tail.slice($-Z)),offset:this.total,gap:!1}}get droppedBytes(){return this.total-this.head.length-this.tail.length}}class TZ{spawn;events;tasks=new Map;counter=0;constructor($,Z={}){this.spawn=$;this.events=Z}setEvents($){this.events=$}start($,Z={}){let W=`task_${++this.counter}`,Q=new O6,Y={id:W,command:$,status:"running",exitCode:null,startedAt:Date.now(),outputBytes:0,truncated:!1,detached:!1},G=this.spawn({command:$,cols:Z.cols??80,rows:Z.rows??24,onOutput:(J)=>{Q.append(J),Y.outputBytes=Q.bytes,Y.truncated=Q.truncated,this.events.onOutput?.(W,J)}}),X={info:Y,buffer:Q,handle:G,readOffset:0,killRequested:!1};return this.tasks.set(W,X),this.events.onStarted?.({...Y}),G.exited.then((J)=>{if(Y.status==="running")Y.status=X.killRequested||J===null?"killed":"exited";Y.exitCode=J,Y.endedAt=Date.now(),this.events.onExited?.({...Y})}),{...Y}}get($){let Z=this.tasks.get($);return Z?{...Z.info}:void 0}list(){return[...this.tasks.values()].map(($)=>({...$.info}))}get runningCount(){return[...this.tasks.values()].filter(($)=>$.info.status==="running").length}output($,Z){let W=this.tasks.get($);if(!W)return;if(Z==="new"){let{text:Q,offset:Y}=W.buffer.readSince(W.readOffset);return W.readOffset=Y,{text:Q,truncated:W.buffer.truncated}}return W.readOffset=W.buffer.bytes,{text:W.buffer.read(),truncated:W.buffer.truncated}}writeStdin($,Z){let W=this.tasks.get($);if(!W||W.info.status!=="running")return!1;return W.handle.write(Z),!0}resize($,Z,W){let Q=this.tasks.get($);if(!Q||Q.info.status!=="running"||Z<=0||W<=0)return!1;return Q.handle.resize(Z,W),!0}resizeAll($,Z){for(let W of this.tasks.values())if(W.info.status==="running")W.handle.resize($,Z)}detach($){let Z=this.tasks.get($);if(!Z||Z.info.status!=="running"||Z.info.detached)return!1;return Z.info.detached=!0,Z.handle.detach(),!0}kill($){let Z=this.tasks.get($);if(!Z||Z.info.status!=="running"||Z.killRequested)return!1;return Z.killRequested=!0,Z.handle.kill(),!0}stopAll(){this.requestStops()}async killAll(){let $=this.requestStops();await Promise.allSettled($)}requestStops(){let $=[];for(let Z of this.tasks.values())if(Z.info.status==="running"&&!Z.info.detached){if($.push(Z.handle.exited),!Z.killRequested)Z.killRequested=!0,Z.handle.kill()}return $}async wait($){let Z=this.tasks.get($);if(!Z)return;return await Z.handle.exited,this.get($)}}function N6($){let Z=$.status==="killed"?"was killed":$.exitCode===0?"finished successfully":`failed with exit code ${$.exitCode}`,W=$.endedAt?`${$.endedAt-$.startedAt}ms`:"unknown duration";return`Background task ${$.id} (${$.command}) ${Z} after ${W}. Use task_output to read its output.`}function M6($){if($.stopReason!=="error")return!1;return OZ($.errorMessage??"")}var w$=1;function d4($){return $.type!=="session"}function i4($){return JSON.stringify($)}function n4($){return JSON.parse($)}function a4($){return $.map(i4).join(`
70
+ ${I1.decode(this.tail)}`,offset:this.total,gap:!0};return{text:I1.decode(this.tail.slice($-Z)),offset:this.total,gap:!1}}get droppedBytes(){return this.total-this.head.length-this.tail.length}}class uZ{spawn;events;tasks=new Map;counter=0;constructor($,Z={}){this.spawn=$;this.events=Z}setEvents($){this.events=$}start($,Z={}){let Q=`task_${++this.counter}`,W=new x6,Y={id:Q,command:$,status:"running",exitCode:null,startedAt:Date.now(),outputBytes:0,truncated:!1,detached:!1},G=this.spawn({command:$,cols:Z.cols??80,rows:Z.rows??24,onOutput:(J)=>{W.append(J),Y.outputBytes=W.bytes,Y.truncated=W.truncated,this.events.onOutput?.(Q,J)}}),X={info:Y,buffer:W,handle:G,readOffset:0,killRequested:!1};return this.tasks.set(Q,X),this.events.onStarted?.({...Y}),G.exited.then((J)=>{if(Y.status==="running")Y.status=X.killRequested||J===null?"killed":"exited";Y.exitCode=J,Y.endedAt=Date.now(),this.events.onExited?.({...Y})}),{...Y}}get($){let Z=this.tasks.get($);return Z?{...Z.info}:void 0}list(){return[...this.tasks.values()].map(($)=>({...$.info}))}get runningCount(){return[...this.tasks.values()].filter(($)=>$.info.status==="running").length}output($,Z){let Q=this.tasks.get($);if(!Q)return;if(Z==="new"){let{text:W,offset:Y}=Q.buffer.readSince(Q.readOffset);return Q.readOffset=Y,{text:W,truncated:Q.buffer.truncated}}return Q.readOffset=Q.buffer.bytes,{text:Q.buffer.read(),truncated:Q.buffer.truncated}}writeStdin($,Z){let Q=this.tasks.get($);if(!Q||Q.info.status!=="running")return!1;return Q.handle.write(Z),!0}resize($,Z,Q){let W=this.tasks.get($);if(!W||W.info.status!=="running"||Z<=0||Q<=0)return!1;return W.handle.resize(Z,Q),!0}resizeAll($,Z){for(let Q of this.tasks.values())if(Q.info.status==="running")Q.handle.resize($,Z)}detach($){let Z=this.tasks.get($);if(!Z||Z.info.status!=="running"||Z.info.detached)return!1;return Z.info.detached=!0,Z.handle.detach(),!0}kill($){let Z=this.tasks.get($);if(!Z||Z.info.status!=="running"||Z.killRequested)return!1;return Z.killRequested=!0,Z.handle.kill(),!0}stopAll(){this.requestStops()}async killAll(){let $=this.requestStops();await Promise.allSettled($)}requestStops(){let $=[];for(let Z of this.tasks.values())if(Z.info.status==="running"&&!Z.info.detached){if($.push(Z.handle.exited),!Z.killRequested)Z.killRequested=!0,Z.handle.kill()}return $}async wait($){let Z=this.tasks.get($);if(!Z)return;return await Z.handle.exited,this.get($)}}function f6($){let Z=$.status==="killed"?"was killed":$.exitCode===0?"finished successfully":`failed with exit code ${$.exitCode}`,Q=$.endedAt?`${$.endedAt-$.startedAt}ms`:"unknown duration";return`Background task ${$.id} (${$.command}) ${Z} after ${Q}. Use task_output to read its output.`}var x$=1;function VW($){return $.type!=="session"}function zW($){return JSON.stringify($)}function FW($){return JSON.parse($)}function DW($){return $.map(zW).join(`
49
71
  `)+($.length>0?`
50
- `:"")}function r4($){return $.split(`
51
- `).filter((Z)=>Z.trim().length>0).map(n4)}var c4=0;function t4(){return c4+=1,`e${Date.now().toString(36)}${c4.toString(36)}`}class Z0{entries=[];byId=new Map;headId=null;constructor($){if($)this.entries.push($)}static fromJsonl($){let Z=new Z0;for(let W of r4($))Z.push(W);return Z}toJsonl(){return a4(this.entries)}get header(){let $=this.entries[0];return $?.type==="session"?$:void 0}get head(){return this.headId}all(){return[...this.entries]}get($){return this.byId.get($)}has($){return $===null||this.byId.has($)}push($){if(this.entries.push($),d4($))this.byId.set($.id,$),this.headId=$.id}append($){let Z={...$,id:$.id??t4(),parentId:$.parentId!==void 0?$.parentId:this.headId};return this.push(Z),Z}appendMessage($,Z){return this.append({type:"message",message:$,...Z?{checkpointRef:Z}:{}})}pathTo($){let Z=[],W=new Set,Q=$;while(Q){if(W.has(Q))break;W.add(Q);let Y=this.byId.get(Q);if(!Y)break;Z.push(Y),Q=Y.parentId}return Z.reverse()}activePath(){return this.headId?this.pathTo(this.headId):[]}entryIdForMessage($){let Z=this.activePath();for(let W=Z.length-1;W>=0;W--){let Q=Z[W];if(Q?.type==="message"&&Q.message===$)return Q.id;if(Q?.type==="microcompaction"){let Y=Q.replacements.find((G)=>G.message===$);if(Y)return Y.entryId}}return}messagesAt($=this.headId){if(!$)return[];let Z=this.pathTo($),W=[];for(let Q of Z){if(Q.type==="message"){W.push({message:Q.message,entryId:Q.id});continue}if(Q.type==="microcompaction"){for(let Y of Q.replacements){let G=W.findIndex((X)=>X.entryId===Y.entryId);if(G!==-1)W[G]={message:Y.message,entryId:Y.entryId}}continue}if(Q.type==="compaction"){if(Q.firstKeptEntryId===null){W=[{message:U$(Q.summary,Q.carryover,Q.timestamp)}];continue}let Y=W.findIndex((G)=>G.entryId===Q.firstKeptEntryId);if(Y===-1)continue;W=[{message:U$(Q.summary,Q.carryover,Q.timestamp)},...W.slice(Y)]}}return W.map((Q)=>Q.message)}fork($){if($!==null&&!this.byId.has($))throw Error(`Cannot fork from unknown entry: ${$}`);this.headId=$}}class T${sessions=new Map;async load($){let Z=this.sessions.get($);return Z===void 0?void 0:Z0.fromJsonl(Z)}async save($,Z){this.sessions.set($,Z.toJsonl())}async list(){return[...this.sessions.keys()]}}import{createHash as R3}from"crypto";import{realpathSync as S3}from"fs";import{mkdir as o4,readFile as C3,rm as y3,writeFile as s4}from"fs/promises";import{homedir as b3}from"os";import{basename as k3,join as IZ,relative as I$,resolve as j6}from"path";function e4($=process.platform){return $==="win32"?"NUL":"/dev/null"}var _3=async($,Z,W)=>{let Q=Bun.spawn(["git",...$],{cwd:W,env:{...process.env,...Z},stdout:"pipe",stderr:"pipe",stdin:"ignore"}),[Y,G,X]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text(),Q.exited]);return{stdout:Y,stderr:G,exitCode:X}};function x3($){let Z=[];for(let W of $.split("\x00")){if(W.length===0)continue;let Q=W.indexOf("\t"),Y=W.indexOf("\t",Q+1);if(Q===-1||Y===-1)continue;let G=W.slice(0,Q),X=W.slice(Q+1,Y),J=W.slice(Y+1);Z.push({path:J,added:G==="-"?0:Number(G),removed:X==="-"?0:Number(X),hunks:[]})}return Z}function f3($){let Z=j6($);try{return S3.native(Z)}catch{return Z}}function v3($,Z){let W=(Z??k3($)).replace(/[^A-Za-z0-9._-]+/g,"-")||"workspace",Q=R3("sha256").update($).digest("hex").slice(0,16);return`${W}-${Q}`}class EZ{root;shadowDir;run;excludedPathspecs;initialized=!1;constructor($){this.root=f3($.root);let Z=v3(this.root,$.scope);this.shadowDir=$.shadowDir??IZ(b3(),".mu","checkpoints",Z),this.run=$.run??_3;let W=I$(this.root,this.shadowDir).replaceAll("\\","/");this.excludedPathspecs=[":(exclude,literal).git",":(exclude,glob).git/**",...W.length>0&&!W.startsWith("..")?[`:(exclude,literal)${W}`,`:(exclude,glob)${W}/**`]:[]]}get directory(){return this.shadowDir}env(){return{GIT_DIR:this.shadowDir,GIT_WORK_TREE:this.root,GIT_AUTHOR_NAME:"mu",GIT_AUTHOR_EMAIL:"mu@localhost",GIT_COMMITTER_NAME:"mu",GIT_COMMITTER_EMAIL:"mu@localhost",GIT_CONFIG_GLOBAL:e4(),GIT_CONFIG_NOSYSTEM:"1"}}async git(...$){return this.run($,this.env(),this.root)}async ensure(){if(this.initialized)return;await o4(this.shadowDir,{recursive:!0});let $=IZ(this.shadowDir,"mu-worktree");try{let Q=(await C3($,"utf8")).trim();if(Q!==this.root)throw Error(`Checkpoint store belongs to ${Q}, not ${this.root}`)}catch(Q){if(Q.code!=="ENOENT")throw Q;await s4($,`${this.root}
52
- `,"utf8")}if((await this.git("rev-parse","--git-dir")).exitCode!==0)await this.git("init","--quiet");let W=I$(this.root,this.shadowDir).replaceAll("\\","/");if(W.length>0&&!W.startsWith(".."))await o4(IZ(this.shadowDir,"info"),{recursive:!0}),await s4(IZ(this.shadowDir,"info","exclude"),`/${W}/
53
- `,"utf8");this.initialized=!0}async snapshot($){if(await this.ensure(),(await this.git("add","-A","--force","--",".",...this.excludedPathspecs)).exitCode!==0)return;if((await this.git("commit","--quiet","--allow-empty","--no-verify","-m",$??`checkpoint ${new Date().toISOString()}`)).exitCode!==0)return;let Y=(await this.git("rev-parse","HEAD")).stdout.trim();return Y.length>0?Y:void 0}async restore($){await this.ensure();let Z=await this.git("read-tree","--reset","-u",$);if(Z.exitCode!==0)throw Error(`Could not restore checkpoint ${$}: ${Z.stderr.trim()}`);let W=await this.git("clean","--force","-d","-x","--quiet","-e",".git",...I$(this.root,this.shadowDir).startsWith("..")?[]:["-e",I$(this.root,this.shadowDir).replaceAll("\\","/")]);if(W.exitCode!==0)throw Error(`Could not clean checkpoint ${$}: ${W.stderr.trim()}`)}async restoreResources($,Z){await this.ensure();let W=[...new Set(Z.map((J)=>{let K=j6(this.root,J),H=I$(this.root,K).replaceAll("\\","/");if(H.length===0||H===".."||H.startsWith("../"))throw Error(`Checkpoint resource escapes the workspace: ${J}`);return H}))];if(W.length===0)return;let Q=W.map((J)=>`:(literal)${J}`),Y=await this.git("reset","--quiet",$,"--",...Q);if(Y.exitCode!==0)throw Error(`Could not reset checkpoint ${$}: ${Y.stderr.trim()}`);let G=[],X=[];for(let J of W){let K=await this.git("ls-tree","-z",$,"--",`:(literal)${J}`);if(K.exitCode!==0)throw Error(`Could not inspect checkpoint ${$}: ${K.stderr.trim()}`);(K.stdout.length>0?G:X).push(J)}if(G.length>0){let J=await this.git("checkout","--force",$,"--",...G.map((K)=>`:(literal)${K}`));if(J.exitCode!==0)throw Error(`Could not restore checkpoint ${$}: ${J.stderr.trim()}`)}await Promise.all(X.map((J)=>y3(j6(this.root,J),{recursive:!0,force:!0})))}async diff($,Z){if(await this.ensure(),!Z){if((await this.git("add","-A","--force","--",".",...this.excludedPathspecs)).exitCode!==0)return[]}let W=Z?["diff","--no-renames","--numstat","-z",$,Z]:["diff","--no-renames","--cached","--numstat","-z",$],Q=await this.git(...W);if(Q.exitCode!==0)return[];let Y=x3(Q.stdout);for(let G of Y){let X=Z?["diff","--no-renames","--unified=3",$,Z,"--",G.path]:["diff","--no-renames","--cached","--unified=3",$,"--",G.path],J=await this.git(...X);if(J.exitCode===0)G.hunks=J.stdout.split(`
54
- `)}return Y}}import{createHash as g3}from"crypto";import{realpathSync as h3}from"fs";import{open as u3,readdir as GQ,realpath as $Q,stat as P6}from"fs/promises";import{homedir as m3}from"os";import{basename as I6,dirname as E$,extname as l3,isAbsolute as yZ,join as H0,relative as R6,resolve as A0,sep as p3}from"path";var SZ=32768,XQ=[".git"],JQ=[".mu/AGENTS.md","CLAUDE.local.md","CLAUDE.md","CLAUDE.MD",".claude/CLAUDE.md"],c3=["AGENTS.override.md","AGENTS.md","AGENTS.MD"],E6="project-instructions-",ZQ=5,d3=new Set(["",".md",".txt",".json",".yaml",".yml",".toml",".xml",".csv",".html",".css",".scss",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".sql",".graphql",".proto",".vue",".svelte",".astro",".php",".lua",".r",".R",".dart",".ex",".exs",".erl",".clj",".hs",".ml",".ini",".cfg",".conf",".properties",".lock",".rst",".adoc",".org",".tex",".diff",".patch"]);function R$($,Z){let W=R6(A0($),A0(Z));return W===""||!W.startsWith(`..${p3}`)&&W!==".."&&!yZ(W)}function RZ($){let Z=A0($);try{return h3.native(Z)}catch{return Z}}function i3($){if(!$||yZ($))return!1;let Z=$.replaceAll("\\","/");return Z!==".."&&!Z.startsWith("../")&&!Z.includes("/../")}function n3($){return[...new Set($.filter(i3))]}function w6($,Z){let W=g3("sha256");W.update(Z?"enabled\x00":"disabled\x00");for(let Q of $)W.update(Q.path),W.update("\x00"),W.update(Q.scope),W.update("\x00"),W.update(Q.parent??""),W.update("\x00"),W.update(Q.content),W.update("\x00");return W.digest("hex").slice(0,16)}async function WQ($,Z){let W=await u3($,"r");try{let Q=Buffer.alloc(Math.max(0,Z)+1),{bytesRead:Y}=await W.read(Q,0,Q.length,0);return Q.subarray(0,Y).toString("utf8")}finally{await W.close()}}function a3($){for(let Z=$.length-1;Z>=0;Z--){let W=$[Z];if(W?.role!=="custom"||!W.customType.startsWith(E6))continue;return W.customType.slice(E6.length)}return}function CZ($,Z){if(R$(Z,$.path))return R6(Z,$.path)||I6($.path);return $.path}function r3($,Z){let W=Z?"This is the complete current instruction snapshot. It supersedes every earlier project-instructions message in this conversation.":"Codebase and user instructions are shown below. Follow them carefully. Sources are ordered from lower to higher precedence; later instructions override conflicting earlier instructions.",Q=$.sources.length===0?"No instruction files are currently active.":$.sources.map((Y)=>{let G=Y.scope==="import"&&Y.parent?`imported by ${CZ({...Y,path:Y.parent},$.projectRoot)}`:`${Y.scope} instructions`;return`Contents of ${CZ(Y,$.projectRoot)} (${G}):
72
+ `:"")}function LW($){return $.split(`
73
+ `).filter((Z)=>Z.trim().length>0).map(FW)}var HW=0;function UW(){return HW+=1,`e${Date.now().toString(36)}${HW.toString(36)}`}class W0{entries=[];byId=new Map;headId=null;constructor($){if($)this.entries.push($)}static fromJsonl($){let Z=new W0;for(let Q of LW($))Z.push(Q);return Z}toJsonl(){return DW(this.entries)}get header(){let $=this.entries[0];return $?.type==="session"?$:void 0}get head(){return this.headId}all(){return[...this.entries]}get($){return this.byId.get($)}has($){return $===null||this.byId.has($)}push($){if(this.entries.push($),VW($))this.byId.set($.id,$),this.headId=$.id}append($){let Z={...$,id:$.id??UW(),parentId:$.parentId!==void 0?$.parentId:this.headId};return this.push(Z),Z}appendMessage($,Z){return this.append({type:"message",message:$,...Z?{checkpointRef:Z}:{}})}pathTo($){let Z=[],Q=new Set,W=$;while(W){if(Q.has(W))break;Q.add(W);let Y=this.byId.get(W);if(!Y)break;Z.push(Y),W=Y.parentId}return Z.reverse()}activePath(){return this.headId?this.pathTo(this.headId):[]}entryIdForMessage($){let Z=this.activePath();for(let Q=Z.length-1;Q>=0;Q--){let W=Z[Q];if(W?.type==="message"&&W.message===$)return W.id;if(W?.type==="microcompaction"){let Y=W.replacements.find((G)=>G.message===$);if(Y)return Y.entryId}}return}messagesAt($=this.headId){if(!$)return[];let Z=this.pathTo($),Q=[];for(let W of Z){if(W.type==="message"){Q.push({message:W.message,entryId:W.id});continue}if(W.type==="microcompaction"){for(let Y of W.replacements){let G=Q.findIndex((X)=>X.entryId===Y.entryId);if(G!==-1)Q[G]={message:Y.message,entryId:Y.entryId}}continue}if(W.type==="compaction"){if(W.firstKeptEntryId===null){Q=[{message:_$(W.summary,W.carryover,W.timestamp)}];continue}let Y=Q.findIndex((G)=>G.entryId===W.firstKeptEntryId);if(Y===-1)continue;Q=[{message:_$(W.summary,W.carryover,W.timestamp)},...Q.slice(Y)]}}return Q.map((W)=>W.message)}fork($){if($!==null&&!this.byId.has($))throw Error(`Cannot fork from unknown entry: ${$}`);this.headId=$}}class f${sessions=new Map;async load($){let Z=this.sessions.get($);return Z===void 0?void 0:W0.fromJsonl(Z)}async save($,Z){this.sessions.set($,Z.toJsonl())}async list(){return[...this.sessions.keys()]}}import{createHash as zB}from"crypto";import{realpathSync as FB}from"fs";import{mkdir as v6,readFile as qW,rm as AW,writeFile as g6}from"fs/promises";import{homedir as DB}from"os";import{basename as LB,join as v$,relative as g$,resolve as u6}from"path";function MW($=process.platform){return $==="win32"?"NUL":"/dev/null"}var UB=async($,Z,Q)=>{let W=Bun.spawn(["git",...$],{cwd:Q,env:{...process.env,...Z},stdout:"pipe",stderr:"pipe",stdin:"ignore",windowsHide:!0}),[Y,G,X]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{stdout:Y,stderr:G,exitCode:X}};function qB($){let Z=[];for(let Q of $.split("\x00")){if(Q.length===0)continue;let W=Q.indexOf("\t"),Y=Q.indexOf("\t",W+1);if(W===-1||Y===-1)continue;let G=Q.slice(0,W),X=Q.slice(W+1,Y),J=Q.slice(Y+1);Z.push({path:J,added:G==="-"?0:Number(G),removed:X==="-"?0:Number(X),hunks:[]})}return Z}function AB($){let Z=u6($);try{return FB.native(Z)}catch{return Z}}function NB($,Z){let Q=(Z??LB($)).replace(/[^A-Za-z0-9._-]+/g,"-")||"workspace",W=zB("sha256").update($).digest("hex").slice(0,16);return`${Q}-${W}`}var OB=new Set([".venv","venv","node_modules","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".nuxt",".cache","coverage"]),NW="2",h6=".mu";function MB($){let Z=$.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/+$/,"").split("/"),Q=Z.findIndex((W)=>OB.has(W));if(Q===-1)return;return Z.slice(0,Q+1).join("/")}function OW($){return`/${$.replaceAll("\\","\\\\").replace(/[?*[#]/g,"\\$&")}/`}class mZ{root;shadowDir;run;excludedPathspecs;initialized=!1;constructor($){this.root=AB($.root);let Z=NB(this.root,$.scope);this.shadowDir=$.shadowDir??v$(DB(),".mu","checkpoints",Z),this.run=$.run??UB;let Q=g$(this.root,this.shadowDir).replaceAll("\\","/");this.excludedPathspecs=[":(exclude,literal).git",":(exclude,glob).git/**",`:(exclude,literal)${h6}`,`:(exclude,glob)${h6}/**`,...Q.length>0&&!Q.startsWith("..")?[`:(exclude,literal)${Q}`,`:(exclude,glob)${Q}/**`]:[]]}get directory(){return this.shadowDir}env(){return{GIT_DIR:this.shadowDir,GIT_WORK_TREE:this.root,GIT_AUTHOR_NAME:"mu",GIT_AUTHOR_EMAIL:"mu@localhost",GIT_COMMITTER_NAME:"mu",GIT_COMMITTER_EMAIL:"mu@localhost",GIT_CONFIG_GLOBAL:MW(),GIT_CONFIG_NOSYSTEM:"1"}}async git(...$){return this.run($,this.env(),this.root)}async ensure(){if(this.initialized)return;await v6(this.shadowDir,{recursive:!0});let $=v$(this.shadowDir,"mu-worktree"),Z=!1;try{let G=(await qW($,"utf8")).trim();if(G!==this.root)throw Error(`Checkpoint store belongs to ${G}, not ${this.root}`);Z=!0}catch(G){if(G.code!=="ENOENT")throw G}let Q=v$(this.shadowDir,"mu-checkpoint-version");if(Z){if((await qW(Q,"utf8").catch((X)=>{if(X.code==="ENOENT")return;throw X}))?.trim()!==NW)await AW(this.shadowDir,{recursive:!0,force:!0}),await v6(this.shadowDir,{recursive:!0})}if(await g6($,`${this.root}
74
+ `,"utf8"),(await this.git("rev-parse","--git-dir")).exitCode!==0)await this.git("init","--quiet");await g6(Q,`${NW}
75
+ `,"utf8");let Y=g$(this.root,this.shadowDir).replaceAll("\\","/");if(Y.length>0&&!Y.startsWith(".."))await v6(v$(this.shadowDir,"info"),{recursive:!0}),await g6(v$(this.shadowDir,"info","exclude"),`/${Y}/
76
+ `,"utf8");this.initialized=!0}async ignoredDisposableDirectories(){let $=await this.git("ls-files","--cached","--others","--ignored","--exclude-standard","--directory","-z");if($.exitCode!==0)return[];let Z=new Set;for(let Q of $.stdout.split("\x00")){if(Q.length===0)continue;let W=MB(Q);if(W)Z.add(W)}return[...Z].sort()}checkpointPathspecs($){return[...this.excludedPathspecs,...$.map((Z)=>`:(exclude,literal)${Z}`)]}async snapshot($){await this.ensure();let Z=await this.ignoredDisposableDirectories();if((await this.git("add","-A","--force","--",".",...this.checkpointPathspecs(Z))).exitCode!==0)return;if((await this.git("commit","--quiet","--allow-empty","--no-verify","-m",$??`checkpoint ${new Date().toISOString()}`)).exitCode!==0)return;let G=(await this.git("rev-parse","HEAD")).stdout.trim();return G.length>0?G:void 0}async restore($){await this.ensure();let Z=await this.git("read-tree","--reset","-u",$);if(Z.exitCode!==0)throw Error(`Could not restore checkpoint ${$}: ${Z.stderr.trim()}`);let Q=await this.ignoredDisposableDirectories(),W=await this.git("clean","--force","-d","-x","--quiet","-e",".git","-e",OW(h6),...g$(this.root,this.shadowDir).startsWith("..")?[]:["-e",g$(this.root,this.shadowDir).replaceAll("\\","/")],...Q.flatMap((Y)=>["-e",OW(Y)]));if(W.exitCode!==0)throw Error(`Could not clean checkpoint ${$}: ${W.stderr.trim()}`)}async restoreResources($,Z){await this.ensure();let Q=[...new Set(Z.map((J)=>{let K=u6(this.root,J),B=g$(this.root,K).replaceAll("\\","/");if(B.length===0||B===".."||B.startsWith("../"))throw Error(`Checkpoint resource escapes the workspace: ${J}`);return B}))];if(Q.length===0)return;let W=Q.map((J)=>`:(literal)${J}`),Y=await this.git("reset","--quiet",$,"--",...W);if(Y.exitCode!==0)throw Error(`Could not reset checkpoint ${$}: ${Y.stderr.trim()}`);let G=[],X=[];for(let J of Q){let K=await this.git("ls-tree","-z",$,"--",`:(literal)${J}`);if(K.exitCode!==0)throw Error(`Could not inspect checkpoint ${$}: ${K.stderr.trim()}`);(K.stdout.length>0?G:X).push(J)}if(G.length>0){let J=await this.git("checkout","--force",$,"--",...G.map((K)=>`:(literal)${K}`));if(J.exitCode!==0)throw Error(`Could not restore checkpoint ${$}: ${J.stderr.trim()}`)}await Promise.all(X.map((J)=>AW(u6(this.root,J),{recursive:!0,force:!0})))}async diff($,Z){if(await this.ensure(),!Z){let G=await this.ignoredDisposableDirectories();if((await this.git("add","-A","--force","--",".",...this.checkpointPathspecs(G))).exitCode!==0)return[]}let Q=Z?["diff","--no-renames","--numstat","-z",$,Z]:["diff","--no-renames","--cached","--numstat","-z",$],W=await this.git(...Q);if(W.exitCode!==0)return[];let Y=qB(W.stdout);for(let G of Y){let X=Z?["diff","--no-renames","--unified=3",$,Z,"--",G.path]:["diff","--no-renames","--cached","--unified=3",$,"--",G.path],J=await this.git(...X);if(J.exitCode===0)G.hunks=J.stdout.split(`
77
+ `)}return Y}}import{createHash as jB}from"crypto";import{realpathSync as PB}from"fs";import{open as wB,readdir as EW,realpath as jW,stat as m6}from"fs/promises";import{homedir as TB}from"os";import{basename as c6,dirname as h$,extname as IB,isAbsolute as dZ,join as D0,relative as i6,resolve as O0,sep as EB}from"path";var pZ=32768,RW=[".git"],CW=[".mu/AGENTS.md","CLAUDE.local.md","CLAUDE.md","CLAUDE.MD",".claude/CLAUDE.md"],RB=["AGENTS.override.md","AGENTS.md","AGENTS.MD"],d6="project-instructions-",PW=5,CB=new Set(["",".md",".txt",".json",".yaml",".yml",".toml",".xml",".csv",".html",".css",".scss",".js",".jsx",".ts",".tsx",".mjs",".cjs",".py",".rb",".go",".rs",".java",".kt",".c",".cc",".cpp",".h",".hpp",".cs",".swift",".sh",".bash",".zsh",".fish",".ps1",".sql",".graphql",".proto",".vue",".svelte",".astro",".php",".lua",".r",".R",".dart",".ex",".exs",".erl",".clj",".hs",".ml",".ini",".cfg",".conf",".properties",".lock",".rst",".adoc",".org",".tex",".diff",".patch"]);function u$($,Z){let Q=i6(O0($),O0(Z));return Q===""||!Q.startsWith(`..${EB}`)&&Q!==".."&&!dZ(Q)}function lZ($){let Z=O0($);try{return PB.native(Z)}catch{return Z}}function SB($){if(!$||dZ($))return!1;let Z=$.replaceAll("\\","/");return Z!==".."&&!Z.startsWith("../")&&!Z.includes("/../")}function yB($){return[...new Set($.filter(SB))]}function l6($,Z){let Q=jB("sha256");Q.update(Z?"enabled\x00":"disabled\x00");for(let W of $)Q.update(W.path),Q.update("\x00"),Q.update(W.scope),Q.update("\x00"),Q.update(W.parent??""),Q.update("\x00"),Q.update(W.content),Q.update("\x00");return Q.digest("hex").slice(0,16)}async function wW($,Z){let Q=await wB($,"r");try{let W=Buffer.alloc(Math.max(0,Z)+1),{bytesRead:Y}=await Q.read(W,0,W.length,0);return W.subarray(0,Y).toString("utf8")}finally{await Q.close()}}function bB($){for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q?.role!=="custom"||!Q.customType.startsWith(d6))continue;return Q.customType.slice(d6.length)}return}function cZ($,Z){if(u$(Z,$.path))return i6(Z,$.path)||c6($.path);return $.path}function _B($,Z){let Q=Z?"This is the complete current instruction snapshot. It supersedes every earlier project-instructions message in this conversation.":"Codebase and user instructions are shown below. Follow them carefully. Sources are ordered from lower to higher precedence; later instructions override conflicting earlier instructions.",W=$.sources.length===0?"No instruction files are currently active.":$.sources.map((Y)=>{let G=Y.scope==="import"&&Y.parent?`imported by ${cZ({...Y,path:Y.parent},$.projectRoot)}`:`${Y.scope} instructions`;return`Contents of ${cZ(Y,$.projectRoot)} (${G}):
55
78
 
56
79
  ${Y.content.trim()}`}).join(`
57
80
 
58
- `);return D$(`${E6}${$.signature}`,`${W}
81
+ `);return k$(`${d6}${$.signature}`,`${Q}
59
82
 
60
- ${Q}`)}function QQ($){let Z=$.replaceAll(`\r
83
+ ${W}`)}function TW($){let Z=$.replaceAll(`\r
61
84
  `,`
62
85
  `);if(!Z.startsWith(`---
63
- `))return{content:$};let W=Z.indexOf(`
86
+ `))return{content:$};let Q=Z.indexOf(`
64
87
  ---
65
- `,4);if(W===-1)return{content:$};let Q=Z.slice(4,W),Y=Z.slice(W+5),G=Q.split(`
66
- `),X=[],J=!1;for(let K of G){let H=K.match(/^paths?\s*:\s*(.*)$/i);if(H){J=!0;let z=H[1]?.trim()??"";if(z){let F=z.startsWith("[")&&z.endsWith("]")?z.slice(1,-1):z;X.push(...F.split(",").map((D)=>D.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean))}continue}if(!J)continue;let V=K.match(/^\s*-\s*(.+?)\s*$/);if(V?.[1]){X.push(V[1].replace(/^['"]|['"]$/g,""));continue}if(K.trim())J=!1}return{content:Y,...X.length>0?{patterns:X}:{}}}function t3($){let Z="",W=$.replaceAll("\\","/").replace(/^\.\//,"");if(!W||W.startsWith("!"))return;for(let Q=0;Q<W.length;Q++){let Y=W[Q];if(Y==="*")if(W[Q+1]==="*")if(Q++,W[Q+1]==="/")Q++,Z+="(?:.*/)?";else Z+=".*";else Z+="[^/]*";else if(Y==="?")Z+="[^/]";else Z+=Y?.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")??""}try{return new RegExp(`^${Z}$`)}catch{return}}function o3($,Z){if(!$.patterns||$.patterns.length===0)return!0;let W=R6($.base,Z).replaceAll("\\","/");if(!W||W===".."||W.startsWith("../")||yZ(W))return!1;let Q=!1;for(let Y of $.patterns){let G=Y.startsWith("!");if(t3(G?Y.slice(1):Y)?.test(W))Q=!G}return Q}function s3($){let Z=new Set,W;for(let Q of $.split(/\r?\n/)){let Y=Q.match(/^\s*(`{3,}|~{3,})/);if(Y?.[1]){let J=Y[1][0];W=W===J?void 0:W??J;continue}if(W)continue;let G=Q.split(/(`[^`]*`)/g).filter((J)=>!J.startsWith("`")).join(" "),X=/(?:^|\s)@((?:\\ |[^\s`])+)/g;for(let J of G.matchAll(X)){let K=J[1]?.replace(/\\ /g," ");if(!K)continue;K=K.replace(/[),.;:!?]+$/,"");let H=K.indexOf("#");if(H>=0)K=K.slice(0,H);if(K&&!K.startsWith("@"))Z.add(K)}}return[...Z]}function T6($){return $<1024?`${$} B`:`${($/1024).toFixed(1)} KiB`}class bZ{root;home;settings;managedPaths;settingDiagnostics;current;nestedSources=new Map;nestedSerial=Promise.resolve();activeSessionId;constructor($){this.root=RZ($.root),this.home=RZ($.home??m3());let Z=[],W=(J,K,H)=>{if(J===void 0)return K;if(typeof J==="boolean")return J;return Z.push({level:"warning",message:`instructions.${H} must be a boolean; using ${K}`}),K},Q=(J,K,H)=>{if(J===void 0)return K;if(!Array.isArray(J)||J.some((z)=>typeof z!=="string"))return Z.push({level:"warning",message:`instructions.${H} must be an array of relative filenames; using defaults`}),K;let V=n3(J);if(V.length!==J.length)Z.push({level:"warning",message:`instructions.${H} ignored unsafe or duplicate entries`});return V},Y=Number.isSafeInteger($.maxBytes)&&($.maxBytes??0)>=0,G=Y?$.maxBytes:SZ;if($.maxBytes!==void 0&&!Y)Z.push({level:"warning",message:`instructions.maxBytes must be a non-negative safe integer; using ${SZ}`});this.settings={enabled:W($.enabled,!0,"enabled"),maxBytes:G,fallbackFilenames:Q($.fallbackFilenames,JQ,"fallbackFilenames"),projectRootMarkers:Q($.projectRootMarkers,XQ,"projectRootMarkers"),imports:W($.imports,!0,"imports"),claudeRules:W($.claudeRules,!0,"claudeRules")},this.settingDiagnostics=Z;let X=process.platform==="win32"?process.env.PROGRAMDATA?[H0(process.env.PROGRAMDATA,"mu","AGENTS.md")]:[]:["/etc/mu/AGENTS.md"];this.managedPaths=($.managedPaths??X).map((J)=>A0(J)),this.current={enabled:this.settings.enabled,projectRoot:this.root,sources:[],diagnostics:[],bytes:0,maxBytes:this.settings.maxBytes,truncated:!1,signature:w6([],this.settings.enabled)}}get snapshot(){return{...this.current,sources:this.current.sources.map(($)=>({...$})),diagnostics:this.current.diagnostics.map(($)=>({...$}))}}async reload($={}){if($.resetNested)this.nestedSources.clear();let Z=this.settingDiagnostics.map((J)=>({...J})),W=await this.findProjectRoot(Z);if(!this.settings.enabled||this.settings.maxBytes===0)return this.current={enabled:!1,projectRoot:W,sources:[],diagnostics:Z,bytes:0,maxBytes:this.settings.maxBytes,truncated:!1,signature:w6([],!1)},this.snapshot;let Q={budget:{remaining:this.settings.maxBytes,truncated:!1},processed:new Set,diagnostics:Z,sources:[]};for(let J of this.managedPaths)await this.loadSource(J,"managed",Q,void 0,E$(J),0);let Y=await this.firstReadableCandidate([H0(this.home,".mu","AGENTS.override.md"),H0(this.home,".mu","AGENTS.md"),H0(this.home,".mu","AGENTS.MD"),H0(this.home,".claude","CLAUDE.md")],Z);if(Y)await this.loadSource(Y,"global",Q,void 0,this.home,0);let G=this.dirsBetween(W,this.root);for(let J of G){for(let H of await this.rulesForDirectory(J,Z))if(!H.patterns)await this.loadSource(H.path,"rule",Q,void 0,W,0);let K=await this.primaryForDirectory(J,Z);if(K){let H=I6(K)==="CLAUDE.local.md"?"local":"project";await this.loadSource(K,H,Q,void 0,W,0)}}let X=this.settings.maxBytes-Q.budget.remaining;return this.current={enabled:!0,projectRoot:W,sources:Q.sources,diagnostics:Z,bytes:X,maxBytes:this.settings.maxBytes,truncated:Q.budget.truncated,signature:w6(Q.sources,!0)},this.snapshot}async refreshedMessages($,Z){let W=a3($);if(Z!==void 0&&Z!==this.activeSessionId)this.activeSessionId=Z,this.nestedSources.clear();else if(Z===void 0&&$.length===0)this.nestedSources.clear();let Q=await this.reload();if(Q.sources.length===0&&W===void 0)return[];if(W===Q.signature)return[];return[r3(Q,W!==void 0)]}async instructionsForPath($){let Z={text:"",sources:[]},W=this.nestedSerial,Q;this.nestedSerial=new Promise((Y)=>{Q=Y}),await W;try{Z=await this.loadNested($)}finally{Q?.()}return Z}formatStatus($="instructions"){if(!this.current.enabled)return`${$} disabled
67
- Use project/user config or remove --no-instructions to enable loading.`;let Z=[...this.current.sources,...this.nestedSources.values()],W=this.current.truncated||Z.some((G)=>G.truncated),Q=this.current.bytes+[...this.nestedSources.values()].reduce((G,X)=>G+Buffer.byteLength(X.content),0),Y=[`${$} \xB7 ${Z.length} file${Z.length===1?"":"s"} \xB7 ${T6(Q)}/${T6(this.current.maxBytes)}${W?" \xB7 truncated":""}`,...Z.map((G)=>{let X=G.truncated?" \xB7 truncated":"";return` ${G.scope.padEnd(7)} ${CZ(G,this.current.projectRoot)}${X}`})];if(Z.length===0)Y.push(" no instruction files found");if(this.current.diagnostics.length>0)Y.push("warnings:",...this.current.diagnostics.map((G)=>` ${G.path?`${G.path}: `:""}${G.message}`));return Y.push("precedence: managed < global < outer project < inner project; AGENTS.override.md wins within one directory"),Y.join(`
68
- `)}async discoverPrimaryFiles($){let Z=[],W=$?A0($):await this.findProjectRoot(Z),Q=[];for(let Y of this.dirsBetween(W,this.root)){let G=await this.primaryForDirectory(Y,Z);if(G)Q.push(G)}return Q}async findProjectRoot($){if(this.settings.projectRootMarkers.length===0)return this.root;let Z=this.root;for(;;){for(let Q of this.settings.projectRootMarkers){let Y=H0(Z,Q);try{return await P6(Y),Z}catch(G){let X=G.code;if(X!=="ENOENT"&&X!=="ENOTDIR")$.push({level:"warning",path:Y,message:`could not inspect project-root marker: ${G instanceof Error?G.message:String(G)}`})}}let W=E$(Z);if(W===Z)return this.root;Z=W}}dirsBetween($,Z){if(!R$($,Z))return[Z];let W=[],Q=Z;for(;;){if(W.push(Q),Q===$)break;let Y=E$(Q);if(Y===Q)break;Q=Y}return W.reverse()}async primaryForDirectory($,Z){return this.firstReadableCandidate([...c3.map((W)=>H0($,W)),...this.settings.fallbackFilenames.map((W)=>H0($,W))],Z)}async firstReadableCandidate($,Z){for(let W of $)try{if((await P6(W)).isFile())return W;Z.push({level:"warning",path:W,message:"instruction candidate is not a file"})}catch(Q){let Y=Q.code;if(Y==="ENOENT"||Y==="ENOTDIR")continue;Z.push({level:"warning",path:W,message:`could not inspect instruction file: ${Q instanceof Error?Q.message:String(Q)}`})}return}async ruleFiles($,Z){let W=[],Q=async(Y,G)=>{let X;try{X=await $Q(Y)}catch(K){let H=K.code;if(H==="ENOENT"||H==="ENOTDIR")return;Z.push({level:"warning",path:Y,message:`could not read rules directory: ${K instanceof Error?K.message:String(K)}`});return}if(G.has(X))return;G.add(X);let J;try{J=await GQ(Y,{withFileTypes:!0})}catch(K){Z.push({level:"warning",path:Y,message:`could not list rules directory: ${K instanceof Error?K.message:String(K)}`});return}for(let K of J.sort((H,V)=>H.name.localeCompare(V.name))){let H=H0(Y,K.name),V=K.isDirectory(),z=K.isFile();if(K.isSymbolicLink())try{let F=await P6(H);V=F.isDirectory(),z=F.isFile()}catch(F){Z.push({level:"warning",path:H,message:`could not inspect rule symlink: ${F instanceof Error?F.message:String(F)}`});continue}if(V)await Q(H,G);else if(z&&K.name.toLowerCase().endsWith(".md"))W.push(H)}};return await Q($,new Set),W}async rulesForDirectory($,Z){let W=[H0($,".mu","rules")];if(this.settings.claudeRules)W.push(H0($,".claude","rules"));let Q=[];for(let Y of W)for(let G of await this.ruleFiles(Y,Z))try{let X=QQ(await WQ(G,SZ));Q.push({path:G,base:$,...X.patterns?{patterns:X.patterns}:{}})}catch(X){Z.push({level:"warning",path:G,message:`could not read rule frontmatter: ${X instanceof Error?X.message:String(X)}`})}return Q}async loadSource($,Z,W,Q,Y,G){if(W.budget.remaining<=0){W.budget.truncated=!0;return}if(G>ZQ){W.diagnostics.push({level:"warning",path:$,message:`import depth exceeds ${ZQ}`});return}let X;try{X=await $Q($)}catch(z){let F=z.code;if(Q||F!=="ENOENT"&&F!=="ENOTDIR")W.diagnostics.push({level:"warning",path:$,message:F==="ENOENT"?`import referenced by ${Q} does not exist`:`could not resolve instruction file: ${z instanceof Error?z.message:String(z)}`});return}if(W.processed.has(X))return;if(!R$(Y,X)){W.diagnostics.push({level:"warning",path:$,message:`external import is outside the allowed instruction root ${Y}`});return}if(!d3.has(l3(X))){W.diagnostics.push({level:"warning",path:$,message:"skipped non-text instruction import"});return}W.processed.add(X);let J;try{J=await WQ(X,W.budget.remaining)}catch(z){W.diagnostics.push({level:"warning",path:$,message:`could not read instruction file: ${z instanceof Error?z.message:String(z)}`});return}if(J.includes("\x00")){W.diagnostics.push({level:"warning",path:$,message:"skipped binary instruction file"});return}let K=QQ(J),H=K.content.trim(),V;if(H&&W.budget.remaining>0){let z=Buffer.from(H),F=Math.min(z.byteLength,W.budget.remaining),D=z.subarray(0,F).toString("utf8").replace(/\uFFFD$/,""),L=F<z.byteLength;if(V={path:X,content:D,scope:Z,...Q?{parent:Q}:{},...L?{truncated:!0}:{}},W.budget.remaining-=F,L)W.budget.truncated=!0,W.diagnostics.push({level:"warning",path:X,message:`instruction content was truncated at the ${T6(this.settings.maxBytes)} total budget`})}if(this.settings.imports)for(let z of s3(K.content)){let F=z.startsWith("~/")?H0(this.home,z.slice(2)):yZ(z)?z:A0(E$(X),z);await this.loadSource(F,"import",W,X,Z==="global"?this.home:Y,G+1)}if(V)W.sources.push(V)}async loadNested($){if(!this.settings.enabled)return{text:"",sources:[]};let Z=A0($);if(!R$(this.root,Z))return{text:"",sources:[]};let W=E$(Z),Q=this.current.projectRoot,Y=this.current.diagnostics,G=[];for(let z of this.dirsBetween(Q,W)){for(let F of await this.rulesForDirectory(z,Y))if(A0(F.path)!==Z&&o3(F,Z))G.push({path:F.path,scope:"rule",allowedRoot:Q});if(R$(this.root,z)&&z!==this.root){let F=await this.primaryForDirectory(z,Y);if(F&&A0(F)!==Z)G.push({path:F,scope:I6(F)==="CLAUDE.local.md"?"local":"project",allowedRoot:Q})}}let X=this.settings.maxBytes-this.current.bytes-[...this.nestedSources.values()].reduce((z,F)=>z+Buffer.byteLength(F.content),0),J=new Set([...this.current.sources.map((z)=>RZ(z.path)),...this.nestedSources.keys()]),K=G.find((z)=>!J.has(RZ(z.path)));if(X<=0&&K){if(this.current.truncated=!0,!Y.some((z)=>z.path===K.path&&z.message==="nested instruction omitted because the total byte budget is exhausted"))Y.push({level:"warning",path:K.path,message:"nested instruction omitted because the total byte budget is exhausted"});return{text:"",sources:[]}}let H={budget:{remaining:Math.max(0,X),truncated:!1},processed:J,diagnostics:Y,sources:[]};for(let z of G)await this.loadSource(z.path,z.scope,H,void 0,z.allowedRoot,0);for(let z of H.sources)this.nestedSources.set(A0(z.path),z);if(H.sources.length===0)return{text:"",sources:[]};return{text:["<system-reminder>","Additional instructions apply to the file just read. Later sources have higher precedence:","",...H.sources.flatMap((z)=>[`Contents of ${CZ(z,Q)}:`,z.content.trim(),""]),"</system-reminder>"].join(`
69
- `),sources:H.sources.map((z)=>z.path)}}}async function YQ($,Z){try{let W=Bun.spawn(["git",...$],{cwd:Z,stdout:"pipe",stderr:"ignore"}),Q=await new Response(W.stdout).text();return await W.exited===0?Q:void 0}catch{return}}async function kZ($){let Z={directory:A0($),platform:process.platform,date:new Date().toISOString().slice(0,10)},Q=(await YQ(["rev-parse","--abbrev-ref","HEAD"],$))?.trim().split(/\r?\n/)[0];if(Q){Z.branch=Q;let Y=await YQ(["status","--porcelain"],$);if(Y!==void 0)Z.uncommittedFiles=String(Y.split(/\r?\n/).filter(Boolean).length)}try{let Y=await GQ($);Z.topLevelEntries=Y.filter((G)=>!G.startsWith(".")).sort().slice(0,40).join(", ")}catch{}return Z}function S6($){let Z=Object.entries($).map(([W,Q])=>`${W}: ${Q}`);return D$("environment",`Session environment:
88
+ `,4);if(Q===-1)return{content:$};let W=Z.slice(4,Q),Y=Z.slice(Q+5),G=W.split(`
89
+ `),X=[],J=!1;for(let K of G){let B=K.match(/^paths?\s*:\s*(.*)$/i);if(B){J=!0;let V=B[1]?.trim()??"";if(V){let F=V.startsWith("[")&&V.endsWith("]")?V.slice(1,-1):V;X.push(...F.split(",").map((D)=>D.trim().replace(/^['"]|['"]$/g,"")).filter(Boolean))}continue}if(!J)continue;let z=K.match(/^\s*-\s*(.+?)\s*$/);if(z?.[1]){X.push(z[1].replace(/^['"]|['"]$/g,""));continue}if(K.trim())J=!1}return{content:Y,...X.length>0?{patterns:X}:{}}}function kB($){let Z="",Q=$.replaceAll("\\","/").replace(/^\.\//,"");if(!Q||Q.startsWith("!"))return;for(let W=0;W<Q.length;W++){let Y=Q[W];if(Y==="*")if(Q[W+1]==="*")if(W++,Q[W+1]==="/")W++,Z+="(?:.*/)?";else Z+=".*";else Z+="[^/]*";else if(Y==="?")Z+="[^/]";else Z+=Y?.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")??""}try{return new RegExp(`^${Z}$`)}catch{return}}function xB($,Z){if(!$.patterns||$.patterns.length===0)return!0;let Q=i6($.base,Z).replaceAll("\\","/");if(!Q||Q===".."||Q.startsWith("../")||dZ(Q))return!1;let W=!1;for(let Y of $.patterns){let G=Y.startsWith("!");if(kB(G?Y.slice(1):Y)?.test(Q))W=!G}return W}function fB($){let Z=new Set,Q;for(let W of $.split(/\r?\n/)){let Y=W.match(/^\s*(`{3,}|~{3,})/);if(Y?.[1]){let J=Y[1][0];Q=Q===J?void 0:Q??J;continue}if(Q)continue;let G=W.split(/(`[^`]*`)/g).filter((J)=>!J.startsWith("`")).join(" "),X=/(?:^|\s)@((?:\\ |[^\s`])+)/g;for(let J of G.matchAll(X)){let K=J[1]?.replace(/\\ /g," ");if(!K)continue;K=K.replace(/[),.;:!?]+$/,"");let B=K.indexOf("#");if(B>=0)K=K.slice(0,B);if(K&&!K.startsWith("@"))Z.add(K)}}return[...Z]}function p6($){return $<1024?`${$} B`:`${($/1024).toFixed(1)} KiB`}class iZ{root;home;settings;managedPaths;settingDiagnostics;current;nestedSources=new Map;nestedSerial=Promise.resolve();activeSessionId;constructor($){this.root=lZ($.root),this.home=lZ($.home??TB());let Z=[],Q=(J,K,B)=>{if(J===void 0)return K;if(typeof J==="boolean")return J;return Z.push({level:"warning",message:`instructions.${B} must be a boolean; using ${K}`}),K},W=(J,K,B)=>{if(J===void 0)return K;if(!Array.isArray(J)||J.some((V)=>typeof V!=="string"))return Z.push({level:"warning",message:`instructions.${B} must be an array of relative filenames; using defaults`}),K;let z=yB(J);if(z.length!==J.length)Z.push({level:"warning",message:`instructions.${B} ignored unsafe or duplicate entries`});return z},Y=Number.isSafeInteger($.maxBytes)&&($.maxBytes??0)>=0,G=Y?$.maxBytes:pZ;if($.maxBytes!==void 0&&!Y)Z.push({level:"warning",message:`instructions.maxBytes must be a non-negative safe integer; using ${pZ}`});this.settings={enabled:Q($.enabled,!0,"enabled"),maxBytes:G,fallbackFilenames:W($.fallbackFilenames,CW,"fallbackFilenames"),projectRootMarkers:W($.projectRootMarkers,RW,"projectRootMarkers"),imports:Q($.imports,!0,"imports"),claudeRules:Q($.claudeRules,!0,"claudeRules")},this.settingDiagnostics=Z;let X=process.platform==="win32"?process.env.PROGRAMDATA?[D0(process.env.PROGRAMDATA,"mu","AGENTS.md")]:[]:["/etc/mu/AGENTS.md"];this.managedPaths=($.managedPaths??X).map((J)=>O0(J)),this.current={enabled:this.settings.enabled,projectRoot:this.root,sources:[],diagnostics:[],bytes:0,maxBytes:this.settings.maxBytes,truncated:!1,signature:l6([],this.settings.enabled)}}get snapshot(){return{...this.current,sources:this.current.sources.map(($)=>({...$})),diagnostics:this.current.diagnostics.map(($)=>({...$}))}}async reload($={}){if($.resetNested)this.nestedSources.clear();let Z=this.settingDiagnostics.map((J)=>({...J})),Q=await this.findProjectRoot(Z);if(!this.settings.enabled||this.settings.maxBytes===0)return this.current={enabled:!1,projectRoot:Q,sources:[],diagnostics:Z,bytes:0,maxBytes:this.settings.maxBytes,truncated:!1,signature:l6([],!1)},this.snapshot;let W={budget:{remaining:this.settings.maxBytes,truncated:!1},processed:new Set,diagnostics:Z,sources:[]};for(let J of this.managedPaths)await this.loadSource(J,"managed",W,void 0,h$(J),0);let Y=await this.firstReadableCandidate([D0(this.home,".mu","AGENTS.override.md"),D0(this.home,".mu","AGENTS.md"),D0(this.home,".mu","AGENTS.MD"),D0(this.home,".claude","CLAUDE.md")],Z);if(Y)await this.loadSource(Y,"global",W,void 0,this.home,0);let G=this.dirsBetween(Q,this.root);for(let J of G){for(let B of await this.rulesForDirectory(J,Z))if(!B.patterns)await this.loadSource(B.path,"rule",W,void 0,Q,0);let K=await this.primaryForDirectory(J,Z);if(K){let B=c6(K)==="CLAUDE.local.md"?"local":"project";await this.loadSource(K,B,W,void 0,Q,0)}}let X=this.settings.maxBytes-W.budget.remaining;return this.current={enabled:!0,projectRoot:Q,sources:W.sources,diagnostics:Z,bytes:X,maxBytes:this.settings.maxBytes,truncated:W.budget.truncated,signature:l6(W.sources,!0)},this.snapshot}async refreshedMessages($,Z){let Q=bB($);if(Z!==void 0&&Z!==this.activeSessionId)this.activeSessionId=Z,this.nestedSources.clear();else if(Z===void 0&&$.length===0)this.nestedSources.clear();let W=await this.reload();if(W.sources.length===0&&Q===void 0)return[];if(Q===W.signature)return[];return[_B(W,Q!==void 0)]}async instructionsForPath($){let Z={text:"",sources:[]},Q=this.nestedSerial,W;this.nestedSerial=new Promise((Y)=>{W=Y}),await Q;try{Z=await this.loadNested($)}finally{W?.()}return Z}formatStatus($="instructions"){if(!this.current.enabled)return`${$} disabled
90
+ Use project/user config or remove --no-instructions to enable loading.`;let Z=[...this.current.sources,...this.nestedSources.values()],Q=this.current.truncated||Z.some((G)=>G.truncated),W=this.current.bytes+[...this.nestedSources.values()].reduce((G,X)=>G+Buffer.byteLength(X.content),0),Y=[`${$} \xB7 ${Z.length} file${Z.length===1?"":"s"} \xB7 ${p6(W)}/${p6(this.current.maxBytes)}${Q?" \xB7 truncated":""}`,...Z.map((G)=>{let X=G.truncated?" \xB7 truncated":"";return` ${G.scope.padEnd(7)} ${cZ(G,this.current.projectRoot)}${X}`})];if(Z.length===0)Y.push(" no instruction files found");if(this.current.diagnostics.length>0)Y.push("warnings:",...this.current.diagnostics.map((G)=>` ${G.path?`${G.path}: `:""}${G.message}`));return Y.push("precedence: managed < global < outer project < inner project; AGENTS.override.md wins within one directory"),Y.join(`
91
+ `)}async discoverPrimaryFiles($){let Z=[],Q=$?O0($):await this.findProjectRoot(Z),W=[];for(let Y of this.dirsBetween(Q,this.root)){let G=await this.primaryForDirectory(Y,Z);if(G)W.push(G)}return W}async findProjectRoot($){if(this.settings.projectRootMarkers.length===0)return this.root;let Z=this.root;for(;;){for(let W of this.settings.projectRootMarkers){let Y=D0(Z,W);try{return await m6(Y),Z}catch(G){let X=G.code;if(X!=="ENOENT"&&X!=="ENOTDIR")$.push({level:"warning",path:Y,message:`could not inspect project-root marker: ${G instanceof Error?G.message:String(G)}`})}}let Q=h$(Z);if(Q===Z)return this.root;Z=Q}}dirsBetween($,Z){if(!u$($,Z))return[Z];let Q=[],W=Z;for(;;){if(Q.push(W),W===$)break;let Y=h$(W);if(Y===W)break;W=Y}return Q.reverse()}async primaryForDirectory($,Z){return this.firstReadableCandidate([...RB.map((Q)=>D0($,Q)),...this.settings.fallbackFilenames.map((Q)=>D0($,Q))],Z)}async firstReadableCandidate($,Z){for(let Q of $)try{if((await m6(Q)).isFile())return Q;Z.push({level:"warning",path:Q,message:"instruction candidate is not a file"})}catch(W){let Y=W.code;if(Y==="ENOENT"||Y==="ENOTDIR")continue;Z.push({level:"warning",path:Q,message:`could not inspect instruction file: ${W instanceof Error?W.message:String(W)}`})}return}async ruleFiles($,Z){let Q=[],W=async(Y,G)=>{let X;try{X=await jW(Y)}catch(K){let B=K.code;if(B==="ENOENT"||B==="ENOTDIR")return;Z.push({level:"warning",path:Y,message:`could not read rules directory: ${K instanceof Error?K.message:String(K)}`});return}if(G.has(X))return;G.add(X);let J;try{J=await EW(Y,{withFileTypes:!0})}catch(K){Z.push({level:"warning",path:Y,message:`could not list rules directory: ${K instanceof Error?K.message:String(K)}`});return}for(let K of J.sort((B,z)=>B.name.localeCompare(z.name))){let B=D0(Y,K.name),z=K.isDirectory(),V=K.isFile();if(K.isSymbolicLink())try{let F=await m6(B);z=F.isDirectory(),V=F.isFile()}catch(F){Z.push({level:"warning",path:B,message:`could not inspect rule symlink: ${F instanceof Error?F.message:String(F)}`});continue}if(z)await W(B,G);else if(V&&K.name.toLowerCase().endsWith(".md"))Q.push(B)}};return await W($,new Set),Q}async rulesForDirectory($,Z){let Q=[D0($,".mu","rules")];if(this.settings.claudeRules)Q.push(D0($,".claude","rules"));let W=[];for(let Y of Q)for(let G of await this.ruleFiles(Y,Z))try{let X=TW(await wW(G,pZ));W.push({path:G,base:$,...X.patterns?{patterns:X.patterns}:{}})}catch(X){Z.push({level:"warning",path:G,message:`could not read rule frontmatter: ${X instanceof Error?X.message:String(X)}`})}return W}async loadSource($,Z,Q,W,Y,G){if(Q.budget.remaining<=0){Q.budget.truncated=!0;return}if(G>PW){Q.diagnostics.push({level:"warning",path:$,message:`import depth exceeds ${PW}`});return}let X;try{X=await jW($)}catch(V){let F=V.code;if(W||F!=="ENOENT"&&F!=="ENOTDIR")Q.diagnostics.push({level:"warning",path:$,message:F==="ENOENT"?`import referenced by ${W} does not exist`:`could not resolve instruction file: ${V instanceof Error?V.message:String(V)}`});return}if(Q.processed.has(X))return;if(!u$(Y,X)){Q.diagnostics.push({level:"warning",path:$,message:`external import is outside the allowed instruction root ${Y}`});return}if(!CB.has(IB(X))){Q.diagnostics.push({level:"warning",path:$,message:"skipped non-text instruction import"});return}Q.processed.add(X);let J;try{J=await wW(X,Q.budget.remaining)}catch(V){Q.diagnostics.push({level:"warning",path:$,message:`could not read instruction file: ${V instanceof Error?V.message:String(V)}`});return}if(J.includes("\x00")){Q.diagnostics.push({level:"warning",path:$,message:"skipped binary instruction file"});return}let K=TW(J),B=K.content.trim(),z;if(B&&Q.budget.remaining>0){let V=Buffer.from(B),F=Math.min(V.byteLength,Q.budget.remaining),D=V.subarray(0,F).toString("utf8").replace(/\uFFFD$/,""),L=F<V.byteLength;if(z={path:X,content:D,scope:Z,...W?{parent:W}:{},...L?{truncated:!0}:{}},Q.budget.remaining-=F,L)Q.budget.truncated=!0,Q.diagnostics.push({level:"warning",path:X,message:`instruction content was truncated at the ${p6(this.settings.maxBytes)} total budget`})}if(this.settings.imports)for(let V of fB(K.content)){let F=V.startsWith("~/")?D0(this.home,V.slice(2)):dZ(V)?V:O0(h$(X),V);await this.loadSource(F,"import",Q,X,Z==="global"?this.home:Y,G+1)}if(z)Q.sources.push(z)}async loadNested($){if(!this.settings.enabled)return{text:"",sources:[]};let Z=O0($);if(!u$(this.root,Z))return{text:"",sources:[]};let Q=h$(Z),W=this.current.projectRoot,Y=this.current.diagnostics,G=[];for(let V of this.dirsBetween(W,Q)){for(let F of await this.rulesForDirectory(V,Y))if(O0(F.path)!==Z&&xB(F,Z))G.push({path:F.path,scope:"rule",allowedRoot:W});if(u$(this.root,V)&&V!==this.root){let F=await this.primaryForDirectory(V,Y);if(F&&O0(F)!==Z)G.push({path:F,scope:c6(F)==="CLAUDE.local.md"?"local":"project",allowedRoot:W})}}let X=this.settings.maxBytes-this.current.bytes-[...this.nestedSources.values()].reduce((V,F)=>V+Buffer.byteLength(F.content),0),J=new Set([...this.current.sources.map((V)=>lZ(V.path)),...this.nestedSources.keys()]),K=G.find((V)=>!J.has(lZ(V.path)));if(X<=0&&K){if(this.current.truncated=!0,!Y.some((V)=>V.path===K.path&&V.message==="nested instruction omitted because the total byte budget is exhausted"))Y.push({level:"warning",path:K.path,message:"nested instruction omitted because the total byte budget is exhausted"});return{text:"",sources:[]}}let B={budget:{remaining:Math.max(0,X),truncated:!1},processed:J,diagnostics:Y,sources:[]};for(let V of G)await this.loadSource(V.path,V.scope,B,void 0,V.allowedRoot,0);for(let V of B.sources)this.nestedSources.set(O0(V.path),V);if(B.sources.length===0)return{text:"",sources:[]};return{text:["<system-reminder>","Additional instructions apply to the file just read. Later sources have higher precedence:","",...B.sources.flatMap((V)=>[`Contents of ${cZ(V,W)}:`,V.content.trim(),""]),"</system-reminder>"].join(`
92
+ `),sources:B.sources.map((V)=>V.path)}}}async function IW($,Z){try{let Q=Bun.spawn(["git",...$],{cwd:Z,stdout:"pipe",stderr:"ignore",windowsHide:!0}),W=await new Response(Q.stdout).text();return await Q.exited===0?W:void 0}catch{return}}async function nZ($){let Z={directory:O0($),platform:process.platform,date:new Date().toISOString().slice(0,10)},W=(await IW(["rev-parse","--abbrev-ref","HEAD"],$))?.trim().split(/\r?\n/)[0];if(W){Z.branch=W;let Y=await IW(["status","--porcelain"],$);if(Y!==void 0)Z.uncommittedFiles=String(Y.split(/\r?\n/).filter(Boolean).length)}try{let Y=await EW($);Z.topLevelEntries=Y.filter((G)=>!G.startsWith(".")).sort().slice(0,40).join(", ")}catch{}return Z}function n6($){let Z=Object.entries($).map(([Q,W])=>`${Q}: ${W}`);return k$("environment",`Session environment:
70
93
  ${Z.join(`
71
- `)}`)}import{mkdir as e3,readFile as $B,writeFile as ZB}from"fs/promises";import{dirname as WB,join as QB}from"path";var C6=[{permission:"*",pattern:"*",action:"ask"},{permission:"read",pattern:"*",action:"allow"},{permission:"ls",pattern:"*",action:"allow"},{permission:"glob",pattern:"*",action:"allow"},{permission:"grep",pattern:"*",action:"allow"},{permission:"todo",pattern:"*",action:"allow"},{permission:"task_output",pattern:"*",action:"allow"},{permission:"task_list",pattern:"*",action:"allow"}],y6=[{id:"default",label:"default",description:"Read freely; ask before edits and commands.",rules:[]},{id:"accept-edits",label:"accept edits",description:"Read and edit files freely; ask before commands.",rules:[{permission:"write",pattern:"*",action:"allow"},{permission:"edit",pattern:"*",action:"allow"}]},{id:"plan-readonly",label:"plan (read-only)",description:"Allow inspection and planning; deny file, command, and task mutations.",rules:[{permission:"write",pattern:"*",action:"deny"},{permission:"edit",pattern:"*",action:"deny"},{permission:"bash",pattern:"*",action:"deny"},{permission:"task_write_stdin",pattern:"*",action:"deny"},{permission:"task_kill",pattern:"*",action:"deny"},{permission:"task_detach",pattern:"*",action:"deny"}]},{id:"yolo",label:"full access",description:"Allow every tool call without asking.",rules:[{permission:"*",pattern:"*",action:"allow"}]}];function KQ($){return QB($,".mu","config.json")}async function _Z($){try{let Z=await $B(KQ($),"utf8"),W=JSON.parse(Z);return typeof W==="object"&&W!==null?W:{}}catch{return{}}}function b6(...$){return $.flatMap((Z)=>Z??[])}async function k6($,Z,W){let Q=KQ($),Y=await _Z($),G=Y.permissions??[];if(!G.some((J)=>J.permission===Z&&J.pattern===W&&J.action==="allow"))G.push({permission:Z,pattern:W,action:"allow"});await e3(WB(Q),{recursive:!0}),await ZB(Q,`${JSON.stringify({...Y,permissions:G},null,2)}
72
- `,"utf8")}function _6($){let Z=[{text:`You are mu, an expert software engineer working in a codebase through tools.
94
+ `)}`)}import{mkdir as vB,readFile as gB,writeFile as hB}from"fs/promises";import{dirname as uB,join as mB}from"path";var a6=[{permission:"*",pattern:"*",action:"ask"},{permission:"read",pattern:"*",action:"allow"},{permission:"ls",pattern:"*",action:"allow"},{permission:"glob",pattern:"*",action:"allow"},{permission:"grep",pattern:"*",action:"allow"},{permission:"todo",pattern:"*",action:"allow"},{permission:"task_output",pattern:"*",action:"allow"},{permission:"task_list",pattern:"*",action:"allow"},{permission:"bash:inspect",pattern:"*",action:"allow"}],r6=[{id:"default",label:"default",description:"Read freely; ask before edits and commands.",rules:[]},{id:"accept-edits",label:"accept edits",description:"Read and edit files freely; ask before commands.",tone:"permissive",rules:[{permission:"write",pattern:"*",action:"allow"},{permission:"edit",pattern:"*",action:"allow"}]},{id:"plan-readonly",label:"plan (read-only)",description:"Allow inspection and planning; deny file, command, and task mutations.",tone:"restrictive",rules:[{permission:"write",pattern:"*",action:"deny"},{permission:"edit",pattern:"*",action:"deny"},{permission:"bash",pattern:"*",action:"deny"},{permission:"bash:inspect",pattern:"*",action:"allow"},{permission:"task_write_stdin",pattern:"*",action:"deny"},{permission:"task_kill",pattern:"*",action:"deny"},{permission:"task_detach",pattern:"*",action:"deny"}]},{id:"yolo",label:"full access",description:"Allow every tool call without asking.",tone:"unrestricted",rules:[{permission:"*",pattern:"*",action:"allow"}]}];function SW($){return mB($,".mu","config.json")}async function aZ($){try{let Z=await gB(SW($),"utf8"),Q=JSON.parse(Z);return typeof Q==="object"&&Q!==null?Q:{}}catch{return{}}}function t6(...$){return $.flatMap((Z)=>Z??[])}async function o6($,Z,Q){let W=SW($),Y=await aZ($),G=Y.permissions??[];if(!G.some((J)=>J.permission===Z&&J.pattern===Q&&J.action==="allow"))G.push({permission:Z,pattern:Q,action:"allow"});await vB(uB(W),{recursive:!0}),await hB(W,`${JSON.stringify({...Y,permissions:G},null,2)}
95
+ `,"utf8")}function s6($){let Z=[{text:`You are mu, an expert software engineer working in a codebase through tools.
73
96
 
74
97
  Approach:
75
98
  - Understand before you change: read the relevant files and search the codebase rather than guessing at names or APIs.
@@ -80,8 +103,12 @@ Approach:
80
103
  Tools:
81
104
  - Read a file before editing or overwriting it.
82
105
  - Prefer edit over write for existing files; write replaces the whole file.
106
+ - Change several places in one file with a single edit call carrying multiple edits,
107
+ rather than one call per change.
83
108
  - Use grep and glob to find things; use bash for building, testing and inspection. The
84
109
  bash tool runs the platform-native shell named in the environment (PowerShell on Windows).
110
+ - During repository exploration, prefer one batched read-only bash call using rg, targeted
111
+ sed/head/tail ranges, and git status/diff over many whole-file reads. Search and narrow first.
85
112
  - Independent read-only lookups can be issued together in one turn.
86
113
 
87
114
  Communication:
@@ -91,16 +118,16 @@ Communication:
91
118
  line from tool output. Put the citation beside the claim or immediately before its code
92
119
  block, repeat the path for separate references, and never invent a line number.
93
120
  - Only write code comments that state something the code cannot \u2014 never narrate what a line does.
94
- - If you cannot complete something, say so plainly and explain what is blocking you.`}],W=$.toLowerCase();if(W.includes("gpt")||W.includes("openai"))Z.push({text:`
95
- Be explicit and literal in your tool use. State briefly what you are about to do before a batch of tool calls, then do it. Do not ask for confirmation for steps that follow directly from the request.`.trim()});else if(W.includes("gemini")||W.includes("google"))Z.push({text:`
96
- Prefer a small number of well-chosen tool calls over many exploratory ones. When editing, reproduce the exact surrounding text in oldString so the match is unambiguous.`.trim()});return Z}import{statSync as BQ}from"fs";import{resolve as xZ}from"path";class fZ{reads=new Map;modified=new Set;markRead($){let Z=xZ($);try{this.reads.set(Z,BQ(Z).mtimeMs)}catch{this.reads.set(Z,0)}}markWritten($){let Z=xZ($);this.modified.add(Z),this.markRead(Z)}hasRead($){return this.reads.has(xZ($))}isStale($){let Z=xZ($),W=this.reads.get(Z);if(W===void 0)return!1;try{return BQ(Z).mtimeMs>W}catch{return!1}}readFiles(){return[...this.reads.keys()]}modifiedFiles(){return[...this.modified]}}import{randomUUID as GB}from"crypto";function HQ($){return $.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens}function x6($,Z){if(!$)return;if($.maxCostUsd!==void 0&&(Z.costUsd??0)>=$.maxCostUsd)return"maxCostUsd";if($.maxTokens!==void 0&&HQ(Z)>=$.maxTokens)return"maxTokens";return}import{z as YB}from"zod";var p1="structured_output";function f6($,Z){let W=YB.toJSONSchema($,{io:"input"});return{name:p1,description:"Report the final answer. Call this exactly once, when you have the complete result. Do not call any other tool afterwards.",inputSchema:W,execute:async(Q,Y)=>{let G=$.safeParse(Y);if(!G.success)return{content:[{type:"text",text:`Output did not match the required schema: ${G.error.issues.map((J)=>`${J.path.join(".")||"(root)"}: ${J.message}`).join("; ")}. Call ${p1} again with corrected values.`}],isError:!0};return Z(G.data),{content:[{type:"text",text:"Final answer recorded."}],terminate:!0}}}}function v6(){return`When you have the final answer, call the ${p1} tool with it. That call ends the task.`}var XB=[{permission:"*",pattern:"*",action:"allow"}],JB="You are mu, a capable and direct assistant. Use the tools available to you to complete the user's task. Be concise: answer what was asked without padding. When a task is done, say so plainly.";function S$($,Z){if($&&typeof $!=="string")return $;let W=$??l1(),Q=Z?.findModel(W)??A1(W);if(!Q)throw Error(`Unknown model: ${W}. Pass a ModelInfo to use a custom model.`);return Q}function KB($){if($===void 0)return[{text:JB}];return typeof $==="string"?[{text:$}]:$}function BB($){for(let Z=$.length-1;Z>=0;Z--){let W=$[Z];if(W?.role!=="assistant")continue;let Q=W.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join("");if(Q.trim().length>0)return Q}return""}function zQ(){return`s${Date.now().toString(36)}-${GB().slice(0,8)}`}class C${options;model;provider;store;tree;_sessionId;controller=new AbortController;steering=[];followUps=[];totals=O$();compactRequested=!1;lastContextPercent=0;lastContextUsage;checkpoints=new UZ;recoveryAttempted=!1;reactiveRecoveryPending=!1;pendingCheckpoint;currentThinking;running=!1;stopping=!1;activeEmit;activeExecution;autonomousScheduled=!1;subscribers=new Set;idleWaiters=new Set;shutdownPromise;sessionStarted=!1;permissionRules;constructor($={}){this.options=$,this.permissionRules=[...$.permissions??XB],this.currentThinking=$.thinkingLevel??"off",this.model=S$($.model,$.extensions),this.provider=this.providerFor(this.model),this.store=$.session??new T$,this._sessionId=$.sessionId??zQ(),this.tree=new Z0({type:"session",version:w$,id:this._sessionId,createdAt:new Date().toISOString(),profile:"default",environment:{}}),$.runtime?.attach({emit:(Z)=>this.emitTaskEvent(Z),followUp:(Z)=>this.followUp(Z)})}get sessionId(){return this._sessionId}get usage(){return this.totals}get session(){return this.tree}get sessionStore(){return this.store}get modelRef(){return`${this.model.provider}/${this.model.id}`}get contextWindow(){return this.model.contextWindow}get thinking(){return this.currentThinking}get isRunning(){return this.running}get permissions(){return[...this.permissionRules]}setPermissions($){this.permissionRules=[...$]}addPermissionRule($){this.permissionRules.push($)}setModel($){this.model=S$($,this.options.extensions),this.provider=this.providerFor(this.model),this.lastContextUsage=void 0,this.lastContextPercent=0,this.tree.append({type:"settings-change",model:this.modelRef}),this.options.extensions?.emitLifecycle({type:"model_select",model:this.modelRef})}setThinking($){this.currentThinking=$,this.tree.append({type:"settings-change",thinkingLevel:$})}resume($){if(this.running)throw Error("Cannot resume a session while a run is active.");let Z=Z0.fromJsonl($.toJsonl()),W=Z.header;if(!W||W.version!==w$)throw Error("Cannot resume an invalid or unsupported session.");this.tree=Z,this._sessionId=W.id,this.totals=O$(),this.lastContextUsage=void 0,this.lastContextPercent=0,this.compactRequested=!1,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1,this.steering=[],this.followUps=[],this.pendingCheckpoint=void 0,this.sessionStarted=!1,this.controller=new AbortController,this.model=S$(this.options.model,this.options.extensions),this.provider=this.providerFor(this.model),this.currentThinking=this.options.thinkingLevel??"off";for(let Q of Z.activePath()){if(Q.type!=="settings-change")continue;if(Q.model)try{this.model=S$(Q.model,this.options.extensions),this.provider=this.providerFor(this.model)}catch{}if(Q.thinkingLevel==="off"||Q.thinkingLevel==="low"||Q.thinkingLevel==="medium"||Q.thinkingLevel==="high")this.currentThinking=Q.thinkingLevel}this.rebuildCheckpointHistory()}newSession($=zQ()){if(this.running)throw Error("Cannot start a new session while a run is active.");this._sessionId=$,this.tree=new Z0({type:"session",version:w$,id:$,createdAt:new Date().toISOString(),profile:"default",environment:{}}),this.tree.append({type:"settings-change",model:this.modelRef,thinkingLevel:this.currentThinking}),this.totals=O$(),this.lastContextUsage=void 0,this.lastContextPercent=0,this.compactRequested=!1,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1,this.steering=[],this.followUps=[],this.pendingCheckpoint=void 0,this.checkpoints.restore([]),this.sessionStarted=!1,this.controller=new AbortController}send($){this.steering.push(x1($))}followUp($){if(this.stopping)return;if(this.followUps.push(x1($)),!this.running)this.scheduleAutonomousRun()}removeQueuedMessage($,Z){let W=$==="steer"?this.steering:this.followUps;for(let Q=W.length-1;Q>=0;Q--){let Y=W[Q];if(Y?.role!=="user")continue;if(Y.content.filter((X)=>X.type==="text").map((X)=>X.text).join("")!==Z)continue;return W.splice(Q,1),this.resolveIdleIfDone(),!0}return!1}emitTaskEvent($){if(this.activeEmit){this.activeEmit($);return}this.publishToSubscribers($),this.options.extensions?.emit($)}subscribe($){return this.subscribers.add($),()=>this.subscribers.delete($)}resize($,Z){if($>0&&Z>0)this.options.runtime?.resize?.($,Z)}waitForIdle(){if(!this.running&&!this.autonomousScheduled&&this.followUps.length===0)return Promise.resolve();return new Promise(($)=>this.idleWaiters.add($))}stop(){if(this.stopping)return;this.stopping=!0,this.followUps=[];try{this.options.runtime?.stop?.()}catch{}this.controller.abort(),this.resolveIdleIfDone()}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;return this.stop(),this.shutdownPromise=(async()=>{await this.activeExecution?.catch(()=>{}),this.options.extensions?.emitLifecycle({type:"session_shutdown",sessionId:this._sessionId}),await Promise.allSettled([Promise.resolve().then(()=>this.options.runtime?.shutdown?.()),Promise.resolve().then(()=>this.options.extensions?.shutdown())]),this.resolveIdleIfDone()})(),this.shutdownPromise}abort(){this.controller.abort()}requestCompaction(){this.compactRequested=!0}get checkpointHistory(){return this.checkpoints}async undo(){if(this.running)return{ok:!1,message:"Cannot undo while a run is active."};let $=this.options.checkpointProvider;if(!$)return{ok:!1,message:"This profile does not support undo."};let Z=this.checkpoints.peekUndo();if(!Z)return{ok:!1,message:"Nothing to undo."};if(!this.tree.has(Z.beforeEntryId))return{ok:!1,message:"Could not undo: the conversation checkpoint is missing."};let W;try{W=await $.diff(Z.beforeRef,Z.afterRef)}catch(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let Q;try{Q=await $.snapshot("before undo of last turn")}catch(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}if(!Q)return{ok:!1,message:"Could not undo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.beforeRef,W)}catch(V){let z=await this.restoreCheckpointResources($,Q,W).then(()=>{return}).catch((F)=>F);return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}${z?`; rollback failed: ${z instanceof Error?z.message:String(z)}`:""}`}}let Y=this.tree,G=Z0.fromJsonl(Y.toJsonl());G.fork(Z.beforeEntryId);let X=this.checkpoints.state(),J=X.done.slice(0,-1),K=[...X.undone,{...Z,redoRef:Q}];this.appendCheckpointCursor(G,J,K);try{await this.store.save(this._sessionId,G)}catch(V){return await this.restoreCheckpointResources($,Q,W).catch(()=>{}),await this.store.save(this._sessionId,Y).catch(()=>{}),{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let H=this.checkpointDetails(Z);return this.checkpoints.restore(J,K),this.tree=G,{ok:!0,message:"Undid the last turn.",data:{kind:"checkpoint",action:"undo",files:W,messageCount:H.messageCount,...H.prompt!==void 0?{prompt:H.prompt}:{}}}}async redo(){if(this.running)return{ok:!1,message:"Cannot redo while a run is active."};let $=this.options.checkpointProvider;if(!$)return{ok:!1,message:"This profile does not support redo."};let Z=this.checkpoints.peekRedo();if(!Z)return{ok:!1,message:"Nothing to redo."};if(!this.tree.has(Z.id))return{ok:!1,message:"Could not redo: the conversation checkpoint is missing."};let W;try{W=await $.diff(Z.beforeRef,Z.afterRef)}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let Q;try{Q=await $.snapshot("before redo of last turn")}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}if(!Q)return{ok:!1,message:"Could not redo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.redoRef??Z.afterRef,W)}catch(F){let D=await this.restoreCheckpointResources($,Q,W).then(()=>{return}).catch((L)=>L);return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}${D?`; rollback failed: ${D instanceof Error?D.message:String(D)}`:""}`}}let Y=this.tree,G=Z0.fromJsonl(Y.toJsonl());G.fork(Z.id);let X=this.checkpoints.state(),{redoRef:J,...K}=Z,H=[...X.done,K],V=X.undone.slice(0,-1);this.appendCheckpointCursor(G,H,V);try{await this.store.save(this._sessionId,G)}catch(F){return await this.restoreCheckpointResources($,Q,W).catch(()=>{}),await this.store.save(this._sessionId,Y).catch(()=>{}),{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let z=this.checkpointDetails(Z);return this.checkpoints.restore(H,V),this.tree=G,{ok:!0,message:"Redid the turn.",data:{kind:"checkpoint",action:"redo",files:W,messageCount:z.messageCount}}}async sessionDiff(){let $=this.options.checkpointProvider,Z=this.checkpoints.first();if(!$||!Z)return[];return $.diff(Z.beforeRef)}forkPoints(){let $=[];for(let Z of this.tree.activePath()){if(Z.type!=="message")continue;let W=Z.message;if(W.role==="toolResult")continue;if(W.role==="assistant"&&W.content.some((G)=>G.type==="toolCall"))continue;let Q=W.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").replace(/\s+/g," ").trim(),Y=W.role==="assistant"?"mu":W.role;$.push({id:Z.id,description:`${Y} \xB7 ${Q.slice(0,80)||"(no text)"}`})}return $}async fork($){if(this.running)return{ok:!1,message:"Cannot fork while a run is active."};if(!this.tree.get($))return{ok:!1,message:`Could not fork: unknown entry ${$}.`};let Z=Z0.fromJsonl(this.tree.toJsonl());Z.fork($),Z.append({type:"custom",customType:"fork",data:{fromEntryId:this.tree.head,targetEntryId:$}});try{await this.store.save(this._sessionId,Z)}catch(W){return{ok:!1,message:`Could not fork: ${W instanceof Error?W.message:String(W)}`}}return this.tree=Z,this.rebuildCheckpointHistory(),{ok:!0,message:`Forked from ${$}.`}}get contextPercent(){return this.lastContextPercent}async run($,Z){return this.execute($,Z,()=>{})}stream($,Z){let W=[],Q=[],Y=!1,G=(J)=>{let K=Q.shift();if(K)K({value:J,done:!1});else W.push(J)},X=this.execute($,Z,G).finally(()=>{Y=!0;while(Q.length>0)Q.shift()?.({value:void 0,done:!0})});return{async*[Symbol.asyncIterator](){for(;;){if(W.length>0){yield W.shift();continue}if(Y)return;let J=await new Promise((K)=>Q.push(K));if(J.done)return;yield J.value}},result:()=>X}}async beginCheckpoint($){let Z=this.options.checkpointProvider;if(this.pendingCheckpoint=void 0,!Z)return;try{let W=await Z.snapshot("before user turn");if(W)this.pendingCheckpoint={beforeEntryId:$,beforeRef:W}}catch{}}async finishCheckpoint(){let $=this.pendingCheckpoint,Z=this.options.checkpointProvider;if(this.pendingCheckpoint=void 0,!$||!Z)return;let W=await Z.snapshot("after user turn").catch(()=>{return});if(!W)return;let Y={id:this.tree.append({type:"checkpoint",beforeEntryId:$.beforeEntryId,checkpointRef:$.beforeRef,checkpointAfterRef:W,label:"turn"}).id,beforeEntryId:$.beforeEntryId,beforeRef:$.beforeRef,afterRef:W,label:"turn"};this.checkpoints.record(Y);let G=this.checkpoints.state();this.appendCheckpointCursor(this.tree,G.done,G.undone)}appendCheckpointCursor($,Z,W){let Q=(Y)=>({id:Y.id,...Y.redoRef?{redoRef:Y.redoRef}:{}});$.append({type:"custom",customType:"checkpoint-cursor",data:{done:Z.map(Q),undone:W.map(Q)}})}async restoreCheckpointResources($,Z,W){if(W.length===0)return;let Q=W.map((Y)=>Y.path);if($.restoreResources){await $.restoreResources(Z,Q);return}await $.restore(Z)}checkpointDetails($){let Z=this.tree.pathTo($.id),W=$.beforeEntryId?Z.findIndex((X)=>X.id===$.beforeEntryId):-1,Q=Z.slice(W+1),Y=Q.find((X)=>X.type==="message"&&X.message.role==="user"),G=Y?.type==="message"?Y.message.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
97
- `):void 0;return{messageCount:Q.filter((X)=>X.type==="message").length,...G!==void 0?{prompt:G}:{}}}rebuildCheckpointHistory(){let $=new Map;for(let Y of this.tree.all()){if(Y.type!=="checkpoint")continue;$.set(Y.id,{id:Y.id,beforeEntryId:Y.beforeEntryId,beforeRef:Y.checkpointRef,afterRef:Y.checkpointAfterRef,...Y.label?{label:Y.label}:{}})}let Z=this.tree.activePath(),W=Z.findLastIndex((Y)=>Y.type==="custom"&&Y.customType==="checkpoint-cursor"),Q=W===-1?void 0:Z[W];if(Q?.type==="custom"){let Y=Q.data,G=(K)=>Array.isArray(K)?K.map((H)=>{let V=typeof H==="string"?H:typeof H==="object"&&H!==null&&typeof H.id==="string"?H.id:void 0,z=V?$.get(V):void 0;if(!z)return;let F=typeof H==="object"&&H!==null&&typeof H.redoRef==="string"?H.redoRef:void 0;return{...z,...F?{redoRef:F}:{}}}).filter((H)=>H!==void 0):[],X=G(Y.done),J=G(Y.undone);for(let K of Z.slice(W+1)){if(K.type!=="checkpoint")continue;let H=$.get(K.id);if(H)X.push(H);J=[]}this.checkpoints.restore(X,J);return}this.checkpoints.restore(Z.filter((Y)=>Y.type==="checkpoint").map((Y)=>$.get(Y.id)).filter((Y)=>Y!==void 0))}execute($,Z,W){if(this.stopping)return Promise.reject(Error("Agent has been stopped."));if(this.running)return Promise.reject(Error("Agent already has an active run; use send() to steer it."));this.running=!0;let Q=(G)=>{if(W(G),this.publishToSubscribers(G),G.type==="agent_start"&&!this.sessionStarted)this.sessionStarted=!0,this.options.extensions?.emitLifecycle({type:"session_start",sessionId:this._sessionId});this.options.extensions?.emit(G)};this.activeEmit=Q;let Y=this.executeRun($,Z,Q).finally(()=>{if(this.running=!1,this.activeEmit=void 0,this.activeExecution=void 0,this.followUps.length>0&&!this.stopping)this.scheduleAutonomousRun();this.resolveIdleIfDone()});return this.activeExecution=Y,Y}async executeRun($,Z,W){this.controller=new AbortController,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1;let Q=this.options.extensions,Y=$;if(typeof $==="string"&&Q){Q.emitLifecycle({type:"input",text:$});let w=await Q.runInputHooks($);if(w?.consume){if(Z?.output)throw Error("Structured output is unavailable because an extension consumed the input.");let f=[{type:"agent_start"},{type:"agent_end",messages:[],reason:"done"}];for(let i of f)W(i);return{text:"",messages:[],usage:this.totals,reason:"done",sessionId:this._sessionId}}if(w?.text!==void 0)Y=w.text}let G=typeof Y==="string"?x1(Y):{role:"user",content:Y,timestamp:Date.now()},X,J=[...this.options.tools??[],...Q?[...Q.tools.values()]:[]];if(Z?.allowedTools){let w=new Set(J.map((v)=>v.name)),f=Z.allowedTools.filter((v)=>!w.has(v));if(f.length>0)throw Error(`Unknown allowed tool${f.length===1?"":"s"}: ${f.join(", ")}`);let i=new Set(Z.allowedTools);J=J.filter((v)=>i.has(v.name))}let K=Z?.model?S$(Z.model,this.options.extensions):this.model,H=Z?.model?this.providerFor(K):this.provider,V=Z?.model?void 0:this.lastContextUsage;if(Z?.model)this.lastContextUsage=void 0;let z=KB(this.options.systemPrompt);if(Z?.output)J.push(f6(Z.output,(w)=>{X=w})),z.push({text:v6(),dynamic:!0});let F=this.tree.messagesAt(),D=F.length===0&&this.options.initialMessages?this.options.initialMessages:[];for(let w of D)this.tree.appendMessage(w);let L=await this.options.refreshContext?.([...F,...D],{sessionId:this._sessionId})??[];for(let w of L)this.tree.appendMessage(w);let U={systemPrompt:z,messages:[...F,...D,...L],...J.length>0?{tools:J}:{}};await this.beginCheckpoint(this.tree.head);let A,q=(w)=>t5(K,w,V?.usage,V?.estimatedTokensAtUsage),O=(w,f,i)=>{if(this.totals=Y6(this.totals,w),i){if(V={usage:w,estimatedTokensAtUsage:S0(i)},!Z?.model)this.lastContextUsage=V}let v=q(f);this.lastContextPercent=v.percent,W({type:"usage_updated",sessionTotals:this.totals,contextTokens:v.tokens,contextPercent:v.percent});let L0=x6(this.options.budget,this.totals);if(L0)A=L0;return L0},j=this.options.getCredentials,P={provider:H,model:K,streamOpts:{sessionId:this._sessionId,...this.options.apiKey?{apiKey:this.options.apiKey}:{},...j?{getCredentials:()=>j(K.provider)}:{}},thinkingLevel:this.currentThinking,...this.options.budget?.maxTurns!==void 0?{maxTurns:this.options.budget.maxTurns}:{},getSteeringMessages:()=>{let w=this.steering;return this.steering=[],w},getFollowUpMessages:()=>{let w=this.followUps.shift();return w?[w]:[]},beforeToolCall:async(w)=>{if(w.toolCall.name===p1)return;let f=w.args;if(Q){let h=await Q.runToolCallHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,args:f});if(h?.block)return{block:!0,reason:h.reason??"Blocked by an extension"};if(h?.args)f=h.args}let i=JSON.stringify(f),v=q6(this.permissionRules,w.toolCall.name,i),L0=f===w.args?void 0:{rewrittenArgs:f};if(v==="allow")return L0;if(v==="deny")return{block:!0,reason:`Permission denied for ${w.toolCall.name}`};let H$=J.find((h)=>h.name===w.toolCall.name),R0=await Promise.resolve(H$?.permissionDetails?.(f)).catch(()=>{return}),b1={id:`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,toolCallId:w.toolCall.id,toolName:w.toolCall.name,pattern:i,description:R0?.description??`Run ${w.toolCall.name}`,...R0?.preview?{preview:R0.preview}:{}};W({type:"permission_asked",request:b1});let z$=this.options.onPermission?await this.options.onPermission(b1):"deny";if(W({type:"permission_resolved",requestId:b1.id,outcome:z$}),z$==="allow")return L0;return{block:!0,reason:`Permission denied for ${w.toolCall.name}`}},prepareContext:async(w)=>{let f=q(w);this.lastContextPercent=f.percent;let i=this.options.autoCompact!==!1,v=w;if(i&&f.percent>=A6&&!this.compactRequested){let h=U6(v,{targetTokens:Math.floor(K.contextWindow*(this.options.compactThreshold??L$)*0.8)});if(h.evicted>0){let _0=h.messages.flatMap((D1,k1)=>{let _1=v[k1];if(!_1||D1===_1)return[];let n5=this.tree.entryIdForMessage(_1);return n5?[{entryId:n5,message:D1}]:[]}),V$=h.messages.filter((D1,k1)=>D1!==v[k1]).length;if(_0.length===V$)W({type:"compaction_start",layer:1}),this.tree.append({type:"microcompaction",replacements:_0}),v=h.messages,V=void 0,this.lastContextUsage=void 0,this.lastContextPercent=q(v).percent,W({type:"compaction_end",layer:1,tokensFreed:h.tokensFreed})}}let L0=q(v);if(!(this.compactRequested||i&&o5(L0,this.options.compactThreshold??L$)))return{messages:v};this.compactRequested=!1;let R0=this.reactiveRecoveryPending?3:2;if(R0===2)W({type:"compaction_start",layer:R0});let b1,z$=!1;try{let h=await s5(v,{provider:H,model:K,...P.streamOpts?{streamOpts:P.streamOpts}:{},...this.options.carryoverExtractor?{carryoverExtractor:this.options.carryoverExtractor}:{},signal:this.controller.signal});b1=h.usage;let _0=qZ(h),V$;if(h.summary.length>0){let D1=h.keptMessages[0],k1=null;if(D1){let H4=this.tree.entryIdForMessage(D1);if(!H4)throw Error("Compaction tail could not be mapped to the session");k1=H4}let _1=_0[0];V$=this.tree.append({type:"compaction",summary:h.summary,...h.carryover!==void 0?{carryover:h.carryover}:{},firstKeptEntryId:k1,..._1?{timestamp:_1.timestamp}:{}}).id}return V=void 0,this.lastContextUsage=void 0,O(h.usage,_0),z$=!0,W({type:"compaction_end",layer:R0,tokensFreed:h.tokensFreed,...V$?{summaryEntryId:V$}:{}}),this.reactiveRecoveryPending=!1,{messages:_0,stop:A!==void 0}}catch(h){let _0=b1??(h instanceof x0?h.usage:void 0);if(_0&&!z$)O(_0,v);return W({type:"compaction_end",layer:R0,tokensFreed:0}),this.reactiveRecoveryPending=!1,{messages:v,stop:A!==void 0}}},...Q?{transformContext:(w)=>Q.runContextHooks(w)}:{},...Q?{afterToolCall:async(w)=>{let f=await Q.runToolResultHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,result:w.result,isError:w.isError});if(!f)return;return{...w.result,...f.content?{content:f.content}:{},...f.isError!==void 0?{isError:f.isError}:{}}}}:{},recoverFromError:(w)=>{if(this.recoveryAttempted||!M6(w))return!1;return this.recoveryAttempted=!0,this.compactRequested=!0,this.reactiveRecoveryPending=!0,W({type:"compaction_start",layer:3}),!0},shouldStopAfterTurn:async(w)=>{if(this.recoveryAttempted=!1,O(w.message.usage,w.context.messages,w.requestMessages))return!0;return!1}},N=await(async()=>{try{return await F6([G],U,P,(w)=>{if(W(w),w.type==="message_end")this.tree.appendMessage(w.message)},this.controller.signal)}finally{await this.finishCheckpoint()}})();await this.store.save(this._sessionId,this.tree);let x=A??(N.reason==="budget"?"maxCostUsd":N.reason),m={text:BB(N.messages),messages:N.messages,usage:this.totals,reason:x,sessionId:this._sessionId};if(!Z?.output)return m;if(X===void 0)throw Error(`Structured output was requested but the model never produced a valid one (run ended: ${x}).`);return{...m,output:X}}providerFor($){return this.options.provider??this.options.extensions?.providers.get($.provider)??B6($.provider)}publishToSubscribers($){for(let Z of this.subscribers)try{Promise.resolve(Z($)).catch(()=>{})}catch{}}scheduleAutonomousRun(){if(this.running||this.autonomousScheduled||this.stopping||this.followUps.length===0)return;this.autonomousScheduled=!0,queueMicrotask(()=>{if(this.autonomousScheduled=!1,this.running||this.stopping){this.resolveIdleIfDone();return}let $=this.followUps.shift();if(!$||$.role!=="user"){this.resolveIdleIfDone();return}this.execute($.content,void 0,()=>{}).catch(()=>{})})}resolveIdleIfDone(){if(this.running||this.autonomousScheduled||this.followUps.length>0)return;for(let $ of this.idleWaiters)$();this.idleWaiters.clear()}}import{createHash as VB,randomBytes as uZ}from"crypto";import{chmod as u6,mkdir as FB,readFile as DB,rename as LB,stat as UB,unlink as AB,writeFile as qB}from"fs/promises";import{createServer as AQ}from"http";import{homedir as OB}from"os";import{dirname as NB,join as qQ}from"path";var HB=[{x:0,y:0,w:5,h:1},{x:0,y:1,w:1,h:4},{x:2,y:1,w:1,h:4},{x:4,y:1,w:1,h:4},{x:6,y:0,w:1,h:5},{x:9,y:0,w:1,h:5},{x:7,y:4,w:2,h:1}];function g6($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function zB(){return`<svg class="mark" viewBox="0 0 10 5" role="img" aria-label="mu">${HB.map((Z)=>`<rect x="${Z.x}" y="${Z.y}" width="${Z.w}" height="${Z.h}"/>`).join("")}</svg>`}function h6($){let Z=$.status==="success"?"#fff":"#f87171";return`<!doctype html>
121
+ - If you cannot complete something, say so plainly and explain what is blocking you.`}],Q=$.toLowerCase();if(Q.includes("gpt")||Q.includes("openai"))Z.push({text:`
122
+ Be explicit and literal in your tool use. State briefly what you are about to do before a batch of tool calls, then do it. Do not ask for confirmation for steps that follow directly from the request.`.trim()});else if(Q.includes("gemini")||Q.includes("google"))Z.push({text:`
123
+ Prefer a small number of well-chosen tool calls over many exploratory ones. When editing, reproduce the exact surrounding text in oldString so the match is unambiguous.`.trim()});return Z}import{statSync as yW}from"fs";import{resolve as rZ}from"path";class tZ{reads=new Map;modified=new Set;markRead($){let Z=rZ($);try{this.reads.set(Z,yW(Z).mtimeMs)}catch{this.reads.set(Z,0)}}markWritten($){let Z=rZ($);this.modified.add(Z),this.markRead(Z)}hasRead($){return this.reads.has(rZ($))}isStale($){let Z=rZ($),Q=this.reads.get(Z);if(Q===void 0)return!1;try{return yW(Z).mtimeMs>Q}catch{return!1}}readFiles(){return[...this.reads.keys()]}modifiedFiles(){return[...this.modified]}}import{randomUUID as pB}from"crypto";function bW($){return $.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens}function e6($,Z){if(!$)return;if($.maxCostUsd!==void 0&&(Z.costUsd??0)>=$.maxCostUsd)return"maxCostUsd";if($.maxTokens!==void 0&&bW(Z)>=$.maxTokens)return"maxTokens";return}import{z as lB}from"zod";var o1="structured_output";function $8($,Z){let Q=lB.toJSONSchema($,{io:"input"});return{name:o1,description:"Report the final answer. Call this exactly once, when you have the complete result. Do not call any other tool afterwards.",inputSchema:Q,execute:async(W,Y)=>{let G=$.safeParse(Y);if(!G.success)return{content:[{type:"text",text:`Output did not match the required schema: ${G.error.issues.map((J)=>`${J.path.join(".")||"(root)"}: ${J.message}`).join("; ")}. Call ${o1} again with corrected values.`}],isError:!0};return Z(G.data),{content:[{type:"text",text:"Final answer recorded."}],terminate:!0}}}}function Z8(){return`When you have the final answer, call the ${o1} tool with it. That call ends the task.`}var cB=[{permission:"*",pattern:"*",action:"allow"}],dB="You are mu, a capable and direct assistant. Use the tools available to you to complete the user's task. Be concise: answer what was asked without padding. When a task is done, say so plainly.";function m$($,Z){if($&&typeof $!=="string")return $;let Q=$??n1(),W=Z?.findModel(Q)??w1(Q);if(!W)throw Error(`Unknown model: ${Q}. Pass a ModelInfo to use a custom model.`);return W}function iB($){if($===void 0)return[{text:dB}];return typeof $==="string"?[{text:$}]:$}function nB($){for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q?.role!=="assistant")continue;let W=Q.content.filter((Y)=>Y.type==="text").map((Y)=>Y.text).join("");if(W.trim().length>0)return W}return""}function _W(){return`s${Date.now().toString(36)}-${pB().slice(0,8)}`}class l${options;model;provider;store;tree;_sessionId;controller=new AbortController;steering=[];followUps=[];totals=w$();compactRequested=!1;compactRequestedFocus;queuedManualCompactionFocus;manualCompactionQueued=!1;compacting=!1;compactorOverride;lastContextPercent=0;lastContextTokens=0;lastContextUsage;checkpoints=new SZ;recoveryAttempted=!1;reactiveRecoveryPending=!1;pendingCheckpoint;currentThinking;running=!1;stopping=!1;activeEmit;activeExecution;autonomousScheduled=!1;subscribers=new Set;idleWaiters=new Set;shutdownPromise;sessionStarted=!1;permissionRules;constructor($={}){this.options=$,this.permissionRules=[...$.permissions??cB],this.model=m$($.model,$.extensions),this.currentThinking=d0(this.model,$.thinkingLevel),this.provider=this.providerFor(this.model),this.store=$.session??new f$,this._sessionId=$.sessionId??_W(),this.tree=new W0({type:"session",version:x$,id:this._sessionId,createdAt:new Date().toISOString(),profile:"default",environment:{}}),$.runtime?.attach({emit:(Z)=>this.emitTaskEvent(Z),followUp:(Z)=>this.followUp(Z)})}get sessionId(){return this._sessionId}get usage(){return this.totals}get session(){return this.tree}get sessionStore(){return this.store}get modelRef(){return`${this.model.provider}/${this.model.id}`}get contextWindow(){return this.model.contextWindow}get thinking(){return this.currentThinking}get thinkingLevels(){return a1(this.model)}get isRunning(){return this.running}get isCompacting(){return this.compacting}get permissions(){return[...this.permissionRules]}setPermissions($){this.permissionRules=[...$]}addPermissionRule($){this.permissionRules.push($)}setModel($){let Z={model:this.model,provider:this.provider},Q=m$($,this.options.extensions),W=this.tree.messagesAt();if(W.length>0&&p(W)>=Q.contextWindow*(this.options.compactThreshold??T1))this.compactRequested=!0,this.compactorOverride=Z;this.model=Q,this.provider=this.providerFor(Q);let Y=d0(Q,this.currentThinking),G=Y!==this.currentThinking;this.currentThinking=Y,this.lastContextUsage=void 0,this.refreshContextAccounting(),this.tree.append({type:"settings-change",model:this.modelRef,...G?{thinkingLevel:Y}:{}}),this.options.extensions?.emitLifecycle({type:"model_select",model:this.modelRef})}setThinking($){let Z=d0(this.model,$);if(Z===this.currentThinking)return;this.currentThinking=Z,this.tree.append({type:"settings-change",thinkingLevel:Z})}resume($){if(this.running)throw Error("Cannot resume a session while a run is active.");let Z=W0.fromJsonl($.toJsonl()),Q=Z.header;if(!Q||Q.version!==x$)throw Error("Cannot resume an invalid or unsupported session.");this.tree=Z,this._sessionId=Q.id;let W=w$();for(let Y of Z.all())if(Y.type==="message"&&Y.message.role==="assistant")W=j1(W,Y.message.usage);else if(Y.type==="compaction"&&Y.usage)W=j1(W,Y.usage);this.totals=W,this.lastContextUsage=void 0,this.compactRequested=!1,this.compactRequestedFocus=void 0,this.queuedManualCompactionFocus=void 0,this.manualCompactionQueued=!1,this.compacting=!1,this.compactorOverride=void 0,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1,this.steering=[],this.followUps=[],this.pendingCheckpoint=void 0,this.sessionStarted=!1,this.controller=new AbortController,this.model=m$(this.options.model,this.options.extensions),this.provider=this.providerFor(this.model),this.currentThinking=d0(this.model,this.options.thinkingLevel);for(let Y of Z.activePath()){if(Y.type!=="settings-change")continue;if(Y.model)try{this.model=m$(Y.model,this.options.extensions),this.provider=this.providerFor(this.model)}catch{}if(typeof Y.thinkingLevel==="string"&&Y.thinkingLevel.length>0)this.currentThinking=Y.thinkingLevel}this.currentThinking=d0(this.model,this.currentThinking),this.rebuildCheckpointHistory(),this.refreshContextAccounting()}newSession($=_W()){if(this.running)throw Error("Cannot start a new session while a run is active.");this._sessionId=$,this.tree=new W0({type:"session",version:x$,id:$,createdAt:new Date().toISOString(),profile:"default",environment:{}}),this.tree.append({type:"settings-change",model:this.modelRef,thinkingLevel:this.currentThinking}),this.totals=w$(),this.lastContextUsage=void 0,this.compactRequested=!1,this.compactRequestedFocus=void 0,this.queuedManualCompactionFocus=void 0,this.manualCompactionQueued=!1,this.compacting=!1,this.compactorOverride=void 0,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1,this.steering=[],this.followUps=[],this.pendingCheckpoint=void 0,this.checkpoints.restore([]),this.sessionStarted=!1,this.controller=new AbortController,this.refreshContextAccounting()}send($){this.steering.push(t1($))}followUp($){if(this.stopping)return;if(this.followUps.push(t1($)),!this.running)this.scheduleAutonomousRun()}removeQueuedMessage($,Z){let Q=$==="steer"?this.steering:this.followUps;for(let W=Q.length-1;W>=0;W--){let Y=Q[W];if(Y?.role!=="user")continue;if(Y.content.filter((X)=>X.type==="text").map((X)=>X.text).join("")!==Z)continue;return Q.splice(W,1),this.resolveIdleIfDone(),!0}return!1}emitTaskEvent($){this.publishEvent($)}subscribe($){return this.subscribers.add($),()=>this.subscribers.delete($)}resize($,Z){if($>0&&Z>0)this.options.runtime?.resize?.($,Z)}waitForIdle(){if(!this.running&&!this.autonomousScheduled&&!this.manualCompactionQueued&&this.followUps.length===0)return Promise.resolve();return new Promise(($)=>this.idleWaiters.add($))}stop(){if(this.stopping)return;this.stopping=!0,this.followUps=[],this.manualCompactionQueued=!1,this.queuedManualCompactionFocus=void 0;try{this.options.runtime?.stop?.()}catch{}this.controller.abort(),this.resolveIdleIfDone()}shutdown(){if(this.shutdownPromise)return this.shutdownPromise;return this.stop(),this.shutdownPromise=(async()=>{await this.activeExecution?.catch(()=>{}),this.options.extensions?.emitLifecycle({type:"session_shutdown",sessionId:this._sessionId}),await Promise.allSettled([Promise.resolve().then(()=>this.options.runtime?.shutdown?.()),Promise.resolve().then(()=>this.options.extensions?.shutdown())]),this.resolveIdleIfDone()})(),this.shutdownPromise}abort(){this.controller.abort()}requestCompaction($){this.compactRequested=!0,this.compactRequestedFocus=$?.trim()||void 0}compactNow($){let Z=$?.trim()||void 0;if(this.stopping)return Promise.resolve({status:"failed",message:"Compaction is unavailable after stop."});if(this.running)return this.manualCompactionQueued=!0,this.queuedManualCompactionFocus=Z,Promise.resolve({status:"queued",message:"Compaction queued \u2014 it will run after the current turn."});this.running=!0,this.compacting=!0,this.controller=new AbortController;let Q=(Y)=>{if(this.publishToSubscribers(Y),Y.type==="agent_start"&&!this.sessionStarted)this.sessionStarted=!0,this.options.extensions?.emitLifecycle({type:"session_start",sessionId:this._sessionId});this.options.extensions?.emit(Y)};this.activeEmit=Q;let W=this.executeManualCompaction(Z,Q).finally(()=>{if(this.running=!1,this.compacting=!1,this.activeEmit=void 0,this.activeExecution=void 0,this.manualCompactionQueued&&!this.stopping)this.scheduleManualCompaction();else if(this.followUps.length>0&&!this.stopping)this.scheduleAutonomousRun();this.resolveIdleIfDone()});return this.activeExecution=W,W}async executeManualCompaction($,Z){Z({type:"agent_start"});let Q=this.tree.messagesAt(),W=y$(this.model,Q,this.lastContextUsage?.usage,this.lastContextUsage?.estimatedTokensAtUsage).tokens;Z({type:"compaction_start",layer:2,trigger:"manual",contextTokensBefore:W});let Y=hZ(Q,{targetTokens:Math.floor(this.model.contextWindow*(this.options.compactThreshold??T1)*0.8)}),G=Q,X=[];if(Y.evicted>0){Z({type:"compaction_update",layer:2,stage:"clearing-tool-output",toolResultsCleared:Y.evicted}),X=Y.messages.flatMap((V,F)=>{let D=Q[F];if(!D||V===D)return[];let L=this.tree.entryIdForMessage(D);return L?[{entryId:L,message:V}]:[]});let z=Y.messages.filter((V,F)=>V!==Q[F]).length;if(X.length===z)G=Y.messages;else X=[]}let J=this.compactorOverride??{model:this.model,provider:this.provider};this.compactorOverride=void 0,Z({type:"compaction_update",layer:2,stage:"summarizing"});let K,B=!1;try{let z=this.options.getCredentials,V=await fZ(G,{provider:J.provider,model:J.model,keepRecentTokens:Math.min(r1,Math.max(2,Math.floor(this.model.contextWindow*0.2))),...$?{customInstructions:$}:{},...this.options.carryoverExtractor?{carryoverExtractor:this.options.carryoverExtractor}:{},signal:this.controller.signal,streamOpts:{sessionId:this._sessionId,...this.options.apiKey?{apiKey:this.options.apiKey}:{},...z?{getCredentials:()=>z(J.model.provider)}:{}}});if(K=V.usage,V.summary.length===0){let d=p(Q);return Z({type:"compaction_end",layer:2,trigger:"manual",status:"noop",tokensFreed:0,contextTokensBefore:W,contextTokensAfter:d}),Z({type:"agent_end",messages:Q,reason:"done"}),{status:"noop",message:"Context is already compact enough \u2014 no changes made.",tokensBefore:W,tokensAfter:d,tokensFreed:0}}Z({type:"compaction_update",layer:2,stage:"installing"});let F=b$(V),D=V.keptMessages[0],L=null;if(D){let d=G.indexOf(D),w=d===-1?D:Q[d],_=w?this.tree.entryIdForMessage(w):void 0;if(!_)throw Error("Compaction tail could not be mapped to the session");L=_}let U=F[0],q=await this.options.refreshContext?.(F,{sessionId:this._sessionId})??[],A=p([...F,...q]),N=W0.fromJsonl(this.tree.toJsonl());if(X.length>0)N.append({type:"microcompaction",replacements:X});let j=N.activePath().filter((d)=>d.type==="compaction").length+1,P=N.append({type:"compaction",summary:V.summary,...V.carryover!==void 0?{carryover:V.carryover}:{},firstKeptEntryId:L,...U?{timestamp:U.timestamp}:{},trigger:"manual",contextTokensBefore:W,contextTokensAfter:A,model:this.modelRef,compactorModel:`${J.model.provider}/${J.model.id}`,windowNumber:j,strategy:"summary-tail",keptTokens:p(V.keptMessages),toolResultsCleared:X.length,usage:V.usage});for(let d of q)N.appendMessage(d);let O=N.messagesAt(),C=p(O),v=Math.max(0,W-C);return await this.store.save(this._sessionId,N),this.tree=N,this.totals=j1(this.totals,V.usage),B=!0,this.lastContextUsage=void 0,this.lastContextPercent=this.model.contextWindow>0?C/this.model.contextWindow:0,this.lastContextTokens=C,Z({type:"usage_updated",sessionTotals:this.totals,contextTokens:C,contextPercent:this.lastContextPercent}),Z({type:"compaction_end",layer:2,trigger:"manual",status:"completed",tokensFreed:v,summaryEntryId:P.id,contextTokensBefore:W,contextTokensAfter:C,toolResultsCleared:X.length,keptTokens:p(V.keptMessages)}),Z({type:"agent_end",messages:O,reason:"done"}),{status:"completed",message:`Context compacted: ${W.toLocaleString()} \u2192 ${C.toLocaleString()} tokens (${v.toLocaleString()} freed).`,tokensBefore:W,tokensAfter:C,tokensFreed:v,toolResultsCleared:X.length,summaryEntryId:P.id}}catch(z){let V=K??(z instanceof _0?z.usage:void 0);if(V&&!B)this.totals=j1(this.totals,V),Z({type:"usage_updated",sessionTotals:this.totals,contextTokens:W,contextPercent:this.model.contextWindow>0?W/this.model.contextWindow:0});let F=this.controller.signal.aborted,D=F?"Compaction cancelled \u2014 original conversation preserved.":`Compaction failed: ${z instanceof Error?z.message:String(z)} Original conversation preserved.`;return Z({type:"compaction_end",layer:2,trigger:"manual",status:F?"cancelled":"failed",tokensFreed:0,contextTokensBefore:W,contextTokensAfter:W,errorMessage:D}),Z({type:"agent_end",messages:Q,reason:F?"aborted":"done"}),{status:F?"cancelled":"failed",message:D,tokensBefore:W,tokensAfter:W,tokensFreed:0}}}get checkpointHistory(){return this.checkpoints}async undo(){if(this.running)return{ok:!1,message:"Cannot undo while a run is active."};let $=this.options.checkpointProvider;if(!$)return{ok:!1,message:"This profile does not support undo."};let Z=this.checkpoints.peekUndo();if(!Z)return{ok:!1,message:"Nothing to undo."};if(!this.tree.has(Z.beforeEntryId))return{ok:!1,message:"Could not undo: the conversation checkpoint is missing."};let Q;try{Q=await $.diff(Z.beforeRef,Z.afterRef)}catch(z){return{ok:!1,message:`Could not undo: ${z instanceof Error?z.message:String(z)}`}}let W;try{W=await $.snapshot("before undo of last turn")}catch(z){return{ok:!1,message:`Could not undo: ${z instanceof Error?z.message:String(z)}`}}if(!W)return{ok:!1,message:"Could not undo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.beforeRef,Q)}catch(z){let V=await this.restoreCheckpointResources($,W,Q).then(()=>{return}).catch((F)=>F);return{ok:!1,message:`Could not undo: ${z instanceof Error?z.message:String(z)}${V?`; rollback failed: ${V instanceof Error?V.message:String(V)}`:""}`}}let Y=this.tree,G=W0.fromJsonl(Y.toJsonl());G.fork(Z.beforeEntryId);let X=this.checkpoints.state(),J=X.done.slice(0,-1),K=[...X.undone,{...Z,redoRef:W}];this.appendCheckpointCursor(G,J,K);try{await this.store.save(this._sessionId,G)}catch(z){return await this.restoreCheckpointResources($,W,Q).catch(()=>{}),await this.store.save(this._sessionId,Y).catch(()=>{}),{ok:!1,message:`Could not undo: ${z instanceof Error?z.message:String(z)}`}}let B=this.checkpointDetails(Z);return this.checkpoints.restore(J,K),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Undid the last turn.",data:{kind:"checkpoint",action:"undo",files:Q,messageCount:B.messageCount,...B.prompt!==void 0?{prompt:B.prompt}:{}}}}async redo(){if(this.running)return{ok:!1,message:"Cannot redo while a run is active."};let $=this.options.checkpointProvider;if(!$)return{ok:!1,message:"This profile does not support redo."};let Z=this.checkpoints.peekRedo();if(!Z)return{ok:!1,message:"Nothing to redo."};if(!this.tree.has(Z.id))return{ok:!1,message:"Could not redo: the conversation checkpoint is missing."};let Q;try{Q=await $.diff(Z.beforeRef,Z.afterRef)}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let W;try{W=await $.snapshot("before redo of last turn")}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}if(!W)return{ok:!1,message:"Could not redo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.redoRef??Z.afterRef,Q)}catch(F){let D=await this.restoreCheckpointResources($,W,Q).then(()=>{return}).catch((L)=>L);return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}${D?`; rollback failed: ${D instanceof Error?D.message:String(D)}`:""}`}}let Y=this.tree,G=W0.fromJsonl(Y.toJsonl());G.fork(Z.id);let X=this.checkpoints.state(),{redoRef:J,...K}=Z,B=[...X.done,K],z=X.undone.slice(0,-1);this.appendCheckpointCursor(G,B,z);try{await this.store.save(this._sessionId,G)}catch(F){return await this.restoreCheckpointResources($,W,Q).catch(()=>{}),await this.store.save(this._sessionId,Y).catch(()=>{}),{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let V=this.checkpointDetails(Z);return this.checkpoints.restore(B,z),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Redid the turn.",data:{kind:"checkpoint",action:"redo",files:Q,messageCount:V.messageCount}}}async sessionDiff(){let $=this.options.checkpointProvider,Z=this.checkpoints.first();if(!$||!Z)return[];return $.diff(Z.beforeRef)}forkPoints(){let $=[];for(let Z of this.tree.activePath()){if(Z.type!=="message")continue;let Q=Z.message;if(Q.role==="toolResult")continue;if(Q.role==="assistant"&&Q.content.some((G)=>G.type==="toolCall"))continue;let W=Q.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").replace(/\s+/g," ").trim(),Y=Q.role==="assistant"?"mu":Q.role;$.push({id:Z.id,description:`${Y} \xB7 ${W.slice(0,80)||"(no text)"}`})}return $}async fork($){if(this.running)return{ok:!1,message:"Cannot fork while a run is active."};if(!this.tree.get($))return{ok:!1,message:`Could not fork: unknown entry ${$}.`};let Z=W0.fromJsonl(this.tree.toJsonl());Z.fork($),Z.append({type:"custom",customType:"fork",data:{fromEntryId:this.tree.head,targetEntryId:$}});try{await this.store.save(this._sessionId,Z)}catch(Q){return{ok:!1,message:`Could not fork: ${Q instanceof Error?Q.message:String(Q)}`}}return this.tree=Z,this.rebuildCheckpointHistory(),this.refreshContextAccounting(),{ok:!0,message:`Forked from ${$}.`}}get contextPercent(){return this.lastContextPercent}get contextTokens(){return this.lastContextTokens}async run($,Z){return this.execute($,Z,()=>{})}stream($,Z){let Q=[],W=[],Y=!1,G=(J)=>{let K=W.shift();if(K)K({value:J,done:!1});else Q.push(J)},X=this.execute($,Z,G).finally(()=>{Y=!0;while(W.length>0)W.shift()?.({value:void 0,done:!0})});return{async*[Symbol.asyncIterator](){for(;;){if(Q.length>0){yield Q.shift();continue}if(Y)return;let J=await new Promise((K)=>W.push(K));if(J.done)return;yield J.value}},result:()=>X}}async beginCheckpoint($){let Z=this.options.checkpointProvider;if(this.pendingCheckpoint=void 0,!Z)return;try{let Q=await Z.snapshot("before user turn");if(Q)this.pendingCheckpoint={beforeEntryId:$,beforeRef:Q}}catch{}}async finishCheckpoint(){let $=this.pendingCheckpoint,Z=this.options.checkpointProvider;if(this.pendingCheckpoint=void 0,!$||!Z)return;let Q=await Z.snapshot("after user turn").catch(()=>{return});if(!Q)return;let Y={id:this.tree.append({type:"checkpoint",beforeEntryId:$.beforeEntryId,checkpointRef:$.beforeRef,checkpointAfterRef:Q,label:"turn"}).id,beforeEntryId:$.beforeEntryId,beforeRef:$.beforeRef,afterRef:Q,label:"turn"};this.checkpoints.record(Y);let G=this.checkpoints.state();this.appendCheckpointCursor(this.tree,G.done,G.undone)}appendCheckpointCursor($,Z,Q){let W=(Y)=>({id:Y.id,...Y.redoRef?{redoRef:Y.redoRef}:{}});$.append({type:"custom",customType:"checkpoint-cursor",data:{done:Z.map(W),undone:Q.map(W)}})}async restoreCheckpointResources($,Z,Q){if(Q.length===0)return;let W=Q.map((Y)=>Y.path);if($.restoreResources){await $.restoreResources(Z,W);return}await $.restore(Z)}checkpointDetails($){let Z=this.tree.pathTo($.id),Q=$.beforeEntryId?Z.findIndex((X)=>X.id===$.beforeEntryId):-1,W=Z.slice(Q+1),Y=W.find((X)=>X.type==="message"&&X.message.role==="user"),G=Y?.type==="message"?Y.message.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
124
+ `):void 0;return{messageCount:W.filter((X)=>X.type==="message").length,...G!==void 0?{prompt:G}:{}}}rebuildCheckpointHistory(){let $=new Map;for(let Y of this.tree.all()){if(Y.type!=="checkpoint")continue;$.set(Y.id,{id:Y.id,beforeEntryId:Y.beforeEntryId,beforeRef:Y.checkpointRef,afterRef:Y.checkpointAfterRef,...Y.label?{label:Y.label}:{}})}let Z=this.tree.activePath(),Q=Z.findLastIndex((Y)=>Y.type==="custom"&&Y.customType==="checkpoint-cursor"),W=Q===-1?void 0:Z[Q];if(W?.type==="custom"){let Y=W.data,G=(K)=>Array.isArray(K)?K.map((B)=>{let z=typeof B==="string"?B:typeof B==="object"&&B!==null&&typeof B.id==="string"?B.id:void 0,V=z?$.get(z):void 0;if(!V)return;let F=typeof B==="object"&&B!==null&&typeof B.redoRef==="string"?B.redoRef:void 0;return{...V,...F?{redoRef:F}:{}}}).filter((B)=>B!==void 0):[],X=G(Y.done),J=G(Y.undone);for(let K of Z.slice(Q+1)){if(K.type!=="checkpoint")continue;let B=$.get(K.id);if(B)X.push(B);J=[]}this.checkpoints.restore(X,J);return}this.checkpoints.restore(Z.filter((Y)=>Y.type==="checkpoint").map((Y)=>$.get(Y.id)).filter((Y)=>Y!==void 0))}execute($,Z,Q){if(this.stopping)return Promise.reject(Error("Agent has been stopped."));if(this.running)return Promise.reject(Error("Agent already has an active run; use send() to steer it."));this.running=!0;let W=(G)=>{if(Q(G),this.publishToSubscribers(G),G.type==="agent_start"&&!this.sessionStarted)this.sessionStarted=!0,this.options.extensions?.emitLifecycle({type:"session_start",sessionId:this._sessionId});this.options.extensions?.emit(G)};this.activeEmit=W;let Y=this.executeRun($,Z,W).finally(()=>{if(this.running=!1,this.activeEmit=void 0,this.activeExecution=void 0,this.manualCompactionQueued&&!this.stopping)this.scheduleManualCompaction();else if(this.followUps.length>0&&!this.stopping)this.scheduleAutonomousRun();this.resolveIdleIfDone()});return this.activeExecution=Y,Y}async executeRun($,Z,Q){this.controller=new AbortController,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1;let W=this.options.extensions,Y=$;if(typeof $==="string"&&W){W.emitLifecycle({type:"input",text:$});let w=await W.runInputHooks($);if(w?.consume){if(Z?.output)throw Error("Structured output is unavailable because an extension consumed the input.");let _=[{type:"agent_start"},{type:"agent_end",messages:[],reason:"done"}];for(let r of _)Q(r);return{text:"",messages:[],usage:this.totals,reason:"done",sessionId:this._sessionId}}if(w?.text!==void 0)Y=w.text}let G=typeof Y==="string"?t1(Y):{role:"user",content:Y,timestamp:Date.now()},X,J=[...this.options.tools??[],...W?[...W.tools.values()]:[]];if(Z?.allowedTools){let w=new Set(J.map((g)=>g.name)),_=Z.allowedTools.filter((g)=>!w.has(g));if(_.length>0)throw Error(`Unknown allowed tool${_.length===1?"":"s"}: ${_.join(", ")}`);let r=new Set(Z.allowedTools);J=J.filter((g)=>r.has(g.name))}let K=Z?.model?m$(Z.model,this.options.extensions):this.model,B=Z?.model?this.providerFor(K):this.provider,z=d0(K,this.currentThinking),V=Z?.model?void 0:this.lastContextUsage;if(Z?.model)this.lastContextUsage=void 0;let F=iB(this.options.systemPrompt);if(Z?.output)J.push($8(Z.output,(w)=>{X=w})),F.push({text:Z8(),dynamic:!0});let D=this.tree.messagesAt(),L=D.length===0&&this.options.initialMessages?this.options.initialMessages:[];for(let w of L)this.tree.appendMessage(w);let U=await this.options.refreshContext?.([...D,...L],{sessionId:this._sessionId})??[];for(let w of U)this.tree.appendMessage(w);let q={systemPrompt:F,messages:[...D,...L,...U],...J.length>0?{tools:J}:{}};await this.beginCheckpoint(this.tree.head);let A,N=(w)=>y$(K,w,V?.usage,V?.estimatedTokensAtUsage),j=(w,_,r)=>{if(this.totals=j1(this.totals,w),r){if(V={usage:w,estimatedTokensAtUsage:p(r)},!Z?.model)this.lastContextUsage=V}let g=N(_);this.lastContextPercent=g.percent,this.lastContextTokens=g.tokens,Q({type:"usage_updated",sessionTotals:this.totals,contextTokens:g.tokens,contextPercent:g.percent});let a=e6(this.options.budget,this.totals);if(a)A=a;return a},P=this.options.getCredentials,O={provider:B,model:K,streamOpts:{sessionId:this._sessionId,...this.options.apiKey?{apiKey:this.options.apiKey}:{},...P?{getCredentials:()=>P(K.provider)}:{}},thinkingLevel:z,...this.options.budget?.maxTurns!==void 0?{maxTurns:this.options.budget.maxTurns}:{},getSteeringMessages:()=>{let w=this.steering;return this.steering=[],w},getFollowUpMessages:()=>{let w=this.followUps.shift();return w?[w]:[]},beforeToolCall:async(w)=>{if(w.toolCall.name===o1)return;let _=w.args;if(W){let h0=await W.runToolCallHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,args:_});if(h0?.block)return{block:!0,reason:h0.reason??"Blocked by an extension"};if(h0?.args)_=h0.args}let r=J.find((h0)=>h0.name===w.toolCall.name),g=w.toolCall.name;try{g=r?.permissionScope?.(_)??g}catch{}let a=JSON.stringify(_);try{a=r?.permissionPattern?.(_)??a}catch{}let RZ=g===w.toolCall.name?[w.toolCall.name]:[w.toolCall.name,g],O1=k6(this.permissionRules,RZ,a),N$=_===w.args?void 0:{rewrittenArgs:_};if(O1==="allow")return N$;if(O1==="deny")return{block:!0,reason:`Permission denied for ${w.toolCall.name}`};let v0=await Promise.resolve(r?.permissionDetails?.(_)).catch(()=>{return}),g0={id:`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,toolCallId:w.toolCall.id,toolName:w.toolCall.name,permission:g,pattern:a,description:v0?.description??`Run ${w.toolCall.name}`,...v0?.preview?{preview:v0.preview}:{}};Q({type:"permission_asked",request:g0});let O$=this.options.onPermission?await this.options.onPermission(g0):"deny";if(Q({type:"permission_resolved",requestId:g0.id,outcome:O$}),O$==="allow")return N$;return{block:!0,reason:`Permission denied for ${w.toolCall.name}`}},prepareContext:async(w)=>{let _=N(w);this.lastContextPercent=_.percent,this.lastContextTokens=_.tokens;let r=this.options.autoCompact!==!1,g=w;if(r&&_.percent>=_6&&!this.compactRequested){let m=hZ(g,{targetTokens:Math.floor(K.contextWindow*(this.options.compactThreshold??T1)*0.8)});if(m.evicted>0){let N0=m.messages.flatMap((y0,h1)=>{let u1=g[h1];if(!u1||y0===u1)return[];let H6=this.tree.entryIdForMessage(u1);return H6?[{entryId:H6,message:y0}]:[]}),M$=m.messages.filter((y0,h1)=>y0!==g[h1]).length;if(N0.length===M$){Q({type:"compaction_start",layer:1}),this.tree.append({type:"microcompaction",replacements:N0}),g=m.messages,V=void 0,this.lastContextUsage=void 0;let y0=N(g);this.lastContextPercent=y0.percent,this.lastContextTokens=y0.tokens,Q({type:"compaction_end",layer:1,tokensFreed:m.tokensFreed})}}}let a=N(g);if(!(this.compactRequested||r&&E6(a,this.options.compactThreshold??T1)))return{messages:g};let O1=this.reactiveRecoveryPending?"overflow":this.compactorOverride?"model-change":this.compactRequested?"manual":"threshold",N$=this.compactRequestedFocus,v0=this.compactorOverride??{model:K,provider:B};this.compactRequested=!1,this.compactRequestedFocus=void 0,this.compactorOverride=void 0;let g0=this.reactiveRecoveryPending?3:2;if(g0===2)Q({type:"compaction_start",layer:g0,trigger:O1,contextTokensBefore:a.tokens});let O$,h0=!1;try{Q({type:"compaction_update",layer:g0,stage:"summarizing"});let m=await fZ(g,{provider:v0.provider,model:v0.model,keepRecentTokens:Math.min(r1,Math.max(2,Math.floor(K.contextWindow*0.2))),...O.streamOpts?{streamOpts:{...O.streamOpts,...P?{getCredentials:()=>P(v0.model.provider)}:{}}}:{},...this.options.carryoverExtractor?{carryoverExtractor:this.options.carryoverExtractor}:{},...N$?{customInstructions:N$}:{},signal:this.controller.signal});O$=m.usage;let N0=b$(m),M$;if(m.summary.length>0){let y0=m.keptMessages[0],h1=null;if(y0){let CZ=this.tree.entryIdForMessage(y0);if(!CZ)throw Error("Compaction tail could not be mapped to the session");h1=CZ}let u1=N0[0];M$=this.tree.append({type:"compaction",summary:m.summary,...m.carryover!==void 0?{carryover:m.carryover}:{},firstKeptEntryId:h1,...u1?{timestamp:u1.timestamp}:{},trigger:O1,contextTokensBefore:a.tokens,contextTokensAfter:p(N0),model:`${K.provider}/${K.id}`,compactorModel:`${v0.model.provider}/${v0.model.id}`,windowNumber:this.tree.activePath().filter((CZ)=>CZ.type==="compaction").length+1,strategy:"summary-tail",keptTokens:p(m.keptMessages),usage:m.usage}).id}return V=void 0,this.lastContextUsage=void 0,j(m.usage,N0),h0=!0,Q({type:"compaction_end",layer:g0,tokensFreed:m.tokensFreed,trigger:O1,status:m.summary.length>0?"completed":"noop",contextTokensBefore:a.tokens,contextTokensAfter:N(N0).tokens,keptTokens:p(m.keptMessages),...M$?{summaryEntryId:M$}:{}}),this.reactiveRecoveryPending=!1,{messages:N0,stop:A!==void 0}}catch(m){let N0=O$??(m instanceof _0?m.usage:void 0);if(N0&&!h0)j(N0,g);return Q({type:"compaction_end",layer:g0,tokensFreed:0,trigger:O1,status:this.controller.signal.aborted?"cancelled":"failed",contextTokensBefore:a.tokens,contextTokensAfter:a.tokens,errorMessage:m instanceof Error?m.message:"Compaction failed for an unknown reason"}),this.reactiveRecoveryPending=!1,{messages:g,stop:A!==void 0}}},...W?{transformContext:(w)=>W.runContextHooks(w)}:{},...W?{afterToolCall:async(w)=>{let _=await W.runToolResultHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,result:w.result,isError:w.isError});if(!_)return;return{...w.result,..._.content?{content:_.content}:{},..._.isError!==void 0?{isError:_.isError}:{}}}}:{},recoverFromError:(w)=>{if(this.recoveryAttempted||!C$(w))return!1;return this.recoveryAttempted=!0,this.compactRequested=!0,this.reactiveRecoveryPending=!0,Q({type:"compaction_start",layer:3,trigger:"overflow"}),!0},shouldStopAfterTurn:async(w)=>{if(this.recoveryAttempted=!1,j(w.message.usage,w.context.messages,w.requestMessages))return!0;return!1}},C=await(async()=>{try{return await S6([G],q,O,(w)=>{if(Q(w),w.type==="message_end")this.tree.appendMessage(w.message)},this.controller.signal)}finally{await this.finishCheckpoint()}})();await this.store.save(this._sessionId,this.tree);let v=A??(C.reason==="budget"?"maxCostUsd":C.reason),d={text:nB(C.messages),messages:C.messages,usage:this.totals,reason:v,sessionId:this._sessionId};if(!Z?.output)return d;if(X===void 0)throw Error(`Structured output was requested but the model never produced a valid one (run ended: ${v}).`);return{...d,output:X}}providerFor($){return this.options.provider??this.options.extensions?.providers.get($.provider)??O6($.provider)}publishEvent($){if(this.activeEmit){this.activeEmit($);return}this.publishToSubscribers($),this.options.extensions?.emit($)}refreshContextAccounting(){let $=y$(this.model,this.tree.messagesAt(),this.lastContextUsage?.usage,this.lastContextUsage?.estimatedTokensAtUsage);this.lastContextPercent=$.percent,this.lastContextTokens=$.tokens,this.publishEvent({type:"usage_updated",sessionTotals:this.totals,contextTokens:$.tokens,contextPercent:$.percent})}publishToSubscribers($){for(let Z of this.subscribers)try{Promise.resolve(Z($)).catch(()=>{})}catch{}}scheduleAutonomousRun(){if(this.running||this.autonomousScheduled||this.stopping||this.followUps.length===0)return;this.autonomousScheduled=!0,queueMicrotask(()=>{if(this.autonomousScheduled=!1,this.running||this.stopping){this.resolveIdleIfDone();return}let $=this.followUps.shift();if(!$||$.role!=="user"){this.resolveIdleIfDone();return}this.execute($.content,void 0,()=>{}).catch(()=>{})})}scheduleManualCompaction(){if(this.running||this.autonomousScheduled||this.stopping||!this.manualCompactionQueued)return;let $=this.queuedManualCompactionFocus;this.manualCompactionQueued=!1,this.queuedManualCompactionFocus=void 0,this.autonomousScheduled=!0,queueMicrotask(()=>{if(this.autonomousScheduled=!1,this.running||this.stopping){this.resolveIdleIfDone();return}this.compactNow($).catch(()=>{})})}resolveIdleIfDone(){if(this.running||this.autonomousScheduled||this.manualCompactionQueued||this.followUps.length>0)return;for(let $ of this.idleWaiters)$();this.idleWaiters.clear()}}import{createHash as tB,randomBytes as $5}from"crypto";import{chmod as Y8,mkdir as oB,readFile as sB,rename as eB,stat as $H,unlink as ZH,writeFile as QH}from"fs/promises";import{createServer as hW}from"http";import{homedir as WH}from"os";import{dirname as YH,join as uW}from"path";var aB=[{x:0,y:0,w:5,h:1},{x:0,y:1,w:1,h:4},{x:2,y:1,w:1,h:4},{x:4,y:1,w:1,h:4},{x:6,y:0,w:1,h:5},{x:9,y:0,w:1,h:5},{x:7,y:4,w:2,h:1}];function Q8($){return $.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function rB(){return`<svg class="mark" viewBox="0 0 10 5" role="img" aria-label="mu">${aB.map((Z)=>`<rect x="${Z.x}" y="${Z.y}" width="${Z.w}" height="${Z.h}"/>`).join("")}</svg>`}function W8($){let Z=$.status==="success"?"#fff":"#f87171";return`<!doctype html>
98
125
  <html lang="en">
99
126
  <head>
100
127
  <meta charset="utf-8">
101
128
  <meta name="viewport" content="width=device-width, initial-scale=1">
102
129
  <meta name="color-scheme" content="dark">
103
- <title>mu \u2014 ${g6($.heading.toLowerCase())}</title>
130
+ <title>mu \u2014 ${Q8($.heading.toLowerCase())}</title>
104
131
  <style>
105
132
  :root { color-scheme: dark; }
106
133
  html, body { height: 100%; }
@@ -152,75 +179,97 @@ Prefer a small number of well-chosen tool calls over many exploratory ones. When
152
179
  </head>
153
180
  <body>
154
181
  <main>
155
- ${zB()}
156
- <h1>${g6($.heading)}</h1>
157
- <p>${g6($.detail)}</p>
182
+ ${rB()}
183
+ <h1>${Q8($.heading)}</h1>
184
+ <p>${Q8($.detail)}</p>
158
185
  </main>
159
186
  </body>
160
187
  </html>
161
- `}function vZ($){return h6({provider:$,status:"success",heading:"Authentication successful",detail:`${$} authentication completed. You can close this window.`})}function O1($,Z){return h6({provider:$,status:"error",heading:"Authentication failed",detail:Z})}var m6=1,l6="app_EMoamEEZ73f0CkXaXp7hrann",gZ="OpenAI",OQ="https://auth.openai.com",MB="openid profile email offline_access api.connectors.read api.connectors.invoke",jB="https://api.openai.com/auth",Z1="openai-codex",p6="github-copilot",mZ={"user-agent":"GitHubCopilotChat/0.35.0","editor-version":"vscode/1.107.0","editor-plugin-version":"copilot-chat/0.35.0","copilot-integration-id":"vscode-chat"},PB="2026-06-01",wB=60000,N1=15000,TB=300000,IB=[1455,1457];function c6(){return qQ(OB(),".mu","auth.json")}function EB(){return{version:m6,providers:{}}}function y$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function RB($,Z){if(!y$($))throw Error(`Invalid stored credentials for "${Z}"`);if($.type==="apiKey"&&typeof $.apiKey==="string"&&$.apiKey.length>0)return{type:"apiKey",apiKey:$.apiKey};if($.type==="oauth"&&typeof $.accessToken==="string"&&typeof $.refreshToken==="string"&&typeof $.expiresAt==="number"&&Number.isFinite($.expiresAt)){if((Z==="openai"||Z===Z1)&&(typeof $.accountId!=="string"||$.accountId.length===0))throw Error(`Invalid stored credentials for "${Z}"`);return{type:"oauth",accessToken:$.accessToken,refreshToken:$.refreshToken,...typeof $.idToken==="string"?{idToken:$.idToken}:{},expiresAt:$.expiresAt,...typeof $.accountId==="string"?{accountId:$.accountId}:{},...typeof $.baseUrl==="string"?{baseUrl:$.baseUrl}:{},...Array.isArray($.availableModelIds)&&$.availableModelIds.every((W)=>typeof W==="string")?{availableModelIds:$.availableModelIds}:{}}}throw Error(`Invalid stored credentials for "${Z}"`)}async function l0($={}){let Z=$.authFile??c6(),W;try{W=await DB(Z,"utf8")}catch(X){if(X.code==="ENOENT")return EB();throw X}let Q;try{Q=JSON.parse(W)}catch{throw Error(`Could not parse authentication file: ${Z}`)}if(!y$(Q)||Q.version!==m6||!y$(Q.providers))throw Error(`Unsupported authentication file: ${Z}`);let Y={};for(let[X,J]of Object.entries(Q.providers)){let K=RB(J,X),H=X==="openai"&&K.type==="oauth"?Z1:X;if(H===X)Y[H]=K;else Y[H]??=K}let G=Q.activeProvider==="openai"&&!Y.openai&&Y[Z1]?.type==="oauth"?Z1:Q.activeProvider;if(process.platform!=="win32"){if(((await UB(Z)).mode&63)!==0)await u6(Z,384)}return{version:m6,...typeof G==="string"?{activeProvider:G}:{},providers:Y}}async function b$($,Z={}){let W=Z.authFile??c6(),Q=NB(W);if(await FB(Q,{recursive:!0,mode:448}),process.platform!=="win32")await u6(Q,448);let Y=qQ(Q,`.auth-${process.pid}-${uZ(8).toString("hex")}.tmp`);try{if(await qB(Y,`${JSON.stringify($,null,2)}
162
- `,{encoding:"utf8",mode:384,flag:"wx"}),await LB(Y,W),process.platform!=="win32")await u6(W,384)}catch(G){throw await AB(Y).catch(()=>{}),G}}async function SB($,Z,W={}){let Q=$.trim(),Y=Z.trim();if(!Q)throw Error("Provider is required");if(!Y)throw Error("API key cannot be empty");let G=await l0(W);G.providers[Q]={type:"apiKey",apiKey:Y},G.activeProvider=Q,await b$(G,W)}async function CB($,Z={}){let W=$.trim();if(!W)throw Error("Provider is required");let Q=await l0(Z);if(!Q.providers[W])return!1;if(delete Q.providers[W],Q.activeProvider===W){let Y=Object.keys(Q.providers)[0];if(Y)Q.activeProvider=Y;else delete Q.activeProvider}return await b$(Q,Z),!0}async function yB($={}){return Object.keys((await l0($)).providers)}async function bB($={}){let Z=await l0($);return Z.activeProvider&&Z.providers[Z.activeProvider]?Z.activeProvider:Object.keys(Z.providers)[0]}async function lZ($,Z,W){let Q=await l0(W);Q.providers[$]=Z,Q.activeProvider=$,await b$(Q,W)}function NQ($){let Z=$.split(".")[1];if(!Z)return;try{let W=JSON.parse(Buffer.from(Z,"base64url").toString("utf8"));return y$(W)?W:void 0}catch{return}}function VQ($){let Z=NQ($)?.[jB]?.chatgpt_account_id;return typeof Z==="string"&&Z.length>0?Z:void 0}function kB($){let Z=NQ($)?.exp;return typeof Z==="number"&&Number.isFinite(Z)?Z*1000:void 0}function _B($,Z,W){let Q=W.trim()?`: ${W.trim().slice(0,1000)}`:"";return Error(`OpenAI token ${$} failed (${Z.status})${Q}`)}async function MQ($,Z){if(!$.ok)throw _B(Z,$,await $.text().catch(()=>""));let W=await $.json();if(!y$(W))throw Error(`OpenAI token ${Z} returned invalid JSON`);return W}function jQ($,Z,W){let Q=typeof $.access_token==="string"?$.access_token:W?.accessToken,Y=typeof $.refresh_token==="string"?$.refresh_token:W?.refreshToken,G=typeof $.id_token==="string"?$.id_token:W?.idToken;if(!Q||!Y)throw Error("OpenAI token response is missing access or refresh token");let X=VQ(Q)??(G?VQ(G):void 0)??W?.accountId;if(!X)throw Error("OpenAI token did not include a ChatGPT account");if(W?.accountId&&X!==W.accountId)throw Error("Refusing to rotate OpenAI credentials across ChatGPT accounts");let J=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in*1000:void 0,K=kB(Q)??(J!==void 0?Z+J:Z+3600000);return{type:"oauth",accessToken:Q,refreshToken:Y,...G?{idToken:G}:{},expiresAt:K,accountId:X}}async function xB($,Z){let W=(Z.openAiIssuer??OQ).replace(/\/+$/,""),Q=await(Z.fetch??fetch)(`${W}/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:Z.openAiClientId??l6,grant_type:"refresh_token",refresh_token:$.refreshToken}),signal:AbortSignal.timeout(N1)});return jQ(await MQ(Q,"refresh"),(Z.now??Date.now)(),$)}function FQ($){return{type:"oauth",accessToken:$.accessToken,...$.accountId?{accountId:$.accountId}:{},...$.baseUrl?{baseUrl:$.baseUrl}:{},...$.availableModelIds?{availableModelIds:$.availableModelIds}:{}}}function DQ($,Z,W){return Z.expiresAt>W+wB&&($!==p6||Z.availableModelIds!==void 0)}async function W1($,Z){let W=await $.text(),Q;try{Q=JSON.parse(W)}catch{throw Error(`${Z} returned invalid JSON (${$.status})`)}if(!$.ok){let Y=typeof Q==="object"&&Q!==null?Q:{},G=Y.error_description??Y.message??Y.error;throw Error(`${Z} failed (${$.status})${typeof G==="string"?`: ${G}`:""}`)}if(typeof Q!=="object"||Q===null||Array.isArray(Q))throw Error(`${Z} returned invalid JSON`);return Q}function LQ($,Z,W=60000){let Q=typeof $.access_token==="string"?$.access_token:Z.accessToken,Y=typeof $.refresh_token==="string"?$.refresh_token:Z.refreshToken,G=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in:3600;if(!Q||!Y)throw Error("OAuth response is missing tokens");return{...Z,accessToken:Q,refreshToken:Y,expiresAt:Date.now()+G*1000-W}}function PQ($){let Z=$.match(/(?:^|;)proxy-ep=([^;]+)/)?.[1];return Z?`https://${Z.replace(/^proxy\./,"api.")}`:"https://api.individual.githubcopilot.com"}function fB($){if(typeof $!=="object"||$===null||!Array.isArray($.data))throw Error("GitHub Copilot models response is invalid");return $.data.filter((Z)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z))}function vB($){let Z=typeof $.policy==="object"&&$.policy!==null?$.policy:void 0,W=typeof $.capabilities==="object"&&$.capabilities!==null?$.capabilities:void 0,Q=typeof W?.supports==="object"&&W.supports!==null?W.supports:void 0;return $.model_picker_enabled===!0&&Z?.state!=="disabled"&&Q?.tool_calls!==!1}async function wQ($,Z,W,Q){let Y=await W(`${Z.replace(/\/+$/,"")}/models`,{headers:{accept:"application/json",authorization:`Bearer ${$}`,...mZ,"x-github-api-version":PB},...Q?{signal:Q}:{}});return fB(await W1(Y,"GitHub Copilot model discovery"))}async function TQ($,Z,W,Q){return(await wQ($,Z,W,Q)).filter(vB).map((Y)=>Y.id).filter((Y)=>typeof Y==="string"&&Y.length>0)}async function IQ($,Z,W,Q){let Y=await wQ($,Z,W,Q);return await Promise.all(Y.map(async(G)=>{if(typeof G.id!=="string"||G.id.length===0)return;await W(`${Z.replace(/\/+$/,"")}/models/${encodeURIComponent(G.id)}/policy`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${$}`,...mZ,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"}),...Q?{signal:Q}:{}}).catch(()=>{return})})),TQ($,Z,W,Q)}async function gB($,Z,W){let Q=W.fetch??fetch;if($==="kimi-coding"){let Y=await Q("https://auth.kimi.com/api/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",grant_type:"refresh_token",refresh_token:Z.refreshToken}),signal:AbortSignal.timeout(N1)});return LQ(await W1(Y,"Kimi Code token refresh"),Z)}if($==="xai"){let Y=await Q("https://auth.x.ai/oauth2/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:"b1a00492-073a-47ea-816f-4c329264a828",grant_type:"refresh_token",refresh_token:Z.refreshToken}),signal:AbortSignal.timeout(N1)});return LQ(await W1(Y,"xAI token refresh"),Z,300000)}if($===p6){let Y=await Q("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${Z.refreshToken}`,...mZ},signal:AbortSignal.timeout(N1)}),G=await W1(Y,"GitHub Copilot token refresh");if(typeof G.token!=="string"||typeof G.expires_at!=="number")throw Error("GitHub Copilot token refresh returned invalid credentials");let X=G.token,J=PQ(X),K=AbortSignal.timeout(N1),H=Z.availableModelIds?await TQ(X,J,Q,K):await IQ(X,J,Q,K);return{...Z,accessToken:X,expiresAt:G.expires_at*1000-300000,baseUrl:J,availableModelIds:H}}if($===Z1){if(!Z.accountId)throw Error("OpenAI login is missing its ChatGPT account");return xB(Z,W)}throw Error(`OAuth refresh is not implemented for provider "${$}"`)}function hB($={}){let Z=new Map;return async(W)=>{let Y=(await l0($)).providers[W];if(!Y)return;if(Y.type==="apiKey")return{type:"apiKey",apiKey:Y.apiKey};let G=($.now??Date.now)();if(DQ(W,Y,G))return FQ(Y);let X=Z.get(W);if(X)return X;let J=(async()=>{let K=await l0($),H=K.providers[W];if(!H||H.type!=="oauth")throw Error(`${W} login is no longer available`);let V=($.now??Date.now)(),z=DQ(W,H,V)?H:await gB(W,H,$);if(z!==H)K.providers[W]=z,await b$(K,$);return FQ(z)})().finally(()=>{Z.delete(W)});return Z.set(W,J),J}}function EQ(){let $=uZ(64).toString("base64url");return{verifier:$,challenge:VB("sha256").update($).digest("base64url")}}function RQ($,Z){return new Promise((W,Q)=>{let Y=(X)=>{$.off("listening",G),Q(X)},G=()=>{$.off("error",Y);let X=$.address();if(!X||typeof X==="string"){Q(Error("Could not determine OAuth callback port"));return}W(X.port)};$.once("error",Y),$.once("listening",G),$.listen(Z,"127.0.0.1")})}async function uB($,Z,W){if(W.aborted)throw Error("OpenAI login cancelled");let Q=Z===void 0?IB:[Z],Y;for(let G of Q){let X=()=>{},J=()=>{},K=new Promise((z,F)=>{X=z,J=F}),H=!1,V=AQ((z,F)=>{let D=new URL(z.url??"/","http://localhost");if(F.setHeader("content-type","text/html; charset=utf-8"),D.pathname!=="/auth/callback"){F.statusCode=404,F.end(O1(gZ,"That page does not exist."));return}if(D.searchParams.get("state")!==$){F.statusCode=400,F.end(O1(gZ,"State mismatch. Return to mu and try again."));return}let L=D.searchParams.get("error"),U=D.searchParams.get("code");if(L||!U){if(F.statusCode=400,F.end(O1(gZ,"Return to mu and try again.")),!H)H=!0,J(Error(`OpenAI login failed: ${L??"missing authorization code"}`));return}if(F.end(vZ(gZ)),!H)H=!0,X(U)});try{let z=await RQ(V,G),F=()=>{if(!H)H=!0,J(Error("OpenAI login cancelled"));V.close()};if(W.addEventListener("abort",F,{once:!0}),W.aborted)F();return{redirectUri:`http://localhost:${z}/auth/callback`,callback:K.finally(()=>W.removeEventListener("abort",F)),close:()=>V.close()}}catch(z){Y=z,V.close()}}throw Error(`Could not start OpenAI login callback server: ${Y instanceof Error?Y.message:String(Y)}`)}async function mB($={}){let Z=new AbortController,W=()=>Z.abort();if($.signal?.addEventListener("abort",W,{once:!0}),$.signal?.aborted)Z.abort();let Q=setTimeout(W,$.timeoutMs??TB);Q.unref?.();let Y=uZ(32).toString("base64url"),G=EQ(),X=($.openAiIssuer??OQ).replace(/\/+$/,""),J;try{J=$.callbackServer?await $.callbackServer(Y,Z.signal):await uB(Y,$.port,Z.signal);let K=new URL(`${X}/oauth/authorize`);K.search=new URLSearchParams({response_type:"code",client_id:$.openAiClientId??l6,redirect_uri:J.redirectUri,scope:MB,code_challenge:G.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:Y,originator:"mu"}).toString(),await $.onAuthUrl?.(K.toString());let H=await J.callback,V=await($.fetch??fetch)(`${X}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$.openAiClientId??l6,code:H,code_verifier:G.verifier,redirect_uri:J.redirectUri}),signal:Z.signal}),z=jQ(await MQ(V,"exchange"),($.now??Date.now)()),F=await l0($);return F.providers[Z1]=z,F.activeProvider=Z1,await b$(F,$),{provider:Z1,accountId:z.accountId}}finally{clearTimeout(Q),$.signal?.removeEventListener("abort",W),J?.close()}}function o($,Z,W){let Q=$[Z];if(typeof Q!=="string"||Q.length===0)throw Error(`${W} response is missing ${Z}`);return Q}function hZ($,Z){let W;try{W=new URL($)}catch{throw Error(`${Z} returned an invalid authorization URL`)}if(W.protocol!=="https:"&&W.protocol!=="http:")throw Error(`${Z} returned an unsafe authorization URL`);return W.toString()}function UQ($,Z){let W=hZ($,Z);if(!W.startsWith("https:"))throw Error(`${Z} returned an unsafe authorization URL`);return W}function m0($,Z,W){let Q=$[Z];return typeof Q==="number"&&Number.isFinite(Q)&&Q>0?Q:W}async function lB($,Z){if(Z?.aborted)throw Error("Login cancelled");await new Promise((W,Q)=>{let G=setTimeout(()=>{Z?.removeEventListener("abort",X),W()},$),X=()=>{clearTimeout(G),Z?.removeEventListener("abort",X),Q(Error("Login cancelled"))};if(Z?.addEventListener("abort",X,{once:!0}),Z?.aborted)X()})}async function d6($){let Z=Date.now()+$.expiresInSeconds*1000,W=Math.max(0.05,$.intervalSeconds);while(Date.now()<Z){await lB(W*1000,$.signal);let Q=await $.fetch($.url,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams($.fields),...$.signal?{signal:$.signal}:{}}),Y=await W1(Q.status>=400&&Q.status<500?new Response(await Q.text(),{status:200,headers:Q.headers}):Q,`${$.provider} device token request`);if(Q.ok&&typeof Y.access_token==="string")return Y;if(Y.error==="authorization_pending")continue;if(Y.error==="slow_down"){W=m0(Y,"interval",W+5);continue}throw Error(`${$.provider} login failed${typeof Y.error_description==="string"?`: ${Y.error_description}`:typeof Y.error==="string"?`: ${Y.error}`:""}`)}throw Error(`${$.provider} login timed out`)}async function i6($,Z,W,Q){let Y=await($.fetch??fetch)(W,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Q),...$.signal?{signal:$.signal}:{}});return W1(Y,`${Z} device authorization`)}async function pB($={}){let W=$.fetch??fetch,Q=await i6($,"Kimi Code","https://auth.kimi.com/api/oauth/device_authorization",{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098"}),Y=typeof Q.verification_uri_complete==="string"?hZ(Q.verification_uri_complete,"Kimi Code"):hZ(o(Q,"verification_uri","Kimi Code"),"Kimi Code"),G=o(Q,"user_code","Kimi Code");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await d6({fetch:W,url:"https://auth.kimi.com/api/oauth/token",fields:{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",device_code:o(Q,"device_code","Kimi Code"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:m0(Q,"interval",5),expiresInSeconds:m0(Q,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"Kimi Code"}),J=m0(X,"expires_in",3600);return await lZ("kimi-coding",{type:"oauth",accessToken:o(X,"access_token","Kimi Code"),refreshToken:o(X,"refresh_token","Kimi Code"),expiresAt:($.now??Date.now)()+J*1000},$),{provider:"kimi-coding"}}async function cB($={}){let W=$.fetch??fetch,Q=await i6($,"xAI","https://auth.x.ai/oauth2/device/code",{client_id:"b1a00492-073a-47ea-816f-4c329264a828",scope:"openid profile email offline_access grok-cli:access api:access",referrer:"mu"}),Y=typeof Q.verification_uri_complete==="string"?UQ(Q.verification_uri_complete,"xAI"):UQ(o(Q,"verification_uri","xAI"),"xAI"),G=o(Q,"user_code","xAI");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await d6({fetch:W,url:"https://auth.x.ai/oauth2/token",fields:{client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_code:o(Q,"device_code","xAI"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:m0(Q,"interval",5),expiresInSeconds:m0(Q,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"xAI"}),J=m0(X,"expires_in",3600);return await lZ("xai",{type:"oauth",accessToken:o(X,"access_token","xAI"),refreshToken:o(X,"refresh_token","xAI"),expiresAt:($.now??Date.now)()+J*1000-300000},$),{provider:"xai"}}async function dB($={}){let Z=Buffer.from("SXYxLmI1MDdhMDhjODdlY2ZlOTg=","base64").toString("utf8"),W=$.fetch??fetch,Q=await i6($,"GitHub Copilot","https://github.com/login/device/code",{client_id:Z,scope:"read:user"}),Y=hZ(o(Q,"verification_uri","GitHub Copilot"),"GitHub Copilot"),G=o(Q,"user_code","GitHub Copilot");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await d6({fetch:W,url:"https://github.com/login/oauth/access_token",fields:{client_id:Z,device_code:o(Q,"device_code","GitHub Copilot"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:m0(Q,"interval",5),expiresInSeconds:m0(Q,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"GitHub Copilot"}),J=o(X,"access_token","GitHub Copilot"),K=await W("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${J}`,...mZ},...$.signal?{signal:$.signal}:{}}),H=await W1(K,"GitHub Copilot token exchange"),V=o(H,"token","GitHub Copilot"),z=H.expires_at;if(typeof z!=="number"||!Number.isFinite(z))throw Error("GitHub Copilot response is missing expires_at");let F=PQ(V),D=$.signal?AbortSignal.any([$.signal,AbortSignal.timeout(N1)]):AbortSignal.timeout(N1),L=await IQ(V,F,W,D);return await lZ(p6,{type:"oauth",accessToken:V,refreshToken:J,expiresAt:z*1000-300000,baseUrl:F,availableModelIds:L},$),{provider:"github-copilot"}}async function iB($,Z){let W=`/oauth/callback/${uZ(18).toString("base64url")}`,Q=()=>{},Y=()=>{},G=new Promise((V,z)=>{Q=V,Y=z}),X=!1,J=AQ((V,z)=>{let F=new URL(V.url??"/","http://127.0.0.1");if(z.setHeader("content-type","text/html; charset=utf-8"),F.pathname!==W){z.statusCode=404,z.end(O1($,"That page does not exist."));return}let D=F.searchParams.get("error"),L=F.searchParams.get("code");if(D||!L){if(z.statusCode=400,z.end(O1($,"Authorization was not completed.")),!X)X=!0,Y(Error(`${$} login failed: ${D??"missing authorization code"}`));return}if(z.end(vZ($)),!X)X=!0,Q(L)});await RQ(J,0);let K=J.address();if(!K||typeof K==="string")throw J.close(),Error(`Could not start the ${$} callback server`);let H=()=>{if(!X)X=!0,Y(Error(`${$} login cancelled`));J.close()};if(Z?.addEventListener("abort",H,{once:!0}),Z?.aborted)H();return{callbackUrl:`http://127.0.0.1:${K.port}${W}`,code:G.finally(()=>Z?.removeEventListener("abort",H)),close:()=>J.close()}}async function nB($={}){let Z=EQ(),W=$.callbackServer?await $.callbackServer("OpenRouter",$.signal):await iB("OpenRouter",$.signal);try{let Q=new URL("https://openrouter.ai/auth");Q.search=new URLSearchParams({callback_url:W.callbackUrl,code_challenge:Z.challenge,code_challenge_method:"S256"}).toString(),await $.onAuthUrl?.(Q.toString());let Y=await W.code,G=await($.fetch??fetch)("https://openrouter.ai/api/v1/auth/keys",{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({code:Y,code_verifier:Z.verifier,code_challenge_method:"S256"}),...$.signal?{signal:$.signal}:{}}),X=await W1(G,"OpenRouter key exchange");return await lZ("openrouter",{type:"oauth",accessToken:o(X,"key","OpenRouter"),refreshToken:"",expiresAt:Number.MAX_SAFE_INTEGER},$),{provider:"openrouter"}}finally{W.close()}}function aB($){let Z=$.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens,W=(Q)=>Math.max(0,Math.trunc(Q)).toLocaleString("en-US");return["Session usage",` Input tokens: ${W($.inputTokens)}`,` Output tokens: ${W($.outputTokens)}`,` Cache read tokens: ${W($.cacheReadTokens)}`,` Cache write tokens: ${W($.cacheWriteTokens)}`,` Total tokens: ${W(Z)}`,` Cost: $${($.costUsd??0).toFixed(6)}`,` Active context: ${(Math.max(0,$.contextPercent)*100).toFixed(1)}%`].join(`
163
- `)}function SQ($={}){return[{name:"help",description:"List available commands",run:(Z)=>{return Z.print("Commands are listed by the registry that owns them."),{handled:!0}}},{name:"model",description:"Show or switch the active model",run:(Z)=>{let W=Z.args.trim();if(!W)return Z.print(`Current model: ${Z.getModel()}`),{handled:!0};let Q=A1(W);if(!Q){let Y=P$().map((G)=>`${G.provider}/${G.id}`).join(", ");return{handled:!0,message:`Unknown model "${W}". Known models: ${Y}`}}return Z.setModel(`${Q.provider}/${Q.id}`),{handled:!0,message:`Model set to ${Q.provider}/${Q.id}`}}},{name:"compact",description:"Summarize the conversation so far to free context",run:()=>{if(!$.requestCompaction)return{handled:!0,message:"Compaction is not available on this surface."};return $.requestCompaction(),{handled:!0,message:"Compacting before the next turn."}}},{name:"undo",description:"Revert the last step \u2014 both the workspace and the conversation",run:async()=>{if(!$.undo)return{handled:!0,message:"Undo is not available here."};let Z=await $.undo();return{handled:!0,message:Z.message,...Z.data?{data:Z.data}:{}}}},{name:"redo",description:"Re-apply the step that was undone",run:async()=>{if(!$.redo)return{handled:!0,message:"Redo is not available here."};let Z=await $.redo();return{handled:!0,message:Z.message,...Z.data?{data:Z.data}:{}}}},{name:"fork",description:"Branch the conversation from an earlier point",run:async(Z)=>{if(!$.fork)return{handled:!0,message:"Fork is not available here."};let W=Z.args.trim();if(!W){let Y=$.forkPoints?.()??[];if(Y.length===0)return{handled:!0,message:"No branch points yet."};return{handled:!0,message:Y.map((G)=>`${G.id} \xB7 ${G.description}`).join(`
164
- `),data:{kind:"fork-points",points:Y}}}return{handled:!0,message:(await $.fork(W)).message}}},{name:"diff",description:"Show everything this session has changed",run:async()=>{if(!$.diff)return{handled:!0,message:"Diff is not available here."};let Z=await $.diff();if(Z.length===0)return{handled:!0,message:"No changes yet."};return{handled:!0,data:{kind:"diff",files:Z}}}},{name:"cost",description:"Show token usage and cost for this session",run:()=>{let Z=$.usage?.();return{handled:!0,message:Z?aB(Z):"Usage is reported by the surface that owns the session."}}}]}function rB($={}){let Z=new L1;for(let W of SQ($))Z.register(W);return Z.register({name:"help",description:"List available commands",run:(W)=>{let Q=Z.list().map((Y)=>` /${Y.name.padEnd(12)} ${Y.description}`);return W.print(`Available commands:
165
- ${Q.join(`
166
- `)}`),{handled:!0}}}),Z}import{readdir as tB,stat as oB}from"fs/promises";import{homedir as sB}from"os";import{isAbsolute as eB,join as n6,resolve as $H}from"path";function ZH($){return typeof $==="object"&&$!==null&&typeof $.name==="string"&&typeof $.activate==="function"}async function a6($){try{return(await tB($)).filter((W)=>W.endsWith(".ts")||W.endsWith(".js")).sort().map((W)=>n6($,W))}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function WH($){try{return(await oB($)).isDirectory()?a6($):[$]}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function CQ($={}){let Z=[];if($.userDir!==!1)Z.push(...await a6(n6(sB(),".mu","extensions")));if($.projectDir)Z.push(...await a6(n6($.projectDir,".mu","extensions")));for(let W of $.paths??[])Z.push(...await WH(eB(W)?W:$H(W)));return Z}async function QH($,Z={}){let W={loaded:[],failed:[]};for(let Q of await CQ(Z))try{let Y=await import(Q),G=Y.default??Y.extension;if(!ZH(G)){W.failed.push({file:Q,error:"no default export with { name, activate } found"});continue}await $.register(G),W.loaded.push(Q)}catch(Y){W.failed.push({file:Q,error:Y instanceof Error?Y.message:String(Y)})}return W}import{mkdir as YH,readdir as GH,readFile as XH,writeFile as JH}from"fs/promises";import{homedir as KH}from"os";import{join as r6}from"path";class yQ{dir;constructor($={}){let Z=$.root??r6(KH(),".mu","sessions");this.dir=$.scope?r6(Z,$.scope):Z}path($){let Z=$.replace(/[^A-Za-z0-9._-]/g,"_");return r6(this.dir,`${Z}.jsonl`)}async load($){try{return Z0.fromJsonl(await XH(this.path($),"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw Z}}async save($,Z){await YH(this.dir,{recursive:!0}),await JH(this.path($),Z.toJsonl(),"utf8")}async list(){try{return(await GH(this.dir)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.slice(0,-6))}catch($){if($.code==="ENOENT")return[];throw $}}}import{readdir as BH,readFile as HH}from"fs/promises";import{homedir as zH}from"os";import{basename as VH,join as t6}from"path";function pZ($){let Z=$.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
167
- `),W=/^---\n([\s\S]*?)\n---\n?/.exec(Z);if(!W)return{meta:{},body:Z.trim()};let Q={};for(let Y of(W[1]??"").split(`
168
- `)){let G=Y.indexOf(":");if(G===-1)continue;let X=Y.slice(0,G).trim(),J=Y.slice(G+1).trim();if(X.length===0)continue;Q[X]=J.startsWith("[")&&J.endsWith("]")?J.slice(1,-1).split(",").map((K)=>K.trim().replace(/^["']|["']$/g,"")).filter((K)=>K.length>0):J.replace(/^["']|["']$/g,"")}return{meta:Q,body:Z.slice(W[0].length).trim()}}function kQ($,Z){let W=Z.trim().length>0?Z.trim().split(/\s+/):[],Q=!1,Y=$.replace(/\$ARGUMENTS\b/g,()=>{return Q=!0,Z.trim()});if(Y=Y.replace(/\$([1-9])\b/g,(G,X)=>{return Q=!0,W[Number(X)-1]??""}),!Q&&Z.trim().length>0)return`${Y}
169
-
170
- ${Z.trim()}`;return Y}function _Q($,Z){let{meta:W,body:Q}=pZ(Z),Y=typeof W.description==="string"?W.description:`Run the ${$} command`,G=typeof W.model==="string"?W.model:void 0,X=W["allowed-tools"],J=Array.isArray(X)?X:typeof X==="string"&&X.length>0?X.split(",").map((K)=>K.trim()):void 0;return{name:$,description:Y,body:Q,...G?{model:G}:{},...J?{allowedTools:J}:{}}}async function bQ($){let Z;try{Z=await BH($)}catch{return[]}let W=[];for(let Q of Z.filter((Y)=>Y.endsWith(".md")).sort())try{let Y=await HH(t6($,Q),"utf8");W.push(_Q(VH(Q,".md"),Y))}catch{}return W}async function FH($={}){let Z=await bQ($.userDir??t6(zH(),".mu","commands")),W=$.projectDir?await bQ(t6($.projectDir,".mu","commands")):[],Q=new Map;for(let Y of[...Z,...W])Q.set(Y.name,Y);return[...Q.values()]}function DH($,Z){return{name:$.name,description:$.description,run:async(W)=>{let Q={kind:"markdown-command",prompt:kQ($.body,W.args),...$.model?{model:$.model}:{},...$.allowedTools?{allowedTools:$.allowedTools}:{}};if(Z)return await Z(Q.prompt,{...Q.model?{model:Q.model}:{},...Q.allowedTools?{allowedTools:Q.allowedTools}:{}}),{handled:!0};return{handled:!0,data:Q}}}}import{readFile as oN}from"fs/promises";import{homedir as sN}from"os";import{dirname as eN,isAbsolute as $M,join as bJ,resolve as ZM}from"path";import*as LH from"zod/v3";import*as cZ from"zod/v4-mini";function c1($){return!!$._zod}function q0($,Z){if(c1($))return cZ.safeParse($,Z);return $.safeParse(Z)}function dZ($){if(!$)return;let Z;if(c1($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function xQ($){if(c1($)){let G=$._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let W=$._def;if(W){if(W.value!==void 0)return W.value;if(Array.isArray(W.values)&&W.values.length>0)return W.values[0]}let Q=$.value;if(Q!==void 0)return Q;return}import*as B from"zod/v4";var o6="2025-11-25";var fQ=[o6,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Q1="io.modelcontextprotocol/related-task",nZ="2.0",c=B.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),vQ=B.union([B.string(),B.number().int()]),gQ=B.string(),GT=B.looseObject({ttl:B.number().optional(),pollInterval:B.number().optional()}),UH=B.object({ttl:B.number().optional()}),AH=B.object({taskId:B.string()}),s6=B.looseObject({progressToken:vQ.optional(),[Q1]:AH.optional()}),B0=B.object({_meta:s6.optional()}),k$=B0.extend({task:UH.optional()}),hQ=($)=>k$.safeParse($).success,n=B.object({method:B.string(),params:B0.loose().optional()}),z0=B.object({_meta:s6.optional()}),V0=B.object({method:B.string(),params:z0.loose().optional()}),a=B.looseObject({_meta:s6.optional()}),aZ=B.union([B.string(),B.number().int()]),uQ=B.object({jsonrpc:B.literal(nZ),id:aZ,...n.shape}).strict(),e6=($)=>uQ.safeParse($).success,mQ=B.object({jsonrpc:B.literal(nZ),...V0.shape}).strict(),lQ=($)=>mQ.safeParse($).success,$8=B.object({jsonrpc:B.literal(nZ),id:aZ,result:a}).strict(),_$=($)=>$8.safeParse($).success;var E;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(E||(E={}));var Z8=B.object({jsonrpc:B.literal(nZ),id:aZ.optional(),error:B.object({code:B.number().int(),message:B.string(),data:B.unknown().optional()})}).strict();var pQ=($)=>Z8.safeParse($).success;var cQ=B.union([uQ,mQ,$8,Z8]),XT=B.union([$8,Z8]),M1=a.strict(),qH=z0.extend({requestId:aZ.optional(),reason:B.string().optional()}),rZ=V0.extend({method:B.literal("notifications/cancelled"),params:qH}),OH=B.object({src:B.string(),mimeType:B.string().optional(),sizes:B.array(B.string()).optional(),theme:B.enum(["light","dark"]).optional()}),x$=B.object({icons:B.array(OH).optional()}),d1=B.object({name:B.string(),title:B.string().optional()}),dQ=d1.extend({...d1.shape,...x$.shape,version:B.string(),websiteUrl:B.string().optional(),description:B.string().optional()}),NH=B.intersection(B.object({applyDefaults:B.boolean().optional()}),B.record(B.string(),B.unknown())),MH=B.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},B.intersection(B.object({form:NH.optional(),url:c.optional()}),B.record(B.string(),B.unknown()).optional())),jH=B.looseObject({list:c.optional(),cancel:c.optional(),requests:B.looseObject({sampling:B.looseObject({createMessage:c.optional()}).optional(),elicitation:B.looseObject({create:c.optional()}).optional()}).optional()}),PH=B.looseObject({list:c.optional(),cancel:c.optional(),requests:B.looseObject({tools:B.looseObject({call:c.optional()}).optional()}).optional()}),wH=B.object({experimental:B.record(B.string(),c).optional(),sampling:B.object({context:c.optional(),tools:c.optional()}).optional(),elicitation:MH.optional(),roots:B.object({listChanged:B.boolean().optional()}).optional(),tasks:jH.optional(),extensions:B.record(B.string(),c).optional()}),TH=B0.extend({protocolVersion:B.string(),capabilities:wH,clientInfo:dQ}),IH=n.extend({method:B.literal("initialize"),params:TH});var EH=B.object({experimental:B.record(B.string(),c).optional(),logging:c.optional(),completions:c.optional(),prompts:B.object({listChanged:B.boolean().optional()}).optional(),resources:B.object({subscribe:B.boolean().optional(),listChanged:B.boolean().optional()}).optional(),tools:B.object({listChanged:B.boolean().optional()}).optional(),tasks:PH.optional(),extensions:B.record(B.string(),c).optional()}),W8=a.extend({protocolVersion:B.string(),capabilities:EH,serverInfo:dQ,instructions:B.string().optional()}),RH=V0.extend({method:B.literal("notifications/initialized"),params:z0.optional()});var tZ=n.extend({method:B.literal("ping"),params:B0.optional()}),SH=B.object({progress:B.number(),total:B.optional(B.number()),message:B.optional(B.string())}),CH=B.object({...z0.shape,...SH.shape,progressToken:vQ}),oZ=V0.extend({method:B.literal("notifications/progress"),params:CH}),yH=B0.extend({cursor:gQ.optional()}),f$=n.extend({params:yH.optional()}),v$=a.extend({nextCursor:gQ.optional()}),bH=B.enum(["working","input_required","completed","failed","cancelled"]),g$=B.object({taskId:B.string(),status:bH,ttl:B.union([B.number(),B.null()]),createdAt:B.string(),lastUpdatedAt:B.string(),pollInterval:B.optional(B.number()),statusMessage:B.optional(B.string())}),j1=a.extend({task:g$}),kH=z0.merge(g$),h$=V0.extend({method:B.literal("notifications/tasks/status"),params:kH}),sZ=n.extend({method:B.literal("tasks/get"),params:B0.extend({taskId:B.string()})}),eZ=a.merge(g$),$5=n.extend({method:B.literal("tasks/result"),params:B0.extend({taskId:B.string()})}),JT=a.loose(),Z5=f$.extend({method:B.literal("tasks/list")}),W5=v$.extend({tasks:B.array(g$)}),Q5=n.extend({method:B.literal("tasks/cancel"),params:B0.extend({taskId:B.string()})}),iQ=a.merge(g$),nQ=B.object({uri:B.string(),mimeType:B.optional(B.string()),_meta:B.record(B.string(),B.unknown()).optional()}),aQ=nQ.extend({text:B.string()}),Q8=B.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),rQ=nQ.extend({blob:Q8}),u$=B.enum(["user","assistant"]),i1=B.object({audience:B.array(u$).optional(),priority:B.number().min(0).max(1).optional(),lastModified:B.iso.datetime({offset:!0}).optional()}),tQ=B.object({...d1.shape,...x$.shape,uri:B.string(),description:B.optional(B.string()),mimeType:B.optional(B.string()),size:B.optional(B.number()),annotations:i1.optional(),_meta:B.optional(B.looseObject({}))}),_H=B.object({...d1.shape,...x$.shape,uriTemplate:B.string(),description:B.optional(B.string()),mimeType:B.optional(B.string()),annotations:i1.optional(),_meta:B.optional(B.looseObject({}))}),xH=f$.extend({method:B.literal("resources/list")}),Y8=v$.extend({resources:B.array(tQ)}),fH=f$.extend({method:B.literal("resources/templates/list")}),G8=v$.extend({resourceTemplates:B.array(_H)}),X8=B0.extend({uri:B.string()}),vH=X8,gH=n.extend({method:B.literal("resources/read"),params:vH}),J8=a.extend({contents:B.array(B.union([aQ,rQ]))}),K8=V0.extend({method:B.literal("notifications/resources/list_changed"),params:z0.optional()}),hH=X8,uH=n.extend({method:B.literal("resources/subscribe"),params:hH}),mH=X8,lH=n.extend({method:B.literal("resources/unsubscribe"),params:mH}),pH=z0.extend({uri:B.string()}),cH=V0.extend({method:B.literal("notifications/resources/updated"),params:pH}),dH=B.object({name:B.string(),description:B.optional(B.string()),required:B.optional(B.boolean())}),iH=B.object({...d1.shape,...x$.shape,description:B.optional(B.string()),arguments:B.optional(B.array(dH)),_meta:B.optional(B.looseObject({}))}),nH=f$.extend({method:B.literal("prompts/list")}),B8=v$.extend({prompts:B.array(iH)}),aH=B0.extend({name:B.string(),arguments:B.record(B.string(),B.string()).optional()}),rH=n.extend({method:B.literal("prompts/get"),params:aH}),H8=B.object({type:B.literal("text"),text:B.string(),annotations:i1.optional(),_meta:B.record(B.string(),B.unknown()).optional()}),z8=B.object({type:B.literal("image"),data:Q8,mimeType:B.string(),annotations:i1.optional(),_meta:B.record(B.string(),B.unknown()).optional()}),V8=B.object({type:B.literal("audio"),data:Q8,mimeType:B.string(),annotations:i1.optional(),_meta:B.record(B.string(),B.unknown()).optional()}),tH=B.object({type:B.literal("tool_use"),name:B.string(),id:B.string(),input:B.record(B.string(),B.unknown()),_meta:B.record(B.string(),B.unknown()).optional()}),oH=B.object({type:B.literal("resource"),resource:B.union([aQ,rQ]),annotations:i1.optional(),_meta:B.record(B.string(),B.unknown()).optional()}),sH=tQ.extend({type:B.literal("resource_link")}),F8=B.union([H8,z8,V8,sH,oH]),eH=B.object({role:u$,content:F8}),D8=a.extend({description:B.string().optional(),messages:B.array(eH)}),L8=V0.extend({method:B.literal("notifications/prompts/list_changed"),params:z0.optional()}),$z=B.object({title:B.string().optional(),readOnlyHint:B.boolean().optional(),destructiveHint:B.boolean().optional(),idempotentHint:B.boolean().optional(),openWorldHint:B.boolean().optional()}),Zz=B.object({taskSupport:B.enum(["required","optional","forbidden"]).optional()}),oQ=B.object({...d1.shape,...x$.shape,description:B.string().optional(),inputSchema:B.object({type:B.literal("object"),properties:B.record(B.string(),c).optional(),required:B.array(B.string()).optional()}).catchall(B.unknown()),outputSchema:B.object({type:B.literal("object"),properties:B.record(B.string(),c).optional(),required:B.array(B.string()).optional()}).catchall(B.unknown()).optional(),annotations:$z.optional(),execution:Zz.optional(),_meta:B.record(B.string(),B.unknown()).optional()}),Wz=f$.extend({method:B.literal("tools/list")}),U8=v$.extend({tools:B.array(oQ)}),n1=a.extend({content:B.array(F8).default([]),structuredContent:B.record(B.string(),B.unknown()).optional(),isError:B.boolean().optional()}),KT=n1.or(a.extend({toolResult:B.unknown()})),Qz=k$.extend({name:B.string(),arguments:B.record(B.string(),B.unknown()).optional()}),Yz=n.extend({method:B.literal("tools/call"),params:Qz}),A8=V0.extend({method:B.literal("notifications/tools/list_changed"),params:z0.optional()}),sQ=B.object({autoRefresh:B.boolean().default(!0),debounceMs:B.number().int().nonnegative().default(300)}),eQ=B.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Gz=B0.extend({level:eQ}),Xz=n.extend({method:B.literal("logging/setLevel"),params:Gz}),Jz=z0.extend({level:eQ,logger:B.string().optional(),data:B.unknown()}),Kz=V0.extend({method:B.literal("notifications/message"),params:Jz}),Bz=B.object({name:B.string().optional()}),Hz=B.object({hints:B.array(Bz).optional(),costPriority:B.number().min(0).max(1).optional(),speedPriority:B.number().min(0).max(1).optional(),intelligencePriority:B.number().min(0).max(1).optional()}),zz=B.object({mode:B.enum(["auto","required","none"]).optional()}),Vz=B.object({type:B.literal("tool_result"),toolUseId:B.string().describe("The unique identifier for the corresponding tool call."),content:B.array(F8).default([]),structuredContent:B.object({}).loose().optional(),isError:B.boolean().optional(),_meta:B.record(B.string(),B.unknown()).optional()}),Fz=B.discriminatedUnion("type",[H8,z8,V8]),iZ=B.discriminatedUnion("type",[H8,z8,V8,tH,Vz]),Dz=B.object({role:u$,content:B.union([iZ,B.array(iZ)]),_meta:B.record(B.string(),B.unknown()).optional()}),Lz=k$.extend({messages:B.array(Dz),modelPreferences:Hz.optional(),systemPrompt:B.string().optional(),includeContext:B.enum(["none","thisServer","allServers"]).optional(),temperature:B.number().optional(),maxTokens:B.number().int(),stopSequences:B.array(B.string()).optional(),metadata:c.optional(),tools:B.array(oQ).optional(),toolChoice:zz.optional()}),q8=n.extend({method:B.literal("sampling/createMessage"),params:Lz}),O8=a.extend({model:B.string(),stopReason:B.optional(B.enum(["endTurn","stopSequence","maxTokens"]).or(B.string())),role:u$,content:Fz}),N8=a.extend({model:B.string(),stopReason:B.optional(B.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(B.string())),role:u$,content:B.union([iZ,B.array(iZ)])}),Uz=B.object({type:B.literal("boolean"),title:B.string().optional(),description:B.string().optional(),default:B.boolean().optional()}),Az=B.object({type:B.literal("string"),title:B.string().optional(),description:B.string().optional(),minLength:B.number().optional(),maxLength:B.number().optional(),format:B.enum(["email","uri","date","date-time"]).optional(),default:B.string().optional()}),qz=B.object({type:B.enum(["number","integer"]),title:B.string().optional(),description:B.string().optional(),minimum:B.number().optional(),maximum:B.number().optional(),default:B.number().optional()}),Oz=B.object({type:B.literal("string"),title:B.string().optional(),description:B.string().optional(),enum:B.array(B.string()),default:B.string().optional()}),Nz=B.object({type:B.literal("string"),title:B.string().optional(),description:B.string().optional(),oneOf:B.array(B.object({const:B.string(),title:B.string()})),default:B.string().optional()}),Mz=B.object({type:B.literal("string"),title:B.string().optional(),description:B.string().optional(),enum:B.array(B.string()),enumNames:B.array(B.string()).optional(),default:B.string().optional()}),jz=B.union([Oz,Nz]),Pz=B.object({type:B.literal("array"),title:B.string().optional(),description:B.string().optional(),minItems:B.number().optional(),maxItems:B.number().optional(),items:B.object({type:B.literal("string"),enum:B.array(B.string())}),default:B.array(B.string()).optional()}),wz=B.object({type:B.literal("array"),title:B.string().optional(),description:B.string().optional(),minItems:B.number().optional(),maxItems:B.number().optional(),items:B.object({anyOf:B.array(B.object({const:B.string(),title:B.string()}))}),default:B.array(B.string()).optional()}),Tz=B.union([Pz,wz]),Iz=B.union([Mz,jz,Tz]),Ez=B.union([Iz,Uz,Az,qz]),Rz=k$.extend({mode:B.literal("form").optional(),message:B.string(),requestedSchema:B.object({type:B.literal("object"),properties:B.record(B.string(),Ez),required:B.array(B.string()).optional()})}),Sz=k$.extend({mode:B.literal("url"),message:B.string(),elicitationId:B.string(),url:B.string().url()}),Cz=B.union([Rz,Sz]),M8=n.extend({method:B.literal("elicitation/create"),params:Cz}),yz=z0.extend({elicitationId:B.string()}),bz=V0.extend({method:B.literal("notifications/elicitation/complete"),params:yz}),j8=a.extend({action:B.enum(["accept","decline","cancel"]),content:B.preprocess(($)=>$===null?void 0:$,B.record(B.string(),B.union([B.string(),B.number(),B.boolean(),B.array(B.string())])).optional())}),kz=B.object({type:B.literal("ref/resource"),uri:B.string()});var _z=B.object({type:B.literal("ref/prompt"),name:B.string()}),xz=B0.extend({ref:B.union([_z,kz]),argument:B.object({name:B.string(),value:B.string()}),context:B.object({arguments:B.record(B.string(),B.string()).optional()}).optional()}),fz=n.extend({method:B.literal("completion/complete"),params:xz});var P8=a.extend({completion:B.looseObject({values:B.array(B.string()).max(100),total:B.optional(B.number().int()),hasMore:B.optional(B.boolean())})}),vz=B.object({uri:B.string().startsWith("file://"),name:B.string().optional(),_meta:B.record(B.string(),B.unknown()).optional()}),gz=n.extend({method:B.literal("roots/list"),params:B0.optional()}),hz=a.extend({roots:B.array(vz)}),uz=V0.extend({method:B.literal("notifications/roots/list_changed"),params:z0.optional()}),BT=B.union([tZ,IH,fz,Xz,rH,nH,xH,fH,gH,uH,lH,Yz,Wz,sZ,$5,Z5,Q5]),HT=B.union([rZ,oZ,RH,uz,h$]),zT=B.union([M1,O8,N8,j8,hz,eZ,W5,j1]),VT=B.union([tZ,q8,M8,gz,sZ,$5,Z5,Q5]),FT=B.union([rZ,oZ,Kz,cH,K8,A8,L8,h$,bz]),DT=B.union([M1,W8,P8,D8,B8,Y8,G8,J8,n1,U8,eZ,W5,j1]);class I extends Error{constructor($,Z,W){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=W,this.name="McpError"}static fromError($,Z,W){if($===E.UrlElicitationRequired&&W){let Q=W;if(Q.elicitations)return new $9(Q.elicitations,Z)}return new I($,Z,W)}}class $9 extends I{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(E.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function Y1($){return $==="completed"||$==="failed"||$==="cancelled"}import*as nz from"zod/v4-mini";var mz=Symbol("Let zodToJsonSchema decide on which parser to use");import{ZodFirstPartyTypeKind as DE}from"zod/v3";import{ZodFirstPartyTypeKind as IT}from"zod/v3";import{ZodFirstPartyTypeKind as sT}from"zod/v3";var rT=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function w8($){let W=dZ($)?.method;if(!W)throw Error("Schema is missing a method literal");let Q=xQ(W);if(typeof Q!=="string")throw Error("Schema method literal must be a string");return Q}function T8($,Z){let W=q0($,Z);if(!W.success)throw W.error;return W.data}var az=60000;class I8{constructor($){if(this._options=$,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(rZ,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(oZ,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(tZ,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(sZ,async(Z,W)=>{let Q=await this._taskStore.getTask(Z.params.taskId,W.sessionId);if(!Q)throw new I(E.InvalidParams,"Failed to retrieve task: Task not found");return{...Q}}),this.setRequestHandler($5,async(Z,W)=>{let Q=async()=>{let Y=Z.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Y,W.sessionId)){if(X.type==="response"||X.type==="error"){let J=X.message,K=J.id,H=this._requestResolvers.get(K);if(H)if(this._requestResolvers.delete(K),X.type==="response")H(J);else{let V=J,z=new I(V.error.code,V.error.message,V.error.data);H(z)}else{let V=X.type==="response"?"Response":"Error";this._onerror(Error(`${V} handler missing for request ${K}`))}continue}await this._transport?.send(X.message,{relatedRequestId:W.requestId})}}let G=await this._taskStore.getTask(Y,W.sessionId);if(!G)throw new I(E.InvalidParams,`Task not found: ${Y}`);if(!Y1(G.status))return await this._waitForTaskUpdate(Y,W.signal),await Q();if(Y1(G.status)){let X=await this._taskStore.getTaskResult(Y,W.sessionId);return this._clearTaskQueue(Y),{...X,_meta:{...X._meta,[Q1]:{taskId:Y}}}}return await Q()};return await Q()}),this.setRequestHandler(Z5,async(Z,W)=>{try{let{tasks:Q,nextCursor:Y}=await this._taskStore.listTasks(Z.params?.cursor,W.sessionId);return{tasks:Q,nextCursor:Y,_meta:{}}}catch(Q){throw new I(E.InvalidParams,`Failed to list tasks: ${Q instanceof Error?Q.message:String(Q)}`)}}),this.setRequestHandler(Q5,async(Z,W)=>{try{let Q=await this._taskStore.getTask(Z.params.taskId,W.sessionId);if(!Q)throw new I(E.InvalidParams,`Task not found: ${Z.params.taskId}`);if(Y1(Q.status))throw new I(E.InvalidParams,`Cannot cancel task in terminal status: ${Q.status}`);await this._taskStore.updateTaskStatus(Z.params.taskId,"cancelled","Client cancelled task execution.",W.sessionId),this._clearTaskQueue(Z.params.taskId);let Y=await this._taskStore.getTask(Z.params.taskId,W.sessionId);if(!Y)throw new I(E.InvalidParams,`Task not found after cancellation: ${Z.params.taskId}`);return{_meta:{},...Y}}catch(Q){if(Q instanceof I)throw Q;throw new I(E.InvalidRequest,`Failed to cancel task: ${Q instanceof Error?Q.message:String(Q)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,W,Q,Y=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Q,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:W,resetTimeoutOnProgress:Y,onTimeout:Q})}_resetTimeout($){let Z=this._timeoutInfo.get($);if(!Z)return!1;let W=Date.now()-Z.startTime;if(Z.maxTotalTimeout&&W>=Z.maxTotalTimeout)throw this._timeoutInfo.delete($),I.fromError(E.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Z.maxTotalTimeout,totalElapsed:W});return clearTimeout(Z.timeoutId),Z.timeoutId=setTimeout(Z.onTimeout,Z.timeout),!0}_cleanupTimeout($){let Z=this._timeoutInfo.get($);if(Z)clearTimeout(Z.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let Z=this.transport?.onclose;this._transport.onclose=()=>{Z?.(),this._onclose()};let W=this.transport?.onerror;this._transport.onerror=(Y)=>{W?.(Y),this._onerror(Y)};let Q=this._transport?.onmessage;this._transport.onmessage=(Y,G)=>{if(Q?.(Y,G),_$(Y)||pQ(Y))this._onresponse(Y);else if(e6(Y))this._onrequest(Y,G);else if(lQ(Y))this._onnotification(Y);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Y)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let W of this._timeoutInfo.values())clearTimeout(W.timeoutId);this._timeoutInfo.clear();for(let W of this._requestHandlerAbortControllers.values())W.abort();this._requestHandlerAbortControllers.clear();let Z=I.fromError(E.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let W of $.values())W(Z)}_onerror($){this.onerror?.($)}_onnotification($){let Z=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z($)).catch((W)=>this._onerror(Error(`Uncaught error in notification handler: ${W}`)))}_onrequest($,Z){let W=this._requestHandlers.get($.method)??this.fallbackRequestHandler,Q=this._transport,Y=$.params?._meta?.[Q1]?.taskId;if(W===void 0){let H={jsonrpc:"2.0",id:$.id,error:{code:E.MethodNotFound,message:"Method not found"}};if(Y&&this._taskMessageQueue)this._enqueueTaskMessage(Y,{type:"error",message:H,timestamp:Date.now()},Q?.sessionId).catch((V)=>this._onerror(Error(`Failed to enqueue error response: ${V}`)));else Q?.send(H).catch((V)=>this._onerror(Error(`Failed to send an error response: ${V}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let X=hQ($.params)?$.params.task:void 0,J=this._taskStore?this.requestTaskStore($,Q?.sessionId):void 0,K={signal:G.signal,sessionId:Q?.sessionId,_meta:$.params?._meta,sendNotification:async(H)=>{if(G.signal.aborted)return;let V={relatedRequestId:$.id};if(Y)V.relatedTask={taskId:Y};await this.notification(H,V)},sendRequest:async(H,V,z)=>{if(G.signal.aborted)throw new I(E.ConnectionClosed,"Request was cancelled");let F={...z,relatedRequestId:$.id};if(Y&&!F.relatedTask)F.relatedTask={taskId:Y};let D=F.relatedTask?.taskId??Y;if(D&&J)await J.updateTaskStatus(D,"input_required");return await this.request(H,V,F)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:Y,taskStore:J,taskRequestedTtl:X?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability($.method)}).then(()=>W($,K)).then(async(H)=>{if(G.signal.aborted)return;let V={result:H,jsonrpc:"2.0",id:$.id};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"response",message:V,timestamp:Date.now()},Q?.sessionId);else await Q?.send(V)},async(H)=>{if(G.signal.aborted)return;let V={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(H.code)?H.code:E.InternalError,message:H.message??"Internal error",...H.data!==void 0&&{data:H.data}}};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"error",message:V,timestamp:Date.now()},Q?.sessionId);else await Q?.send(V)}).catch((H)=>this._onerror(Error(`Failed to send response: ${H}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...W}=$.params,Q=Number(Z),Y=this._progressHandlers.get(Q);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(Q),X=this._timeoutInfo.get(Q);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(Q)}catch(J){this._responseHandlers.delete(Q),this._progressHandlers.delete(Q),this._cleanupTimeout(Q),G(J);return}Y(W)}_onresponse($){let Z=Number($.id),W=this._requestResolvers.get(Z);if(W){if(this._requestResolvers.delete(Z),_$($))W($);else{let G=new I($.error.code,$.error.message,$.error.data);W(G)}return}let Q=this._responseHandlers.get(Z);if(Q===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(Z),this._cleanupTimeout(Z);let Y=!1;if(_$($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Y=!0,this._taskProgressTokens.set(X.taskId,Z)}}if(!Y)this._progressHandlers.delete(Z);if(_$($))Q($);else{let G=I.fromError($.error.code,$.error.message,$.error.data);Q(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,W){let{task:Q}=W??{};if(!Q){try{yield{type:"result",result:await this.request($,Z,W)}}catch(G){yield{type:"error",error:G instanceof I?G:new I(E.InternalError,String(G))}}return}let Y;try{let G=await this.request($,j1,W);if(G.task)Y=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new I(E.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Y},W);if(yield{type:"taskStatus",task:X},Y1(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Y},Z,W)};else if(X.status==="failed")yield{type:"error",error:new I(E.InternalError,`Task ${Y} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new I(E.InternalError,`Task ${Y} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Y},Z,W)};return}let J=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((K)=>setTimeout(K,J)),W?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof I?G:new I(E.InternalError,String(G))}}}request($,Z,W){let{relatedRequestId:Q,resumptionToken:Y,onresumptiontoken:G,task:X,relatedTask:J}=W??{};return new Promise((K,H)=>{let V=(q)=>{H(q)};if(!this._transport){V(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),X)this.assertTaskCapability($.method)}catch(q){V(q);return}W?.signal?.throwIfAborted();let z=this._requestMessageId++,F={...$,jsonrpc:"2.0",id:z};if(W?.onprogress)this._progressHandlers.set(z,W.onprogress),F.params={...$.params,_meta:{...$.params?._meta||{},progressToken:z}};if(X)F.params={...F.params,task:X};if(J)F.params={...F.params,_meta:{...F.params?._meta||{},[Q1]:J}};let D=(q)=>{this._responseHandlers.delete(z),this._progressHandlers.delete(z),this._cleanupTimeout(z),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:z,reason:String(q)}},{relatedRequestId:Q,resumptionToken:Y,onresumptiontoken:G}).catch((j)=>this._onerror(Error(`Failed to send cancellation: ${j}`)));let O=q instanceof I?q:new I(E.RequestTimeout,String(q));H(O)};this._responseHandlers.set(z,(q)=>{if(W?.signal?.aborted)return;if(q instanceof Error)return H(q);try{let O=q0(Z,q.result);if(!O.success)H(O.error);else K(O.data)}catch(O){H(O)}}),W?.signal?.addEventListener("abort",()=>{D(W?.signal?.reason)});let L=W?.timeout??az,U=()=>D(I.fromError(E.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(z,L,W?.maxTotalTimeout,U,W?.resetTimeoutOnProgress??!1);let A=J?.taskId;if(A){let q=(O)=>{let j=this._responseHandlers.get(z);if(j)j(O);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,q),this._enqueueTaskMessage(A,{type:"request",message:F,timestamp:Date.now()}).catch((O)=>{this._cleanupTimeout(z),H(O)})}else this._transport.send(F,{relatedRequestId:Q,resumptionToken:Y,onresumptiontoken:G}).catch((q)=>{this._cleanupTimeout(z),H(q)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},eZ,Z)}async getTaskResult($,Z,W){return this.request({method:"tasks/result",params:$},Z,W)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},W5,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},iQ,Z)}async notification($,Z){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let W=Z?.relatedTask?.taskId;if(W){let X={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[Q1]:Z.relatedTask}}};await this._enqueueTaskMessage(W,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!Z?.relatedRequestId&&!Z?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let X={...$,jsonrpc:"2.0"};if(Z?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[Q1]:Z.relatedTask}}};this._transport?.send(X,Z).catch((J)=>this._onerror(J))});return}let G={...$,jsonrpc:"2.0"};if(Z?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[Q1]:Z.relatedTask}}};await this._transport.send(G,Z)}setRequestHandler($,Z){let W=w8($);this.assertRequestHandlerCapability(W),this._requestHandlers.set(W,(Q,Y)=>{let G=T8($,Q);return Promise.resolve(Z(G,Y))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,Z){let W=w8($);this._notificationHandlers.set(W,(Q)=>{let Y=T8($,Q);return Promise.resolve(Z(Y))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let Z=this._taskProgressTokens.get($);if(Z!==void 0)this._progressHandlers.delete(Z),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,Z,W){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let Q=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,W,Q)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let W=await this._taskMessageQueue.dequeueAll($,Z);for(let Q of W)if(Q.type==="request"&&e6(Q.message)){let Y=Q.message.id,G=this._requestResolvers.get(Y);if(G)G(new I(E.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Y);else this._onerror(Error(`Resolver missing for request ${Y} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,Z){let W=this._options?.defaultTaskPollInterval??1000;try{let Q=await this._taskStore?.getTask($);if(Q?.pollInterval)W=Q.pollInterval}catch{}return new Promise((Q,Y)=>{if(Z.aborted){Y(new I(E.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Q,W);Z.addEventListener("abort",()=>{clearTimeout(G),Y(new I(E.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,Z){let W=this._taskStore;if(!W)throw Error("No task store configured");return{createTask:async(Q)=>{if(!$)throw Error("No request provided");return await W.createTask(Q,$.id,{method:$.method,params:$.params},Z)},getTask:async(Q)=>{let Y=await W.getTask(Q,Z);if(!Y)throw new I(E.InvalidParams,"Failed to retrieve task: Task not found");return Y},storeTaskResult:async(Q,Y,G)=>{await W.storeTaskResult(Q,Y,G,Z);let X=await W.getTask(Q,Z);if(X){let J=h$.parse({method:"notifications/tasks/status",params:X});if(await this.notification(J),Y1(X.status))this._cleanupTaskProgressHandler(Q)}},getTaskResult:(Q)=>{return W.getTaskResult(Q,Z)},updateTaskStatus:async(Q,Y,G)=>{let X=await W.getTask(Q,Z);if(!X)throw new I(E.InvalidParams,`Task "${Q}" not found - it may have been cleaned up`);if(Y1(X.status))throw new I(E.InvalidParams,`Cannot update task "${Q}" from terminal status "${X.status}" to "${Y}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await W.updateTaskStatus(Q,Y,G,Z);let J=await W.getTask(Q,Z);if(J){let K=h$.parse({method:"notifications/tasks/status",params:J});if(await this.notification(K),Y1(J.status))this._cleanupTaskProgressHandler(Q)}},listTasks:(Q)=>{return W.listTasks(Q,Z)}}}}function Z9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function W9($,Z){let W={...$};for(let Q in Z){let Y=Q,G=Z[Y];if(G===void 0)continue;let X=W[Y];if(Z9(X)&&Z9(G))W[Y]={...X,...G};else W[Y]=G}return W}var gX=a5(MW(),1),hX=a5(vX(),1);function AN(){let $=new gX.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return hX.default($),$}class yW{constructor($){this._ajv=$??AN()}getValidator($){let Z="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(W)=>{if(Z(W))return{valid:!0,data:W,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Z.errors)}}}}class bW{constructor($){this._client=$}async*callToolStream($,Z=n1,W){let Q=this._client,Y={...W,task:W?.task??(Q.isToolTask($.name)?{}:void 0)},G=Q.requestStream({method:"tools/call",params:$},Z,Y),X=Q.getToolOutputValidator($.name);for await(let J of G){if(J.type==="result"&&X){let K=J.result;if(!K.structuredContent&&!K.isError){yield{type:"error",error:new I(E.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`)};return}if(K.structuredContent)try{let H=X(K.structuredContent);if(!H.valid){yield{type:"error",error:new I(E.InvalidParams,`Structured content does not match the tool's output schema: ${H.errorMessage}`)};return}}catch(H){if(H instanceof I){yield{type:"error",error:H};return}yield{type:"error",error:new I(E.InvalidParams,`Failed to validate structured content: ${H instanceof Error?H.message:String(H)}`)};return}}yield J}}async getTask($,Z){return this._client.getTask({taskId:$},Z)}async getTaskResult($,Z,W){return this._client.getTaskResult({taskId:$},Z,W)}async listTasks($,Z){return this._client.listTasks($?{cursor:$}:void 0,Z)}async cancelTask($,Z){return this._client.cancelTask({taskId:$},Z)}requestStream($,Z,W){return this._client.requestStream($,Z,W)}}function uX($,Z,W){if(!$)throw Error(`${W} does not support task creation (required for ${Z})`);switch(Z){case"tools/call":if(!$.tools?.call)throw Error(`${W} does not support task creation for tools/call (required for ${Z})`);break;default:break}}function mX($,Z,W){if(!$)throw Error(`${W} does not support task creation (required for ${Z})`);switch(Z){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${W} does not support task creation for sampling/createMessage (required for ${Z})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${W} does not support task creation for elicitation/create (required for ${Z})`);break;default:break}}function u5($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let W=Z,Q=$.properties;for(let Y of Object.keys(Q)){let G=Q[Y];if(W[Y]===void 0&&Object.prototype.hasOwnProperty.call(G,"default"))W[Y]=G.default;if(W[Y]!==void 0)u5(G,W[Y])}}if(Array.isArray($.anyOf)){for(let W of $.anyOf)if(typeof W!=="boolean")u5(W,Z)}if(Array.isArray($.oneOf)){for(let W of $.oneOf)if(typeof W!=="boolean")u5(W,Z)}}function qN($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,W=$.url!==void 0;return{supportsFormMode:Z||!Z&&!W,supportsUrlMode:W}}class kW extends I8{constructor($,Z){super(Z);if(this._clientInfo=$,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=Z?.capabilities??{},this._jsonSchemaValidator=Z?.jsonSchemaValidator??new yW,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",A8,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",L8,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",K8,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new bW(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=W9(this._capabilities,$)}setRequestHandler($,Z){let Q=dZ($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y;if(c1(Q)){let X=Q;Y=X._zod?.def?.value??X.value}else{let X=Q;Y=X._def?.value??X.value}if(typeof Y!=="string")throw Error("Schema method literal must be a string");let G=Y;if(G==="elicitation/create"){let X=async(J,K)=>{let H=q0(M8,J);if(!H.success){let q=H.error instanceof Error?H.error.message:String(H.error);throw new I(E.InvalidParams,`Invalid elicitation request: ${q}`)}let{params:V}=H.data;V.mode=V.mode??"form";let{supportsFormMode:z,supportsUrlMode:F}=qN(this._capabilities.elicitation);if(V.mode==="form"&&!z)throw new I(E.InvalidParams,"Client does not support form-mode elicitation requests");if(V.mode==="url"&&!F)throw new I(E.InvalidParams,"Client does not support URL-mode elicitation requests");let D=await Promise.resolve(Z(J,K));if(V.task){let q=q0(j1,D);if(!q.success){let O=q.error instanceof Error?q.error.message:String(q.error);throw new I(E.InvalidParams,`Invalid task creation result: ${O}`)}return q.data}let L=q0(j8,D);if(!L.success){let q=L.error instanceof Error?L.error.message:String(L.error);throw new I(E.InvalidParams,`Invalid elicitation result: ${q}`)}let U=L.data,A=V.mode==="form"?V.requestedSchema:void 0;if(V.mode==="form"&&U.action==="accept"&&U.content&&A){if(this._capabilities.elicitation?.form?.applyDefaults)try{u5(A,U.content)}catch{}}return U};return super.setRequestHandler($,X)}if(G==="sampling/createMessage"){let X=async(J,K)=>{let H=q0(q8,J);if(!H.success){let U=H.error instanceof Error?H.error.message:String(H.error);throw new I(E.InvalidParams,`Invalid sampling request: ${U}`)}let{params:V}=H.data,z=await Promise.resolve(Z(J,K));if(V.task){let U=q0(j1,z);if(!U.success){let A=U.error instanceof Error?U.error.message:String(U.error);throw new I(E.InvalidParams,`Invalid task creation result: ${A}`)}return U.data}let D=V.tools||V.toolChoice?N8:O8,L=q0(D,z);if(!L.success){let U=L.error instanceof Error?L.error.message:String(L.error);throw new I(E.InvalidParams,`Invalid sampling result: ${U}`)}return L.data};return super.setRequestHandler($,X)}return super.setRequestHandler($,Z)}assertCapability($,Z){if(!this._serverCapabilities?.[$])throw Error(`Server does not support ${$} (required for ${Z})`)}async connect($,Z){if(await super.connect($),$.sessionId!==void 0)return;try{let W=await this.request({method:"initialize",params:{protocolVersion:o6,capabilities:this._capabilities,clientInfo:this._clientInfo}},W8,Z);if(W===void 0)throw Error(`Server sent invalid initialize result: ${W}`);if(!fQ.includes(W.protocolVersion))throw Error(`Server's protocol version is not supported: ${W.protocolVersion}`);if(this._serverCapabilities=W.capabilities,this._serverVersion=W.serverInfo,$.setProtocolVersion)$.setProtocolVersion(W.protocolVersion);if(this._instructions=W.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(W){throw this.close(),W}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod($){switch($){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${$})`);if($==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${$})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${$})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${$})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${$})`);break;case"ping":break}}assertTaskCapability($){uX(this._serverCapabilities?.tasks?.requests,$,"Server")}assertTaskHandlerCapability($){if(!this._capabilities)return;mX(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},M1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},P8,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},M1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},D8,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},B8,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},Y8,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},G8,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},J8,Z)}async subscribeResource($,Z){return this.request({method:"resources/subscribe",params:$},M1,Z)}async unsubscribeResource($,Z){return this.request({method:"resources/unsubscribe",params:$},M1,Z)}async callTool($,Z=n1,W){if(this.isToolTaskRequired($.name))throw new I(E.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let Q=await this.request({method:"tools/call",params:$},Z,W),Y=this.getToolOutputValidator($.name);if(Y){if(!Q.structuredContent&&!Q.isError)throw new I(E.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(Q.structuredContent)try{let G=Y(Q.structuredContent);if(!G.valid)throw new I(E.InvalidParams,`Structured content does not match the tool's output schema: ${G.errorMessage}`)}catch(G){if(G instanceof I)throw G;throw new I(E.InvalidParams,`Failed to validate structured content: ${G instanceof Error?G.message:String(G)}`)}}return Q}isToolTask($){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has($)}isToolTaskRequired($){return this._cachedRequiredTaskTools.has($)}cacheToolMetadata($){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let Z of $){if(Z.outputSchema){let Q=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,Q)}let W=Z.execution?.taskSupport;if(W==="required"||W==="optional")this._cachedKnownTaskTools.add(Z.name);if(W==="required")this._cachedRequiredTaskTools.add(Z.name)}}getToolOutputValidator($){return this._cachedToolOutputValidators.get($)}async listTools($,Z){let W=await this.request({method:"tools/list",params:$},U8,Z);return this.cacheToolMetadata(W.tools),W}_setupListChangedHandler($,Z,W,Q){let Y=sQ.safeParse(W);if(!Y.success)throw Error(`Invalid ${$} listChanged options: ${Y.error.message}`);if(typeof W.onChanged!=="function")throw Error(`Invalid ${$} listChanged options: onChanged must be a function`);let{autoRefresh:G,debounceMs:X}=Y.data,{onChanged:J}=W,K=async()=>{if(!G){J(null,null);return}try{let V=await Q();J(null,V)}catch(V){let z=V instanceof Error?V:Error(String(V));J(z,null)}},H=()=>{if(X){let V=this._listChangedDebounceTimers.get($);if(V)clearTimeout(V);let z=setTimeout(K,X);this._listChangedDebounceTimers.set($,z)}else K()};this.setNotificationHandler(Z,H)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var yJ=a5(SJ(),1);import cW from"process";import{PassThrough as rN}from"stream";class pW{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
171
- `);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),aN(Z)}clear(){this._buffer=void 0}}function aN($){return cQ.parse(JSON.parse($))}function CJ($){return JSON.stringify($)+`
172
- `}var tN=cW.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function dW(){let $={};for(let Z of tN){let W=cW.env[Z];if(W===void 0)continue;if(W.startsWith("()"))continue;$[Z]=W}return $}class iW{constructor($){if(this._readBuffer=new pW,this._stderrStream=null,this._serverParams=$,$.stderr==="pipe"||$.stderr==="overlapped")this._stderrStream=new rN}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{if(this._process=yJ.default(this._serverParams.command,this._serverParams.args??[],{env:{...dW(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:cW.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",(W)=>{Z(W),this.onerror?.(W)}),this._process.on("spawn",()=>{$()}),this._process.on("close",(W)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(W)=>{this.onerror?.(W)}),this._process.stdout?.on("data",(W)=>{this._readBuffer.append(W),this.processReadBuffer()}),this._process.stdout?.on("error",(W)=>{this.onerror?.(W)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._process){let $=this._process;this._process=void 0;let Z=new Promise((W)=>{$.once("close",()=>{W()})});try{$.stdin?.end()}catch{}if(await Promise.race([Z,new Promise((W)=>setTimeout(W,2000).unref())]),$.exitCode===null){try{$.kill("SIGTERM")}catch{}await Promise.race([Z,new Promise((W)=>setTimeout(W,2000).unref())])}if($.exitCode===null)try{$.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send($){return new Promise((Z)=>{if(!this._process?.stdin)throw Error("Not connected");let W=CJ($);if(this._process.stdin.write(W))Z();else this._process.stdin.once("drain",Z)})}}var WM=1e4,QM=60000,kJ=50000;function C1($){if($.length<=kJ)return $;let Z=Math.floor(kJ/2);return`${$.slice(0,Z)}
188
+ `}function oZ($){return W8({provider:$,status:"success",heading:"Authentication successful",detail:`${$} authentication completed. You can close this window.`})}function E1($,Z){return W8({provider:$,status:"error",heading:"Authentication failed",detail:Z})}var G8=1,X8="app_EMoamEEZ73f0CkXaXp7hrann",sZ="OpenAI",mW="https://auth.openai.com",GH="openid profile email offline_access api.connectors.read api.connectors.invoke",XH="https://api.openai.com/auth",J1="openai-codex",J8="github-copilot",Z5={"user-agent":"GitHubCopilotChat/0.35.0","editor-version":"vscode/1.107.0","editor-plugin-version":"copilot-chat/0.35.0","copilot-integration-id":"vscode-chat"},JH="2026-06-01",KH=60000,R1=15000,BH=300000,HH=[1455,1457];function K8(){return uW(WH(),".mu","auth.json")}function VH(){return{version:G8,providers:{}}}function p$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function zH($,Z){if(!p$($))throw Error(`Invalid stored credentials for "${Z}"`);if($.type==="apiKey"&&typeof $.apiKey==="string"&&$.apiKey.length>0)return{type:"apiKey",apiKey:$.apiKey};if($.type==="oauth"&&typeof $.accessToken==="string"&&typeof $.refreshToken==="string"&&typeof $.expiresAt==="number"&&Number.isFinite($.expiresAt)){if((Z==="openai"||Z===J1)&&(typeof $.accountId!=="string"||$.accountId.length===0))throw Error(`Invalid stored credentials for "${Z}"`);return{type:"oauth",accessToken:$.accessToken,refreshToken:$.refreshToken,...typeof $.idToken==="string"?{idToken:$.idToken}:{},expiresAt:$.expiresAt,...typeof $.accountId==="string"?{accountId:$.accountId}:{},...typeof $.baseUrl==="string"?{baseUrl:$.baseUrl}:{},...Array.isArray($.availableModelIds)&&$.availableModelIds.every((Q)=>typeof Q==="string")?{availableModelIds:$.availableModelIds}:{}}}throw Error(`Invalid stored credentials for "${Z}"`)}async function n0($={}){let Z=$.authFile??K8(),Q;try{Q=await sB(Z,"utf8")}catch(X){if(X.code==="ENOENT")return VH();throw X}let W;try{W=JSON.parse(Q)}catch{throw Error(`Could not parse authentication file: ${Z}`)}if(!p$(W)||W.version!==G8||!p$(W.providers))throw Error(`Unsupported authentication file: ${Z}`);let Y={};for(let[X,J]of Object.entries(W.providers)){let K=zH(J,X),B=X==="openai"&&K.type==="oauth"?J1:X;if(B===X)Y[B]=K;else Y[B]??=K}let G=W.activeProvider==="openai"&&!Y.openai&&Y[J1]?.type==="oauth"?J1:W.activeProvider;if(process.platform!=="win32"){if(((await $H(Z)).mode&63)!==0)await Y8(Z,384)}return{version:G8,...typeof G==="string"?{activeProvider:G}:{},providers:Y}}async function c$($,Z={}){let Q=Z.authFile??K8(),W=YH(Q);if(await oB(W,{recursive:!0,mode:448}),process.platform!=="win32")await Y8(W,448);let Y=uW(W,`.auth-${process.pid}-${$5(8).toString("hex")}.tmp`);try{if(await QH(Y,`${JSON.stringify($,null,2)}
189
+ `,{encoding:"utf8",mode:384,flag:"wx"}),await eB(Y,Q),process.platform!=="win32")await Y8(Q,384)}catch(G){throw await ZH(Y).catch(()=>{}),G}}async function FH($,Z,Q={}){let W=$.trim(),Y=Z.trim();if(!W)throw Error("Provider is required");if(!Y)throw Error("API key cannot be empty");let G=await n0(Q);G.providers[W]={type:"apiKey",apiKey:Y},G.activeProvider=W,await c$(G,Q)}async function DH($,Z={}){let Q=$.trim();if(!Q)throw Error("Provider is required");let W=await n0(Z);if(!W.providers[Q])return!1;if(delete W.providers[Q],W.activeProvider===Q){let Y=Object.keys(W.providers)[0];if(Y)W.activeProvider=Y;else delete W.activeProvider}return await c$(W,Z),!0}async function LH($={}){return Object.keys((await n0($)).providers)}async function UH($={}){let Z=await n0($);return Z.activeProvider&&Z.providers[Z.activeProvider]?Z.activeProvider:Object.keys(Z.providers)[0]}async function Q5($,Z,Q){let W=await n0(Q);W.providers[$]=Z,W.activeProvider=$,await c$(W,Q)}function lW($){let Z=$.split(".")[1];if(!Z)return;try{let Q=JSON.parse(Buffer.from(Z,"base64url").toString("utf8"));return p$(Q)?Q:void 0}catch{return}}function kW($){let Z=lW($)?.[XH]?.chatgpt_account_id;return typeof Z==="string"&&Z.length>0?Z:void 0}function qH($){let Z=lW($)?.exp;return typeof Z==="number"&&Number.isFinite(Z)?Z*1000:void 0}function AH($,Z,Q){let W=Q.trim()?`: ${Q.trim().slice(0,1000)}`:"";return Error(`OpenAI token ${$} failed (${Z.status})${W}`)}async function pW($,Z){if(!$.ok)throw AH(Z,$,await $.text().catch(()=>""));let Q=await $.json();if(!p$(Q))throw Error(`OpenAI token ${Z} returned invalid JSON`);return Q}function cW($,Z,Q){let W=typeof $.access_token==="string"?$.access_token:Q?.accessToken,Y=typeof $.refresh_token==="string"?$.refresh_token:Q?.refreshToken,G=typeof $.id_token==="string"?$.id_token:Q?.idToken;if(!W||!Y)throw Error("OpenAI token response is missing access or refresh token");let X=kW(W)??(G?kW(G):void 0)??Q?.accountId;if(!X)throw Error("OpenAI token did not include a ChatGPT account");if(Q?.accountId&&X!==Q.accountId)throw Error("Refusing to rotate OpenAI credentials across ChatGPT accounts");let J=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in*1000:void 0,K=qH(W)??(J!==void 0?Z+J:Z+3600000);return{type:"oauth",accessToken:W,refreshToken:Y,...G?{idToken:G}:{},expiresAt:K,accountId:X}}async function NH($,Z){let Q=(Z.openAiIssuer??mW).replace(/\/+$/,""),W=await(Z.fetch??fetch)(`${Q}/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:Z.openAiClientId??X8,grant_type:"refresh_token",refresh_token:$.refreshToken}),signal:AbortSignal.timeout(R1)});return cW(await pW(W,"refresh"),(Z.now??Date.now)(),$)}function xW($){return{type:"oauth",accessToken:$.accessToken,...$.accountId?{accountId:$.accountId}:{},...$.baseUrl?{baseUrl:$.baseUrl}:{},...$.availableModelIds?{availableModelIds:$.availableModelIds}:{}}}function fW($,Z,Q){return Z.expiresAt>Q+KH&&($!==J8||Z.availableModelIds!==void 0)}async function K1($,Z){let Q=await $.text(),W;try{W=JSON.parse(Q)}catch{throw Error(`${Z} returned invalid JSON (${$.status})`)}if(!$.ok){let Y=typeof W==="object"&&W!==null?W:{},G=Y.error_description??Y.message??Y.error;throw Error(`${Z} failed (${$.status})${typeof G==="string"?`: ${G}`:""}`)}if(typeof W!=="object"||W===null||Array.isArray(W))throw Error(`${Z} returned invalid JSON`);return W}function vW($,Z,Q=60000){let W=typeof $.access_token==="string"?$.access_token:Z.accessToken,Y=typeof $.refresh_token==="string"?$.refresh_token:Z.refreshToken,G=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in:3600;if(!W||!Y)throw Error("OAuth response is missing tokens");return{...Z,accessToken:W,refreshToken:Y,expiresAt:Date.now()+G*1000-Q}}function dW($){let Z=$.match(/(?:^|;)proxy-ep=([^;]+)/)?.[1];return Z?`https://${Z.replace(/^proxy\./,"api.")}`:"https://api.individual.githubcopilot.com"}function OH($){if(typeof $!=="object"||$===null||!Array.isArray($.data))throw Error("GitHub Copilot models response is invalid");return $.data.filter((Z)=>typeof Z==="object"&&Z!==null&&!Array.isArray(Z))}function MH($){let Z=typeof $.policy==="object"&&$.policy!==null?$.policy:void 0,Q=typeof $.capabilities==="object"&&$.capabilities!==null?$.capabilities:void 0,W=typeof Q?.supports==="object"&&Q.supports!==null?Q.supports:void 0;return $.model_picker_enabled===!0&&Z?.state!=="disabled"&&W?.tool_calls!==!1}async function iW($,Z,Q,W){let Y=await Q(`${Z.replace(/\/+$/,"")}/models`,{headers:{accept:"application/json",authorization:`Bearer ${$}`,...Z5,"x-github-api-version":JH},...W?{signal:W}:{}});return OH(await K1(Y,"GitHub Copilot model discovery"))}async function nW($,Z,Q,W){return(await iW($,Z,Q,W)).filter(MH).map((Y)=>Y.id).filter((Y)=>typeof Y==="string"&&Y.length>0)}async function aW($,Z,Q,W){let Y=await iW($,Z,Q,W);return await Promise.all(Y.map(async(G)=>{if(typeof G.id!=="string"||G.id.length===0)return;await Q(`${Z.replace(/\/+$/,"")}/models/${encodeURIComponent(G.id)}/policy`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${$}`,...Z5,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"}),...W?{signal:W}:{}}).catch(()=>{return})})),nW($,Z,Q,W)}async function jH($,Z,Q){let W=Q.fetch??fetch;if($==="kimi-coding"){let Y=await W("https://auth.kimi.com/api/oauth/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",grant_type:"refresh_token",refresh_token:Z.refreshToken}),signal:AbortSignal.timeout(R1)});return vW(await K1(Y,"Kimi Code token refresh"),Z)}if($==="xai"){let Y=await W("https://auth.x.ai/oauth2/token",{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:"b1a00492-073a-47ea-816f-4c329264a828",grant_type:"refresh_token",refresh_token:Z.refreshToken}),signal:AbortSignal.timeout(R1)});return vW(await K1(Y,"xAI token refresh"),Z,300000)}if($===J8){let Y=await W("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${Z.refreshToken}`,...Z5},signal:AbortSignal.timeout(R1)}),G=await K1(Y,"GitHub Copilot token refresh");if(typeof G.token!=="string"||typeof G.expires_at!=="number")throw Error("GitHub Copilot token refresh returned invalid credentials");let X=G.token,J=dW(X),K=AbortSignal.timeout(R1),B=Z.availableModelIds?await nW(X,J,W,K):await aW(X,J,W,K);return{...Z,accessToken:X,expiresAt:G.expires_at*1000-300000,baseUrl:J,availableModelIds:B}}if($===J1){if(!Z.accountId)throw Error("OpenAI login is missing its ChatGPT account");return NH(Z,Q)}throw Error(`OAuth refresh is not implemented for provider "${$}"`)}function PH($={}){let Z=new Map;return async(Q)=>{let Y=(await n0($)).providers[Q];if(!Y)return;if(Y.type==="apiKey")return{type:"apiKey",apiKey:Y.apiKey};let G=($.now??Date.now)();if(fW(Q,Y,G))return xW(Y);let X=Z.get(Q);if(X)return X;let J=(async()=>{let K=await n0($),B=K.providers[Q];if(!B||B.type!=="oauth")throw Error(`${Q} login is no longer available`);let z=($.now??Date.now)(),V=fW(Q,B,z)?B:await jH(Q,B,$);if(V!==B)K.providers[Q]=V,await c$(K,$);return xW(V)})().finally(()=>{Z.delete(Q)});return Z.set(Q,J),J}}function rW(){let $=$5(64).toString("base64url");return{verifier:$,challenge:tB("sha256").update($).digest("base64url")}}function tW($,Z){return new Promise((Q,W)=>{let Y=(X)=>{$.off("listening",G),W(X)},G=()=>{$.off("error",Y);let X=$.address();if(!X||typeof X==="string"){W(Error("Could not determine OAuth callback port"));return}Q(X.port)};$.once("error",Y),$.once("listening",G),$.listen(Z,"127.0.0.1")})}async function wH($,Z,Q){if(Q.aborted)throw Error("OpenAI login cancelled");let W=Z===void 0?HH:[Z],Y;for(let G of W){let X=()=>{},J=()=>{},K=new Promise((V,F)=>{X=V,J=F}),B=!1,z=hW((V,F)=>{let D=new URL(V.url??"/","http://localhost");if(F.setHeader("content-type","text/html; charset=utf-8"),D.pathname!=="/auth/callback"){F.statusCode=404,F.end(E1(sZ,"That page does not exist."));return}if(D.searchParams.get("state")!==$){F.statusCode=400,F.end(E1(sZ,"State mismatch. Return to mu and try again."));return}let L=D.searchParams.get("error"),U=D.searchParams.get("code");if(L||!U){if(F.statusCode=400,F.end(E1(sZ,"Return to mu and try again.")),!B)B=!0,J(Error(`OpenAI login failed: ${L??"missing authorization code"}`));return}if(F.end(oZ(sZ)),!B)B=!0,X(U)});try{let V=await tW(z,G),F=()=>{if(!B)B=!0,J(Error("OpenAI login cancelled"));z.close()};if(Q.addEventListener("abort",F,{once:!0}),Q.aborted)F();return{redirectUri:`http://localhost:${V}/auth/callback`,callback:K.finally(()=>Q.removeEventListener("abort",F)),close:()=>z.close()}}catch(V){Y=V,z.close()}}throw Error(`Could not start OpenAI login callback server: ${Y instanceof Error?Y.message:String(Y)}`)}async function TH($={}){let Z=new AbortController,Q=()=>Z.abort();if($.signal?.addEventListener("abort",Q,{once:!0}),$.signal?.aborted)Z.abort();let W=setTimeout(Q,$.timeoutMs??BH);W.unref?.();let Y=$5(32).toString("base64url"),G=rW(),X=($.openAiIssuer??mW).replace(/\/+$/,""),J;try{J=$.callbackServer?await $.callbackServer(Y,Z.signal):await wH(Y,$.port,Z.signal);let K=new URL(`${X}/oauth/authorize`);K.search=new URLSearchParams({response_type:"code",client_id:$.openAiClientId??X8,redirect_uri:J.redirectUri,scope:GH,code_challenge:G.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:Y,originator:"mu"}).toString(),await $.onAuthUrl?.(K.toString());let B=await J.callback,z=await($.fetch??fetch)(`${X}/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$.openAiClientId??X8,code:B,code_verifier:G.verifier,redirect_uri:J.redirectUri}),signal:Z.signal}),V=cW(await pW(z,"exchange"),($.now??Date.now)()),F=await n0($);return F.providers[J1]=V,F.activeProvider=J1,await c$(F,$),{provider:J1,accountId:V.accountId}}finally{clearTimeout(W),$.signal?.removeEventListener("abort",Q),J?.close()}}function $0($,Z,Q){let W=$[Z];if(typeof W!=="string"||W.length===0)throw Error(`${Q} response is missing ${Z}`);return W}function eZ($,Z){let Q;try{Q=new URL($)}catch{throw Error(`${Z} returned an invalid authorization URL`)}if(Q.protocol!=="https:"&&Q.protocol!=="http:")throw Error(`${Z} returned an unsafe authorization URL`);return Q.toString()}function gW($,Z){let Q=eZ($,Z);if(!Q.startsWith("https:"))throw Error(`${Z} returned an unsafe authorization URL`);return Q}function i0($,Z,Q){let W=$[Z];return typeof W==="number"&&Number.isFinite(W)&&W>0?W:Q}async function IH($,Z){if(Z?.aborted)throw Error("Login cancelled");await new Promise((Q,W)=>{let G=setTimeout(()=>{Z?.removeEventListener("abort",X),Q()},$),X=()=>{clearTimeout(G),Z?.removeEventListener("abort",X),W(Error("Login cancelled"))};if(Z?.addEventListener("abort",X,{once:!0}),Z?.aborted)X()})}async function B8($){let Z=Date.now()+$.expiresInSeconds*1000,Q=Math.max(0.05,$.intervalSeconds);while(Date.now()<Z){await IH(Q*1000,$.signal);let W=await $.fetch($.url,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams($.fields),...$.signal?{signal:$.signal}:{}}),Y=await K1(W.status>=400&&W.status<500?new Response(await W.text(),{status:200,headers:W.headers}):W,`${$.provider} device token request`);if(W.ok&&typeof Y.access_token==="string")return Y;if(Y.error==="authorization_pending")continue;if(Y.error==="slow_down"){Q=i0(Y,"interval",Q+5);continue}throw Error(`${$.provider} login failed${typeof Y.error_description==="string"?`: ${Y.error_description}`:typeof Y.error==="string"?`: ${Y.error}`:""}`)}throw Error(`${$.provider} login timed out`)}async function H8($,Z,Q,W){let Y=await($.fetch??fetch)(Q,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(W),...$.signal?{signal:$.signal}:{}});return K1(Y,`${Z} device authorization`)}async function EH($={}){let Q=$.fetch??fetch,W=await H8($,"Kimi Code","https://auth.kimi.com/api/oauth/device_authorization",{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098"}),Y=typeof W.verification_uri_complete==="string"?eZ(W.verification_uri_complete,"Kimi Code"):eZ($0(W,"verification_uri","Kimi Code"),"Kimi Code"),G=$0(W,"user_code","Kimi Code");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await B8({fetch:Q,url:"https://auth.kimi.com/api/oauth/token",fields:{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",device_code:$0(W,"device_code","Kimi Code"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:i0(W,"interval",5),expiresInSeconds:i0(W,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"Kimi Code"}),J=i0(X,"expires_in",3600);return await Q5("kimi-coding",{type:"oauth",accessToken:$0(X,"access_token","Kimi Code"),refreshToken:$0(X,"refresh_token","Kimi Code"),expiresAt:($.now??Date.now)()+J*1000},$),{provider:"kimi-coding"}}async function RH($={}){let Q=$.fetch??fetch,W=await H8($,"xAI","https://auth.x.ai/oauth2/device/code",{client_id:"b1a00492-073a-47ea-816f-4c329264a828",scope:"openid profile email offline_access grok-cli:access api:access",referrer:"mu"}),Y=typeof W.verification_uri_complete==="string"?gW(W.verification_uri_complete,"xAI"):gW($0(W,"verification_uri","xAI"),"xAI"),G=$0(W,"user_code","xAI");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await B8({fetch:Q,url:"https://auth.x.ai/oauth2/token",fields:{client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_code:$0(W,"device_code","xAI"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:i0(W,"interval",5),expiresInSeconds:i0(W,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"xAI"}),J=i0(X,"expires_in",3600);return await Q5("xai",{type:"oauth",accessToken:$0(X,"access_token","xAI"),refreshToken:$0(X,"refresh_token","xAI"),expiresAt:($.now??Date.now)()+J*1000-300000},$),{provider:"xai"}}async function CH($={}){let Z=Buffer.from("SXYxLmI1MDdhMDhjODdlY2ZlOTg=","base64").toString("utf8"),Q=$.fetch??fetch,W=await H8($,"GitHub Copilot","https://github.com/login/device/code",{client_id:Z,scope:"read:user"}),Y=eZ($0(W,"verification_uri","GitHub Copilot"),"GitHub Copilot"),G=$0(W,"user_code","GitHub Copilot");await $.onDeviceCode?.(Y,G),await $.onAuthUrl?.(Y);let X=await B8({fetch:Q,url:"https://github.com/login/oauth/access_token",fields:{client_id:Z,device_code:$0(W,"device_code","GitHub Copilot"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:i0(W,"interval",5),expiresInSeconds:i0(W,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"GitHub Copilot"}),J=$0(X,"access_token","GitHub Copilot"),K=await Q("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${J}`,...Z5},...$.signal?{signal:$.signal}:{}}),B=await K1(K,"GitHub Copilot token exchange"),z=$0(B,"token","GitHub Copilot"),V=B.expires_at;if(typeof V!=="number"||!Number.isFinite(V))throw Error("GitHub Copilot response is missing expires_at");let F=dW(z),D=$.signal?AbortSignal.any([$.signal,AbortSignal.timeout(R1)]):AbortSignal.timeout(R1),L=await aW(z,F,Q,D);return await Q5(J8,{type:"oauth",accessToken:z,refreshToken:J,expiresAt:V*1000-300000,baseUrl:F,availableModelIds:L},$),{provider:"github-copilot"}}async function SH($,Z){let Q=`/oauth/callback/${$5(18).toString("base64url")}`,W=()=>{},Y=()=>{},G=new Promise((z,V)=>{W=z,Y=V}),X=!1,J=hW((z,V)=>{let F=new URL(z.url??"/","http://127.0.0.1");if(V.setHeader("content-type","text/html; charset=utf-8"),F.pathname!==Q){V.statusCode=404,V.end(E1($,"That page does not exist."));return}let D=F.searchParams.get("error"),L=F.searchParams.get("code");if(D||!L){if(V.statusCode=400,V.end(E1($,"Authorization was not completed.")),!X)X=!0,Y(Error(`${$} login failed: ${D??"missing authorization code"}`));return}if(V.end(oZ($)),!X)X=!0,W(L)});await tW(J,0);let K=J.address();if(!K||typeof K==="string")throw J.close(),Error(`Could not start the ${$} callback server`);let B=()=>{if(!X)X=!0,Y(Error(`${$} login cancelled`));J.close()};if(Z?.addEventListener("abort",B,{once:!0}),Z?.aborted)B();return{callbackUrl:`http://127.0.0.1:${K.port}${Q}`,code:G.finally(()=>Z?.removeEventListener("abort",B)),close:()=>J.close()}}async function yH($={}){let Z=rW(),Q=$.callbackServer?await $.callbackServer("OpenRouter",$.signal):await SH("OpenRouter",$.signal);try{let W=new URL("https://openrouter.ai/auth");W.search=new URLSearchParams({callback_url:Q.callbackUrl,code_challenge:Z.challenge,code_challenge_method:"S256"}).toString(),await $.onAuthUrl?.(W.toString());let Y=await Q.code,G=await($.fetch??fetch)("https://openrouter.ai/api/v1/auth/keys",{method:"POST",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({code:Y,code_verifier:Z.verifier,code_challenge_method:"S256"}),...$.signal?{signal:$.signal}:{}}),X=await K1(G,"OpenRouter key exchange");return await Q5("openrouter",{type:"oauth",accessToken:$0(X,"key","OpenRouter"),refreshToken:"",expiresAt:Number.MAX_SAFE_INTEGER},$),{provider:"openrouter"}}finally{Q.close()}}function bH($){let Z=$.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens,Q=(W)=>Math.max(0,Math.trunc(W)).toLocaleString("en-US");return["Session usage",` Input tokens: ${Q($.inputTokens)}`,` Output tokens: ${Q($.outputTokens)}`,` Cache read tokens: ${Q($.cacheReadTokens)}`,` Cache write tokens: ${Q($.cacheWriteTokens)}`,` Total tokens: ${Q(Z)}`,` Cost: $${($.costUsd??0).toFixed(6)}`,` Active context: ${(Math.max(0,$.contextPercent)*100).toFixed(1)}%`].join(`
190
+ `)}function oW($={}){return[{name:"help",description:"List available commands",run:(Z)=>{return Z.print("Commands are listed by the registry that owns them."),{handled:!0}}},{name:"model",description:"Show or switch the active model",run:(Z)=>{let Q=Z.args.trim();if(!Q)return Z.print(`Current model: ${Z.getModel()}`),{handled:!0};let W=w1(Q);if(!W){let Y=R$().map((G)=>`${G.provider}/${G.id}`).join(", ");return{handled:!0,message:`Unknown model "${Q}". Known models: ${Y}`}}return Z.setModel(`${W.provider}/${W.id}`),{handled:!0,message:`Model set to ${W.provider}/${W.id}`}}},{name:"compact",description:"Summarize older context now while preserving recent work: /compact [focus]",run:async(Z)=>{if(!$.requestCompaction)return{handled:!0,message:"Compaction is not available on this surface."};let Q=await $.requestCompaction(Z.args.trim()||void 0);if(!Q)return{handled:!0,message:"Compaction requested."};return{handled:!0,message:Q.message,data:{kind:"compaction",...Q}}}},{name:"undo",description:"Revert the last step \u2014 both the workspace and the conversation",run:async()=>{if(!$.undo)return{handled:!0,message:"Undo is not available here."};let Z=await $.undo();return{handled:!0,message:Z.message,...Z.data?{data:Z.data}:{}}}},{name:"redo",description:"Re-apply the step that was undone",run:async()=>{if(!$.redo)return{handled:!0,message:"Redo is not available here."};let Z=await $.redo();return{handled:!0,message:Z.message,...Z.data?{data:Z.data}:{}}}},{name:"fork",description:"Branch the conversation from an earlier point",run:async(Z)=>{if(!$.fork)return{handled:!0,message:"Fork is not available here."};let Q=Z.args.trim();if(!Q){let Y=$.forkPoints?.()??[];if(Y.length===0)return{handled:!0,message:"No branch points yet."};return{handled:!0,message:Y.map((G)=>`${G.id} \xB7 ${G.description}`).join(`
191
+ `),data:{kind:"fork-points",points:Y}}}return{handled:!0,message:(await $.fork(Q)).message}}},{name:"diff",description:"Show everything this session has changed",run:async()=>{if(!$.diff)return{handled:!0,message:"Diff is not available here."};let Z=await $.diff();if(Z.length===0)return{handled:!0,message:"No changes yet."};return{handled:!0,data:{kind:"diff",files:Z}}}},{name:"cost",description:"Show token usage and cost for this session",run:()=>{let Z=$.usage?.();return{handled:!0,message:Z?bH(Z):"Usage is reported by the surface that owns the session."}}}]}function _H($={}){let Z=new M1;for(let Q of oW($))Z.register(Q);return Z.register({name:"help",description:"List available commands",run:(Q)=>{let W=Z.list().map((Y)=>` /${Y.name.padEnd(12)} ${Y.description}`);return Q.print(`Available commands:
192
+ ${W.join(`
193
+ `)}`),{handled:!0}}}),Z}import{readdir as kH,stat as xH}from"fs/promises";import{homedir as fH}from"os";import{isAbsolute as vH,join as V8,resolve as gH}from"path";function hH($){return typeof $==="object"&&$!==null&&typeof $.name==="string"&&typeof $.activate==="function"}async function z8($){try{return(await kH($)).filter((Q)=>Q.endsWith(".ts")||Q.endsWith(".js")).sort().map((Q)=>V8($,Q))}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function uH($){try{return(await xH($)).isDirectory()?z8($):[$]}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function sW($={}){let Z=[];if($.userDir!==!1)Z.push(...await z8(V8(fH(),".mu","extensions")));if($.projectDir)Z.push(...await z8(V8($.projectDir,".mu","extensions")));for(let Q of $.paths??[])Z.push(...await uH(vH(Q)?Q:gH(Q)));return Z}async function mH($,Z={}){let Q={loaded:[],failed:[]};for(let W of await sW(Z))try{let Y=await import(W),G=Y.default??Y.extension;if(!hH(G)){Q.failed.push({file:W,error:"no default export with { name, activate } found"});continue}await $.register(G),Q.loaded.push(W)}catch(Y){Q.failed.push({file:W,error:Y instanceof Error?Y.message:String(Y)})}return Q}import{randomUUID as lH}from"crypto";import{mkdir as pH,readdir as cH,readFile as dH,rename as iH,rm as nH,writeFile as aH}from"fs/promises";import{homedir as rH}from"os";import{join as F8}from"path";class eW{dir;constructor($={}){let Z=$.root??F8(rH(),".mu","sessions");this.dir=$.scope?F8(Z,$.scope):Z}path($){let Z=$.replace(/[^A-Za-z0-9._-]/g,"_");return F8(this.dir,`${Z}.jsonl`)}async load($){try{return W0.fromJsonl(await dH(this.path($),"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw Z}}async save($,Z){await pH(this.dir,{recursive:!0});let Q=this.path($),W=`${Q}.${process.pid}.${lH()}.tmp`;try{await aH(W,Z.toJsonl(),"utf8"),await iH(W,Q)}catch(Y){throw await nH(W,{force:!0}).catch(()=>{}),Y}}async list(){try{return(await cH(this.dir)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.slice(0,-6))}catch($){if($.code==="ENOENT")return[];throw $}}}import{readdir as tH,readFile as oH}from"fs/promises";import{homedir as sH}from"os";import{basename as eH,join as D8}from"path";function W5($){let Z=$.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
194
+ `),Q=/^---\n([\s\S]*?)\n---\n?/.exec(Z);if(!Q)return{meta:{},body:Z.trim()};let W={};for(let Y of(Q[1]??"").split(`
195
+ `)){let G=Y.indexOf(":");if(G===-1)continue;let X=Y.slice(0,G).trim(),J=Y.slice(G+1).trim();if(X.length===0)continue;W[X]=J.startsWith("[")&&J.endsWith("]")?J.slice(1,-1).split(",").map((K)=>K.trim().replace(/^["']|["']$/g,"")).filter((K)=>K.length>0):J.replace(/^["']|["']$/g,"")}return{meta:W,body:Z.slice(Q[0].length).trim()}}function Z9($,Z){let Q=Z.trim().length>0?Z.trim().split(/\s+/):[],W=!1,Y=$.replace(/\$ARGUMENTS\b/g,()=>{return W=!0,Z.trim()});if(Y=Y.replace(/\$([1-9])\b/g,(G,X)=>{return W=!0,Q[Number(X)-1]??""}),!W&&Z.trim().length>0)return`${Y}
196
+
197
+ ${Z.trim()}`;return Y}function Q9($,Z){let{meta:Q,body:W}=W5(Z),Y=typeof Q.description==="string"?Q.description:`Run the ${$} command`,G=typeof Q.model==="string"?Q.model:void 0,X=Q["allowed-tools"],J=Array.isArray(X)?X:typeof X==="string"&&X.length>0?X.split(",").map((K)=>K.trim()):void 0;return{name:$,description:Y,body:W,...G?{model:G}:{},...J?{allowedTools:J}:{}}}async function $9($){let Z;try{Z=await tH($)}catch{return[]}let Q=[];for(let W of Z.filter((Y)=>Y.endsWith(".md")).sort())try{let Y=await oH(D8($,W),"utf8");Q.push(Q9(eH(W,".md"),Y))}catch{}return Q}async function $V($={}){let Z=await $9($.userDir??D8(sH(),".mu","commands")),Q=$.projectDir?await $9(D8($.projectDir,".mu","commands")):[],W=new Map;for(let Y of[...Z,...Q])W.set(Y.name,Y);return[...W.values()]}function ZV($,Z){return{name:$.name,description:$.description,run:async(Q)=>{let W={kind:"markdown-command",prompt:Z9($.body,Q.args),...$.model?{model:$.model}:{},...$.allowedTools?{allowedTools:$.allowedTools}:{}};if(Z)return await Z(W.prompt,{...W.model?{model:W.model}:{},...W.allowedTools?{allowedTools:W.allowedTools}:{}}),{handled:!0};return{handled:!0,data:W}}}}import{readFile as gM}from"fs/promises";import{homedir as hM}from"os";import{dirname as uM,isAbsolute as mM,join as $3,resolve as lM}from"path";import*as QV from"zod/v3";import*as Y5 from"zod/v4-mini";function s1($){return!!$._zod}function M0($,Z){if(s1($))return Y5.safeParse($,Z);return $.safeParse(Z)}function G5($){if(!$)return;let Z;if(s1($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function W9($){if(s1($)){let G=$._zod?.def;if(G){if(G.value!==void 0)return G.value;if(Array.isArray(G.values)&&G.values.length>0)return G.values[0]}}let Q=$._def;if(Q){if(Q.value!==void 0)return Q.value;if(Array.isArray(Q.values)&&Q.values.length>0)return Q.values[0]}let W=$.value;if(W!==void 0)return W;return}import*as H from"zod/v4";var L8="2025-11-25";var Y9=[L8,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],B1="io.modelcontextprotocol/related-task",J5="2.0",i=H.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),G9=H.union([H.string(),H.number().int()]),X9=H.string(),LI=H.looseObject({ttl:H.number().optional(),pollInterval:H.number().optional()}),WV=H.object({ttl:H.number().optional()}),YV=H.object({taskId:H.string()}),U8=H.looseObject({progressToken:G9.optional(),[B1]:YV.optional()}),V0=H.object({_meta:U8.optional()}),d$=V0.extend({task:WV.optional()}),J9=($)=>d$.safeParse($).success,t=H.object({method:H.string(),params:V0.loose().optional()}),L0=H.object({_meta:U8.optional()}),U0=H.object({method:H.string(),params:L0.loose().optional()}),o=H.looseObject({_meta:U8.optional()}),K5=H.union([H.string(),H.number().int()]),K9=H.object({jsonrpc:H.literal(J5),id:K5,...t.shape}).strict(),q8=($)=>K9.safeParse($).success,B9=H.object({jsonrpc:H.literal(J5),...U0.shape}).strict(),H9=($)=>B9.safeParse($).success,A8=H.object({jsonrpc:H.literal(J5),id:K5,result:o}).strict(),i$=($)=>A8.safeParse($).success;var E;(function($){$[$.ConnectionClosed=-32000]="ConnectionClosed",$[$.RequestTimeout=-32001]="RequestTimeout",$[$.ParseError=-32700]="ParseError",$[$.InvalidRequest=-32600]="InvalidRequest",$[$.MethodNotFound=-32601]="MethodNotFound",$[$.InvalidParams=-32602]="InvalidParams",$[$.InternalError=-32603]="InternalError",$[$.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(E||(E={}));var N8=H.object({jsonrpc:H.literal(J5),id:K5.optional(),error:H.object({code:H.number().int(),message:H.string(),data:H.unknown().optional()})}).strict();var V9=($)=>N8.safeParse($).success;var z9=H.union([K9,B9,A8,N8]),UI=H.union([A8,N8]),C1=o.strict(),GV=L0.extend({requestId:K5.optional(),reason:H.string().optional()}),B5=U0.extend({method:H.literal("notifications/cancelled"),params:GV}),XV=H.object({src:H.string(),mimeType:H.string().optional(),sizes:H.array(H.string()).optional(),theme:H.enum(["light","dark"]).optional()}),n$=H.object({icons:H.array(XV).optional()}),e1=H.object({name:H.string(),title:H.string().optional()}),F9=e1.extend({...e1.shape,...n$.shape,version:H.string(),websiteUrl:H.string().optional(),description:H.string().optional()}),JV=H.intersection(H.object({applyDefaults:H.boolean().optional()}),H.record(H.string(),H.unknown())),KV=H.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},H.intersection(H.object({form:JV.optional(),url:i.optional()}),H.record(H.string(),H.unknown()).optional())),BV=H.looseObject({list:i.optional(),cancel:i.optional(),requests:H.looseObject({sampling:H.looseObject({createMessage:i.optional()}).optional(),elicitation:H.looseObject({create:i.optional()}).optional()}).optional()}),HV=H.looseObject({list:i.optional(),cancel:i.optional(),requests:H.looseObject({tools:H.looseObject({call:i.optional()}).optional()}).optional()}),VV=H.object({experimental:H.record(H.string(),i).optional(),sampling:H.object({context:i.optional(),tools:i.optional()}).optional(),elicitation:KV.optional(),roots:H.object({listChanged:H.boolean().optional()}).optional(),tasks:BV.optional(),extensions:H.record(H.string(),i).optional()}),zV=V0.extend({protocolVersion:H.string(),capabilities:VV,clientInfo:F9}),FV=t.extend({method:H.literal("initialize"),params:zV});var DV=H.object({experimental:H.record(H.string(),i).optional(),logging:i.optional(),completions:i.optional(),prompts:H.object({listChanged:H.boolean().optional()}).optional(),resources:H.object({subscribe:H.boolean().optional(),listChanged:H.boolean().optional()}).optional(),tools:H.object({listChanged:H.boolean().optional()}).optional(),tasks:HV.optional(),extensions:H.record(H.string(),i).optional()}),O8=o.extend({protocolVersion:H.string(),capabilities:DV,serverInfo:F9,instructions:H.string().optional()}),LV=U0.extend({method:H.literal("notifications/initialized"),params:L0.optional()});var H5=t.extend({method:H.literal("ping"),params:V0.optional()}),UV=H.object({progress:H.number(),total:H.optional(H.number()),message:H.optional(H.string())}),qV=H.object({...L0.shape,...UV.shape,progressToken:G9}),V5=U0.extend({method:H.literal("notifications/progress"),params:qV}),AV=V0.extend({cursor:X9.optional()}),a$=t.extend({params:AV.optional()}),r$=o.extend({nextCursor:X9.optional()}),NV=H.enum(["working","input_required","completed","failed","cancelled"]),t$=H.object({taskId:H.string(),status:NV,ttl:H.union([H.number(),H.null()]),createdAt:H.string(),lastUpdatedAt:H.string(),pollInterval:H.optional(H.number()),statusMessage:H.optional(H.string())}),S1=o.extend({task:t$}),OV=L0.merge(t$),o$=U0.extend({method:H.literal("notifications/tasks/status"),params:OV}),z5=t.extend({method:H.literal("tasks/get"),params:V0.extend({taskId:H.string()})}),F5=o.merge(t$),D5=t.extend({method:H.literal("tasks/result"),params:V0.extend({taskId:H.string()})}),qI=o.loose(),L5=a$.extend({method:H.literal("tasks/list")}),U5=r$.extend({tasks:H.array(t$)}),q5=t.extend({method:H.literal("tasks/cancel"),params:V0.extend({taskId:H.string()})}),D9=o.merge(t$),L9=H.object({uri:H.string(),mimeType:H.optional(H.string()),_meta:H.record(H.string(),H.unknown()).optional()}),U9=L9.extend({text:H.string()}),M8=H.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),q9=L9.extend({blob:M8}),s$=H.enum(["user","assistant"]),$$=H.object({audience:H.array(s$).optional(),priority:H.number().min(0).max(1).optional(),lastModified:H.iso.datetime({offset:!0}).optional()}),A9=H.object({...e1.shape,...n$.shape,uri:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),size:H.optional(H.number()),annotations:$$.optional(),_meta:H.optional(H.looseObject({}))}),MV=H.object({...e1.shape,...n$.shape,uriTemplate:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),annotations:$$.optional(),_meta:H.optional(H.looseObject({}))}),jV=a$.extend({method:H.literal("resources/list")}),j8=r$.extend({resources:H.array(A9)}),PV=a$.extend({method:H.literal("resources/templates/list")}),P8=r$.extend({resourceTemplates:H.array(MV)}),w8=V0.extend({uri:H.string()}),wV=w8,TV=t.extend({method:H.literal("resources/read"),params:wV}),T8=o.extend({contents:H.array(H.union([U9,q9]))}),I8=U0.extend({method:H.literal("notifications/resources/list_changed"),params:L0.optional()}),IV=w8,EV=t.extend({method:H.literal("resources/subscribe"),params:IV}),RV=w8,CV=t.extend({method:H.literal("resources/unsubscribe"),params:RV}),SV=L0.extend({uri:H.string()}),yV=U0.extend({method:H.literal("notifications/resources/updated"),params:SV}),bV=H.object({name:H.string(),description:H.optional(H.string()),required:H.optional(H.boolean())}),_V=H.object({...e1.shape,...n$.shape,description:H.optional(H.string()),arguments:H.optional(H.array(bV)),_meta:H.optional(H.looseObject({}))}),kV=a$.extend({method:H.literal("prompts/list")}),E8=r$.extend({prompts:H.array(_V)}),xV=V0.extend({name:H.string(),arguments:H.record(H.string(),H.string()).optional()}),fV=t.extend({method:H.literal("prompts/get"),params:xV}),R8=H.object({type:H.literal("text"),text:H.string(),annotations:$$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),C8=H.object({type:H.literal("image"),data:M8,mimeType:H.string(),annotations:$$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),S8=H.object({type:H.literal("audio"),data:M8,mimeType:H.string(),annotations:$$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),vV=H.object({type:H.literal("tool_use"),name:H.string(),id:H.string(),input:H.record(H.string(),H.unknown()),_meta:H.record(H.string(),H.unknown()).optional()}),gV=H.object({type:H.literal("resource"),resource:H.union([U9,q9]),annotations:$$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),hV=A9.extend({type:H.literal("resource_link")}),y8=H.union([R8,C8,S8,hV,gV]),uV=H.object({role:s$,content:y8}),b8=o.extend({description:H.string().optional(),messages:H.array(uV)}),_8=U0.extend({method:H.literal("notifications/prompts/list_changed"),params:L0.optional()}),mV=H.object({title:H.string().optional(),readOnlyHint:H.boolean().optional(),destructiveHint:H.boolean().optional(),idempotentHint:H.boolean().optional(),openWorldHint:H.boolean().optional()}),lV=H.object({taskSupport:H.enum(["required","optional","forbidden"]).optional()}),N9=H.object({...e1.shape,...n$.shape,description:H.string().optional(),inputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),i).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()),outputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),i).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()).optional(),annotations:mV.optional(),execution:lV.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),pV=a$.extend({method:H.literal("tools/list")}),k8=r$.extend({tools:H.array(N9)}),Z$=o.extend({content:H.array(y8).default([]),structuredContent:H.record(H.string(),H.unknown()).optional(),isError:H.boolean().optional()}),AI=Z$.or(o.extend({toolResult:H.unknown()})),cV=d$.extend({name:H.string(),arguments:H.record(H.string(),H.unknown()).optional()}),dV=t.extend({method:H.literal("tools/call"),params:cV}),x8=U0.extend({method:H.literal("notifications/tools/list_changed"),params:L0.optional()}),O9=H.object({autoRefresh:H.boolean().default(!0),debounceMs:H.number().int().nonnegative().default(300)}),M9=H.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),iV=V0.extend({level:M9}),nV=t.extend({method:H.literal("logging/setLevel"),params:iV}),aV=L0.extend({level:M9,logger:H.string().optional(),data:H.unknown()}),rV=U0.extend({method:H.literal("notifications/message"),params:aV}),tV=H.object({name:H.string().optional()}),oV=H.object({hints:H.array(tV).optional(),costPriority:H.number().min(0).max(1).optional(),speedPriority:H.number().min(0).max(1).optional(),intelligencePriority:H.number().min(0).max(1).optional()}),sV=H.object({mode:H.enum(["auto","required","none"]).optional()}),eV=H.object({type:H.literal("tool_result"),toolUseId:H.string().describe("The unique identifier for the corresponding tool call."),content:H.array(y8).default([]),structuredContent:H.object({}).loose().optional(),isError:H.boolean().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),$z=H.discriminatedUnion("type",[R8,C8,S8]),X5=H.discriminatedUnion("type",[R8,C8,S8,vV,eV]),Zz=H.object({role:s$,content:H.union([X5,H.array(X5)]),_meta:H.record(H.string(),H.unknown()).optional()}),Qz=d$.extend({messages:H.array(Zz),modelPreferences:oV.optional(),systemPrompt:H.string().optional(),includeContext:H.enum(["none","thisServer","allServers"]).optional(),temperature:H.number().optional(),maxTokens:H.number().int(),stopSequences:H.array(H.string()).optional(),metadata:i.optional(),tools:H.array(N9).optional(),toolChoice:sV.optional()}),f8=t.extend({method:H.literal("sampling/createMessage"),params:Qz}),v8=o.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens"]).or(H.string())),role:s$,content:$z}),g8=o.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(H.string())),role:s$,content:H.union([X5,H.array(X5)])}),Wz=H.object({type:H.literal("boolean"),title:H.string().optional(),description:H.string().optional(),default:H.boolean().optional()}),Yz=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),minLength:H.number().optional(),maxLength:H.number().optional(),format:H.enum(["email","uri","date","date-time"]).optional(),default:H.string().optional()}),Gz=H.object({type:H.enum(["number","integer"]),title:H.string().optional(),description:H.string().optional(),minimum:H.number().optional(),maximum:H.number().optional(),default:H.number().optional()}),Xz=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),enum:H.array(H.string()),default:H.string().optional()}),Jz=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),oneOf:H.array(H.object({const:H.string(),title:H.string()})),default:H.string().optional()}),Kz=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),enum:H.array(H.string()),enumNames:H.array(H.string()).optional(),default:H.string().optional()}),Bz=H.union([Xz,Jz]),Hz=H.object({type:H.literal("array"),title:H.string().optional(),description:H.string().optional(),minItems:H.number().optional(),maxItems:H.number().optional(),items:H.object({type:H.literal("string"),enum:H.array(H.string())}),default:H.array(H.string()).optional()}),Vz=H.object({type:H.literal("array"),title:H.string().optional(),description:H.string().optional(),minItems:H.number().optional(),maxItems:H.number().optional(),items:H.object({anyOf:H.array(H.object({const:H.string(),title:H.string()}))}),default:H.array(H.string()).optional()}),zz=H.union([Hz,Vz]),Fz=H.union([Kz,Bz,zz]),Dz=H.union([Fz,Wz,Yz,Gz]),Lz=d$.extend({mode:H.literal("form").optional(),message:H.string(),requestedSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),Dz),required:H.array(H.string()).optional()})}),Uz=d$.extend({mode:H.literal("url"),message:H.string(),elicitationId:H.string(),url:H.string().url()}),qz=H.union([Lz,Uz]),h8=t.extend({method:H.literal("elicitation/create"),params:qz}),Az=L0.extend({elicitationId:H.string()}),Nz=U0.extend({method:H.literal("notifications/elicitation/complete"),params:Az}),u8=o.extend({action:H.enum(["accept","decline","cancel"]),content:H.preprocess(($)=>$===null?void 0:$,H.record(H.string(),H.union([H.string(),H.number(),H.boolean(),H.array(H.string())])).optional())}),Oz=H.object({type:H.literal("ref/resource"),uri:H.string()});var Mz=H.object({type:H.literal("ref/prompt"),name:H.string()}),jz=V0.extend({ref:H.union([Mz,Oz]),argument:H.object({name:H.string(),value:H.string()}),context:H.object({arguments:H.record(H.string(),H.string()).optional()}).optional()}),Pz=t.extend({method:H.literal("completion/complete"),params:jz});var m8=o.extend({completion:H.looseObject({values:H.array(H.string()).max(100),total:H.optional(H.number().int()),hasMore:H.optional(H.boolean())})}),wz=H.object({uri:H.string().startsWith("file://"),name:H.string().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Tz=t.extend({method:H.literal("roots/list"),params:V0.optional()}),Iz=o.extend({roots:H.array(wz)}),Ez=U0.extend({method:H.literal("notifications/roots/list_changed"),params:L0.optional()}),NI=H.union([H5,FV,Pz,nV,fV,kV,jV,PV,TV,EV,CV,dV,pV,z5,D5,L5,q5]),OI=H.union([B5,V5,LV,Ez,o$]),MI=H.union([C1,v8,g8,u8,Iz,F5,U5,S1]),jI=H.union([H5,f8,h8,Tz,z5,D5,L5,q5]),PI=H.union([B5,V5,rV,yV,I8,x8,_8,o$,Nz]),wI=H.union([C1,O8,m8,b8,E8,j8,P8,T8,Z$,k8,F5,U5,S1]);class I extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===E.UrlElicitationRequired&&Q){let W=Q;if(W.elicitations)return new j9(W.elicitations,Z)}return new I($,Z,Q)}}class j9 extends I{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(E.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function H1($){return $==="completed"||$==="failed"||$==="cancelled"}import*as kz from"zod/v4-mini";var Rz=Symbol("Let zodToJsonSchema decide on which parser to use");import{ZodFirstPartyTypeKind as wR}from"zod/v3";import{ZodFirstPartyTypeKind as fI}from"zod/v3";import{ZodFirstPartyTypeKind as KE}from"zod/v3";var GE=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function l8($){let Q=G5($)?.method;if(!Q)throw Error("Schema is missing a method literal");let W=W9(Q);if(typeof W!=="string")throw Error("Schema method literal must be a string");return W}function p8($,Z){let Q=M0($,Z);if(!Q.success)throw Q.error;return Q.data}var xz=60000;class c8{constructor($){if(this._options=$,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(B5,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(V5,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(H5,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(z5,async(Z,Q)=>{let W=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!W)throw new I(E.InvalidParams,"Failed to retrieve task: Task not found");return{...W}}),this.setRequestHandler(D5,async(Z,Q)=>{let W=async()=>{let Y=Z.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(Y,Q.sessionId)){if(X.type==="response"||X.type==="error"){let J=X.message,K=J.id,B=this._requestResolvers.get(K);if(B)if(this._requestResolvers.delete(K),X.type==="response")B(J);else{let z=J,V=new I(z.error.code,z.error.message,z.error.data);B(V)}else{let z=X.type==="response"?"Response":"Error";this._onerror(Error(`${z} handler missing for request ${K}`))}continue}await this._transport?.send(X.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(Y,Q.sessionId);if(!G)throw new I(E.InvalidParams,`Task not found: ${Y}`);if(!H1(G.status))return await this._waitForTaskUpdate(Y,Q.signal),await W();if(H1(G.status)){let X=await this._taskStore.getTaskResult(Y,Q.sessionId);return this._clearTaskQueue(Y),{...X,_meta:{...X._meta,[B1]:{taskId:Y}}}}return await W()};return await W()}),this.setRequestHandler(L5,async(Z,Q)=>{try{let{tasks:W,nextCursor:Y}=await this._taskStore.listTasks(Z.params?.cursor,Q.sessionId);return{tasks:W,nextCursor:Y,_meta:{}}}catch(W){throw new I(E.InvalidParams,`Failed to list tasks: ${W instanceof Error?W.message:String(W)}`)}}),this.setRequestHandler(q5,async(Z,Q)=>{try{let W=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!W)throw new I(E.InvalidParams,`Task not found: ${Z.params.taskId}`);if(H1(W.status))throw new I(E.InvalidParams,`Cannot cancel task in terminal status: ${W.status}`);await this._taskStore.updateTaskStatus(Z.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(Z.params.taskId);let Y=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!Y)throw new I(E.InvalidParams,`Task not found after cancellation: ${Z.params.taskId}`);return{_meta:{},...Y}}catch(W){if(W instanceof I)throw W;throw new I(E.InvalidRequest,`Failed to cancel task: ${W instanceof Error?W.message:String(W)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,Q,W,Y=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(W,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:Q,resetTimeoutOnProgress:Y,onTimeout:W})}_resetTimeout($){let Z=this._timeoutInfo.get($);if(!Z)return!1;let Q=Date.now()-Z.startTime;if(Z.maxTotalTimeout&&Q>=Z.maxTotalTimeout)throw this._timeoutInfo.delete($),I.fromError(E.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:Z.maxTotalTimeout,totalElapsed:Q});return clearTimeout(Z.timeoutId),Z.timeoutId=setTimeout(Z.onTimeout,Z.timeout),!0}_cleanupTimeout($){let Z=this._timeoutInfo.get($);if(Z)clearTimeout(Z.timeoutId),this._timeoutInfo.delete($)}async connect($){if(this._transport)throw Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=$;let Z=this.transport?.onclose;this._transport.onclose=()=>{Z?.(),this._onclose()};let Q=this.transport?.onerror;this._transport.onerror=(Y)=>{Q?.(Y),this._onerror(Y)};let W=this._transport?.onmessage;this._transport.onmessage=(Y,G)=>{if(W?.(Y,G),i$(Y)||V9(Y))this._onresponse(Y);else if(q8(Y))this._onrequest(Y,G);else if(H9(Y))this._onnotification(Y);else this._onerror(Error(`Unknown message type: ${JSON.stringify(Y)}`))},await this._transport.start()}_onclose(){let $=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let Q of this._timeoutInfo.values())clearTimeout(Q.timeoutId);this._timeoutInfo.clear();for(let Q of this._requestHandlerAbortControllers.values())Q.abort();this._requestHandlerAbortControllers.clear();let Z=I.fromError(E.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let Q of $.values())Q(Z)}_onerror($){this.onerror?.($)}_onnotification($){let Z=this._notificationHandlers.get($.method)??this.fallbackNotificationHandler;if(Z===void 0)return;Promise.resolve().then(()=>Z($)).catch((Q)=>this._onerror(Error(`Uncaught error in notification handler: ${Q}`)))}_onrequest($,Z){let Q=this._requestHandlers.get($.method)??this.fallbackRequestHandler,W=this._transport,Y=$.params?._meta?.[B1]?.taskId;if(Q===void 0){let B={jsonrpc:"2.0",id:$.id,error:{code:E.MethodNotFound,message:"Method not found"}};if(Y&&this._taskMessageQueue)this._enqueueTaskMessage(Y,{type:"error",message:B,timestamp:Date.now()},W?.sessionId).catch((z)=>this._onerror(Error(`Failed to enqueue error response: ${z}`)));else W?.send(B).catch((z)=>this._onerror(Error(`Failed to send an error response: ${z}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let X=J9($.params)?$.params.task:void 0,J=this._taskStore?this.requestTaskStore($,W?.sessionId):void 0,K={signal:G.signal,sessionId:W?.sessionId,_meta:$.params?._meta,sendNotification:async(B)=>{if(G.signal.aborted)return;let z={relatedRequestId:$.id};if(Y)z.relatedTask={taskId:Y};await this.notification(B,z)},sendRequest:async(B,z,V)=>{if(G.signal.aborted)throw new I(E.ConnectionClosed,"Request was cancelled");let F={...V,relatedRequestId:$.id};if(Y&&!F.relatedTask)F.relatedTask={taskId:Y};let D=F.relatedTask?.taskId??Y;if(D&&J)await J.updateTaskStatus(D,"input_required");return await this.request(B,z,F)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:Y,taskStore:J,taskRequestedTtl:X?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,K)).then(async(B)=>{if(G.signal.aborted)return;let z={result:B,jsonrpc:"2.0",id:$.id};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"response",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)},async(B)=>{if(G.signal.aborted)return;let z={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(B.code)?B.code:E.InternalError,message:B.message??"Internal error",...B.data!==void 0&&{data:B.data}}};if(Y&&this._taskMessageQueue)await this._enqueueTaskMessage(Y,{type:"error",message:z,timestamp:Date.now()},W?.sessionId);else await W?.send(z)}).catch((B)=>this._onerror(Error(`Failed to send response: ${B}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...Q}=$.params,W=Number(Z),Y=this._progressHandlers.get(W);if(!Y){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(W),X=this._timeoutInfo.get(W);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(W)}catch(J){this._responseHandlers.delete(W),this._progressHandlers.delete(W),this._cleanupTimeout(W),G(J);return}Y(Q)}_onresponse($){let Z=Number($.id),Q=this._requestResolvers.get(Z);if(Q){if(this._requestResolvers.delete(Z),i$($))Q($);else{let G=new I($.error.code,$.error.message,$.error.data);Q(G)}return}let W=this._responseHandlers.get(Z);if(W===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(Z),this._cleanupTimeout(Z);let Y=!1;if(i$($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")Y=!0,this._taskProgressTokens.set(X.taskId,Z)}}if(!Y)this._progressHandlers.delete(Z);if(i$($))W($);else{let G=I.fromError($.error.code,$.error.message,$.error.data);W(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,Q){let{task:W}=Q??{};if(!W){try{yield{type:"result",result:await this.request($,Z,Q)}}catch(G){yield{type:"error",error:G instanceof I?G:new I(E.InternalError,String(G))}}return}let Y;try{let G=await this.request($,S1,Q);if(G.task)Y=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new I(E.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:Y},Q);if(yield{type:"taskStatus",task:X},H1(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:Y},Z,Q)};else if(X.status==="failed")yield{type:"error",error:new I(E.InternalError,`Task ${Y} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new I(E.InternalError,`Task ${Y} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:Y},Z,Q)};return}let J=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((K)=>setTimeout(K,J)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof I?G:new I(E.InternalError,String(G))}}}request($,Z,Q){let{relatedRequestId:W,resumptionToken:Y,onresumptiontoken:G,task:X,relatedTask:J}=Q??{};return new Promise((K,B)=>{let z=(A)=>{B(A)};if(!this._transport){z(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),X)this.assertTaskCapability($.method)}catch(A){z(A);return}Q?.signal?.throwIfAborted();let V=this._requestMessageId++,F={...$,jsonrpc:"2.0",id:V};if(Q?.onprogress)this._progressHandlers.set(V,Q.onprogress),F.params={...$.params,_meta:{...$.params?._meta||{},progressToken:V}};if(X)F.params={...F.params,task:X};if(J)F.params={...F.params,_meta:{...F.params?._meta||{},[B1]:J}};let D=(A)=>{this._responseHandlers.delete(V),this._progressHandlers.delete(V),this._cleanupTimeout(V),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:V,reason:String(A)}},{relatedRequestId:W,resumptionToken:Y,onresumptiontoken:G}).catch((j)=>this._onerror(Error(`Failed to send cancellation: ${j}`)));let N=A instanceof I?A:new I(E.RequestTimeout,String(A));B(N)};this._responseHandlers.set(V,(A)=>{if(Q?.signal?.aborted)return;if(A instanceof Error)return B(A);try{let N=M0(Z,A.result);if(!N.success)B(N.error);else K(N.data)}catch(N){B(N)}}),Q?.signal?.addEventListener("abort",()=>{D(Q?.signal?.reason)});let L=Q?.timeout??xz,U=()=>D(I.fromError(E.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(V,L,Q?.maxTotalTimeout,U,Q?.resetTimeoutOnProgress??!1);let q=J?.taskId;if(q){let A=(N)=>{let j=this._responseHandlers.get(V);if(j)j(N);else this._onerror(Error(`Response handler missing for side-channeled request ${V}`))};this._requestResolvers.set(V,A),this._enqueueTaskMessage(q,{type:"request",message:F,timestamp:Date.now()}).catch((N)=>{this._cleanupTimeout(V),B(N)})}else this._transport.send(F,{relatedRequestId:W,resumptionToken:Y,onresumptiontoken:G}).catch((A)=>{this._cleanupTimeout(V),B(A)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},F5,Z)}async getTaskResult($,Z,Q){return this.request({method:"tasks/result",params:$},Z,Q)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},U5,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},D9,Z)}async notification($,Z){if(!this._transport)throw Error("Not connected");this.assertNotificationCapability($.method);let Q=Z?.relatedTask?.taskId;if(Q){let X={...$,jsonrpc:"2.0",params:{...$.params,_meta:{...$.params?._meta||{},[B1]:Z.relatedTask}}};await this._enqueueTaskMessage(Q,{type:"notification",message:X,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes($.method)&&!$.params&&!Z?.relatedRequestId&&!Z?.relatedTask){if(this._pendingDebouncedNotifications.has($.method))return;this._pendingDebouncedNotifications.add($.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete($.method),!this._transport)return;let X={...$,jsonrpc:"2.0"};if(Z?.relatedTask)X={...X,params:{...X.params,_meta:{...X.params?._meta||{},[B1]:Z.relatedTask}}};this._transport?.send(X,Z).catch((J)=>this._onerror(J))});return}let G={...$,jsonrpc:"2.0"};if(Z?.relatedTask)G={...G,params:{...G.params,_meta:{...G.params?._meta||{},[B1]:Z.relatedTask}}};await this._transport.send(G,Z)}setRequestHandler($,Z){let Q=l8($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(W,Y)=>{let G=p8($,W);return Promise.resolve(Z(G,Y))})}removeRequestHandler($){this._requestHandlers.delete($)}assertCanSetRequestHandler($){if(this._requestHandlers.has($))throw Error(`A request handler for ${$} already exists, which would be overridden`)}setNotificationHandler($,Z){let Q=l8($);this._notificationHandlers.set(Q,(W)=>{let Y=p8($,W);return Promise.resolve(Z(Y))})}removeNotificationHandler($){this._notificationHandlers.delete($)}_cleanupTaskProgressHandler($){let Z=this._taskProgressTokens.get($);if(Z!==void 0)this._progressHandlers.delete(Z),this._taskProgressTokens.delete($)}async _enqueueTaskMessage($,Z,Q){if(!this._taskStore||!this._taskMessageQueue)throw Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let W=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,Q,W)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,Z);for(let W of Q)if(W.type==="request"&&q8(W.message)){let Y=W.message.id,G=this._requestResolvers.get(Y);if(G)G(new I(E.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(Y);else this._onerror(Error(`Resolver missing for request ${Y} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,Z){let Q=this._options?.defaultTaskPollInterval??1000;try{let W=await this._taskStore?.getTask($);if(W?.pollInterval)Q=W.pollInterval}catch{}return new Promise((W,Y)=>{if(Z.aborted){Y(new I(E.InvalidRequest,"Request cancelled"));return}let G=setTimeout(W,Q);Z.addEventListener("abort",()=>{clearTimeout(G),Y(new I(E.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,Z){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(W)=>{if(!$)throw Error("No request provided");return await Q.createTask(W,$.id,{method:$.method,params:$.params},Z)},getTask:async(W)=>{let Y=await Q.getTask(W,Z);if(!Y)throw new I(E.InvalidParams,"Failed to retrieve task: Task not found");return Y},storeTaskResult:async(W,Y,G)=>{await Q.storeTaskResult(W,Y,G,Z);let X=await Q.getTask(W,Z);if(X){let J=o$.parse({method:"notifications/tasks/status",params:X});if(await this.notification(J),H1(X.status))this._cleanupTaskProgressHandler(W)}},getTaskResult:(W)=>{return Q.getTaskResult(W,Z)},updateTaskStatus:async(W,Y,G)=>{let X=await Q.getTask(W,Z);if(!X)throw new I(E.InvalidParams,`Task "${W}" not found - it may have been cleaned up`);if(H1(X.status))throw new I(E.InvalidParams,`Cannot update task "${W}" from terminal status "${X.status}" to "${Y}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(W,Y,G,Z);let J=await Q.getTask(W,Z);if(J){let K=o$.parse({method:"notifications/tasks/status",params:J});if(await this.notification(K),H1(J.status))this._cleanupTaskProgressHandler(W)}},listTasks:(W)=>{return Q.listTasks(W,Z)}}}}function P9($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function w9($,Z){let Q={...$};for(let W in Z){let Y=W,G=Z[Y];if(G===void 0)continue;let X=Q[Y];if(P9(X)&&P9(G))Q[Y]={...X,...G};else Q[Y]=G}return Q}var XJ=V6(h4(),1),JJ=V6(GJ(),1);function YM(){let $=new XJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return JJ.default($),$}class r4{constructor($){this._ajv=$??YM()}getValidator($){let Z="$id"in $&&typeof $.$id==="string"?this._ajv.getSchema($.$id)??this._ajv.compile($):this._ajv.compile($);return(Q)=>{if(Z(Q))return{valid:!0,data:Q,errorMessage:void 0};else return{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(Z.errors)}}}}class t4{constructor($){this._client=$}async*callToolStream($,Z=Z$,Q){let W=this._client,Y={...Q,task:Q?.task??(W.isToolTask($.name)?{}:void 0)},G=W.requestStream({method:"tools/call",params:$},Z,Y),X=W.getToolOutputValidator($.name);for await(let J of G){if(J.type==="result"&&X){let K=J.result;if(!K.structuredContent&&!K.isError){yield{type:"error",error:new I(E.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`)};return}if(K.structuredContent)try{let B=X(K.structuredContent);if(!B.valid){yield{type:"error",error:new I(E.InvalidParams,`Structured content does not match the tool's output schema: ${B.errorMessage}`)};return}}catch(B){if(B instanceof I){yield{type:"error",error:B};return}yield{type:"error",error:new I(E.InvalidParams,`Failed to validate structured content: ${B instanceof Error?B.message:String(B)}`)};return}}yield J}}async getTask($,Z){return this._client.getTask({taskId:$},Z)}async getTaskResult($,Z,Q){return this._client.getTaskResult({taskId:$},Z,Q)}async listTasks($,Z){return this._client.listTasks($?{cursor:$}:void 0,Z)}async cancelTask($,Z){return this._client.cancelTask({taskId:$},Z)}requestStream($,Z,Q){return this._client.requestStream($,Z,Q)}}function KJ($,Z,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${Z})`);switch(Z){case"tools/call":if(!$.tools?.call)throw Error(`${Q} does not support task creation for tools/call (required for ${Z})`);break;default:break}}function BJ($,Z,Q){if(!$)throw Error(`${Q} does not support task creation (required for ${Z})`);switch(Z){case"sampling/createMessage":if(!$.sampling?.createMessage)throw Error(`${Q} does not support task creation for sampling/createMessage (required for ${Z})`);break;case"elicitation/create":if(!$.elicitation?.create)throw Error(`${Q} does not support task creation for elicitation/create (required for ${Z})`);break;default:break}}function $6($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let Q=Z,W=$.properties;for(let Y of Object.keys(W)){let G=W[Y];if(Q[Y]===void 0&&Object.prototype.hasOwnProperty.call(G,"default"))Q[Y]=G.default;if(Q[Y]!==void 0)$6(G,Q[Y])}}if(Array.isArray($.anyOf)){for(let Q of $.anyOf)if(typeof Q!=="boolean")$6(Q,Z)}if(Array.isArray($.oneOf)){for(let Q of $.oneOf)if(typeof Q!=="boolean")$6(Q,Z)}}function GM($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,Q=$.url!==void 0;return{supportsFormMode:Z||!Z&&!Q,supportsUrlMode:Q}}class o4 extends c8{constructor($,Z){super(Z);if(this._clientInfo=$,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=Z?.capabilities??{},this._jsonSchemaValidator=Z?.jsonSchemaValidator??new r4,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",x8,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",_8,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",I8,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new t4(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=w9(this._capabilities,$)}setRequestHandler($,Z){let W=G5($)?.method;if(!W)throw Error("Schema is missing a method literal");let Y;if(s1(W)){let X=W;Y=X._zod?.def?.value??X.value}else{let X=W;Y=X._def?.value??X.value}if(typeof Y!=="string")throw Error("Schema method literal must be a string");let G=Y;if(G==="elicitation/create"){let X=async(J,K)=>{let B=M0(h8,J);if(!B.success){let A=B.error instanceof Error?B.error.message:String(B.error);throw new I(E.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:z}=B.data;z.mode=z.mode??"form";let{supportsFormMode:V,supportsUrlMode:F}=GM(this._capabilities.elicitation);if(z.mode==="form"&&!V)throw new I(E.InvalidParams,"Client does not support form-mode elicitation requests");if(z.mode==="url"&&!F)throw new I(E.InvalidParams,"Client does not support URL-mode elicitation requests");let D=await Promise.resolve(Z(J,K));if(z.task){let A=M0(S1,D);if(!A.success){let N=A.error instanceof Error?A.error.message:String(A.error);throw new I(E.InvalidParams,`Invalid task creation result: ${N}`)}return A.data}let L=M0(u8,D);if(!L.success){let A=L.error instanceof Error?L.error.message:String(L.error);throw new I(E.InvalidParams,`Invalid elicitation result: ${A}`)}let U=L.data,q=z.mode==="form"?z.requestedSchema:void 0;if(z.mode==="form"&&U.action==="accept"&&U.content&&q){if(this._capabilities.elicitation?.form?.applyDefaults)try{$6(q,U.content)}catch{}}return U};return super.setRequestHandler($,X)}if(G==="sampling/createMessage"){let X=async(J,K)=>{let B=M0(f8,J);if(!B.success){let U=B.error instanceof Error?B.error.message:String(B.error);throw new I(E.InvalidParams,`Invalid sampling request: ${U}`)}let{params:z}=B.data,V=await Promise.resolve(Z(J,K));if(z.task){let U=M0(S1,V);if(!U.success){let q=U.error instanceof Error?U.error.message:String(U.error);throw new I(E.InvalidParams,`Invalid task creation result: ${q}`)}return U.data}let D=z.tools||z.toolChoice?g8:v8,L=M0(D,V);if(!L.success){let U=L.error instanceof Error?L.error.message:String(L.error);throw new I(E.InvalidParams,`Invalid sampling result: ${U}`)}return L.data};return super.setRequestHandler($,X)}return super.setRequestHandler($,Z)}assertCapability($,Z){if(!this._serverCapabilities?.[$])throw Error(`Server does not support ${$} (required for ${Z})`)}async connect($,Z){if(await super.connect($),$.sessionId!==void 0)return;try{let Q=await this.request({method:"initialize",params:{protocolVersion:L8,capabilities:this._capabilities,clientInfo:this._clientInfo}},O8,Z);if(Q===void 0)throw Error(`Server sent invalid initialize result: ${Q}`);if(!Y9.includes(Q.protocolVersion))throw Error(`Server's protocol version is not supported: ${Q.protocolVersion}`);if(this._serverCapabilities=Q.capabilities,this._serverVersion=Q.serverInfo,$.setProtocolVersion)$.setProtocolVersion(Q.protocolVersion);if(this._instructions=Q.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig)this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0}catch(Q){throw this.close(),Q}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod($){switch($){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw Error(`Server does not support logging (required for ${$})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw Error(`Server does not support prompts (required for ${$})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw Error(`Server does not support resources (required for ${$})`);if($==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw Error(`Server does not support resource subscriptions (required for ${$})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw Error(`Server does not support tools (required for ${$})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw Error(`Server does not support completions (required for ${$})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability($){switch($){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw Error(`Client does not support roots list changed notifications (required for ${$})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability($){if(!this._capabilities)return;switch($){case"sampling/createMessage":if(!this._capabilities.sampling)throw Error(`Client does not support sampling capability (required for ${$})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw Error(`Client does not support elicitation capability (required for ${$})`);break;case"roots/list":if(!this._capabilities.roots)throw Error(`Client does not support roots capability (required for ${$})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw Error(`Client does not support tasks capability (required for ${$})`);break;case"ping":break}}assertTaskCapability($){KJ(this._serverCapabilities?.tasks?.requests,$,"Server")}assertTaskHandlerCapability($){if(!this._capabilities)return;BJ(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},C1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},m8,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},C1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},b8,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},E8,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},j8,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},P8,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},T8,Z)}async subscribeResource($,Z){return this.request({method:"resources/subscribe",params:$},C1,Z)}async unsubscribeResource($,Z){return this.request({method:"resources/unsubscribe",params:$},C1,Z)}async callTool($,Z=Z$,Q){if(this.isToolTaskRequired($.name))throw new I(E.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let W=await this.request({method:"tools/call",params:$},Z,Q),Y=this.getToolOutputValidator($.name);if(Y){if(!W.structuredContent&&!W.isError)throw new I(E.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(W.structuredContent)try{let G=Y(W.structuredContent);if(!G.valid)throw new I(E.InvalidParams,`Structured content does not match the tool's output schema: ${G.errorMessage}`)}catch(G){if(G instanceof I)throw G;throw new I(E.InvalidParams,`Failed to validate structured content: ${G instanceof Error?G.message:String(G)}`)}}return W}isToolTask($){if(!this._serverCapabilities?.tasks?.requests?.tools?.call)return!1;return this._cachedKnownTaskTools.has($)}isToolTaskRequired($){return this._cachedRequiredTaskTools.has($)}cacheToolMetadata($){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let Z of $){if(Z.outputSchema){let W=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,W)}let Q=Z.execution?.taskSupport;if(Q==="required"||Q==="optional")this._cachedKnownTaskTools.add(Z.name);if(Q==="required")this._cachedRequiredTaskTools.add(Z.name)}}getToolOutputValidator($){return this._cachedToolOutputValidators.get($)}async listTools($,Z){let Q=await this.request({method:"tools/list",params:$},k8,Z);return this.cacheToolMetadata(Q.tools),Q}_setupListChangedHandler($,Z,Q,W){let Y=O9.safeParse(Q);if(!Y.success)throw Error(`Invalid ${$} listChanged options: ${Y.error.message}`);if(typeof Q.onChanged!=="function")throw Error(`Invalid ${$} listChanged options: onChanged must be a function`);let{autoRefresh:G,debounceMs:X}=Y.data,{onChanged:J}=Q,K=async()=>{if(!G){J(null,null);return}try{let z=await W();J(null,z)}catch(z){let V=z instanceof Error?z:Error(String(z));J(V,null)}},B=()=>{if(X){let z=this._listChangedDebounceTimers.get($);if(z)clearTimeout(z);let V=setTimeout(K,X);this._listChangedDebounceTimers.set($,V)}else K()};this.setNotificationHandler(Z,B)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var eJ=V6(oJ(),1);import KQ from"process";import{PassThrough as fM}from"stream";class JQ{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
198
+ `);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),xM(Z)}clear(){this._buffer=void 0}}function xM($){return z9.parse(JSON.parse($))}function sJ($){return JSON.stringify($)+`
199
+ `}var vM=KQ.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function BQ(){let $={};for(let Z of vM){let Q=KQ.env[Z];if(Q===void 0)continue;if(Q.startsWith("()"))continue;$[Z]=Q}return $}class HQ{constructor($){if(this._readBuffer=new JQ,this._stderrStream=null,this._serverParams=$,$.stderr==="pipe"||$.stderr==="overlapped")this._stderrStream=new fM}async start(){if(this._process)throw Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise(($,Z)=>{if(this._process=eJ.default(this._serverParams.command,this._serverParams.args??[],{env:{...BQ(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:KQ.platform==="win32",cwd:this._serverParams.cwd}),this._process.on("error",(Q)=>{Z(Q),this.onerror?.(Q)}),this._process.on("spawn",()=>{$()}),this._process.on("close",(Q)=>{this._process=void 0,this.onclose?.()}),this._process.stdin?.on("error",(Q)=>{this.onerror?.(Q)}),this._process.stdout?.on("data",(Q)=>{this._readBuffer.append(Q),this.processReadBuffer()}),this._process.stdout?.on("error",(Q)=>{this.onerror?.(Q)}),this._stderrStream&&this._process.stderr)this._process.stderr.pipe(this._stderrStream)})}get stderr(){if(this._stderrStream)return this._stderrStream;return this._process?.stderr??null}get pid(){return this._process?.pid??null}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._process){let $=this._process;this._process=void 0;let Z=new Promise((Q)=>{$.once("close",()=>{Q()})});try{$.stdin?.end()}catch{}if(await Promise.race([Z,new Promise((Q)=>setTimeout(Q,2000).unref())]),$.exitCode===null){try{$.kill("SIGTERM")}catch{}await Promise.race([Z,new Promise((Q)=>setTimeout(Q,2000).unref())])}if($.exitCode===null)try{$.kill("SIGKILL")}catch{}}this._readBuffer.clear()}send($){return new Promise((Z)=>{if(!this._process?.stdin)throw Error("Not connected");let Q=sJ($);if(this._process.stdin.write(Q))Z();else this._process.stdin.once("drain",Z)})}}var pM=1e4,cM=60000,Z3=50000;function g1($){if($.length<=Z3)return $;let Z=Math.floor(Z3/2);return`${$.slice(0,Z)}
173
200
 
174
201
  \u2026 [${$.length-Z*2} characters omitted] \u2026
175
202
 
176
- ${$.slice(-Z)}`}function l5($){try{return JSON.stringify($,null,2)}catch{return String($)}}function _J($,Z){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||Z}function YM($){if($.type==="text")return[{type:"text",text:C1($.text)}];if($.type==="image")return[{type:"image",mimeType:$.mimeType,data:$.data,evictable:!0}];if($.type==="audio")return[{type:"text",text:`[audio ${$.mimeType}, ${$.data.length.toLocaleString()} base64 characters]`}];if($.type==="resource_link")return[{type:"text",text:C1(l5({type:$.type,uri:$.uri,name:$.name,...$.description?{description:$.description}:{},...$.mimeType?{mimeType:$.mimeType}:{}}))}];let Z=$.resource;if("text"in Z)return[{type:"text",text:C1(`[resource ${Z.uri}]
177
- ${Z.text}`)}];if(Z.mimeType?.startsWith("image/"))return[{type:"image",mimeType:Z.mimeType,data:Z.blob,evictable:!0}];return[{type:"text",text:`[resource ${Z.uri}, ${Z.mimeType??"application/octet-stream"}, ${Z.blob.length.toLocaleString()} base64 characters]`}]}function GM($){let Z=$.content.flatMap(YM);if(Z.length===0&&$.structuredContent!==void 0)Z.push({type:"text",text:C1(l5($.structuredContent))});if(Z.length===0)Z.push({type:"text",text:"(no content)"});return{content:Z,...$.structuredContent!==void 0?{details:{structuredContent:$.structuredContent}}:{},...$.isError?{isError:!0}:{}}}function XM($){return typeof $==="object"&&$!==null&&Array.isArray($.content)}function xJ($){return typeof $==="number"&&Number.isFinite($)&&$>0}function JM($,Z){if(typeof $!=="object"||$===null)return;let W=$;if(typeof W.command!=="string"||W.command.trim().length===0)return;if(W.args!==void 0&&(!Array.isArray(W.args)||W.args.some((Y)=>typeof Y!=="string")))return;if(W.env!==void 0&&(typeof W.env!=="object"||W.env===null||Array.isArray(W.env)||Object.values(W.env).some((Y)=>typeof Y!=="string")))return;if(W.cwd!==void 0&&typeof W.cwd!=="string")return;if(W.startupTimeoutMs!==void 0&&!xJ(W.startupTimeoutMs))return;if(W.toolTimeoutMs!==void 0&&!xJ(W.toolTimeoutMs))return;let Q=typeof W.cwd==="string"?$M(W.cwd)?W.cwd:ZM(Z,W.cwd):void 0;return{command:W.command,...W.args?{args:W.args}:{},...W.env?{env:W.env}:{},...Q?{cwd:Q}:{},...W.startupTimeoutMs?{startupTimeoutMs:W.startupTimeoutMs}:{},...W.toolTimeoutMs?{toolTimeoutMs:W.toolTimeoutMs}:{}}}async function KM($){let Z;try{Z=await oN($,"utf8")}catch(W){if(W.code==="ENOENT")return{servers:{}};return{servers:{},error:W instanceof Error?W.message:String(W)}}try{let W=JSON.parse(Z);if(typeof W!=="object"||W===null||W.mcpServers===void 0)return{servers:{}};if(typeof W.mcpServers!=="object"||W.mcpServers===null||Array.isArray(W.mcpServers))return{servers:{},error:"mcpServers must be an object"};let Q={},Y=[];for(let[G,X]of Object.entries(W.mcpServers)){let J=JM(X,eN($));if(J)Q[G]=J;else Y.push(G)}return{servers:Q,...Y.length>0?{error:`invalid MCP server config${Y.length===1?"":"s"}: ${Y.join(", ")}`}:{}}}catch(W){return{servers:{},error:W instanceof Error?W.message:String(W)}}}async function BM($={}){let Z=[$.userFile??bJ(sN(),".mu","config.json"),...$.projectDir?[bJ($.projectDir,".mu","config.json")]:[]],W={},Q=[];for(let Y of Z){let G=await KM(Y);if(Object.assign(W,G.servers),G.error)Q.push({file:Y,message:G.error})}return{servers:W,errors:Q}}async function HM($,Z,W){let Q=[],Y;do{let G=await $.listResources(Y?{cursor:Y}:void 0,{signal:Z,timeout:W});Q.push(...G.resources),Y=G.nextCursor}while(Y);return Q}function zM($){let Z=[];return{name:"mcp",activate:async(W)=>{let Q=new Set;for(let[Y,G]of Object.entries($)){let X=_J(Y,"server"),J=new kW({name:"mu",version:"0.0.1"}),K=new iW({command:G.command,...G.args?{args:G.args}:{},env:{...dW(),...G.env??{}},...G.cwd?{cwd:G.cwd}:{},stderr:"pipe"});K.stderr?.on("data",(L)=>{let U=String(L).trim();if(U)W.log(`${Y}: ${U}`)});try{await J.connect(K,{timeout:G.startupTimeoutMs??WM})}catch(L){await K.close().catch(()=>{}),W.log(`could not connect ${Y}: ${L instanceof Error?L.message:String(L)}`);continue}Z.push(J);let H=G.toolTimeoutMs??QM,V=[],z;try{do{let L=await J.listTools(z?{cursor:z}:void 0,{timeout:H});V.push(...L.tools),z=L.nextCursor}while(z)}catch(L){Z.pop(),await J.close().catch(()=>{}),W.log(`could not discover tools from ${Y}: ${L instanceof Error?L.message:String(L)}`);continue}for(let L of V){let U=`mcp_${X}_${_J(L.name,"tool")}`,A=2;while(Q.has(U))U=`${U}_${A++}`;Q.add(U),W.registerTool({name:U,description:L.description??`Run the ${L.name} tool provided by the ${Y} MCP server.`,inputSchema:L.inputSchema,...L.annotations?.readOnlyHint&&!L.annotations.destructiveHint?{isConcurrencySafe:()=>!0}:{},execute:async(q,O,j,P)=>{try{let N=await J.callTool({name:L.name,arguments:O},void 0,{signal:j,timeout:H,resetTimeoutOnProgress:!0,maxTotalTimeout:H,onprogress:({progress:x,total:m})=>{P?.([{type:"text",text:`mcp progress ${x}${m===void 0?"":`/${m}`}`}])}});if(!XM(N))return{content:[{type:"text",text:C1(l5(N.toolResult))}]};return GM(N)}catch(N){return S(`MCP tool ${Y}/${L.name} failed: ${N instanceof Error?N.message:String(N)}`)}}})}if(!J.getServerCapabilities()?.resources)continue;let F=`mcp_${X}_resources_list`;if(!Q.has(F))Q.add(F),W.registerTool({name:F,description:`List resources exposed by the ${Y} MCP server.`,inputSchema:{type:"object",properties:{},additionalProperties:!1},isConcurrencySafe:()=>!0,execute:async(L,U,A)=>{try{return{content:[{type:"text",text:C1(l5(await HM(J,A,H)))}]}}catch(q){return S(`Could not list MCP resources from ${Y}: ${q instanceof Error?q.message:String(q)}`)}}});let D=`mcp_${X}_resource_read`;if(!Q.has(D))Q.add(D),W.registerTool({name:D,description:`Read a resource exposed by the ${Y} MCP server.`,inputSchema:{type:"object",properties:{uri:{type:"string",description:"Resource URI to read"}},required:["uri"],additionalProperties:!1},isConcurrencySafe:()=>!0,execute:async(L,U,A)=>{if(typeof U.uri!=="string"||U.uri.length===0)return S("uri must be a non-empty string");try{let q=await J.readResource({uri:U.uri},{signal:A,timeout:H}),O=[];for(let j of q.contents){if("text"in j){O.push({type:"text",text:C1(`[resource ${j.uri}]
178
- ${j.text}`)});continue}if(j.mimeType?.startsWith("image/")){O.push({type:"image",mimeType:j.mimeType,data:j.blob,evictable:!0});continue}O.push({type:"text",text:`[resource ${j.uri}, ${j.mimeType??"application/octet-stream"}, ${j.blob.length.toLocaleString()} base64 characters]`})}return{content:O.length>0?O:[{type:"text",text:"(empty)"}]}}catch(q){return S(`Could not read MCP resource ${U.uri}: ${q instanceof Error?q.message:String(q)}`)}}})}},deactivate:async()=>{await Promise.allSettled(Z.splice(0).map((W)=>W.close()))}}}async function nW($,Z,W={}){let Q=await $.contextMessages?.()??[];return{...W,model:W.model??Z,systemPrompt:W.systemPrompt??$.promptFor(Z),tools:[...$.toolset,...W.tools??[]],permissions:[...$.permissionDefaults,...W.permissions??[]],...Q.length>0?{initialMessages:Q}:{},...$.refreshContext?{refreshContext:$.refreshContext}:{},...$.carryoverExtractor?{carryoverExtractor:$.carryoverExtractor}:{},...W.runtime??$.runtime?{runtime:W.runtime??$.runtime}:{},...W.checkpointProvider??$.checkpointProvider?{checkpointProvider:W.checkpointProvider??$.checkpointProvider}:{}}}async function VM($,Z={},W=(Q)=>import(Q)){let Q=await W($),Y=Q.default??Q.profile??Q.codingProfile;if(typeof Y==="function")return await Y(Z);if(Y&&typeof Y==="object"&&"toolset"in Y)return Y;throw Error(`Module "${$}" does not export a profile`)}async function FM($,Z,W){let Q=Bun.spawn(["sh","-c",$],{stdin:new TextEncoder().encode(Z),stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>Q.kill(),W);try{let[G,X,J]=await Promise.all([new Response(Q.stdout).text(),new Response(Q.stderr).text(),Q.exited]);return{exitCode:J,stdout:G,stderr:X}}finally{clearTimeout(Y)}}function fJ($,Z){if(!$||$==="*")return!0;let W=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${W}$`).test(Z)}function aW($){let Z=$.trim();if(!Z.startsWith("{"))return;try{return JSON.parse(Z)}catch{return}}function DM($,Z=FM){let W=(Q)=>$.filter((Y)=>Y.event===Q);return{name:"shell-hooks",activate(Q){let Y=W("PreToolUse");if(Y.length>0)Q.onToolCall(async(J)=>{for(let K of Y){if(!fJ(K.matcher,J.toolName))continue;let H=JSON.stringify({event:"PreToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_input:J.args}),V=await Z(K.command,H,K.timeoutMs??30000),z=aW(V.stdout);if(V.exitCode===2)return{block:!0,reason:(typeof z?.reason==="string"?z.reason:void 0)??V.stderr.trim()??`Blocked by ${K.command}`};if(V.exitCode===0&&z?.tool_input&&typeof z.tool_input==="object")return{args:z.tool_input}}return});let G=W("PostToolUse");if(G.length>0)Q.onToolResult(async(J)=>{for(let K of G){if(!fJ(K.matcher,J.toolName))continue;let H=J.result.content.filter((D)=>D.type==="text").map((D)=>D.text).join(`
179
- `),V=JSON.stringify({event:"PostToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_output:H,is_error:J.isError}),z=await Z(K.command,V,K.timeoutMs??30000),F=aW(z.stdout);if(typeof F?.tool_output==="string")return{content:[{type:"text",text:F.tool_output}]}}return});let X=W("UserPromptSubmit");if(X.length>0)Q.onInput(async(J)=>{for(let K of X){let H=await Z(K.command,JSON.stringify({event:"UserPromptSubmit",prompt:J}),K.timeoutMs??30000);if(H.exitCode===2)return{consume:!0};let V=aW(H.stdout);if(typeof V?.prompt==="string")return{text:V.prompt}}return});for(let J of["SessionStart","Stop"]){let K=W(J);if(K.length===0)continue;let H=J==="SessionStart"?"session_start":"agent_end";Q.on(H,()=>{for(let V of K)Z(V.command,JSON.stringify({event:J}),V.timeoutMs??30000)})}}}}import{readdir as LM,readFile as UM,stat as AM}from"fs/promises";import{homedir as qM}from"os";import{basename as OM,join as p5}from"path";async function rW($){try{let Z=await UM(p5($,"SKILL.md"),"utf8"),{meta:W,body:Q}=pZ(Z),Y=typeof W.name==="string"&&W.name?W.name:OM($),G=typeof W.description==="string"&&W.description?W.description:`The ${Y} skill`;return{name:Y,description:G,body:Q,directory:$}}catch{return}}async function NM($){let Z=[];for(let W of $){let Q;try{Q=await LM(W)}catch{continue}for(let Y of Q.sort()){let G=p5(W,Y);try{if(!(await AM(G)).isDirectory())continue}catch{continue}let X=await rW(G);if(X)Z.push(X)}}return Z}function MM($){let Z=[p5(qM(),".mu","skills")];if($)Z.push(p5($,".mu","skills"));return Z}function vJ($){if($.length===0)return"";return`Available skills (load one with the skill tool when it is relevant):
180
- ${$.map((W)=>`- ${W.name}: ${W.description}`).join(`
181
- `)}`}function jM($){return{name:"skills",activate(Z){if($.length===0)return;let W=new Map($.map((Q)=>[Q.name,Q]));Z.registerTool({name:"skill",description:`Load the full instructions for a skill. ${vJ($)}`,inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill to load"}},required:["name"]},isConcurrencySafe:()=>!0,execute:async(Q,Y)=>{let G=Y.name??"",X=W.get(G),J=X?await rW(X.directory)??X:void 0;if(!J)return{content:[{type:"text",text:`No such skill: ${G}. Available: ${[...W.keys()].join(", ")}`}],isError:!0};return{content:[{type:"text",text:`Skill "${J.name}" (files are in ${J.directory}):
182
-
183
- ${J.body}`}],details:{skill:J.name}}}}),Z.onContext((Q)=>Q),Z.log(`loaded ${$.length} skill(s)`)}}}import{z as PM}from"zod";function wM($){return typeof $==="string"?{content:[{type:"text",text:$}]}:$}function d($){let Z=PM.toJSONSchema($.inputSchema,{io:"input"});return{name:$.name,description:$.description,inputSchema:Z,...$.isConcurrencySafe?{isConcurrencySafe:$.isConcurrencySafe}:{},...$.executionMode?{executionMode:$.executionMode}:{},...$.changesState!==void 0?{changesState:$.changesState}:{},...$.permissionDetails?{permissionDetails:async(W)=>{let Q=$.inputSchema.safeParse(W);return Q.success?$.permissionDetails?.(Q.data):void 0}}:{},execute:async(W,Q,Y,G)=>{let X=$.inputSchema.safeParse(Q);if(!X.success){let K=X.error.issues.map((H)=>`${H.path.join(".")||"(root)"}: ${H.message}`).join("; ");return S(`Invalid arguments for ${$.name}: ${K}`)}let J=(K)=>G?.([{type:"text",text:K}]);return wM(await $.execute(X.data,{toolCallId:W,signal:Y,update:J}))}}}import{z as VZ}from"zod";function zZ($,Z={}){if((Z.platform??process.platform)==="win32")return["powershell.exe","-NoLogo","-NoProfile",...Z.interactive?[]:["-NonInteractive"],"-Command",$];return["bash","-c",$]}function gJ($){return["taskkill.exe","/PID",String($),"/T","/F"]}function c5($,Z){try{$.kill(Z)}catch{}}function y1($,Z,W=globalThis.process.platform){if(W!=="win32"){try{globalThis.process.kill(-$.pid,Z)}catch{c5($,Z)}return}try{Bun.spawn(gJ($.pid),{stdin:"ignore",stdout:"ignore",stderr:"ignore",windowsHide:!0}).exited.then((Y)=>{if(Y!==0&&$.exitCode===null)c5($,Z)}).catch(()=>c5($,Z))}catch{c5($,Z)}}function T0($,Z=30000,W=1000){let Q=$.split(`
184
- `);if($.length<=Z&&Q.length<=W)return{text:$,truncated:!1};if(Q.length>W){let Y=Q.slice(0,Math.floor(W/2)),G=Q.slice(-Math.floor(W/2)),X=Q.length-Y.length-G.length,J=`${Y.join(`
203
+ ${$.slice(-Z)}`}function Q6($){try{return JSON.stringify($,null,2)}catch{return String($)}}function Q3($,Z){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||Z}function dM($){if($.type==="text")return[{type:"text",text:g1($.text)}];if($.type==="image")return[{type:"image",mimeType:$.mimeType,data:$.data,evictable:!0}];if($.type==="audio")return[{type:"text",text:`[audio ${$.mimeType}, ${$.data.length.toLocaleString()} base64 characters]`}];if($.type==="resource_link")return[{type:"text",text:g1(Q6({type:$.type,uri:$.uri,name:$.name,...$.description?{description:$.description}:{},...$.mimeType?{mimeType:$.mimeType}:{}}))}];let Z=$.resource;if("text"in Z)return[{type:"text",text:g1(`[resource ${Z.uri}]
204
+ ${Z.text}`)}];if(Z.mimeType?.startsWith("image/"))return[{type:"image",mimeType:Z.mimeType,data:Z.blob,evictable:!0}];return[{type:"text",text:`[resource ${Z.uri}, ${Z.mimeType??"application/octet-stream"}, ${Z.blob.length.toLocaleString()} base64 characters]`}]}function iM($){let Z=$.content.flatMap(dM);if(Z.length===0&&$.structuredContent!==void 0)Z.push({type:"text",text:g1(Q6($.structuredContent))});if(Z.length===0)Z.push({type:"text",text:"(no content)"});return{content:Z,...$.structuredContent!==void 0?{details:{structuredContent:$.structuredContent}}:{},...$.isError?{isError:!0}:{}}}function nM($){return typeof $==="object"&&$!==null&&Array.isArray($.content)}function W3($){return typeof $==="number"&&Number.isFinite($)&&$>0}function aM($,Z){if(typeof $!=="object"||$===null)return;let Q=$;if(typeof Q.command!=="string"||Q.command.trim().length===0)return;if(Q.args!==void 0&&(!Array.isArray(Q.args)||Q.args.some((Y)=>typeof Y!=="string")))return;if(Q.env!==void 0&&(typeof Q.env!=="object"||Q.env===null||Array.isArray(Q.env)||Object.values(Q.env).some((Y)=>typeof Y!=="string")))return;if(Q.cwd!==void 0&&typeof Q.cwd!=="string")return;if(Q.startupTimeoutMs!==void 0&&!W3(Q.startupTimeoutMs))return;if(Q.toolTimeoutMs!==void 0&&!W3(Q.toolTimeoutMs))return;let W=typeof Q.cwd==="string"?mM(Q.cwd)?Q.cwd:lM(Z,Q.cwd):void 0;return{command:Q.command,...Q.args?{args:Q.args}:{},...Q.env?{env:Q.env}:{},...W?{cwd:W}:{},...Q.startupTimeoutMs?{startupTimeoutMs:Q.startupTimeoutMs}:{},...Q.toolTimeoutMs?{toolTimeoutMs:Q.toolTimeoutMs}:{}}}async function rM($){let Z;try{Z=await gM($,"utf8")}catch(Q){if(Q.code==="ENOENT")return{servers:{}};return{servers:{},error:Q instanceof Error?Q.message:String(Q)}}try{let Q=JSON.parse(Z);if(typeof Q!=="object"||Q===null||Q.mcpServers===void 0)return{servers:{}};if(typeof Q.mcpServers!=="object"||Q.mcpServers===null||Array.isArray(Q.mcpServers))return{servers:{},error:"mcpServers must be an object"};let W={},Y=[];for(let[G,X]of Object.entries(Q.mcpServers)){let J=aM(X,uM($));if(J)W[G]=J;else Y.push(G)}return{servers:W,...Y.length>0?{error:`invalid MCP server config${Y.length===1?"":"s"}: ${Y.join(", ")}`}:{}}}catch(Q){return{servers:{},error:Q instanceof Error?Q.message:String(Q)}}}async function tM($={}){let Z=[$.userFile??$3(hM(),".mu","config.json"),...$.projectDir?[$3($.projectDir,".mu","config.json")]:[]],Q={},W=[];for(let Y of Z){let G=await rM(Y);if(Object.assign(Q,G.servers),G.error)W.push({file:Y,message:G.error})}return{servers:Q,errors:W}}async function oM($,Z,Q){let W=[],Y;do{let G=await $.listResources(Y?{cursor:Y}:void 0,{signal:Z,timeout:Q});W.push(...G.resources),Y=G.nextCursor}while(Y);return W}function sM($){let Z=[];return{name:"mcp",activate:async(Q)=>{let W=new Set;for(let[Y,G]of Object.entries($)){let X=Q3(Y,"server"),J=new o4({name:"mu",version:"0.0.1"}),K=new HQ({command:G.command,...G.args?{args:G.args}:{},env:{...BQ(),...G.env??{}},...G.cwd?{cwd:G.cwd}:{},stderr:"pipe"});K.stderr?.on("data",(L)=>{let U=String(L).trim();if(U)Q.log(`${Y}: ${U}`)});try{await J.connect(K,{timeout:G.startupTimeoutMs??pM})}catch(L){await K.close().catch(()=>{}),Q.log(`could not connect ${Y}: ${L instanceof Error?L.message:String(L)}`);continue}Z.push(J);let B=G.toolTimeoutMs??cM,z=[],V;try{do{let L=await J.listTools(V?{cursor:V}:void 0,{timeout:B});z.push(...L.tools),V=L.nextCursor}while(V)}catch(L){Z.pop(),await J.close().catch(()=>{}),Q.log(`could not discover tools from ${Y}: ${L instanceof Error?L.message:String(L)}`);continue}for(let L of z){let U=`mcp_${X}_${Q3(L.name,"tool")}`,q=2;while(W.has(U))U=`${U}_${q++}`;W.add(U),Q.registerTool({name:U,description:L.description??`Run the ${L.name} tool provided by the ${Y} MCP server.`,inputSchema:L.inputSchema,...L.annotations?.readOnlyHint&&!L.annotations.destructiveHint?{isConcurrencySafe:()=>!0}:{},execute:async(A,N,j,P)=>{try{let O=await J.callTool({name:L.name,arguments:N},void 0,{signal:j,timeout:B,resetTimeoutOnProgress:!0,maxTotalTimeout:B,onprogress:({progress:C,total:v})=>{P?.([{type:"text",text:`mcp progress ${C}${v===void 0?"":`/${v}`}`}])}});if(!nM(O))return{content:[{type:"text",text:g1(Q6(O.toolResult))}]};return iM(O)}catch(O){return y(`MCP tool ${Y}/${L.name} failed: ${O instanceof Error?O.message:String(O)}`)}}})}if(!J.getServerCapabilities()?.resources)continue;let F=`mcp_${X}_resources_list`;if(!W.has(F))W.add(F),Q.registerTool({name:F,description:`List resources exposed by the ${Y} MCP server.`,inputSchema:{type:"object",properties:{},additionalProperties:!1},isConcurrencySafe:()=>!0,execute:async(L,U,q)=>{try{return{content:[{type:"text",text:g1(Q6(await oM(J,q,B)))}]}}catch(A){return y(`Could not list MCP resources from ${Y}: ${A instanceof Error?A.message:String(A)}`)}}});let D=`mcp_${X}_resource_read`;if(!W.has(D))W.add(D),Q.registerTool({name:D,description:`Read a resource exposed by the ${Y} MCP server.`,inputSchema:{type:"object",properties:{uri:{type:"string",description:"Resource URI to read"}},required:["uri"],additionalProperties:!1},isConcurrencySafe:()=>!0,execute:async(L,U,q)=>{if(typeof U.uri!=="string"||U.uri.length===0)return y("uri must be a non-empty string");try{let A=await J.readResource({uri:U.uri},{signal:q,timeout:B}),N=[];for(let j of A.contents){if("text"in j){N.push({type:"text",text:g1(`[resource ${j.uri}]
205
+ ${j.text}`)});continue}if(j.mimeType?.startsWith("image/")){N.push({type:"image",mimeType:j.mimeType,data:j.blob,evictable:!0});continue}N.push({type:"text",text:`[resource ${j.uri}, ${j.mimeType??"application/octet-stream"}, ${j.blob.length.toLocaleString()} base64 characters]`})}return{content:N.length>0?N:[{type:"text",text:"(empty)"}]}}catch(A){return y(`Could not read MCP resource ${U.uri}: ${A instanceof Error?A.message:String(A)}`)}}})}},deactivate:async()=>{await Promise.allSettled(Z.splice(0).map((Q)=>Q.close()))}}}async function VQ($,Z,Q={}){let W=await $.contextMessages?.()??[];return{...Q,model:Q.model??Z,systemPrompt:Q.systemPrompt??$.promptFor(Z),tools:[...$.toolset,...Q.tools??[]],permissions:[...$.permissionDefaults,...Q.permissions??[]],...W.length>0?{initialMessages:W}:{},...$.refreshContext?{refreshContext:$.refreshContext}:{},...$.carryoverExtractor?{carryoverExtractor:$.carryoverExtractor}:{},...Q.runtime??$.runtime?{runtime:Q.runtime??$.runtime}:{},...Q.checkpointProvider??$.checkpointProvider?{checkpointProvider:Q.checkpointProvider??$.checkpointProvider}:{}}}async function eM($,Z={},Q=(W)=>import(W)){let W=await Q($),Y=W.default??W.profile??W.codingProfile;if(typeof Y==="function")return await Y(Z);if(Y&&typeof Y==="object"&&"toolset"in Y)return Y;throw Error(`Module "${$}" does not export a profile`)}async function $j($,Z,Q){let W=Bun.spawn(["sh","-c",$],{stdin:new TextEncoder().encode(Z),stdout:"pipe",stderr:"pipe"}),Y=setTimeout(()=>W.kill(),Q);try{let[G,X,J]=await Promise.all([new Response(W.stdout).text(),new Response(W.stderr).text(),W.exited]);return{exitCode:J,stdout:G,stderr:X}}finally{clearTimeout(Y)}}function Y3($,Z){if(!$||$==="*")return!0;let Q=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${Q}$`).test(Z)}function zQ($){let Z=$.trim();if(!Z.startsWith("{"))return;try{return JSON.parse(Z)}catch{return}}function Zj($,Z=$j){let Q=(W)=>$.filter((Y)=>Y.event===W);return{name:"shell-hooks",activate(W){let Y=Q("PreToolUse");if(Y.length>0)W.onToolCall(async(J)=>{for(let K of Y){if(!Y3(K.matcher,J.toolName))continue;let B=JSON.stringify({event:"PreToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_input:J.args}),z=await Z(K.command,B,K.timeoutMs??30000),V=zQ(z.stdout);if(z.exitCode===2)return{block:!0,reason:(typeof V?.reason==="string"?V.reason:void 0)??z.stderr.trim()??`Blocked by ${K.command}`};if(z.exitCode===0&&V?.tool_input&&typeof V.tool_input==="object")return{args:V.tool_input}}return});let G=Q("PostToolUse");if(G.length>0)W.onToolResult(async(J)=>{for(let K of G){if(!Y3(K.matcher,J.toolName))continue;let B=J.result.content.filter((D)=>D.type==="text").map((D)=>D.text).join(`
206
+ `),z=JSON.stringify({event:"PostToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_output:B,is_error:J.isError}),V=await Z(K.command,z,K.timeoutMs??30000),F=zQ(V.stdout);if(typeof F?.tool_output==="string")return{content:[{type:"text",text:F.tool_output}]}}return});let X=Q("UserPromptSubmit");if(X.length>0)W.onInput(async(J)=>{for(let K of X){let B=await Z(K.command,JSON.stringify({event:"UserPromptSubmit",prompt:J}),K.timeoutMs??30000);if(B.exitCode===2)return{consume:!0};let z=zQ(B.stdout);if(typeof z?.prompt==="string")return{text:z.prompt}}return});for(let J of["SessionStart","Stop"]){let K=Q(J);if(K.length===0)continue;let B=J==="SessionStart"?"session_start":"agent_end";W.on(B,()=>{for(let z of K)Z(z.command,JSON.stringify({event:J}),z.timeoutMs??30000)})}}}}import{readdir as Qj,readFile as Wj,stat as Yj}from"fs/promises";import{homedir as Gj}from"os";import{basename as Xj,join as W6}from"path";async function FQ($){try{let Z=await Wj(W6($,"SKILL.md"),"utf8"),{meta:Q,body:W}=W5(Z),Y=typeof Q.name==="string"&&Q.name?Q.name:Xj($),G=typeof Q.description==="string"&&Q.description?Q.description:`The ${Y} skill`;return{name:Y,description:G,body:W,directory:$}}catch{return}}async function Jj($){let Z=[];for(let Q of $){let W;try{W=await Qj(Q)}catch{continue}for(let Y of W.sort()){let G=W6(Q,Y);try{if(!(await Yj(G)).isDirectory())continue}catch{continue}let X=await FQ(G);if(X)Z.push(X)}}return Z}function Kj($){let Z=[W6(Gj(),".mu","skills")];if($)Z.push(W6($,".mu","skills"));return Z}function G3($){if($.length===0)return"";return`Available skills (load one with the skill tool when it is relevant):
207
+ ${$.map((Q)=>`- ${Q.name}: ${Q.description}`).join(`
208
+ `)}`}function Bj($){return{name:"skills",activate(Z){if($.length===0)return;let Q=new Map($.map((W)=>[W.name,W]));Z.registerTool({name:"skill",description:`Load the full instructions for a skill. ${G3($)}`,inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill to load"}},required:["name"]},isConcurrencySafe:()=>!0,execute:async(W,Y)=>{let G=Y.name??"",X=Q.get(G),J=X?await FQ(X.directory)??X:void 0;if(!J)return{content:[{type:"text",text:`No such skill: ${G}. Available: ${[...Q.keys()].join(", ")}`}],isError:!0};return{content:[{type:"text",text:`Skill "${J.name}" (files are in ${J.directory}):
209
+
210
+ ${J.body}`}],details:{skill:J.name}}}}),Z.onContext((W)=>W),Z.log(`loaded ${$.length} skill(s)`)}}}import{z as Hj}from"zod";function Vj($){return typeof $==="string"?{content:[{type:"text",text:$}]}:$}function n($){let Z=Hj.toJSONSchema($.inputSchema,{io:"input"}),Q=(W)=>{let Y=W;if($.coerceInput)try{Y=$.coerceInput(W)}catch{Y=W}return $.inputSchema.safeParse(Y)};return{name:$.name,description:$.description,inputSchema:Z,...$.isConcurrencySafe?{isConcurrencySafe:$.isConcurrencySafe}:{},...$.executionMode?{executionMode:$.executionMode}:{},...$.changesState!==void 0?{changesState:$.changesState}:{},...$.permissionScope?{permissionScope:(W)=>{let Y=Q(W);return Y.success?$.permissionScope?.(Y.data)??$.name:$.name}}:{},...$.permissionPattern?{permissionPattern:(W)=>{let Y=Q(W);return Y.success?$.permissionPattern?.(Y.data)??JSON.stringify(W):JSON.stringify(W)}}:{},...$.permissionDetails?{permissionDetails:async(W)=>{let Y=Q(W);return Y.success?$.permissionDetails?.(Y.data):void 0}}:{},execute:async(W,Y,G,X)=>{let J=Q(Y);if(!J.success){let B=J.error.issues.map((z)=>`${z.path.join(".")||"(root)"}: ${z.message}`).join("; ");return y(`Invalid arguments for ${$.name}: ${B}`)}let K=(B)=>X?.([{type:"text",text:B}]);return Vj(await $.execute(J.data,{toolCallId:W,signal:G,update:K}))}}}function Y6($,Z="text"){let Q=Math.max(0,...[...$.matchAll(/`+/g)].map((Y)=>Y[0].length)),W="`".repeat(Math.max(3,Q+1));return`${W}${Z}
211
+ ${$}
212
+ ${W}`}function X3($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;")}function G6($){let Z=new Date($);return Number.isNaN(Z.getTime())?"":`_${Z.toISOString()}_
213
+ `}function J3($){return`> [Image omitted from text export: ${$}]`}function K3($){return $.content.map((Z)=>Z.type==="text"?Z.text:J3(Z.mimeType))}function zj($){return["## User",G6($.timestamp),...K3($)].filter(Boolean).join(`
214
+ `)}function Fj($){let Z=$.content.map((Q)=>{if(Q.type==="text")return Q.text;if(Q.type==="thinking")return["<details>","<summary>Thinking</summary>","",Q.thinking,"","</details>"].join(`
215
+ `);return["<details>",`<summary>Tool call: <code>${X3(Q.name)}</code></summary>`,"",Y6(JSON.stringify(Q.arguments,null,2)??"null","json"),"","</details>"].join(`
216
+ `)});if($.errorMessage)Z.push(`> Error: ${$.errorMessage}`);return["## Mu",G6($.timestamp),...Z].filter(Boolean).join(`
217
+ `)}function Dj($){let Z=$.content.map((W)=>W.type==="text"?W.text:J3(W.mimeType)).join(`
218
+ `),Q=$.details===void 0?[]:["","**Details**","",Y6(JSON.stringify($.details,null,2)??"null","json")];return["<details>",`<summary>Tool result: <code>${X3($.toolName)}</code>${$.isError?" (error)":""}</summary>`,"",G6($.timestamp),Y6(Z||"(no output)"),...Q,"","</details>"].filter(Boolean).join(`
219
+ `)}function Lj($){let Z=$.customType.replaceAll(/[^\p{L}\p{N} _-]/gu,"").trim();return[`## ${$.customType==="user_shell_command"?"User shell":Z||"Context"}`,G6($.timestamp),...K3($).map((W)=>Y6(W))].filter(Boolean).join(`
220
+ `)}function Uj($){return $.role!=="custom"||$.display===!0||$.customType==="user_shell_command"}function qj($){if($.role==="user")return zj($);if($.role==="assistant")return Fj($);if($.role==="toolResult")return Dj($);return Lj($)}function Aj($,Z={}){let Q=$.activePath().filter((X)=>X.type==="message").map((X)=>X.message).filter(Uj),W=Z.exportedAt??new Date,Y=[Z.sessionId?`- Session: \`${Z.sessionId}\``:void 0,Z.model?`- Model: \`${Z.model}\``:void 0,`- Exported: ${W.toISOString()}`].filter((X)=>X!==void 0),G=Q.map(qj);return{markdown:["# Mu chat transcript","",...Y,...G.length>0?["",G.join(`
221
+
222
+ `)]:[],""].join(`
223
+ `),messageCount:Q.length}}import{z as wZ}from"zod";function q$($,Z={}){if((Z.platform??process.platform)==="win32")return["powershell.exe","-NoLogo","-NoProfile",...Z.interactive?[]:["-NonInteractive"],"-Command",$];return["bash","-c",$]}function B3($){return["taskkill.exe","/PID",String($),"/T","/F"]}function X6($,Z){try{$.kill(Z)}catch{}}function e0($,Z,Q=globalThis.process.platform){if(Q!=="win32"){try{globalThis.process.kill(-$.pid,Z)}catch{X6($,Z)}return}try{Bun.spawn(B3($.pid),{stdin:"ignore",stdout:"ignore",stderr:"ignore",windowsHide:!0}).exited.then((Y)=>{if(Y!==0&&$.exitCode===null)X6($,Z)}).catch(()=>X6($,Z))}catch{X6($,Z)}}var Nj=new Set(["base64","cat","cd","cut","echo","expr","false","grep","head","id","ls","nl","paste","pwd","rev","seq","stat","tail","tr","true","uname","uniq","wc","which","whoami"]),Oj=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),Mj=["--hostname-bin","--pre"],jj=["-C","-c","-p","--config-env","--exec-path","--git-dir","--namespace","--paginate","--super-prefix","--work-tree"],Pj=["--exec","--ext-diff","--output","--textconv"];function wj($){return($.split(/[\\/]/).at(-1)?.toLowerCase()??$.toLowerCase()).replace(/\.(?:exe|cmd|bat|com)$/i,"")}function Tj($,Z){if($===Z||$.startsWith(`${Z}=`))return!0;return Z.length===2&&$.startsWith(Z)&&$.length>Z.length}function J6($,Z){return $.some((Q)=>Z.some((W)=>Tj(Q,W)))}function Ij($){let Z=[],Q=-1,W=!1;for(let X=1;X<$.length;X++){let J=$[X]??"";if(W){Z.push(J),W=!1;continue}if(J==="--")return!1;if(J.startsWith("-")){if(Z.push(J),["-C","-c","--config-env","--exec-path","--git-dir","--namespace","--super-prefix","--work-tree"].includes(J))W=!0;continue}Q=X;break}if(Q===-1||J6(Z,jj))return!1;let Y=$[Q]?.toLowerCase(),G=$.slice(Q+1);if(!Y||!["branch","diff","log","show","status"].includes(Y))return!1;if(J6(G,Pj))return!1;if(Y!=="branch")return!0;if(G.length===0)return!0;return G.every((X)=>["--all","--list","--remotes","--show-current","--verbose","-a","-l","-r","-v","-vv"].includes(X)||X.startsWith("--format="))}function Ej($){let Z=$[0]??"";if(Z.includes("/")||Z.includes("\\"))return!1;let Q=wj(Z);if(Nj.has(Q)){if(Q!=="base64")return!0;return!J6($.slice(1),["-o","--output"])}if(Q==="find")return!$.slice(1).some((W)=>Oj.has(W));if(Q==="rg")return!$.slice(1).some((W)=>W==="-z"||W==="--search-zip")&&!J6($.slice(1),Mj);if(Q==="git")return Ij($);if(Q==="sed")return $.length>=3&&$.length<=4&&$[1]==="-n"&&/^(?:\d+,)?\d+p$/.test($[2]??"");return process.platform==="linux"&&(Q==="numfmt"||Q==="tac")}function H3($){let Z=[],Q=[],W="",Y=!1,G,X=!1,J=()=>{if(!Y)return;Q.push(W),W="",Y=!1},K=()=>{if(J(),Q.length===0)return!1;return Z.push(Q),Q=[],!0};for(let B=0;B<$.length;B++){let z=$[B]??"";if(G==="single"){if(z==="'")G=void 0;else W+=z;continue}if(G==="double"){if(z==='"')G=void 0;else if(z==="$"||z==="`")return;else if(z==="\\"&&process.platform!=="win32"){let V=$[++B];if(V===void 0)return;if(V!==`
224
+ `)W+=V}else W+=z;continue}if(z==="'"||z==='"'){G=z==="'"?"single":"double",Y=!0,X=!1;continue}if(z==="\\"&&process.platform!=="win32"){let V=$[++B];if(V===void 0)return;if(V!==`
225
+ `)Y=!0,W+=V,X=!1;continue}if(z==="$"||z==="`"||"<>(){}".includes(z))return;if(z==="#"&&!Y)return;if(z===`
226
+ `||z==="\r"){if(z==="\r"&&$[B+1]===`
227
+ `)B++;if(!K())return;X=!0;continue}if(/\s/.test(z)){J();continue}if(z===";"){if(!K())return;X=!0;continue}if(z==="&"){if($[B+1]!=="&"||!K())return;B++,X=!1;continue}if(z==="|"){let V=$[B+1]==="|";if(!K())return;if(V)B++;X=!1;continue}Y=!0,W+=z,X=!1}if(G)return;if(J(),Q.length>0)Z.push(Q);return Z.length>0&&(Q.length>0||X)?Z:void 0}function V3($){let Z=H3($);return Z?.length&&Z.every(Ej)?"inspect":"other"}function PZ($){return V3($)==="inspect"}function R0($,Z=30000,Q=1000){let W=$.split(`
228
+ `);if($.length<=Z&&W.length<=Q)return{text:$,truncated:!1};if(W.length>Q){let Y=W.slice(0,Math.floor(Q/2)),G=W.slice(-Math.floor(Q/2)),X=W.length-Y.length-G.length,J=`${Y.join(`
185
229
  `)}
186
230
 
187
231
  \u2026 [${X} lines omitted] \u2026
188
232
 
189
233
  ${G.join(`
190
- `)}`;return{text:J.length>Z?hJ(J,Z):J,truncated:!0}}return{text:hJ($,Z),truncated:!0}}function hJ($,Z){let W=Math.floor(Z/2),Q=$.length-W*2;return`${$.slice(0,W)}
234
+ `)}`;return{text:J.length>Z?z3(J,Z):J,truncated:!0}}return{text:z3($,Z),truncated:!0}}function z3($,Z){let Q=Math.floor(Z/2),W=$.length-Q*2;return`${$.slice(0,Q)}
191
235
 
192
- \u2026 [${Q} characters omitted] \u2026
236
+ \u2026 [${W} characters omitted] \u2026
193
237
 
194
- ${$.slice(-W)}`}function I0($,Z){return $.truncated?`${$.text}
238
+ ${$.slice(-Q)}`}function C0($,Z){return $.truncated?`${$.text}
195
239
 
196
- [output truncated \u2014 ${Z}. Narrow the request to see more.]`:$.text}var TM=120000,IM=600000,EM=80;async function uJ($,Z,W){let Q=$.getReader(),Y=new TextDecoder,G="";while(!0){let{done:J,value:K}=await Q.read();if(J)break;let H=Y.decode(K,{stream:!0});if(!H)continue;G+=H,W?.(H,Z)}let X=Y.decode();if(X)G+=X,W?.(X,Z);return G}async function RM($,Z,W,Q,Y){let G=Bun.spawn(zZ($),{cwd:Z,detached:!0,stdout:"pipe",stderr:"pipe",stdin:"ignore"}),X=!1,J=setTimeout(()=>{X=!0,y1(G,"SIGTERM")},Q),K=()=>y1(G,"SIGTERM");W.addEventListener("abort",K,{once:!0});try{let[H,V,z]=await Promise.all([uJ(G.stdout,"stdout",Y),uJ(G.stderr,"stderr",Y),G.exited]);return{stdout:H,stderr:V,exitCode:z,timedOut:X}}finally{clearTimeout(J),W.removeEventListener("abort",K)}}function SM($){let Z="",W,Q=!1,Y=()=>{if(W)clearTimeout(W);if(W=void 0,!Z)return;$(Z),Z=""};return{push(G,X){if(X==="stderr"&&!Q)Z+=`${Z.endsWith(`
240
+ [output truncated \u2014 ${Z}. Narrow the request to see more.]`:$.text}var Rj=120000,Cj=600000,Sj=80;async function F3($,Z,Q){let W=$.getReader(),Y=new TextDecoder,G="";while(!0){let{done:J,value:K}=await W.read();if(J)break;let B=Y.decode(K,{stream:!0});if(!B)continue;G+=B,Q?.(B,Z)}let X=Y.decode();if(X)G+=X,Q?.(X,Z);return G}async function yj($,Z,Q,W,Y){let G=Bun.spawn(q$($),{cwd:Z,detached:process.platform!=="win32",stdout:"pipe",stderr:"pipe",stdin:"ignore",windowsHide:!0}),X=!1,J=setTimeout(()=>{X=!0,e0(G,"SIGTERM")},W),K=()=>e0(G,"SIGTERM");Q.addEventListener("abort",K,{once:!0});try{let[B,z,V]=await Promise.all([F3(G.stdout,"stdout",Y),F3(G.stderr,"stderr",Y),G.exited]);return{stdout:B,stderr:z,exitCode:V,timedOut:X}}finally{clearTimeout(J),Q.removeEventListener("abort",K)}}function bj($){let Z="",Q,W=!1,Y=()=>{if(Q)clearTimeout(Q);if(Q=void 0,!Z)return;$(Z),Z=""};return{push(G,X){if(X==="stderr"&&!W)Z+=`${Z.endsWith(`
197
241
  `)||Z.length===0?"":`
198
242
  `}[stderr]
199
- `,Q=!0;Z+=G,W??=setTimeout(Y,EM)},flush:Y}}function tW($){let Z=$.spawn??RM;return d({name:"bash",changesState:!0,description:"Run a command with the platform-native shell in the session root. Use for building, testing and inspecting the project. Prefer the dedicated read/edit/grep/glob tools for file work.",inputSchema:VZ.object({command:VZ.string().describe("The shell command to run"),description:VZ.string().optional().describe("A short description of what this command does, for the user"),timeoutMs:VZ.number().int().positive().max(IM).optional(),run_in_background:VZ.boolean().optional().describe("Start the command in the background and return a task id immediately")}),execute:async({command:W,timeoutMs:Q,run_in_background:Y},{signal:G,update:X})=>{if(G.aborted)return S("Aborted before the command started.");if(Y){if(!$.processes)return S("Background execution is not available in this session.");let L=$.processes.start(W);return{content:[{type:"text",text:`Started ${L.id} in the background. Use task_output to read it, task_kill to stop it.`}],details:{taskId:L.id,command:W,background:!0}}}let J=Date.now(),K=SM(X),H;try{H=await Z(W,$.root,G,Q??TM,K.push)}finally{K.flush()}let V=Date.now()-J,z=[];if(H.stdout.trim())z.push(H.stdout.trimEnd());if(H.stderr.trim())z.push(`[stderr]
200
- ${H.stderr.trimEnd()}`);let F=I0(T0(z.join(`
201
-
202
- `)||"(no output)"),"command produced a lot of output");if(H.timedOut)return{content:[{type:"text",text:`${F}
203
-
204
- [command timed out and was killed]`}],details:{command:W,exitCode:H.exitCode,timedOut:!0,durationMs:V},isError:!0};let D=H.exitCode!==0;return{content:[{type:"text",text:D?`${F}
205
-
206
- [exit code ${H.exitCode}]`:F}],details:{command:W,exitCode:H.exitCode,durationMs:V},isError:D}}})}import{mkdir as CM,readdir as yM,readFile as d5,stat as lJ,writeFile as pJ}from"fs/promises";import{dirname as bM,isAbsolute as kM,relative as cJ,resolve as FZ}from"path";import{z as J0}from"zod";function k0($,Z){let W=kM(Z)?FZ(Z):FZ($,Z);if(cJ(FZ($),W).startsWith(".."))throw Error(`Path escapes the session root: ${Z}`);return W}function X0($,Z){let W=cJ(FZ($),Z);return W===""?".":W}function mJ($){let Z=$.split(`
207
- `);if(Z.at(-1)==="")Z.pop();return Z}function dJ($,Z,W){let Q=Z===void 0?[]:mJ(Z),Y=mJ(W),G=0;while(G<Q.length&&G<Y.length&&Q[G]===Y[G])G++;let X=0;while(X<Q.length-G&&X<Y.length-G&&Q[Q.length-1-X]===Y[Y.length-1-X])X++;let J=Q.length-G-X,K=Y.length-G-X;if(K===0&&J===0)return{path:$,added:K,removed:J,hunks:[]};let H=Math.min(3,G),V=Math.min(3,X),z=G-H,F=G-H,D=H+J+V,L=H+K+V,U=[`@@ -${Q.length===0?0:z+1},${D} +${Y.length===0?0:F+1},${L} @@`,...Q.slice(z,G).map((A)=>` ${A}`),...Q.slice(G,Q.length-X).map((A)=>`-${A}`),...Y.slice(G,Y.length-X).map((A)=>`+${A}`),...Y.slice(Y.length-X,Y.length-X+V).map((A)=>` ${A}`)];return{path:$,added:K,removed:J,hunks:U}}function oW($){return d({name:"read",description:"Read a file from the filesystem. Returns contents with line numbers for grounded path:line citations. Read a file before editing it.",inputSchema:J0.object({path:J0.string().describe("Path to the file, absolute or relative to the session root"),offset:J0.number().int().min(1).optional().describe("First line to read (1-based)"),limit:J0.number().int().min(1).optional().describe("Maximum number of lines to read")}),isConcurrencySafe:()=>!0,execute:async({path:Z,offset:W,limit:Q})=>{let Y=k0($.root,Z),G;try{G=await d5(Y,"utf8")}catch(D){let L=D.code;if(L==="ENOENT")return S(`File not found: ${X0($.root,Y)}`);if(L==="EISDIR")return S(`${X0($.root,Y)} is a directory \u2014 use ls instead.`);throw D}$.state.markRead(Y);let X=G.split(`
208
- `),J=(W??1)-1,H=X.slice(J,Q?J+Q:void 0).map((D,L)=>`${String(J+L+1).padStart(5)} ${D}`),V=I0(T0(H.join(`
209
- `)),"file is large"),z=await $.instructions?.instructionsForPath(Y);return{content:[{type:"text",text:[V||"(empty file)",z?.text].filter(Boolean).join(`
210
-
211
- `)}],details:{path:Y,lines:X.length,...z&&z.sources.length>0?{loadedInstructions:z.sources}:{}}}}})}function sW($){return d({name:"write",changesState:!0,description:"Write a complete file, creating it or replacing its contents. To change part of an existing file, prefer edit.",inputSchema:J0.object({path:J0.string().describe("Path to the file"),content:J0.string().describe("The complete file contents")}),permissionDetails:async({path:Z,content:W})=>{let Q=k0($.root,Z),Y;try{Y=await d5(Q,"utf8")}catch{Y=void 0}let G=X0($.root,Q);return{description:`${Y===void 0?"Create":"Overwrite"} ${G}`,preview:{kind:"diff",file:dJ(G,Y,W)}}},execute:async({path:Z,content:W})=>{let Q=k0($.root,Z),Y=!0;try{await lJ(Q)}catch{Y=!1}if(Y&&!$.state.hasRead(Q))return S(`Refusing to overwrite ${X0($.root,Q)} because it has not been read in this session. Read it first, then write.`);if(Y&&$.state.isStale(Q))return S(`${X0($.root,Q)} changed on disk since you read it. Read it again before writing.`);await CM(bM(Q),{recursive:!0}),await pJ(Q,W,"utf8"),$.state.markWritten(Q);let G=W.split(`
212
- `).length;return{content:[{type:"text",text:`${Y?"Updated":"Created"} ${X0($.root,Q)} (${G} lines)`}],details:{path:Q,created:!Y}}}})}function eW($){return d({name:"edit",changesState:!0,description:"Replace an exact string in a file. The old string must appear exactly once unless replaceAll is set. Read the file first.",inputSchema:J0.object({path:J0.string().describe("Path to the file"),oldString:J0.string().describe("Exact text to replace, including indentation"),newString:J0.string().describe("Replacement text"),replaceAll:J0.boolean().optional().describe("Replace every occurrence")}),permissionDetails:async({path:Z,oldString:W,newString:Q,replaceAll:Y})=>{let G=k0($.root,Z),X=X0($.root,G),J;try{J=await d5(G,"utf8")}catch{return{description:`Edit ${X}`}}let K=Y?J.split(W).join(Q):J.replace(W,Q);return{description:`Edit ${X}`,preview:{kind:"diff",file:dJ(X,J,K)}}},execute:async({path:Z,oldString:W,newString:Q,replaceAll:Y})=>{let G=k0($.root,Z);if(!$.state.hasRead(G))return S(`Read ${X0($.root,G)} before editing it, so you can see what you are changing.`);if(W===Q)return S("oldString and newString are identical \u2014 nothing to do.");let X;try{X=await d5(G,"utf8")}catch(H){if(H.code==="ENOENT")return S(`File not found: ${X0($.root,G)}`);throw H}if($.state.isStale(G))return S(`${X0($.root,G)} changed on disk since you read it. Read it again before editing.`);let J=X.split(W).length-1;if(J===0)return S(`oldString was not found in ${X0($.root,G)}. The text must match exactly, including whitespace and indentation.`);if(J>1&&!Y)return S(`oldString appears ${J} times in ${X0($.root,G)}. Include more surrounding context to make it unique, or set replaceAll.`);let K=Y?X.split(W).join(Q):X.replace(W,Q);return await pJ(G,K,"utf8"),$.state.markWritten(G),{content:[{type:"text",text:`Edited ${X0($.root,G)} (${J} replacement${J===1?"":"s"})`}],details:{path:G,occurrences:J,oldString:W,newString:Q}}}})}function $4($){return d({name:"ls",description:"List the entries of a directory.",inputSchema:J0.object({path:J0.string().optional().describe("Directory to list; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({path:Z})=>{let W=k0($.root,Z??"."),Q;try{Q=await yM(W)}catch(G){if(G.code==="ENOENT")return S(`Directory not found: ${X0($.root,W)}`);throw G}let Y=await Promise.all(Q.sort().map(async(G)=>{try{return(await lJ(FZ(W,G))).isDirectory()?`${G}/`:G}catch{return G}}));return I0(T0(Y.join(`
213
- `)||"(empty directory)"),"directory has many entries")}})}import{accessSync as aJ,constants as rJ,statSync as tJ}from"fs";import{readdir as _M,readFile as xM,stat as fM}from"fs/promises";import{dirname as Z4,relative as DZ,resolve as F1}from"path";import{z as V1}from"zod";var W4=new Set(["node_modules",".git","dist","build",".next","coverage",".venv"]),B$=200,iJ=2000000;function vM($,Z){let W=Z==="win32"?"rg.exe":"rg",Q=F1(Z4($),"..","mu-path",W);try{if(!tJ(Q).isFile())return;if(Z!=="win32")aJ(Q,rJ.X_OK);return Q}catch{return}}var gM={darwin:{arm64:"@mu-agent/ripgrep-darwin-arm64"},linux:{x64:"@mu-agent/ripgrep-linux-x64"},win32:{x64:"@mu-agent/ripgrep-windows-x64"}};function oJ($=process.platform,Z=process.arch,W=process.argv[1]?Z4(F1(process.argv[1])):process.cwd(),Q=(Y,G)=>Bun.resolveSync(Y,G)){let Y=gM[$]?.[Z];if(!Y)return;try{let G=Q(`${Y}/package.json`,W),X=$==="win32"?"rg.exe":"rg",J=F1(Z4(G),"vendor",X);if(!tJ(J).isFile())return;if($!=="win32")aJ(J,rJ.X_OK);return J}catch{return}}function sJ($=process.execPath,Z=process.platform,W=(Y)=>Bun.which(Y),Q=()=>oJ(Z,process.arch)){return vM($,Z)??Q()??W("rg")??void 0}async function hM($,Z,W){let Q=$.getReader(),Y=new TextDecoder,G="";while(!0){let{done:J,value:K}=await Q.read();if(J)break;G+=Y.decode(K,{stream:!0});let H=G.indexOf(`
214
- `);while(H!==-1){let V=G.slice(0,H).replace(/\r$/,"");if(G=G.slice(H+1),!Z(V))return W(),await Q.cancel(),!1;H=G.indexOf(`
215
- `)}}G+=Y.decode();let X=G.length===0||Z(G.replace(/\r$/,""));if(!X)W();return X}var uM=async($,Z,W,Q)=>{W.throwIfAborted();let Y=sJ();if(!Y)return;let G;try{G=Bun.spawn([Y,...$],{cwd:Z,stdin:"ignore",stdout:"pipe",stderr:"pipe"})}catch(J){if(J.code==="ENOENT")return;throw J}let X=()=>G.kill("SIGTERM");W.addEventListener("abort",X,{once:!0});try{let[J,K,H]=await Promise.all([hM(G.stdout,Q,X),new Response(G.stderr).text(),G.exited]);return W.throwIfAborted(),{exitCode:H,stderr:K,stopped:!J}}finally{W.removeEventListener("abort",X)}};function eJ($){return $.ripgrep===!1?void 0:$.ripgrep??uM}function $K(){let $=["--hidden","--no-ignore","--no-config","--no-messages","--sort","path"];for(let Z of W4)$.push("--glob",`!${Z}`,"--glob",`!${Z}/**`,"--glob",`!**/${Z}`,"--glob",`!**/${Z}/**`);return $}function ZK($){return $.split(/[\\/]/).some((Z)=>W4.has(Z))}function WK($,Z,W){return DZ(F1($),F1(Z,W.replace(/^\.[\\/]/,"")))}function QK($){return $!==void 0&&($.stopped||$.exitCode===0||$.exitCode===1)}function Q4($){let Z="";for(let W=0;W<$.length;W++){let Q=$[W];if(Q==="*")if($[W+1]==="*")if($[W+2]==="/")Z+="(?:.*/)?",W+=2;else Z+=".*",W+=1;else Z+="[^/]*";else if(Q==="?")Z+="[^/]";else if(".+^${}()|[]\\".includes(Q))Z+=`\\${Q}`;else Z+=Q}return new RegExp(`^${Z}$`)}async function*Y4($,Z){Z.throwIfAborted();let W;try{W=await _M($)}catch{return}for(let Q of W.sort()){if(Z.throwIfAborted(),W4.has(Q))continue;let Y=F1($,Q),G;try{G=await fM(Y)}catch{continue}if(G.isDirectory())yield*Y4(Y,Z);else yield Y}}async function mM($,Z,W,Q,Y){if(!Y)return;let G=[],X=await Y(["--files",...$K()],Z,Q,(J)=>{if(!J||ZK(J))return!0;let K=J.replaceAll("\\","/");if(W.test(K))G.push(WK($,Z,J));return G.length<B$});return QK(X)?G:void 0}async function lM($,Z,W,Q,Y,G,X){if(!X)return;let J=[],K=["--json","--engine","auto",...$K(),...Y?["--ignore-case"]:[],"--",W,"."],H=await X(K,Z,G,(V)=>{let z;try{z=JSON.parse(V)}catch{return!0}if(z.type!=="match")return!0;let F=z.data?.path?.text,D=z.data?.lines?.text,L=z.data?.line_number;if(typeof F!=="string"||typeof D!=="string"||typeof L!=="number")return!0;let U=F.replace(/^\.[\\/]/,"");if(ZK(U))return!0;let A=U.replaceAll("\\","/");if(Q&&!Q.test(A))return!0;return J.push(`${WK($,Z,U)}:${L}: ${D.trim()}`),J.length<B$});if(!QK(H))return;return{results:J,hitLimit:H?.stopped===!0||J.length>=B$}}function G4($,Z={}){return d({name:"glob",description:"Find files by glob pattern (e.g. 'src/**/*.ts'). Returns paths relative to the session root.",inputSchema:V1.object({pattern:V1.string().describe("Glob pattern, e.g. **/*.test.ts"),path:V1.string().optional().describe("Directory to search; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({pattern:W,path:Q},{signal:Y})=>{let G=k0($.root,Q??"."),X=Q4(W),J=await mM($.root,G,X,Y,eJ(Z)),K=J??[];if(!J)for await(let H of Y4(G,Y)){let V=DZ(G,H).replaceAll("\\","/");if(X.test(V))K.push(DZ(F1($.root),H));if(K.length>=B$)break}if(K.length===0)return`No files matched ${W}`;return I0(T0(K.join(`
216
- `)),`showing the first ${B$} matches`)}})}function X4($,Z={}){return d({name:"grep",description:"Search file contents with a regular expression. Returns matching lines with file and line numbers for grounded path:line citations.",inputSchema:V1.object({pattern:V1.string().describe("Regular expression to search for"),path:V1.string().optional().describe("Directory to search; defaults to the session root"),include:V1.string().optional().describe("Only search files matching this glob"),ignoreCase:V1.boolean().optional()}),isConcurrencySafe:()=>!0,execute:async({pattern:W,path:Q,include:Y,ignoreCase:G},{signal:X})=>{let J=k0($.root,Q??"."),K;try{K=new RegExp(W,G?"i":"")}catch(L){return S(`Invalid regular expression: ${L instanceof Error?L.message:String(L)}`)}let H=Y?Q4(Y):void 0,V=await lM($.root,J,W,H,G,X,eJ(Z));if(V)return nJ(W,V.results,V.hitLimit);let z=[],F=0,D=!1;for await(let L of Y4(J,X)){let U=DZ(J,L).replaceAll("\\","/");if(H&&!H.test(U))continue;let A;try{A=await xM(L,"utf8")}catch{continue}if(F+=A.length,A.includes("\x00"))continue;let q=A.split(`
217
- `);for(let O=0;O<q.length;O++){X.throwIfAborted();let j=q[O];if(!K.test(j))continue;if(z.push(`${DZ(F1($.root),L)}:${O+1}: ${j.trim()}`),z.length>=B$){D=!0;break}}if(D||F>iJ){D=D||F>iJ;break}}return nJ(W,z,D)}})}function nJ($,Z,W){if(Z.length===0)return`No matches for ${$}`;let Q=Z.join(`
218
- `);return W?`${Q}
219
-
220
- [search stopped early \u2014 narrow the pattern or scope to see the rest]`:I0(T0(Q),"many matches")}import{z as E0}from"zod";function J4($){return({command:Z,onOutput:W,cols:Q,rows:Y})=>{let G=new TextDecoder,X=!1,J,K=new Promise((L)=>{J=L}),H=()=>{if(X)return;X=!0;let L=G.decode();if(L)W(L)},V=Bun.spawn(zZ(Z,{interactive:!0}),{cwd:$,detached:!0,env:{...process.env,TERM:"xterm-256color"},terminal:{cols:Q,rows:Y,data:(L,U)=>{let A=G.decode(U,{stream:!0});if(A)W(A)},exit:()=>{H(),J?.()}}}),z=V.terminal;if(!z)throw Error("Could not allocate a pseudo-terminal.");let F=Promise.all([V.exited,K]).then(([L])=>{if(H(),!z.closed)z.close();return L??null}),D;return{write:(L)=>void z.write(L),resize:(L,U)=>z.resize(L,U),detach:()=>{V.unref(),z.unref()},kill:()=>{y1(V,"SIGTERM"),D=setTimeout(()=>{if(V.exitCode===null)y1(V,"SIGKILL")},1000),D.unref?.()},exited:F.finally(()=>{if(D)clearTimeout(D)})}}}function K4($){let Z=d({name:"task_output",description:"Read output from a background task. Returns only what is new since the last read unless full is set.",inputSchema:E0.object({taskId:E0.string(),full:E0.boolean().optional().describe("Return all output rather than only what is new")}),isConcurrencySafe:()=>!0,execute:({taskId:X,full:J})=>{let K=$.get(X);if(!K)return S(`No such task: ${X}`);let H=$.output(X,J?"start":"new"),V=K.status==="running"?"still running":`${K.status}${K.exitCode!==null?` (exit ${K.exitCode})`:""}`,z=H?.text.trim().length?H.text:"(no new output)";return{content:[{type:"text",text:`${I0(T0(z),"task output is large")}
221
-
222
- [${V}]`}],details:{taskId:X,status:K.status,exitCode:K.exitCode}}}}),W=d({name:"task_write_stdin",description:"Write to a background task's stdin \u2014 use for REPLs and interactive processes. Include a trailing newline to submit a line.",inputSchema:E0.object({taskId:E0.string(),data:E0.string()}),execute:({taskId:X,data:J})=>{if(!$.get(X))return S(`No such task: ${X}`);return $.writeStdin(X,J)?`Wrote ${J.length} characters to ${X}.`:S(`Task ${X} is not running.`)}}),Q=d({name:"task_kill",description:"Stop a background task.",inputSchema:E0.object({taskId:E0.string()}),execute:({taskId:X})=>{if(!$.get(X))return S(`No such task: ${X}`);return $.kill(X)?`Killed ${X}.`:`Task ${X} had already stopped.`}}),Y=d({name:"task_detach",description:"Detach a background task so it is not stopped when the mu session exits. Use only for work that must outlive the session.",inputSchema:E0.object({taskId:E0.string()}),execute:({taskId:X})=>{if(!$.get(X))return S(`No such task: ${X}`);return $.detach(X)?`Detached ${X}. It will continue after this session exits.`:S(`Task ${X} is not running or was already detached.`)}}),G=d({name:"task_list",description:"List background tasks started in this session.",inputSchema:E0.object({}),isConcurrencySafe:()=>!0,execute:()=>{let X=$.list();if(X.length===0)return"No background tasks.";return X.map((J)=>`${J.id} \xB7 ${J.status}${J.detached?" (detached)":""}${J.exitCode!==null?` (exit ${J.exitCode})`:""} \xB7 ${J.command}`).join(`
223
- `)}});return[Z,W,Q,Y,G]}import{z as LZ}from"zod";class i5{items=[];replace($){this.items=$}all(){return[...this.items]}}var pM={pending:"[ ]",in_progress:"[~]",completed:"[x]"};function YK($){if($.length===0)return"(no tasks)";return $.map((Z)=>`${pM[Z.status]} ${Z.content}`).join(`
224
- `)}function B4($){return d({name:"todo",description:"Record and update the task list for multi-step work. Send the complete list every time; it replaces the previous one. Mark exactly one task in_progress while you work on it.",inputSchema:LZ.object({items:LZ.array(LZ.object({content:LZ.string().describe("What needs doing"),status:LZ.enum(["pending","in_progress","completed"])})).describe("The complete task list")}),execute:({items:Z})=>{let W=Z.filter((G)=>G.status==="in_progress").length;$.replace(Z);let Q=YK(Z),Y=W>1?`
225
-
226
- [note: more than one task is in_progress \u2014 work on one at a time]`:"";return{content:[{type:"text",text:`${Q}${Y}`}],details:{items:Z}}}})}async function nM($){try{let Z=JSON.parse(await cM(iM($,".mu","config.json"),"utf8"));return Z.instructions&&typeof Z.instructions==="object"&&!Array.isArray(Z.instructions)?Z.instructions:{}}catch{return{}}}async function XK($={}){let Z=GK($.root??process.cwd()),W=GK($.home??dM()),Q=new fZ,Y=new i5,G=await _Z(Z),X=new bZ({root:Z,home:W,...await nM(W),...G.instructions??{},...$.instructions??{},...$.managedInstructionPaths?{managedPaths:$.managedInstructionPaths}:{}});await X.reload();let J={root:Z,state:Q,instructions:X},K=new TZ($.spawner??J4(Z),$.processEvents??{}),H=[oW(J),sW(J),eW(J),$4(J),G4(J),X4(J),tW({root:Z,processes:K,...$.spawn?{spawn:$.spawn}:{}}),B4(Y),...K4(K)],V={attach:(z)=>{K.setEvents({onStarted:(F)=>{$.processEvents?.onStarted?.(F),z.emit({type:"task_started",taskId:F.id,command:F.command,background:!0})},onOutput:(F,D)=>{$.processEvents?.onOutput?.(F,D),z.emit({type:"task_output",taskId:F,chunk:D})},onExited:(F)=>{if($.processEvents?.onExited?.(F),z.emit({type:"task_exited",taskId:F.id,exitCode:F.exitCode,status:F.status==="killed"?"killed":"exited"}),!F.detached)z.followUp(N6(F))}})},resize:(z,F)=>K.resizeAll(z,F),stop:()=>K.stopAll(),shutdown:()=>K.killAll()};return{name:"coding",toolset:H,promptFor:_6,permissionDefaults:b6(C6,G.permissions),permissionModes:y6,defaultPermissionMode:"default",rememberPermission:(z,F)=>k6(Z,z,F),environment:()=>kZ(Z),contextMessages:async()=>[S6(await kZ(Z))],refreshContext:(z,F)=>X.refreshedMessages(z,F.sessionId),diagnostics:X.snapshot.diagnostics.map((z)=>z.path?`${z.path}: ${z.message}`:z.message),commands:[{name:"instructions",description:"Show or reload instruction files",run:async(z)=>{let F=z.args.trim();if(F&&F!=="reload")return{handled:!0,message:"Usage: /instructions [reload]"};if(F==="reload")await X.reload({resetNested:!0});return{handled:!0,message:X.formatStatus(F==="reload"?"instructions reloaded":"instructions")}}},{name:"reload",description:"Reload instruction files",run:async()=>{return await X.reload({resetNested:!0}),{handled:!0,message:X.formatStatus("instructions reloaded")}}}],carryoverExtractor:()=>({readFiles:Q.readFiles(),modifiedFiles:Q.modifiedFiles(),todos:Y.all()}),scope:()=>Z.replace(/[^A-Za-z0-9]+/g,"-").replace(/^-|-$/g,""),checkpointProvider:new EZ({root:Z}),runtime:V,fileState:Q,todos:Y,processes:K,instructions:X}}function aM($){if(typeof $.model==="string")return $.model;if($.model)return`${$.model.provider}/${$.model.id}`;return l1()}async function Gb($={}){let{profile:Z,profileOptions:W,...Q}=$;if(!Z)return new C$(Q);let Y=Z==="coding"?await XK(W):Z;return new C$(await nW(Y,aM(Q),Q))}export{x1 as userMessage,HQ as totalTokens,d as tool,DH as toCommand,g4 as textResult,kQ as substituteArguments,f6 as structuredOutputTool,v6 as structuredOutputPrompt,yB as storedAuthProviders,jM as skillsExtension,vJ as skillListing,DM as shellHooksExtension,SB as saveApiKey,CQ as resolveExtensionFiles,h6 as renderAuthPage,CB as removeStoredCredential,rB as registryWithCoreCommands,S4 as registerProvider,f4 as registerModels,x4 as refreshModels,l0 as readAuthFile,V6 as providerHasCredentials,bB as preferredAuthProvider,_Q as parseMarkdownCommand,pZ as parseFrontmatter,nW as optionsFromProfile,zM as mcpExtension,cB as loginXai,nB as loginOpenRouter,mB as loginOpenAI,pB as loginKimiCoding,dB as loginGitHubCopilot,rW as loadSkill,VM as loadProfile,BM as loadMcpConfig,FH as loadMarkdownCommands,QH as loadExtensions,P$ as listModels,A1 as findModel,S as errorResult,NM as discoverSkills,_4 as discoverModels,MM as defaultSkillRoots,l1 as defaultModelRef,c6 as defaultAuthFile,D$ as customMessage,hB as createCredentialResolver,Gb as createAgent,SQ as coreCommands,XK as codingProfile,x6 as checkBudget,f0 as builtinProviderConfigs,vZ as authSuccessPage,O1 as authErrorPage,Z0 as SessionTree,p1 as STRUCTURED_OUTPUT_TOOL,T$ as MemorySessionStore,yQ as FileSessionStore,e5 as ExtensionHost,L1 as CommandRegistry,C$ as Agent};
243
+ `,W=!0;Z+=G,Q??=setTimeout(Y,Sj)},flush:Y}}function DQ($){let Z=$.spawn??yj;return n({name:"bash",changesState:({command:Q,run_in_background:W})=>W===!0||!PZ(Q),isConcurrencySafe:({command:Q,run_in_background:W})=>W!==!0&&PZ(Q),permissionScope:({command:Q,run_in_background:W})=>W!==!0&&PZ(Q)?"bash:inspect":"bash",permissionPattern:({command:Q})=>Q,description:"Run a command with the platform-native shell in the session root. For repository exploration, batch read-only rg, sed, head, tail, find, and git status/diff commands to search and narrow before reading files. Use write/edit tools for file changes.",inputSchema:wZ.object({command:wZ.string().describe("The shell command to run"),description:wZ.string().optional().describe("A short description of what this command does, for the user"),timeoutMs:wZ.number().int().positive().max(Cj).optional(),run_in_background:wZ.boolean().optional().describe("Start the command in the background and return a task id immediately")}),execute:async({command:Q,timeoutMs:W,run_in_background:Y},{signal:G,update:X})=>{if(G.aborted)return y("Aborted before the command started.");if(Y){if(!$.processes)return y("Background execution is not available in this session.");let L=$.processes.start(Q);return{content:[{type:"text",text:`Started ${L.id} in the background. Use task_output to read it, task_kill to stop it.`}],details:{taskId:L.id,command:Q,background:!0}}}let J=Date.now(),K=bj(X),B;try{B=await Z(Q,$.root,G,W??Rj,K.push)}finally{K.flush()}let z=Date.now()-J,V=[];if(B.stdout.trim())V.push(B.stdout.trimEnd());if(B.stderr.trim())V.push(`[stderr]
244
+ ${B.stderr.trimEnd()}`);let F=C0(R0(V.join(`
245
+
246
+ `)||"(no output)"),"command produced a lot of output");if(B.timedOut)return{content:[{type:"text",text:`${F}
247
+
248
+ [command timed out and was killed]`}],details:{command:Q,exitCode:B.exitCode,timedOut:!0,durationMs:z},isError:!0};let D=B.exitCode!==0;return{content:[{type:"text",text:D?`${F}
249
+
250
+ [exit code ${B.exitCode}]`:F}],details:{command:Q,exitCode:B.exitCode,durationMs:z},isError:D}}})}import{mkdir as _j,readdir as kj,readFile as K6,stat as N3,writeFile as O3}from"fs/promises";import{dirname as xj,isAbsolute as fj,relative as M3,resolve as TZ}from"path";import{z as Q0}from"zod";function f0($,Z){let Q=fj(Z)?TZ(Z):TZ($,Z);if(M3(TZ($),Q).startsWith(".."))throw Error(`Path escapes the session root: ${Z}`);return Q}function z0($,Z){let Q=M3(TZ($),Z);return Q===""?".":Q}function D3($){let Z=$.split(`
251
+ `);if(Z.at(-1)==="")Z.pop();return Z}function j3($,Z,Q){let W=Z===void 0?[]:D3(Z),Y=D3(Q),G=0;while(G<W.length&&G<Y.length&&W[G]===Y[G])G++;let X=0;while(X<W.length-G&&X<Y.length-G&&W[W.length-1-X]===Y[Y.length-1-X])X++;let J=W.length-G-X,K=Y.length-G-X;if(K===0&&J===0)return{path:$,added:K,removed:J,hunks:[]};let B=Math.min(3,G),z=Math.min(3,X),V=G-B,F=G-B,D=B+J+z,L=B+K+z,U=[`@@ -${W.length===0?0:V+1},${D} +${Y.length===0?0:F+1},${L} @@`,...W.slice(V,G).map((q)=>` ${q}`),...W.slice(G,W.length-X).map((q)=>`-${q}`),...Y.slice(G,Y.length-X).map((q)=>`+${q}`),...Y.slice(Y.length-X,Y.length-X+z).map((q)=>` ${q}`)];return{path:$,added:K,removed:J,hunks:U}}function UQ($){return n({name:"read",description:"Read a file from the filesystem. Returns contents with line numbers for grounded path:line citations. Read a file before editing it.",inputSchema:Q0.object({path:Q0.string().describe("Path to the file, absolute or relative to the session root"),offset:Q0.number().int().min(1).optional().describe("First line to read (1-based)"),limit:Q0.number().int().min(1).optional().describe("Maximum number of lines to read")}),isConcurrencySafe:()=>!0,execute:async({path:Z,offset:Q,limit:W})=>{let Y=f0($.root,Z),G;try{G=await K6(Y,"utf8")}catch(D){let L=D.code;if(L==="ENOENT")return y(`File not found: ${z0($.root,Y)}`);if(L==="EISDIR")return y(`${z0($.root,Y)} is a directory \u2014 use ls instead.`);throw D}$.state.markRead(Y);let X=G.split(`
252
+ `),J=(Q??1)-1,B=X.slice(J,W?J+W:void 0).map((D,L)=>`${String(J+L+1).padStart(5)} ${D}`),z=C0(R0(B.join(`
253
+ `)),"file is large"),V=await $.instructions?.instructionsForPath(Y);return{content:[{type:"text",text:[z||"(empty file)",V?.text].filter(Boolean).join(`
254
+
255
+ `)}],details:{path:Y,lines:X.length,...V&&V.sources.length>0?{loadedInstructions:V.sources}:{}}}}})}function qQ($){return n({name:"write",changesState:!0,description:"Write a complete file, creating it or replacing its contents. To change part of an existing file, prefer edit.",inputSchema:Q0.object({path:Q0.string().describe("Path to the file"),content:Q0.string().describe("The complete file contents")}),permissionDetails:async({path:Z,content:Q})=>{let W=f0($.root,Z),Y;try{Y=await K6(W,"utf8")}catch{Y=void 0}let G=z0($.root,W);return{description:`${Y===void 0?"Create":"Overwrite"} ${G}`,preview:{kind:"diff",file:j3(G,Y,Q)}}},execute:async({path:Z,content:Q})=>{let W=f0($.root,Z),Y=!0;try{await N3(W)}catch{Y=!1}if(Y&&!$.state.hasRead(W))return y(`Refusing to overwrite ${z0($.root,W)} because it has not been read in this session. Read it first, then write.`);if(Y&&$.state.isStale(W))return y(`${z0($.root,W)} changed on disk since you read it. Read it again before writing.`);await _j(xj(W),{recursive:!0}),await O3(W,Q,"utf8"),$.state.markWritten(W);let G=Q.split(`
256
+ `).length;return{content:[{type:"text",text:`${Y?"Updated":"Created"} ${z0($.root,W)} (${G} lines)`}],details:{path:W,created:!Y}}}})}var vj=Q0.object({oldString:Q0.string().describe("Exact text to replace, including indentation"),newString:Q0.string().describe("Replacement text"),replaceAll:Q0.boolean().optional().describe("Replace every occurrence of this oldString")}),LQ=($)=>$.split(`
257
+ `).length-1,L3="\uFEFF";function U3($){return $.startsWith(L3)?{bom:L3,text:$.slice(1)}:{bom:"",text:$}}var q3=($)=>$.replace(/\r?\n/g,`\r
258
+ `),gj=($)=>$.replace(/\r\n/g,`
259
+ `);function hj($,Z,Q){if(Z.includes(`
260
+ `)&&!$.includes(Z)){for(let W of[q3,gj]){let Y=W(Z);if(Y!==Z&&$.includes(Y))return{oldString:Y,newString:W(Q)}}return{oldString:Z,newString:Q}}return{oldString:Z,newString:$.includes(`\r
261
+ `)?q3(Q):Q}}function A3($,Z,Q){let W=(V)=>Z.length>1?`edits[${V}]: `:"",Y=[];for(let[V,F]of Z.entries()){let{replaceAll:D}=F,{oldString:L,newString:U}=hj($,F.oldString,F.newString);if(L==="")return{ok:!1,message:`${W(V)}oldString is empty \u2014 nothing to match.`};if(L===U)return{ok:!1,message:`${W(V)}oldString and newString are identical \u2014 nothing to do.`};let q=$.split(L).length-1;if(q===0)return{ok:!1,message:`${W(V)}oldString was not found in ${Q}. The text must match exactly, including whitespace and indentation.`};if(q>1&&!D)return{ok:!1,message:`${W(V)}oldString appears ${q} times in ${Q}. Include more surrounding context to make it unique, or set replaceAll.`};let A=0;for(;;){let N=$.indexOf(L,A);if(N===-1)break;if(Y.push({start:N,end:N+L.length,newString:U,index:V}),!D)break;A=N+L.length}}Y.sort((V,F)=>V.start-F.start);let G;for(let V of Y){if(G&&G.end>V.start)return{ok:!1,message:G.start===V.start&&G.end===V.end?`edits[${G.index}] and edits[${V.index}] match the same text in ${Q}. Drop the duplicate, or give each edit different text to match.`:`edits[${G.index}] and edits[${V.index}] overlap in ${Q}. Merge them into one edit, or target text that does not overlap.`};G=V}let X="",J=0,K=1,B=1,z=[];for(let V of Y){let F=$.slice(J,V.start),D=LQ(F);K+=D,B+=D,z.push({edit:V.index,oldLine:K,newLine:B}),X+=F+V.newString,K+=LQ($.slice(V.start,V.end)),B+=LQ(V.newString),J=V.end}return X+=$.slice(J),{ok:!0,updated:X,replacements:Y.length,hunks:z}}function uj($){if(!$||typeof $!=="object"||Array.isArray($))return $;let Z={...$};if(typeof Z.edits==="string")try{let Q=JSON.parse(Z.edits);if(Array.isArray(Q))Z.edits=Q}catch{}if(typeof Z.oldString==="string"&&typeof Z.newString==="string"){let{oldString:Q,newString:W,replaceAll:Y,...G}=Z,X=Array.isArray(Z.edits)?Z.edits:[];return{...G,edits:[...X,{oldString:Q,newString:W,...Y===void 0?{}:{replaceAll:Y}}]}}return Z}function AQ($){return n({name:"edit",changesState:!0,description:"Replace exact strings in a file. Each oldString must appear exactly once unless that edit sets replaceAll. Pass several edits to change one file in a single call. Read the file first.",inputSchema:Q0.object({path:Q0.string().describe("Path to the file"),edits:Q0.array(vj).min(1).describe("One or more replacements applied in a single write. Each is matched against the file as you read it, not against the result of earlier edits in this call, and they must not overlap \u2014 merge changes that touch the same text into one edit.")}),coerceInput:uj,permissionDetails:async({path:Z,edits:Q})=>{let W=f0($.root,Z),Y=z0($.root,W),G;try{G=await K6(W,"utf8")}catch{return{description:`Edit ${Y}`}}let{text:X}=U3(G),J=A3(X,Q,Y);if(!J.ok)return{description:`Edit ${Y}`};return{description:`Edit ${Y}`,preview:{kind:"diff",file:j3(Y,X,J.updated)}}},execute:async({path:Z,edits:Q})=>{let W=f0($.root,Z);if(!$.state.hasRead(W))return y(`Read ${z0($.root,W)} before editing it, so you can see what you are changing.`);let Y;try{Y=await K6(W,"utf8")}catch(V){if(V.code==="ENOENT")return y(`File not found: ${z0($.root,W)}`);throw V}if($.state.isStale(W))return y(`${z0($.root,W)} changed on disk since you read it. Read it again before editing.`);let{bom:G,text:X}=U3(Y),J=A3(X,Q,z0($.root,W));if(!J.ok)return y(J.message);let{updated:K,replacements:B,hunks:z}=J;return await O3(W,G+K,"utf8"),$.state.markWritten(W),{content:[{type:"text",text:`Edited ${z0($.root,W)} (${B} replacement${B===1?"":"s"})`}],details:{path:W,occurrences:B,edits:Q.length,hunks:z}}}})}function NQ($){return n({name:"ls",description:"List the entries of a directory.",inputSchema:Q0.object({path:Q0.string().optional().describe("Directory to list; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({path:Z})=>{let Q=f0($.root,Z??"."),W;try{W=await kj(Q)}catch(G){if(G.code==="ENOENT")return y(`Directory not found: ${z0($.root,Q)}`);throw G}let Y=await Promise.all(W.sort().map(async(G)=>{try{return(await N3(TZ(Q,G))).isDirectory()?`${G}/`:G}catch{return G}}));return C0(R0(Y.join(`
262
+ `)||"(empty directory)"),"directory has many entries")}})}import{accessSync as T3,constants as I3,statSync as E3}from"fs";import{readdir as mj,readFile as lj,stat as pj}from"fs/promises";import{dirname as OQ,relative as IZ,resolve as N1}from"path";import{z as A1}from"zod";var MQ=new Set(["node_modules",".git","dist","build",".next","coverage",".venv"]),A$=200,P3=2000000;function cj($,Z){let Q=Z==="win32"?"rg.exe":"rg",W=N1(OQ($),"..","mu-path",Q);try{if(!E3(W).isFile())return;if(Z!=="win32")T3(W,I3.X_OK);return W}catch{return}}var dj={darwin:{arm64:"@mu-agent/ripgrep-darwin-arm64"},linux:{x64:"@mu-agent/ripgrep-linux-x64"},win32:{x64:"@mu-agent/ripgrep-windows-x64"}};function R3($=process.platform,Z=process.arch,Q=process.argv[1]?OQ(N1(process.argv[1])):process.cwd(),W=(Y,G)=>Bun.resolveSync(Y,G)){let Y=dj[$]?.[Z];if(!Y)return;try{let G=W(`${Y}/package.json`,Q),X=$==="win32"?"rg.exe":"rg",J=N1(OQ(G),"vendor",X);if(!E3(J).isFile())return;if($!=="win32")T3(J,I3.X_OK);return J}catch{return}}function C3($=process.execPath,Z=process.platform,Q=(Y)=>Bun.which(Y),W=()=>R3(Z,process.arch)){return cj($,Z)??W()??Q("rg")??void 0}async function ij($,Z,Q){let W=$.getReader(),Y=new TextDecoder,G="";while(!0){let{done:J,value:K}=await W.read();if(J)break;G+=Y.decode(K,{stream:!0});let B=G.indexOf(`
263
+ `);while(B!==-1){let z=G.slice(0,B).replace(/\r$/,"");if(G=G.slice(B+1),!Z(z))return Q(),await W.cancel(),!1;B=G.indexOf(`
264
+ `)}}G+=Y.decode();let X=G.length===0||Z(G.replace(/\r$/,""));if(!X)Q();return X}var nj=async($,Z,Q,W)=>{Q.throwIfAborted();let Y=C3();if(!Y)return;let G;try{G=Bun.spawn([Y,...$],{cwd:Z,stdin:"ignore",stdout:"pipe",stderr:"pipe",windowsHide:!0})}catch(J){if(J.code==="ENOENT")return;throw J}let X=()=>G.kill("SIGTERM");Q.addEventListener("abort",X,{once:!0});try{let[J,K,B]=await Promise.all([ij(G.stdout,W,X),new Response(G.stderr).text(),G.exited]);return Q.throwIfAborted(),{exitCode:B,stderr:K,stopped:!J}}finally{Q.removeEventListener("abort",X)}};function S3($){return $.ripgrep===!1?void 0:$.ripgrep??nj}function y3(){let $=["--hidden","--no-ignore","--no-config","--no-messages","--sort","path"];for(let Z of MQ)$.push("--glob",`!${Z}`,"--glob",`!${Z}/**`,"--glob",`!**/${Z}`,"--glob",`!**/${Z}/**`);return $}function b3($){return $.split(/[\\/]/).some((Z)=>MQ.has(Z))}function _3($,Z,Q){return IZ(N1($),N1(Z,Q.replace(/^\.[\\/]/,"")))}function k3($){return $!==void 0&&($.stopped||$.exitCode===0||$.exitCode===1)}function jQ($){let Z="";for(let Q=0;Q<$.length;Q++){let W=$[Q];if(W==="*")if($[Q+1]==="*")if($[Q+2]==="/")Z+="(?:.*/)?",Q+=2;else Z+=".*",Q+=1;else Z+="[^/]*";else if(W==="?")Z+="[^/]";else if(".+^${}()|[]\\".includes(W))Z+=`\\${W}`;else Z+=W}return new RegExp(`^${Z}$`)}async function*PQ($,Z){Z.throwIfAborted();let Q;try{Q=await mj($)}catch{return}for(let W of Q.sort()){if(Z.throwIfAborted(),MQ.has(W))continue;let Y=N1($,W),G;try{G=await pj(Y)}catch{continue}if(G.isDirectory())yield*PQ(Y,Z);else yield Y}}async function aj($,Z,Q,W,Y){if(!Y)return;let G=[],X=await Y(["--files",...y3()],Z,W,(J)=>{if(!J||b3(J))return!0;let K=J.replaceAll("\\","/");if(Q.test(K))G.push(_3($,Z,J));return G.length<A$});return k3(X)?G:void 0}async function rj($,Z,Q,W,Y,G,X){if(!X)return;let J=[],K=["--json","--engine","auto",...y3(),...Y?["--ignore-case"]:[],"--",Q,"."],B=await X(K,Z,G,(z)=>{let V;try{V=JSON.parse(z)}catch{return!0}if(V.type!=="match")return!0;let F=V.data?.path?.text,D=V.data?.lines?.text,L=V.data?.line_number;if(typeof F!=="string"||typeof D!=="string"||typeof L!=="number")return!0;let U=F.replace(/^\.[\\/]/,"");if(b3(U))return!0;let q=U.replaceAll("\\","/");if(W&&!W.test(q))return!0;return J.push(`${_3($,Z,U)}:${L}: ${D.trim()}`),J.length<A$});if(!k3(B))return;return{results:J,hitLimit:B?.stopped===!0||J.length>=A$}}function wQ($,Z={}){return n({name:"glob",description:"Find files by glob pattern (e.g. 'src/**/*.ts'). Returns paths relative to the session root.",inputSchema:A1.object({pattern:A1.string().describe("Glob pattern, e.g. **/*.test.ts"),path:A1.string().optional().describe("Directory to search; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({pattern:Q,path:W},{signal:Y})=>{let G=f0($.root,W??"."),X=jQ(Q),J=await aj($.root,G,X,Y,S3(Z)),K=J??[];if(!J)for await(let B of PQ(G,Y)){let z=IZ(G,B).replaceAll("\\","/");if(X.test(z))K.push(IZ(N1($.root),B));if(K.length>=A$)break}if(K.length===0)return`No files matched ${Q}`;return C0(R0(K.join(`
265
+ `)),`showing the first ${A$} matches`)}})}function TQ($,Z={}){return n({name:"grep",description:"Search file contents with a regular expression. Returns matching lines with file and line numbers for grounded path:line citations.",inputSchema:A1.object({pattern:A1.string().describe("Regular expression to search for"),path:A1.string().optional().describe("Directory to search; defaults to the session root"),include:A1.string().optional().describe("Only search files matching this glob"),ignoreCase:A1.boolean().optional()}),isConcurrencySafe:()=>!0,execute:async({pattern:Q,path:W,include:Y,ignoreCase:G},{signal:X})=>{let J=f0($.root,W??"."),K;try{K=new RegExp(Q,G?"i":"")}catch(L){return y(`Invalid regular expression: ${L instanceof Error?L.message:String(L)}`)}let B=Y?jQ(Y):void 0,z=await rj($.root,J,Q,B,G,X,S3(Z));if(z)return w3(Q,z.results,z.hitLimit);let V=[],F=0,D=!1;for await(let L of PQ(J,X)){let U=IZ(J,L).replaceAll("\\","/");if(B&&!B.test(U))continue;let q;try{q=await lj(L,"utf8")}catch{continue}if(F+=q.length,q.includes("\x00"))continue;let A=q.split(`
266
+ `);for(let N=0;N<A.length;N++){X.throwIfAborted();let j=A[N];if(!K.test(j))continue;if(V.push(`${IZ(N1($.root),L)}:${N+1}: ${j.trim()}`),V.length>=A$){D=!0;break}}if(D||F>P3){D=D||F>P3;break}}return w3(Q,V,D)}})}function w3($,Z,Q){if(Z.length===0)return`No matches for ${$}`;let W=Z.join(`
267
+ `);return Q?`${W}
268
+
269
+ [search stopped early \u2014 narrow the pattern or scope to see the rest]`:C0(R0(W),"many matches")}import{z as S0}from"zod";function IQ($){return({command:Z,onOutput:Q,cols:W,rows:Y})=>{if(process.platform==="win32"){let L=Bun.spawn(q$(Z,{interactive:!0}),{cwd:$,detached:!1,env:process.env,stdin:"pipe",stdout:"pipe",stderr:"pipe",windowsHide:!0}),U=async(N)=>{let j=N.getReader(),P=new TextDecoder;while(!0){let{done:C,value:v}=await j.read();if(C)break;let d=P.decode(v,{stream:!0});if(d)Q(d)}let O=P.decode();if(O)Q(O)},q=Promise.all([U(L.stdout),U(L.stderr)]),A;return{write:(N)=>{L.stdin.write(N),L.stdin.flush()},resize:()=>{},detach:()=>L.unref(),kill:()=>{e0(L,"SIGTERM"),A=setTimeout(()=>{if(L.exitCode===null)e0(L,"SIGKILL")},1000),A.unref?.()},exited:Promise.all([L.exited,q]).then(([N])=>N??null).finally(()=>{if(A)clearTimeout(A)})}}let G=new TextDecoder,X=!1,J,K=new Promise((L)=>{J=L}),B=()=>{if(X)return;X=!0;let L=G.decode();if(L)Q(L)},z=Bun.spawn(q$(Z,{interactive:!0}),{cwd:$,detached:!0,env:{...process.env,TERM:"xterm-256color"},terminal:{cols:W,rows:Y,data:(L,U)=>{let q=G.decode(U,{stream:!0});if(q)Q(q)},exit:()=>{B(),J?.()}}}),V=z.terminal;if(!V)throw Error("Could not allocate a pseudo-terminal.");let F=Promise.all([z.exited,K]).then(([L])=>{if(B(),!V.closed)V.close();return L??null}),D;return{write:(L)=>void V.write(L),resize:(L,U)=>V.resize(L,U),detach:()=>{z.unref(),V.unref()},kill:()=>{e0(z,"SIGTERM"),D=setTimeout(()=>{if(z.exitCode===null)e0(z,"SIGKILL")},1000),D.unref?.()},exited:F.finally(()=>{if(D)clearTimeout(D)})}}}function EQ($){let Z=n({name:"task_output",description:"Read output from a background task. Returns only what is new since the last read unless full is set.",inputSchema:S0.object({taskId:S0.string(),full:S0.boolean().optional().describe("Return all output rather than only what is new")}),isConcurrencySafe:()=>!0,execute:({taskId:X,full:J})=>{let K=$.get(X);if(!K)return y(`No such task: ${X}`);let B=$.output(X,J?"start":"new"),z=K.status==="running"?"still running":`${K.status}${K.exitCode!==null?` (exit ${K.exitCode})`:""}`,V=B?.text.trim().length?B.text:"(no new output)";return{content:[{type:"text",text:`${C0(R0(V),"task output is large")}
270
+
271
+ [${z}]`}],details:{taskId:X,status:K.status,exitCode:K.exitCode}}}}),Q=n({name:"task_write_stdin",description:"Write to a background task's stdin \u2014 use for REPLs and interactive processes. Include a trailing newline to submit a line.",inputSchema:S0.object({taskId:S0.string(),data:S0.string()}),execute:({taskId:X,data:J})=>{if(!$.get(X))return y(`No such task: ${X}`);return $.writeStdin(X,J)?`Wrote ${J.length} characters to ${X}.`:y(`Task ${X} is not running.`)}}),W=n({name:"task_kill",description:"Stop a background task.",inputSchema:S0.object({taskId:S0.string()}),execute:({taskId:X})=>{if(!$.get(X))return y(`No such task: ${X}`);return $.kill(X)?`Killed ${X}.`:`Task ${X} had already stopped.`}}),Y=n({name:"task_detach",description:"Detach a background task so it is not stopped when the mu session exits. Use only for work that must outlive the session.",inputSchema:S0.object({taskId:S0.string()}),execute:({taskId:X})=>{if(!$.get(X))return y(`No such task: ${X}`);return $.detach(X)?`Detached ${X}. It will continue after this session exits.`:y(`Task ${X} is not running or was already detached.`)}}),G=n({name:"task_list",description:"List background tasks started in this session.",inputSchema:S0.object({}),isConcurrencySafe:()=>!0,execute:()=>{let X=$.list();if(X.length===0)return"No background tasks.";return X.map((J)=>`${J.id} \xB7 ${J.status}${J.detached?" (detached)":""}${J.exitCode!==null?` (exit ${J.exitCode})`:""} \xB7 ${J.command}`).join(`
272
+ `)}});return[Z,Q,W,Y,G]}import{z as EZ}from"zod";class B6{items=[];replace($){this.items=$}all(){return[...this.items]}}var tj={pending:"[ ]",in_progress:"[~]",completed:"[x]"};function x3($){if($.length===0)return"(no tasks)";return $.map((Z)=>`${tj[Z.status]} ${Z.content}`).join(`
273
+ `)}function RQ($){return n({name:"todo",description:"Record and update the task list for multi-step work. Send the complete list every time; it replaces the previous one. Mark exactly one task in_progress while you work on it.",inputSchema:EZ.object({items:EZ.array(EZ.object({content:EZ.string().describe("What needs doing"),status:EZ.enum(["pending","in_progress","completed"])})).describe("The complete task list")}),execute:({items:Z})=>{let Q=Z.filter((G)=>G.status==="in_progress").length;$.replace(Z);let W=x3(Z),Y=Q>1?`
274
+
275
+ [note: more than one task is in_progress \u2014 work on one at a time]`:"";return{content:[{type:"text",text:`${W}${Y}`}],details:{items:Z}}}})}async function $P($){try{let Z=JSON.parse(await oj(ej($,".mu","config.json"),"utf8"));return Z.instructions&&typeof Z.instructions==="object"&&!Array.isArray(Z.instructions)?Z.instructions:{}}catch{return{}}}async function v3($={}){let Z=f3($.root??process.cwd()),Q=f3($.home??sj()),W=new tZ,Y=new B6,G=await aZ(Z),X=new iZ({root:Z,home:Q,...await $P(Q),...G.instructions??{},...$.instructions??{},...$.managedInstructionPaths?{managedPaths:$.managedInstructionPaths}:{}});await X.reload();let J={root:Z,state:W,instructions:X},K=new uZ($.spawner??IQ(Z),$.processEvents??{}),B=[UQ(J),qQ(J),AQ(J),NQ(J),wQ(J),TQ(J),DQ({root:Z,processes:K,...$.spawn?{spawn:$.spawn}:{}}),RQ(Y),...EQ(K)],z={attach:(V)=>{K.setEvents({onStarted:(F)=>{$.processEvents?.onStarted?.(F),V.emit({type:"task_started",taskId:F.id,command:F.command,background:!0})},onOutput:(F,D)=>{$.processEvents?.onOutput?.(F,D),V.emit({type:"task_output",taskId:F,chunk:D})},onExited:(F)=>{if($.processEvents?.onExited?.(F),V.emit({type:"task_exited",taskId:F.id,exitCode:F.exitCode,status:F.status==="killed"?"killed":"exited"}),!F.detached)V.followUp(f6(F))}})},resize:(V,F)=>K.resizeAll(V,F),stop:()=>K.stopAll(),shutdown:()=>K.killAll()};return{name:"coding",toolset:B,promptFor:s6,permissionDefaults:t6(a6,G.permissions),permissionModes:r6,defaultPermissionMode:"default",rememberPermission:(V,F)=>o6(Z,V,F),environment:()=>nZ(Z),contextMessages:async()=>[n6(await nZ(Z))],refreshContext:(V,F)=>X.refreshedMessages(V,F.sessionId),diagnostics:X.snapshot.diagnostics.map((V)=>V.path?`${V.path}: ${V.message}`:V.message),commands:[{name:"instructions",description:"Show or reload instruction files",run:async(V)=>{let F=V.args.trim();if(F&&F!=="reload")return{handled:!0,message:"Usage: /instructions [reload]"};if(F==="reload")await X.reload({resetNested:!0});return{handled:!0,message:X.formatStatus(F==="reload"?"instructions reloaded":"instructions")}}},{name:"reload",description:"Reload instruction files",run:async()=>{return await X.reload({resetNested:!0}),{handled:!0,message:X.formatStatus("instructions reloaded")}}}],carryoverExtractor:()=>({readFiles:W.readFiles(),modifiedFiles:W.modifiedFiles(),todos:Y.all()}),scope:()=>Z.replace(/[^A-Za-z0-9]+/g,"-").replace(/^-|-$/g,""),checkpointProvider:new mZ({root:Z}),runtime:z,fileState:W,todos:Y,processes:K,instructions:X}}function ZP($){if(typeof $.model==="string")return $.model;if($.model)return`${$.model.provider}/${$.model.id}`;return n1()}async function O_($={}){let{profile:Z,profileOptions:Q,...W}=$;if(!Z)return new l$(W);let Y=Z==="coding"?await v3(Q):Z;return new l$(await VQ(Y,ZP(W),W))}export{t1 as userMessage,bW as totalTokens,n as tool,ZV as toCommand,d0 as thinkingLevelForModel,YW as textResult,a1 as supportedThinkingLevels,Z9 as substituteArguments,$8 as structuredOutputTool,Z8 as structuredOutputPrompt,LH as storedAuthProviders,Bj as skillsExtension,G3 as skillListing,Zj as shellHooksExtension,Aj as sessionToMarkdown,FH as saveApiKey,sW as resolveExtensionFiles,W8 as renderAuthPage,DH as removeStoredCredential,_H as registryWithCoreCommands,cQ as registerProvider,oQ as registerModels,tQ as refreshModels,n0 as readAuthFile,P6 as providerHasCredentials,UH as preferredAuthProvider,Q9 as parseMarkdownCommand,W5 as parseFrontmatter,VQ as optionsFromProfile,sM as mcpExtension,RH as loginXai,yH as loginOpenRouter,TH as loginOpenAI,EH as loginKimiCoding,CH as loginGitHubCopilot,FQ as loadSkill,eM as loadProfile,tM as loadMcpConfig,$V as loadMarkdownCommands,mH as loadExtensions,R$ as listModels,w1 as findModel,y as errorResult,Jj as discoverSkills,rQ as discoverModels,w6 as defaultThinkingLevel,Kj as defaultSkillRoots,n1 as defaultModelRef,K8 as defaultAuthFile,k$ as customMessage,PH as createCredentialResolver,O_ as createAgent,oW as coreCommands,v3 as codingProfile,e6 as checkBudget,u0 as builtinProviderConfigs,oZ as authSuccessPage,E1 as authErrorPage,W0 as SessionTree,o1 as STRUCTURED_OUTPUT_TOOL,f$ as MemorySessionStore,eW as FileSessionStore,R6 as ExtensionHost,M1 as CommandRegistry,l$ as Agent};