@mu-agent/mu 0.0.6 → 0.0.8
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 +118 -119
- package/dist/mu.js +218 -218
- package/dist/types/profile-coding/index.d.ts +0 -1
- package/dist/types/profile-coding/ripgrep.d.ts +2 -0
- package/dist/types/profile-coding/shell-inspection.d.ts +1 -0
- package/dist/types/profile-coding/tools/todo.d.ts +1 -1
- package/package.json +1 -1
- package/dist/types/profile-coding/tools/search.d.ts +0 -23
package/dist/index.js
CHANGED
|
@@ -1,25 +1,25 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var LK=Object.create;var{getPrototypeOf:UK,defineProperty:o9,getOwnPropertyNames:qK}=Object;var AK=Object.prototype.hasOwnProperty;function NK($){return this[$]}var OK,MK,R6=($,Z,Q)=>{var Y=$!=null&&typeof $==="object";if(Y){var W=Z?OK??=new WeakMap:MK??=new WeakMap,G=W.get($);if(G)return G}Q=$!=null?LK(UK($)):{};let X=Z||!$||!$.__esModule?o9(Q,"default",{value:$,enumerable:!0}):Q;for(let J of qK($))if(!AK.call(X,J))o9(X,J,{get:NK.bind($,J),enumerable:!0});if(Y)W.set($,X);return X};var M=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var G1=import.meta.require;var HZ=M(($Y)=>{Object.defineProperty($Y,"__esModule",{value:!0});$Y.regexpCode=$Y.getEsmExportName=$Y.getProperty=$Y.safeStringify=$Y.stringify=$Y.strConcat=$Y.addCodeArg=$Y.str=$Y._=$Y.nil=$Y._Code=$Y.Name=$Y.IDENTIFIER=$Y._CodeOrName=void 0;class b5{}$Y._CodeOrName=b5;$Y.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class V$ extends b5{constructor($){super();if(!$Y.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}}}$Y.Name=V$;class E0 extends b5{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 V$)Z[Q.str]=(Z[Q.str]||0)+1;return Z},{})}}$Y._Code=E0;$Y.nil=new E0("");function s7($,...Z){let Q=[$[0]],Y=0;while(Y<Z.length)V4(Q,Z[Y]),Q.push($[++Y]);return new E0(Q)}$Y._=s7;var H4=new E0("+");function e7($,...Z){let Q=[BZ($[0])],Y=0;while(Y<Z.length)Q.push(H4),V4(Q,Z[Y]),Q.push(H4,BZ($[++Y]));return wF(Q),new E0(Q)}$Y.str=e7;function V4($,Z){if(Z instanceof E0)$.push(...Z._items);else if(Z instanceof V$)$.push(Z);else $.push(RF(Z))}$Y.addCodeArg=V4;function wF($){let Z=1;while(Z<$.length-1){if($[Z]===H4){let Q=IF($[Z-1],$[Z+1]);if(Q!==void 0){$.splice(Z-1,3,Q);continue}$[Z++]="+"}Z++}}function IF($,Z){if(Z==='""')return $;if($==='""')return Z;if(typeof $=="string"){if(Z instanceof V$||$[$.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 V$))return`"${$}${Z.slice(1)}`;return}function TF($,Z){return Z.emptyStr()?$:$.emptyStr()?Z:e7`${$}${Z}`}$Y.strConcat=TF;function RF($){return typeof $=="number"||typeof $=="boolean"||$===null?$:BZ(Array.isArray($)?$.join(","):$)}function EF($){return new E0(BZ($))}$Y.stringify=EF;function BZ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}$Y.safeStringify=BZ;function CF($){return typeof $=="string"&&$Y.IDENTIFIER.test($)?new E0(`.${$}`):s7`[${$}]`}$Y.getProperty=CF;function SF($){if(typeof $=="string"&&$Y.IDENTIFIER.test($))return new E0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}$Y.getEsmExportName=SF;function yF($){return new E0($.toString())}$Y.regexpCode=yF});var L4=M((WY)=>{Object.defineProperty(WY,"__esModule",{value:!0});WY.ValueScope=WY.ValueScopeName=WY.Scope=WY.varKinds=WY.UsedValueState=void 0;var z0=HZ();class QY extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var x5;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(x5||(WY.UsedValueState=x5={}));WY.varKinds={const:new z0.Name("const"),let:new z0.Name("let"),var:new z0.Name("var")};class F4{constructor({prefixes:$,parent:Z}={}){this._names={},this._prefixes=$,this._parent=Z}toName($){return $ instanceof z0.Name?$:this.name($)}name($){return new z0.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}}}WY.Scope=F4;class D4 extends z0.Name{constructor($,Z){super(Z);this.prefix=$}setValue($,{property:Z,itemIndex:Q}){this.value=$,this.scopePath=z0._`.${new z0.Name(Z)}[${Q}]`}}WY.ValueScopeName=D4;var cF=z0._`\n`;class YY extends F4{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?cF:z0.nil}}get(){return this._scope}name($){return new D4($,this._newName($))}value($,Z){var Q;if(Z.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Y=this.toName($),{prefix:W}=Y,G=(Q=Z.key)!==null&&Q!==void 0?Q:Z.ref,X=this._values[W];if(X){let K=X.get(G);if(K)return K}else X=this._values[W]=new Map;X.set(G,Y);let J=this._scope[W]||(this._scope[W]=[]),B=J.length;return J[B]=Z.ref,Y.setValue(Z,{property:W,itemIndex:B}),Y}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 z0._`${$}${Q.scopePath}`})}scopeCode($=this._values,Z,Q){return this._reduceValues($,(Y)=>{if(Y.value===void 0)throw Error(`CodeGen: name "${Y}" has no value`);return Y.value.code},Z,Q)}_reduceValues($,Z,Q={},Y){let W=z0.nil;for(let G in $){let X=$[G];if(!X)continue;let J=Q[G]=Q[G]||new Map;X.forEach((B)=>{if(J.has(B))return;J.set(B,x5.Started);let K=Z(B);if(K){let V=this.opts.es5?WY.varKinds.var:WY.varKinds.const;W=z0._`${W}${V} ${B} = ${K};${this.opts._n}`}else if(K=Y===null||Y===void 0?void 0:Y(B))W=z0._`${W}${K}${this.opts._n}`;else throw new QY(B);J.set(B,x5.Completed)})}return W}}WY.ValueScope=YY});var b=M((F0)=>{Object.defineProperty(F0,"__esModule",{value:!0});F0.or=F0.and=F0.not=F0.CodeGen=F0.operators=F0.varKinds=F0.ValueScopeName=F0.ValueScope=F0.Scope=F0.Name=F0.regexpCode=F0.stringify=F0.getProperty=F0.nil=F0.strConcat=F0.str=F0._=void 0;var x=HZ(),C0=L4(),A1=HZ();Object.defineProperty(F0,"_",{enumerable:!0,get:function(){return A1._}});Object.defineProperty(F0,"str",{enumerable:!0,get:function(){return A1.str}});Object.defineProperty(F0,"strConcat",{enumerable:!0,get:function(){return A1.strConcat}});Object.defineProperty(F0,"nil",{enumerable:!0,get:function(){return A1.nil}});Object.defineProperty(F0,"getProperty",{enumerable:!0,get:function(){return A1.getProperty}});Object.defineProperty(F0,"stringify",{enumerable:!0,get:function(){return A1.stringify}});Object.defineProperty(F0,"regexpCode",{enumerable:!0,get:function(){return A1.regexpCode}});Object.defineProperty(F0,"Name",{enumerable:!0,get:function(){return A1.Name}});var u5=L4();Object.defineProperty(F0,"Scope",{enumerable:!0,get:function(){return u5.Scope}});Object.defineProperty(F0,"ValueScope",{enumerable:!0,get:function(){return u5.ValueScope}});Object.defineProperty(F0,"ValueScopeName",{enumerable:!0,get:function(){return u5.ValueScopeName}});Object.defineProperty(F0,"varKinds",{enumerable:!0,get:function(){return u5.varKinds}});F0.operators={GT:new x._Code(">"),GTE:new x._Code(">="),LT:new x._Code("<"),LTE:new x._Code("<="),EQ:new x._Code("==="),NEQ:new x._Code("!=="),NOT:new x._Code("!"),OR:new x._Code("||"),AND:new x._Code("&&"),ADD:new x._Code("+")};class N1{optimizeNodes(){return this}optimizeNames($,Z){return this}}class XY extends N1{constructor($,Z,Q){super();this.varKind=$,this.name=Z,this.rhs=Q}render({es5:$,_n:Z}){let Q=$?C0.varKinds.var:this.varKind,Y=this.rhs===void 0?"":` = ${this.rhs}`;return`${Q} ${this.name}${Y};`+Z}optimizeNames($,Z){if(!$[this.name.str])return;if(this.rhs)this.rhs=F$(this.rhs,$,Z);return this}get names(){return this.rhs instanceof x._CodeOrName?this.rhs.names:{}}}class A4 extends N1{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 x.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=F$(this.rhs,$,Z),this}get names(){let $=this.lhs instanceof x.Name?{}:{...this.lhs.names};return h5($,this.rhs)}}class JY extends A4{constructor($,Z,Q,Y){super($,Q,Y);this.op=Z}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class KY extends N1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class BY extends N1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class HY extends N1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class VY extends N1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,Z){return this.code=F$(this.code,$,Z),this}get names(){return this.code instanceof x._CodeOrName?this.code.names:{}}}class m5 extends N1{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,Y=Q.length;while(Y--){let W=Q[Y];if(W.optimizeNames($,Z))continue;aF($,W.names),Q.splice(Y,1)}return Q.length>0?this:void 0}get names(){return this.nodes.reduce(($,Z)=>g1($,Z.names),{})}}class O1 extends m5{render($){return"{"+$._n+super.render($)+"}"+$._n}}class zY extends m5{}class VZ extends O1{}VZ.kind="else";class e0 extends O1{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 VZ(Q):Q}if(Z){if($===!1)return Z instanceof e0?Z:Z.nodes;if(this.nodes.length)return this;return new e0(qY($),Z instanceof e0?[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=F$(this.condition,$,Z),this}get names(){let $=super.names;if(h5($,this.condition),this.else)g1($,this.else.names);return $}}e0.kind="if";class z$ extends O1{}z$.kind="for";class FY extends z${constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iteration=F$(this.iteration,$,Z),this}get names(){return g1(super.names,this.iteration.names)}}class DY extends z${constructor($,Z,Q,Y){super();this.varKind=$,this.name=Z,this.from=Q,this.to=Y}render($){let Z=$.es5?C0.varKinds.var:this.varKind,{name:Q,from:Y,to:W}=this;return`for(${Z} ${Q}=${Y}; ${Q}<${W}; ${Q}++)`+super.render($)}get names(){let $=h5(super.names,this.from);return h5($,this.to)}}class U4 extends z${constructor($,Z,Q,Y){super();this.loop=$,this.varKind=Z,this.name=Q,this.iterable=Y}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iterable=F$(this.iterable,$,Z),this}get names(){return g1(super.names,this.iterable.names)}}class k5 extends O1{constructor($,Z,Q){super();this.name=$,this.args=Z,this.async=Q}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}k5.kind="func";class f5 extends m5{render($){return"return "+super.render($)}}f5.kind="return";class LY extends O1{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,Y;return super.optimizeNames($,Z),(Q=this.catch)===null||Q===void 0||Q.optimizeNames($,Z),(Y=this.finally)===null||Y===void 0||Y.optimizeNames($,Z),this}get names(){let $=super.names;if(this.catch)g1($,this.catch.names);if(this.finally)g1($,this.finally.names);return $}}class v5 extends O1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}v5.kind="catch";class g5 extends O1{render($){return"finally"+super.render($)}}g5.kind="finally";class UY{constructor($,Z={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Z,_n:Z.lines?`
|
|
3
|
-
`:""},this._extScope=$,this._scope=new C0.Scope({parent:$}),this._nodes=[new zY]}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,Y){let W=this._scope.toName(Z);if(Q!==void 0&&Y)this._constants[W.str]=Q;return this._leafNode(new XY($,W,Q)),W}const($,Z,Q){return this._def(C0.varKinds.const,$,Z,Q)}let($,Z,Q){return this._def(C0.varKinds.let,$,Z,Q)}var($,Z,Q){return this._def(C0.varKinds.var,$,Z,Q)}assign($,Z,Q){return this._leafNode(new A4($,Z,Q))}add($,Z){return this._leafNode(new JY($,F0.operators.ADD,Z))}code($){if(typeof $=="function")$();else if($!==x.nil)this._leafNode(new VY($));return this}object(...$){let Z=["{"];for(let[Q,Y]of $){if(Z.length>1)Z.push(",");if(Z.push(Q),Q!==Y||this.opts.es5)Z.push(":"),(0,x.addCodeArg)(Z,Y)}return Z.push("}"),new x._Code(Z)}if($,Z,Q){if(this._blockNode(new e0($)),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 e0($))}else(){return this._elseNode(new VZ)}endIf(){return this._endBlockNode(e0,VZ)}_for($,Z){if(this._blockNode($),Z)this.code(Z).endFor();return this}for($,Z){return this._for(new FY($),Z)}forRange($,Z,Q,Y,W=this.opts.es5?C0.varKinds.var:C0.varKinds.let){let G=this._scope.toName($);return this._for(new DY(W,G,Z,Q),()=>Y(G))}forOf($,Z,Q,Y=C0.varKinds.const){let W=this._scope.toName($);if(this.opts.es5){let G=Z instanceof x.Name?Z:this.var("_arr",Z);return this.forRange("_i",0,x._`${G}.length`,(X)=>{this.var(W,x._`${G}[${X}]`),Q(W)})}return this._for(new U4("of",Y,W,Z),()=>Q(W))}forIn($,Z,Q,Y=this.opts.es5?C0.varKinds.var:C0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,x._`Object.keys(${Z})`,Q);let W=this._scope.toName($);return this._for(new U4("in",Y,W,Z),()=>Q(W))}endFor(){return this._endBlockNode(z$)}label($){return this._leafNode(new KY($))}break($){return this._leafNode(new BY($))}return($){let Z=new f5;if(this._blockNode(Z),this.code($),Z.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(f5)}try($,Z,Q){if(!Z&&!Q)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new LY;if(this._blockNode(Y),this.code($),Z){let W=this.name("e");this._currNode=Y.catch=new v5(W),Z(W)}if(Q)this._currNode=Y.finally=new g5,this.code(Q);return this._endBlockNode(v5,g5)}throw($){return this._leafNode(new HY($))}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=x.nil,Q,Y){if(this._blockNode(new k5($,Z,Q)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(k5)}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 e0))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]=$}}F0.CodeGen=UY;function g1($,Z){for(let Q in Z)$[Q]=($[Q]||0)+(Z[Q]||0);return $}function h5($,Z){return Z instanceof x._CodeOrName?g1($,Z.names):$}function F$($,Z,Q){if($ instanceof x.Name)return Y($);if(!W($))return $;return new x._Code($._items.reduce((G,X)=>{if(X instanceof x.Name)X=Y(X);if(X instanceof x._Code)G.push(...X._items);else G.push(X);return G},[]));function Y(G){let X=Q[G.str];if(X===void 0||Z[G.str]!==1)return G;return delete Z[G.str],X}function W(G){return G instanceof x._Code&&G._items.some((X)=>X instanceof x.Name&&Z[X.str]===1&&Q[X.str]!==void 0)}}function aF($,Z){for(let Q in Z)$[Q]=($[Q]||0)-(Z[Q]||0)}function qY($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:x._`!${q4($)}`}F0.not=qY;var rF=AY(F0.operators.AND);function tF(...$){return $.reduce(rF)}F0.and=tF;var oF=AY(F0.operators.OR);function sF(...$){return $.reduce(oF)}F0.or=sF;function AY($){return(Z,Q)=>Z===x.nil?Q:Q===x.nil?Z:x._`${q4(Z)} ${$} ${q4(Q)}`}function q4($){return $ instanceof x.Name?$:x._`(${$})`}});var k=M((RY)=>{Object.defineProperty(RY,"__esModule",{value:!0});RY.checkStrictMode=RY.getErrorPath=RY.Type=RY.useFunc=RY.setEvaluated=RY.evaluatedPropsToName=RY.mergeEvaluated=RY.eachItem=RY.unescapeJsonPointer=RY.escapeJsonPointer=RY.escapeFragment=RY.unescapeFragment=RY.schemaRefOrVal=RY.schemaHasRulesButRef=RY.schemaHasRules=RY.checkUnknownRules=RY.alwaysValidSchema=RY.toHash=void 0;var m=b(),QD=HZ();function YD($){let Z={};for(let Q of $)Z[Q]=!0;return Z}RY.toHash=YD;function WD($,Z){if(typeof Z=="boolean")return Z;if(Object.keys(Z).length===0)return!0;return jY($,Z),!PY(Z,$.self.RULES.all)}RY.alwaysValidSchema=WD;function jY($,Z=$.schema){let{opts:Q,self:Y}=$;if(!Q.strictSchema)return;if(typeof Z==="boolean")return;let W=Y.RULES.keywords;for(let G in Z)if(!W[G])TY($,`unknown keyword: "${G}"`)}RY.checkUnknownRules=jY;function PY($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Z[Q])return!0;return!1}RY.schemaHasRules=PY;function GD($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Q!=="$ref"&&Z.all[Q])return!0;return!1}RY.schemaHasRulesButRef=GD;function XD({topSchemaRef:$,schemaPath:Z},Q,Y,W){if(!W){if(typeof Q=="number"||typeof Q=="boolean")return Q;if(typeof Q=="string")return m._`${Q}`}return m._`${$}${Z}${(0,m.getProperty)(Y)}`}RY.schemaRefOrVal=XD;function JD($){return wY(decodeURIComponent($))}RY.unescapeFragment=JD;function KD($){return encodeURIComponent(O4($))}RY.escapeFragment=KD;function O4($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}RY.escapeJsonPointer=O4;function wY($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}RY.unescapeJsonPointer=wY;function BD($,Z){if(Array.isArray($))for(let Q of $)Z(Q);else Z($)}RY.eachItem=BD;function OY({mergeNames:$,mergeToName:Z,mergeValues:Q,resultToName:Y}){return(W,G,X,J)=>{let B=X===void 0?G:X instanceof m.Name?(G instanceof m.Name?$(W,G,X):Z(W,G,X),X):G instanceof m.Name?(Z(W,X,G),G):Q(G,X);return J===m.Name&&!(B instanceof m.Name)?Y(W,B):B}}RY.mergeEvaluated={props:OY({mergeNames:($,Z,Q)=>$.if(m._`${Q} !== true && ${Z} !== undefined`,()=>{$.if(m._`${Z} === true`,()=>$.assign(Q,!0),()=>$.assign(Q,m._`${Q} || {}`).code(m._`Object.assign(${Q}, ${Z})`))}),mergeToName:($,Z,Q)=>$.if(m._`${Q} !== true`,()=>{if(Z===!0)$.assign(Q,!0);else $.assign(Q,m._`${Q} || {}`),M4($,Q,Z)}),mergeValues:($,Z)=>$===!0?!0:{...$,...Z},resultToName:IY}),items:OY({mergeNames:($,Z,Q)=>$.if(m._`${Q} !== true && ${Z} !== undefined`,()=>$.assign(Q,m._`${Z} === true ? true : ${Q} > ${Z} ? ${Q} : ${Z}`)),mergeToName:($,Z,Q)=>$.if(m._`${Q} !== true`,()=>$.assign(Q,Z===!0?!0:m._`${Q} > ${Z} ? ${Q} : ${Z}`)),mergeValues:($,Z)=>$===!0?!0:Math.max($,Z),resultToName:($,Z)=>$.var("items",Z)})};function IY($,Z){if(Z===!0)return $.var("props",!0);let Q=$.var("props",m._`{}`);if(Z!==void 0)M4($,Q,Z);return Q}RY.evaluatedPropsToName=IY;function M4($,Z,Q){Object.keys(Q).forEach((Y)=>$.assign(m._`${Z}${(0,m.getProperty)(Y)}`,!0))}RY.setEvaluated=M4;var MY={};function HD($,Z){return $.scopeValue("func",{ref:Z,code:MY[Z.code]||(MY[Z.code]=new QD._Code(Z.code))})}RY.useFunc=HD;var N4;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(N4||(RY.Type=N4={}));function VD($,Z,Q){if($ instanceof m.Name){let Y=Z===N4.Num;return Q?Y?m._`"[" + ${$} + "]"`:m._`"['" + ${$} + "']"`:Y?m._`"/" + ${$}`:m._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Q?(0,m.getProperty)($).toString():"/"+O4($)}RY.getErrorPath=VD;function TY($,Z,Q=$.opts.strictSchema){if(!Q)return;if(Z=`strict mode: ${Z}`,Q===!0)throw Error(Z);$.self.logger.warn(Z)}RY.checkStrictMode=TY});var $1=M((CY)=>{Object.defineProperty(CY,"__esModule",{value:!0});var W0=b(),CD={data:new W0.Name("data"),valCxt:new W0.Name("valCxt"),instancePath:new W0.Name("instancePath"),parentData:new W0.Name("parentData"),parentDataProperty:new W0.Name("parentDataProperty"),rootData:new W0.Name("rootData"),dynamicAnchors:new W0.Name("dynamicAnchors"),vErrors:new W0.Name("vErrors"),errors:new W0.Name("errors"),this:new W0.Name("this"),self:new W0.Name("self"),scope:new W0.Name("scope"),json:new W0.Name("json"),jsonPos:new W0.Name("jsonPos"),jsonLen:new W0.Name("jsonLen"),jsonPart:new W0.Name("jsonPart")};CY.default=CD});var zZ=M((_Y)=>{Object.defineProperty(_Y,"__esModule",{value:!0});_Y.extendErrors=_Y.resetErrorsCount=_Y.reportExtraError=_Y.reportError=_Y.keyword$DataError=_Y.keywordError=void 0;var f=b(),p5=k(),J0=$1();_Y.keywordError={message:({keyword:$})=>f.str`must pass "${$}" keyword validation`};_Y.keyword$DataError={message:({keyword:$,schemaType:Z})=>Z?f.str`"${$}" keyword must be ${Z} ($data)`:f.str`"${$}" keyword is invalid ($data)`};function yD($,Z=_Y.keywordError,Q,Y){let{it:W}=$,{gen:G,compositeRule:X,allErrors:J}=W,B=bY($,Z,Q);if(Y!==null&&Y!==void 0?Y:X||J)SY(G,B);else yY(W,f._`[${B}]`)}_Y.reportError=yD;function bD($,Z=_Y.keywordError,Q){let{it:Y}=$,{gen:W,compositeRule:G,allErrors:X}=Y,J=bY($,Z,Q);if(SY(W,J),!(G||X))yY(Y,J0.default.vErrors)}_Y.reportExtraError=bD;function _D($,Z){$.assign(J0.default.errors,Z),$.if(f._`${J0.default.vErrors} !== null`,()=>$.if(Z,()=>$.assign(f._`${J0.default.vErrors}.length`,Z),()=>$.assign(J0.default.vErrors,null)))}_Y.resetErrorsCount=_D;function xD({gen:$,keyword:Z,schemaValue:Q,data:Y,errsCount:W,it:G}){if(W===void 0)throw Error("ajv implementation error");let X=$.name("err");$.forRange("i",W,J0.default.errors,(J)=>{if($.const(X,f._`${J0.default.vErrors}[${J}]`),$.if(f._`${X}.instancePath === undefined`,()=>$.assign(f._`${X}.instancePath`,(0,f.strConcat)(J0.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`,Y)})}_Y.extendErrors=xD;function SY($,Z){let Q=$.const("err",Z);$.if(f._`${J0.default.vErrors} === null`,()=>$.assign(J0.default.vErrors,f._`[${Q}]`),f._`${J0.default.vErrors}.push(${Q})`),$.code(f._`${J0.default.errors}++`)}function yY($,Z){let{gen:Q,validateName:Y,schemaEnv:W}=$;if(W.$async)Q.throw(f._`new ${$.ValidationError}(${Z})`);else Q.assign(f._`${Y}.errors`,Z),Q.return(!1)}var h1={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 bY($,Z,Q){let{createErrors:Y}=$.it;if(Y===!1)return f._`{}`;return kD($,Z,Q)}function kD($,Z,Q={}){let{gen:Y,it:W}=$,G=[fD(W,Q),vD($,Q)];return gD($,Z,G),Y.object(...G)}function fD({errorPath:$},{instancePath:Z}){let Q=Z?f.str`${$}${(0,p5.getErrorPath)(Z,p5.Type.Str)}`:$;return[J0.default.instancePath,(0,f.strConcat)(J0.default.instancePath,Q)]}function vD({keyword:$,it:{errSchemaPath:Z}},{schemaPath:Q,parentSchema:Y}){let W=Y?Z:f.str`${Z}/${$}`;if(Q)W=f.str`${W}${(0,p5.getErrorPath)(Q,p5.Type.Str)}`;return[h1.schemaPath,W]}function gD($,{params:Z,message:Q},Y){let{keyword:W,data:G,schemaValue:X,it:J}=$,{opts:B,propertyName:K,topSchemaRef:V,schemaPath:z}=J;if(Y.push([h1.keyword,W],[h1.params,typeof Z=="function"?Z($):Z||f._`{}`]),B.messages)Y.push([h1.message,typeof Q=="function"?Q($):Q]);if(B.verbose)Y.push([h1.schema,X],[h1.parentSchema,f._`${V}${z}`],[J0.default.data,G]);if(K)Y.push([h1.propertyName,K])}});var gY=M((fY)=>{Object.defineProperty(fY,"__esModule",{value:!0});fY.boolOrEmptySchema=fY.topBoolOrEmptySchema=void 0;var pD=zZ(),cD=b(),dD=$1(),iD={message:"boolean schema is false"};function nD($){let{gen:Z,schema:Q,validateName:Y}=$;if(Q===!1)kY($,!1);else if(typeof Q=="object"&&Q.$async===!0)Z.return(dD.default.data);else Z.assign(cD._`${Y}.errors`,null),Z.return(!0)}fY.topBoolOrEmptySchema=nD;function aD($,Z){let{gen:Q,schema:Y}=$;if(Y===!1)Q.var(Z,!1),kY($);else Q.var(Z,!0)}fY.boolOrEmptySchema=aD;function kY($,Z){let{gen:Q,data:Y}=$,W={gen:Q,keyword:"false schema",data:Y,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,pD.reportError)(W,iD,void 0,Z)}});var P4=M((hY)=>{Object.defineProperty(hY,"__esModule",{value:!0});hY.getRules=hY.isJSONType=void 0;var tD=["string","number","integer","boolean","null","object","array"],oD=new Set(tD);function sD($){return typeof $=="string"&&oD.has($)}hY.isJSONType=sD;function eD(){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:{}}}hY.getRules=eD});var w4=M((pY)=>{Object.defineProperty(pY,"__esModule",{value:!0});pY.shouldUseRule=pY.shouldUseGroup=pY.schemaHasRulesForType=void 0;function ZL({schema:$,self:Z},Q){let Y=Z.RULES.types[Q];return Y&&Y!==!0&&mY($,Y)}pY.schemaHasRulesForType=ZL;function mY($,Z){return Z.rules.some((Q)=>lY($,Q))}pY.shouldUseGroup=mY;function lY($,Z){var Q;return $[Z.keyword]!==void 0||((Q=Z.definition.implements)===null||Q===void 0?void 0:Q.some((Y)=>$[Y]!==void 0))}pY.shouldUseRule=lY});var FZ=M((aY)=>{Object.defineProperty(aY,"__esModule",{value:!0});aY.reportTypeError=aY.checkDataTypes=aY.checkDataType=aY.coerceAndCheckDataType=aY.getJSONTypes=aY.getSchemaTypes=aY.DataType=void 0;var WL=P4(),GL=w4(),XL=zZ(),y=b(),dY=k(),D$;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(D$||(aY.DataType=D$={}));function JL($){let Z=iY($.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}aY.getSchemaTypes=JL;function iY($){let Z=Array.isArray($)?$:$?[$]:[];if(Z.every(WL.isJSONType))return Z;throw Error("type must be JSONType or JSONType[]: "+Z.join(","))}aY.getJSONTypes=iY;function KL($,Z){let{gen:Q,data:Y,opts:W}=$,G=BL(Z,W.coerceTypes),X=Z.length>0&&!(G.length===0&&Z.length===1&&(0,GL.schemaHasRulesForType)($,Z[0]));if(X){let J=T4(Z,Y,W.strictNumbers,D$.Wrong);Q.if(J,()=>{if(G.length)HL($,Z,G);else R4($)})}return X}aY.coerceAndCheckDataType=KL;var nY=new Set(["string","number","integer","boolean","null"]);function BL($,Z){return Z?$.filter((Q)=>nY.has(Q)||Z==="array"&&Q==="array"):[]}function HL($,Z,Q){let{gen:Y,data:W,opts:G}=$,X=Y.let("dataType",y._`typeof ${W}`),J=Y.let("coerced",y._`undefined`);if(G.coerceTypes==="array")Y.if(y._`${X} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>Y.assign(W,y._`${W}[0]`).assign(X,y._`typeof ${W}`).if(T4(Z,W,G.strictNumbers),()=>Y.assign(J,W)));Y.if(y._`${J} !== undefined`);for(let K of Q)if(nY.has(K)||K==="array"&&G.coerceTypes==="array")B(K);Y.else(),R4($),Y.endIf(),Y.if(y._`${J} !== undefined`,()=>{Y.assign(W,J),VL($,J)});function B(K){switch(K){case"string":Y.elseIf(y._`${X} == "number" || ${X} == "boolean"`).assign(J,y._`"" + ${W}`).elseIf(y._`${W} === null`).assign(J,y._`""`);return;case"number":Y.elseIf(y._`${X} == "boolean" || ${W} === null
|
|
4
|
-
|| (${X} == "string" && ${W} && ${W} == +${W})`).assign(J,
|
|
5
|
-
|| (${X} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(J,
|
|
6
|
-
|| ${X} === "boolean" || ${W} === null`).assign(J,y._`[${W}]`)}}}function VL({gen:$,parentData:Z,parentDataProperty:Q},Y){$.if(y._`${Z} !== undefined`,()=>$.assign(y._`${Z}[${Q}]`,Y))}function I4($,Z,Q,Y=D$.Correct){let W=Y===D$.Correct?y.operators.EQ:y.operators.NEQ,G;switch($){case"null":return y._`${Z} ${W} null`;case"array":G=y._`Array.isArray(${Z})`;break;case"object":G=y._`${Z} && typeof ${Z} == "object" && !Array.isArray(${Z})`;break;case"integer":G=X(y._`!(${Z} % 1) && !isNaN(${Z})`);break;case"number":G=X();break;default:return y._`typeof ${Z} ${W} ${$}`}return Y===D$.Correct?G:(0,y.not)(G);function X(J=y.nil){return(0,y.and)(y._`typeof ${Z} == "number"`,J,Q?y._`isFinite(${Z})`:y.nil)}}aY.checkDataType=I4;function T4($,Z,Q,Y){if($.length===1)return I4($[0],Z,Q,Y);let W,G=(0,dY.toHash)($);if(G.array&&G.object){let X=y._`typeof ${Z} != "object"`;W=G.null?X:y._`!${Z} || ${X}`,delete G.null,delete G.array,delete G.object}else W=y.nil;if(G.number)delete G.integer;for(let X in G)W=(0,y.and)(W,I4(X,Z,Q,Y));return W}aY.checkDataTypes=T4;var zL={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:Z})=>typeof $=="string"?y._`{type: ${$}}`:y._`{type: ${Z}}`};function R4($){let Z=FL($);(0,XL.reportError)(Z,zL)}aY.reportTypeError=R4;function FL($){let{gen:Z,data:Q,schema:Y}=$,W=(0,dY.schemaRefOrVal)($,Y,"type");return{gen:Z,keyword:"type",data:Q,schema:Y.type,schemaCode:W,schemaValue:W,parentSchema:Y,params:{},it:$}}});var eY=M((oY)=>{Object.defineProperty(oY,"__esModule",{value:!0});oY.assignDefaults=void 0;var L$=b(),OL=k();function ML($,Z){let{properties:Q,items:Y}=$.schema;if(Z==="object"&&Q)for(let W in Q)tY($,W,Q[W].default);else if(Z==="array"&&Array.isArray(Y))Y.forEach((W,G)=>tY($,G,W.default))}oY.assignDefaults=ML;function tY($,Z,Q){let{gen:Y,compositeRule:W,data:G,opts:X}=$;if(Q===void 0)return;let J=L$._`${G}${(0,L$.getProperty)(Z)}`;if(W){(0,OL.checkStrictMode)($,`default is ignored for: ${J}`);return}let B=L$._`${J} === undefined`;if(X.useDefaults==="empty")B=L$._`${B} || ${J} === null || ${J} === ""`;Y.if(B,L$._`${J} = ${(0,L$.stringify)(Q)}`)}});var P0=M((QW)=>{Object.defineProperty(QW,"__esModule",{value:!0});QW.validateUnion=QW.validateArray=QW.usePattern=QW.callValidateCode=QW.schemaProperties=QW.allSchemaProperties=QW.noPropertyInData=QW.propertyInData=QW.isOwnProperty=QW.hasPropFunc=QW.reportMissingProp=QW.checkMissingProp=QW.checkReportMissingProp=void 0;var p=b(),E4=k(),M1=$1(),jL=k();function PL($,Z){let{gen:Q,data:Y,it:W}=$;Q.if(S4(Q,Y,Z,W.opts.ownProperties),()=>{$.setParams({missingProperty:p._`${Z}`},!0),$.error()})}QW.checkReportMissingProp=PL;function wL({gen:$,data:Z,it:{opts:Q}},Y,W){return(0,p.or)(...Y.map((G)=>(0,p.and)(S4($,Z,G,Q.ownProperties),p._`${W} = ${G}`)))}QW.checkMissingProp=wL;function IL($,Z){$.setParams({missingProperty:Z},!0),$.error()}QW.reportMissingProp=IL;function $W($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:p._`Object.prototype.hasOwnProperty`})}QW.hasPropFunc=$W;function C4($,Z,Q){return p._`${$W($)}.call(${Z}, ${Q})`}QW.isOwnProperty=C4;function TL($,Z,Q,Y){let W=p._`${Z}${(0,p.getProperty)(Q)} !== undefined`;return Y?p._`${W} && ${C4($,Z,Q)}`:W}QW.propertyInData=TL;function S4($,Z,Q,Y){let W=p._`${Z}${(0,p.getProperty)(Q)} === undefined`;return Y?(0,p.or)(W,(0,p.not)(C4($,Z,Q))):W}QW.noPropertyInData=S4;function ZW($){return $?Object.keys($).filter((Z)=>Z!=="__proto__"):[]}QW.allSchemaProperties=ZW;function RL($,Z){return ZW(Z).filter((Q)=>!(0,E4.alwaysValidSchema)($,Z[Q]))}QW.schemaProperties=RL;function EL({schemaCode:$,data:Z,it:{gen:Q,topSchemaRef:Y,schemaPath:W,errorPath:G},it:X},J,B,K){let V=K?p._`${$}, ${Z}, ${Y}${W}`:Z,z=[[M1.default.instancePath,(0,p.strConcat)(M1.default.instancePath,G)],[M1.default.parentData,X.parentData],[M1.default.parentDataProperty,X.parentDataProperty],[M1.default.rootData,M1.default.rootData]];if(X.opts.dynamicRef)z.push([M1.default.dynamicAnchors,M1.default.dynamicAnchors]);let F=p._`${V}, ${Q.object(...z)}`;return B!==p.nil?p._`${J}.call(${B}, ${F})`:p._`${J}(${F})`}QW.callValidateCode=EL;var CL=p._`new RegExp`;function SL({gen:$,it:{opts:Z}},Q){let Y=Z.unicodeRegExp?"u":"",{regExp:W}=Z.code,G=W(Q,Y);return $.scopeValue("pattern",{key:G.toString(),ref:G,code:p._`${W.code==="new RegExp"?CL:(0,jL.useFunc)($,W)}(${Q}, ${Y})`})}QW.usePattern=SL;function yL($){let{gen:Z,data:Q,keyword:Y,it:W}=$,G=Z.name("valid");if(W.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 B=Z.const("len",p._`${Q}.length`);Z.forRange("i",0,B,(K)=>{$.subschema({keyword:Y,dataProp:K,dataPropType:E4.Type.Num},G),Z.if((0,p.not)(G),J)})}}QW.validateArray=yL;function bL($){let{gen:Z,schema:Q,keyword:Y,it:W}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Q.some((B)=>(0,E4.alwaysValidSchema)(W,B))&&!W.opts.unevaluated)return;let X=Z.let("valid",!1),J=Z.name("_valid");Z.block(()=>Q.forEach((B,K)=>{let V=$.subschema({keyword:Y,schemaProp:K,compositeRule:!0},J);if(Z.assign(X,p._`${X} || ${J}`),!$.mergeValidEvaluated(V,J))Z.if((0,p.not)(X))})),$.result(X,()=>$.reset(),()=>$.error(!0))}QW.validateUnion=bL});var KW=M((XW)=>{Object.defineProperty(XW,"__esModule",{value:!0});XW.validateKeywordUsage=XW.validSchemaType=XW.funcKeywordCode=XW.macroKeywordCode=void 0;var K0=b(),u1=$1(),dL=P0(),iL=zZ();function nL($,Z){let{gen:Q,keyword:Y,schema:W,parentSchema:G,it:X}=$,J=Z.macro.call(X.self,W,G,X),B=GW(Q,Y,J);if(X.opts.validateSchema!==!1)X.self.validateSchema(J,!0);let K=Q.name("valid");$.subschema({schema:J,schemaPath:K0.nil,errSchemaPath:`${X.errSchemaPath}/${Y}`,topSchemaRef:B,compositeRule:!0},K),$.pass(K,()=>$.error(!0))}XW.macroKeywordCode=nL;function aL($,Z){var Q;let{gen:Y,keyword:W,schema:G,parentSchema:X,$data:J,it:B}=$;tL(B,Z);let K=!J&&Z.compile?Z.compile.call(B.self,G,X,B):Z.validate,V=GW(Y,W,K),z=Y.let("valid");$.block$data(z,F),$.ok((Q=Z.valid)!==null&&Q!==void 0?Q:z);function F(){if(Z.errors===!1){if(U(),Z.modifying)WW($);q(()=>$.error())}else{let A=Z.async?L():D();if(Z.modifying)WW($);q(()=>rL($,A))}}function L(){let A=Y.let("ruleErrs",null);return Y.try(()=>U(K0._`await `),(N)=>Y.assign(z,!1).if(K0._`${N} instanceof ${B.ValidationError}`,()=>Y.assign(A,K0._`${N}.errors`),()=>Y.throw(N))),A}function D(){let A=K0._`${V}.errors`;return Y.assign(A,null),U(K0.nil),A}function U(A=Z.async?K0._`await `:K0.nil){let N=B.opts.passContext?u1.default.this:u1.default.self,j=!(("compile"in Z)&&!J||Z.schema===!1);Y.assign(z,K0._`${A}${(0,dL.callValidateCode)($,V,N,j)}`,Z.modifying)}function q(A){var N;Y.if((0,K0.not)((N=Z.valid)!==null&&N!==void 0?N:z),A)}}XW.funcKeywordCode=aL;function WW($){let{gen:Z,data:Q,it:Y}=$;Z.if(Y.parentData,()=>Z.assign(Q,K0._`${Y.parentData}[${Y.parentDataProperty}]`))}function rL($,Z){let{gen:Q}=$;Q.if(K0._`Array.isArray(${Z})`,()=>{Q.assign(u1.default.vErrors,K0._`${u1.default.vErrors} === null ? ${Z} : ${u1.default.vErrors}.concat(${Z})`).assign(u1.default.errors,K0._`${u1.default.vErrors}.length`),(0,iL.extendErrors)($)},()=>$.error())}function tL({schemaEnv:$},Z){if(Z.async&&!$.$async)throw Error("async keyword in sync schema")}function GW($,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,K0.stringify)(Q)})}function oL($,Z,Q=!1){return!Z.length||Z.some((Y)=>Y==="array"?Array.isArray($):Y==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Y||Q&&typeof $>"u")}XW.validSchemaType=oL;function sL({schema:$,opts:Z,self:Q,errSchemaPath:Y},W,G){if(Array.isArray(W.keyword)?!W.keyword.includes(G):W.keyword!==G)throw Error("ajv implementation error");let X=W.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(W.validateSchema){if(!W.validateSchema($[G])){let B=`keyword "${G}" value is invalid at path "${Y}": `+Q.errorsText(W.validateSchema.errors);if(Z.validateSchema==="log")Q.logger.error(B);else throw Error(B)}}}XW.validateKeywordUsage=sL});var zW=M((HW)=>{Object.defineProperty(HW,"__esModule",{value:!0});HW.extendSubschemaMode=HW.extendSubschemaData=HW.getSubschema=void 0;var u0=b(),BW=k();function QU($,{keyword:Z,schemaProp:Q,schema:Y,schemaPath:W,errSchemaPath:G,topSchemaRef:X}){if(Z!==void 0&&Y!==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:u0._`${$.schemaPath}${(0,u0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${Z}`}:{schema:J[Q],schemaPath:u0._`${$.schemaPath}${(0,u0.getProperty)(Z)}${(0,u0.getProperty)(Q)}`,errSchemaPath:`${$.errSchemaPath}/${Z}/${(0,BW.escapeFragment)(Q)}`}}if(Y!==void 0){if(W===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Y,schemaPath:W,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}HW.getSubschema=QU;function YU($,Z,{dataProp:Q,dataPropType:Y,data:W,dataTypes:G,propertyName:X}){if(W!==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:K,dataPathArr:V,opts:z}=Z,F=J.let("data",u0._`${Z.data}${(0,u0.getProperty)(Q)}`,!0);B(F),$.errorPath=u0.str`${K}${(0,BW.getErrorPath)(Q,Y,z.jsPropertySyntax)}`,$.parentDataProperty=u0._`${Q}`,$.dataPathArr=[...V,$.parentDataProperty]}if(W!==void 0){let K=W instanceof u0.Name?W:J.let("data",W,!0);if(B(K),X!==void 0)$.propertyName=X}if(G)$.dataTypes=G;function B(K){$.data=K,$.dataLevel=Z.dataLevel+1,$.dataTypes=[],Z.definedProperties=new Set,$.parentData=Z.data,$.dataNames=[...Z.dataNames,K]}}HW.extendSubschemaData=YU;function WU($,{jtdDiscriminator:Z,jtdMetadata:Q,compositeRule:Y,createErrors:W,allErrors:G}){if(Y!==void 0)$.compositeRule=Y;if(W!==void 0)$.createErrors=W;if(G!==void 0)$.allErrors=G;$.jtdDiscriminator=Z,$.jtdMetadata=Q}HW.extendSubschemaMode=WU});var y4=M((R2,FW)=>{FW.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 Y,W,G;if(Array.isArray(Z)){if(Y=Z.length,Y!=Q.length)return!1;for(W=Y;W--!==0;)if(!$(Z[W],Q[W]))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),Y=G.length,Y!==Object.keys(Q).length)return!1;for(W=Y;W--!==0;)if(!Object.prototype.hasOwnProperty.call(Q,G[W]))return!1;for(W=Y;W--!==0;){var X=G[W];if(!$(Z[X],Q[X]))return!1}return!0}return Z!==Z&&Q!==Q}});var LW=M((E2,DW)=>{var j1=DW.exports=function($,Z,Q){if(typeof Z=="function")Q=Z,Z={};Q=Z.cb||Q;var Y=typeof Q=="function"?Q:Q.pre||function(){},W=Q.post||function(){};c5(Z,Y,W,$,"",$)};j1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};j1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};j1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};j1.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 c5($,Z,Q,Y,W,G,X,J,B,K){if(Y&&typeof Y=="object"&&!Array.isArray(Y)){Z(Y,W,G,X,J,B,K);for(var V in Y){var z=Y[V];if(Array.isArray(z)){if(V in j1.arrayKeywords)for(var F=0;F<z.length;F++)c5($,Z,Q,z[F],W+"/"+V+"/"+F,G,W,V,Y,F)}else if(V in j1.propsKeywords){if(z&&typeof z=="object")for(var L in z)c5($,Z,Q,z[L],W+"/"+V+"/"+JU(L),G,W,V,Y,L)}else if(V in j1.keywords||$.allKeys&&!(V in j1.skipKeywords))c5($,Z,Q,z,W+"/"+V,G,W,V,Y)}Q(Y,W,G,X,J,B,K)}}function JU($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var DZ=M((NW)=>{Object.defineProperty(NW,"__esModule",{value:!0});NW.getSchemaRefs=NW.resolveUrl=NW.normalizeId=NW._getFullPath=NW.getFullPath=NW.inlineRef=void 0;var KU=k(),BU=y4(),HU=LW(),VU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function zU($,Z=!0){if(typeof $=="boolean")return!0;if(Z===!0)return!b4($);if(!Z)return!1;return UW($)<=Z}NW.inlineRef=zU;var FU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function b4($){for(let Z in $){if(FU.has(Z))return!0;let Q=$[Z];if(Array.isArray(Q)&&Q.some(b4))return!0;if(typeof Q=="object"&&b4(Q))return!0}return!1}function UW($){let Z=0;for(let Q in $){if(Q==="$ref")return 1/0;if(Z++,VU.has(Q))continue;if(typeof $[Q]=="object")(0,KU.eachItem)($[Q],(Y)=>Z+=UW(Y));if(Z===1/0)return 1/0}return Z}function qW($,Z="",Q){if(Q!==!1)Z=U$(Z);let Y=$.parse(Z);return AW($,Y)}NW.getFullPath=qW;function AW($,Z){return $.serialize(Z).split("#")[0]+"#"}NW._getFullPath=AW;var DU=/#\/?$/;function U$($){return $?$.replace(DU,""):""}NW.normalizeId=U$;function LU($,Z,Q){return Q=U$(Q),$.resolve(Z,Q)}NW.resolveUrl=LU;var UU=/^[a-z_][-a-z0-9._]*$/i;function qU($,Z){if(typeof $=="boolean")return{};let{schemaId:Q,uriResolver:Y}=this.opts,W=U$($[Q]||Z),G={"":W},X=qW(Y,W,!1),J={},B=new Set;return HU($,{allKeys:!0},(z,F,L,D)=>{if(D===void 0)return;let U=X+F,q=G[D];if(typeof z[Q]=="string")q=A.call(this,z[Q]);N.call(this,z.$anchor),N.call(this,z.$dynamicAnchor),G[F]=q;function A(j){let P=this.opts.uriResolver.resolve;if(j=U$(q?P(q,j):j),B.has(j))throw V(j);B.add(j);let O=this.refs[j];if(typeof O=="string")O=this.refs[O];if(typeof O=="object")K(z,O.schema,j);else if(j!==U$(U))if(j[0]==="#")K(z,J[j],j),J[j]=z;else this.refs[j]=U;return j}function N(j){if(typeof j=="string"){if(!UU.test(j))throw Error(`invalid anchor "${j}"`);A.call(this,`#${j}`)}}}),J;function K(z,F,L){if(F!==void 0&&!BU(z,F))throw V(L)}function V(z){return Error(`reference "${z}" resolves to more than one schema`)}}NW.getSchemaRefs=qU});var qZ=M((kW)=>{Object.defineProperty(kW,"__esModule",{value:!0});kW.getData=kW.KeywordCxt=kW.validateFunctionCode=void 0;var IW=gY(),MW=FZ(),x4=w4(),d5=FZ(),PU=eY(),UZ=KW(),_4=zW(),I=b(),E=$1(),wU=DZ(),Z1=k(),LZ=zZ();function IU($){if(EW($)){if(CW($),RW($)){EU($);return}}TW($,()=>(0,IW.topBoolOrEmptySchema)($))}kW.validateFunctionCode=IU;function TW({gen:$,validateName:Z,schema:Q,schemaEnv:Y,opts:W},G){if(W.code.es5)$.func(Z,I._`${E.default.data}, ${E.default.valCxt}`,Y.$async,()=>{$.code(I._`"use strict"; ${jW(Q,W)}`),RU($,W),$.code(G)});else $.func(Z,I._`${E.default.data}, ${TU(W)}`,Y.$async,()=>$.code(jW(Q,W)).code(G))}function TU($){return I._`{${E.default.instancePath}="", ${E.default.parentData}, ${E.default.parentDataProperty}, ${E.default.rootData}=${E.default.data}${$.dynamicRef?I._`, ${E.default.dynamicAnchors}={}`:I.nil}}={}`}function RU($,Z){$.if(E.default.valCxt,()=>{if($.var(E.default.instancePath,I._`${E.default.valCxt}.${E.default.instancePath}`),$.var(E.default.parentData,I._`${E.default.valCxt}.${E.default.parentData}`),$.var(E.default.parentDataProperty,I._`${E.default.valCxt}.${E.default.parentDataProperty}`),$.var(E.default.rootData,I._`${E.default.valCxt}.${E.default.rootData}`),Z.dynamicRef)$.var(E.default.dynamicAnchors,I._`${E.default.valCxt}.${E.default.dynamicAnchors}`)},()=>{if($.var(E.default.instancePath,I._`""`),$.var(E.default.parentData,I._`undefined`),$.var(E.default.parentDataProperty,I._`undefined`),$.var(E.default.rootData,E.default.data),Z.dynamicRef)$.var(E.default.dynamicAnchors,I._`{}`)})}function EU($){let{schema:Z,opts:Q,gen:Y}=$;TW($,()=>{if(Q.$comment&&Z.$comment)yW($);if(_U($),Y.let(E.default.vErrors,null),Y.let(E.default.errors,0),Q.unevaluated)CU($);SW($),fU($)});return}function CU($){let{gen:Z,validateName:Q}=$;$.evaluated=Z.const("evaluated",I._`${Q}.evaluated`),Z.if(I._`${$.evaluated}.dynamicProps`,()=>Z.assign(I._`${$.evaluated}.props`,I._`undefined`)),Z.if(I._`${$.evaluated}.dynamicItems`,()=>Z.assign(I._`${$.evaluated}.items`,I._`undefined`))}function jW($,Z){let Q=typeof $=="object"&&$[Z.schemaId];return Q&&(Z.code.source||Z.code.process)?I._`/*# sourceURL=${Q} */`:I.nil}function SU($,Z){if(EW($)){if(CW($),RW($)){yU($,Z);return}}(0,IW.boolOrEmptySchema)($,Z)}function RW({schema:$,self:Z}){if(typeof $=="boolean")return!$;for(let Q in $)if(Z.RULES.all[Q])return!0;return!1}function EW($){return typeof $.schema!="boolean"}function yU($,Z){let{schema:Q,gen:Y,opts:W}=$;if(W.$comment&&Q.$comment)yW($);xU($),kU($);let G=Y.const("_errs",E.default.errors);SW($,G),Y.var(Z,I._`${G} === ${E.default.errors}`)}function CW($){(0,Z1.checkUnknownRules)($),bU($)}function SW($,Z){if($.opts.jtd)return PW($,[],!1,Z);let Q=(0,MW.getSchemaTypes)($.schema),Y=(0,MW.coerceAndCheckDataType)($,Q);PW($,Q,!Y,Z)}function bU($){let{schema:Z,errSchemaPath:Q,opts:Y,self:W}=$;if(Z.$ref&&Y.ignoreKeywordsWithRef&&(0,Z1.schemaHasRulesButRef)(Z,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${Q}"`)}function _U($){let{schema:Z,opts:Q}=$;if(Z.default!==void 0&&Q.useDefaults&&Q.strictSchema)(0,Z1.checkStrictMode)($,"default is ignored in the schema root")}function xU($){let Z=$.schema[$.opts.schemaId];if(Z)$.baseId=(0,wU.resolveUrl)($.opts.uriResolver,$.baseId,Z)}function kU($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function yW({gen:$,schemaEnv:Z,schema:Q,errSchemaPath:Y,opts:W}){let G=Q.$comment;if(W.$comment===!0)$.code(I._`${E.default.self}.logger.log(${G})`);else if(typeof W.$comment=="function"){let X=I.str`${Y}/$comment`,J=$.scopeValue("root",{ref:Z.root});$.code(I._`${E.default.self}.opts.$comment(${G}, ${X}, ${J}.schema)`)}}function fU($){let{gen:Z,schemaEnv:Q,validateName:Y,ValidationError:W,opts:G}=$;if(Q.$async)Z.if(I._`${E.default.errors} === 0`,()=>Z.return(E.default.data),()=>Z.throw(I._`new ${W}(${E.default.vErrors})`));else{if(Z.assign(I._`${Y}.errors`,E.default.vErrors),G.unevaluated)vU($);Z.return(I._`${E.default.errors} === 0`)}}function vU({gen:$,evaluated:Z,props:Q,items:Y}){if(Q instanceof I.Name)$.assign(I._`${Z}.props`,Q);if(Y instanceof I.Name)$.assign(I._`${Z}.items`,Y)}function PW($,Z,Q,Y){let{gen:W,schema:G,data:X,allErrors:J,opts:B,self:K}=$,{RULES:V}=K;if(G.$ref&&(B.ignoreKeywordsWithRef||!(0,Z1.schemaHasRulesButRef)(G,V))){W.block(()=>_W($,"$ref",V.all.$ref.definition));return}if(!B.jtd)gU($,Z);W.block(()=>{for(let F of V.rules)z(F);z(V.post)});function z(F){if(!(0,x4.shouldUseGroup)(G,F))return;if(F.type){if(W.if((0,d5.checkDataType)(F.type,X,B.strictNumbers)),wW($,F),Z.length===1&&Z[0]===F.type&&Q)W.else(),(0,d5.reportTypeError)($);W.endIf()}else wW($,F);if(!J)W.if(I._`${E.default.errors} === ${Y||0}`)}}function wW($,Z){let{gen:Q,schema:Y,opts:{useDefaults:W}}=$;if(W)(0,PU.assignDefaults)($,Z.type);Q.block(()=>{for(let G of Z.rules)if((0,x4.shouldUseRule)(Y,G))_W($,G.keyword,G.definition,Z.type)})}function gU($,Z){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(hU($,Z),!$.opts.allowUnionTypes)uU($,Z);mU($,$.dataTypes)}function hU($,Z){if(!Z.length)return;if(!$.dataTypes.length){$.dataTypes=Z;return}Z.forEach((Q)=>{if(!bW($.dataTypes,Q))k4($,`type "${Q}" not allowed by context "${$.dataTypes.join(",")}"`)}),pU($,Z)}function uU($,Z){if(Z.length>1&&!(Z.length===2&&Z.includes("null")))k4($,"use allowUnionTypes to allow union type keyword")}function mU($,Z){let Q=$.self.RULES.all;for(let Y in Q){let W=Q[Y];if(typeof W=="object"&&(0,x4.shouldUseRule)($.schema,W)){let{type:G}=W.definition;if(G.length&&!G.some((X)=>lU(Z,X)))k4($,`missing type "${G.join(",")}" for keyword "${Y}"`)}}}function lU($,Z){return $.includes(Z)||Z==="number"&&$.includes("integer")}function bW($,Z){return $.includes(Z)||Z==="integer"&&$.includes("number")}function pU($,Z){let Q=[];for(let Y of $.dataTypes)if(bW(Z,Y))Q.push(Y);else if(Z.includes("integer")&&Y==="number")Q.push("integer");$.dataTypes=Q}function k4($,Z){let Q=$.schemaEnv.baseId+$.errSchemaPath;Z+=` at "${Q}" (strictTypes)`,(0,Z1.checkStrictMode)($,Z,$.opts.strictTypes)}class f4{constructor($,Z,Q){if((0,UZ.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,Z1.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",xW(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,UZ.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",E.default.errors)}result($,Z,Q){this.failResult((0,I.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,I.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(I._`${Z} !== undefined && (${(0,I.or)(this.invalid$data(),$)})`)}error($,Z,Q){if(Z){this.setParams(Z),this._error($,Q),this.setParams({});return}this._error($,Q)}_error($,Z){($?LZ.reportExtraError:LZ.reportError)(this,this.def.error,Z)}$dataError(){(0,LZ.reportError)(this,this.def.$dataError||LZ.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,LZ.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=I.nil){this.gen.block(()=>{this.check$data($,Q),Z()})}check$data($=I.nil,Z=I.nil){if(!this.$data)return;let{gen:Q,schemaCode:Y,schemaType:W,def:G}=this;if(Q.if((0,I.or)(I._`${Y} === undefined`,Z)),$!==I.nil)Q.assign($,!0);if(W.length||G.validateSchema){if(Q.elseIf(this.invalid$data()),this.$dataError(),$!==I.nil)Q.assign($,!1)}Q.else()}invalid$data(){let{gen:$,schemaCode:Z,schemaType:Q,def:Y,it:W}=this;return(0,I.or)(G(),X());function G(){if(Q.length){if(!(Z instanceof I.Name))throw Error("ajv implementation error");let J=Array.isArray(Q)?Q:[Q];return I._`${(0,d5.checkDataTypes)(J,Z,W.opts.strictNumbers,d5.DataType.Wrong)}`}return I.nil}function X(){if(Y.validateSchema){let J=$.scopeValue("validate$data",{ref:Y.validateSchema});return I._`!${J}(${Z})`}return I.nil}}subschema($,Z){let Q=(0,_4.getSubschema)(this.it,$);(0,_4.extendSubschemaData)(Q,this.it,$),(0,_4.extendSubschemaMode)(Q,$);let Y={...this.it,...Q,items:void 0,props:void 0};return SU(Y,Z),Y}mergeEvaluated($,Z){let{it:Q,gen:Y}=this;if(!Q.opts.unevaluated)return;if(Q.props!==!0&&$.props!==void 0)Q.props=Z1.mergeEvaluated.props(Y,$.props,Q.props,Z);if(Q.items!==!0&&$.items!==void 0)Q.items=Z1.mergeEvaluated.items(Y,$.items,Q.items,Z)}mergeValidEvaluated($,Z){let{it:Q,gen:Y}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return Y.if(Z,()=>this.mergeEvaluated($,I.Name)),!0}}kW.KeywordCxt=f4;function _W($,Z,Q,Y){let W=new f4($,Q,Z);if("code"in Q)Q.code(W,Y);else if(W.$data&&Q.validate)(0,UZ.funcKeywordCode)(W,Q);else if("macro"in Q)(0,UZ.macroKeywordCode)(W,Q);else if(Q.compile||Q.validate)(0,UZ.funcKeywordCode)(W,Q)}var cU=/^\/(?:[^~]|~0|~1)*$/,dU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function xW($,{dataLevel:Z,dataNames:Q,dataPathArr:Y}){let W,G;if($==="")return E.default.rootData;if($[0]==="/"){if(!cU.test($))throw Error(`Invalid JSON-pointer: ${$}`);W=$,G=E.default.rootData}else{let K=dU.exec($);if(!K)throw Error(`Invalid JSON-pointer: ${$}`);let V=+K[1];if(W=K[2],W==="#"){if(V>=Z)throw Error(B("property/index",V));return Y[Z-V]}if(V>Z)throw Error(B("data",V));if(G=Q[Z-V],!W)return G}let X=G,J=W.split("/");for(let K of J)if(K)G=I._`${G}${(0,I.getProperty)((0,Z1.unescapeJsonPointer)(K))}`,X=I._`${X} && ${G}`;return X;function B(K,V){return`Cannot access ${K} ${V} levels up, current level is ${Z}`}}kW.getData=xW});var i5=M((gW)=>{Object.defineProperty(gW,"__esModule",{value:!0});class vW extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}gW.default=vW});var AZ=M((uW)=>{Object.defineProperty(uW,"__esModule",{value:!0});var v4=DZ();class hW extends Error{constructor($,Z,Q,Y){super(Y||`can't resolve reference ${Q} from id ${Z}`);this.missingRef=(0,v4.resolveUrl)($,Z,Q),this.missingSchema=(0,v4.normalizeId)((0,v4.getFullPath)($,this.missingRef))}}uW.default=hW});var a5=M((pW)=>{Object.defineProperty(pW,"__esModule",{value:!0});pW.resolveSchema=pW.getCompilingSchema=pW.resolveRef=pW.compileSchema=pW.SchemaEnv=void 0;var S0=b(),tU=i5(),m1=$1(),y0=DZ(),mW=k(),oU=qZ();class NZ{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,y0.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={}}}pW.SchemaEnv=NZ;function h4($){let Z=lW.call(this,$);if(Z)return Z;let Q=(0,y0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Y,lines:W}=this.opts.code,{ownProperties:G}=this.opts,X=new S0.CodeGen(this.scope,{es5:Y,lines:W,ownProperties:G}),J;if($.$async)J=X.scopeValue("Error",{ref:tU.default,code:S0._`require("ajv/dist/runtime/validation_error").default`});let B=X.scopeName("validate");$.validateName=B;let K={gen:X,allErrors:this.opts.allErrors,data:m1.default.data,parentData:m1.default.parentData,parentDataProperty:m1.default.parentDataProperty,dataNames:[m1.default.data],dataPathArr:[S0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,S0.stringify)($.schema)}:{ref:$.schema}),validateName:B,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:Q,baseId:$.baseId||Q,schemaPath:S0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:S0._`""`,opts:this.opts,self:this},V;try{this._compilations.add($),(0,oU.validateFunctionCode)(K),X.optimize(this.opts.code.optimize);let z=X.toString();if(V=`${X.scopeRefs(m1.default.scope)}return ${z}`,this.opts.code.process)V=this.opts.code.process(V,$);let L=Function(`${m1.default.self}`,`${m1.default.scope}`,V)(this,this.scope.get());if(this.scope.value(B,{ref:L}),L.errors=null,L.schema=$.schema,L.schemaEnv=$,$.$async)L.$async=!0;if(this.opts.code.source===!0)L.source={validateName:B,validateCode:z,scopeValues:X._values};if(this.opts.unevaluated){let{props:D,items:U}=K;if(L.evaluated={props:D instanceof S0.Name?void 0:D,items:U instanceof S0.Name?void 0:U,dynamicProps:D instanceof S0.Name,dynamicItems:U instanceof S0.Name},L.source)L.source.evaluated=(0,S0.stringify)(L.evaluated)}return $.validate=L,$}catch(z){if(delete $.validate,delete $.validateName,V)this.logger.error("Error compiling schema, function code:",V);throw z}finally{this._compilations.delete($)}}pW.compileSchema=h4;function sU($,Z,Q){var Y;Q=(0,y0.resolveUrl)(this.opts.uriResolver,Z,Q);let W=$.refs[Q];if(W)return W;let G=Zq.call(this,$,Q);if(G===void 0){let X=(Y=$.localRefs)===null||Y===void 0?void 0:Y[Q],{schemaId:J}=this.opts;if(X)G=new NZ({schema:X,schemaId:J,root:$,baseId:Z})}if(G===void 0)return;return $.refs[Q]=eU.call(this,G)}pW.resolveRef=sU;function eU($){if((0,y0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:h4.call(this,$)}function lW($){for(let Z of this._compilations)if($q(Z,$))return Z}pW.getCompilingSchema=lW;function $q($,Z){return $.schema===Z.schema&&$.root===Z.root&&$.baseId===Z.baseId}function Zq($,Z){let Q;while(typeof(Q=this.refs[Z])=="string")Z=Q;return Q||this.schemas[Z]||n5.call(this,$,Z)}function n5($,Z){let Q=this.opts.uriResolver.parse(Z),Y=(0,y0._getFullPath)(this.opts.uriResolver,Q),W=(0,y0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Y===W)return g4.call(this,Q,$);let G=(0,y0.normalizeId)(Y),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let J=n5.call(this,$,X);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return g4.call(this,Q,J)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)h4.call(this,X);if(G===(0,y0.normalizeId)(Z)){let{schema:J}=X,{schemaId:B}=this.opts,K=J[B];if(K)W=(0,y0.resolveUrl)(this.opts.uriResolver,W,K);return new NZ({schema:J,schemaId:B,root:$,baseId:W})}return g4.call(this,Q,X)}pW.resolveSchema=n5;var Qq=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function g4($,{baseId:Z,schema:Q,root:Y}){var W;if(((W=$.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof Q==="boolean")return;let B=Q[(0,mW.unescapeFragment)(J)];if(B===void 0)return;Q=B;let K=typeof Q==="object"&&Q[this.opts.schemaId];if(!Qq.has(J)&&K)Z=(0,y0.resolveUrl)(this.opts.uriResolver,Z,K)}let G;if(typeof Q!="boolean"&&Q.$ref&&!(0,mW.schemaHasRulesButRef)(Q,this.RULES)){let J=(0,y0.resolveUrl)(this.opts.uriResolver,Z,Q.$ref);G=n5.call(this,Y,J)}let{schemaId:X}=this.opts;if(G=G||new NZ({schema:Q,schemaId:X,root:Y,baseId:Z}),G.schema!==G.root.schema)return G;return}});var dW=M((x2,Jq)=>{Jq.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 l4=M((k2,oW)=>{var Kq=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),nW=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),u4=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),aW=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),Bq=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function m4($){let Z="",Q=0,Y=0;for(Y=0;Y<$.length;Y++){if(Q=$[Y].charCodeAt(0),Q===48)continue;if(!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[Y];break}for(Y+=1;Y<$.length;Y++){if(Q=$[Y].charCodeAt(0),!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[Y]}return Z}var Hq=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function iW($){return $.length=0,!0}function Vq($,Z,Q){if($.length){let Y=m4($);if(Y!=="")Z.push(Y);else return Q.error=!0,!1;$.length=0}return!0}function zq($){let Z=0,Q={error:!1,address:"",zone:""},Y=[],W=[],G=!1,X=!1,J=Vq;for(let B=0;B<$.length;B++){let K=$[B];if(K==="["||K==="]")continue;if(K===":"){if(G===!0)X=!0;if(!J(W,Y,Q))break;if(++Z>7){Q.error=!0;break}if(B>0&&$[B-1]===":")G=!0;Y.push(":");continue}else if(K==="%"){if(!J(W,Y,Q))break;J=iW}else{W.push(K);continue}}if(W.length)if(J===iW)Q.zone=W.join("");else if(X)Y.push(W.join(""));else Y.push(m4(W));return Q.address=Y.join(""),Q}function rW($){if(Fq($,":")<2)return{host:$,isIPV6:!1};let Z=zq($);if(!Z.error){let{address:Q,address:Y}=Z;if(Z.zone)Q+="%"+Z.zone,Y+="%25"+Z.zone;return{host:Q,isIPV6:!0,escapedHost:Y}}else return{host:$,isIPV6:!1}}function Fq($,Z){let Q=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Z)Q++;return Q}function Dq($){let Z=$,Q=[],Y=-1,W=0;while(W=Z.length){if(W===1)if(Z===".")break;else if(Z==="/"){Q.push("/");break}else{Q.push(Z);break}else if(W===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(W===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((Y=Z.indexOf("/",1))===-1){Q.push(Z);break}else Q.push(Z.slice(0,Y)),Z=Z.slice(Y)}return Q.join("")}var Lq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Uq=/[@/?#:]/g,qq=/[@/?#]/g;function tW($,Z){let Q=Z?qq:Uq;return Q.lastIndex=0,$.replace(Q,(Y)=>Lq[Y])}function Aq($,Z=!1){if($.indexOf("%")===-1)return $;let Q="";for(let Y=0;Y<$.length;Y++){if($[Y]==="%"&&Y+2<$.length){let W=$.slice(Y+1,Y+3);if(u4(W)){let G=W.toUpperCase(),X=String.fromCharCode(parseInt(G,16));if(Z&&aW(X))Q+=X;else Q+="%"+G;Y+=2;continue}}Q+=$[Y]}return Q}function Nq($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let Y=$.slice(Q+1,Q+3);if(u4(Y)){let W=Y.toUpperCase(),G=String.fromCharCode(parseInt(W,16));if(G!=="."&&aW(G))Z+=G;else Z+="%"+W;Q+=2;continue}}if(Bq($[Q]))Z+=$[Q];else Z+=escape($[Q])}return Z}function Oq($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let Y=$.slice(Q+1,Q+3);if(u4(Y)){Z+="%"+Y.toUpperCase(),Q+=2;continue}}Z+=escape($[Q])}return Z}function Mq($){let Z=[];if($.userinfo!==void 0)Z.push($.userinfo),Z.push("@");if($.host!==void 0){let Q=unescape($.host);if(!nW(Q)){let Y=rW(Q);if(Y.isIPV6===!0)Q=`[${Y.escapedHost}]`;else Q=tW(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}oW.exports={nonSimpleDomain:Hq,recomposeAuthority:Mq,reescapeHostDelimiters:tW,normalizePercentEncoding:Aq,normalizePathEncoding:Nq,escapePreservingEscapes:Oq,removeDotSegments:Dq,isIPv4:nW,isUUID:Kq,normalizeIPv6:rW,stringArrayToHexStripped:m4}});var QG=M((f2,ZG)=>{var{isUUID:jq}=l4(),Pq=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,wq=["http","https","ws","wss","urn","urn:uuid"];function Iq($){return wq.indexOf($)!==-1}function p4($){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 sW($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function eW($){let Z=String($.scheme).toLowerCase()==="https";if($.port===(Z?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function Tq($){return $.secure=p4($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function Rq($){if($.port===(p4($)?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 Eq($,Z){if(!$.path)return $.error="URN can not be parsed",$;let Q=$.path.match(Pq);if(Q){let Y=Z.scheme||$.scheme||"urn";$.nid=Q[1].toLowerCase(),$.nss=Q[2];let W=`${Y}:${Z.nid||$.nid}`,G=c4(W);if($.path=void 0,G)$=G.parse($,Z)}else $.error=$.error||"URN can not be parsed.";return $}function Cq($,Z){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Q=Z.scheme||$.scheme||"urn",Y=$.nid.toLowerCase(),W=`${Q}:${Z.nid||Y}`,G=c4(W);if(G)$=G.serialize($,Z);let X=$,J=$.nss;return X.path=`${Y||Z.nid}:${J}`,Z.skipEscape=!0,X}function Sq($,Z){let Q=$;if(Q.uuid=Q.nss,Q.nss=void 0,!Z.tolerant&&(!Q.uuid||!jq(Q.uuid)))Q.error=Q.error||"UUID is not valid.";return Q}function yq($){let Z=$;return Z.nss=($.uuid||"").toLowerCase(),Z}var $G={scheme:"http",domainHost:!0,parse:sW,serialize:eW},bq={scheme:"https",domainHost:$G.domainHost,parse:sW,serialize:eW},r5={scheme:"ws",domainHost:!0,parse:Tq,serialize:Rq},_q={scheme:"wss",domainHost:r5.domainHost,parse:r5.parse,serialize:r5.serialize},xq={scheme:"urn",parse:Eq,serialize:Cq,skipNormalize:!0},kq={scheme:"urn:uuid",parse:Sq,serialize:yq,skipNormalize:!0},t5={http:$G,https:bq,ws:r5,wss:_q,urn:xq,"urn:uuid":kq};Object.setPrototypeOf(t5,null);function c4($){return $&&(t5[$]||t5[$.toLowerCase()])||void 0}ZG.exports={wsIsSecure:p4,SCHEMES:t5,isValidSchemeName:Iq,getSchemeHandler:c4}});var KG=M((v2,o5)=>{var{normalizeIPv6:fq,removeDotSegments:OZ,recomposeAuthority:vq,normalizePercentEncoding:gq,normalizePathEncoding:hq,escapePreservingEscapes:uq,reescapeHostDelimiters:mq,isIPv4:lq,nonSimpleDomain:pq}=l4(),{SCHEMES:cq,getSchemeHandler:WG}=QG();function dq($,Z){if(typeof $==="string")$=oq($,Z);else if(typeof $==="object")$=q$(l1($,Z),Z);return $}function iq($,Z,Q){let Y=Q?Object.assign({scheme:"null"},Q):{scheme:"null"},W=GG(q$($,Y),q$(Z,Y),Y,!0);return Y.skipEscape=!0,l1(W,Y)}function GG($,Z,Q,Y){let W={};if(!Y)$=q$(l1($,Q),Q),Z=q$(l1(Z,Q),Q);if(Q=Q||{},!Q.tolerant&&Z.scheme)W.scheme=Z.scheme,W.userinfo=Z.userinfo,W.host=Z.host,W.port=Z.port,W.path=OZ(Z.path||""),W.query=Z.query;else{if(Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)W.userinfo=Z.userinfo,W.host=Z.host,W.port=Z.port,W.path=OZ(Z.path||""),W.query=Z.query;else{if(!Z.path)if(W.path=$.path,Z.query!==void 0)W.query=Z.query;else W.query=$.query;else{if(Z.path[0]==="/")W.path=OZ(Z.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)W.path="/"+Z.path;else if(!$.path)W.path=Z.path;else W.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+Z.path;W.path=OZ(W.path)}W.query=Z.query}W.userinfo=$.userinfo,W.host=$.host,W.port=$.port}W.scheme=$.scheme}return W.fragment=Z.fragment,W}function nq($,Z,Q){let Y=YG($,Q),W=YG(Z,Q);return Y!==void 0&&W!==void 0&&Y.toLowerCase()===W.toLowerCase()}function l1($,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:""},Y=Object.assign({},Z),W=[],G=WG(Y.scheme||Q.scheme);if(G&&G.serialize)G.serialize(Q,Y);if(Q.path!==void 0)if(!Y.skipEscape){if(Q.path=uq(Q.path),Q.scheme!==void 0)Q.path=Q.path.split("%3A").join(":")}else Q.path=gq(Q.path);if(Y.reference!=="suffix"&&Q.scheme)W.push(Q.scheme,":");let X=vq(Q);if(X!==void 0){if(Y.reference!=="suffix")W.push("//");if(W.push(X),Q.path&&Q.path[0]!=="/")W.push("/")}if(Q.path!==void 0){let J=Q.path;if(!Y.absolutePath&&(!G||!G.absolutePath))J=OZ(J);if(X===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);W.push(J)}if(Q.query!==void 0)W.push("?",Q.query);if(Q.fragment!==void 0)W.push("#",Q.fragment);return W.join("")}var aq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,rq=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function tq($,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 XG($,Z){let Q=Object.assign({},Z),Y={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1,G=!1;if(Q.reference==="suffix")if(Q.scheme)$=Q.scheme+":"+$;else $="//"+$;let X=$.match(rq);if(X!==null&&X[1].indexOf("\\")!==-1)Y.error="URI authority must not contain a literal backslash.",W=!0;let J=$.match(aq);if(J){if(Y.scheme=J[1],Y.userinfo=J[3],Y.host=J[4],Y.port=parseInt(J[5],10),Y.path=J[6]||"",Y.query=J[7],Y.fragment=J[8],isNaN(Y.port))Y.port=J[5];let B=tq(Y,J);if(B!==void 0)Y.error=Y.error||B,W=!0;if(Y.host)if(lq(Y.host)===!1){let z=fq(Y.host);Y.host=z.host.toLowerCase(),G=z.isIPV6}else G=!0;if(Y.scheme===void 0&&Y.userinfo===void 0&&Y.host===void 0&&Y.port===void 0&&Y.query===void 0&&!Y.path)Y.reference="same-document";else if(Y.scheme===void 0)Y.reference="relative";else if(Y.fragment===void 0)Y.reference="absolute";else Y.reference="uri";if(Q.reference&&Q.reference!=="suffix"&&Q.reference!==Y.reference)Y.error=Y.error||"URI is not a "+Q.reference+" reference.";let K=WG(Q.scheme||Y.scheme);if(!Q.unicodeSupport&&(!K||!K.unicodeSupport)){if(Y.host&&(Q.domainHost||K&&K.domainHost)&&G===!1&&pq(Y.host))try{Y.host=new URL("http://"+Y.host).hostname}catch(V){Y.error=Y.error||"Host's domain name can not be converted to ASCII: "+V}}if(!K||K&&!K.skipNormalize){if($.indexOf("%")!==-1){if(Y.scheme!==void 0)Y.scheme=unescape(Y.scheme);if(Y.host!==void 0)Y.host=mq(unescape(Y.host),G)}if(Y.path)Y.path=hq(Y.path);if(Y.fragment)try{Y.fragment=encodeURI(decodeURIComponent(Y.fragment))}catch{Y.error=Y.error||"URI malformed"}}if(K&&K.parse)K.parse(Y,Q)}else Y.error=Y.error||"URI can not be parsed.";return{parsed:Y,malformedAuthorityOrPort:W}}function q$($,Z){return XG($,Z).parsed}function oq($,Z){return JG($,Z).normalized}function JG($,Z){let{parsed:Q,malformedAuthorityOrPort:Y}=XG($,Z);return{normalized:Y?$:l1(Q,Z),malformedAuthorityOrPort:Y}}function YG($,Z){if(typeof $==="string"){let{normalized:Q,malformedAuthorityOrPort:Y}=JG($,Z);return Y?void 0:Q}if(typeof $==="object")return l1($,Z)}var d4={SCHEMES:cq,normalize:dq,resolve:iq,resolveComponent:GG,equal:nq,serialize:l1,parse:q$};o5.exports=d4;o5.exports.default=d4;o5.exports.fastUri=d4});var VG=M((HG)=>{Object.defineProperty(HG,"__esModule",{value:!0});var BG=KG();BG.code='require("ajv/dist/runtime/uri").default';HG.default=BG});var NG=M((Q1)=>{Object.defineProperty(Q1,"__esModule",{value:!0});Q1.CodeGen=Q1.Name=Q1.nil=Q1.stringify=Q1.str=Q1._=Q1.KeywordCxt=void 0;var eq=qZ();Object.defineProperty(Q1,"KeywordCxt",{enumerable:!0,get:function(){return eq.KeywordCxt}});var A$=b();Object.defineProperty(Q1,"_",{enumerable:!0,get:function(){return A$._}});Object.defineProperty(Q1,"str",{enumerable:!0,get:function(){return A$.str}});Object.defineProperty(Q1,"stringify",{enumerable:!0,get:function(){return A$.stringify}});Object.defineProperty(Q1,"nil",{enumerable:!0,get:function(){return A$.nil}});Object.defineProperty(Q1,"Name",{enumerable:!0,get:function(){return A$.Name}});Object.defineProperty(Q1,"CodeGen",{enumerable:!0,get:function(){return A$.CodeGen}});var $A=i5(),UG=AZ(),ZA=P4(),MZ=a5(),QA=b(),jZ=DZ(),s5=FZ(),n4=k(),zG=dW(),YA=VG(),qG=($,Z)=>new RegExp($,Z);qG.code="new RegExp";var WA=["removeAdditional","useDefaults","coerceTypes"],GA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),XA={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."},JA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},FG=200;function KA($){var Z,Q,Y,W,G,X,J,B,K,V,z,F,L,D,U,q,A,N,j,P,O,C,g,n,w;let _=$.strict,o=(Z=$.code)===null||Z===void 0?void 0:Z.optimize,h=o===!0||o===void 0?1:o||0,t=(Y=(Q=$.code)===null||Q===void 0?void 0:Q.regExp)!==null&&Y!==void 0?Y:qG,hZ=(W=$.uriResolver)!==null&&W!==void 0?W:YA.default;return{strictSchema:(X=(G=$.strictSchema)!==null&&G!==void 0?G:_)!==null&&X!==void 0?X:!0,strictNumbers:(B=(J=$.strictNumbers)!==null&&J!==void 0?J:_)!==null&&B!==void 0?B:!0,strictTypes:(V=(K=$.strictTypes)!==null&&K!==void 0?K:_)!==null&&V!==void 0?V:"log",strictTuples:(F=(z=$.strictTuples)!==null&&z!==void 0?z:_)!==null&&F!==void 0?F:"log",strictRequired:(D=(L=$.strictRequired)!==null&&L!==void 0?L:_)!==null&&D!==void 0?D:!1,code:$.code?{...$.code,optimize:h,regExp:t}:{optimize:h,regExp:t},loopRequired:(U=$.loopRequired)!==null&&U!==void 0?U:FG,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:FG,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:(g=$.validateFormats)!==null&&g!==void 0?g:!0,unicodeRegExp:(n=$.unicodeRegExp)!==null&&n!==void 0?n:!0,int32range:(w=$.int32range)!==null&&w!==void 0?w:!0,uriResolver:hZ}}class e5{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...KA($)};let{es5:Z,lines:Q}=this.opts.code;this.scope=new QA.ValueScope({scope:{},prefixes:GA,es5:Z,lines:Q}),this.logger=DA($.logger);let Y=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,ZA.getRules)(),DG.call(this,XA,$,"NOT SUPPORTED"),DG.call(this,JA,$,"DEPRECATED","warn"),this._metaOpts=zA.call(this),$.formats)HA.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)VA.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);BA.call(this),$.validateFormats=Y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:Z,schemaId:Q}=this.opts,Y=zG;if(Q==="id")Y={...zG},Y.id=Y.$id,delete Y.$id;if(Z&&$)this.addMetaSchema(Y,Y[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 Y=Q(Z);if(!("$async"in Q))this.errors=Q.errors;return Y}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 Y.call(this,$,Z);async function Y(K,V){await W.call(this,K.$schema);let z=this._addSchema(K,V);return z.validate||G.call(this,z)}async function W(K){if(K&&!this.getSchema(K))await Y.call(this,{$ref:K},!0)}async function G(K){try{return this._compileSchemaEnv(K)}catch(V){if(!(V instanceof UG.default))throw V;return X.call(this,V),await J.call(this,V.missingSchema),G.call(this,K)}}function X({missingSchema:K,missingRef:V}){if(this.refs[K])throw Error(`AnySchema ${K} is loaded but ${V} cannot be resolved`)}async function J(K){let V=await B.call(this,K);if(!this.refs[K])await W.call(this,V.$schema);if(!this.refs[K])this.addSchema(V,K,Z)}async function B(K){let V=this._loading[K];if(V)return V;try{return await(this._loading[K]=Q(K))}finally{delete this._loading[K]}}}addSchema($,Z,Q,Y=this.opts.validateSchema){if(Array.isArray($)){for(let G of $)this.addSchema(G,void 0,Q,Y);return this}let W;if(typeof $==="object"){let{schemaId:G}=this.opts;if(W=$[G],W!==void 0&&typeof W!="string")throw Error(`schema ${G} must be string`)}return Z=(0,jZ.normalizeId)(Z||W),this._checkUnique(Z),this.schemas[Z]=this._addSchema($,Q,Z,Y,!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 Y=this.validate(Q,$);if(!Y&&Z){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return Y}getSchema($){let Z;while(typeof(Z=LG.call(this,$))=="string")$=Z;if(Z===void 0){let{schemaId:Q}=this.opts,Y=new MZ.SchemaEnv({schema:{},schemaId:Q});if(Z=MZ.resolveSchema.call(this,Y,$),!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=LG.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,jZ.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(UA.call(this,Q,Z),!Z)return(0,n4.eachItem)(Q,(W)=>i4.call(this,W)),this;AA.call(this,Z);let Y={...Z,type:(0,s5.getJSONTypes)(Z.type),schemaType:(0,s5.getJSONTypes)(Z.schemaType)};return(0,n4.eachItem)(Q,Y.type.length===0?(W)=>i4.call(this,W,Y):(W)=>Y.type.forEach((G)=>i4.call(this,W,Y,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 Y=Q.rules.findIndex((W)=>W.keyword===$);if(Y>=0)Q.rules.splice(Y,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((Y)=>`${Q}${Y.instancePath} ${Y.message}`).reduce((Y,W)=>Y+Z+W)}$dataMetaSchema($,Z){let Q=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Y of Z){let W=Y.split("/").slice(1),G=$;for(let X of W)G=G[X];for(let X in Q){let J=Q[X];if(typeof J!="object")continue;let{$data:B}=J.definition,K=G[X];if(B&&K)G[X]=AG(K)}}return $}_removeAllSchemas($,Z){for(let Q in $){let Y=$[Q];if(!Z||Z.test(Q)){if(typeof Y=="string")delete $[Q];else if(Y&&!Y.meta)this._cache.delete(Y.schema),delete $[Q]}}}_addSchema($,Z,Q,Y=this.opts.validateSchema,W=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,jZ.normalizeId)(G||Q);let B=jZ.getSchemaRefs.call(this,$,Q);if(J=new MZ.SchemaEnv({schema:$,schemaId:X,meta:Z,baseId:Q,localRefs:B}),this._cache.set(J.schema,J),W&&!Q.startsWith("#")){if(Q)this._checkUnique(Q);this.refs[Q]=J}if(Y)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 MZ.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let Z=this.opts;this.opts=this._metaOpts;try{MZ.compileSchema.call(this,$)}finally{this.opts=Z}}}e5.ValidationError=$A.default;e5.MissingRefError=UG.default;Q1.default=e5;function DG($,Z,Q,Y="error"){for(let W in $){let G=W;if(G in Z)this.logger[Y](`${Q}: option ${W}. ${$[G]}`)}}function LG($){return $=(0,jZ.normalizeId)($),this.schemas[$]||this.refs[$]}function BA(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let Z in $)this.addSchema($[Z],Z)}function HA(){for(let $ in this.opts.formats){let Z=this.opts.formats[$];if(Z)this.addFormat($,Z)}}function VA($){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 zA(){let $={...this.opts};for(let Z of WA)delete $[Z];return $}var FA={log(){},warn(){},error(){}};function DA($){if($===!1)return FA;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var LA=/^[a-z_$][a-z0-9_$:-]*$/i;function UA($,Z){let{RULES:Q}=this;if((0,n4.eachItem)($,(Y)=>{if(Q.keywords[Y])throw Error(`Keyword ${Y} is already defined`);if(!LA.test(Y))throw Error(`Keyword ${Y} 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 i4($,Z,Q){var Y;let W=Z===null||Z===void 0?void 0:Z.post;if(Q&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=W?G.post:G.rules.find(({type:B})=>B===Q);if(!X)X={type:Q,rules:[]},G.rules.push(X);if(G.keywords[$]=!0,!Z)return;let J={keyword:$,definition:{...Z,type:(0,s5.getJSONTypes)(Z.type),schemaType:(0,s5.getJSONTypes)(Z.schemaType)}};if(Z.before)qA.call(this,X,J,Z.before);else X.rules.push(J);G.all[$]=J,(Y=Z.implements)===null||Y===void 0||Y.forEach((B)=>this.addKeyword(B))}function qA($,Z,Q){let Y=$.rules.findIndex((W)=>W.keyword===Q);if(Y>=0)$.rules.splice(Y,0,Z);else $.rules.push(Z),this.logger.warn(`rule ${Q} is not defined`)}function AA($){let{metaSchema:Z}=$;if(Z===void 0)return;if($.$data&&this.opts.$data)Z=AG(Z);$.validateSchema=this.compile(Z,!0)}var NA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function AG($){return{anyOf:[$,NA]}}});var MG=M((OG)=>{Object.defineProperty(OG,"__esModule",{value:!0});var jA={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};OG.default=jA});var RG=M((IG)=>{Object.defineProperty(IG,"__esModule",{value:!0});IG.callRef=IG.getValidate=void 0;var wA=AZ(),jG=P0(),D0=b(),N$=$1(),PG=a5(),$6=k(),IA={keyword:"$ref",schemaType:"string",code($){let{gen:Z,schema:Q,it:Y}=$,{baseId:W,schemaEnv:G,validateName:X,opts:J,self:B}=Y,{root:K}=G;if((Q==="#"||Q==="#/")&&W===K.baseId)return z();let V=PG.resolveRef.call(B,K,W,Q);if(V===void 0)throw new wA.default(Y.opts.uriResolver,W,Q);if(V instanceof PG.SchemaEnv)return F(V);return L(V);function z(){if(G===K)return Z6($,X,G,G.$async);let D=Z.scopeValue("root",{ref:K});return Z6($,D0._`${D}.validate`,K,K.$async)}function F(D){let U=wG($,D);Z6($,U,D,D.$async)}function L(D){let U=Z.scopeValue("schema",J.code.source===!0?{ref:D,code:(0,D0.stringify)(D)}:{ref:D}),q=Z.name("valid"),A=$.subschema({schema:D,dataTypes:[],schemaPath:D0.nil,topSchemaRef:U,errSchemaPath:Q},q);$.mergeEvaluated(A),$.ok(q)}}};function wG($,Z){let{gen:Q}=$;return Z.validate?Q.scopeValue("validate",{ref:Z.validate}):D0._`${Q.scopeValue("wrapper",{ref:Z})}.validate`}IG.getValidate=wG;function Z6($,Z,Q,Y){let{gen:W,it:G}=$,{allErrors:X,schemaEnv:J,opts:B}=G,K=B.passContext?N$.default.this:D0.nil;if(Y)V();else z();function V(){if(!J.$async)throw Error("async schema referenced by sync schema");let D=W.let("valid");W.try(()=>{if(W.code(D0._`await ${(0,jG.callValidateCode)($,Z,K)}`),L(Z),!X)W.assign(D,!0)},(U)=>{if(W.if(D0._`!(${U} instanceof ${G.ValidationError})`,()=>W.throw(U)),F(U),!X)W.assign(D,!1)}),$.ok(D)}function z(){$.result((0,jG.callValidateCode)($,Z,K),()=>L(Z),()=>F(Z))}function F(D){let U=D0._`${D}.errors`;W.assign(N$.default.vErrors,D0._`${N$.default.vErrors} === null ? ${U} : ${N$.default.vErrors}.concat(${U})`),W.assign(N$.default.errors,D0._`${N$.default.vErrors}.length`)}function L(D){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=$6.mergeEvaluated.props(W,q.props,G.props)}else{let A=W.var("props",D0._`${D}.evaluated.props`);G.props=$6.mergeEvaluated.props(W,A,G.props,D0.Name)}if(G.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)G.items=$6.mergeEvaluated.items(W,q.items,G.items)}else{let A=W.var("items",D0._`${D}.evaluated.items`);G.items=$6.mergeEvaluated.items(W,A,G.items,D0.Name)}}}IG.callRef=Z6;IG.default=IA});var CG=M((EG)=>{Object.defineProperty(EG,"__esModule",{value:!0});var EA=MG(),CA=RG(),SA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",EA.default,CA.default];EG.default=SA});var yG=M((SG)=>{Object.defineProperty(SG,"__esModule",{value:!0});var Q6=b(),P1=Q6.operators,Y6={maximum:{okStr:"<=",ok:P1.LTE,fail:P1.GT},minimum:{okStr:">=",ok:P1.GTE,fail:P1.LT},exclusiveMaximum:{okStr:"<",ok:P1.LT,fail:P1.GTE},exclusiveMinimum:{okStr:">",ok:P1.GT,fail:P1.LTE}},bA={message:({keyword:$,schemaCode:Z})=>Q6.str`must be ${Y6[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>Q6._`{comparison: ${Y6[$].okStr}, limit: ${Z}}`},_A={keyword:Object.keys(Y6),type:"number",schemaType:"number",$data:!0,error:bA,code($){let{keyword:Z,data:Q,schemaCode:Y}=$;$.fail$data(Q6._`${Q} ${Y6[Z].fail} ${Y} || isNaN(${Q})`)}};SG.default=_A});var _G=M((bG)=>{Object.defineProperty(bG,"__esModule",{value:!0});var PZ=b(),kA={message:({schemaCode:$})=>PZ.str`must be multiple of ${$}`,params:({schemaCode:$})=>PZ._`{multipleOf: ${$}}`},fA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:kA,code($){let{gen:Z,data:Q,schemaCode:Y,it:W}=$,G=W.opts.multipleOfPrecision,X=Z.let("res"),J=G?PZ._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:PZ._`${X} !== parseInt(${X})`;$.fail$data(PZ._`(${Y} === 0 || (${X} = ${Q}/${Y}, ${J}))`)}};bG.default=fA});var fG=M((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});function xG($){let Z=$.length,Q=0,Y=0,W;while(Y<Z)if(Q++,W=$.charCodeAt(Y++),W>=55296&&W<=56319&&Y<Z){if(W=$.charCodeAt(Y),(W&64512)===56320)Y++}return Q}kG.default=xG;xG.code='require("ajv/dist/runtime/ucs2length").default'});var gG=M((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});var p1=b(),hA=k(),uA=fG(),mA={message({keyword:$,schemaCode:Z}){let Q=$==="maxLength"?"more":"fewer";return p1.str`must NOT have ${Q} than ${Z} characters`},params:({schemaCode:$})=>p1._`{limit: ${$}}`},lA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:mA,code($){let{keyword:Z,data:Q,schemaCode:Y,it:W}=$,G=Z==="maxLength"?p1.operators.GT:p1.operators.LT,X=W.opts.unicode===!1?p1._`${Q}.length`:p1._`${(0,hA.useFunc)($.gen,uA.default)}(${Q})`;$.fail$data(p1._`${X} ${G} ${Y}`)}};vG.default=lA});var uG=M((hG)=>{Object.defineProperty(hG,"__esModule",{value:!0});var cA=P0(),dA=k(),O$=b(),iA={message:({schemaCode:$})=>O$.str`must match pattern "${$}"`,params:({schemaCode:$})=>O$._`{pattern: ${$}}`},nA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:iA,code($){let{gen:Z,data:Q,$data:Y,schema:W,schemaCode:G,it:X}=$,J=X.opts.unicodeRegExp?"u":"";if(Y){let{regExp:B}=X.opts.code,K=B.code==="new RegExp"?O$._`new RegExp`:(0,dA.useFunc)(Z,B),V=Z.let("valid");Z.try(()=>Z.assign(V,O$._`${K}(${G}, ${J}).test(${Q})`),()=>Z.assign(V,!1)),$.fail$data(O$._`!${V}`)}else{let B=(0,cA.usePattern)($,W);$.fail$data(O$._`!${B}.test(${Q})`)}}};hG.default=nA});var lG=M((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var wZ=b(),rA={message({keyword:$,schemaCode:Z}){let Q=$==="maxProperties"?"more":"fewer";return wZ.str`must NOT have ${Q} than ${Z} properties`},params:({schemaCode:$})=>wZ._`{limit: ${$}}`},tA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:rA,code($){let{keyword:Z,data:Q,schemaCode:Y}=$,W=Z==="maxProperties"?wZ.operators.GT:wZ.operators.LT;$.fail$data(wZ._`Object.keys(${Q}).length ${W} ${Y}`)}};mG.default=tA});var cG=M((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var IZ=P0(),TZ=b(),sA=k(),eA={message:({params:{missingProperty:$}})=>TZ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>TZ._`{missingProperty: ${$}}`},$N={keyword:"required",type:"object",schemaType:"array",$data:!0,error:eA,code($){let{gen:Z,schema:Q,schemaCode:Y,data:W,$data:G,it:X}=$,{opts:J}=X;if(!G&&Q.length===0)return;let B=Q.length>=J.loopRequired;if(X.allErrors)K();else V();if(J.strictRequired){let L=$.parentSchema.properties,{definedProperties:D}=$.it;for(let U of Q)if((L===null||L===void 0?void 0:L[U])===void 0&&!D.has(U)){let q=X.schemaEnv.baseId+X.errSchemaPath,A=`required property "${U}" is not defined at "${q}" (strictRequired)`;(0,sA.checkStrictMode)(X,A,X.opts.strictRequired)}}function K(){if(B||G)$.block$data(TZ.nil,z);else for(let L of Q)(0,IZ.checkReportMissingProp)($,L)}function V(){let L=Z.let("missing");if(B||G){let D=Z.let("valid",!0);$.block$data(D,()=>F(L,D)),$.ok(D)}else Z.if((0,IZ.checkMissingProp)($,Q,L)),(0,IZ.reportMissingProp)($,L),Z.else()}function z(){Z.forOf("prop",Y,(L)=>{$.setParams({missingProperty:L}),Z.if((0,IZ.noPropertyInData)(Z,W,L,J.ownProperties),()=>$.error())})}function F(L,D){$.setParams({missingProperty:L}),Z.forOf(L,Y,()=>{Z.assign(D,(0,IZ.propertyInData)(Z,W,L,J.ownProperties)),Z.if((0,TZ.not)(D),()=>{$.error(),Z.break()})},TZ.nil)}}};pG.default=$N});var iG=M((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});var RZ=b(),QN={message({keyword:$,schemaCode:Z}){let Q=$==="maxItems"?"more":"fewer";return RZ.str`must NOT have ${Q} than ${Z} items`},params:({schemaCode:$})=>RZ._`{limit: ${$}}`},YN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:QN,code($){let{keyword:Z,data:Q,schemaCode:Y}=$,W=Z==="maxItems"?RZ.operators.GT:RZ.operators.LT;$.fail$data(RZ._`${Q}.length ${W} ${Y}`)}};dG.default=YN});var W6=M((aG)=>{Object.defineProperty(aG,"__esModule",{value:!0});var nG=y4();nG.code='require("ajv/dist/runtime/equal").default';aG.default=nG});var tG=M((rG)=>{Object.defineProperty(rG,"__esModule",{value:!0});var a4=FZ(),Q0=b(),XN=k(),JN=W6(),KN={message:({params:{i:$,j:Z}})=>Q0.str`must NOT have duplicate items (items ## ${Z} and ${$} are identical)`,params:({params:{i:$,j:Z}})=>Q0._`{i: ${$}, j: ${Z}}`},BN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:KN,code($){let{gen:Z,data:Q,$data:Y,schema:W,parentSchema:G,schemaCode:X,it:J}=$;if(!Y&&!W)return;let B=Z.let("valid"),K=G.items?(0,a4.getSchemaTypes)(G.items):[];$.block$data(B,V,Q0._`${X} === false`),$.ok(B);function V(){let D=Z.let("i",Q0._`${Q}.length`),U=Z.let("j");$.setParams({i:D,j:U}),Z.assign(B,!0),Z.if(Q0._`${D} > 1`,()=>(z()?F:L)(D,U))}function z(){return K.length>0&&!K.some((D)=>D==="object"||D==="array")}function F(D,U){let q=Z.name("item"),A=(0,a4.checkDataTypes)(K,q,J.opts.strictNumbers,a4.DataType.Wrong),N=Z.const("indices",Q0._`{}`);Z.for(Q0._`;${D}--;`,()=>{if(Z.let(q,Q0._`${Q}[${D}]`),Z.if(A,Q0._`continue`),K.length>1)Z.if(Q0._`typeof ${q} == "string"`,Q0._`${q} += "_"`);Z.if(Q0._`typeof ${N}[${q}] == "number"`,()=>{Z.assign(U,Q0._`${N}[${q}]`),$.error(),Z.assign(B,!1).break()}).code(Q0._`${N}[${q}] = ${D}`)})}function L(D,U){let q=(0,XN.useFunc)(Z,JN.default),A=Z.name("outer");Z.label(A).for(Q0._`;${D}--;`,()=>Z.for(Q0._`${U} = ${D}; ${U}--;`,()=>Z.if(Q0._`${q}(${Q}[${D}], ${Q}[${U}])`,()=>{$.error(),Z.assign(B,!1).break(A)})))}}};rG.default=BN});var sG=M((oG)=>{Object.defineProperty(oG,"__esModule",{value:!0});var r4=b(),VN=k(),zN=W6(),FN={message:"must be equal to constant",params:({schemaCode:$})=>r4._`{allowedValue: ${$}}`},DN={keyword:"const",$data:!0,error:FN,code($){let{gen:Z,data:Q,$data:Y,schemaCode:W,schema:G}=$;if(Y||G&&typeof G=="object")$.fail$data(r4._`!${(0,VN.useFunc)(Z,zN.default)}(${Q}, ${W})`);else $.fail(r4._`${G} !== ${Q}`)}};oG.default=DN});var $X=M((eG)=>{Object.defineProperty(eG,"__esModule",{value:!0});var EZ=b(),UN=k(),qN=W6(),AN={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>EZ._`{allowedValues: ${$}}`},NN={keyword:"enum",schemaType:"array",$data:!0,error:AN,code($){let{gen:Z,data:Q,$data:Y,schema:W,schemaCode:G,it:X}=$;if(!Y&&W.length===0)throw Error("enum must have non-empty array");let J=W.length>=X.opts.loopEnum,B,K=()=>B!==null&&B!==void 0?B:B=(0,UN.useFunc)(Z,qN.default),V;if(J||Y)V=Z.let("valid"),$.block$data(V,z);else{if(!Array.isArray(W))throw Error("ajv implementation error");let L=Z.const("vSchema",G);V=(0,EZ.or)(...W.map((D,U)=>F(L,U)))}$.pass(V);function z(){Z.assign(V,!1),Z.forOf("v",G,(L)=>Z.if(EZ._`${K()}(${Q}, ${L})`,()=>Z.assign(V,!0).break()))}function F(L,D){let U=W[D];return typeof U==="object"&&U!==null?EZ._`${K()}(${Q}, ${L}[${D}])`:EZ._`${Q} === ${U}`}}};eG.default=NN});var QX=M((ZX)=>{Object.defineProperty(ZX,"__esModule",{value:!0});var MN=yG(),jN=_G(),PN=gG(),wN=uG(),IN=lG(),TN=cG(),RN=iG(),EN=tG(),CN=sG(),SN=$X(),yN=[MN.default,jN.default,PN.default,wN.default,IN.default,TN.default,RN.default,EN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},CN.default,SN.default];ZX.default=yN});var o4=M((WX)=>{Object.defineProperty(WX,"__esModule",{value:!0});WX.validateAdditionalItems=void 0;var c1=b(),t4=k(),_N={message:({params:{len:$}})=>c1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>c1._`{limit: ${$}}`},xN={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:_N,code($){let{parentSchema:Z,it:Q}=$,{items:Y}=Z;if(!Array.isArray(Y)){(0,t4.checkStrictMode)(Q,'"additionalItems" is ignored when "items" is not an array of schemas');return}YX($,Y)}};function YX($,Z){let{gen:Q,schema:Y,data:W,keyword:G,it:X}=$;X.items=!0;let J=Q.const("len",c1._`${W}.length`);if(Y===!1)$.setParams({len:Z.length}),$.pass(c1._`${J} <= ${Z.length}`);else if(typeof Y=="object"&&!(0,t4.alwaysValidSchema)(X,Y)){let K=Q.var("valid",c1._`${J} <= ${Z.length}`);Q.if((0,c1.not)(K),()=>B(K)),$.ok(K)}function B(K){Q.forRange("i",Z.length,J,(V)=>{if($.subschema({keyword:G,dataProp:V,dataPropType:t4.Type.Num},K),!X.allErrors)Q.if((0,c1.not)(K),()=>Q.break())})}}WX.validateAdditionalItems=YX;WX.default=xN});var s4=M((KX)=>{Object.defineProperty(KX,"__esModule",{value:!0});KX.validateTuple=void 0;var XX=b(),G6=k(),fN=P0(),vN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:Z,it:Q}=$;if(Array.isArray(Z))return JX($,"additionalItems",Z);if(Q.items=!0,(0,G6.alwaysValidSchema)(Q,Z))return;$.ok((0,fN.validateArray)($))}};function JX($,Z,Q=$.schema){let{gen:Y,parentSchema:W,data:G,keyword:X,it:J}=$;if(V(W),J.opts.unevaluated&&Q.length&&J.items!==!0)J.items=G6.mergeEvaluated.items(Y,Q.length,J.items);let B=Y.name("valid"),K=Y.const("len",XX._`${G}.length`);Q.forEach((z,F)=>{if((0,G6.alwaysValidSchema)(J,z))return;Y.if(XX._`${K} > ${F}`,()=>$.subschema({keyword:X,schemaProp:F,dataProp:F},B)),$.ok(B)});function V(z){let{opts:F,errSchemaPath:L}=J,D=Q.length,U=D===z.minItems&&(D===z.maxItems||z[Z]===!1);if(F.strictTuples&&!U){let q=`"${X}" is ${D}-tuple, but minItems or maxItems/${Z} are not specified or different at path "${L}"`;(0,G6.checkStrictMode)(J,q,F.strictTuples)}}}KX.validateTuple=JX;KX.default=vN});var VX=M((HX)=>{Object.defineProperty(HX,"__esModule",{value:!0});var hN=s4(),uN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,hN.validateTuple)($,"items")};HX.default=uN});var DX=M((FX)=>{Object.defineProperty(FX,"__esModule",{value:!0});var zX=b(),lN=k(),pN=P0(),cN=o4(),dN={message:({params:{len:$}})=>zX.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>zX._`{limit: ${$}}`},iN={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:dN,code($){let{schema:Z,parentSchema:Q,it:Y}=$,{prefixItems:W}=Q;if(Y.items=!0,(0,lN.alwaysValidSchema)(Y,Z))return;if(W)(0,cN.validateAdditionalItems)($,W);else $.ok((0,pN.validateArray)($))}};FX.default=iN});var UX=M((LX)=>{Object.defineProperty(LX,"__esModule",{value:!0});var w0=b(),X6=k(),aN={message:({params:{min:$,max:Z}})=>Z===void 0?w0.str`must contain at least ${$} valid item(s)`:w0.str`must contain at least ${$} and no more than ${Z} valid item(s)`,params:({params:{min:$,max:Z}})=>Z===void 0?w0._`{minContains: ${$}}`:w0._`{minContains: ${$}, maxContains: ${Z}}`},rN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:aN,code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,it:G}=$,X,J,{minContains:B,maxContains:K}=Y;if(G.opts.next)X=B===void 0?1:B,J=K;else X=1;let V=Z.const("len",w0._`${W}.length`);if($.setParams({min:X,max:J}),J===void 0&&X===0){(0,X6.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&X>J){(0,X6.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,X6.alwaysValidSchema)(G,Q)){let U=w0._`${V} >= ${X}`;if(J!==void 0)U=w0._`${U} && ${V} <= ${J}`;$.pass(U);return}G.items=!0;let z=Z.name("valid");if(J===void 0&&X===1)L(z,()=>Z.if(z,()=>Z.break()));else if(X===0){if(Z.let(z,!0),J!==void 0)Z.if(w0._`${W}.length > 0`,F)}else Z.let(z,!1),F();$.result(z,()=>$.reset());function F(){let U=Z.name("_valid"),q=Z.let("count",0);L(U,()=>Z.if(U,()=>D(q)))}function L(U,q){Z.forRange("i",0,V,(A)=>{$.subschema({keyword:"contains",dataProp:A,dataPropType:X6.Type.Num,compositeRule:!0},U),q()})}function D(U){if(Z.code(w0._`${U}++`),J===void 0)Z.if(w0._`${U} >= ${X}`,()=>Z.assign(z,!0).break());else if(Z.if(w0._`${U} > ${J}`,()=>Z.assign(z,!1).break()),X===1)Z.assign(z,!0);else Z.if(w0._`${U} >= ${X}`,()=>Z.assign(z,!0))}}};LX.default=rN});var jX=M((NX)=>{Object.defineProperty(NX,"__esModule",{value:!0});NX.validateSchemaDeps=NX.validatePropertyDeps=NX.error=void 0;var e4=b(),oN=k(),CZ=P0();NX.error={message:({params:{property:$,depsCount:Z,deps:Q}})=>{let Y=Z===1?"property":"properties";return e4.str`must have ${Y} ${Q} when property ${$} is present`},params:({params:{property:$,depsCount:Z,deps:Q,missingProperty:Y}})=>e4._`{property: ${$},
|
|
2
|
+
var QK=Object.create;var{getPrototypeOf:YK,defineProperty:p9,getOwnPropertyNames:WK}=Object;var GK=Object.prototype.hasOwnProperty;function XK($){return this[$]}var JK,KK,j6=($,Z,Q)=>{var Y=$!=null&&typeof $==="object";if(Y){var W=Z?JK??=new WeakMap:KK??=new WeakMap,G=W.get($);if(G)return G}Q=$!=null?QK(YK($)):{};let X=Z||!$||!$.__esModule?p9(Q,"default",{value:$,enumerable:!0}):Q;for(let J of WK($))if(!GK.call(X,J))p9(X,J,{get:XK.bind($,J),enumerable:!0});if(Y)W.set($,X);return X};var O=($,Z)=>()=>(Z||$((Z={exports:{}}).exports,Z),Z.exports);var Y1=import.meta.require;var XZ=O((iY)=>{Object.defineProperty(iY,"__esModule",{value:!0});iY.regexpCode=iY.getEsmExportName=iY.getProperty=iY.safeStringify=iY.stringify=iY.strConcat=iY.addCodeArg=iY.str=iY._=iY.nil=iY._Code=iY.Name=iY.IDENTIFIER=iY._CodeOrName=void 0;class R5{}iY._CodeOrName=R5;iY.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class K$ extends R5{constructor($){super();if(!iY.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}}}iY.Name=K$;class E0 extends R5{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 K$)Z[Q.str]=(Z[Q.str]||0)+1;return Z},{})}}iY._Code=E0;iY.nil=new E0("");function cY($,...Z){let Q=[$[0]],Y=0;while(Y<Z.length)X8(Q,Z[Y]),Q.push($[++Y]);return new E0(Q)}iY._=cY;var G8=new E0("+");function dY($,...Z){let Q=[GZ($[0])],Y=0;while(Y<Z.length)Q.push(G8),X8(Q,Z[Y]),Q.push(G8,GZ($[++Y]));return VF(Q),new E0(Q)}iY.str=dY;function X8($,Z){if(Z instanceof E0)$.push(...Z._items);else if(Z instanceof K$)$.push(Z);else $.push(LF(Z))}iY.addCodeArg=X8;function VF($){let Z=1;while(Z<$.length-1){if($[Z]===G8){let Q=zF($[Z-1],$[Z+1]);if(Q!==void 0){$.splice(Z-1,3,Q);continue}$[Z++]="+"}Z++}}function zF($,Z){if(Z==='""')return $;if($==='""')return Z;if(typeof $=="string"){if(Z instanceof K$||$[$.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 K$))return`"${$}${Z.slice(1)}`;return}function FF($,Z){return Z.emptyStr()?$:$.emptyStr()?Z:dY`${$}${Z}`}iY.strConcat=FF;function LF($){return typeof $=="number"||typeof $=="boolean"||$===null?$:GZ(Array.isArray($)?$.join(","):$)}function DF($){return new E0(GZ($))}iY.stringify=DF;function GZ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}iY.safeStringify=GZ;function UF($){return typeof $=="string"&&iY.IDENTIFIER.test($)?new E0(`.${$}`):cY`[${$}]`}iY.getProperty=UF;function qF($){if(typeof $=="string"&&iY.IDENTIFIER.test($))return new E0(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}iY.getEsmExportName=qF;function AF($){return new E0($.toString())}iY.regexpCode=AF});var H8=O((tY)=>{Object.defineProperty(tY,"__esModule",{value:!0});tY.ValueScope=tY.ValueScopeName=tY.Scope=tY.varKinds=tY.UsedValueState=void 0;var z0=XZ();class aY extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var S5;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(S5||(tY.UsedValueState=S5={}));tY.varKinds={const:new z0.Name("const"),let:new z0.Name("let"),var:new z0.Name("var")};class K8{constructor({prefixes:$,parent:Z}={}){this._names={},this._prefixes=$,this._parent=Z}toName($){return $ instanceof z0.Name?$:this.name($)}name($){return new z0.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}}}tY.Scope=K8;class B8 extends z0.Name{constructor($,Z){super(Z);this.prefix=$}setValue($,{property:Z,itemIndex:Q}){this.value=$,this.scopePath=z0._`.${new z0.Name(Z)}[${Q}]`}}tY.ValueScopeName=B8;var yF=z0._`\n`;class rY extends K8{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?yF:z0.nil}}get(){return this._scope}name($){return new B8($,this._newName($))}value($,Z){var Q;if(Z.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Y=this.toName($),{prefix:W}=Y,G=(Q=Z.key)!==null&&Q!==void 0?Q:Z.ref,X=this._values[W];if(X){let K=X.get(G);if(K)return K}else X=this._values[W]=new Map;X.set(G,Y);let J=this._scope[W]||(this._scope[W]=[]),B=J.length;return J[B]=Z.ref,Y.setValue(Z,{property:W,itemIndex:B}),Y}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 z0._`${$}${Q.scopePath}`})}scopeCode($=this._values,Z,Q){return this._reduceValues($,(Y)=>{if(Y.value===void 0)throw Error(`CodeGen: name "${Y}" has no value`);return Y.value.code},Z,Q)}_reduceValues($,Z,Q={},Y){let W=z0.nil;for(let G in $){let X=$[G];if(!X)continue;let J=Q[G]=Q[G]||new Map;X.forEach((B)=>{if(J.has(B))return;J.set(B,S5.Started);let K=Z(B);if(K){let V=this.opts.es5?tY.varKinds.var:tY.varKinds.const;W=z0._`${W}${V} ${B} = ${K};${this.opts._n}`}else if(K=Y===null||Y===void 0?void 0:Y(B))W=z0._`${W}${K}${this.opts._n}`;else throw new aY(B);J.set(B,S5.Completed)})}return W}}tY.ValueScope=rY});var b=O((F0)=>{Object.defineProperty(F0,"__esModule",{value:!0});F0.or=F0.and=F0.not=F0.CodeGen=F0.operators=F0.varKinds=F0.ValueScopeName=F0.ValueScope=F0.Scope=F0.Name=F0.regexpCode=F0.stringify=F0.getProperty=F0.nil=F0.strConcat=F0.str=F0._=void 0;var x=XZ(),S0=H8(),U1=XZ();Object.defineProperty(F0,"_",{enumerable:!0,get:function(){return U1._}});Object.defineProperty(F0,"str",{enumerable:!0,get:function(){return U1.str}});Object.defineProperty(F0,"strConcat",{enumerable:!0,get:function(){return U1.strConcat}});Object.defineProperty(F0,"nil",{enumerable:!0,get:function(){return U1.nil}});Object.defineProperty(F0,"getProperty",{enumerable:!0,get:function(){return U1.getProperty}});Object.defineProperty(F0,"stringify",{enumerable:!0,get:function(){return U1.stringify}});Object.defineProperty(F0,"regexpCode",{enumerable:!0,get:function(){return U1.regexpCode}});Object.defineProperty(F0,"Name",{enumerable:!0,get:function(){return U1.Name}});var k5=H8();Object.defineProperty(F0,"Scope",{enumerable:!0,get:function(){return k5.Scope}});Object.defineProperty(F0,"ValueScope",{enumerable:!0,get:function(){return k5.ValueScope}});Object.defineProperty(F0,"ValueScopeName",{enumerable:!0,get:function(){return k5.ValueScopeName}});Object.defineProperty(F0,"varKinds",{enumerable:!0,get:function(){return k5.varKinds}});F0.operators={GT:new x._Code(">"),GTE:new x._Code(">="),LT:new x._Code("<"),LTE:new x._Code("<="),EQ:new x._Code("==="),NEQ:new x._Code("!=="),NOT:new x._Code("!"),OR:new x._Code("||"),AND:new x._Code("&&"),ADD:new x._Code("+")};class q1{optimizeNodes(){return this}optimizeNames($,Z){return this}}class sY extends q1{constructor($,Z,Q){super();this.varKind=$,this.name=Z,this.rhs=Q}render({es5:$,_n:Z}){let Q=$?S0.varKinds.var:this.varKind,Y=this.rhs===void 0?"":` = ${this.rhs}`;return`${Q} ${this.name}${Y};`+Z}optimizeNames($,Z){if(!$[this.name.str])return;if(this.rhs)this.rhs=H$(this.rhs,$,Z);return this}get names(){return this.rhs instanceof x._CodeOrName?this.rhs.names:{}}}class F8 extends q1{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 x.Name&&!$[this.lhs.str]&&!this.sideEffects)return;return this.rhs=H$(this.rhs,$,Z),this}get names(){let $=this.lhs instanceof x.Name?{}:{...this.lhs.names};return x5($,this.rhs)}}class eY extends F8{constructor($,Z,Q,Y){super($,Q,Y);this.op=Z}render({_n:$}){return`${this.lhs} ${this.op}= ${this.rhs};`+$}}class $7 extends q1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`${this.label}:`+$}}class Z7 extends q1{constructor($){super();this.label=$,this.names={}}render({_n:$}){return`break${this.label?` ${this.label}`:""};`+$}}class Q7 extends q1{constructor($){super();this.error=$}render({_n:$}){return`throw ${this.error};`+$}get names(){return this.error.names}}class Y7 extends q1{constructor($){super();this.code=$}render({_n:$}){return`${this.code};`+$}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames($,Z){return this.code=H$(this.code,$,Z),this}get names(){return this.code instanceof x._CodeOrName?this.code.names:{}}}class f5 extends q1{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,Y=Q.length;while(Y--){let W=Q[Y];if(W.optimizeNames($,Z))continue;kF($,W.names),Q.splice(Y,1)}return Q.length>0?this:void 0}get names(){return this.nodes.reduce(($,Z)=>f1($,Z.names),{})}}class A1 extends f5{render($){return"{"+$._n+super.render($)+"}"+$._n}}class W7 extends f5{}class JZ extends A1{}JZ.kind="else";class o0 extends A1{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 JZ(Q):Q}if(Z){if($===!1)return Z instanceof o0?Z:Z.nodes;if(this.nodes.length)return this;return new o0(B7($),Z instanceof o0?[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=H$(this.condition,$,Z),this}get names(){let $=super.names;if(x5($,this.condition),this.else)f1($,this.else.names);return $}}o0.kind="if";class B$ extends A1{}B$.kind="for";class G7 extends B${constructor($){super();this.iteration=$}render($){return`for(${this.iteration})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iteration=H$(this.iteration,$,Z),this}get names(){return f1(super.names,this.iteration.names)}}class X7 extends B${constructor($,Z,Q,Y){super();this.varKind=$,this.name=Z,this.from=Q,this.to=Y}render($){let Z=$.es5?S0.varKinds.var:this.varKind,{name:Q,from:Y,to:W}=this;return`for(${Z} ${Q}=${Y}; ${Q}<${W}; ${Q}++)`+super.render($)}get names(){let $=x5(super.names,this.from);return x5($,this.to)}}class V8 extends B${constructor($,Z,Q,Y){super();this.loop=$,this.varKind=Z,this.name=Q,this.iterable=Y}render($){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render($)}optimizeNames($,Z){if(!super.optimizeNames($,Z))return;return this.iterable=H$(this.iterable,$,Z),this}get names(){return f1(super.names,this.iterable.names)}}class C5 extends A1{constructor($,Z,Q){super();this.name=$,this.args=Z,this.async=Q}render($){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render($)}}C5.kind="func";class y5 extends f5{render($){return"return "+super.render($)}}y5.kind="return";class J7 extends A1{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,Y;return super.optimizeNames($,Z),(Q=this.catch)===null||Q===void 0||Q.optimizeNames($,Z),(Y=this.finally)===null||Y===void 0||Y.optimizeNames($,Z),this}get names(){let $=super.names;if(this.catch)f1($,this.catch.names);if(this.finally)f1($,this.finally.names);return $}}class b5 extends A1{constructor($){super();this.error=$}render($){return`catch(${this.error})`+super.render($)}}b5.kind="catch";class _5 extends A1{render($){return"finally"+super.render($)}}_5.kind="finally";class K7{constructor($,Z={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...Z,_n:Z.lines?`
|
|
3
|
+
`:""},this._extScope=$,this._scope=new S0.Scope({parent:$}),this._nodes=[new W7]}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,Y){let W=this._scope.toName(Z);if(Q!==void 0&&Y)this._constants[W.str]=Q;return this._leafNode(new sY($,W,Q)),W}const($,Z,Q){return this._def(S0.varKinds.const,$,Z,Q)}let($,Z,Q){return this._def(S0.varKinds.let,$,Z,Q)}var($,Z,Q){return this._def(S0.varKinds.var,$,Z,Q)}assign($,Z,Q){return this._leafNode(new F8($,Z,Q))}add($,Z){return this._leafNode(new eY($,F0.operators.ADD,Z))}code($){if(typeof $=="function")$();else if($!==x.nil)this._leafNode(new Y7($));return this}object(...$){let Z=["{"];for(let[Q,Y]of $){if(Z.length>1)Z.push(",");if(Z.push(Q),Q!==Y||this.opts.es5)Z.push(":"),(0,x.addCodeArg)(Z,Y)}return Z.push("}"),new x._Code(Z)}if($,Z,Q){if(this._blockNode(new o0($)),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 o0($))}else(){return this._elseNode(new JZ)}endIf(){return this._endBlockNode(o0,JZ)}_for($,Z){if(this._blockNode($),Z)this.code(Z).endFor();return this}for($,Z){return this._for(new G7($),Z)}forRange($,Z,Q,Y,W=this.opts.es5?S0.varKinds.var:S0.varKinds.let){let G=this._scope.toName($);return this._for(new X7(W,G,Z,Q),()=>Y(G))}forOf($,Z,Q,Y=S0.varKinds.const){let W=this._scope.toName($);if(this.opts.es5){let G=Z instanceof x.Name?Z:this.var("_arr",Z);return this.forRange("_i",0,x._`${G}.length`,(X)=>{this.var(W,x._`${G}[${X}]`),Q(W)})}return this._for(new V8("of",Y,W,Z),()=>Q(W))}forIn($,Z,Q,Y=this.opts.es5?S0.varKinds.var:S0.varKinds.const){if(this.opts.ownProperties)return this.forOf($,x._`Object.keys(${Z})`,Q);let W=this._scope.toName($);return this._for(new V8("in",Y,W,Z),()=>Q(W))}endFor(){return this._endBlockNode(B$)}label($){return this._leafNode(new $7($))}break($){return this._leafNode(new Z7($))}return($){let Z=new y5;if(this._blockNode(Z),this.code($),Z.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(y5)}try($,Z,Q){if(!Z&&!Q)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new J7;if(this._blockNode(Y),this.code($),Z){let W=this.name("e");this._currNode=Y.catch=new b5(W),Z(W)}if(Q)this._currNode=Y.finally=new _5,this.code(Q);return this._endBlockNode(b5,_5)}throw($){return this._leafNode(new Q7($))}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=x.nil,Q,Y){if(this._blockNode(new C5($,Z,Q)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(C5)}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 o0))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]=$}}F0.CodeGen=K7;function f1($,Z){for(let Q in Z)$[Q]=($[Q]||0)+(Z[Q]||0);return $}function x5($,Z){return Z instanceof x._CodeOrName?f1($,Z.names):$}function H$($,Z,Q){if($ instanceof x.Name)return Y($);if(!W($))return $;return new x._Code($._items.reduce((G,X)=>{if(X instanceof x.Name)X=Y(X);if(X instanceof x._Code)G.push(...X._items);else G.push(X);return G},[]));function Y(G){let X=Q[G.str];if(X===void 0||Z[G.str]!==1)return G;return delete Z[G.str],X}function W(G){return G instanceof x._Code&&G._items.some((X)=>X instanceof x.Name&&Z[X.str]===1&&Q[X.str]!==void 0)}}function kF($,Z){for(let Q in Z)$[Q]=($[Q]||0)-(Z[Q]||0)}function B7($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:x._`!${z8($)}`}F0.not=B7;var fF=H7(F0.operators.AND);function vF(...$){return $.reduce(fF)}F0.and=vF;var gF=H7(F0.operators.OR);function hF(...$){return $.reduce(gF)}F0.or=hF;function H7($){return(Z,Q)=>Z===x.nil?Q:Q===x.nil?Z:x._`${z8(Z)} ${$} ${z8(Q)}`}function z8($){return $ instanceof x.Name?$:x._`(${$})`}});var k=O((N7)=>{Object.defineProperty(N7,"__esModule",{value:!0});N7.checkStrictMode=N7.getErrorPath=N7.Type=N7.useFunc=N7.setEvaluated=N7.evaluatedPropsToName=N7.mergeEvaluated=N7.eachItem=N7.unescapeJsonPointer=N7.escapeJsonPointer=N7.escapeFragment=N7.unescapeFragment=N7.schemaRefOrVal=N7.schemaHasRulesButRef=N7.schemaHasRules=N7.checkUnknownRules=N7.alwaysValidSchema=N7.toHash=void 0;var m=b(),pF=XZ();function cF($){let Z={};for(let Q of $)Z[Q]=!0;return Z}N7.toHash=cF;function dF($,Z){if(typeof Z=="boolean")return Z;if(Object.keys(Z).length===0)return!0;return L7($,Z),!D7(Z,$.self.RULES.all)}N7.alwaysValidSchema=dF;function L7($,Z=$.schema){let{opts:Q,self:Y}=$;if(!Q.strictSchema)return;if(typeof Z==="boolean")return;let W=Y.RULES.keywords;for(let G in Z)if(!W[G])A7($,`unknown keyword: "${G}"`)}N7.checkUnknownRules=L7;function D7($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Z[Q])return!0;return!1}N7.schemaHasRules=D7;function iF($,Z){if(typeof $=="boolean")return!$;for(let Q in $)if(Q!=="$ref"&&Z.all[Q])return!0;return!1}N7.schemaHasRulesButRef=iF;function nF({topSchemaRef:$,schemaPath:Z},Q,Y,W){if(!W){if(typeof Q=="number"||typeof Q=="boolean")return Q;if(typeof Q=="string")return m._`${Q}`}return m._`${$}${Z}${(0,m.getProperty)(Y)}`}N7.schemaRefOrVal=nF;function aF($){return U7(decodeURIComponent($))}N7.unescapeFragment=aF;function rF($){return encodeURIComponent(D8($))}N7.escapeFragment=rF;function D8($){if(typeof $=="number")return`${$}`;return $.replace(/~/g,"~0").replace(/\//g,"~1")}N7.escapeJsonPointer=D8;function U7($){return $.replace(/~1/g,"/").replace(/~0/g,"~")}N7.unescapeJsonPointer=U7;function tF($,Z){if(Array.isArray($))for(let Q of $)Z(Q);else Z($)}N7.eachItem=tF;function z7({mergeNames:$,mergeToName:Z,mergeValues:Q,resultToName:Y}){return(W,G,X,J)=>{let B=X===void 0?G:X instanceof m.Name?(G instanceof m.Name?$(W,G,X):Z(W,G,X),X):G instanceof m.Name?(Z(W,X,G),G):Q(G,X);return J===m.Name&&!(B instanceof m.Name)?Y(W,B):B}}N7.mergeEvaluated={props:z7({mergeNames:($,Z,Q)=>$.if(m._`${Q} !== true && ${Z} !== undefined`,()=>{$.if(m._`${Z} === true`,()=>$.assign(Q,!0),()=>$.assign(Q,m._`${Q} || {}`).code(m._`Object.assign(${Q}, ${Z})`))}),mergeToName:($,Z,Q)=>$.if(m._`${Q} !== true`,()=>{if(Z===!0)$.assign(Q,!0);else $.assign(Q,m._`${Q} || {}`),U8($,Q,Z)}),mergeValues:($,Z)=>$===!0?!0:{...$,...Z},resultToName:q7}),items:z7({mergeNames:($,Z,Q)=>$.if(m._`${Q} !== true && ${Z} !== undefined`,()=>$.assign(Q,m._`${Z} === true ? true : ${Q} > ${Z} ? ${Q} : ${Z}`)),mergeToName:($,Z,Q)=>$.if(m._`${Q} !== true`,()=>$.assign(Q,Z===!0?!0:m._`${Q} > ${Z} ? ${Q} : ${Z}`)),mergeValues:($,Z)=>$===!0?!0:Math.max($,Z),resultToName:($,Z)=>$.var("items",Z)})};function q7($,Z){if(Z===!0)return $.var("props",!0);let Q=$.var("props",m._`{}`);if(Z!==void 0)U8($,Q,Z);return Q}N7.evaluatedPropsToName=q7;function U8($,Z,Q){Object.keys(Q).forEach((Y)=>$.assign(m._`${Z}${(0,m.getProperty)(Y)}`,!0))}N7.setEvaluated=U8;var F7={};function oF($,Z){return $.scopeValue("func",{ref:Z,code:F7[Z.code]||(F7[Z.code]=new pF._Code(Z.code))})}N7.useFunc=oF;var L8;(function($){$[$.Num=0]="Num",$[$.Str=1]="Str"})(L8||(N7.Type=L8={}));function sF($,Z,Q){if($ instanceof m.Name){let Y=Z===L8.Num;return Q?Y?m._`"[" + ${$} + "]"`:m._`"['" + ${$} + "']"`:Y?m._`"/" + ${$}`:m._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return Q?(0,m.getProperty)($).toString():"/"+D8($)}N7.getErrorPath=sF;function A7($,Z,Q=$.opts.strictSchema){if(!Q)return;if(Z=`strict mode: ${Z}`,Q===!0)throw Error(Z);$.self.logger.warn(Z)}N7.checkStrictMode=A7});var s0=O((O7)=>{Object.defineProperty(O7,"__esModule",{value:!0});var Y0=b(),UL={data:new Y0.Name("data"),valCxt:new Y0.Name("valCxt"),instancePath:new Y0.Name("instancePath"),parentData:new Y0.Name("parentData"),parentDataProperty:new Y0.Name("parentDataProperty"),rootData:new Y0.Name("rootData"),dynamicAnchors:new Y0.Name("dynamicAnchors"),vErrors:new Y0.Name("vErrors"),errors:new Y0.Name("errors"),this:new Y0.Name("this"),self:new Y0.Name("self"),scope:new Y0.Name("scope"),json:new Y0.Name("json"),jsonPos:new Y0.Name("jsonPos"),jsonLen:new Y0.Name("jsonLen"),jsonPart:new Y0.Name("jsonPart")};O7.default=UL});var KZ=O((T7)=>{Object.defineProperty(T7,"__esModule",{value:!0});T7.extendErrors=T7.resetErrorsCount=T7.reportExtraError=T7.reportError=T7.keyword$DataError=T7.keywordError=void 0;var f=b(),g5=k(),J0=s0();T7.keywordError={message:({keyword:$})=>f.str`must pass "${$}" keyword validation`};T7.keyword$DataError={message:({keyword:$,schemaType:Z})=>Z?f.str`"${$}" keyword must be ${Z} ($data)`:f.str`"${$}" keyword is invalid ($data)`};function AL($,Z=T7.keywordError,Q,Y){let{it:W}=$,{gen:G,compositeRule:X,allErrors:J}=W,B=w7($,Z,Q);if(Y!==null&&Y!==void 0?Y:X||J)j7(G,B);else P7(W,f._`[${B}]`)}T7.reportError=AL;function NL($,Z=T7.keywordError,Q){let{it:Y}=$,{gen:W,compositeRule:G,allErrors:X}=Y,J=w7($,Z,Q);if(j7(W,J),!(G||X))P7(Y,J0.default.vErrors)}T7.reportExtraError=NL;function ML($,Z){$.assign(J0.default.errors,Z),$.if(f._`${J0.default.vErrors} !== null`,()=>$.if(Z,()=>$.assign(f._`${J0.default.vErrors}.length`,Z),()=>$.assign(J0.default.vErrors,null)))}T7.resetErrorsCount=ML;function OL({gen:$,keyword:Z,schemaValue:Q,data:Y,errsCount:W,it:G}){if(W===void 0)throw Error("ajv implementation error");let X=$.name("err");$.forRange("i",W,J0.default.errors,(J)=>{if($.const(X,f._`${J0.default.vErrors}[${J}]`),$.if(f._`${X}.instancePath === undefined`,()=>$.assign(f._`${X}.instancePath`,(0,f.strConcat)(J0.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`,Y)})}T7.extendErrors=OL;function j7($,Z){let Q=$.const("err",Z);$.if(f._`${J0.default.vErrors} === null`,()=>$.assign(J0.default.vErrors,f._`[${Q}]`),f._`${J0.default.vErrors}.push(${Q})`),$.code(f._`${J0.default.errors}++`)}function P7($,Z){let{gen:Q,validateName:Y,schemaEnv:W}=$;if(W.$async)Q.throw(f._`new ${$.ValidationError}(${Z})`);else Q.assign(f._`${Y}.errors`,Z),Q.return(!1)}var v1={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 w7($,Z,Q){let{createErrors:Y}=$.it;if(Y===!1)return f._`{}`;return jL($,Z,Q)}function jL($,Z,Q={}){let{gen:Y,it:W}=$,G=[PL(W,Q),wL($,Q)];return TL($,Z,G),Y.object(...G)}function PL({errorPath:$},{instancePath:Z}){let Q=Z?f.str`${$}${(0,g5.getErrorPath)(Z,g5.Type.Str)}`:$;return[J0.default.instancePath,(0,f.strConcat)(J0.default.instancePath,Q)]}function wL({keyword:$,it:{errSchemaPath:Z}},{schemaPath:Q,parentSchema:Y}){let W=Y?Z:f.str`${Z}/${$}`;if(Q)W=f.str`${W}${(0,g5.getErrorPath)(Q,g5.Type.Str)}`;return[v1.schemaPath,W]}function TL($,{params:Z,message:Q},Y){let{keyword:W,data:G,schemaValue:X,it:J}=$,{opts:B,propertyName:K,topSchemaRef:V,schemaPath:z}=J;if(Y.push([v1.keyword,W],[v1.params,typeof Z=="function"?Z($):Z||f._`{}`]),B.messages)Y.push([v1.message,typeof Q=="function"?Q($):Q]);if(B.verbose)Y.push([v1.schema,X],[v1.parentSchema,f._`${V}${z}`],[J0.default.data,G]);if(K)Y.push([v1.propertyName,K])}});var C7=O((E7)=>{Object.defineProperty(E7,"__esModule",{value:!0});E7.boolOrEmptySchema=E7.topBoolOrEmptySchema=void 0;var CL=KZ(),yL=b(),bL=s0(),_L={message:"boolean schema is false"};function xL($){let{gen:Z,schema:Q,validateName:Y}=$;if(Q===!1)R7($,!1);else if(typeof Q=="object"&&Q.$async===!0)Z.return(bL.default.data);else Z.assign(yL._`${Y}.errors`,null),Z.return(!0)}E7.topBoolOrEmptySchema=xL;function kL($,Z){let{gen:Q,schema:Y}=$;if(Y===!1)Q.var(Z,!1),R7($);else Q.var(Z,!0)}E7.boolOrEmptySchema=kL;function R7($,Z){let{gen:Q,data:Y}=$,W={gen:Q,keyword:"false schema",data:Y,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:$};(0,CL.reportError)(W,_L,void 0,Z)}});var A8=O((y7)=>{Object.defineProperty(y7,"__esModule",{value:!0});y7.getRules=y7.isJSONType=void 0;var vL=["string","number","integer","boolean","null","object","array"],gL=new Set(vL);function hL($){return typeof $=="string"&&gL.has($)}y7.isJSONType=hL;function uL(){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:{}}}y7.getRules=uL});var N8=O((k7)=>{Object.defineProperty(k7,"__esModule",{value:!0});k7.shouldUseRule=k7.shouldUseGroup=k7.schemaHasRulesForType=void 0;function lL({schema:$,self:Z},Q){let Y=Z.RULES.types[Q];return Y&&Y!==!0&&_7($,Y)}k7.schemaHasRulesForType=lL;function _7($,Z){return Z.rules.some((Q)=>x7($,Q))}k7.shouldUseGroup=_7;function x7($,Z){var Q;return $[Z.keyword]!==void 0||((Q=Z.definition.implements)===null||Q===void 0?void 0:Q.some((Y)=>$[Y]!==void 0))}k7.shouldUseRule=x7});var BZ=O((u7)=>{Object.defineProperty(u7,"__esModule",{value:!0});u7.reportTypeError=u7.checkDataTypes=u7.checkDataType=u7.coerceAndCheckDataType=u7.getJSONTypes=u7.getSchemaTypes=u7.DataType=void 0;var dL=A8(),iL=N8(),nL=KZ(),C=b(),v7=k(),V$;(function($){$[$.Correct=0]="Correct",$[$.Wrong=1]="Wrong"})(V$||(u7.DataType=V$={}));function aL($){let Z=g7($.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}u7.getSchemaTypes=aL;function g7($){let Z=Array.isArray($)?$:$?[$]:[];if(Z.every(dL.isJSONType))return Z;throw Error("type must be JSONType or JSONType[]: "+Z.join(","))}u7.getJSONTypes=g7;function rL($,Z){let{gen:Q,data:Y,opts:W}=$,G=tL(Z,W.coerceTypes),X=Z.length>0&&!(G.length===0&&Z.length===1&&(0,iL.schemaHasRulesForType)($,Z[0]));if(X){let J=O8(Z,Y,W.strictNumbers,V$.Wrong);Q.if(J,()=>{if(G.length)oL($,Z,G);else j8($)})}return X}u7.coerceAndCheckDataType=rL;var h7=new Set(["string","number","integer","boolean","null"]);function tL($,Z){return Z?$.filter((Q)=>h7.has(Q)||Z==="array"&&Q==="array"):[]}function oL($,Z,Q){let{gen:Y,data:W,opts:G}=$,X=Y.let("dataType",C._`typeof ${W}`),J=Y.let("coerced",C._`undefined`);if(G.coerceTypes==="array")Y.if(C._`${X} == 'object' && Array.isArray(${W}) && ${W}.length == 1`,()=>Y.assign(W,C._`${W}[0]`).assign(X,C._`typeof ${W}`).if(O8(Z,W,G.strictNumbers),()=>Y.assign(J,W)));Y.if(C._`${J} !== undefined`);for(let K of Q)if(h7.has(K)||K==="array"&&G.coerceTypes==="array")B(K);Y.else(),j8($),Y.endIf(),Y.if(C._`${J} !== undefined`,()=>{Y.assign(W,J),sL($,J)});function B(K){switch(K){case"string":Y.elseIf(C._`${X} == "number" || ${X} == "boolean"`).assign(J,C._`"" + ${W}`).elseIf(C._`${W} === null`).assign(J,C._`""`);return;case"number":Y.elseIf(C._`${X} == "boolean" || ${W} === null
|
|
4
|
+
|| (${X} == "string" && ${W} && ${W} == +${W})`).assign(J,C._`+${W}`);return;case"integer":Y.elseIf(C._`${X} === "boolean" || ${W} === null
|
|
5
|
+
|| (${X} === "string" && ${W} && ${W} == +${W} && !(${W} % 1))`).assign(J,C._`+${W}`);return;case"boolean":Y.elseIf(C._`${W} === "false" || ${W} === 0 || ${W} === null`).assign(J,!1).elseIf(C._`${W} === "true" || ${W} === 1`).assign(J,!0);return;case"null":Y.elseIf(C._`${W} === "" || ${W} === 0 || ${W} === false`),Y.assign(J,null);return;case"array":Y.elseIf(C._`${X} === "string" || ${X} === "number"
|
|
6
|
+
|| ${X} === "boolean" || ${W} === null`).assign(J,C._`[${W}]`)}}}function sL({gen:$,parentData:Z,parentDataProperty:Q},Y){$.if(C._`${Z} !== undefined`,()=>$.assign(C._`${Z}[${Q}]`,Y))}function M8($,Z,Q,Y=V$.Correct){let W=Y===V$.Correct?C.operators.EQ:C.operators.NEQ,G;switch($){case"null":return C._`${Z} ${W} 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} ${W} ${$}`}return Y===V$.Correct?G:(0,C.not)(G);function X(J=C.nil){return(0,C.and)(C._`typeof ${Z} == "number"`,J,Q?C._`isFinite(${Z})`:C.nil)}}u7.checkDataType=M8;function O8($,Z,Q,Y){if($.length===1)return M8($[0],Z,Q,Y);let W,G=(0,v7.toHash)($);if(G.array&&G.object){let X=C._`typeof ${Z} != "object"`;W=G.null?X:C._`!${Z} || ${X}`,delete G.null,delete G.array,delete G.object}else W=C.nil;if(G.number)delete G.integer;for(let X in G)W=(0,C.and)(W,M8(X,Z,Q,Y));return W}u7.checkDataTypes=O8;var eL={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:Z})=>typeof $=="string"?C._`{type: ${$}}`:C._`{type: ${Z}}`};function j8($){let Z=$D($);(0,nL.reportError)(Z,eL)}u7.reportTypeError=j8;function $D($){let{gen:Z,data:Q,schema:Y}=$,W=(0,v7.schemaRefOrVal)($,Y,"type");return{gen:Z,keyword:"type",data:Q,schema:Y.type,schemaCode:W,schemaValue:W,parentSchema:Y,params:{},it:$}}});var d7=O((p7)=>{Object.defineProperty(p7,"__esModule",{value:!0});p7.assignDefaults=void 0;var z$=b(),JD=k();function KD($,Z){let{properties:Q,items:Y}=$.schema;if(Z==="object"&&Q)for(let W in Q)l7($,W,Q[W].default);else if(Z==="array"&&Array.isArray(Y))Y.forEach((W,G)=>l7($,G,W.default))}p7.assignDefaults=KD;function l7($,Z,Q){let{gen:Y,compositeRule:W,data:G,opts:X}=$;if(Q===void 0)return;let J=z$._`${G}${(0,z$.getProperty)(Z)}`;if(W){(0,JD.checkStrictMode)($,`default is ignored for: ${J}`);return}let B=z$._`${J} === undefined`;if(X.useDefaults==="empty")B=z$._`${B} || ${J} === null || ${J} === ""`;Y.if(B,z$._`${J} = ${(0,z$.stringify)(Q)}`)}});var P0=O((a7)=>{Object.defineProperty(a7,"__esModule",{value:!0});a7.validateUnion=a7.validateArray=a7.usePattern=a7.callValidateCode=a7.schemaProperties=a7.allSchemaProperties=a7.noPropertyInData=a7.propertyInData=a7.isOwnProperty=a7.hasPropFunc=a7.reportMissingProp=a7.checkMissingProp=a7.checkReportMissingProp=void 0;var p=b(),P8=k(),N1=s0(),BD=k();function HD($,Z){let{gen:Q,data:Y,it:W}=$;Q.if(T8(Q,Y,Z,W.opts.ownProperties),()=>{$.setParams({missingProperty:p._`${Z}`},!0),$.error()})}a7.checkReportMissingProp=HD;function VD({gen:$,data:Z,it:{opts:Q}},Y,W){return(0,p.or)(...Y.map((G)=>(0,p.and)(T8($,Z,G,Q.ownProperties),p._`${W} = ${G}`)))}a7.checkMissingProp=VD;function zD($,Z){$.setParams({missingProperty:Z},!0),$.error()}a7.reportMissingProp=zD;function i7($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:p._`Object.prototype.hasOwnProperty`})}a7.hasPropFunc=i7;function w8($,Z,Q){return p._`${i7($)}.call(${Z}, ${Q})`}a7.isOwnProperty=w8;function FD($,Z,Q,Y){let W=p._`${Z}${(0,p.getProperty)(Q)} !== undefined`;return Y?p._`${W} && ${w8($,Z,Q)}`:W}a7.propertyInData=FD;function T8($,Z,Q,Y){let W=p._`${Z}${(0,p.getProperty)(Q)} === undefined`;return Y?(0,p.or)(W,(0,p.not)(w8($,Z,Q))):W}a7.noPropertyInData=T8;function n7($){return $?Object.keys($).filter((Z)=>Z!=="__proto__"):[]}a7.allSchemaProperties=n7;function LD($,Z){return n7(Z).filter((Q)=>!(0,P8.alwaysValidSchema)($,Z[Q]))}a7.schemaProperties=LD;function DD({schemaCode:$,data:Z,it:{gen:Q,topSchemaRef:Y,schemaPath:W,errorPath:G},it:X},J,B,K){let V=K?p._`${$}, ${Z}, ${Y}${W}`:Z,z=[[N1.default.instancePath,(0,p.strConcat)(N1.default.instancePath,G)],[N1.default.parentData,X.parentData],[N1.default.parentDataProperty,X.parentDataProperty],[N1.default.rootData,N1.default.rootData]];if(X.opts.dynamicRef)z.push([N1.default.dynamicAnchors,N1.default.dynamicAnchors]);let F=p._`${V}, ${Q.object(...z)}`;return B!==p.nil?p._`${J}.call(${B}, ${F})`:p._`${J}(${F})`}a7.callValidateCode=DD;var UD=p._`new RegExp`;function qD({gen:$,it:{opts:Z}},Q){let Y=Z.unicodeRegExp?"u":"",{regExp:W}=Z.code,G=W(Q,Y);return $.scopeValue("pattern",{key:G.toString(),ref:G,code:p._`${W.code==="new RegExp"?UD:(0,BD.useFunc)($,W)}(${Q}, ${Y})`})}a7.usePattern=qD;function AD($){let{gen:Z,data:Q,keyword:Y,it:W}=$,G=Z.name("valid");if(W.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 B=Z.const("len",p._`${Q}.length`);Z.forRange("i",0,B,(K)=>{$.subschema({keyword:Y,dataProp:K,dataPropType:P8.Type.Num},G),Z.if((0,p.not)(G),J)})}}a7.validateArray=AD;function ND($){let{gen:Z,schema:Q,keyword:Y,it:W}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(Q.some((B)=>(0,P8.alwaysValidSchema)(W,B))&&!W.opts.unevaluated)return;let X=Z.let("valid",!1),J=Z.name("_valid");Z.block(()=>Q.forEach((B,K)=>{let V=$.subschema({keyword:Y,schemaProp:K,compositeRule:!0},J);if(Z.assign(X,p._`${X} || ${J}`),!$.mergeValidEvaluated(V,J))Z.if((0,p.not)(X))})),$.result(X,()=>$.reset(),()=>$.error(!0))}a7.validateUnion=ND});var $W=O((s7)=>{Object.defineProperty(s7,"__esModule",{value:!0});s7.validateKeywordUsage=s7.validSchemaType=s7.funcKeywordCode=s7.macroKeywordCode=void 0;var K0=b(),g1=s0(),bD=P0(),_D=KZ();function xD($,Z){let{gen:Q,keyword:Y,schema:W,parentSchema:G,it:X}=$,J=Z.macro.call(X.self,W,G,X),B=o7(Q,Y,J);if(X.opts.validateSchema!==!1)X.self.validateSchema(J,!0);let K=Q.name("valid");$.subschema({schema:J,schemaPath:K0.nil,errSchemaPath:`${X.errSchemaPath}/${Y}`,topSchemaRef:B,compositeRule:!0},K),$.pass(K,()=>$.error(!0))}s7.macroKeywordCode=xD;function kD($,Z){var Q;let{gen:Y,keyword:W,schema:G,parentSchema:X,$data:J,it:B}=$;vD(B,Z);let K=!J&&Z.compile?Z.compile.call(B.self,G,X,B):Z.validate,V=o7(Y,W,K),z=Y.let("valid");$.block$data(z,F),$.ok((Q=Z.valid)!==null&&Q!==void 0?Q:z);function F(){if(Z.errors===!1){if(U(),Z.modifying)t7($);q(()=>$.error())}else{let A=Z.async?D():L();if(Z.modifying)t7($);q(()=>fD($,A))}}function D(){let A=Y.let("ruleErrs",null);return Y.try(()=>U(K0._`await `),(N)=>Y.assign(z,!1).if(K0._`${N} instanceof ${B.ValidationError}`,()=>Y.assign(A,K0._`${N}.errors`),()=>Y.throw(N))),A}function L(){let A=K0._`${V}.errors`;return Y.assign(A,null),U(K0.nil),A}function U(A=Z.async?K0._`await `:K0.nil){let N=B.opts.passContext?g1.default.this:g1.default.self,j=!(("compile"in Z)&&!J||Z.schema===!1);Y.assign(z,K0._`${A}${(0,bD.callValidateCode)($,V,N,j)}`,Z.modifying)}function q(A){var N;Y.if((0,K0.not)((N=Z.valid)!==null&&N!==void 0?N:z),A)}}s7.funcKeywordCode=kD;function t7($){let{gen:Z,data:Q,it:Y}=$;Z.if(Y.parentData,()=>Z.assign(Q,K0._`${Y.parentData}[${Y.parentDataProperty}]`))}function fD($,Z){let{gen:Q}=$;Q.if(K0._`Array.isArray(${Z})`,()=>{Q.assign(g1.default.vErrors,K0._`${g1.default.vErrors} === null ? ${Z} : ${g1.default.vErrors}.concat(${Z})`).assign(g1.default.errors,K0._`${g1.default.vErrors}.length`),(0,_D.extendErrors)($)},()=>$.error())}function vD({schemaEnv:$},Z){if(Z.async&&!$.$async)throw Error("async keyword in sync schema")}function o7($,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,K0.stringify)(Q)})}function gD($,Z,Q=!1){return!Z.length||Z.some((Y)=>Y==="array"?Array.isArray($):Y==="object"?$&&typeof $=="object"&&!Array.isArray($):typeof $==Y||Q&&typeof $>"u")}s7.validSchemaType=gD;function hD({schema:$,opts:Z,self:Q,errSchemaPath:Y},W,G){if(Array.isArray(W.keyword)?!W.keyword.includes(G):W.keyword!==G)throw Error("ajv implementation error");let X=W.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(W.validateSchema){if(!W.validateSchema($[G])){let B=`keyword "${G}" value is invalid at path "${Y}": `+Q.errorsText(W.validateSchema.errors);if(Z.validateSchema==="log")Q.logger.error(B);else throw Error(B)}}}s7.validateKeywordUsage=hD});var WW=O((QW)=>{Object.defineProperty(QW,"__esModule",{value:!0});QW.extendSubschemaMode=QW.extendSubschemaData=QW.getSubschema=void 0;var g0=b(),ZW=k();function pD($,{keyword:Z,schemaProp:Q,schema:Y,schemaPath:W,errSchemaPath:G,topSchemaRef:X}){if(Z!==void 0&&Y!==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:g0._`${$.schemaPath}${(0,g0.getProperty)(Z)}`,errSchemaPath:`${$.errSchemaPath}/${Z}`}:{schema:J[Q],schemaPath:g0._`${$.schemaPath}${(0,g0.getProperty)(Z)}${(0,g0.getProperty)(Q)}`,errSchemaPath:`${$.errSchemaPath}/${Z}/${(0,ZW.escapeFragment)(Q)}`}}if(Y!==void 0){if(W===void 0||G===void 0||X===void 0)throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:Y,schemaPath:W,topSchemaRef:X,errSchemaPath:G}}throw Error('either "keyword" or "schema" must be passed')}QW.getSubschema=pD;function cD($,Z,{dataProp:Q,dataPropType:Y,data:W,dataTypes:G,propertyName:X}){if(W!==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:K,dataPathArr:V,opts:z}=Z,F=J.let("data",g0._`${Z.data}${(0,g0.getProperty)(Q)}`,!0);B(F),$.errorPath=g0.str`${K}${(0,ZW.getErrorPath)(Q,Y,z.jsPropertySyntax)}`,$.parentDataProperty=g0._`${Q}`,$.dataPathArr=[...V,$.parentDataProperty]}if(W!==void 0){let K=W instanceof g0.Name?W:J.let("data",W,!0);if(B(K),X!==void 0)$.propertyName=X}if(G)$.dataTypes=G;function B(K){$.data=K,$.dataLevel=Z.dataLevel+1,$.dataTypes=[],Z.definedProperties=new Set,$.parentData=Z.data,$.dataNames=[...Z.dataNames,K]}}QW.extendSubschemaData=cD;function dD($,{jtdDiscriminator:Z,jtdMetadata:Q,compositeRule:Y,createErrors:W,allErrors:G}){if(Y!==void 0)$.compositeRule=Y;if(W!==void 0)$.createErrors=W;if(G!==void 0)$.allErrors=G;$.jtdDiscriminator=Z,$.jtdMetadata=Q}QW.extendSubschemaMode=dD});var I8=O((G2,GW)=>{GW.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 Y,W,G;if(Array.isArray(Z)){if(Y=Z.length,Y!=Q.length)return!1;for(W=Y;W--!==0;)if(!$(Z[W],Q[W]))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),Y=G.length,Y!==Object.keys(Q).length)return!1;for(W=Y;W--!==0;)if(!Object.prototype.hasOwnProperty.call(Q,G[W]))return!1;for(W=Y;W--!==0;){var X=G[W];if(!$(Z[X],Q[X]))return!1}return!0}return Z!==Z&&Q!==Q}});var JW=O((X2,XW)=>{var M1=XW.exports=function($,Z,Q){if(typeof Z=="function")Q=Z,Z={};Q=Z.cb||Q;var Y=typeof Q=="function"?Q:Q.pre||function(){},W=Q.post||function(){};h5(Z,Y,W,$,"",$)};M1.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};M1.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};M1.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};M1.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 h5($,Z,Q,Y,W,G,X,J,B,K){if(Y&&typeof Y=="object"&&!Array.isArray(Y)){Z(Y,W,G,X,J,B,K);for(var V in Y){var z=Y[V];if(Array.isArray(z)){if(V in M1.arrayKeywords)for(var F=0;F<z.length;F++)h5($,Z,Q,z[F],W+"/"+V+"/"+F,G,W,V,Y,F)}else if(V in M1.propsKeywords){if(z&&typeof z=="object")for(var D in z)h5($,Z,Q,z[D],W+"/"+V+"/"+aD(D),G,W,V,Y,D)}else if(V in M1.keywords||$.allKeys&&!(V in M1.skipKeywords))h5($,Z,Q,z,W+"/"+V,G,W,V,Y)}Q(Y,W,G,X,J,B,K)}}function aD($){return $.replace(/~/g,"~0").replace(/\//g,"~1")}});var HZ=O((VW)=>{Object.defineProperty(VW,"__esModule",{value:!0});VW.getSchemaRefs=VW.resolveUrl=VW.normalizeId=VW._getFullPath=VW.getFullPath=VW.inlineRef=void 0;var rD=k(),tD=I8(),oD=JW(),sD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function eD($,Z=!0){if(typeof $=="boolean")return!0;if(Z===!0)return!R8($);if(!Z)return!1;return KW($)<=Z}VW.inlineRef=eD;var $U=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function R8($){for(let Z in $){if($U.has(Z))return!0;let Q=$[Z];if(Array.isArray(Q)&&Q.some(R8))return!0;if(typeof Q=="object"&&R8(Q))return!0}return!1}function KW($){let Z=0;for(let Q in $){if(Q==="$ref")return 1/0;if(Z++,sD.has(Q))continue;if(typeof $[Q]=="object")(0,rD.eachItem)($[Q],(Y)=>Z+=KW(Y));if(Z===1/0)return 1/0}return Z}function BW($,Z="",Q){if(Q!==!1)Z=F$(Z);let Y=$.parse(Z);return HW($,Y)}VW.getFullPath=BW;function HW($,Z){return $.serialize(Z).split("#")[0]+"#"}VW._getFullPath=HW;var ZU=/#\/?$/;function F$($){return $?$.replace(ZU,""):""}VW.normalizeId=F$;function QU($,Z,Q){return Q=F$(Q),$.resolve(Z,Q)}VW.resolveUrl=QU;var YU=/^[a-z_][-a-z0-9._]*$/i;function WU($,Z){if(typeof $=="boolean")return{};let{schemaId:Q,uriResolver:Y}=this.opts,W=F$($[Q]||Z),G={"":W},X=BW(Y,W,!1),J={},B=new Set;return oD($,{allKeys:!0},(z,F,D,L)=>{if(L===void 0)return;let U=X+F,q=G[L];if(typeof z[Q]=="string")q=A.call(this,z[Q]);N.call(this,z.$anchor),N.call(this,z.$dynamicAnchor),G[F]=q;function A(j){let P=this.opts.uriResolver.resolve;if(j=F$(q?P(q,j):j),B.has(j))throw V(j);B.add(j);let M=this.refs[j];if(typeof M=="string")M=this.refs[M];if(typeof M=="object")K(z,M.schema,j);else if(j!==F$(U))if(j[0]==="#")K(z,J[j],j),J[j]=z;else this.refs[j]=U;return j}function N(j){if(typeof j=="string"){if(!YU.test(j))throw Error(`invalid anchor "${j}"`);A.call(this,`#${j}`)}}}),J;function K(z,F,D){if(F!==void 0&&!tD(z,F))throw V(D)}function V(z){return Error(`reference "${z}" resolves to more than one schema`)}}VW.getSchemaRefs=WU});var FZ=O((RW)=>{Object.defineProperty(RW,"__esModule",{value:!0});RW.getData=RW.KeywordCxt=RW.validateFunctionCode=void 0;var qW=C7(),FW=BZ(),S8=N8(),u5=BZ(),HU=d7(),zZ=$W(),E8=WW(),T=b(),E=s0(),VU=HZ(),e0=k(),VZ=KZ();function zU($){if(MW($)){if(OW($),NW($)){DU($);return}}AW($,()=>(0,qW.topBoolOrEmptySchema)($))}RW.validateFunctionCode=zU;function AW({gen:$,validateName:Z,schema:Q,schemaEnv:Y,opts:W},G){if(W.code.es5)$.func(Z,T._`${E.default.data}, ${E.default.valCxt}`,Y.$async,()=>{$.code(T._`"use strict"; ${LW(Q,W)}`),LU($,W),$.code(G)});else $.func(Z,T._`${E.default.data}, ${FU(W)}`,Y.$async,()=>$.code(LW(Q,W)).code(G))}function FU($){return T._`{${E.default.instancePath}="", ${E.default.parentData}, ${E.default.parentDataProperty}, ${E.default.rootData}=${E.default.data}${$.dynamicRef?T._`, ${E.default.dynamicAnchors}={}`:T.nil}}={}`}function LU($,Z){$.if(E.default.valCxt,()=>{if($.var(E.default.instancePath,T._`${E.default.valCxt}.${E.default.instancePath}`),$.var(E.default.parentData,T._`${E.default.valCxt}.${E.default.parentData}`),$.var(E.default.parentDataProperty,T._`${E.default.valCxt}.${E.default.parentDataProperty}`),$.var(E.default.rootData,T._`${E.default.valCxt}.${E.default.rootData}`),Z.dynamicRef)$.var(E.default.dynamicAnchors,T._`${E.default.valCxt}.${E.default.dynamicAnchors}`)},()=>{if($.var(E.default.instancePath,T._`""`),$.var(E.default.parentData,T._`undefined`),$.var(E.default.parentDataProperty,T._`undefined`),$.var(E.default.rootData,E.default.data),Z.dynamicRef)$.var(E.default.dynamicAnchors,T._`{}`)})}function DU($){let{schema:Z,opts:Q,gen:Y}=$;AW($,()=>{if(Q.$comment&&Z.$comment)PW($);if(MU($),Y.let(E.default.vErrors,null),Y.let(E.default.errors,0),Q.unevaluated)UU($);jW($),PU($)});return}function UU($){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 LW($,Z){let Q=typeof $=="object"&&$[Z.schemaId];return Q&&(Z.code.source||Z.code.process)?T._`/*# sourceURL=${Q} */`:T.nil}function qU($,Z){if(MW($)){if(OW($),NW($)){AU($,Z);return}}(0,qW.boolOrEmptySchema)($,Z)}function NW({schema:$,self:Z}){if(typeof $=="boolean")return!$;for(let Q in $)if(Z.RULES.all[Q])return!0;return!1}function MW($){return typeof $.schema!="boolean"}function AU($,Z){let{schema:Q,gen:Y,opts:W}=$;if(W.$comment&&Q.$comment)PW($);OU($),jU($);let G=Y.const("_errs",E.default.errors);jW($,G),Y.var(Z,T._`${G} === ${E.default.errors}`)}function OW($){(0,e0.checkUnknownRules)($),NU($)}function jW($,Z){if($.opts.jtd)return DW($,[],!1,Z);let Q=(0,FW.getSchemaTypes)($.schema),Y=(0,FW.coerceAndCheckDataType)($,Q);DW($,Q,!Y,Z)}function NU($){let{schema:Z,errSchemaPath:Q,opts:Y,self:W}=$;if(Z.$ref&&Y.ignoreKeywordsWithRef&&(0,e0.schemaHasRulesButRef)(Z,W.RULES))W.logger.warn(`$ref: keywords ignored in schema at path "${Q}"`)}function MU($){let{schema:Z,opts:Q}=$;if(Z.default!==void 0&&Q.useDefaults&&Q.strictSchema)(0,e0.checkStrictMode)($,"default is ignored in the schema root")}function OU($){let Z=$.schema[$.opts.schemaId];if(Z)$.baseId=(0,VU.resolveUrl)($.opts.uriResolver,$.baseId,Z)}function jU($){if($.schema.$async&&!$.schemaEnv.$async)throw Error("async schema in sync schema")}function PW({gen:$,schemaEnv:Z,schema:Q,errSchemaPath:Y,opts:W}){let G=Q.$comment;if(W.$comment===!0)$.code(T._`${E.default.self}.logger.log(${G})`);else if(typeof W.$comment=="function"){let X=T.str`${Y}/$comment`,J=$.scopeValue("root",{ref:Z.root});$.code(T._`${E.default.self}.opts.$comment(${G}, ${X}, ${J}.schema)`)}}function PU($){let{gen:Z,schemaEnv:Q,validateName:Y,ValidationError:W,opts:G}=$;if(Q.$async)Z.if(T._`${E.default.errors} === 0`,()=>Z.return(E.default.data),()=>Z.throw(T._`new ${W}(${E.default.vErrors})`));else{if(Z.assign(T._`${Y}.errors`,E.default.vErrors),G.unevaluated)wU($);Z.return(T._`${E.default.errors} === 0`)}}function wU({gen:$,evaluated:Z,props:Q,items:Y}){if(Q instanceof T.Name)$.assign(T._`${Z}.props`,Q);if(Y instanceof T.Name)$.assign(T._`${Z}.items`,Y)}function DW($,Z,Q,Y){let{gen:W,schema:G,data:X,allErrors:J,opts:B,self:K}=$,{RULES:V}=K;if(G.$ref&&(B.ignoreKeywordsWithRef||!(0,e0.schemaHasRulesButRef)(G,V))){W.block(()=>TW($,"$ref",V.all.$ref.definition));return}if(!B.jtd)TU($,Z);W.block(()=>{for(let F of V.rules)z(F);z(V.post)});function z(F){if(!(0,S8.shouldUseGroup)(G,F))return;if(F.type){if(W.if((0,u5.checkDataType)(F.type,X,B.strictNumbers)),UW($,F),Z.length===1&&Z[0]===F.type&&Q)W.else(),(0,u5.reportTypeError)($);W.endIf()}else UW($,F);if(!J)W.if(T._`${E.default.errors} === ${Y||0}`)}}function UW($,Z){let{gen:Q,schema:Y,opts:{useDefaults:W}}=$;if(W)(0,HU.assignDefaults)($,Z.type);Q.block(()=>{for(let G of Z.rules)if((0,S8.shouldUseRule)(Y,G))TW($,G.keyword,G.definition,Z.type)})}function TU($,Z){if($.schemaEnv.meta||!$.opts.strictTypes)return;if(IU($,Z),!$.opts.allowUnionTypes)RU($,Z);EU($,$.dataTypes)}function IU($,Z){if(!Z.length)return;if(!$.dataTypes.length){$.dataTypes=Z;return}Z.forEach((Q)=>{if(!wW($.dataTypes,Q))C8($,`type "${Q}" not allowed by context "${$.dataTypes.join(",")}"`)}),CU($,Z)}function RU($,Z){if(Z.length>1&&!(Z.length===2&&Z.includes("null")))C8($,"use allowUnionTypes to allow union type keyword")}function EU($,Z){let Q=$.self.RULES.all;for(let Y in Q){let W=Q[Y];if(typeof W=="object"&&(0,S8.shouldUseRule)($.schema,W)){let{type:G}=W.definition;if(G.length&&!G.some((X)=>SU(Z,X)))C8($,`missing type "${G.join(",")}" for keyword "${Y}"`)}}}function SU($,Z){return $.includes(Z)||Z==="number"&&$.includes("integer")}function wW($,Z){return $.includes(Z)||Z==="integer"&&$.includes("number")}function CU($,Z){let Q=[];for(let Y of $.dataTypes)if(wW(Z,Y))Q.push(Y);else if(Z.includes("integer")&&Y==="number")Q.push("integer");$.dataTypes=Q}function C8($,Z){let Q=$.schemaEnv.baseId+$.errSchemaPath;Z+=` at "${Q}" (strictTypes)`,(0,e0.checkStrictMode)($,Z,$.opts.strictTypes)}class y8{constructor($,Z,Q){if((0,zZ.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,e0.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",IW(this.$data,$));else if(this.schemaCode=this.schemaValue,!(0,zZ.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",E.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){($?VZ.reportExtraError:VZ.reportError)(this,this.def.error,Z)}$dataError(){(0,VZ.reportError)(this,this.def.$dataError||VZ.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error('add "trackErrors" to keyword definition');(0,VZ.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:Y,schemaType:W,def:G}=this;if(Q.if((0,T.or)(T._`${Y} === undefined`,Z)),$!==T.nil)Q.assign($,!0);if(W.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:Y,it:W}=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,u5.checkDataTypes)(J,Z,W.opts.strictNumbers,u5.DataType.Wrong)}`}return T.nil}function X(){if(Y.validateSchema){let J=$.scopeValue("validate$data",{ref:Y.validateSchema});return T._`!${J}(${Z})`}return T.nil}}subschema($,Z){let Q=(0,E8.getSubschema)(this.it,$);(0,E8.extendSubschemaData)(Q,this.it,$),(0,E8.extendSubschemaMode)(Q,$);let Y={...this.it,...Q,items:void 0,props:void 0};return qU(Y,Z),Y}mergeEvaluated($,Z){let{it:Q,gen:Y}=this;if(!Q.opts.unevaluated)return;if(Q.props!==!0&&$.props!==void 0)Q.props=e0.mergeEvaluated.props(Y,$.props,Q.props,Z);if(Q.items!==!0&&$.items!==void 0)Q.items=e0.mergeEvaluated.items(Y,$.items,Q.items,Z)}mergeValidEvaluated($,Z){let{it:Q,gen:Y}=this;if(Q.opts.unevaluated&&(Q.props!==!0||Q.items!==!0))return Y.if(Z,()=>this.mergeEvaluated($,T.Name)),!0}}RW.KeywordCxt=y8;function TW($,Z,Q,Y){let W=new y8($,Q,Z);if("code"in Q)Q.code(W,Y);else if(W.$data&&Q.validate)(0,zZ.funcKeywordCode)(W,Q);else if("macro"in Q)(0,zZ.macroKeywordCode)(W,Q);else if(Q.compile||Q.validate)(0,zZ.funcKeywordCode)(W,Q)}var yU=/^\/(?:[^~]|~0|~1)*$/,bU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function IW($,{dataLevel:Z,dataNames:Q,dataPathArr:Y}){let W,G;if($==="")return E.default.rootData;if($[0]==="/"){if(!yU.test($))throw Error(`Invalid JSON-pointer: ${$}`);W=$,G=E.default.rootData}else{let K=bU.exec($);if(!K)throw Error(`Invalid JSON-pointer: ${$}`);let V=+K[1];if(W=K[2],W==="#"){if(V>=Z)throw Error(B("property/index",V));return Y[Z-V]}if(V>Z)throw Error(B("data",V));if(G=Q[Z-V],!W)return G}let X=G,J=W.split("/");for(let K of J)if(K)G=T._`${G}${(0,T.getProperty)((0,e0.unescapeJsonPointer)(K))}`,X=T._`${X} && ${G}`;return X;function B(K,V){return`Cannot access ${K} ${V} levels up, current level is ${Z}`}}RW.getData=IW});var m5=O((CW)=>{Object.defineProperty(CW,"__esModule",{value:!0});class SW extends Error{constructor($){super("validation failed");this.errors=$,this.ajv=this.validation=!0}}CW.default=SW});var LZ=O((bW)=>{Object.defineProperty(bW,"__esModule",{value:!0});var b8=HZ();class yW extends Error{constructor($,Z,Q,Y){super(Y||`can't resolve reference ${Q} from id ${Z}`);this.missingRef=(0,b8.resolveUrl)($,Z,Q),this.missingSchema=(0,b8.normalizeId)((0,b8.getFullPath)($,this.missingRef))}}bW.default=yW});var p5=O((kW)=>{Object.defineProperty(kW,"__esModule",{value:!0});kW.resolveSchema=kW.getCompilingSchema=kW.resolveRef=kW.compileSchema=kW.SchemaEnv=void 0;var C0=b(),vU=m5(),h1=s0(),y0=HZ(),_W=k(),gU=FZ();class DZ{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,y0.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={}}}kW.SchemaEnv=DZ;function x8($){let Z=xW.call(this,$);if(Z)return Z;let Q=(0,y0.getFullPath)(this.opts.uriResolver,$.root.baseId),{es5:Y,lines:W}=this.opts.code,{ownProperties:G}=this.opts,X=new C0.CodeGen(this.scope,{es5:Y,lines:W,ownProperties:G}),J;if($.$async)J=X.scopeValue("Error",{ref:vU.default,code:C0._`require("ajv/dist/runtime/validation_error").default`});let B=X.scopeName("validate");$.validateName=B;let K={gen:X,allErrors:this.opts.allErrors,data:h1.default.data,parentData:h1.default.parentData,parentDataProperty:h1.default.parentDataProperty,dataNames:[h1.default.data],dataPathArr:[C0.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:X.scopeValue("schema",this.opts.code.source===!0?{ref:$.schema,code:(0,C0.stringify)($.schema)}:{ref:$.schema}),validateName:B,ValidationError:J,schema:$.schema,schemaEnv:$,rootId:Q,baseId:$.baseId||Q,schemaPath:C0.nil,errSchemaPath:$.schemaPath||(this.opts.jtd?"":"#"),errorPath:C0._`""`,opts:this.opts,self:this},V;try{this._compilations.add($),(0,gU.validateFunctionCode)(K),X.optimize(this.opts.code.optimize);let z=X.toString();if(V=`${X.scopeRefs(h1.default.scope)}return ${z}`,this.opts.code.process)V=this.opts.code.process(V,$);let D=Function(`${h1.default.self}`,`${h1.default.scope}`,V)(this,this.scope.get());if(this.scope.value(B,{ref:D}),D.errors=null,D.schema=$.schema,D.schemaEnv=$,$.$async)D.$async=!0;if(this.opts.code.source===!0)D.source={validateName:B,validateCode:z,scopeValues:X._values};if(this.opts.unevaluated){let{props:L,items:U}=K;if(D.evaluated={props:L instanceof C0.Name?void 0:L,items:U instanceof C0.Name?void 0:U,dynamicProps:L instanceof C0.Name,dynamicItems:U instanceof C0.Name},D.source)D.source.evaluated=(0,C0.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($)}}kW.compileSchema=x8;function hU($,Z,Q){var Y;Q=(0,y0.resolveUrl)(this.opts.uriResolver,Z,Q);let W=$.refs[Q];if(W)return W;let G=lU.call(this,$,Q);if(G===void 0){let X=(Y=$.localRefs)===null||Y===void 0?void 0:Y[Q],{schemaId:J}=this.opts;if(X)G=new DZ({schema:X,schemaId:J,root:$,baseId:Z})}if(G===void 0)return;return $.refs[Q]=uU.call(this,G)}kW.resolveRef=hU;function uU($){if((0,y0.inlineRef)($.schema,this.opts.inlineRefs))return $.schema;return $.validate?$:x8.call(this,$)}function xW($){for(let Z of this._compilations)if(mU(Z,$))return Z}kW.getCompilingSchema=xW;function mU($,Z){return $.schema===Z.schema&&$.root===Z.root&&$.baseId===Z.baseId}function lU($,Z){let Q;while(typeof(Q=this.refs[Z])=="string")Z=Q;return Q||this.schemas[Z]||l5.call(this,$,Z)}function l5($,Z){let Q=this.opts.uriResolver.parse(Z),Y=(0,y0._getFullPath)(this.opts.uriResolver,Q),W=(0,y0.getFullPath)(this.opts.uriResolver,$.baseId,void 0);if(Object.keys($.schema).length>0&&Y===W)return _8.call(this,Q,$);let G=(0,y0.normalizeId)(Y),X=this.refs[G]||this.schemas[G];if(typeof X=="string"){let J=l5.call(this,$,X);if(typeof(J===null||J===void 0?void 0:J.schema)!=="object")return;return _8.call(this,Q,J)}if(typeof(X===null||X===void 0?void 0:X.schema)!=="object")return;if(!X.validate)x8.call(this,X);if(G===(0,y0.normalizeId)(Z)){let{schema:J}=X,{schemaId:B}=this.opts,K=J[B];if(K)W=(0,y0.resolveUrl)(this.opts.uriResolver,W,K);return new DZ({schema:J,schemaId:B,root:$,baseId:W})}return _8.call(this,Q,X)}kW.resolveSchema=l5;var pU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function _8($,{baseId:Z,schema:Q,root:Y}){var W;if(((W=$.fragment)===null||W===void 0?void 0:W[0])!=="/")return;for(let J of $.fragment.slice(1).split("/")){if(typeof Q==="boolean")return;let B=Q[(0,_W.unescapeFragment)(J)];if(B===void 0)return;Q=B;let K=typeof Q==="object"&&Q[this.opts.schemaId];if(!pU.has(J)&&K)Z=(0,y0.resolveUrl)(this.opts.uriResolver,Z,K)}let G;if(typeof Q!="boolean"&&Q.$ref&&!(0,_W.schemaHasRulesButRef)(Q,this.RULES)){let J=(0,y0.resolveUrl)(this.opts.uriResolver,Z,Q.$ref);G=l5.call(this,Y,J)}let{schemaId:X}=this.opts;if(G=G||new DZ({schema:Q,schemaId:X,root:Y,baseId:Z}),G.schema!==G.root.schema)return G;return}});var vW=O((z2,aU)=>{aU.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 v8=O((F2,pW)=>{var rU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),hW=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),k8=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),uW=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),tU=RegExp.prototype.test.bind(/^[\da-z\-._~!$&'()*+,;=:@/]$/iu);function f8($){let Z="",Q=0,Y=0;for(Y=0;Y<$.length;Y++){if(Q=$[Y].charCodeAt(0),Q===48)continue;if(!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[Y];break}for(Y+=1;Y<$.length;Y++){if(Q=$[Y].charCodeAt(0),!(Q>=48&&Q<=57||Q>=65&&Q<=70||Q>=97&&Q<=102))return"";Z+=$[Y]}return Z}var oU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function gW($){return $.length=0,!0}function sU($,Z,Q){if($.length){let Y=f8($);if(Y!=="")Z.push(Y);else return Q.error=!0,!1;$.length=0}return!0}function eU($){let Z=0,Q={error:!1,address:"",zone:""},Y=[],W=[],G=!1,X=!1,J=sU;for(let B=0;B<$.length;B++){let K=$[B];if(K==="["||K==="]")continue;if(K===":"){if(G===!0)X=!0;if(!J(W,Y,Q))break;if(++Z>7){Q.error=!0;break}if(B>0&&$[B-1]===":")G=!0;Y.push(":");continue}else if(K==="%"){if(!J(W,Y,Q))break;J=gW}else{W.push(K);continue}}if(W.length)if(J===gW)Q.zone=W.join("");else if(X)Y.push(W.join(""));else Y.push(f8(W));return Q.address=Y.join(""),Q}function mW($){if($q($,":")<2)return{host:$,isIPV6:!1};let Z=eU($);if(!Z.error){let{address:Q,address:Y}=Z;if(Z.zone)Q+="%"+Z.zone,Y+="%25"+Z.zone;return{host:Q,isIPV6:!0,escapedHost:Y}}else return{host:$,isIPV6:!1}}function $q($,Z){let Q=0;for(let Y=0;Y<$.length;Y++)if($[Y]===Z)Q++;return Q}function Zq($){let Z=$,Q=[],Y=-1,W=0;while(W=Z.length){if(W===1)if(Z===".")break;else if(Z==="/"){Q.push("/");break}else{Q.push(Z);break}else if(W===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(W===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((Y=Z.indexOf("/",1))===-1){Q.push(Z);break}else Q.push(Z.slice(0,Y)),Z=Z.slice(Y)}return Q.join("")}var Qq={"@":"%40","/":"%2F","?":"%3F","#":"%23",":":"%3A"},Yq=/[@/?#:]/g,Wq=/[@/?#]/g;function lW($,Z){let Q=Z?Wq:Yq;return Q.lastIndex=0,$.replace(Q,(Y)=>Qq[Y])}function Gq($,Z=!1){if($.indexOf("%")===-1)return $;let Q="";for(let Y=0;Y<$.length;Y++){if($[Y]==="%"&&Y+2<$.length){let W=$.slice(Y+1,Y+3);if(k8(W)){let G=W.toUpperCase(),X=String.fromCharCode(parseInt(G,16));if(Z&&uW(X))Q+=X;else Q+="%"+G;Y+=2;continue}}Q+=$[Y]}return Q}function Xq($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let Y=$.slice(Q+1,Q+3);if(k8(Y)){let W=Y.toUpperCase(),G=String.fromCharCode(parseInt(W,16));if(G!=="."&&uW(G))Z+=G;else Z+="%"+W;Q+=2;continue}}if(tU($[Q]))Z+=$[Q];else Z+=escape($[Q])}return Z}function Jq($){let Z="";for(let Q=0;Q<$.length;Q++){if($[Q]==="%"&&Q+2<$.length){let Y=$.slice(Q+1,Q+3);if(k8(Y)){Z+="%"+Y.toUpperCase(),Q+=2;continue}}Z+=escape($[Q])}return Z}function Kq($){let Z=[];if($.userinfo!==void 0)Z.push($.userinfo),Z.push("@");if($.host!==void 0){let Q=unescape($.host);if(!hW(Q)){let Y=mW(Q);if(Y.isIPV6===!0)Q=`[${Y.escapedHost}]`;else Q=lW(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}pW.exports={nonSimpleDomain:oU,recomposeAuthority:Kq,reescapeHostDelimiters:lW,normalizePercentEncoding:Gq,normalizePathEncoding:Xq,escapePreservingEscapes:Jq,removeDotSegments:Zq,isIPv4:hW,isUUID:rU,normalizeIPv6:mW,stringArrayToHexStripped:f8}});var aW=O((L2,nW)=>{var{isUUID:Bq}=v8(),Hq=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,Vq=["http","https","ws","wss","urn","urn:uuid"];function zq($){return Vq.indexOf($)!==-1}function g8($){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 cW($){if(!$.host)$.error=$.error||"HTTP URIs must have a host.";return $}function dW($){let Z=String($.scheme).toLowerCase()==="https";if($.port===(Z?443:80)||$.port==="")$.port=void 0;if(!$.path)$.path="/";return $}function Fq($){return $.secure=g8($),$.resourceName=($.path||"/")+($.query?"?"+$.query:""),$.path=void 0,$.query=void 0,$}function Lq($){if($.port===(g8($)?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 Dq($,Z){if(!$.path)return $.error="URN can not be parsed",$;let Q=$.path.match(Hq);if(Q){let Y=Z.scheme||$.scheme||"urn";$.nid=Q[1].toLowerCase(),$.nss=Q[2];let W=`${Y}:${Z.nid||$.nid}`,G=h8(W);if($.path=void 0,G)$=G.parse($,Z)}else $.error=$.error||"URN can not be parsed.";return $}function Uq($,Z){if($.nid===void 0)throw Error("URN without nid cannot be serialized");let Q=Z.scheme||$.scheme||"urn",Y=$.nid.toLowerCase(),W=`${Q}:${Z.nid||Y}`,G=h8(W);if(G)$=G.serialize($,Z);let X=$,J=$.nss;return X.path=`${Y||Z.nid}:${J}`,Z.skipEscape=!0,X}function qq($,Z){let Q=$;if(Q.uuid=Q.nss,Q.nss=void 0,!Z.tolerant&&(!Q.uuid||!Bq(Q.uuid)))Q.error=Q.error||"UUID is not valid.";return Q}function Aq($){let Z=$;return Z.nss=($.uuid||"").toLowerCase(),Z}var iW={scheme:"http",domainHost:!0,parse:cW,serialize:dW},Nq={scheme:"https",domainHost:iW.domainHost,parse:cW,serialize:dW},c5={scheme:"ws",domainHost:!0,parse:Fq,serialize:Lq},Mq={scheme:"wss",domainHost:c5.domainHost,parse:c5.parse,serialize:c5.serialize},Oq={scheme:"urn",parse:Dq,serialize:Uq,skipNormalize:!0},jq={scheme:"urn:uuid",parse:qq,serialize:Aq,skipNormalize:!0},d5={http:iW,https:Nq,ws:c5,wss:Mq,urn:Oq,"urn:uuid":jq};Object.setPrototypeOf(d5,null);function h8($){return $&&(d5[$]||d5[$.toLowerCase()])||void 0}nW.exports={wsIsSecure:g8,SCHEMES:d5,isValidSchemeName:zq,getSchemeHandler:h8}});var $G=O((D2,i5)=>{var{normalizeIPv6:Pq,removeDotSegments:UZ,recomposeAuthority:wq,normalizePercentEncoding:Tq,normalizePathEncoding:Iq,escapePreservingEscapes:Rq,reescapeHostDelimiters:Eq,isIPv4:Sq,nonSimpleDomain:Cq}=v8(),{SCHEMES:yq,getSchemeHandler:tW}=aW();function bq($,Z){if(typeof $==="string")$=gq($,Z);else if(typeof $==="object")$=L$(u1($,Z),Z);return $}function _q($,Z,Q){let Y=Q?Object.assign({scheme:"null"},Q):{scheme:"null"},W=oW(L$($,Y),L$(Z,Y),Y,!0);return Y.skipEscape=!0,u1(W,Y)}function oW($,Z,Q,Y){let W={};if(!Y)$=L$(u1($,Q),Q),Z=L$(u1(Z,Q),Q);if(Q=Q||{},!Q.tolerant&&Z.scheme)W.scheme=Z.scheme,W.userinfo=Z.userinfo,W.host=Z.host,W.port=Z.port,W.path=UZ(Z.path||""),W.query=Z.query;else{if(Z.userinfo!==void 0||Z.host!==void 0||Z.port!==void 0)W.userinfo=Z.userinfo,W.host=Z.host,W.port=Z.port,W.path=UZ(Z.path||""),W.query=Z.query;else{if(!Z.path)if(W.path=$.path,Z.query!==void 0)W.query=Z.query;else W.query=$.query;else{if(Z.path[0]==="/")W.path=UZ(Z.path);else{if(($.userinfo!==void 0||$.host!==void 0||$.port!==void 0)&&!$.path)W.path="/"+Z.path;else if(!$.path)W.path=Z.path;else W.path=$.path.slice(0,$.path.lastIndexOf("/")+1)+Z.path;W.path=UZ(W.path)}W.query=Z.query}W.userinfo=$.userinfo,W.host=$.host,W.port=$.port}W.scheme=$.scheme}return W.fragment=Z.fragment,W}function xq($,Z,Q){let Y=rW($,Q),W=rW(Z,Q);return Y!==void 0&&W!==void 0&&Y.toLowerCase()===W.toLowerCase()}function u1($,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:""},Y=Object.assign({},Z),W=[],G=tW(Y.scheme||Q.scheme);if(G&&G.serialize)G.serialize(Q,Y);if(Q.path!==void 0)if(!Y.skipEscape){if(Q.path=Rq(Q.path),Q.scheme!==void 0)Q.path=Q.path.split("%3A").join(":")}else Q.path=Tq(Q.path);if(Y.reference!=="suffix"&&Q.scheme)W.push(Q.scheme,":");let X=wq(Q);if(X!==void 0){if(Y.reference!=="suffix")W.push("//");if(W.push(X),Q.path&&Q.path[0]!=="/")W.push("/")}if(Q.path!==void 0){let J=Q.path;if(!Y.absolutePath&&(!G||!G.absolutePath))J=UZ(J);if(X===void 0&&J[0]==="/"&&J[1]==="/")J="/%2F"+J.slice(2);W.push(J)}if(Q.query!==void 0)W.push("?",Q.query);if(Q.fragment!==void 0)W.push("#",Q.fragment);return W.join("")}var kq=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,fq=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/;function vq($,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 sW($,Z){let Q=Object.assign({},Z),Y={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},W=!1,G=!1;if(Q.reference==="suffix")if(Q.scheme)$=Q.scheme+":"+$;else $="//"+$;let X=$.match(fq);if(X!==null&&X[1].indexOf("\\")!==-1)Y.error="URI authority must not contain a literal backslash.",W=!0;let J=$.match(kq);if(J){if(Y.scheme=J[1],Y.userinfo=J[3],Y.host=J[4],Y.port=parseInt(J[5],10),Y.path=J[6]||"",Y.query=J[7],Y.fragment=J[8],isNaN(Y.port))Y.port=J[5];let B=vq(Y,J);if(B!==void 0)Y.error=Y.error||B,W=!0;if(Y.host)if(Sq(Y.host)===!1){let z=Pq(Y.host);Y.host=z.host.toLowerCase(),G=z.isIPV6}else G=!0;if(Y.scheme===void 0&&Y.userinfo===void 0&&Y.host===void 0&&Y.port===void 0&&Y.query===void 0&&!Y.path)Y.reference="same-document";else if(Y.scheme===void 0)Y.reference="relative";else if(Y.fragment===void 0)Y.reference="absolute";else Y.reference="uri";if(Q.reference&&Q.reference!=="suffix"&&Q.reference!==Y.reference)Y.error=Y.error||"URI is not a "+Q.reference+" reference.";let K=tW(Q.scheme||Y.scheme);if(!Q.unicodeSupport&&(!K||!K.unicodeSupport)){if(Y.host&&(Q.domainHost||K&&K.domainHost)&&G===!1&&Cq(Y.host))try{Y.host=new URL("http://"+Y.host).hostname}catch(V){Y.error=Y.error||"Host's domain name can not be converted to ASCII: "+V}}if(!K||K&&!K.skipNormalize){if($.indexOf("%")!==-1){if(Y.scheme!==void 0)Y.scheme=unescape(Y.scheme);if(Y.host!==void 0)Y.host=Eq(unescape(Y.host),G)}if(Y.path)Y.path=Iq(Y.path);if(Y.fragment)try{Y.fragment=encodeURI(decodeURIComponent(Y.fragment))}catch{Y.error=Y.error||"URI malformed"}}if(K&&K.parse)K.parse(Y,Q)}else Y.error=Y.error||"URI can not be parsed.";return{parsed:Y,malformedAuthorityOrPort:W}}function L$($,Z){return sW($,Z).parsed}function gq($,Z){return eW($,Z).normalized}function eW($,Z){let{parsed:Q,malformedAuthorityOrPort:Y}=sW($,Z);return{normalized:Y?$:u1(Q,Z),malformedAuthorityOrPort:Y}}function rW($,Z){if(typeof $==="string"){let{normalized:Q,malformedAuthorityOrPort:Y}=eW($,Z);return Y?void 0:Q}if(typeof $==="object")return u1($,Z)}var u8={SCHEMES:yq,normalize:bq,resolve:_q,resolveComponent:oW,equal:xq,serialize:u1,parse:L$};i5.exports=u8;i5.exports.default=u8;i5.exports.fastUri=u8});var YG=O((QG)=>{Object.defineProperty(QG,"__esModule",{value:!0});var ZG=$G();ZG.code='require("ajv/dist/runtime/uri").default';QG.default=ZG});var VG=O(($1)=>{Object.defineProperty($1,"__esModule",{value:!0});$1.CodeGen=$1.Name=$1.nil=$1.stringify=$1.str=$1._=$1.KeywordCxt=void 0;var uq=FZ();Object.defineProperty($1,"KeywordCxt",{enumerable:!0,get:function(){return uq.KeywordCxt}});var D$=b();Object.defineProperty($1,"_",{enumerable:!0,get:function(){return D$._}});Object.defineProperty($1,"str",{enumerable:!0,get:function(){return D$.str}});Object.defineProperty($1,"stringify",{enumerable:!0,get:function(){return D$.stringify}});Object.defineProperty($1,"nil",{enumerable:!0,get:function(){return D$.nil}});Object.defineProperty($1,"Name",{enumerable:!0,get:function(){return D$.Name}});Object.defineProperty($1,"CodeGen",{enumerable:!0,get:function(){return D$.CodeGen}});var mq=m5(),KG=LZ(),lq=A8(),qZ=p5(),pq=b(),AZ=HZ(),n5=BZ(),l8=k(),WG=vW(),cq=YG(),BG=($,Z)=>new RegExp($,Z);BG.code="new RegExp";var dq=["removeAdditional","useDefaults","coerceTypes"],iq=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),nq={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."},aq={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},GG=200;function rq($){var Z,Q,Y,W,G,X,J,B,K,V,z,F,D,L,U,q,A,N,j,P,M,S,g,n,w;let _=$.strict,t=(Z=$.code)===null||Z===void 0?void 0:Z.optimize,h=t===!0||t===void 0?1:t||0,r=(Y=(Q=$.code)===null||Q===void 0?void 0:Q.regExp)!==null&&Y!==void 0?Y:BG,xZ=(W=$.uriResolver)!==null&&W!==void 0?W:cq.default;return{strictSchema:(X=(G=$.strictSchema)!==null&&G!==void 0?G:_)!==null&&X!==void 0?X:!0,strictNumbers:(B=(J=$.strictNumbers)!==null&&J!==void 0?J:_)!==null&&B!==void 0?B:!0,strictTypes:(V=(K=$.strictTypes)!==null&&K!==void 0?K:_)!==null&&V!==void 0?V:"log",strictTuples:(F=(z=$.strictTuples)!==null&&z!==void 0?z:_)!==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:h,regExp:r}:{optimize:h,regExp:r},loopRequired:(U=$.loopRequired)!==null&&U!==void 0?U:GG,loopEnum:(q=$.loopEnum)!==null&&q!==void 0?q:GG,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:(M=$.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(S=$.validateSchema)!==null&&S!==void 0?S:!0,validateFormats:(g=$.validateFormats)!==null&&g!==void 0?g:!0,unicodeRegExp:(n=$.unicodeRegExp)!==null&&n!==void 0?n:!0,int32range:(w=$.int32range)!==null&&w!==void 0?w:!0,uriResolver:xZ}}class a5{constructor($={}){this.schemas={},this.refs={},this.formats=Object.create(null),this._compilations=new Set,this._loading={},this._cache=new Map,$=this.opts={...$,...rq($)};let{es5:Z,lines:Q}=this.opts.code;this.scope=new pq.ValueScope({scope:{},prefixes:iq,es5:Z,lines:Q}),this.logger=ZA($.logger);let Y=$.validateFormats;if($.validateFormats=!1,this.RULES=(0,lq.getRules)(),XG.call(this,nq,$,"NOT SUPPORTED"),XG.call(this,aq,$,"DEPRECATED","warn"),this._metaOpts=eq.call(this),$.formats)oq.call(this);if(this._addVocabularies(),this._addDefaultMetaSchema(),$.keywords)sq.call(this,$.keywords);if(typeof $.meta=="object")this.addMetaSchema($.meta);tq.call(this),$.validateFormats=Y}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:$,meta:Z,schemaId:Q}=this.opts,Y=WG;if(Q==="id")Y={...WG},Y.id=Y.$id,delete Y.$id;if(Z&&$)this.addMetaSchema(Y,Y[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 Y=Q(Z);if(!("$async"in Q))this.errors=Q.errors;return Y}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 Y.call(this,$,Z);async function Y(K,V){await W.call(this,K.$schema);let z=this._addSchema(K,V);return z.validate||G.call(this,z)}async function W(K){if(K&&!this.getSchema(K))await Y.call(this,{$ref:K},!0)}async function G(K){try{return this._compileSchemaEnv(K)}catch(V){if(!(V instanceof KG.default))throw V;return X.call(this,V),await J.call(this,V.missingSchema),G.call(this,K)}}function X({missingSchema:K,missingRef:V}){if(this.refs[K])throw Error(`AnySchema ${K} is loaded but ${V} cannot be resolved`)}async function J(K){let V=await B.call(this,K);if(!this.refs[K])await W.call(this,V.$schema);if(!this.refs[K])this.addSchema(V,K,Z)}async function B(K){let V=this._loading[K];if(V)return V;try{return await(this._loading[K]=Q(K))}finally{delete this._loading[K]}}}addSchema($,Z,Q,Y=this.opts.validateSchema){if(Array.isArray($)){for(let G of $)this.addSchema(G,void 0,Q,Y);return this}let W;if(typeof $==="object"){let{schemaId:G}=this.opts;if(W=$[G],W!==void 0&&typeof W!="string")throw Error(`schema ${G} must be string`)}return Z=(0,AZ.normalizeId)(Z||W),this._checkUnique(Z),this.schemas[Z]=this._addSchema($,Q,Z,Y,!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 Y=this.validate(Q,$);if(!Y&&Z){let W="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(W);else throw Error(W)}return Y}getSchema($){let Z;while(typeof(Z=JG.call(this,$))=="string")$=Z;if(Z===void 0){let{schemaId:Q}=this.opts,Y=new qZ.SchemaEnv({schema:{},schemaId:Q});if(Z=qZ.resolveSchema.call(this,Y,$),!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=JG.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,AZ.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(YA.call(this,Q,Z),!Z)return(0,l8.eachItem)(Q,(W)=>m8.call(this,W)),this;GA.call(this,Z);let Y={...Z,type:(0,n5.getJSONTypes)(Z.type),schemaType:(0,n5.getJSONTypes)(Z.schemaType)};return(0,l8.eachItem)(Q,Y.type.length===0?(W)=>m8.call(this,W,Y):(W)=>Y.type.forEach((G)=>m8.call(this,W,Y,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 Y=Q.rules.findIndex((W)=>W.keyword===$);if(Y>=0)Q.rules.splice(Y,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((Y)=>`${Q}${Y.instancePath} ${Y.message}`).reduce((Y,W)=>Y+Z+W)}$dataMetaSchema($,Z){let Q=this.RULES.all;$=JSON.parse(JSON.stringify($));for(let Y of Z){let W=Y.split("/").slice(1),G=$;for(let X of W)G=G[X];for(let X in Q){let J=Q[X];if(typeof J!="object")continue;let{$data:B}=J.definition,K=G[X];if(B&&K)G[X]=HG(K)}}return $}_removeAllSchemas($,Z){for(let Q in $){let Y=$[Q];if(!Z||Z.test(Q)){if(typeof Y=="string")delete $[Q];else if(Y&&!Y.meta)this._cache.delete(Y.schema),delete $[Q]}}}_addSchema($,Z,Q,Y=this.opts.validateSchema,W=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,AZ.normalizeId)(G||Q);let B=AZ.getSchemaRefs.call(this,$,Q);if(J=new qZ.SchemaEnv({schema:$,schemaId:X,meta:Z,baseId:Q,localRefs:B}),this._cache.set(J.schema,J),W&&!Q.startsWith("#")){if(Q)this._checkUnique(Q);this.refs[Q]=J}if(Y)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 qZ.compileSchema.call(this,$);if(!$.validate)throw Error("ajv implementation error");return $.validate}_compileMetaSchema($){let Z=this.opts;this.opts=this._metaOpts;try{qZ.compileSchema.call(this,$)}finally{this.opts=Z}}}a5.ValidationError=mq.default;a5.MissingRefError=KG.default;$1.default=a5;function XG($,Z,Q,Y="error"){for(let W in $){let G=W;if(G in Z)this.logger[Y](`${Q}: option ${W}. ${$[G]}`)}}function JG($){return $=(0,AZ.normalizeId)($),this.schemas[$]||this.refs[$]}function tq(){let $=this.opts.schemas;if(!$)return;if(Array.isArray($))this.addSchema($);else for(let Z in $)this.addSchema($[Z],Z)}function oq(){for(let $ in this.opts.formats){let Z=this.opts.formats[$];if(Z)this.addFormat($,Z)}}function sq($){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 eq(){let $={...this.opts};for(let Z of dq)delete $[Z];return $}var $A={log(){},warn(){},error(){}};function ZA($){if($===!1)return $A;if($===void 0)return console;if($.log&&$.warn&&$.error)return $;throw Error("logger must implement log, warn and error methods")}var QA=/^[a-z_$][a-z0-9_$:-]*$/i;function YA($,Z){let{RULES:Q}=this;if((0,l8.eachItem)($,(Y)=>{if(Q.keywords[Y])throw Error(`Keyword ${Y} is already defined`);if(!QA.test(Y))throw Error(`Keyword ${Y} 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 m8($,Z,Q){var Y;let W=Z===null||Z===void 0?void 0:Z.post;if(Q&&W)throw Error('keyword with "post" flag cannot have "type"');let{RULES:G}=this,X=W?G.post:G.rules.find(({type:B})=>B===Q);if(!X)X={type:Q,rules:[]},G.rules.push(X);if(G.keywords[$]=!0,!Z)return;let J={keyword:$,definition:{...Z,type:(0,n5.getJSONTypes)(Z.type),schemaType:(0,n5.getJSONTypes)(Z.schemaType)}};if(Z.before)WA.call(this,X,J,Z.before);else X.rules.push(J);G.all[$]=J,(Y=Z.implements)===null||Y===void 0||Y.forEach((B)=>this.addKeyword(B))}function WA($,Z,Q){let Y=$.rules.findIndex((W)=>W.keyword===Q);if(Y>=0)$.rules.splice(Y,0,Z);else $.rules.push(Z),this.logger.warn(`rule ${Q} is not defined`)}function GA($){let{metaSchema:Z}=$;if(Z===void 0)return;if($.$data&&this.opts.$data)Z=HG(Z);$.validateSchema=this.compile(Z,!0)}var XA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function HG($){return{anyOf:[$,XA]}}});var FG=O((zG)=>{Object.defineProperty(zG,"__esModule",{value:!0});var BA={keyword:"id",code(){throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};zG.default=BA});var NG=O((qG)=>{Object.defineProperty(qG,"__esModule",{value:!0});qG.callRef=qG.getValidate=void 0;var VA=LZ(),LG=P0(),L0=b(),U$=s0(),DG=p5(),r5=k(),zA={keyword:"$ref",schemaType:"string",code($){let{gen:Z,schema:Q,it:Y}=$,{baseId:W,schemaEnv:G,validateName:X,opts:J,self:B}=Y,{root:K}=G;if((Q==="#"||Q==="#/")&&W===K.baseId)return z();let V=DG.resolveRef.call(B,K,W,Q);if(V===void 0)throw new VA.default(Y.opts.uriResolver,W,Q);if(V instanceof DG.SchemaEnv)return F(V);return D(V);function z(){if(G===K)return t5($,X,G,G.$async);let L=Z.scopeValue("root",{ref:K});return t5($,L0._`${L}.validate`,K,K.$async)}function F(L){let U=UG($,L);t5($,U,L,L.$async)}function D(L){let U=Z.scopeValue("schema",J.code.source===!0?{ref:L,code:(0,L0.stringify)(L)}:{ref:L}),q=Z.name("valid"),A=$.subschema({schema:L,dataTypes:[],schemaPath:L0.nil,topSchemaRef:U,errSchemaPath:Q},q);$.mergeEvaluated(A),$.ok(q)}}};function UG($,Z){let{gen:Q}=$;return Z.validate?Q.scopeValue("validate",{ref:Z.validate}):L0._`${Q.scopeValue("wrapper",{ref:Z})}.validate`}qG.getValidate=UG;function t5($,Z,Q,Y){let{gen:W,it:G}=$,{allErrors:X,schemaEnv:J,opts:B}=G,K=B.passContext?U$.default.this:L0.nil;if(Y)V();else z();function V(){if(!J.$async)throw Error("async schema referenced by sync schema");let L=W.let("valid");W.try(()=>{if(W.code(L0._`await ${(0,LG.callValidateCode)($,Z,K)}`),D(Z),!X)W.assign(L,!0)},(U)=>{if(W.if(L0._`!(${U} instanceof ${G.ValidationError})`,()=>W.throw(U)),F(U),!X)W.assign(L,!1)}),$.ok(L)}function z(){$.result((0,LG.callValidateCode)($,Z,K),()=>D(Z),()=>F(Z))}function F(L){let U=L0._`${L}.errors`;W.assign(U$.default.vErrors,L0._`${U$.default.vErrors} === null ? ${U} : ${U$.default.vErrors}.concat(${U})`),W.assign(U$.default.errors,L0._`${U$.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=r5.mergeEvaluated.props(W,q.props,G.props)}else{let A=W.var("props",L0._`${L}.evaluated.props`);G.props=r5.mergeEvaluated.props(W,A,G.props,L0.Name)}if(G.items!==!0)if(q&&!q.dynamicItems){if(q.items!==void 0)G.items=r5.mergeEvaluated.items(W,q.items,G.items)}else{let A=W.var("items",L0._`${L}.evaluated.items`);G.items=r5.mergeEvaluated.items(W,A,G.items,L0.Name)}}}qG.callRef=t5;qG.default=zA});var OG=O((MG)=>{Object.defineProperty(MG,"__esModule",{value:!0});var DA=FG(),UA=NG(),qA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",DA.default,UA.default];MG.default=qA});var PG=O((jG)=>{Object.defineProperty(jG,"__esModule",{value:!0});var o5=b(),O1=o5.operators,s5={maximum:{okStr:"<=",ok:O1.LTE,fail:O1.GT},minimum:{okStr:">=",ok:O1.GTE,fail:O1.LT},exclusiveMaximum:{okStr:"<",ok:O1.LT,fail:O1.GTE},exclusiveMinimum:{okStr:">",ok:O1.GT,fail:O1.LTE}},NA={message:({keyword:$,schemaCode:Z})=>o5.str`must be ${s5[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>o5._`{comparison: ${s5[$].okStr}, limit: ${Z}}`},MA={keyword:Object.keys(s5),type:"number",schemaType:"number",$data:!0,error:NA,code($){let{keyword:Z,data:Q,schemaCode:Y}=$;$.fail$data(o5._`${Q} ${s5[Z].fail} ${Y} || isNaN(${Q})`)}};jG.default=MA});var TG=O((wG)=>{Object.defineProperty(wG,"__esModule",{value:!0});var NZ=b(),jA={message:({schemaCode:$})=>NZ.str`must be multiple of ${$}`,params:({schemaCode:$})=>NZ._`{multipleOf: ${$}}`},PA={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:jA,code($){let{gen:Z,data:Q,schemaCode:Y,it:W}=$,G=W.opts.multipleOfPrecision,X=Z.let("res"),J=G?NZ._`Math.abs(Math.round(${X}) - ${X}) > 1e-${G}`:NZ._`${X} !== parseInt(${X})`;$.fail$data(NZ._`(${Y} === 0 || (${X} = ${Q}/${Y}, ${J}))`)}};wG.default=PA});var EG=O((RG)=>{Object.defineProperty(RG,"__esModule",{value:!0});function IG($){let Z=$.length,Q=0,Y=0,W;while(Y<Z)if(Q++,W=$.charCodeAt(Y++),W>=55296&&W<=56319&&Y<Z){if(W=$.charCodeAt(Y),(W&64512)===56320)Y++}return Q}RG.default=IG;IG.code='require("ajv/dist/runtime/ucs2length").default'});var CG=O((SG)=>{Object.defineProperty(SG,"__esModule",{value:!0});var m1=b(),IA=k(),RA=EG(),EA={message({keyword:$,schemaCode:Z}){let Q=$==="maxLength"?"more":"fewer";return m1.str`must NOT have ${Q} than ${Z} characters`},params:({schemaCode:$})=>m1._`{limit: ${$}}`},SA={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:EA,code($){let{keyword:Z,data:Q,schemaCode:Y,it:W}=$,G=Z==="maxLength"?m1.operators.GT:m1.operators.LT,X=W.opts.unicode===!1?m1._`${Q}.length`:m1._`${(0,IA.useFunc)($.gen,RA.default)}(${Q})`;$.fail$data(m1._`${X} ${G} ${Y}`)}};SG.default=SA});var bG=O((yG)=>{Object.defineProperty(yG,"__esModule",{value:!0});var yA=P0(),bA=k(),q$=b(),_A={message:({schemaCode:$})=>q$.str`must match pattern "${$}"`,params:({schemaCode:$})=>q$._`{pattern: ${$}}`},xA={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:_A,code($){let{gen:Z,data:Q,$data:Y,schema:W,schemaCode:G,it:X}=$,J=X.opts.unicodeRegExp?"u":"";if(Y){let{regExp:B}=X.opts.code,K=B.code==="new RegExp"?q$._`new RegExp`:(0,bA.useFunc)(Z,B),V=Z.let("valid");Z.try(()=>Z.assign(V,q$._`${K}(${G}, ${J}).test(${Q})`),()=>Z.assign(V,!1)),$.fail$data(q$._`!${V}`)}else{let B=(0,yA.usePattern)($,W);$.fail$data(q$._`!${B}.test(${Q})`)}}};yG.default=xA});var xG=O((_G)=>{Object.defineProperty(_G,"__esModule",{value:!0});var MZ=b(),fA={message({keyword:$,schemaCode:Z}){let Q=$==="maxProperties"?"more":"fewer";return MZ.str`must NOT have ${Q} than ${Z} properties`},params:({schemaCode:$})=>MZ._`{limit: ${$}}`},vA={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:fA,code($){let{keyword:Z,data:Q,schemaCode:Y}=$,W=Z==="maxProperties"?MZ.operators.GT:MZ.operators.LT;$.fail$data(MZ._`Object.keys(${Q}).length ${W} ${Y}`)}};_G.default=vA});var fG=O((kG)=>{Object.defineProperty(kG,"__esModule",{value:!0});var OZ=P0(),jZ=b(),hA=k(),uA={message:({params:{missingProperty:$}})=>jZ.str`must have required property '${$}'`,params:({params:{missingProperty:$}})=>jZ._`{missingProperty: ${$}}`},mA={keyword:"required",type:"object",schemaType:"array",$data:!0,error:uA,code($){let{gen:Z,schema:Q,schemaCode:Y,data:W,$data:G,it:X}=$,{opts:J}=X;if(!G&&Q.length===0)return;let B=Q.length>=J.loopRequired;if(X.allErrors)K();else V();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 K(){if(B||G)$.block$data(jZ.nil,z);else for(let D of Q)(0,OZ.checkReportMissingProp)($,D)}function V(){let D=Z.let("missing");if(B||G){let L=Z.let("valid",!0);$.block$data(L,()=>F(D,L)),$.ok(L)}else Z.if((0,OZ.checkMissingProp)($,Q,D)),(0,OZ.reportMissingProp)($,D),Z.else()}function z(){Z.forOf("prop",Y,(D)=>{$.setParams({missingProperty:D}),Z.if((0,OZ.noPropertyInData)(Z,W,D,J.ownProperties),()=>$.error())})}function F(D,L){$.setParams({missingProperty:D}),Z.forOf(D,Y,()=>{Z.assign(L,(0,OZ.propertyInData)(Z,W,D,J.ownProperties)),Z.if((0,jZ.not)(L),()=>{$.error(),Z.break()})},jZ.nil)}}};kG.default=mA});var gG=O((vG)=>{Object.defineProperty(vG,"__esModule",{value:!0});var PZ=b(),pA={message({keyword:$,schemaCode:Z}){let Q=$==="maxItems"?"more":"fewer";return PZ.str`must NOT have ${Q} than ${Z} items`},params:({schemaCode:$})=>PZ._`{limit: ${$}}`},cA={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:pA,code($){let{keyword:Z,data:Q,schemaCode:Y}=$,W=Z==="maxItems"?PZ.operators.GT:PZ.operators.LT;$.fail$data(PZ._`${Q}.length ${W} ${Y}`)}};vG.default=cA});var e5=O((uG)=>{Object.defineProperty(uG,"__esModule",{value:!0});var hG=I8();hG.code='require("ajv/dist/runtime/equal").default';uG.default=hG});var lG=O((mG)=>{Object.defineProperty(mG,"__esModule",{value:!0});var p8=BZ(),Z0=b(),nA=k(),aA=e5(),rA={message:({params:{i:$,j:Z}})=>Z0.str`must NOT have duplicate items (items ## ${Z} and ${$} are identical)`,params:({params:{i:$,j:Z}})=>Z0._`{i: ${$}, j: ${Z}}`},tA={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rA,code($){let{gen:Z,data:Q,$data:Y,schema:W,parentSchema:G,schemaCode:X,it:J}=$;if(!Y&&!W)return;let B=Z.let("valid"),K=G.items?(0,p8.getSchemaTypes)(G.items):[];$.block$data(B,V,Z0._`${X} === false`),$.ok(B);function V(){let L=Z.let("i",Z0._`${Q}.length`),U=Z.let("j");$.setParams({i:L,j:U}),Z.assign(B,!0),Z.if(Z0._`${L} > 1`,()=>(z()?F:D)(L,U))}function z(){return K.length>0&&!K.some((L)=>L==="object"||L==="array")}function F(L,U){let q=Z.name("item"),A=(0,p8.checkDataTypes)(K,q,J.opts.strictNumbers,p8.DataType.Wrong),N=Z.const("indices",Z0._`{}`);Z.for(Z0._`;${L}--;`,()=>{if(Z.let(q,Z0._`${Q}[${L}]`),Z.if(A,Z0._`continue`),K.length>1)Z.if(Z0._`typeof ${q} == "string"`,Z0._`${q} += "_"`);Z.if(Z0._`typeof ${N}[${q}] == "number"`,()=>{Z.assign(U,Z0._`${N}[${q}]`),$.error(),Z.assign(B,!1).break()}).code(Z0._`${N}[${q}] = ${L}`)})}function D(L,U){let q=(0,nA.useFunc)(Z,aA.default),A=Z.name("outer");Z.label(A).for(Z0._`;${L}--;`,()=>Z.for(Z0._`${U} = ${L}; ${U}--;`,()=>Z.if(Z0._`${q}(${Q}[${L}], ${Q}[${U}])`,()=>{$.error(),Z.assign(B,!1).break(A)})))}}};mG.default=tA});var cG=O((pG)=>{Object.defineProperty(pG,"__esModule",{value:!0});var c8=b(),sA=k(),eA=e5(),$N={message:"must be equal to constant",params:({schemaCode:$})=>c8._`{allowedValue: ${$}}`},ZN={keyword:"const",$data:!0,error:$N,code($){let{gen:Z,data:Q,$data:Y,schemaCode:W,schema:G}=$;if(Y||G&&typeof G=="object")$.fail$data(c8._`!${(0,sA.useFunc)(Z,eA.default)}(${Q}, ${W})`);else $.fail(c8._`${G} !== ${Q}`)}};pG.default=ZN});var iG=O((dG)=>{Object.defineProperty(dG,"__esModule",{value:!0});var wZ=b(),YN=k(),WN=e5(),GN={message:"must be equal to one of the allowed values",params:({schemaCode:$})=>wZ._`{allowedValues: ${$}}`},XN={keyword:"enum",schemaType:"array",$data:!0,error:GN,code($){let{gen:Z,data:Q,$data:Y,schema:W,schemaCode:G,it:X}=$;if(!Y&&W.length===0)throw Error("enum must have non-empty array");let J=W.length>=X.opts.loopEnum,B,K=()=>B!==null&&B!==void 0?B:B=(0,YN.useFunc)(Z,WN.default),V;if(J||Y)V=Z.let("valid"),$.block$data(V,z);else{if(!Array.isArray(W))throw Error("ajv implementation error");let D=Z.const("vSchema",G);V=(0,wZ.or)(...W.map((L,U)=>F(D,U)))}$.pass(V);function z(){Z.assign(V,!1),Z.forOf("v",G,(D)=>Z.if(wZ._`${K()}(${Q}, ${D})`,()=>Z.assign(V,!0).break()))}function F(D,L){let U=W[L];return typeof U==="object"&&U!==null?wZ._`${K()}(${Q}, ${D}[${L}])`:wZ._`${Q} === ${U}`}}};dG.default=XN});var aG=O((nG)=>{Object.defineProperty(nG,"__esModule",{value:!0});var KN=PG(),BN=TG(),HN=CG(),VN=bG(),zN=xG(),FN=fG(),LN=gG(),DN=lG(),UN=cG(),qN=iG(),AN=[KN.default,BN.default,HN.default,VN.default,zN.default,FN.default,LN.default,DN.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},UN.default,qN.default];nG.default=AN});var i8=O((tG)=>{Object.defineProperty(tG,"__esModule",{value:!0});tG.validateAdditionalItems=void 0;var l1=b(),d8=k(),MN={message:({params:{len:$}})=>l1.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>l1._`{limit: ${$}}`},ON={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:MN,code($){let{parentSchema:Z,it:Q}=$,{items:Y}=Z;if(!Array.isArray(Y)){(0,d8.checkStrictMode)(Q,'"additionalItems" is ignored when "items" is not an array of schemas');return}rG($,Y)}};function rG($,Z){let{gen:Q,schema:Y,data:W,keyword:G,it:X}=$;X.items=!0;let J=Q.const("len",l1._`${W}.length`);if(Y===!1)$.setParams({len:Z.length}),$.pass(l1._`${J} <= ${Z.length}`);else if(typeof Y=="object"&&!(0,d8.alwaysValidSchema)(X,Y)){let K=Q.var("valid",l1._`${J} <= ${Z.length}`);Q.if((0,l1.not)(K),()=>B(K)),$.ok(K)}function B(K){Q.forRange("i",Z.length,J,(V)=>{if($.subschema({keyword:G,dataProp:V,dataPropType:d8.Type.Num},K),!X.allErrors)Q.if((0,l1.not)(K),()=>Q.break())})}}tG.validateAdditionalItems=rG;tG.default=ON});var n8=O(($X)=>{Object.defineProperty($X,"__esModule",{value:!0});$X.validateTuple=void 0;var sG=b(),$6=k(),PN=P0(),wN={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code($){let{schema:Z,it:Q}=$;if(Array.isArray(Z))return eG($,"additionalItems",Z);if(Q.items=!0,(0,$6.alwaysValidSchema)(Q,Z))return;$.ok((0,PN.validateArray)($))}};function eG($,Z,Q=$.schema){let{gen:Y,parentSchema:W,data:G,keyword:X,it:J}=$;if(V(W),J.opts.unevaluated&&Q.length&&J.items!==!0)J.items=$6.mergeEvaluated.items(Y,Q.length,J.items);let B=Y.name("valid"),K=Y.const("len",sG._`${G}.length`);Q.forEach((z,F)=>{if((0,$6.alwaysValidSchema)(J,z))return;Y.if(sG._`${K} > ${F}`,()=>$.subschema({keyword:X,schemaProp:F,dataProp:F},B)),$.ok(B)});function V(z){let{opts:F,errSchemaPath:D}=J,L=Q.length,U=L===z.minItems&&(L===z.maxItems||z[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,$6.checkStrictMode)(J,q,F.strictTuples)}}}$X.validateTuple=eG;$X.default=wN});var YX=O((QX)=>{Object.defineProperty(QX,"__esModule",{value:!0});var IN=n8(),RN={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:($)=>(0,IN.validateTuple)($,"items")};QX.default=RN});var XX=O((GX)=>{Object.defineProperty(GX,"__esModule",{value:!0});var WX=b(),SN=k(),CN=P0(),yN=i8(),bN={message:({params:{len:$}})=>WX.str`must NOT have more than ${$} items`,params:({params:{len:$}})=>WX._`{limit: ${$}}`},_N={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:bN,code($){let{schema:Z,parentSchema:Q,it:Y}=$,{prefixItems:W}=Q;if(Y.items=!0,(0,SN.alwaysValidSchema)(Y,Z))return;if(W)(0,yN.validateAdditionalItems)($,W);else $.ok((0,CN.validateArray)($))}};GX.default=_N});var KX=O((JX)=>{Object.defineProperty(JX,"__esModule",{value:!0});var w0=b(),Z6=k(),kN={message:({params:{min:$,max:Z}})=>Z===void 0?w0.str`must contain at least ${$} valid item(s)`:w0.str`must contain at least ${$} and no more than ${Z} valid item(s)`,params:({params:{min:$,max:Z}})=>Z===void 0?w0._`{minContains: ${$}}`:w0._`{minContains: ${$}, maxContains: ${Z}}`},fN={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:kN,code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,it:G}=$,X,J,{minContains:B,maxContains:K}=Y;if(G.opts.next)X=B===void 0?1:B,J=K;else X=1;let V=Z.const("len",w0._`${W}.length`);if($.setParams({min:X,max:J}),J===void 0&&X===0){(0,Z6.checkStrictMode)(G,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(J!==void 0&&X>J){(0,Z6.checkStrictMode)(G,'"minContains" > "maxContains" is always invalid'),$.fail();return}if((0,Z6.alwaysValidSchema)(G,Q)){let U=w0._`${V} >= ${X}`;if(J!==void 0)U=w0._`${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(w0._`${W}.length > 0`,F)}else Z.let(z,!1),F();$.result(z,()=>$.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,V,(A)=>{$.subschema({keyword:"contains",dataProp:A,dataPropType:Z6.Type.Num,compositeRule:!0},U),q()})}function L(U){if(Z.code(w0._`${U}++`),J===void 0)Z.if(w0._`${U} >= ${X}`,()=>Z.assign(z,!0).break());else if(Z.if(w0._`${U} > ${J}`,()=>Z.assign(z,!1).break()),X===1)Z.assign(z,!0);else Z.if(w0._`${U} >= ${X}`,()=>Z.assign(z,!0))}}};JX.default=fN});var LX=O((VX)=>{Object.defineProperty(VX,"__esModule",{value:!0});VX.validateSchemaDeps=VX.validatePropertyDeps=VX.error=void 0;var a8=b(),gN=k(),TZ=P0();VX.error={message:({params:{property:$,depsCount:Z,deps:Q}})=>{let Y=Z===1?"property":"properties";return a8.str`must have ${Y} ${Q} when property ${$} is present`},params:({params:{property:$,depsCount:Z,deps:Q,missingProperty:Y}})=>a8._`{property: ${$},
|
|
7
7
|
missingProperty: ${Y},
|
|
8
8
|
depsCount: ${Z},
|
|
9
|
-
deps: ${Q}}`};var sN={keyword:"dependencies",type:"object",schemaType:"object",error:NX.error,code($){let[Z,Q]=eN($);qX($,Z),AX($,Q)}};function eN({schema:$}){let Z={},Q={};for(let Y in $){if(Y==="__proto__")continue;let W=Array.isArray($[Y])?Z:Q;W[Y]=$[Y]}return[Z,Q]}function qX($,Z=$.schema){let{gen:Q,data:Y,it:W}=$;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 B=(0,CZ.propertyInData)(Q,Y,X,W.opts.ownProperties);if($.setParams({property:X,depsCount:J.length,deps:J.join(", ")}),W.allErrors)Q.if(B,()=>{for(let K of J)(0,CZ.checkReportMissingProp)($,K)});else Q.if(e4._`${B} && (${(0,CZ.checkMissingProp)($,J,G)})`),(0,CZ.reportMissingProp)($,G),Q.else()}}NX.validatePropertyDeps=qX;function AX($,Z=$.schema){let{gen:Q,data:Y,keyword:W,it:G}=$,X=Q.name("valid");for(let J in Z){if((0,oN.alwaysValidSchema)(G,Z[J]))continue;Q.if((0,CZ.propertyInData)(Q,Y,J,G.opts.ownProperties),()=>{let B=$.subschema({keyword:W,schemaProp:J},X);$.mergeValidEvaluated(B,X)},()=>Q.var(X,!0)),$.ok(X)}}NX.validateSchemaDeps=AX;NX.default=sN});var IX=M((wX)=>{Object.defineProperty(wX,"__esModule",{value:!0});var PX=b(),QO=k(),YO={message:"property name must be valid",params:({params:$})=>PX._`{propertyName: ${$.propertyName}}`},WO={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:YO,code($){let{gen:Z,schema:Q,data:Y,it:W}=$;if((0,QO.alwaysValidSchema)(W,Q))return;let G=Z.name("valid");Z.forIn("key",Y,(X)=>{$.setParams({propertyName:X}),$.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),Z.if((0,PX.not)(G),()=>{if($.error(!0),!W.allErrors)Z.break()})}),$.ok(G)}};wX.default=WO});var $9=M((TX)=>{Object.defineProperty(TX,"__esModule",{value:!0});var J6=P0(),b0=b(),XO=$1(),K6=k(),JO={message:"must NOT have additional properties",params:({params:$})=>b0._`{additionalProperty: ${$.additionalProperty}}`},KO={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:JO,code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,errsCount:G,it:X}=$;if(!G)throw Error("ajv implementation error");let{allErrors:J,opts:B}=X;if(X.props=!0,B.removeAdditional!=="all"&&(0,K6.alwaysValidSchema)(X,Q))return;let K=(0,J6.allSchemaProperties)(Y.properties),V=(0,J6.allSchemaProperties)(Y.patternProperties);z(),$.ok(b0._`${G} === ${XO.default.errors}`);function z(){Z.forIn("key",W,(q)=>{if(!K.length&&!V.length)D(q);else Z.if(F(q),()=>D(q))})}function F(q){let A;if(K.length>8){let N=(0,K6.schemaRefOrVal)(X,Y.properties,"properties");A=(0,J6.isOwnProperty)(Z,N,q)}else if(K.length)A=(0,b0.or)(...K.map((N)=>b0._`${q} === ${N}`));else A=b0.nil;if(V.length)A=(0,b0.or)(A,...V.map((N)=>b0._`${(0,J6.usePattern)($,N)}.test(${q})`));return(0,b0.not)(A)}function L(q){Z.code(b0._`delete ${W}[${q}]`)}function D(q){if(B.removeAdditional==="all"||B.removeAdditional&&Q===!1){L(q);return}if(Q===!1){if($.setParams({additionalProperty:q}),$.error(),!J)Z.break();return}if(typeof Q=="object"&&!(0,K6.alwaysValidSchema)(X,Q)){let A=Z.name("valid");if(B.removeAdditional==="failing")U(q,A,!1),Z.if((0,b0.not)(A),()=>{$.reset(),L(q)});else if(U(q,A),!J)Z.if((0,b0.not)(A),()=>Z.break())}}function U(q,A,N){let j={keyword:"additionalProperties",dataProp:q,dataPropType:K6.Type.Str};if(N===!1)Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(j,A)}}};TX.default=KO});var SX=M((CX)=>{Object.defineProperty(CX,"__esModule",{value:!0});var HO=qZ(),RX=P0(),Z9=k(),EX=$9(),VO={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,it:G}=$;if(G.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)EX.default.code(new HO.KeywordCxt(G,EX.default,"additionalProperties"));let X=(0,RX.allSchemaProperties)(Q);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=Z9.mergeEvaluated.props(Z,(0,Z9.toHash)(X),G.props);let J=X.filter((z)=>!(0,Z9.alwaysValidSchema)(G,Q[z]));if(J.length===0)return;let B=Z.name("valid");for(let z of J){if(K(z))V(z);else{if(Z.if((0,RX.propertyInData)(Z,W,z,G.opts.ownProperties)),V(z),!G.allErrors)Z.else().var(B,!0);Z.endIf()}$.it.definedProperties.add(z),$.ok(B)}function K(z){return G.opts.useDefaults&&!G.compositeRule&&Q[z].default!==void 0}function V(z){$.subschema({keyword:"properties",schemaProp:z,dataProp:z},B)}}};CX.default=VO});var kX=M((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});var yX=P0(),B6=b(),bX=k(),_X=k(),FO={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,data:Y,parentSchema:W,it:G}=$,{opts:X}=G,J=(0,yX.allSchemaProperties)(Q),B=J.filter((U)=>(0,bX.alwaysValidSchema)(G,Q[U]));if(J.length===0||B.length===J.length&&(!G.opts.unevaluated||G.props===!0))return;let K=X.strictSchema&&!X.allowMatchingProperties&&W.properties,V=Z.name("valid");if(G.props!==!0&&!(G.props instanceof B6.Name))G.props=(0,_X.evaluatedPropsToName)(Z,G.props);let{props:z}=G;F();function F(){for(let U of J){if(K)L(U);if(G.allErrors)D(U);else Z.var(V,!0),D(U),Z.if(V)}}function L(U){for(let q in K)if(new RegExp(U).test(q))(0,bX.checkStrictMode)(G,`property ${q} matches pattern ${U} (use allowMatchingProperties)`)}function D(U){Z.forIn("key",Y,(q)=>{Z.if(B6._`${(0,yX.usePattern)($,U)}.test(${q})`,()=>{let A=B.includes(U);if(!A)$.subschema({keyword:"patternProperties",schemaProp:U,dataProp:q,dataPropType:_X.Type.Str},V);if(G.opts.unevaluated&&z!==!0)Z.assign(B6._`${z}[${q}]`,!0);else if(!A&&!G.allErrors)Z.if((0,B6.not)(V),()=>Z.break())})})}}};xX.default=FO});var vX=M((fX)=>{Object.defineProperty(fX,"__esModule",{value:!0});var LO=k(),UO={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:Z,schema:Q,it:Y}=$;if((0,LO.alwaysValidSchema)(Y,Q)){$.fail();return}let W=Z.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),$.failResult(W,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};fX.default=UO});var hX=M((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});var AO=P0(),NO={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:AO.validateUnion,error:{message:"must match a schema in anyOf"}};gX.default=NO});var mX=M((uX)=>{Object.defineProperty(uX,"__esModule",{value:!0});var H6=b(),MO=k(),jO={message:"must match exactly one schema in oneOf",params:({params:$})=>H6._`{passingSchemas: ${$.passing}}`},PO={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jO,code($){let{gen:Z,schema:Q,parentSchema:Y,it:W}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(W.opts.discriminator&&Y.discriminator)return;let G=Q,X=Z.let("valid",!1),J=Z.let("passing",null),B=Z.name("_valid");$.setParams({passing:J}),Z.block(K),$.result(X,()=>$.reset(),()=>$.error(!0));function K(){G.forEach((V,z)=>{let F;if((0,MO.alwaysValidSchema)(W,V))Z.var(B,!0);else F=$.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},B);if(z>0)Z.if(H6._`${B} && ${X}`).assign(X,!1).assign(J,H6._`[${J}, ${z}]`).else();Z.if(B,()=>{if(Z.assign(X,!0),Z.assign(J,z),F)$.mergeEvaluated(F,H6.Name)})})}}};uX.default=PO});var pX=M((lX)=>{Object.defineProperty(lX,"__esModule",{value:!0});var IO=k(),TO={keyword:"allOf",schemaType:"array",code($){let{gen:Z,schema:Q,it:Y}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");let W=Z.name("valid");Q.forEach((G,X)=>{if((0,IO.alwaysValidSchema)(Y,G))return;let J=$.subschema({keyword:"allOf",schemaProp:X},W);$.ok(W),$.mergeEvaluated(J)})}};lX.default=TO});var nX=M((iX)=>{Object.defineProperty(iX,"__esModule",{value:!0});var V6=b(),dX=k(),EO={message:({params:$})=>V6.str`must match "${$.ifClause}" schema`,params:({params:$})=>V6._`{failingKeyword: ${$.ifClause}}`},CO={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:EO,code($){let{gen:Z,parentSchema:Q,it:Y}=$;if(Q.then===void 0&&Q.else===void 0)(0,dX.checkStrictMode)(Y,'"if" without "then" and "else" is ignored');let W=cX(Y,"then"),G=cX(Y,"else");if(!W&&!G)return;let X=Z.let("valid",!0),J=Z.name("_valid");if(B(),$.reset(),W&&G){let V=Z.let("ifClause");$.setParams({ifClause:V}),Z.if(J,K("then",V),K("else",V))}else if(W)Z.if(J,K("then"));else Z.if((0,V6.not)(J),K("else"));$.pass(X,()=>$.error(!0));function B(){let V=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(V)}function K(V,z){return()=>{let F=$.subschema({keyword:V},J);if(Z.assign(X,J),$.mergeValidEvaluated(F,X),z)Z.assign(z,V6._`${V}`);else $.setParams({ifClause:V})}}}};function cX($,Z){let Q=$.schema[Z];return Q!==void 0&&!(0,dX.alwaysValidSchema)($,Q)}iX.default=CO});var rX=M((aX)=>{Object.defineProperty(aX,"__esModule",{value:!0});var yO=k(),bO={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:Z,it:Q}){if(Z.if===void 0)(0,yO.checkStrictMode)(Q,`"${$}" without "if" is ignored`)}};aX.default=bO});var oX=M((tX)=>{Object.defineProperty(tX,"__esModule",{value:!0});var xO=o4(),kO=VX(),fO=s4(),vO=DX(),gO=UX(),hO=jX(),uO=IX(),mO=$9(),lO=SX(),pO=kX(),cO=vX(),dO=hX(),iO=mX(),nO=pX(),aO=nX(),rO=rX();function tO($=!1){let Z=[cO.default,dO.default,iO.default,nO.default,aO.default,rO.default,uO.default,mO.default,hO.default,lO.default,pO.default];if($)Z.push(kO.default,vO.default);else Z.push(xO.default,fO.default);return Z.push(gO.default),Z}tX.default=tO});var eX=M((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var i=b(),sO={message:({schemaCode:$})=>i.str`must match format "${$}"`,params:({schemaCode:$})=>i._`{format: ${$}}`},eO={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:sO,code($,Z){let{gen:Q,data:Y,$data:W,schema:G,schemaCode:X,it:J}=$,{opts:B,errSchemaPath:K,schemaEnv:V,self:z}=J;if(!B.validateFormats)return;if(W)F();else L();function F(){let D=Q.scopeValue("formats",{ref:z.formats,code:B.code.formats}),U=Q.const("fDef",i._`${D}[${X}]`),q=Q.let("fType"),A=Q.let("format");Q.if(i._`typeof ${U} == "object" && !(${U} instanceof RegExp)`,()=>Q.assign(q,i._`${U}.type || "string"`).assign(A,i._`${U}.validate`),()=>Q.assign(q,i._`"string"`).assign(A,U)),$.fail$data((0,i.or)(N(),j()));function N(){if(B.strictSchema===!1)return i.nil;return i._`${X} && !${A}`}function j(){let P=V.$async?i._`(${U}.async ? await ${A}(${Y}) : ${A}(${Y}))`:i._`${A}(${Y})`,O=i._`(typeof ${A} == "function" ? ${P} : ${A}.test(${Y}))`;return i._`${A} && ${A} !== true && ${q} === ${Z} && !${O}`}}function L(){let D=z.formats[G];if(!D){N();return}if(D===!0)return;let[U,q,A]=j(D);if(U===Z)$.pass(P());function N(){if(B.strictSchema===!1){z.logger.warn(O());return}throw Error(O());function O(){return`unknown format "${G}" ignored in schema at path "${K}"`}}function j(O){let C=O instanceof RegExp?(0,i.regexpCode)(O):B.code.formats?i._`${B.code.formats}${(0,i.getProperty)(G)}`:void 0,g=Q.scopeValue("formats",{key:G,ref:O,code:C});if(typeof O=="object"&&!(O instanceof RegExp))return[O.type||"string",O.validate,i._`${g}.validate`];return["string",O,g]}function P(){if(typeof D=="object"&&!(D instanceof RegExp)&&D.async){if(!V.$async)throw Error("async format in sync schema");return i._`await ${A}(${Y})`}return typeof q=="function"?i._`${A}(${Y})`:i._`${A}.test(${Y})`}}}};sX.default=eO});var ZJ=M(($J)=>{Object.defineProperty($J,"__esModule",{value:!0});var ZM=eX(),QM=[ZM.default];$J.default=QM});var WJ=M((QJ)=>{Object.defineProperty(QJ,"__esModule",{value:!0});QJ.contentVocabulary=QJ.metadataVocabulary=void 0;QJ.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];QJ.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var JJ=M((XJ)=>{Object.defineProperty(XJ,"__esModule",{value:!0});var GM=CG(),XM=QX(),JM=oX(),KM=ZJ(),GJ=WJ(),BM=[GM.default,XM.default,(0,JM.default)(),KM.default,GJ.metadataVocabulary,GJ.contentVocabulary];XJ.default=BM});var VJ=M((BJ)=>{Object.defineProperty(BJ,"__esModule",{value:!0});BJ.DiscrError=void 0;var KJ;(function($){$.Tag="tag",$.Mapping="mapping"})(KJ||(BJ.DiscrError=KJ={}))});var DJ=M((FJ)=>{Object.defineProperty(FJ,"__esModule",{value:!0});var M$=b(),Q9=VJ(),zJ=a5(),VM=AZ(),zM=k(),FM={message:({params:{discrError:$,tagName:Z}})=>$===Q9.DiscrError.Tag?`tag "${Z}" must be string`:`value of tag "${Z}" must be in oneOf`,params:({params:{discrError:$,tag:Z,tagName:Q}})=>M$._`{error: ${$}, tag: ${Q}, tagValue: ${Z}}`},DM={keyword:"discriminator",type:"object",schemaType:"object",error:FM,code($){let{gen:Z,data:Q,schema:Y,parentSchema:W,it:G}=$,{oneOf:X}=W;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=Y.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(Y.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let B=Z.let("valid",!1),K=Z.const("tag",M$._`${Q}${(0,M$.getProperty)(J)}`);Z.if(M$._`typeof ${K} == "string"`,()=>V(),()=>$.error(!1,{discrError:Q9.DiscrError.Tag,tag:K,tagName:J})),$.ok(B);function V(){let L=F();Z.if(!1);for(let D in L)Z.elseIf(M$._`${K} === ${D}`),Z.assign(B,z(L[D]));Z.else(),$.error(!1,{discrError:Q9.DiscrError.Mapping,tag:K,tagName:J}),Z.endIf()}function z(L){let D=Z.name("valid"),U=$.subschema({keyword:"oneOf",schemaProp:L},D);return $.mergeEvaluated(U,M$.Name),D}function F(){var L;let D={},U=A(W),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,zM.schemaHasRulesButRef)(O,G.self.RULES)){let g=O.$ref;if(O=zJ.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,g),O instanceof zJ.SchemaEnv)O=O.schema;if(O===void 0)throw new VM.default(G.opts.uriResolver,G.baseId,g)}let C=(L=O===null||O===void 0?void 0:O.properties)===null||L===void 0?void 0:L[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 D;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 D)throw Error(`discriminator: "${J}" values must be unique strings`);D[P]=O}}}};FJ.default=DM});var LJ=M((yy,UM)=>{UM.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var W9=M((L0,Y9)=>{Object.defineProperty(L0,"__esModule",{value:!0});L0.MissingRefError=L0.ValidationError=L0.CodeGen=L0.Name=L0.nil=L0.stringify=L0.str=L0._=L0.KeywordCxt=L0.Ajv=void 0;var qM=NG(),AM=JJ(),NM=DJ(),UJ=LJ(),OM=["/properties"],z6="http://json-schema.org/draft-07/schema";class SZ extends qM.default{_addVocabularies(){if(super._addVocabularies(),AM.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(NM.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(UJ,OM):UJ;this.addMetaSchema($,z6,!1),this.refs["http://json-schema.org/schema"]=z6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(z6)?z6:void 0)}}L0.Ajv=SZ;Y9.exports=L0=SZ;Y9.exports.Ajv=SZ;Object.defineProperty(L0,"__esModule",{value:!0});L0.default=SZ;var MM=qZ();Object.defineProperty(L0,"KeywordCxt",{enumerable:!0,get:function(){return MM.KeywordCxt}});var j$=b();Object.defineProperty(L0,"_",{enumerable:!0,get:function(){return j$._}});Object.defineProperty(L0,"str",{enumerable:!0,get:function(){return j$.str}});Object.defineProperty(L0,"stringify",{enumerable:!0,get:function(){return j$.stringify}});Object.defineProperty(L0,"nil",{enumerable:!0,get:function(){return j$.nil}});Object.defineProperty(L0,"Name",{enumerable:!0,get:function(){return j$.Name}});Object.defineProperty(L0,"CodeGen",{enumerable:!0,get:function(){return j$.CodeGen}});var jM=i5();Object.defineProperty(L0,"ValidationError",{enumerable:!0,get:function(){return jM.default}});var PM=AZ();Object.defineProperty(L0,"MissingRefError",{enumerable:!0,get:function(){return PM.default}})});var TJ=M((wJ)=>{Object.defineProperty(wJ,"__esModule",{value:!0});wJ.formatNames=wJ.fastFormats=wJ.fullFormats=void 0;function m0($,Z){return{validate:$,compare:Z}}wJ.fullFormats={date:m0(OJ,K9),time:m0(X9(!0),B9),"date-time":m0(qJ(!0),jJ),"iso-time":m0(X9(),MJ),"iso-date-time":m0(qJ(),PJ),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:yM,"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:gM,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:bM,int32:{type:"number",validate:kM},int64:{type:"number",validate:fM},float:{type:"number",validate:NJ},double:{type:"number",validate:NJ},password:!0,binary:!0};wJ.fastFormats={...wJ.fullFormats,date:m0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,K9),time:m0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,B9),"date-time":m0(/^\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,jJ),"iso-time":m0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,MJ),"iso-date-time":m0(/^\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,PJ),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};wJ.formatNames=Object.keys(wJ.fullFormats);function TM($){return $%4===0&&($%100!==0||$%400===0)}var RM=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,EM=[0,31,28,31,30,31,30,31,31,30,31,30,31];function OJ($){let Z=RM.exec($);if(!Z)return!1;let Q=+Z[1],Y=+Z[2],W=+Z[3];return Y>=1&&Y<=12&&W>=1&&W<=(Y===2&&TM(Q)?29:EM[Y])}function K9($,Z){if(!($&&Z))return;if($>Z)return 1;if($<Z)return-1;return 0}var G9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function X9($){return function(Q){let Y=G9.exec(Q);if(!Y)return!1;let W=+Y[1],G=+Y[2],X=+Y[3],J=Y[4],B=Y[5]==="-"?-1:1,K=+(Y[6]||0),V=+(Y[7]||0);if(K>23||V>59||$&&!J)return!1;if(W<=23&&G<=59&&X<60)return!0;let z=G-V*B,F=W-K*B-(z<0?1:0);return(F===23||F===-1)&&(z===59||z===-1)&&X<61}}function B9($,Z){if(!($&&Z))return;let Q=new Date("2020-01-01T"+$).valueOf(),Y=new Date("2020-01-01T"+Z).valueOf();if(!(Q&&Y))return;return Q-Y}function MJ($,Z){if(!($&&Z))return;let Q=G9.exec($),Y=G9.exec(Z);if(!(Q&&Y))return;if($=Q[1]+Q[2]+Q[3],Z=Y[1]+Y[2]+Y[3],$>Z)return 1;if($<Z)return-1;return 0}var J9=/t|\s/i;function qJ($){let Z=X9($);return function(Y){let W=Y.split(J9);return W.length===2&&OJ(W[0])&&Z(W[1])}}function jJ($,Z){if(!($&&Z))return;let Q=new Date($).valueOf(),Y=new Date(Z).valueOf();if(!(Q&&Y))return;return Q-Y}function PJ($,Z){if(!($&&Z))return;let[Q,Y]=$.split(J9),[W,G]=Z.split(J9),X=K9(Q,W);if(X===void 0)return;return X||B9(Y,G)}var CM=/\/|:/,SM=/^(?:[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 yM($){return CM.test($)&&SM.test($)}var AJ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function bM($){return AJ.lastIndex=0,AJ.test($)}var _M=-2147483648,xM=2147483647;function kM($){return Number.isInteger($)&&$<=xM&&$>=_M}function fM($){return Number.isInteger($)}function NJ(){return!0}var vM=/[^\\]\\Z/;function gM($){if(vM.test($))return!1;try{return new RegExp($),!0}catch(Z){return!1}}});var EJ=M((RJ)=>{Object.defineProperty(RJ,"__esModule",{value:!0});RJ.formatLimitDefinition=void 0;var uM=W9(),_0=b(),w1=_0.operators,F6={formatMaximum:{okStr:"<=",ok:w1.LTE,fail:w1.GT},formatMinimum:{okStr:">=",ok:w1.GTE,fail:w1.LT},formatExclusiveMaximum:{okStr:"<",ok:w1.LT,fail:w1.GTE},formatExclusiveMinimum:{okStr:">",ok:w1.GT,fail:w1.LTE}},mM={message:({keyword:$,schemaCode:Z})=>_0.str`should be ${F6[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>_0._`{comparison: ${F6[$].okStr}, limit: ${Z}}`};RJ.formatLimitDefinition={keyword:Object.keys(F6),type:"string",schemaType:"string",$data:!0,error:mM,code($){let{gen:Z,data:Q,schemaCode:Y,keyword:W,it:G}=$,{opts:X,self:J}=G;if(!X.validateFormats)return;let B=new uM.KeywordCxt(G,J.RULES.all.format.definition,"format");if(B.$data)K();else V();function K(){let F=Z.scopeValue("formats",{ref:J.formats,code:X.code.formats}),L=Z.const("fmt",_0._`${F}[${B.schemaCode}]`);$.fail$data((0,_0.or)(_0._`typeof ${L} != "object"`,_0._`${L} instanceof RegExp`,_0._`typeof ${L}.compare != "function"`,z(L)))}function V(){let F=B.schema,L=J.formats[F];if(!L||L===!0)return;if(typeof L!="object"||L instanceof RegExp||typeof L.compare!="function")throw Error(`"${W}": format "${F}" does not define "compare" function`);let D=Z.scopeValue("formats",{key:F,ref:L,code:X.code.formats?_0._`${X.code.formats}${(0,_0.getProperty)(F)}`:void 0});$.fail$data(z(D))}function z(F){return _0._`${F}.compare(${Q}, ${Y}) ${F6[W].fail} 0`}},dependencies:["format"]};var lM=($)=>{return $.addKeyword(RJ.formatLimitDefinition),$};RJ.default=lM});var bJ=M((yZ,yJ)=>{Object.defineProperty(yZ,"__esModule",{value:!0});var P$=TJ(),cM=EJ(),z9=b(),CJ=new z9.Name("fullFormats"),dM=new z9.Name("fastFormats"),F9=($,Z={keywords:!0})=>{if(Array.isArray(Z))return SJ($,Z,P$.fullFormats,CJ),$;let[Q,Y]=Z.mode==="fast"?[P$.fastFormats,dM]:[P$.fullFormats,CJ],W=Z.formats||P$.formatNames;if(SJ($,W,Q,Y),Z.keywords)(0,cM.default)($);return $};F9.get=($,Z="full")=>{let Y=(Z==="fast"?P$.fastFormats:P$.fullFormats)[$];if(!Y)throw Error(`Unknown format "${$}"`);return Y};function SJ($,Z,Q,Y){var W,G;(W=(G=$.opts.code).formats)!==null&&W!==void 0||(G.formats=z9._`require("ajv-formats/dist/formats").${Y}`);for(let X of Z)$.addFormat(X,Q[X])}yJ.exports=yZ=F9;Object.defineProperty(yZ,"__esModule",{value:!0});yZ.default=F9});var mJ=M((ey,uJ)=>{uJ.exports=hJ;hJ.sync=rM;var vJ=G1("fs");function aM($,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 Y=0;Y<Q.length;Y++){var W=Q[Y].toLowerCase();if(W&&$.substr(-W.length).toLowerCase()===W)return!0}return!1}function gJ($,Z,Q){if(!$.isSymbolicLink()&&!$.isFile())return!1;return aM(Z,Q)}function hJ($,Z,Q){vJ.stat($,function(Y,W){Q(Y,Y?!1:gJ(W,$,Z))})}function rM($,Z){return gJ(vJ.statSync($),$,Z)}});var iJ=M(($b,dJ)=>{dJ.exports=pJ;pJ.sync=tM;var lJ=G1("fs");function pJ($,Z,Q){lJ.stat($,function(Y,W){Q(Y,Y?!1:cJ(W,Z))})}function tM($,Z){return cJ(lJ.statSync($),Z)}function cJ($,Z){return $.isFile()&&oM($,Z)}function oM($,Z){var{mode:Q,uid:Y,gid:W}=$,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),B=parseInt("010",8),K=parseInt("001",8),V=J|B,z=Q&K||Q&B&&W===X||Q&J&&Y===G||Q&V&&G===0;return z}});var aJ=M((Qb,nJ)=>{var Zb=G1("fs"),L6;if(process.platform==="win32"||global.TESTING_WINDOWS)L6=mJ();else L6=iJ();nJ.exports=q9;q9.sync=sM;function q9($,Z,Q){if(typeof Z==="function")Q=Z,Z={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(Y,W){q9($,Z||{},function(G,X){if(G)W(G);else Y(X)})})}L6($,Z||{},function(Y,W){if(Y){if(Y.code==="EACCES"||Z&&Z.ignoreErrors)Y=null,W=!1}Q(Y,W)})}function sM($,Z){try{return L6.sync($,Z||{})}catch(Q){if(Z&&Z.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var Z3=M((Yb,$3)=>{var w$=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",rJ=G1("path"),eM=w$?";":":",tJ=aJ(),oJ=($)=>Object.assign(Error(`not found: ${$}`),{code:"ENOENT"}),sJ=($,Z)=>{let Q=Z.colon||eM,Y=$.match(/\//)||w$&&$.match(/\\/)?[""]:[...w$?[process.cwd()]:[],...(Z.path||process.env.PATH||"").split(Q)],W=w$?Z.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",G=w$?W.split(Q):[""];if(w$){if($.indexOf(".")!==-1&&G[0]!=="")G.unshift("")}return{pathEnv:Y,pathExt:G,pathExtExe:W}},eJ=($,Z,Q)=>{if(typeof Z==="function")Q=Z,Z={};if(!Z)Z={};let{pathEnv:Y,pathExt:W,pathExtExe:G}=sJ($,Z),X=[],J=(K)=>new Promise((V,z)=>{if(K===Y.length)return Z.all&&X.length?V(X):z(oJ($));let F=Y[K],L=/^".*"$/.test(F)?F.slice(1,-1):F,D=rJ.join(L,$),U=!L&&/^\.[\\\/]/.test($)?$.slice(0,2)+D:D;V(B(U,K,0))}),B=(K,V,z)=>new Promise((F,L)=>{if(z===W.length)return F(J(V+1));let D=W[z];tJ(K+D,{pathExt:G},(U,q)=>{if(!U&&q)if(Z.all)X.push(K+D);else return F(K+D);return F(B(K,V,z+1))})});return Q?J(0).then((K)=>Q(null,K),Q):J(0)},$j=($,Z)=>{Z=Z||{};let{pathEnv:Q,pathExt:Y,pathExtExe:W}=sJ($,Z),G=[];for(let X=0;X<Q.length;X++){let J=Q[X],B=/^".*"$/.test(J)?J.slice(1,-1):J,K=rJ.join(B,$),V=!B&&/^\.[\\\/]/.test($)?$.slice(0,2)+K:K;for(let z=0;z<Y.length;z++){let F=V+Y[z];try{if(tJ.sync(F,{pathExt:W}))if(Z.all)G.push(F);else return F}catch(L){}}}if(Z.all&&G.length)return G;if(Z.nothrow)return null;throw oJ($)};$3.exports=eJ;eJ.sync=$j});var Y3=M((Wb,A9)=>{var Q3=($={})=>{let Z=$.env||process.env;if(($.platform||process.platform)!=="win32")return"PATH";return Object.keys(Z).reverse().find((Y)=>Y.toUpperCase()==="PATH")||"Path"};A9.exports=Q3;A9.exports.default=Q3});var J3=M((Gb,X3)=>{var W3=G1("path"),Zj=Z3(),Qj=Y3();function G3($,Z){let Q=$.options.env||process.env,Y=process.cwd(),W=$.options.cwd!=null,G=W&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir($.options.cwd)}catch(J){}let X;try{X=Zj.sync($.command,{path:Q[Qj({env:Q})],pathExt:Z?W3.delimiter:void 0})}catch(J){}finally{if(G)process.chdir(Y)}if(X)X=W3.resolve(W?$.options.cwd:"",X);return X}function Yj($){return G3($)||G3($,!0)}X3.exports=Yj});var K3=M((Xj,O9)=>{var N9=/([()\][%!^"`<>&|;, *?])/g;function Wj($){return $=$.replace(N9,"^$1"),$}function Gj($,Z){if($=`${$}`,$=$.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),$=$.replace(/(?=(\\+?)?)\1$/,"$1$1"),$=`"${$}"`,$=$.replace(N9,"^$1"),Z)$=$.replace(N9,"^$1");return $}Xj.command=Wj;Xj.argument=Gj});var H3=M((Xb,B3)=>{B3.exports=/^#!(.*)/});var z3=M((Jb,V3)=>{var Bj=H3();V3.exports=($="")=>{let Z=$.match(Bj);if(!Z)return null;let[Q,Y]=Z[0].replace(/#! ?/,"").split(" "),W=Q.split("/").pop();if(W==="env")return Y;return Y?`${W} ${Y}`:W}});var D3=M((Kb,F3)=>{var M9=G1("fs"),Hj=z3();function Vj($){let Q=Buffer.alloc(150),Y;try{Y=M9.openSync($,"r"),M9.readSync(Y,Q,0,150,0),M9.closeSync(Y)}catch(W){}return Hj(Q.toString())}F3.exports=Vj});var A3=M((Bb,q3)=>{var zj=G1("path"),L3=J3(),U3=K3(),Fj=D3(),Dj=process.platform==="win32",Lj=/\.(?:com|exe)$/i,Uj=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function qj($){$.file=L3($);let Z=$.file&&Fj($.file);if(Z)return $.args.unshift($.file),$.command=Z,L3($);return $.file}function Aj($){if(!Dj)return $;let Z=qj($),Q=!Lj.test(Z);if($.options.forceShell||Q){let Y=Uj.test(Z);$.command=zj.normalize($.command),$.command=U3.command($.command),$.args=$.args.map((G)=>U3.argument(G,Y));let W=[$.command].concat($.args).join(" ");$.args=["/d","/s","/c",`"${W}"`],$.command=process.env.comspec||"cmd.exe",$.options.windowsVerbatimArguments=!0}return $}function Nj($,Z,Q){if(Z&&!Array.isArray(Z))Q=Z,Z=null;Z=Z?Z.slice(0):[],Q=Object.assign({},Q);let Y={command:$,args:Z,options:Q,file:void 0,original:{command:$,args:Z}};return Q.shell?Y:Aj(Y)}q3.exports=Nj});var M3=M((Hb,O3)=>{var j9=process.platform==="win32";function P9($,Z){return Object.assign(Error(`${Z} ${$.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Z} ${$.command}`,path:$.command,spawnargs:$.args})}function Oj($,Z){if(!j9)return;let Q=$.emit;$.emit=function(Y,W){if(Y==="exit"){let G=N3(W,Z);if(G)return Q.call($,"error",G)}return Q.apply($,arguments)}}function N3($,Z){if(j9&&$===1&&!Z.file)return P9(Z.original,"spawn");return null}function Mj($,Z){if(j9&&$===1&&!Z.file)return P9(Z.original,"spawnSync");return null}O3.exports={hookChildProcess:Oj,verifyENOENT:N3,verifyENOENTSync:Mj,notFoundError:P9}});var w3=M((Vb,I$)=>{var j3=G1("child_process"),w9=A3(),I9=M3();function P3($,Z,Q){let Y=w9($,Z,Q),W=j3.spawn(Y.command,Y.args,Y.options);return I9.hookChildProcess(W,Y),W}function jj($,Z,Q){let Y=w9($,Z,Q),W=j3.spawnSync(Y.command,Y.args,Y.options);return W.error=W.error||I9.verifyENOENTSync(W.status,Y),W}I$.exports=P3;I$.exports.spawn=P3;I$.exports.sync=jj;I$.exports._parse=w9;I$.exports._enoent=I9});import{readFile as cP}from"fs/promises";import{homedir as dP}from"os";import{join as iP,resolve as FK}from"path";class mZ{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 E1{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 Y=this.commands.get(Q.name);if(!Y)return{handled:!0,message:`Unknown command: /${Q.name}`};return await Y.run({...Z,args:Q.args})??{handled:!0}}}var jK=new Set(["rate_limit","overloaded","network"]);class c 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 jK.has(this.kind)}}var PK=[/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 lZ($){return PK.some((Z)=>Z.test($))}function wK($){let Z=$.get("retry-after-ms");if(Z){let Y=Number.parseFloat(Z);if(!Number.isNaN(Y))return Y}let Q=$.get("retry-after");if(Q){let Y=Number.parseFloat(Q);if(!Number.isNaN(Y))return Y*1000;let W=Date.parse(Q);if(!Number.isNaN(W))return W-Date.now()}return}function y$($,Z,Q){let Y={status:$,retryAfterMs:wK(Q)};if($===401||$===403)return new c("auth",Z,Y);if($===404)return new c("not_found",Z,Y);if($===429)return new c("rate_limit",Z,Y);if($===529||$===503)return new c("overloaded",Z,Y);if($>=500)return new c("api",Z,Y);if(lZ(Z))return new c("context_too_long",Z,Y);return new c("bad_request",Z,Y)}var s9={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 TK=[{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"]}],p0=new Map(TK.map(($)=>[$.id,$]));function t1($){return p0.get($)}function b$($){return $.api??t1($.provider)?.api??"openai-completions"}function E6($){return $.baseUrl??t1($.provider)?.baseUrl}function o1($){return t1($)?.env??[]}var RK=new Set(['"',"\\","/","b","f","n","r","t","u"]),EK={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function C6($){let Z="",Q=!1;for(let Y=0;Y<$.length;Y++){let W=$[Y];if(!Q){if(Z+=W,W==='"')Q=!0;continue}if(W==='"'){Z+=W,Q=!1;continue}if(W==="\\"){let X=$[Y+1];if(X===void 0){Z+="\\\\";continue}if(X==="u"&&/^[0-9a-fA-F]{4}$/.test($.slice(Y+2,Y+6))){Z+=$.slice(Y,Y+6),Y+=5;continue}if(X!=="u"&&RK.has(X)){Z+=`\\${X}`,Y+=1;continue}Z+="\\\\";continue}let G=W.codePointAt(0)??0;if(G<=31)Z+=EK[W]??`\\u${G.toString(16).padStart(4,"0")}`;else Z+=W}return Z}function e9($){try{return JSON.parse($)}catch(Z){let Q=C6($);if(Q!==$)return JSON.parse(Q);throw Z}}class $Q{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 Y=this.pos,W=this.value();if(W!==void 0||this.consumedNull(Y))$[Q]=W??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 W=this.text.slice(this.pos+2,this.pos+6);if(/^[0-9a-fA-F]{4}$/.test(W))$+=String.fromCharCode(Number.parseInt(W,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
|
|
11
|
-
`)};return $.event=null,$.data=[],Z}function
|
|
12
|
-
`)K+=1;G=G.slice(K);let V=QQ(B,W);if(V)yield V;J=G.search(/[\r\n]/)}};try{while(!0){if(Z?.aborted)throw Error("Request was aborted");let{value:B,done:K}=await Q.read();if(K)break;G+=Y.decode(B,{stream:!0}),yield*X()}if(G+=Y.decode(),yield*X(),G.length>0){let B=QQ(G,W);if(B)yield B}let J=YQ(W);if(J)yield J}finally{Q.releaseLock()}}function i0($){return $.replace(/\/+$/,"")}function bK($){for(let Z of $){let Q=process.env[Z];if(Q)return Q}return}async function X1($,Z){let Q=await Z?.getCredentials?.();if(Q){if($.provider==="anthropic"&&Q.type==="oauth")throw new c("auth","Anthropic account-plan authentication is not supported");return Q}let Y=Z?.apiKey??bK(o1($.provider));if(!Y){let W=o1($.provider),G=W.length>0?`set ${W.join(" or ")} or run /login`:"run /login";throw new c("auth",`No credentials for provider "${$.provider}" (${G})`)}return{type:"apiKey",apiKey:Y}}function _K($){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 Y=`https://gateway.ai.cloudflare.com/v1/${Z}/${Q}`;if($.api==="anthropic-messages")return`${Y}/anthropic`;if($.api==="openai-responses")return`${Y}/openai`;return`${Y}/compat`}function xK(){let $=process.env.AZURE_OPENAI_BASE_URL,Z=process.env.AZURE_OPENAI_RESOURCE_NAME;if(!$&&!Z)return;let Q=i0($??`https://${Z}.openai.azure.com`);return Q.endsWith("/openai/v1")?Q:`${Q}/openai/v1`}function kK(){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 fK(){return`https://bedrock-runtime.${process.env.AWS_REGION??process.env.AWS_DEFAULT_REGION??"us-east-1"}.amazonaws.com/openai/v1`}function vK($,Z){if(Z?.baseUrl)return i0(Z.baseUrl);if($.provider.startsWith("cloudflare-")){let Q=_K($);if(Q)return i0(Q)}if($.provider==="azure-openai-responses"){let Q=xK();if(Q)return i0(Q)}if($.provider==="google-vertex"){let Q=kK();if(Q)return i0(Q)}if($.provider==="amazon-bedrock")return fK();return i0(E6($)??"")}function s1($,Z){let Q=i0($),Y=Z.startsWith("/")?Z:`/${Z}`;if(!Q)return Y;if(Y.startsWith("/v1/")&&Q.endsWith("/v1"))return`${Q}${Y.slice(3)}`;return`${Q}${Y}`}function J1($,Z){let Q=t1($.provider),Y={...Q?.headers,...$.headers};if(Z.type==="oauth")return{...Y,authorization:`Bearer ${Z.accessToken}`,...Z.headers};if(Q?.auth==="anthropic")return{...Y,"x-api-key":Z.apiKey};if(Q?.auth==="google")return{...Y,"x-goog-api-key":Z.apiKey};if(Q?.auth==="azure")return{...Y,"api-key":Z.apiKey};if(Q?.auth==="cloudflare")return{...Y,"cf-aig-authorization":`Bearer ${Z.apiKey}`};return{...Y,authorization:`Bearer ${Z.apiKey}`}}function K1($,Z,Q){if(Q?.baseUrl)return i0(Q.baseUrl);if(Z.type==="oauth"&&Z.baseUrl)return i0(Z.baseUrl);return vK($,Q)}function y6($,Z){return(Z.inputTokens*$.input+Z.outputTokens*$.output+Z.cacheReadTokens*$.cacheRead+Z.cacheWriteTokens*$.cacheWrite)/1e6}function _$(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0}}function B1($,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 pZ{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 cZ extends pZ{constructor(){super(($)=>$.type==="done"||$.type==="error",($)=>{if($.type==="done")return $.message;if($.type==="error")return $.error;throw Error("unexpected final event")})}}function gK($){return{role:"assistant",content:[],model:`${$.provider}/${$.id}`,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0},stopReason:"end",timestamp:Date.now()}}function n0($,Z){Z.usage.costUsd=y6($.pricing,Z.usage)}function H1($,Z,Q){let Y=new cZ,W=gK($);return(async()=>{try{if(await Q(Y,W),Z?.signal?.aborted)throw Error("Request was aborted");if(W.stopReason==="error")throw new c("api",W.errorMessage??"provider reported an error");Y.push({type:"done",message:W})}catch(G){W.stopReason=Z?.signal?.aborted?"aborted":"error",W.errorMessage=G instanceof Error?G.message:JSON.stringify(G),Y.push({type:"error",reason:W.stopReason,...G instanceof c?{errorKind:G.kind}:{},error:W})}finally{Y.end()}})(),Y}async function V1($,Z,Q,Y){let W=Y?.fetch??fetch,G;try{G=await W($,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...Z},body:JSON.stringify(Q),...Y?.signal?{signal:Y.signal}:{}})}catch(X){if(Y?.signal?.aborted)throw X;let J=X instanceof Error?X.message:String(X);throw new c("network",J)}if(!G.ok){let X=await G.text();throw y$(G.status,X,G.headers)}if(!G.body)throw new c("api","response has no body");return G}var hK="2023-06-01",b6={type:"ephemeral"};function WQ($){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 uK($){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 mK($,Z){let Q=[];for(let W=0;W<$.length;W++){let G=$[W];if(G.role==="user"){let X=WQ(G.content);if(X.length>0)Q.push({role:"user",content:X})}else if(G.role==="assistant"){let X=uK(G.content);if(X.length>0)Q.push({role:"assistant",content:X})}else{let X=[];while(W<$.length){let J=$[W];if(!J||J.role!=="toolResult")break;X.push({type:"tool_result",tool_use_id:J.toolCallId,content:WQ(J.content),is_error:J.isError}),W++}W--,Q.push({role:"user",content:X})}}let Y=Q[Q.length-1];if(Z&&Y&&Y.role==="user"){let W=Y.content,G=W[W.length-1];if(G)G.cache_control=b6}return Q}function lK($,Z,Q){if(!$.thinking||Z===void 0)return;if(Z==="off"){Q.thinking={type:"disabled"};return}if($.thinkingMode==="budget"){let Y={low:4096,medium:8192,high:16384};Q.thinking={type:"enabled",budget_tokens:Y[Z]??8192,display:"summarized"};return}Q.thinking={type:"adaptive",display:"summarized"},Q.output_config={effort:Z}}function pK($,Z,Q){let Y=$.provider==="anthropic",W={model:$.id,max_tokens:Q?.maxTokens??$.maxOutput,messages:mK(Z.messages,Y),stream:!0};if(Z.systemPrompt&&Z.systemPrompt.length>0){let G=Z.systemPrompt.reduce((X,J,B)=>J.dynamic?X:B,-1);W.system=Z.systemPrompt.map((X,J)=>({type:"text",text:X.text,...Y&&J===G?{cache_control:b6}:{}}))}if(Z.tools&&Z.tools.length>0)W.tools=Z.tools.map((G,X)=>({name:G.name,description:G.description,input_schema:G.inputSchema,...Y&&X===(Z.tools?.length??0)-1?{cache_control:b6}:{}}));if(Q?.temperature!==void 0)W.temperature=Q.temperature;return lK($,Q?.thinkingLevel,W),W}function cK($){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 GQ($,Z,Q){return H1($,Q,async(Y,W)=>{let G=pK($,Z,Q),X=await c0(async()=>{let K=await X1($,Q),V=K1($,K,Q),z={"anthropic-version":hK,...J1($,K),...Q?.headers};return V1(s1(V,"/v1/messages"),z,G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=new Map,B=X.body;for await(let K of d0(B,Q?.signal)){if(K.event==="error")throw Error(K.data);if(!K.data)continue;let V=JSON.parse(K.data),z=V.type;if(z==="message_start"){let F=V.message?.usage;if(F)W.usage.inputTokens=F.input_tokens??0,W.usage.outputTokens=F.output_tokens??0,W.usage.cacheReadTokens=F.cache_read_input_tokens??0,W.usage.cacheWriteTokens=F.cache_creation_input_tokens??0,n0($,W)}else if(z==="content_block_start"){let{index:F,content_block:L}=V,D=W.content.length;J.set(F,{contentIndex:D,partialJson:""});let U=L.type;if(U==="text")W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:D,partial:W});else if(U==="thinking")W.content.push({type:"thinking",thinking:"",signature:""}),Y.push({type:"thinking_start",contentIndex:D,partial:W});else if(U==="redacted_thinking")W.content.push({type:"thinking",thinking:"[reasoning redacted]",signature:L.data??"",redacted:!0}),Y.push({type:"thinking_start",contentIndex:D,partial:W});else if(U==="tool_use")W.content.push({type:"toolCall",id:L.id,name:L.name,arguments:L.input??{}}),Y.push({type:"toolcall_start",contentIndex:D,partial:W});else J.delete(F)}else if(z==="content_block_delta"){let F=J.get(V.index);if(!F)continue;let L=W.content[F.contentIndex],D=V.delta,U=D.type;if(U==="text_delta"&&L?.type==="text")L.text+=D.text,Y.push({type:"text_delta",contentIndex:F.contentIndex,delta:D.text,partial:W});else if(U==="thinking_delta"&&L?.type==="thinking")L.thinking+=D.thinking,Y.push({type:"thinking_delta",contentIndex:F.contentIndex,delta:D.thinking,partial:W});else if(U==="input_json_delta"&&L?.type==="toolCall")F.partialJson+=D.partial_json,L.arguments=g0(F.partialJson),Y.push({type:"toolcall_delta",contentIndex:F.contentIndex,delta:D.partial_json,partial:W});else if(U==="signature_delta"&&L?.type==="thinking")L.signature=(L.signature??"")+D.signature}else if(z==="content_block_stop"){let F=J.get(V.index);if(!F)continue;let L=W.content[F.contentIndex];if(L?.type==="text")Y.push({type:"text_end",contentIndex:F.contentIndex,content:L.text,partial:W});else if(L?.type==="thinking")Y.push({type:"thinking_end",contentIndex:F.contentIndex,content:L.thinking,partial:W});else if(L?.type==="toolCall")L.arguments=g0(F.partialJson),Y.push({type:"toolcall_end",contentIndex:F.contentIndex,toolCall:L,partial:W})}else if(z==="message_delta"){let F=V.delta;if(F?.stop_reason){let D=cK(F.stop_reason);if(W.stopReason=D.stopReason,D.errorMessage)W.errorMessage=D.errorMessage}let L=V.usage;if(L){if(L.input_tokens!=null)W.usage.inputTokens=L.input_tokens;if(L.output_tokens!=null)W.usage.outputTokens=L.output_tokens;if(L.cache_read_input_tokens!=null)W.usage.cacheReadTokens=L.cache_read_input_tokens;if(L.cache_creation_input_tokens!=null)W.usage.cacheWriteTokens=L.cache_creation_input_tokens;n0($,W)}}}})}var x$={id:"anthropic",stream:GQ};function dK($){let Z=[],Q=new Map,Y=(W,G)=>{if(G.length===0)return;let X=Z[Z.length-1];if(X&&X.role===W)X.parts.push(...G);else Z.push({role:W,parts:G})};for(let W of $)if(W.role==="user")Y("user",W.content.map((G)=>G.type==="text"?{text:G.text}:{inlineData:{mimeType:G.mimeType,data:G.data}}));else if(W.role==="assistant"){let G=[];for(let X of W.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}:{}});Y("model",G)}else{let G=Q.get(W.toolCallId)??W.toolName,X=W.content.filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
13
|
-
`),J=[{functionResponse:{name:G,response:W.isError?{error:X}:{output:X}}}];for(let B of W.content)if(B.type==="image")J.push({inlineData:{mimeType:B.mimeType,data:B.data}});Y("user",J)}return{contents:Z,toolNames:Q}}function
|
|
14
|
-
`):Q.content.map((W)=>W.type==="text"?{type:"input_text",text:W.text}:{type:"input_image",image_url:`data:${W.mimeType};base64,${W.data}`});Z.push({type:"function_call_output",call_id:Q.toolCallId,output:Y})}return Z}function
|
|
15
|
-
|
|
16
|
-
`);else if(Y)W.instructions="You are a helpful assistant.";if(Z.tools&&Z.tools.length>0)W.tools=Z.tools.map((G)=>({type:"function",name:G.name,description:G.description,parameters:G.inputSchema,strict:Y?null:!1}));if(Y){W.text={verbosity:"low"},W.include=["reasoning.encrypted_content"],W.tool_choice="auto",W.parallel_tool_calls=!0;let G=
|
|
17
|
-
`)||"(image result attached in the following user message)"}function
|
|
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
|
|
19
|
-
|
|
20
|
-
`)});let Y=[],W=()=>{let G=Y.filter((X)=>X.type==="image");if(G.length>0)Q.push({role:"user",content:[{type:"text",text:"Images returned by the preceding tool calls:"},...G.map((X)=>({type:"image_url",image_url:{url:`data:${X.mimeType};base64,${X.data}`}}))]});Y=[]};for(let G of $){if(G.role!=="toolResult")W();if(G.role==="user"){Q.push({role:"user",content:
|
|
9
|
+
deps: ${Q}}`};var hN={keyword:"dependencies",type:"object",schemaType:"object",error:VX.error,code($){let[Z,Q]=uN($);BX($,Z),HX($,Q)}};function uN({schema:$}){let Z={},Q={};for(let Y in $){if(Y==="__proto__")continue;let W=Array.isArray($[Y])?Z:Q;W[Y]=$[Y]}return[Z,Q]}function BX($,Z=$.schema){let{gen:Q,data:Y,it:W}=$;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 B=(0,TZ.propertyInData)(Q,Y,X,W.opts.ownProperties);if($.setParams({property:X,depsCount:J.length,deps:J.join(", ")}),W.allErrors)Q.if(B,()=>{for(let K of J)(0,TZ.checkReportMissingProp)($,K)});else Q.if(a8._`${B} && (${(0,TZ.checkMissingProp)($,J,G)})`),(0,TZ.reportMissingProp)($,G),Q.else()}}VX.validatePropertyDeps=BX;function HX($,Z=$.schema){let{gen:Q,data:Y,keyword:W,it:G}=$,X=Q.name("valid");for(let J in Z){if((0,gN.alwaysValidSchema)(G,Z[J]))continue;Q.if((0,TZ.propertyInData)(Q,Y,J,G.opts.ownProperties),()=>{let B=$.subschema({keyword:W,schemaProp:J},X);$.mergeValidEvaluated(B,X)},()=>Q.var(X,!0)),$.ok(X)}}VX.validateSchemaDeps=HX;VX.default=hN});var qX=O((UX)=>{Object.defineProperty(UX,"__esModule",{value:!0});var DX=b(),pN=k(),cN={message:"property name must be valid",params:({params:$})=>DX._`{propertyName: ${$.propertyName}}`},dN={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:cN,code($){let{gen:Z,schema:Q,data:Y,it:W}=$;if((0,pN.alwaysValidSchema)(W,Q))return;let G=Z.name("valid");Z.forIn("key",Y,(X)=>{$.setParams({propertyName:X}),$.subschema({keyword:"propertyNames",data:X,dataTypes:["string"],propertyName:X,compositeRule:!0},G),Z.if((0,DX.not)(G),()=>{if($.error(!0),!W.allErrors)Z.break()})}),$.ok(G)}};UX.default=dN});var r8=O((AX)=>{Object.defineProperty(AX,"__esModule",{value:!0});var Q6=P0(),b0=b(),nN=s0(),Y6=k(),aN={message:"must NOT have additional properties",params:({params:$})=>b0._`{additionalProperty: ${$.additionalProperty}}`},rN={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:aN,code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,errsCount:G,it:X}=$;if(!G)throw Error("ajv implementation error");let{allErrors:J,opts:B}=X;if(X.props=!0,B.removeAdditional!=="all"&&(0,Y6.alwaysValidSchema)(X,Q))return;let K=(0,Q6.allSchemaProperties)(Y.properties),V=(0,Q6.allSchemaProperties)(Y.patternProperties);z(),$.ok(b0._`${G} === ${nN.default.errors}`);function z(){Z.forIn("key",W,(q)=>{if(!K.length&&!V.length)L(q);else Z.if(F(q),()=>L(q))})}function F(q){let A;if(K.length>8){let N=(0,Y6.schemaRefOrVal)(X,Y.properties,"properties");A=(0,Q6.isOwnProperty)(Z,N,q)}else if(K.length)A=(0,b0.or)(...K.map((N)=>b0._`${q} === ${N}`));else A=b0.nil;if(V.length)A=(0,b0.or)(A,...V.map((N)=>b0._`${(0,Q6.usePattern)($,N)}.test(${q})`));return(0,b0.not)(A)}function D(q){Z.code(b0._`delete ${W}[${q}]`)}function L(q){if(B.removeAdditional==="all"||B.removeAdditional&&Q===!1){D(q);return}if(Q===!1){if($.setParams({additionalProperty:q}),$.error(),!J)Z.break();return}if(typeof Q=="object"&&!(0,Y6.alwaysValidSchema)(X,Q)){let A=Z.name("valid");if(B.removeAdditional==="failing")U(q,A,!1),Z.if((0,b0.not)(A),()=>{$.reset(),D(q)});else if(U(q,A),!J)Z.if((0,b0.not)(A),()=>Z.break())}}function U(q,A,N){let j={keyword:"additionalProperties",dataProp:q,dataPropType:Y6.Type.Str};if(N===!1)Object.assign(j,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(j,A)}}};AX.default=rN});var jX=O((OX)=>{Object.defineProperty(OX,"__esModule",{value:!0});var oN=FZ(),NX=P0(),t8=k(),MX=r8(),sN={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,parentSchema:Y,data:W,it:G}=$;if(G.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)MX.default.code(new oN.KeywordCxt(G,MX.default,"additionalProperties"));let X=(0,NX.allSchemaProperties)(Q);for(let z of X)G.definedProperties.add(z);if(G.opts.unevaluated&&X.length&&G.props!==!0)G.props=t8.mergeEvaluated.props(Z,(0,t8.toHash)(X),G.props);let J=X.filter((z)=>!(0,t8.alwaysValidSchema)(G,Q[z]));if(J.length===0)return;let B=Z.name("valid");for(let z of J){if(K(z))V(z);else{if(Z.if((0,NX.propertyInData)(Z,W,z,G.opts.ownProperties)),V(z),!G.allErrors)Z.else().var(B,!0);Z.endIf()}$.it.definedProperties.add(z),$.ok(B)}function K(z){return G.opts.useDefaults&&!G.compositeRule&&Q[z].default!==void 0}function V(z){$.subschema({keyword:"properties",schemaProp:z,dataProp:z},B)}}};OX.default=sN});var RX=O((IX)=>{Object.defineProperty(IX,"__esModule",{value:!0});var PX=P0(),W6=b(),wX=k(),TX=k(),$M={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:Z,schema:Q,data:Y,parentSchema:W,it:G}=$,{opts:X}=G,J=(0,PX.allSchemaProperties)(Q),B=J.filter((U)=>(0,wX.alwaysValidSchema)(G,Q[U]));if(J.length===0||B.length===J.length&&(!G.opts.unevaluated||G.props===!0))return;let K=X.strictSchema&&!X.allowMatchingProperties&&W.properties,V=Z.name("valid");if(G.props!==!0&&!(G.props instanceof W6.Name))G.props=(0,TX.evaluatedPropsToName)(Z,G.props);let{props:z}=G;F();function F(){for(let U of J){if(K)D(U);if(G.allErrors)L(U);else Z.var(V,!0),L(U),Z.if(V)}}function D(U){for(let q in K)if(new RegExp(U).test(q))(0,wX.checkStrictMode)(G,`property ${q} matches pattern ${U} (use allowMatchingProperties)`)}function L(U){Z.forIn("key",Y,(q)=>{Z.if(W6._`${(0,PX.usePattern)($,U)}.test(${q})`,()=>{let A=B.includes(U);if(!A)$.subschema({keyword:"patternProperties",schemaProp:U,dataProp:q,dataPropType:TX.Type.Str},V);if(G.opts.unevaluated&&z!==!0)Z.assign(W6._`${z}[${q}]`,!0);else if(!A&&!G.allErrors)Z.if((0,W6.not)(V),()=>Z.break())})})}}};IX.default=$M});var SX=O((EX)=>{Object.defineProperty(EX,"__esModule",{value:!0});var QM=k(),YM={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code($){let{gen:Z,schema:Q,it:Y}=$;if((0,QM.alwaysValidSchema)(Y,Q)){$.fail();return}let W=Z.name("valid");$.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},W),$.failResult(W,()=>$.reset(),()=>$.error())},error:{message:"must NOT be valid"}};EX.default=YM});var yX=O((CX)=>{Object.defineProperty(CX,"__esModule",{value:!0});var GM=P0(),XM={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:GM.validateUnion,error:{message:"must match a schema in anyOf"}};CX.default=XM});var _X=O((bX)=>{Object.defineProperty(bX,"__esModule",{value:!0});var G6=b(),KM=k(),BM={message:"must match exactly one schema in oneOf",params:({params:$})=>G6._`{passingSchemas: ${$.passing}}`},HM={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:BM,code($){let{gen:Z,schema:Q,parentSchema:Y,it:W}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");if(W.opts.discriminator&&Y.discriminator)return;let G=Q,X=Z.let("valid",!1),J=Z.let("passing",null),B=Z.name("_valid");$.setParams({passing:J}),Z.block(K),$.result(X,()=>$.reset(),()=>$.error(!0));function K(){G.forEach((V,z)=>{let F;if((0,KM.alwaysValidSchema)(W,V))Z.var(B,!0);else F=$.subschema({keyword:"oneOf",schemaProp:z,compositeRule:!0},B);if(z>0)Z.if(G6._`${B} && ${X}`).assign(X,!1).assign(J,G6._`[${J}, ${z}]`).else();Z.if(B,()=>{if(Z.assign(X,!0),Z.assign(J,z),F)$.mergeEvaluated(F,G6.Name)})})}}};bX.default=HM});var kX=O((xX)=>{Object.defineProperty(xX,"__esModule",{value:!0});var zM=k(),FM={keyword:"allOf",schemaType:"array",code($){let{gen:Z,schema:Q,it:Y}=$;if(!Array.isArray(Q))throw Error("ajv implementation error");let W=Z.name("valid");Q.forEach((G,X)=>{if((0,zM.alwaysValidSchema)(Y,G))return;let J=$.subschema({keyword:"allOf",schemaProp:X},W);$.ok(W),$.mergeEvaluated(J)})}};xX.default=FM});var hX=O((gX)=>{Object.defineProperty(gX,"__esModule",{value:!0});var X6=b(),vX=k(),DM={message:({params:$})=>X6.str`must match "${$.ifClause}" schema`,params:({params:$})=>X6._`{failingKeyword: ${$.ifClause}}`},UM={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:DM,code($){let{gen:Z,parentSchema:Q,it:Y}=$;if(Q.then===void 0&&Q.else===void 0)(0,vX.checkStrictMode)(Y,'"if" without "then" and "else" is ignored');let W=fX(Y,"then"),G=fX(Y,"else");if(!W&&!G)return;let X=Z.let("valid",!0),J=Z.name("_valid");if(B(),$.reset(),W&&G){let V=Z.let("ifClause");$.setParams({ifClause:V}),Z.if(J,K("then",V),K("else",V))}else if(W)Z.if(J,K("then"));else Z.if((0,X6.not)(J),K("else"));$.pass(X,()=>$.error(!0));function B(){let V=$.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},J);$.mergeEvaluated(V)}function K(V,z){return()=>{let F=$.subschema({keyword:V},J);if(Z.assign(X,J),$.mergeValidEvaluated(F,X),z)Z.assign(z,X6._`${V}`);else $.setParams({ifClause:V})}}}};function fX($,Z){let Q=$.schema[Z];return Q!==void 0&&!(0,vX.alwaysValidSchema)($,Q)}gX.default=UM});var mX=O((uX)=>{Object.defineProperty(uX,"__esModule",{value:!0});var AM=k(),NM={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:$,parentSchema:Z,it:Q}){if(Z.if===void 0)(0,AM.checkStrictMode)(Q,`"${$}" without "if" is ignored`)}};uX.default=NM});var pX=O((lX)=>{Object.defineProperty(lX,"__esModule",{value:!0});var OM=i8(),jM=YX(),PM=n8(),wM=XX(),TM=KX(),IM=LX(),RM=qX(),EM=r8(),SM=jX(),CM=RX(),yM=SX(),bM=yX(),_M=_X(),xM=kX(),kM=hX(),fM=mX();function vM($=!1){let Z=[yM.default,bM.default,_M.default,xM.default,kM.default,fM.default,RM.default,EM.default,IM.default,SM.default,CM.default];if($)Z.push(jM.default,wM.default);else Z.push(OM.default,PM.default);return Z.push(TM.default),Z}lX.default=vM});var dX=O((cX)=>{Object.defineProperty(cX,"__esModule",{value:!0});var i=b(),hM={message:({schemaCode:$})=>i.str`must match format "${$}"`,params:({schemaCode:$})=>i._`{format: ${$}}`},uM={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:hM,code($,Z){let{gen:Q,data:Y,$data:W,schema:G,schemaCode:X,it:J}=$,{opts:B,errSchemaPath:K,schemaEnv:V,self:z}=J;if(!B.validateFormats)return;if(W)F();else D();function F(){let L=Q.scopeValue("formats",{ref:z.formats,code:B.code.formats}),U=Q.const("fDef",i._`${L}[${X}]`),q=Q.let("fType"),A=Q.let("format");Q.if(i._`typeof ${U} == "object" && !(${U} instanceof RegExp)`,()=>Q.assign(q,i._`${U}.type || "string"`).assign(A,i._`${U}.validate`),()=>Q.assign(q,i._`"string"`).assign(A,U)),$.fail$data((0,i.or)(N(),j()));function N(){if(B.strictSchema===!1)return i.nil;return i._`${X} && !${A}`}function j(){let P=V.$async?i._`(${U}.async ? await ${A}(${Y}) : ${A}(${Y}))`:i._`${A}(${Y})`,M=i._`(typeof ${A} == "function" ? ${P} : ${A}.test(${Y}))`;return i._`${A} && ${A} !== true && ${q} === ${Z} && !${M}`}}function D(){let L=z.formats[G];if(!L){N();return}if(L===!0)return;let[U,q,A]=j(L);if(U===Z)$.pass(P());function N(){if(B.strictSchema===!1){z.logger.warn(M());return}throw Error(M());function M(){return`unknown format "${G}" ignored in schema at path "${K}"`}}function j(M){let S=M instanceof RegExp?(0,i.regexpCode)(M):B.code.formats?i._`${B.code.formats}${(0,i.getProperty)(G)}`:void 0,g=Q.scopeValue("formats",{key:G,ref:M,code:S});if(typeof M=="object"&&!(M instanceof RegExp))return[M.type||"string",M.validate,i._`${g}.validate`];return["string",M,g]}function P(){if(typeof L=="object"&&!(L instanceof RegExp)&&L.async){if(!V.$async)throw Error("async format in sync schema");return i._`await ${A}(${Y})`}return typeof q=="function"?i._`${A}(${Y})`:i._`${A}.test(${Y})`}}}};cX.default=uM});var nX=O((iX)=>{Object.defineProperty(iX,"__esModule",{value:!0});var lM=dX(),pM=[lM.default];iX.default=pM});var tX=O((aX)=>{Object.defineProperty(aX,"__esModule",{value:!0});aX.contentVocabulary=aX.metadataVocabulary=void 0;aX.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];aX.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var eX=O((sX)=>{Object.defineProperty(sX,"__esModule",{value:!0});var iM=OG(),nM=aG(),aM=pX(),rM=nX(),oX=tX(),tM=[iM.default,nM.default,(0,aM.default)(),rM.default,oX.metadataVocabulary,oX.contentVocabulary];sX.default=tM});var YJ=O((ZJ)=>{Object.defineProperty(ZJ,"__esModule",{value:!0});ZJ.DiscrError=void 0;var $J;(function($){$.Tag="tag",$.Mapping="mapping"})($J||(ZJ.DiscrError=$J={}))});var XJ=O((GJ)=>{Object.defineProperty(GJ,"__esModule",{value:!0});var A$=b(),o8=YJ(),WJ=p5(),sM=LZ(),eM=k(),$O={message:({params:{discrError:$,tagName:Z}})=>$===o8.DiscrError.Tag?`tag "${Z}" must be string`:`value of tag "${Z}" must be in oneOf`,params:({params:{discrError:$,tag:Z,tagName:Q}})=>A$._`{error: ${$}, tag: ${Q}, tagValue: ${Z}}`},ZO={keyword:"discriminator",type:"object",schemaType:"object",error:$O,code($){let{gen:Z,data:Q,schema:Y,parentSchema:W,it:G}=$,{oneOf:X}=W;if(!G.opts.discriminator)throw Error("discriminator: requires discriminator option");let J=Y.propertyName;if(typeof J!="string")throw Error("discriminator: requires propertyName");if(Y.mapping)throw Error("discriminator: mapping is not supported");if(!X)throw Error("discriminator: requires oneOf keyword");let B=Z.let("valid",!1),K=Z.const("tag",A$._`${Q}${(0,A$.getProperty)(J)}`);Z.if(A$._`typeof ${K} == "string"`,()=>V(),()=>$.error(!1,{discrError:o8.DiscrError.Tag,tag:K,tagName:J})),$.ok(B);function V(){let D=F();Z.if(!1);for(let L in D)Z.elseIf(A$._`${K} === ${L}`),Z.assign(B,z(D[L]));Z.else(),$.error(!1,{discrError:o8.DiscrError.Mapping,tag:K,tagName:J}),Z.endIf()}function z(D){let L=Z.name("valid"),U=$.subschema({keyword:"oneOf",schemaProp:D},L);return $.mergeEvaluated(U,A$.Name),L}function F(){var D;let L={},U=A(W),q=!0;for(let P=0;P<X.length;P++){let M=X[P];if((M===null||M===void 0?void 0:M.$ref)&&!(0,eM.schemaHasRulesButRef)(M,G.self.RULES)){let g=M.$ref;if(M=WJ.resolveRef.call(G.self,G.schemaEnv.root,G.baseId,g),M instanceof WJ.SchemaEnv)M=M.schema;if(M===void 0)throw new sM.default(G.opts.uriResolver,G.baseId,g)}let S=(D=M===null||M===void 0?void 0:M.properties)===null||D===void 0?void 0:D[J];if(typeof S!="object")throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${J}"`);q=q&&(U||A(M)),N(S,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,M){if(P.const)j(P.const,M);else if(P.enum)for(let S of P.enum)j(S,M);else throw Error(`discriminator: "properties/${J}" must have "const" or "enum"`)}function j(P,M){if(typeof P!="string"||P in L)throw Error(`discriminator: "${J}" values must be unique strings`);L[P]=M}}}};GJ.default=ZO});var JJ=O((By,YO)=>{YO.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 e8=O((D0,s8)=>{Object.defineProperty(D0,"__esModule",{value:!0});D0.MissingRefError=D0.ValidationError=D0.CodeGen=D0.Name=D0.nil=D0.stringify=D0.str=D0._=D0.KeywordCxt=D0.Ajv=void 0;var WO=VG(),GO=eX(),XO=XJ(),KJ=JJ(),JO=["/properties"],J6="http://json-schema.org/draft-07/schema";class IZ extends WO.default{_addVocabularies(){if(super._addVocabularies(),GO.default.forEach(($)=>this.addVocabulary($)),this.opts.discriminator)this.addKeyword(XO.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let $=this.opts.$data?this.$dataMetaSchema(KJ,JO):KJ;this.addMetaSchema($,J6,!1),this.refs["http://json-schema.org/schema"]=J6}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(J6)?J6:void 0)}}D0.Ajv=IZ;s8.exports=D0=IZ;s8.exports.Ajv=IZ;Object.defineProperty(D0,"__esModule",{value:!0});D0.default=IZ;var KO=FZ();Object.defineProperty(D0,"KeywordCxt",{enumerable:!0,get:function(){return KO.KeywordCxt}});var N$=b();Object.defineProperty(D0,"_",{enumerable:!0,get:function(){return N$._}});Object.defineProperty(D0,"str",{enumerable:!0,get:function(){return N$.str}});Object.defineProperty(D0,"stringify",{enumerable:!0,get:function(){return N$.stringify}});Object.defineProperty(D0,"nil",{enumerable:!0,get:function(){return N$.nil}});Object.defineProperty(D0,"Name",{enumerable:!0,get:function(){return N$.Name}});Object.defineProperty(D0,"CodeGen",{enumerable:!0,get:function(){return N$.CodeGen}});var BO=m5();Object.defineProperty(D0,"ValidationError",{enumerable:!0,get:function(){return BO.default}});var HO=LZ();Object.defineProperty(D0,"MissingRefError",{enumerable:!0,get:function(){return HO.default}})});var AJ=O((UJ)=>{Object.defineProperty(UJ,"__esModule",{value:!0});UJ.formatNames=UJ.fastFormats=UJ.fullFormats=void 0;function h0($,Z){return{validate:$,compare:Z}}UJ.fullFormats={date:h0(zJ,Y9),time:h0(Z9(!0),W9),"date-time":h0(BJ(!0),LJ),"iso-time":h0(Z9(),FJ),"iso-date-time":h0(BJ(),DJ),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:AO,"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:NO,int32:{type:"number",validate:jO},int64:{type:"number",validate:PO},float:{type:"number",validate:VJ},double:{type:"number",validate:VJ},password:!0,binary:!0};UJ.fastFormats={...UJ.fullFormats,date:h0(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Y9),time:h0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,W9),"date-time":h0(/^\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,LJ),"iso-time":h0(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,FJ),"iso-date-time":h0(/^\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,DJ),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};UJ.formatNames=Object.keys(UJ.fullFormats);function FO($){return $%4===0&&($%100!==0||$%400===0)}var LO=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,DO=[0,31,28,31,30,31,30,31,31,30,31,30,31];function zJ($){let Z=LO.exec($);if(!Z)return!1;let Q=+Z[1],Y=+Z[2],W=+Z[3];return Y>=1&&Y<=12&&W>=1&&W<=(Y===2&&FO(Q)?29:DO[Y])}function Y9($,Z){if(!($&&Z))return;if($>Z)return 1;if($<Z)return-1;return 0}var $9=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Z9($){return function(Q){let Y=$9.exec(Q);if(!Y)return!1;let W=+Y[1],G=+Y[2],X=+Y[3],J=Y[4],B=Y[5]==="-"?-1:1,K=+(Y[6]||0),V=+(Y[7]||0);if(K>23||V>59||$&&!J)return!1;if(W<=23&&G<=59&&X<60)return!0;let z=G-V*B,F=W-K*B-(z<0?1:0);return(F===23||F===-1)&&(z===59||z===-1)&&X<61}}function W9($,Z){if(!($&&Z))return;let Q=new Date("2020-01-01T"+$).valueOf(),Y=new Date("2020-01-01T"+Z).valueOf();if(!(Q&&Y))return;return Q-Y}function FJ($,Z){if(!($&&Z))return;let Q=$9.exec($),Y=$9.exec(Z);if(!(Q&&Y))return;if($=Q[1]+Q[2]+Q[3],Z=Y[1]+Y[2]+Y[3],$>Z)return 1;if($<Z)return-1;return 0}var Q9=/t|\s/i;function BJ($){let Z=Z9($);return function(Y){let W=Y.split(Q9);return W.length===2&&zJ(W[0])&&Z(W[1])}}function LJ($,Z){if(!($&&Z))return;let Q=new Date($).valueOf(),Y=new Date(Z).valueOf();if(!(Q&&Y))return;return Q-Y}function DJ($,Z){if(!($&&Z))return;let[Q,Y]=$.split(Q9),[W,G]=Z.split(Q9),X=Y9(Q,W);if(X===void 0)return;return X||W9(Y,G)}var UO=/\/|:/,qO=/^(?:[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 AO($){return UO.test($)&&qO.test($)}var HJ=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function NO($){return HJ.lastIndex=0,HJ.test($)}var MO=-2147483648,OO=2147483647;function jO($){return Number.isInteger($)&&$<=OO&&$>=MO}function PO($){return Number.isInteger($)}function VJ(){return!0}var wO=/[^\\]\\Z/;function TO($){if(wO.test($))return!1;try{return new RegExp($),!0}catch(Z){return!1}}});var MJ=O((NJ)=>{Object.defineProperty(NJ,"__esModule",{value:!0});NJ.formatLimitDefinition=void 0;var RO=e8(),_0=b(),j1=_0.operators,K6={formatMaximum:{okStr:"<=",ok:j1.LTE,fail:j1.GT},formatMinimum:{okStr:">=",ok:j1.GTE,fail:j1.LT},formatExclusiveMaximum:{okStr:"<",ok:j1.LT,fail:j1.GTE},formatExclusiveMinimum:{okStr:">",ok:j1.GT,fail:j1.LTE}},EO={message:({keyword:$,schemaCode:Z})=>_0.str`should be ${K6[$].okStr} ${Z}`,params:({keyword:$,schemaCode:Z})=>_0._`{comparison: ${K6[$].okStr}, limit: ${Z}}`};NJ.formatLimitDefinition={keyword:Object.keys(K6),type:"string",schemaType:"string",$data:!0,error:EO,code($){let{gen:Z,data:Q,schemaCode:Y,keyword:W,it:G}=$,{opts:X,self:J}=G;if(!X.validateFormats)return;let B=new RO.KeywordCxt(G,J.RULES.all.format.definition,"format");if(B.$data)K();else V();function K(){let F=Z.scopeValue("formats",{ref:J.formats,code:X.code.formats}),D=Z.const("fmt",_0._`${F}[${B.schemaCode}]`);$.fail$data((0,_0.or)(_0._`typeof ${D} != "object"`,_0._`${D} instanceof RegExp`,_0._`typeof ${D}.compare != "function"`,z(D)))}function V(){let F=B.schema,D=J.formats[F];if(!D||D===!0)return;if(typeof D!="object"||D instanceof RegExp||typeof D.compare!="function")throw Error(`"${W}": format "${F}" does not define "compare" function`);let L=Z.scopeValue("formats",{key:F,ref:D,code:X.code.formats?_0._`${X.code.formats}${(0,_0.getProperty)(F)}`:void 0});$.fail$data(z(L))}function z(F){return _0._`${F}.compare(${Q}, ${Y}) ${K6[W].fail} 0`}},dependencies:["format"]};var SO=($)=>{return $.addKeyword(NJ.formatLimitDefinition),$};NJ.default=SO});var wJ=O((RZ,PJ)=>{Object.defineProperty(RZ,"__esModule",{value:!0});var M$=AJ(),yO=MJ(),J9=b(),OJ=new J9.Name("fullFormats"),bO=new J9.Name("fastFormats"),K9=($,Z={keywords:!0})=>{if(Array.isArray(Z))return jJ($,Z,M$.fullFormats,OJ),$;let[Q,Y]=Z.mode==="fast"?[M$.fastFormats,bO]:[M$.fullFormats,OJ],W=Z.formats||M$.formatNames;if(jJ($,W,Q,Y),Z.keywords)(0,yO.default)($);return $};K9.get=($,Z="full")=>{let Y=(Z==="fast"?M$.fastFormats:M$.fullFormats)[$];if(!Y)throw Error(`Unknown format "${$}"`);return Y};function jJ($,Z,Q,Y){var W,G;(W=(G=$.opts.code).formats)!==null&&W!==void 0||(G.formats=J9._`require("ajv-formats/dist/formats").${Y}`);for(let X of Z)$.addFormat(X,Q[X])}PJ.exports=RZ=K9;Object.defineProperty(RZ,"__esModule",{value:!0});RZ.default=K9});var _J=O((yy,bJ)=>{bJ.exports=yJ;yJ.sync=fO;var SJ=Y1("fs");function kO($,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 Y=0;Y<Q.length;Y++){var W=Q[Y].toLowerCase();if(W&&$.substr(-W.length).toLowerCase()===W)return!0}return!1}function CJ($,Z,Q){if(!$.isSymbolicLink()&&!$.isFile())return!1;return kO(Z,Q)}function yJ($,Z,Q){SJ.stat($,function(Y,W){Q(Y,Y?!1:CJ(W,$,Z))})}function fO($,Z){return CJ(SJ.statSync($),$,Z)}});var gJ=O((by,vJ)=>{vJ.exports=kJ;kJ.sync=vO;var xJ=Y1("fs");function kJ($,Z,Q){xJ.stat($,function(Y,W){Q(Y,Y?!1:fJ(W,Z))})}function vO($,Z){return fJ(xJ.statSync($),Z)}function fJ($,Z){return $.isFile()&&gO($,Z)}function gO($,Z){var{mode:Q,uid:Y,gid:W}=$,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),B=parseInt("010",8),K=parseInt("001",8),V=J|B,z=Q&K||Q&B&&W===X||Q&J&&Y===G||Q&V&&G===0;return z}});var uJ=O((xy,hJ)=>{var _y=Y1("fs"),H6;if(process.platform==="win32"||global.TESTING_WINDOWS)H6=_J();else H6=gJ();hJ.exports=z9;z9.sync=hO;function z9($,Z,Q){if(typeof Z==="function")Q=Z,Z={};if(!Q){if(typeof Promise!=="function")throw TypeError("callback not provided");return new Promise(function(Y,W){z9($,Z||{},function(G,X){if(G)W(G);else Y(X)})})}H6($,Z||{},function(Y,W){if(Y){if(Y.code==="EACCES"||Z&&Z.ignoreErrors)Y=null,W=!1}Q(Y,W)})}function hO($,Z){try{return H6.sync($,Z||{})}catch(Q){if(Z&&Z.ignoreErrors||Q.code==="EACCES")return!1;else throw Q}}});var nJ=O((ky,iJ)=>{var O$=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",mJ=Y1("path"),uO=O$?";":":",lJ=uJ(),pJ=($)=>Object.assign(Error(`not found: ${$}`),{code:"ENOENT"}),cJ=($,Z)=>{let Q=Z.colon||uO,Y=$.match(/\//)||O$&&$.match(/\\/)?[""]:[...O$?[process.cwd()]:[],...(Z.path||process.env.PATH||"").split(Q)],W=O$?Z.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",G=O$?W.split(Q):[""];if(O$){if($.indexOf(".")!==-1&&G[0]!=="")G.unshift("")}return{pathEnv:Y,pathExt:G,pathExtExe:W}},dJ=($,Z,Q)=>{if(typeof Z==="function")Q=Z,Z={};if(!Z)Z={};let{pathEnv:Y,pathExt:W,pathExtExe:G}=cJ($,Z),X=[],J=(K)=>new Promise((V,z)=>{if(K===Y.length)return Z.all&&X.length?V(X):z(pJ($));let F=Y[K],D=/^".*"$/.test(F)?F.slice(1,-1):F,L=mJ.join(D,$),U=!D&&/^\.[\\\/]/.test($)?$.slice(0,2)+L:L;V(B(U,K,0))}),B=(K,V,z)=>new Promise((F,D)=>{if(z===W.length)return F(J(V+1));let L=W[z];lJ(K+L,{pathExt:G},(U,q)=>{if(!U&&q)if(Z.all)X.push(K+L);else return F(K+L);return F(B(K,V,z+1))})});return Q?J(0).then((K)=>Q(null,K),Q):J(0)},mO=($,Z)=>{Z=Z||{};let{pathEnv:Q,pathExt:Y,pathExtExe:W}=cJ($,Z),G=[];for(let X=0;X<Q.length;X++){let J=Q[X],B=/^".*"$/.test(J)?J.slice(1,-1):J,K=mJ.join(B,$),V=!B&&/^\.[\\\/]/.test($)?$.slice(0,2)+K:K;for(let z=0;z<Y.length;z++){let F=V+Y[z];try{if(lJ.sync(F,{pathExt:W}))if(Z.all)G.push(F);else return F}catch(D){}}}if(Z.all&&G.length)return G;if(Z.nothrow)return null;throw pJ($)};iJ.exports=dJ;dJ.sync=mO});var rJ=O((fy,F9)=>{var aJ=($={})=>{let Z=$.env||process.env;if(($.platform||process.platform)!=="win32")return"PATH";return Object.keys(Z).reverse().find((Y)=>Y.toUpperCase()==="PATH")||"Path"};F9.exports=aJ;F9.exports.default=aJ});var eJ=O((vy,sJ)=>{var tJ=Y1("path"),lO=nJ(),pO=rJ();function oJ($,Z){let Q=$.options.env||process.env,Y=process.cwd(),W=$.options.cwd!=null,G=W&&process.chdir!==void 0&&!process.chdir.disabled;if(G)try{process.chdir($.options.cwd)}catch(J){}let X;try{X=lO.sync($.command,{path:Q[pO({env:Q})],pathExt:Z?tJ.delimiter:void 0})}catch(J){}finally{if(G)process.chdir(Y)}if(X)X=tJ.resolve(W?$.options.cwd:"",X);return X}function cO($){return oJ($)||oJ($,!0)}sJ.exports=cO});var $3=O((nO,D9)=>{var L9=/([()\][%!^"`<>&|;, *?])/g;function dO($){return $=$.replace(L9,"^$1"),$}function iO($,Z){if($=`${$}`,$=$.replace(/(?=(\\+?)?)\1"/g,"$1$1\\\""),$=$.replace(/(?=(\\+?)?)\1$/,"$1$1"),$=`"${$}"`,$=$.replace(L9,"^$1"),Z)$=$.replace(L9,"^$1");return $}nO.command=dO;nO.argument=iO});var Q3=O((gy,Z3)=>{Z3.exports=/^#!(.*)/});var W3=O((hy,Y3)=>{var tO=Q3();Y3.exports=($="")=>{let Z=$.match(tO);if(!Z)return null;let[Q,Y]=Z[0].replace(/#! ?/,"").split(" "),W=Q.split("/").pop();if(W==="env")return Y;return Y?`${W} ${Y}`:W}});var X3=O((uy,G3)=>{var U9=Y1("fs"),oO=W3();function sO($){let Q=Buffer.alloc(150),Y;try{Y=U9.openSync($,"r"),U9.readSync(Y,Q,0,150,0),U9.closeSync(Y)}catch(W){}return oO(Q.toString())}G3.exports=sO});var H3=O((my,B3)=>{var eO=Y1("path"),J3=eJ(),K3=$3(),$j=X3(),Zj=process.platform==="win32",Qj=/\.(?:com|exe)$/i,Yj=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function Wj($){$.file=J3($);let Z=$.file&&$j($.file);if(Z)return $.args.unshift($.file),$.command=Z,J3($);return $.file}function Gj($){if(!Zj)return $;let Z=Wj($),Q=!Qj.test(Z);if($.options.forceShell||Q){let Y=Yj.test(Z);$.command=eO.normalize($.command),$.command=K3.command($.command),$.args=$.args.map((G)=>K3.argument(G,Y));let W=[$.command].concat($.args).join(" ");$.args=["/d","/s","/c",`"${W}"`],$.command=process.env.comspec||"cmd.exe",$.options.windowsVerbatimArguments=!0}return $}function Xj($,Z,Q){if(Z&&!Array.isArray(Z))Q=Z,Z=null;Z=Z?Z.slice(0):[],Q=Object.assign({},Q);let Y={command:$,args:Z,options:Q,file:void 0,original:{command:$,args:Z}};return Q.shell?Y:Gj(Y)}B3.exports=Xj});var F3=O((ly,z3)=>{var q9=process.platform==="win32";function A9($,Z){return Object.assign(Error(`${Z} ${$.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${Z} ${$.command}`,path:$.command,spawnargs:$.args})}function Jj($,Z){if(!q9)return;let Q=$.emit;$.emit=function(Y,W){if(Y==="exit"){let G=V3(W,Z);if(G)return Q.call($,"error",G)}return Q.apply($,arguments)}}function V3($,Z){if(q9&&$===1&&!Z.file)return A9(Z.original,"spawn");return null}function Kj($,Z){if(q9&&$===1&&!Z.file)return A9(Z.original,"spawnSync");return null}z3.exports={hookChildProcess:Jj,verifyENOENT:V3,verifyENOENTSync:Kj,notFoundError:A9}});var U3=O((py,j$)=>{var L3=Y1("child_process"),N9=H3(),M9=F3();function D3($,Z,Q){let Y=N9($,Z,Q),W=L3.spawn(Y.command,Y.args,Y.options);return M9.hookChildProcess(W,Y),W}function Bj($,Z,Q){let Y=N9($,Z,Q),W=L3.spawnSync(Y.command,Y.args,Y.options);return W.error=W.error||M9.verifyENOENTSync(W.status,Y),W}j$.exports=D3;j$.exports.spawn=D3;j$.exports.sync=Bj;j$.exports._parse=N9;j$.exports._enoent=M9});import{readFile as jP}from"fs/promises";import{homedir as PP}from"os";import{join as wP,resolve as $K}from"path";class fZ{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 I1{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 Y=this.commands.get(Q.name);if(!Y)return{handled:!0,message:`Unknown command: /${Q.name}`};return await Y.run({...Z,args:Q.args})??{handled:!0}}}var BK=new Set(["rate_limit","overloaded","network"]);class c 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 BK.has(this.kind)}}var HK=[/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 vZ($){return HK.some((Z)=>Z.test($))}function VK($){let Z=$.get("retry-after-ms");if(Z){let Y=Number.parseFloat(Z);if(!Number.isNaN(Y))return Y}let Q=$.get("retry-after");if(Q){let Y=Number.parseFloat(Q);if(!Number.isNaN(Y))return Y*1000;let W=Date.parse(Q);if(!Number.isNaN(W))return W-Date.now()}return}function R$($,Z,Q){let Y={status:$,retryAfterMs:VK(Q)};if($===401||$===403)return new c("auth",Z,Y);if($===404)return new c("not_found",Z,Y);if($===429)return new c("rate_limit",Z,Y);if($===529||$===503)return new c("overloaded",Z,Y);if($>=500)return new c("api",Z,Y);if(vZ(Z))return new c("context_too_long",Z,Y);return new c("bad_request",Z,Y)}var c9={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 FK=[{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"]}],m0=new Map(FK.map(($)=>[$.id,$]));function n1($){return m0.get($)}function E$($){return $.api??n1($.provider)?.api??"openai-completions"}function P6($){return $.baseUrl??n1($.provider)?.baseUrl}function a1($){return n1($)?.env??[]}var LK=new Set(['"',"\\","/","b","f","n","r","t","u"]),DK={"\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"};function w6($){let Z="",Q=!1;for(let Y=0;Y<$.length;Y++){let W=$[Y];if(!Q){if(Z+=W,W==='"')Q=!0;continue}if(W==='"'){Z+=W,Q=!1;continue}if(W==="\\"){let X=$[Y+1];if(X===void 0){Z+="\\\\";continue}if(X==="u"&&/^[0-9a-fA-F]{4}$/.test($.slice(Y+2,Y+6))){Z+=$.slice(Y,Y+6),Y+=5;continue}if(X!=="u"&&LK.has(X)){Z+=`\\${X}`,Y+=1;continue}Z+="\\\\";continue}let G=W.codePointAt(0)??0;if(G<=31)Z+=DK[W]??`\\u${G.toString(16).padStart(4,"0")}`;else Z+=W}return Z}function d9($){try{return JSON.parse($)}catch(Z){let Q=w6($);if(Q!==$)return JSON.parse(Q);throw Z}}class i9{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 Y=this.pos,W=this.value();if(W!==void 0||this.consumedNull(Y))$[Q]=W??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 W=this.text.slice(this.pos+2,this.pos+6);if(/^[0-9a-fA-F]{4}$/.test(W))$+=String.fromCharCode(Number.parseInt(W,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 n9($){return new i9($).value()}function f0($){if(!$||$.trim()==="")return{};try{let Z=d9($);if(Z!==null&&typeof Z==="object"&&!Array.isArray(Z))return Z;return{}}catch{for(let Z of[$,w6($)])try{let Q=n9(Z);if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return{}}}var UK=60000;function T6(){let $=Error("Request aborted");return $.name="AbortError",$}function qK($,Z){return new Promise((Q,Y)=>{if(Z?.aborted){Y(T6());return}let W=()=>{clearTimeout(G),Y(T6())},G=setTimeout(()=>{Z?.removeEventListener("abort",W),Q()},Math.max(0,$));Z?.addEventListener("abort",W,{once:!0})})}function AK($,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 l0($,Z={}){let Q=Z.maxRetries??2,Y=Z.maxRetryDelayMs??UK,W=Q;for(;;)try{return await $()}catch(G){if(Z.signal?.aborted)throw T6();if(W<=0||!(G instanceof c)||!G.retryable)throw G;let X=Q-W;W--,await qK(AK(G,X,Y),Z.signal)}}function r9($){if(!$.event&&$.data.length===0)return null;let Z={event:$.event,data:$.data.join(`
|
|
11
|
+
`)};return $.event=null,$.data=[],Z}function a9($,Z){if($==="")return r9(Z);if($.startsWith(":"))return null;let Q=$.indexOf(":"),Y=Q===-1?$:$.slice(0,Q),W=Q===-1?"":$.slice(Q+1);if(W.startsWith(" "))W=W.slice(1);if(Y==="event")Z.event=W;else if(Y==="data")Z.data.push(W);return null}async function*p0($,Z){let Q=$.getReader(),Y=new TextDecoder,W={event:null,data:[]},G="",X=function*(){let J=G.search(/[\r\n]/);while(J!==-1){let B=G.slice(0,J),K=J+1;if(G[J]==="\r"&&G[K]===`
|
|
12
|
+
`)K+=1;G=G.slice(K);let V=a9(B,W);if(V)yield V;J=G.search(/[\r\n]/)}};try{while(!0){if(Z?.aborted)throw Error("Request was aborted");let{value:B,done:K}=await Q.read();if(K)break;G+=Y.decode(B,{stream:!0}),yield*X()}if(G+=Y.decode(),yield*X(),G.length>0){let B=a9(G,W);if(B)yield B}let J=r9(W);if(J)yield J}finally{Q.releaseLock()}}function c0($){return $.replace(/\/+$/,"")}function NK($){for(let Z of $){let Q=process.env[Z];if(Q)return Q}return}async function W1($,Z){let Q=await Z?.getCredentials?.();if(Q){if($.provider==="anthropic"&&Q.type==="oauth")throw new c("auth","Anthropic account-plan authentication is not supported");return Q}let Y=Z?.apiKey??NK(a1($.provider));if(!Y){let W=a1($.provider),G=W.length>0?`set ${W.join(" or ")} or run /login`:"run /login";throw new c("auth",`No credentials for provider "${$.provider}" (${G})`)}return{type:"apiKey",apiKey:Y}}function MK($){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 Y=`https://gateway.ai.cloudflare.com/v1/${Z}/${Q}`;if($.api==="anthropic-messages")return`${Y}/anthropic`;if($.api==="openai-responses")return`${Y}/openai`;return`${Y}/compat`}function OK(){let $=process.env.AZURE_OPENAI_BASE_URL,Z=process.env.AZURE_OPENAI_RESOURCE_NAME;if(!$&&!Z)return;let Q=c0($??`https://${Z}.openai.azure.com`);return Q.endsWith("/openai/v1")?Q:`${Q}/openai/v1`}function jK(){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 PK(){return`https://bedrock-runtime.${process.env.AWS_REGION??process.env.AWS_DEFAULT_REGION??"us-east-1"}.amazonaws.com/openai/v1`}function wK($,Z){if(Z?.baseUrl)return c0(Z.baseUrl);if($.provider.startsWith("cloudflare-")){let Q=MK($);if(Q)return c0(Q)}if($.provider==="azure-openai-responses"){let Q=OK();if(Q)return c0(Q)}if($.provider==="google-vertex"){let Q=jK();if(Q)return c0(Q)}if($.provider==="amazon-bedrock")return PK();return c0(P6($)??"")}function r1($,Z){let Q=c0($),Y=Z.startsWith("/")?Z:`/${Z}`;if(!Q)return Y;if(Y.startsWith("/v1/")&&Q.endsWith("/v1"))return`${Q}${Y.slice(3)}`;return`${Q}${Y}`}function G1($,Z){let Q=n1($.provider),Y={...Q?.headers,...$.headers};if(Z.type==="oauth")return{...Y,authorization:`Bearer ${Z.accessToken}`,...Z.headers};if(Q?.auth==="anthropic")return{...Y,"x-api-key":Z.apiKey};if(Q?.auth==="google")return{...Y,"x-goog-api-key":Z.apiKey};if(Q?.auth==="azure")return{...Y,"api-key":Z.apiKey};if(Q?.auth==="cloudflare")return{...Y,"cf-aig-authorization":`Bearer ${Z.apiKey}`};return{...Y,authorization:`Bearer ${Z.apiKey}`}}function X1($,Z,Q){if(Q?.baseUrl)return c0(Q.baseUrl);if(Z.type==="oauth"&&Z.baseUrl)return c0(Z.baseUrl);return wK($,Q)}function I6($,Z){return(Z.inputTokens*$.input+Z.outputTokens*$.output+Z.cacheReadTokens*$.cacheRead+Z.cacheWriteTokens*$.cacheWrite)/1e6}function S$(){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 gZ{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 hZ extends gZ{constructor(){super(($)=>$.type==="done"||$.type==="error",($)=>{if($.type==="done")return $.message;if($.type==="error")return $.error;throw Error("unexpected final event")})}}function TK($){return{role:"assistant",content:[],model:`${$.provider}/${$.id}`,usage:{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,costUsd:0},stopReason:"end",timestamp:Date.now()}}function d0($,Z){Z.usage.costUsd=I6($.pricing,Z.usage)}function K1($,Z,Q){let Y=new hZ,W=TK($);return(async()=>{try{if(await Q(Y,W),Z?.signal?.aborted)throw Error("Request was aborted");if(W.stopReason==="error")throw new c("api",W.errorMessage??"provider reported an error");Y.push({type:"done",message:W})}catch(G){W.stopReason=Z?.signal?.aborted?"aborted":"error",W.errorMessage=G instanceof Error?G.message:JSON.stringify(G),Y.push({type:"error",reason:W.stopReason,...G instanceof c?{errorKind:G.kind}:{},error:W})}finally{Y.end()}})(),Y}async function B1($,Z,Q,Y){let W=Y?.fetch??fetch,G;try{G=await W($,{method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",...Z},body:JSON.stringify(Q),...Y?.signal?{signal:Y.signal}:{}})}catch(X){if(Y?.signal?.aborted)throw X;let J=X instanceof Error?X.message:String(X);throw new c("network",J)}if(!G.ok){let X=await G.text();throw R$(G.status,X,G.headers)}if(!G.body)throw new c("api","response has no body");return G}var IK="2023-06-01",R6={type:"ephemeral"};function t9($){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 RK($){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 EK($,Z){let Q=[];for(let W=0;W<$.length;W++){let G=$[W];if(G.role==="user"){let X=t9(G.content);if(X.length>0)Q.push({role:"user",content:X})}else if(G.role==="assistant"){let X=RK(G.content);if(X.length>0)Q.push({role:"assistant",content:X})}else{let X=[];while(W<$.length){let J=$[W];if(!J||J.role!=="toolResult")break;X.push({type:"tool_result",tool_use_id:J.toolCallId,content:t9(J.content),is_error:J.isError}),W++}W--,Q.push({role:"user",content:X})}}let Y=Q[Q.length-1];if(Z&&Y&&Y.role==="user"){let W=Y.content,G=W[W.length-1];if(G)G.cache_control=R6}return Q}function SK($,Z,Q){if(!$.thinking||Z===void 0)return;if(Z==="off"){Q.thinking={type:"disabled"};return}if($.thinkingMode==="budget"){let Y={low:4096,medium:8192,high:16384};Q.thinking={type:"enabled",budget_tokens:Y[Z]??8192,display:"summarized"};return}Q.thinking={type:"adaptive",display:"summarized"},Q.output_config={effort:Z}}function CK($,Z,Q){let Y=$.provider==="anthropic",W={model:$.id,max_tokens:Q?.maxTokens??$.maxOutput,messages:EK(Z.messages,Y),stream:!0};if(Z.systemPrompt&&Z.systemPrompt.length>0){let G=Z.systemPrompt.reduce((X,J,B)=>J.dynamic?X:B,-1);W.system=Z.systemPrompt.map((X,J)=>({type:"text",text:X.text,...Y&&J===G?{cache_control:R6}:{}}))}if(Z.tools&&Z.tools.length>0)W.tools=Z.tools.map((G,X)=>({name:G.name,description:G.description,input_schema:G.inputSchema,...Y&&X===(Z.tools?.length??0)-1?{cache_control:R6}:{}}));if(Q?.temperature!==void 0)W.temperature=Q.temperature;return SK($,Q?.thinkingLevel,W),W}function yK($){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 o9($,Z,Q){return K1($,Q,async(Y,W)=>{let G=CK($,Z,Q),X=await l0(async()=>{let K=await W1($,Q),V=X1($,K,Q),z={"anthropic-version":IK,...G1($,K),...Q?.headers};return B1(r1(V,"/v1/messages"),z,G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=new Map,B=X.body;for await(let K of p0(B,Q?.signal)){if(K.event==="error")throw Error(K.data);if(!K.data)continue;let V=JSON.parse(K.data),z=V.type;if(z==="message_start"){let F=V.message?.usage;if(F)W.usage.inputTokens=F.input_tokens??0,W.usage.outputTokens=F.output_tokens??0,W.usage.cacheReadTokens=F.cache_read_input_tokens??0,W.usage.cacheWriteTokens=F.cache_creation_input_tokens??0,d0($,W)}else if(z==="content_block_start"){let{index:F,content_block:D}=V,L=W.content.length;J.set(F,{contentIndex:L,partialJson:""});let U=D.type;if(U==="text")W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:L,partial:W});else if(U==="thinking")W.content.push({type:"thinking",thinking:"",signature:""}),Y.push({type:"thinking_start",contentIndex:L,partial:W});else if(U==="redacted_thinking")W.content.push({type:"thinking",thinking:"[reasoning redacted]",signature:D.data??"",redacted:!0}),Y.push({type:"thinking_start",contentIndex:L,partial:W});else if(U==="tool_use")W.content.push({type:"toolCall",id:D.id,name:D.name,arguments:D.input??{}}),Y.push({type:"toolcall_start",contentIndex:L,partial:W});else J.delete(F)}else if(z==="content_block_delta"){let F=J.get(V.index);if(!F)continue;let D=W.content[F.contentIndex],L=V.delta,U=L.type;if(U==="text_delta"&&D?.type==="text")D.text+=L.text,Y.push({type:"text_delta",contentIndex:F.contentIndex,delta:L.text,partial:W});else if(U==="thinking_delta"&&D?.type==="thinking")D.thinking+=L.thinking,Y.push({type:"thinking_delta",contentIndex:F.contentIndex,delta:L.thinking,partial:W});else if(U==="input_json_delta"&&D?.type==="toolCall")F.partialJson+=L.partial_json,D.arguments=f0(F.partialJson),Y.push({type:"toolcall_delta",contentIndex:F.contentIndex,delta:L.partial_json,partial:W});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=W.content[F.contentIndex];if(D?.type==="text")Y.push({type:"text_end",contentIndex:F.contentIndex,content:D.text,partial:W});else if(D?.type==="thinking")Y.push({type:"thinking_end",contentIndex:F.contentIndex,content:D.thinking,partial:W});else if(D?.type==="toolCall")D.arguments=f0(F.partialJson),Y.push({type:"toolcall_end",contentIndex:F.contentIndex,toolCall:D,partial:W})}else if(z==="message_delta"){let F=V.delta;if(F?.stop_reason){let L=yK(F.stop_reason);if(W.stopReason=L.stopReason,L.errorMessage)W.errorMessage=L.errorMessage}let D=V.usage;if(D){if(D.input_tokens!=null)W.usage.inputTokens=D.input_tokens;if(D.output_tokens!=null)W.usage.outputTokens=D.output_tokens;if(D.cache_read_input_tokens!=null)W.usage.cacheReadTokens=D.cache_read_input_tokens;if(D.cache_creation_input_tokens!=null)W.usage.cacheWriteTokens=D.cache_creation_input_tokens;d0($,W)}}}})}var C$={id:"anthropic",stream:o9};function bK($){let Z=[],Q=new Map,Y=(W,G)=>{if(G.length===0)return;let X=Z[Z.length-1];if(X&&X.role===W)X.parts.push(...G);else Z.push({role:W,parts:G})};for(let W of $)if(W.role==="user")Y("user",W.content.map((G)=>G.type==="text"?{text:G.text}:{inlineData:{mimeType:G.mimeType,data:G.data}}));else if(W.role==="assistant"){let G=[];for(let X of W.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}:{}});Y("model",G)}else{let G=Q.get(W.toolCallId)??W.toolName,X=W.content.filter((B)=>B.type==="text").map((B)=>B.text).join(`
|
|
13
|
+
`),J=[{functionResponse:{name:G,response:W.isError?{error:X}:{output:X}}}];for(let B of W.content)if(B.type==="image")J.push({inlineData:{mimeType:B.mimeType,data:B.data}});Y("user",J)}return{contents:Z,toolNames:Q}}function _K($){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 xK($,Z,Q){let Y={contents:bK(Z.messages).contents};if(Z.systemPrompt&&Z.systemPrompt.length>0)Y.systemInstruction={parts:Z.systemPrompt.map((G)=>({text:G.text}))};if(Z.tools&&Z.tools.length>0)Y.tools=[{functionDeclarations:Z.tools.map((G)=>({name:G.name,description:G.description,parameters:G.inputSchema}))}];let W={maxOutputTokens:Q?.maxTokens??$.maxOutput};if(Q?.temperature!==void 0)W.temperature=Q.temperature;if($.thinking&&Q?.thinkingLevel)W.thinkingConfig={thinkingBudget:_K(Q.thinkingLevel),includeThoughts:Q.thinkingLevel!=="off"&&Q.thinkingLevel!=="none"};return Y.generationConfig=W,Y}function kK($,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 s9($,Z,Q){return K1($,Q,async(Y,W)=>{let G=xK($,Z,Q),X=await l0(async()=>{let U=await W1($,Q);if(U.type!=="apiKey")throw new c("auth",`${$.provider} requires API-key auth`);let q=X1($,U,Q).replace(/\/+$/,""),A=$.provider==="google-vertex"?`/models/${$.id}:streamGenerateContent?alt=sse`:`/models/${$.id}:streamGenerateContent?alt=sse`,N=`${q}${A}`;return B1(N,{...G1($,U),...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=-1,B=-1,K=0,V=!1,z,F=X.body,D=()=>{if(J!==-1){let U=W.content[J];if(U?.type==="text")Y.push({type:"text_end",contentIndex:J,content:U.text,partial:W});J=-1}if(B!==-1){let U=W.content[B];if(U?.type==="thinking")Y.push({type:"thinking_end",contentIndex:B,content:U.thinking,partial:W});B=-1}};for await(let U of p0(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;W.usage.inputTokens=(N.promptTokenCount??0)-P,W.usage.cacheReadTokens=P,W.usage.outputTokens=(N.candidatesTokenCount??0)+(N.thoughtsTokenCount??0),d0($,W)}if(!A)continue;let j=A.content?.parts??[];for(let P of j)if(typeof P.text==="string")if(P.thought===!0){if(B===-1)B=W.content.length,W.content.push({type:"thinking",thinking:""}),Y.push({type:"thinking_start",contentIndex:B,partial:W});let M=W.content[B];if(M?.type==="thinking"){if(M.thinking+=P.text,typeof P.thoughtSignature==="string")M.signature=P.thoughtSignature;Y.push({type:"thinking_delta",contentIndex:B,delta:P.text,partial:W})}}else{if(J===-1)J=W.content.length,W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:J,partial:W});let M=W.content[J];if(M?.type==="text")M.text+=P.text,Y.push({type:"text_delta",contentIndex:J,delta:P.text,partial:W})}else if(P.functionCall){V=!0;let M=P.functionCall,S=W.content.length,g={type:"toolCall",id:`call_${K++}_${M.name}`,name:M.name,arguments:M.args??{},...typeof P.thoughtSignature==="string"?{signature:P.thoughtSignature}:{}};W.content.push(g),Y.push({type:"toolcall_start",contentIndex:S,partial:W}),Y.push({type:"toolcall_end",contentIndex:S,toolCall:g,partial:W})}if(typeof A.finishReason==="string")z=A.finishReason}D();let L=kK(z??"STOP",V);if(W.stopReason=L.stopReason,L.errorMessage)W.errorMessage=L.errorMessage})}var y$={id:"google",stream:s9};async function E6($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||Z.availableModelIds===void 0)return;let Q=new Set(Z.availableModelIds);return $.currentModels.filter((Y)=>Y.provider==="github-copilot"&&Q.has(Y.id))}var ZQ="https://chatgpt.com/backend-api/codex",fK=64,vK=128000,gK={input:0,output:0,cacheRead:0,cacheWrite:0};function QQ($){let Z=$?.trim();return Z?Z.slice(0,fK):void 0}function e9($){return typeof $==="number"&&Number.isFinite($)&&$>0?$:void 0}function hK($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function $Q($){return typeof $==="string"&&$.length>0?$:void 0}function uK($,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 Y=Z.find((F)=>F.provider==="openai-codex"&&F.id===Q.slug),W=e9(Q.context_window)??e9(Q.max_context_window)??Y?.contextWindow;if(!W)return;let G=Array.isArray(Q.input_modalities)?Q.input_modalities.filter((F)=>typeof F==="string"):[],X=["text"];if(G.includes("image")||Y?.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?$Q(F.effort):void 0).filter((F)=>F!==void 0):[],B=Y?.thinkingLevels,K=J.length>0?J:B,V=$Q(Q.default_reasoning_level)??Y?.defaultThinkingLevel,z=V&&(!K||K.includes(V))?V:void 0;return{provider:"openai-codex",id:Q.slug,...typeof Q.display_name==="string"?{name:Q.display_name}:{},contextWindow:W,maxOutput:Y?.maxOutput??vK,modalities:X,...K?.length||z||Y?.thinking?{thinking:!0}:{},...K&&K.length>0?{thinkingLevels:K}:{},...z?{defaultThinkingLevel:z}:{},pricing:Y?.pricing??gK,priority:hK(Q.priority)??Number.MAX_SAFE_INTEGER}}async function YQ($){let Z=await $.getCredentials?.();if(!Z||Z.type!=="oauth"||!Z.accountId)return;let Q=new URL(`${ZQ}/models`);Q.searchParams.set("client_version",$.clientVersion??"0.0.0");let Y=await($.fetch??fetch)(Q,{headers:{accept:"application/json",authorization:`Bearer ${Z.accessToken}`,"chatgpt-account-id":Z.accountId,originator:"mu"},...$.signal?{signal:$.signal}:{}});if(!Y.ok)throw R$(Y.status,await Y.text(),Y.headers);let W=await Y.json();if(typeof W!=="object"||W===null||!Array.isArray(W.models))throw Error("Could not discover ChatGPT models: invalid catalog response");let G=W.models;if(G.length===0)return;let X=G.map((J)=>uK(J,$.currentModels)).filter((J)=>J!==void 0).sort((J,B)=>J.priority-B.priority).map(({priority:J,...B})=>B);if(X.length===0)throw Error("Could not discover ChatGPT models: catalog contained no compatible models");return X}function mK($,Z,Q){if(Q?.provider==="openai-codex"){if($.type!=="oauth"||!$.accountId)throw Error("OpenAI Codex requires a ChatGPT account credential");let W=(Z?.baseUrl??ZQ).replace(/\/+$/,""),G=QQ(Z?.sessionId);return{url:`${W}/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 Y=X1(Q,$,Z);return{url:r1(Y,"/responses"),headers:G1(Q,$)}}function lK($){let Z=[];for(let Q of $)if(Q.role==="user")Z.push({role:"user",content:Q.content.map((Y)=>Y.type==="text"?{type:"input_text",text:Y.text}:{type:"input_image",image_url:`data:${Y.mimeType};base64,${Y.data}`})});else if(Q.role==="assistant")for(let Y of Q.content)if(Y.type==="text"){if(Y.text.trim().length===0)continue;Z.push({role:"assistant",content:[{type:"output_text",text:Y.text}]})}else if(Y.type==="thinking"){if(!Y.signature)continue;try{let W=JSON.parse(Y.signature);Z.push({type:"reasoning",id:W.id,summary:[],...W.encrypted_content?{encrypted_content:W.encrypted_content}:{}})}catch{}}else Z.push({type:"function_call",call_id:Y.id,name:Y.name,arguments:JSON.stringify(Y.arguments??{})});else{let Y=Q.content.every((W)=>W.type==="text")?Q.content.map((W)=>W.text).join(`
|
|
14
|
+
`):Q.content.map((W)=>W.type==="text"?{type:"input_text",text:W.text}:{type:"input_image",image_url:`data:${W.mimeType};base64,${W.data}`});Z.push({type:"function_call_output",call_id:Q.toolCallId,output:Y})}return Z}function pK($,Z,Q){let Y=$.provider==="openai-codex",W={model:$.id,input:lK(Z.messages),stream:!0,store:!1};if(!Y)W.max_output_tokens=Q?.maxTokens??$.maxOutput;if(Z.systemPrompt&&Z.systemPrompt.length>0)W.instructions=Z.systemPrompt.map((G)=>G.text).join(`
|
|
15
|
+
|
|
16
|
+
`);else if(Y)W.instructions="You are a helpful assistant.";if(Z.tools&&Z.tools.length>0)W.tools=Z.tools.map((G)=>({type:"function",name:G.name,description:G.description,parameters:G.inputSchema,strict:Y?null:!1}));if(Y){W.text={verbosity:"low"},W.include=["reasoning.encrypted_content"],W.tool_choice="auto",W.parallel_tool_calls=!0;let G=QQ(Q?.sessionId);if(G)W.prompt_cache_key=G}if(Q?.temperature!==void 0)W.temperature=Q.temperature;if($.thinking&&Q?.thinkingLevel&&Q.thinkingLevel!=="off"){if(W.reasoning={effort:Q.thinkingLevel,summary:"auto"},!Y)W.include=["reasoning.encrypted_content"]}return W}function S6($,Z,Q){return K1($,Q,async(Y,W)=>{let G=pK($,Z,Q),X=await l0(async()=>{let V=await W1($,Q),{url:z,headers:F}=mK(V,Q,$);return B1(z,{...F,...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=new Map,B=!1,K=X.body;for await(let V of p0(K,Q?.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,q=W.content.length;if(U==="message")J.set(L,{contentIndex:q,kind:"text",partialJson:""}),W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:q,partial:W});else if(U==="reasoning")J.set(L,{contentIndex:q,kind:"reasoning",partialJson:""}),W.content.push({type:"thinking",thinking:"",signature:JSON.stringify({id:D.id})}),Y.push({type:"thinking_start",contentIndex:q,partial:W});else if(U==="function_call")B=!0,J.set(L,{contentIndex:q,kind:"function_call",partialJson:""}),W.content.push({type:"toolCall",id:D.call_id??D.id,name:D.name,arguments:{}}),Y.push({type:"toolcall_start",contentIndex:q,partial:W})}else if(F==="response.output_text.delta"){let D=J.get(z.output_index),L=D&&W.content[D.contentIndex];if(D&&L?.type==="text")L.text+=z.delta,Y.push({type:"text_delta",contentIndex:D.contentIndex,delta:z.delta,partial:W})}else if(F==="response.reasoning_summary_text.delta"){let D=J.get(z.output_index),L=D&&W.content[D.contentIndex];if(D&&L?.type==="thinking")L.thinking+=z.delta,Y.push({type:"thinking_delta",contentIndex:D.contentIndex,delta:z.delta,partial:W})}else if(F==="response.function_call_arguments.delta"){let D=J.get(z.output_index),L=D&&W.content[D.contentIndex];if(D&&L?.type==="toolCall")D.partialJson+=z.delta,L.arguments=f0(D.partialJson),Y.push({type:"toolcall_delta",contentIndex:D.contentIndex,delta:z.delta,partial:W})}else if(F==="response.output_item.done"){let D=J.get(z.output_index);if(!D)continue;let L=z.item,U=W.content[D.contentIndex];if(U?.type==="text")Y.push({type:"text_end",contentIndex:D.contentIndex,content:U.text,partial:W});else if(U?.type==="thinking")U.signature=JSON.stringify({id:L.id,...L.encrypted_content?{encrypted_content:L.encrypted_content}:{}}),Y.push({type:"thinking_end",contentIndex:D.contentIndex,content:U.thinking,partial:W});else if(U?.type==="toolCall"){let q=L.arguments??D.partialJson;U.arguments=f0(q),Y.push({type:"toolcall_end",contentIndex:D.contentIndex,toolCall:U,partial:W})}}else if(F==="response.completed"||F==="response.incomplete"||F==="response.failed"){let D=z.response,L=D.usage;if(L){let q=L.input_tokens_details?.cached_tokens??0;W.usage.inputTokens=(L.input_tokens??0)-q,W.usage.cacheReadTokens=q,W.usage.outputTokens=L.output_tokens??0,d0($,W)}if(F==="response.completed")W.stopReason=B?"toolUse":"end";else if(F==="response.incomplete"){let U=D.incomplete_details?.reason;W.stopReason=U==="max_output_tokens"?"length":"end"}else{let U=D.error;W.stopReason="error",W.errorMessage=U?.message??"response failed"}}else if(F==="error")throw Error(z.message??V.data)}})}var b$={id:"openai",stream:S6},t1={id:"openai-codex",stream:S6,discoverModels:YQ};function cK($){return $.content.filter((Q)=>Q.type==="text").map((Q)=>Q.text).join(`
|
|
17
|
+
`)||"(image result attached in the following user message)"}function dK($){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 iK($,Z){let Q=[];if(Z&&Z.length>0)Q.push({role:"system",content:Z.map((G)=>G.text).join(`
|
|
19
|
+
|
|
20
|
+
`)});let Y=[],W=()=>{let G=Y.filter((X)=>X.type==="image");if(G.length>0)Q.push({role:"user",content:[{type:"text",text:"Images returned by the preceding tool calls:"},...G.map((X)=>({type:"image_url",image_url:{url:`data:${X.mimeType};base64,${X.data}`}}))]});Y=[]};for(let G of $){if(G.role!=="toolResult")W();if(G.role==="user"){Q.push({role:"user",content:dK(G)});continue}if(G.role==="toolResult"){Q.push({role:"tool",tool_call_id:G.toolCallId,content:cK(G)}),Y.push(...G.content);continue}let X=G.content.filter((K)=>K.type==="text").map((K)=>K.text).join(`
|
|
21
21
|
`),J=G.content.filter((K)=>K.type==="thinking").map((K)=>K.thinking).join(`
|
|
22
|
-
`),B=G.content.filter((K)=>K.type==="toolCall").map((K)=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments??{})}}));if(!X&&!J&&B.length===0)continue;Q.push({role:"assistant",content:X||null,...J?{reasoning_content:J}:{},...B.length>0?{tool_calls:B}:{}})}return W(),Q}function C1($){return $!==void 0&&$!=="off"}function XB($,Z,Q){if(!Z.thinking||Q===void 0)return;if(Z.provider==="zai"){if($.thinking={type:C1(Q)?"enabled":"disabled"},C1(Q)&&Z.id==="glm-5.2")$.reasoning_effort=Q;return}if(Z.provider.startsWith("qwen-token-plan")){$.enable_thinking=C1(Q);return}if(Z.provider==="deepseek"||Z.provider==="moonshotai"){if($.thinking={type:C1(Q)?"enabled":"disabled"},C1(Q))$.reasoning_effort=Q;return}if(Z.provider==="openrouter"){if(C1(Q))$.reasoning={effort:Q};return}if(C1(Q))$.reasoning_effort=Q}function JB($,Z,Q){let Y={model:$.id,messages:GB(Z.messages,Z.systemPrompt),stream:!0,stream_options:{include_usage:!0},max_tokens:Q?.maxTokens??$.maxOutput};if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((W)=>({type:"function",function:{name:W.name,description:W.description,parameters:W.inputSchema}})),Y.tool_choice="auto";if(Q?.temperature!==void 0)Y.temperature=Q.temperature;if(Q?.sessionId)if($.provider==="openrouter")Y.user=Q.sessionId;else Y.prompt_cache_key=Q.sessionId;return XB(Y,$,Q?.thinkingLevel),Y}function dZ($){return typeof $==="number"&&Number.isFinite($)?$:0}function k6($,Z,Q){return H1($,Q,async(Y,W)=>{let G=JB($,Z,Q),X=await c0(async()=>{let z=await X1($,Q),F=K1($,z,Q);return V1(s1(F,"/chat/completions"),{...J1($,z),...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=-1,B=-1,K=new Map,V=X.body;for await(let z of d0(V,Q?.signal)){if(!z.data||z.data==="[DONE]")continue;let F=JSON.parse(z.data),L=F.usage;if(L){let N=L.prompt_tokens_details,j=dZ(N?.cached_tokens);W.usage.inputTokens=Math.max(0,dZ(L.prompt_tokens)-j),W.usage.cacheReadTokens=j,W.usage.outputTokens=dZ(L.completion_tokens),n0($,W)}let D=F.choices?.[0];if(!D)continue;let U=D.delta??{},q=typeof U.reasoning_content==="string"?U.reasoning_content:typeof U.reasoning==="string"?U.reasoning:"";if(q){if(B===-1)B=W.content.length,W.content.push({type:"thinking",thinking:""}),Y.push({type:"thinking_start",contentIndex:B,partial:W});let N=W.content[B];if(N?.type==="thinking")N.thinking+=q,Y.push({type:"thinking_delta",contentIndex:B,delta:q,partial:W})}if(typeof U.content==="string"&&U.content){if(J===-1)J=W.content.length,W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:J,partial:W});let N=W.content[J];if(N?.type==="text")N.text+=U.content,Y.push({type:"text_delta",contentIndex:J,delta:U.content,partial:W})}for(let N of U.tool_calls??[]){let j=dZ(N.index),P=K.get(j),O=N.function??{};if(!P){let g=W.content.length;P={contentIndex:g,partialJson:""},K.set(j,P),W.content.push({type:"toolCall",id:String(N.id??`call_${j}`),name:String(O.name??""),arguments:{}}),Y.push({type:"toolcall_start",contentIndex:g,partial:W})}let C=W.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=g0(P.partialJson),Y.push({type:"toolcall_delta",contentIndex:P.contentIndex,delta:O.arguments,partial:W})}let A=D.finish_reason;if(typeof A==="string")W.stopReason=A==="length"?"length":A==="tool_calls"||K.size>0?"toolUse":"end"}if(B!==-1){let z=W.content[B];if(z?.type==="thinking")Y.push({type:"thinking_end",contentIndex:B,content:z.thinking,partial:W})}if(J!==-1){let z=W.content[J];if(z?.type==="text")Y.push({type:"text_end",contentIndex:J,content:z.text,partial:W})}for(let z of K.values()){let F=W.content[z.contentIndex];if(F?.type!=="toolCall")continue;F.arguments=g0(z.partialJson),Y.push({type:"toolcall_end",contentIndex:z.contentIndex,toolCall:F,partial:W})}if(K.size>0&&W.stopReason==="end")W.stopReason="toolUse"})}var KB=new Map([[x$.id,x$],[f$.id,f$],[e1.id,e1],[k$.id,k$]]);function BB($){let Z=KB.get($);if(Z)return Z;return{id:$,stream:(Q,Y,W)=>{switch(b$(Q)){case"anthropic-messages":return x$.stream(Q,Y,W);case"google-generative-ai":case"google-vertex":return k$.stream(Q,Y,W);case"openai-responses":return f$.stream(Q,Y,W);default:return k6(Q,Y,W)}},...$==="github-copilot"?{discoverModels:_6}:{}}}var $$=new Map([...p0.keys()].map(($)=>[$,BB($)]));$$.set(e1.id,e1);function f6($){let Z=$$.get($);if(!Z)throw Error(`Unknown provider: ${$}`);return Z}function zQ($){$$.set($.id,$)}var HB="https://models.dev/api.json",VB=15000,Z$={input:0,output:0,cacheRead:0,cacheWrite:0},zB=[{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"]}],FB=[{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:Z$},{provider:"kimi-coding",id:"kimi-for-coding",name:"Kimi For Coding",api:"anthropic-messages",contextWindow:262144,maxOutput:65536,modalities:["text"],thinking:!0,pricing:Z$},{provider:"openrouter",id:"auto",name:"OpenRouter Auto",api:"openai-completions",contextWindow:2000000,maxOutput:30000,modalities:["text","image"],thinking:!0,pricing:Z$},{provider:"xai",id:"grok-4.3",name:"Grok 4.3",api:"openai-completions",contextWindow:256000,maxOutput:64000,modalities:["text","image"],thinking:!0,pricing:Z$},{provider:"zai",id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",contextWindow:202752,maxOutput:65536,modalities:["text"],thinking:!0,pricing:Z$},{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:Z$}],g6=[...s9.models,...FB],U0=[...g6],LQ=new Set;function N0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function z1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function v6($){return Array.isArray($)?$.filter((Z)=>typeof Z==="string"):[]}function DB($){if($.tool_call!==!0||$.status==="deprecated")return!1;let Z=N0($.limit)?$.limit:{};if((z1(Z.context)??0)<=0||(z1(Z.output)??0)<=0)return!1;if(!N0($.modalities))return!0;let Q=v6($.modalities.input),Y=v6($.modalities.output);return Q.includes("text")&&Y.includes("text")}function LB($){if(!Array.isArray($.reasoning_options))return"budget";return $.reasoning_options.some((Z)=>N0(Z)&&Z.type==="effort")?"adaptive":"budget"}function UB($){if(!Array.isArray($.reasoning_options))return;let Z=[];for(let Q of $.reasoning_options){if(!N0(Q)||Q.type!=="effort"||!Array.isArray(Q.values))continue;for(let Y of Q.values){if(typeof Y!=="string"||Y.length===0||Y==="default")continue;if(!Z.includes(Y))Z.push(Y)}}return Z.length>0?Z:void 0}function qB($,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=N0(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 b$({provider:$,id:"",contextWindow:1,maxOutput:1,modalities:["text"],pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}})}function UQ($,Z){if(typeof Z.id!=="string")return;let Q=qB($,Z),Y=Z.id,W=p0.get($)?.baseUrl;if($==="cloudflare-ai-gateway"){let G=Y.indexOf("/"),X=G===-1?"":Y.slice(0,G);if(X==="openai"||X==="anthropic")Y=Y.slice(G+1)}else if($==="fireworks"&&Q==="openai-completions")W="https://api.fireworks.ai/inference/v1";else if(($==="opencode"||$==="opencode-go")&&Q==="anthropic-messages")W=W?.replace(/\/v1$/,"");return{id:Y,api:Q,...W?{baseUrl:W}:{}}}function AB($,Z){if(!DB(Z)||typeof Z.id!=="string")return;let Q=N0(Z.limit)?Z.limit:{},Y=z1(Q.context),W=z1(Q.output);if(Y===void 0||W===void 0)return;let G=N0(Z.cost)?Z.cost:{},X=N0(Z.modalities)?v6(Z.modalities.input):["text"],J=["text"];if(X.includes("image"))J.push("image");let B=Z.reasoning===!0,K=B?UB(Z):void 0,V=UQ($,Z);if(!V)return;return{provider:$,id:V.id,...typeof Z.name==="string"?{name:Z.name}:{},api:V.api,...V.baseUrl?{baseUrl:V.baseUrl}:{},contextWindow:Y,maxOutput:W,modalities:J,...B?{thinking:!0}:{},...K?{thinkingLevels:K}:{},...B&&$==="anthropic"?{thinkingMode:LB(Z)}:{},pricing:{input:z1(G.input)??0,output:z1(G.output)??0,cacheRead:z1(G.cache_read)??0,cacheWrite:z1(G.cache_write)??0}}}async function NB($){let Z=await($.fetch??fetch)($.url??HB,{headers:{accept:"application/json"},signal:$.signal??AbortSignal.timeout(VB)});if(!Z.ok)throw Error(`Could not discover models: ${Z.status} ${Z.statusText}`.trim());let Q=await Z.json();if(!N0(Q))throw Error("Could not discover models: invalid catalog response");let Y=[],W=new Set;for(let G of zB){let X=Q[G.source];if(!N0(X)||!N0(X.models))continue;for(let J of G.providers){let B=0;for(let[K,V]of Object.entries(X.models)){if(!N0(V))continue;let z=typeof V.id==="string"?V:{...V,id:K},F=AB(J,z);if(F)Y.push(F),B++}if(B>0)W.add(J)}}if(Y.length===0)throw Error("Could not discover models: catalog contained no compatible models");return{models:Y,authoritativeProviders:W}}function FQ($){return $ instanceof Error?$.message:String($)}async function qQ($){let Z=[],Q=new Set,Y=[],W=U0;try{let B=await NB($);Z.push(...B.models);for(let V of B.authoritativeProviders)Q.add(V);let K=new Map(U0.map((V)=>[`${V.provider}/${V.id}`,V]));for(let V of B.models)K.set(`${V.provider}/${V.id}`,V);W=[...K.values()]}catch(B){Y.push(FQ(B))}let G=[],X=$.getCredentials;for(let B of $.providers??$$.values()){if(!B.discoverModels)continue;G.push(B.discoverModels({...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{},...X?{getCredentials:()=>X(B.id)}:{},...$.clientVersion?{clientVersion:$.clientVersion}:{},currentModels:W}).then((K)=>{if(K===void 0)return;if(K.length===0)throw Error(`Could not discover ${B.id} models: catalog returned no models`);return{models:K,authoritativeProviders:new Set([B.id])}}))}let J=await Promise.allSettled(G);for(let B of J){if(B.status==="rejected"){Y.push(FQ(B.reason));continue}if(!B.value)continue;for(let K of B.value.authoritativeProviders){for(let V=Z.length-1;V>=0;V--)if(Z[V]?.provider===K)Z.splice(V,1);Q.add(K)}Z.push(...B.value.models)}if(Q.size===0)throw Error(Y[0]??"Could not discover models: no discovery source was available");for(let B of Y)$.onWarning?.(B);return{models:Z,authoritativeProviders:Q}}async function AQ($={}){return(await qQ($)).models}async function NQ($={}){let Z=await qQ($);for(let Y of Z.authoritativeProviders)LQ.add(Y);let Q=U0.filter((Y)=>!Z.authoritativeProviders.has(Y.provider));for(let Y of g6){if(Z.authoritativeProviders.has(Y.provider))continue;if(!Q.some((W)=>W.provider===Y.provider&&W.id===Y.id))Q.push(Y)}for(let Y of Z.models){let W=Q.findIndex((G)=>G.provider===Y.provider&&G.id===Y.id);if(W===-1)Q.push(Y);else Q[W]=Y}return U0=Q,h6()}function h6(){return[...U0]}function OQ($){for(let Z of $){let Q=U0.findIndex((Y)=>Y.provider===Z.provider&&Y.id===Z.id);if(Q===-1)U0.push(Z);else U0[Q]=Z}}function iZ($){let Z=$.indexOf("/");if(Z!==-1){let Q=$.slice(0,Z),Y=$.slice(Z+1),W=U0.find((J)=>J.provider===Q&&J.id===Y);if(W)return W;if(LQ.has(Q))return;if(!p0.get(Q)||!Y)return;let X=UQ(Q,{id:Y});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 U0.find((Q)=>Q.id===$)}function MQ($){return`${$.provider}/${$.id}`}function u6($,Z=process.env){if($==="openai-codex")return!1;let Q=o1($);return Q.length===0||Q.some((Y)=>Boolean(Z[Y]))}var m6={"openai-codex":"gpt-5.6-sol",openai:"gpt-5.6-sol",anthropic:"claude-opus-5",google:"gemini-2.5-pro","github-copilot":"gpt-5.3-codex","kimi-coding":"kimi-for-coding",xai:"grok-4.3"};function jQ($){return m6[$]}function DQ($){for(let Z of $){let Q=U0.filter((G)=>G.provider===Z);if(Q.length===0)continue;let Y=m6[Z];return(Y?Q.find((G)=>G.id===Y):void 0)??Q[0]}return}function Q$($=process.env,Z){let Q=Z?[...Z]:[...new Set(U0.map((W)=>W.provider))].filter((W)=>u6(W,$)),Y=DQ(Q)??DQ(Object.keys(m6))??U0[0]??g6[0];if(!Y)throw Error("No models are available");return MQ(Y)}var OB=["off","low","medium","high"];function Y$($){if(!$.thinking)return["off"];if($.thinkingLevels&&$.thinkingLevels.length>0)return[...new Set($.thinkingLevels)];return[...OB]}function l6($){let Z=Y$($);if($.defaultThinkingLevel&&Z.includes($.defaultThinkingLevel))return $.defaultThinkingLevel;return Z[0]??"off"}function a0($,Z){let Q=Y$($);if(Z&&Q.includes(Z))return Z;return l6($)}function v$($){if($.stopReason!=="error")return!1;return lZ($.errorMessage??"")}var wQ=3.5;function aZ($){return Math.ceil($.length/wQ)}function l($){let Z=0;for(let Q of $)if(Q.role==="toolResult"||Q.role==="user"||Q.role==="custom")for(let Y of Q.content)Z+=Y.type==="text"?Y.text.length:1500;else for(let Y of Q.content)if(Y.type==="text")Z+=Y.text.length;else if(Y.type==="thinking")Z+=Y.thinking.length;else Z+=JSON.stringify(Y.arguments).length+Y.name.length;return Math.ceil(Z/wQ)}function h$($,Z,Q,Y){let W=l(Z),G=Q?Q.inputTokens+Q.cacheReadTokens+Q.cacheWriteTokens:0,X=Q&&Y!==void 0?Math.max(0,W-Y):0,J=Math.max(G+X,W),B=$.contextWindow;return{tokens:J,limit:B,percent:B>0?J/B:0}}var S1=0.85;function d6($,Z=S1){return $.percent>=Z}class h0 extends Error{usage;constructor($,Z){super($);this.usage=Z;this.name="CompactionError"}}var W$=20000;function MB($,Z){for(let Q=Math.min(Z,$.length-1);Q>=0;Q--)if($[Q]?.role==="user")return Q;return null}function IQ($,Z=W$){if($.length<=4&&l($)<=Z)return{keepFromIndex:$.length,keptTokens:0,isSplitTurn:!1,turnStartIndex:null};let Q=0,Y=$.length;while(Y>0&&Q<Z){let X=Y-1,J=l([$[X]]);if(Q>0&&Q+J>Z)break;Y=X,Q+=J}while(Y>0&&$[Y]?.role==="toolResult")Y--,Q+=l([$[Y]]);if(Y===0){if($.length===1)Y=$.length;else if(Y=$.findIndex((X,J)=>J>0&&X.role!=="toolResult"),Y<0)Y=$.length;Q=l($.slice(Y))}let W=Y<$.length?MB($,Y):null,G=W!==null&&W<Y;return{keepFromIndex:Y,keptTokens:Q,isSplitTurn:G,turnStartIndex:W}}var p6=`Summarize the conversation so far so that work can continue without the original transcript.
|
|
22
|
+
`),B=G.content.filter((K)=>K.type==="toolCall").map((K)=>({id:K.id,type:"function",function:{name:K.name,arguments:JSON.stringify(K.arguments??{})}}));if(!X&&!J&&B.length===0)continue;Q.push({role:"assistant",content:X||null,...J?{reasoning_content:J}:{},...B.length>0?{tool_calls:B}:{}})}return W(),Q}function R1($){return $!==void 0&&$!=="off"}function nK($,Z,Q){if(!Z.thinking||Q===void 0)return;if(Z.provider==="zai"){if($.thinking={type:R1(Q)?"enabled":"disabled"},R1(Q)&&Z.id==="glm-5.2")$.reasoning_effort=Q;return}if(Z.provider.startsWith("qwen-token-plan")){$.enable_thinking=R1(Q);return}if(Z.provider==="deepseek"||Z.provider==="moonshotai"){if($.thinking={type:R1(Q)?"enabled":"disabled"},R1(Q))$.reasoning_effort=Q;return}if(Z.provider==="openrouter"){if(R1(Q))$.reasoning={effort:Q};return}if(R1(Q))$.reasoning_effort=Q}function aK($,Z,Q){let Y={model:$.id,messages:iK(Z.messages,Z.systemPrompt),stream:!0,stream_options:{include_usage:!0},max_tokens:Q?.maxTokens??$.maxOutput};if(Z.tools&&Z.tools.length>0)Y.tools=Z.tools.map((W)=>({type:"function",function:{name:W.name,description:W.description,parameters:W.inputSchema}})),Y.tool_choice="auto";if(Q?.temperature!==void 0)Y.temperature=Q.temperature;if(Q?.sessionId)if($.provider==="openrouter")Y.user=Q.sessionId;else Y.prompt_cache_key=Q.sessionId;return nK(Y,$,Q?.thinkingLevel),Y}function uZ($){return typeof $==="number"&&Number.isFinite($)?$:0}function C6($,Z,Q){return K1($,Q,async(Y,W)=>{let G=aK($,Z,Q),X=await l0(async()=>{let z=await W1($,Q),F=X1($,z,Q);return B1(r1(F,"/chat/completions"),{...G1($,z),...Q?.headers},G,Q)},{...Q?.maxRetries!==void 0?{maxRetries:Q.maxRetries}:{},...Q?.signal?{signal:Q.signal}:{}});Y.push({type:"start",partial:W});let J=-1,B=-1,K=new Map,V=X.body;for await(let z of p0(V,Q?.signal)){if(!z.data||z.data==="[DONE]")continue;let F=JSON.parse(z.data),D=F.usage;if(D){let N=D.prompt_tokens_details,j=uZ(N?.cached_tokens);W.usage.inputTokens=Math.max(0,uZ(D.prompt_tokens)-j),W.usage.cacheReadTokens=j,W.usage.outputTokens=uZ(D.completion_tokens),d0($,W)}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(B===-1)B=W.content.length,W.content.push({type:"thinking",thinking:""}),Y.push({type:"thinking_start",contentIndex:B,partial:W});let N=W.content[B];if(N?.type==="thinking")N.thinking+=q,Y.push({type:"thinking_delta",contentIndex:B,delta:q,partial:W})}if(typeof U.content==="string"&&U.content){if(J===-1)J=W.content.length,W.content.push({type:"text",text:""}),Y.push({type:"text_start",contentIndex:J,partial:W});let N=W.content[J];if(N?.type==="text")N.text+=U.content,Y.push({type:"text_delta",contentIndex:J,delta:U.content,partial:W})}for(let N of U.tool_calls??[]){let j=uZ(N.index),P=K.get(j),M=N.function??{};if(!P){let g=W.content.length;P={contentIndex:g,partialJson:""},K.set(j,P),W.content.push({type:"toolCall",id:String(N.id??`call_${j}`),name:String(M.name??""),arguments:{}}),Y.push({type:"toolcall_start",contentIndex:g,partial:W})}let S=W.content[P.contentIndex];if(S?.type!=="toolCall")continue;if(typeof N.id==="string")S.id=N.id;if(typeof M.name==="string"&&M.name)S.name+=M.name;if(typeof M.arguments==="string")P.partialJson+=M.arguments,S.arguments=f0(P.partialJson),Y.push({type:"toolcall_delta",contentIndex:P.contentIndex,delta:M.arguments,partial:W})}let A=L.finish_reason;if(typeof A==="string")W.stopReason=A==="length"?"length":A==="tool_calls"||K.size>0?"toolUse":"end"}if(B!==-1){let z=W.content[B];if(z?.type==="thinking")Y.push({type:"thinking_end",contentIndex:B,content:z.thinking,partial:W})}if(J!==-1){let z=W.content[J];if(z?.type==="text")Y.push({type:"text_end",contentIndex:J,content:z.text,partial:W})}for(let z of K.values()){let F=W.content[z.contentIndex];if(F?.type!=="toolCall")continue;F.arguments=f0(z.partialJson),Y.push({type:"toolcall_end",contentIndex:z.contentIndex,toolCall:F,partial:W})}if(K.size>0&&W.stopReason==="end")W.stopReason="toolUse"})}var rK=new Map([[C$.id,C$],[b$.id,b$],[t1.id,t1],[y$.id,y$]]);function tK($){let Z=rK.get($);if(Z)return Z;return{id:$,stream:(Q,Y,W)=>{switch(E$(Q)){case"anthropic-messages":return C$.stream(Q,Y,W);case"google-generative-ai":case"google-vertex":return y$.stream(Q,Y,W);case"openai-responses":return b$.stream(Q,Y,W);default:return C6(Q,Y,W)}},...$==="github-copilot"?{discoverModels:E6}:{}}}var o1=new Map([...m0.keys()].map(($)=>[$,tK($)]));o1.set(t1.id,t1);function y6($){let Z=o1.get($);if(!Z)throw Error(`Unknown provider: ${$}`);return Z}function WQ($){o1.set($.id,$)}var oK="https://models.dev/api.json",sK=15000,s1={input:0,output:0,cacheRead:0,cacheWrite:0},eK=[{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"]}],$B=[{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:s1},{provider:"kimi-coding",id:"kimi-for-coding",name:"Kimi For Coding",api:"anthropic-messages",contextWindow:262144,maxOutput:65536,modalities:["text"],thinking:!0,pricing:s1},{provider:"openrouter",id:"auto",name:"OpenRouter Auto",api:"openai-completions",contextWindow:2000000,maxOutput:30000,modalities:["text","image"],thinking:!0,pricing:s1},{provider:"xai",id:"grok-4.3",name:"Grok 4.3",api:"openai-completions",contextWindow:256000,maxOutput:64000,modalities:["text","image"],thinking:!0,pricing:s1},{provider:"zai",id:"glm-5.1",name:"GLM-5.1",api:"openai-completions",contextWindow:202752,maxOutput:65536,modalities:["text"],thinking:!0,pricing:s1},{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:s1}],_6=[...c9.models,...$B],U0=[..._6],JQ=new Set;function N0($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function H1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function b6($){return Array.isArray($)?$.filter((Z)=>typeof Z==="string"):[]}function ZB($){if($.tool_call!==!0||$.status==="deprecated")return!1;let Z=N0($.limit)?$.limit:{};if((H1(Z.context)??0)<=0||(H1(Z.output)??0)<=0)return!1;if(!N0($.modalities))return!0;let Q=b6($.modalities.input),Y=b6($.modalities.output);return Q.includes("text")&&Y.includes("text")}function QB($){if(!Array.isArray($.reasoning_options))return"budget";return $.reasoning_options.some((Z)=>N0(Z)&&Z.type==="effort")?"adaptive":"budget"}function YB($){if(!Array.isArray($.reasoning_options))return;let Z=[];for(let Q of $.reasoning_options){if(!N0(Q)||Q.type!=="effort"||!Array.isArray(Q.values))continue;for(let Y of Q.values){if(typeof Y!=="string"||Y.length===0||Y==="default")continue;if(!Z.includes(Y))Z.push(Y)}}return Z.length>0?Z:void 0}function WB($,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=N0(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 E$({provider:$,id:"",contextWindow:1,maxOutput:1,modalities:["text"],pricing:{input:0,output:0,cacheRead:0,cacheWrite:0}})}function KQ($,Z){if(typeof Z.id!=="string")return;let Q=WB($,Z),Y=Z.id,W=m0.get($)?.baseUrl;if($==="cloudflare-ai-gateway"){let G=Y.indexOf("/"),X=G===-1?"":Y.slice(0,G);if(X==="openai"||X==="anthropic")Y=Y.slice(G+1)}else if($==="fireworks"&&Q==="openai-completions")W="https://api.fireworks.ai/inference/v1";else if(($==="opencode"||$==="opencode-go")&&Q==="anthropic-messages")W=W?.replace(/\/v1$/,"");return{id:Y,api:Q,...W?{baseUrl:W}:{}}}function GB($,Z){if(!ZB(Z)||typeof Z.id!=="string")return;let Q=N0(Z.limit)?Z.limit:{},Y=H1(Q.context),W=H1(Q.output);if(Y===void 0||W===void 0)return;let G=N0(Z.cost)?Z.cost:{},X=N0(Z.modalities)?b6(Z.modalities.input):["text"],J=["text"];if(X.includes("image"))J.push("image");let B=Z.reasoning===!0,K=B?YB(Z):void 0,V=KQ($,Z);if(!V)return;return{provider:$,id:V.id,...typeof Z.name==="string"?{name:Z.name}:{},api:V.api,...V.baseUrl?{baseUrl:V.baseUrl}:{},contextWindow:Y,maxOutput:W,modalities:J,...B?{thinking:!0}:{},...K?{thinkingLevels:K}:{},...B&&$==="anthropic"?{thinkingMode:QB(Z)}:{},pricing:{input:H1(G.input)??0,output:H1(G.output)??0,cacheRead:H1(G.cache_read)??0,cacheWrite:H1(G.cache_write)??0}}}async function XB($){let Z=await($.fetch??fetch)($.url??oK,{headers:{accept:"application/json"},signal:$.signal??AbortSignal.timeout(sK)});if(!Z.ok)throw Error(`Could not discover models: ${Z.status} ${Z.statusText}`.trim());let Q=await Z.json();if(!N0(Q))throw Error("Could not discover models: invalid catalog response");let Y=[],W=new Set;for(let G of eK){let X=Q[G.source];if(!N0(X)||!N0(X.models))continue;for(let J of G.providers){let B=0;for(let[K,V]of Object.entries(X.models)){if(!N0(V))continue;let z=typeof V.id==="string"?V:{...V,id:K},F=GB(J,z);if(F)Y.push(F),B++}if(B>0)W.add(J)}}if(Y.length===0)throw Error("Could not discover models: catalog contained no compatible models");return{models:Y,authoritativeProviders:W}}function GQ($){return $ instanceof Error?$.message:String($)}async function BQ($){let Z=[],Q=new Set,Y=[],W=U0;try{let B=await XB($);Z.push(...B.models);for(let V of B.authoritativeProviders)Q.add(V);let K=new Map(U0.map((V)=>[`${V.provider}/${V.id}`,V]));for(let V of B.models)K.set(`${V.provider}/${V.id}`,V);W=[...K.values()]}catch(B){Y.push(GQ(B))}let G=[],X=$.getCredentials;for(let B of $.providers??o1.values()){if(!B.discoverModels)continue;G.push(B.discoverModels({...$.fetch?{fetch:$.fetch}:{},...$.signal?{signal:$.signal}:{},...X?{getCredentials:()=>X(B.id)}:{},...$.clientVersion?{clientVersion:$.clientVersion}:{},currentModels:W}).then((K)=>{if(K===void 0)return;if(K.length===0)throw Error(`Could not discover ${B.id} models: catalog returned no models`);return{models:K,authoritativeProviders:new Set([B.id])}}))}let J=await Promise.allSettled(G);for(let B of J){if(B.status==="rejected"){Y.push(GQ(B.reason));continue}if(!B.value)continue;for(let K of B.value.authoritativeProviders){for(let V=Z.length-1;V>=0;V--)if(Z[V]?.provider===K)Z.splice(V,1);Q.add(K)}Z.push(...B.value.models)}if(Q.size===0)throw Error(Y[0]??"Could not discover models: no discovery source was available");for(let B of Y)$.onWarning?.(B);return{models:Z,authoritativeProviders:Q}}async function HQ($={}){return(await BQ($)).models}async function VQ($={}){let Z=await BQ($);for(let Y of Z.authoritativeProviders)JQ.add(Y);let Q=U0.filter((Y)=>!Z.authoritativeProviders.has(Y.provider));for(let Y of _6){if(Z.authoritativeProviders.has(Y.provider))continue;if(!Q.some((W)=>W.provider===Y.provider&&W.id===Y.id))Q.push(Y)}for(let Y of Z.models){let W=Q.findIndex((G)=>G.provider===Y.provider&&G.id===Y.id);if(W===-1)Q.push(Y);else Q[W]=Y}return U0=Q,x6()}function x6(){return[...U0]}function zQ($){for(let Z of $){let Q=U0.findIndex((Y)=>Y.provider===Z.provider&&Y.id===Z.id);if(Q===-1)U0.push(Z);else U0[Q]=Z}}function mZ($){let Z=$.indexOf("/");if(Z!==-1){let Q=$.slice(0,Z),Y=$.slice(Z+1),W=U0.find((J)=>J.provider===Q&&J.id===Y);if(W)return W;if(JQ.has(Q))return;if(!m0.get(Q)||!Y)return;let X=KQ(Q,{id:Y});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 U0.find((Q)=>Q.id===$)}function FQ($){return`${$.provider}/${$.id}`}function k6($,Z=process.env){if($==="openai-codex")return!1;let Q=a1($);return Q.length===0||Q.some((Y)=>Boolean(Z[Y]))}var f6={"openai-codex":"gpt-5.6-sol",openai:"gpt-5.6-sol",anthropic:"claude-opus-5",google:"gemini-2.5-pro","github-copilot":"gpt-5.3-codex","kimi-coding":"kimi-for-coding",xai:"grok-4.3"};function LQ($){return f6[$]}function XQ($){for(let Z of $){let Q=U0.filter((G)=>G.provider===Z);if(Q.length===0)continue;let Y=f6[Z];return(Y?Q.find((G)=>G.id===Y):void 0)??Q[0]}return}function e1($=process.env,Z){let Q=Z?[...Z]:[...new Set(U0.map((W)=>W.provider))].filter((W)=>k6(W,$)),Y=XQ(Q)??XQ(Object.keys(f6))??U0[0]??_6[0];if(!Y)throw Error("No models are available");return FQ(Y)}var JB=["off","low","medium","high"];function $$($){if(!$.thinking)return["off"];if($.thinkingLevels&&$.thinkingLevels.length>0)return[...new Set($.thinkingLevels)];return[...JB]}function v6($){let Z=$$($);if($.defaultThinkingLevel&&Z.includes($.defaultThinkingLevel))return $.defaultThinkingLevel;return Z[0]??"off"}function i0($,Z){let Q=$$($);if(Z&&Q.includes(Z))return Z;return v6($)}function _$($){if($.stopReason!=="error")return!1;return vZ($.errorMessage??"")}var UQ=3.5;function pZ($){return Math.ceil($.length/UQ)}function l($){let Z=0;for(let Q of $)if(Q.role==="toolResult"||Q.role==="user"||Q.role==="custom")for(let Y of Q.content)Z+=Y.type==="text"?Y.text.length:1500;else for(let Y of Q.content)if(Y.type==="text")Z+=Y.text.length;else if(Y.type==="thinking")Z+=Y.thinking.length;else Z+=JSON.stringify(Y.arguments).length+Y.name.length;return Math.ceil(Z/UQ)}function k$($,Z,Q,Y){let W=l(Z),G=Q?Q.inputTokens+Q.cacheReadTokens+Q.cacheWriteTokens:0,X=Q&&Y!==void 0?Math.max(0,W-Y):0,J=Math.max(G+X,W),B=$.contextWindow;return{tokens:J,limit:B,percent:B>0?J/B:0}}var E1=0.85;function u6($,Z=E1){return $.percent>=Z}class v0 extends Error{usage;constructor($,Z){super($);this.usage=Z;this.name="CompactionError"}}var Z$=20000;function KB($,Z){for(let Q=Math.min(Z,$.length-1);Q>=0;Q--)if($[Q]?.role==="user")return Q;return null}function qQ($,Z=Z$){if($.length<=4&&l($)<=Z)return{keepFromIndex:$.length,keptTokens:0,isSplitTurn:!1,turnStartIndex:null};let Q=0,Y=$.length;while(Y>0&&Q<Z){let X=Y-1,J=l([$[X]]);if(Q>0&&Q+J>Z)break;Y=X,Q+=J}while(Y>0&&$[Y]?.role==="toolResult")Y--,Q+=l([$[Y]]);if(Y===0){if($.length===1)Y=$.length;else if(Y=$.findIndex((X,J)=>J>0&&X.role!=="toolResult"),Y<0)Y=$.length;Q=l($.slice(Y))}let W=Y<$.length?KB($,Y):null,G=W!==null&&W<Y;return{keepFromIndex:Y,keptTokens:Q,isSplitTurn:G,turnStartIndex:W}}var g6=`Summarize the conversation so far so that work can continue without the original transcript.
|
|
23
23
|
|
|
24
24
|
Preserve, in this order:
|
|
25
25
|
1. What the user asked for \u2014 the goal, in their terms, including any constraints they stated.
|
|
@@ -28,73 +28,73 @@ Preserve, in this order:
|
|
|
28
28
|
4. Concrete facts discovered that would be expensive to rediscover (file locations, API shapes, error messages, command invocations that work).
|
|
29
29
|
5. Anything the user corrected you on.
|
|
30
30
|
|
|
31
|
-
Be specific and factual. Do not include pleasantries or narration. This summary replaces the transcript, so anything you omit is lost.`,
|
|
32
|
-
[... ${$.length-Z} characters omitted]`}function
|
|
33
|
-
`)}function
|
|
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=
|
|
35
|
-
${X}`);continue}if(Q.role==="toolResult"){let X=
|
|
31
|
+
Be specific and factual. Do not include pleasantries or narration. This summary replaces the transcript, so anything you omit is lost.`,BB="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.",HB=2000,VB=4000,zB=3;function DQ($,Z){if($.length<=Z)return $;return`${$.slice(0,Z)}
|
|
32
|
+
[... ${$.length-Z} characters omitted]`}function x$($){return $.content.filter((Z)=>Z.type==="text").map((Z)=>Z.text).join(`
|
|
33
|
+
`)}function AQ($){let Z=[];for(let Q of $){if(Q.role==="user"){let X=x$(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=x$(Q);if(X)Z.push(`[Injected context: ${Q.customType}]
|
|
35
|
+
${X}`);continue}if(Q.role==="toolResult"){let X=DQ(x$(Q),HB);Z.push(`[Tool result: ${Q.toolName}${Q.isError?" (error)":""}]
|
|
36
36
|
${X||"(non-text output omitted)"}`);continue}let Y=Q.content.filter((X)=>X.type==="thinking").map((X)=>X.thinking).join(`
|
|
37
|
-
`),W=
|
|
37
|
+
`),W=x$(Q),G=Q.content.filter((X)=>X.type==="toolCall").map((X)=>`${X.name}(${DQ(JSON.stringify(X.arguments),VB)})`).join(`
|
|
38
38
|
`);if(Y)Z.push(`[Assistant thinking]
|
|
39
39
|
${Y}`);if(W)Z.push(`[Assistant]
|
|
40
40
|
${W}`);if(G)Z.push(`[Assistant tool calls]
|
|
41
41
|
${G}`)}return Z.join(`
|
|
42
42
|
|
|
43
|
-
`)}async function
|
|
43
|
+
`)}async function cZ($,Z){let Q=Z.keepRecentTokens??Math.min(Z$,Math.max(2,Math.floor(Z.model.contextWindow*0.2))),Y=qQ($,Q),{keepFromIndex:W}=Y,G=$.slice(0,W),X=$.slice(W);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)lZ(J);let B=G.findIndex((U)=>U.role==="custom"&&U.customType==="compaction-summary"),K=B===-1?void 0:x$(G[B]),V=G.filter((U,q)=>q!==B),z,F=0;for(;;){let U=[g6,K?"Update the previous summary with the newly summarized conversation.":"",Y.isSplitTurn?BB:"",Z.customInstructions?`Additional focus from the user: ${Z.customInstructions}`:""].filter(Boolean).join(`
|
|
44
44
|
|
|
45
45
|
`),q=[`<conversation>
|
|
46
|
-
${
|
|
46
|
+
${AQ(V)}
|
|
47
47
|
</conversation>`,...K?[`<previous-summary>
|
|
48
48
|
${K}
|
|
49
49
|
</previous-summary>`]:[],U,"Produce the summary now."].join(`
|
|
50
50
|
|
|
51
51
|
`),A={systemPrompt:[{text:`You are a context summarization assistant. Do not continue the conversation. Output only the requested handoff summary.
|
|
52
52
|
|
|
53
|
-
${
|
|
53
|
+
${g6}`}],messages:[{role:"user",content:[{type:"text",text:q}],timestamp:Date.now()}]};if(z=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(),!_$(z)||V.length<=1||F+1>=zB)break;V=V.slice(Math.max(1,Math.floor(V.length/2))),F++}if(z.stopReason!=="end")throw new v0(`Compaction failed: ${z.errorMessage??`incomplete response (${z.stopReason})`}`,z.usage);let D=z.content.filter((U)=>U.type==="text").map((U)=>U.text).join("").trim();if(D.length===0)throw new v0("Compaction failed: the provider returned no usable summary",z.usage);let L={summary:D,...J!==void 0?{carryover:J}:{},keptMessages:X,tokensFreed:0,usage:z.usage};return L.tokensFreed=Math.max(0,l($)-l(f$(L))),L}function f$($){if($.summary.length===0)return $.keptMessages;return[v$($.summary,$.carryover),...$.keptMessages]}function v$($,Z,Q=Date.now()){let Y=Z===void 0?"":`
|
|
54
54
|
|
|
55
55
|
Carried forward:
|
|
56
|
-
${
|
|
56
|
+
${NQ(Z)}`;return{role:"custom",customType:"compaction-summary",content:[{type:"text",text:`Summary of the earlier conversation:
|
|
57
57
|
|
|
58
|
-
${$}${Y}`}],display:!1,timestamp:Q}}function
|
|
58
|
+
${$}${Y}`}],display:!1,timestamp:Q}}function NQ($){if(typeof $==="string")return $;return lZ($),JSON.stringify(h6($),null,2)}function lZ($,Z=new Set){if($===null||typeof $==="string"||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return;if(typeof $!=="object")throw new v0("Compaction failed: carryover must be JSON-serializable");let Q=Object.getPrototypeOf($);if(!Array.isArray($)&&Q!==Object.prototype&&Q!==null)throw new v0("Compaction failed: carryover must contain only plain objects");if(Z.has($))throw new v0("Compaction failed: carryover must not contain cycles");if(Z.add($),Array.isArray($))for(let Y of $)lZ(Y,Z);else for(let Y of Object.values($))lZ(Y,Z);Z.delete($)}function h6($){if(Array.isArray($))return $.map(h6);if($&&typeof $==="object")return Object.fromEntries(Object.entries($).sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0).map(([Z,Q])=>[Z,h6(Q)]));return $}class m6{tools=new Map;commands=new I1;providers=new Map;models=new Map;renderers=new Map;logs=[];extensions=[];eventHandlers=new Map;toolCallHooks=[];toolResultHooks=[];contextHooks=[];inputHooks=[];async register($){let Z={on:(Q,Y)=>{let W=this.eventHandlers.get(Q)??[];W.push(Y),this.eventHandlers.set(Q,W)},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 Y of Q)this.models.set(`${Y.provider}/${Y.id}`,Y)},registerRenderer:(Q,Y)=>void this.renderers.set(Q,Y),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)??[])try{Promise.resolve(Z($)).catch((Q)=>{this.logs.push(`[extension observer] ${$.type}: ${Q instanceof Error?Q.message:String(Q)}`)})}catch(Q){this.logs.push(`[extension observer] ${$.type}: ${Q instanceof Error?Q.message:String(Q)}`)}}emitLifecycle($){for(let Z of this.eventHandlers.get($.type)??[])try{Promise.resolve(Z($)).catch((Q)=>{this.logs.push(`[extension observer] ${$.type}: ${Q instanceof Error?Q.message:String(Q)}`)})}catch(Q){this.logs.push(`[extension observer] ${$.type}: ${Q instanceof Error?Q.message:String(Q)}`)}}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 Y=await Q({...$,args:Z});if(Y?.block)return Y;if(Y?.args)Z=Y.args}return Z===$.args?void 0:{args:Z}}async runToolResultHooks($){let Z=$.result.content,Q=$.isError,Y=!1;for(let W of this.toolResultHooks){let G=await W({...$,result:{...$.result,content:Z},isError:Q});if(!G)continue;if(G.content)Z=G.content,Y=!0;if(G.isError!==void 0)Q=G.isError,Y=!0}return Y?{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 Y=await Q(Z);if(Y?.consume)return{consume:!0,...Y.text!==void 0?{text:Y.text}:{}};if(Y?.text!==void 0)Z=Y.text}return Z===$?void 0:{text:Z}}get hasContextHooks(){return this.contextHooks.length>0}}function MQ($){let Z=$.customType,Q=[];for(let Y of $.content)Q.push(Y.type==="text"?{type:"text",text:`<${Z}>
|
|
59
59
|
${Y.text}
|
|
60
|
-
</${Z}>`}:Y);return{role:"user",content:Q,timestamp:$.timestamp}}function n6($){return $.map((Z)=>Z.role==="custom"?EQ(Z):Z)}function G$($){return{role:"user",content:[{type:"text",text:$}],timestamp:Date.now()}}function l$($,Z,Q=!1){return{role:"custom",customType:$,content:[{type:"text",text:Z}],display:Q,timestamp:Date.now()}}function S($){return{content:[{type:"text",text:$}],isError:!0}}function CQ($){return{content:[{type:"text",text:$}]}}function tZ($,Z){if($.executionMode==="sequential")return!1;if(!$.isConcurrencySafe)return!1;try{return $.isConcurrencySafe(Z)===!0}catch{return!1}}var TB=10,SQ=3;function RB($){return $.content.filter((Z)=>Z.type==="toolCall")}function EB($){return`${$.name}:${JSON.stringify($.arguments)}`}async function a6($,Z,Q,Y,W){let G=W??new AbortController().signal,X=[...$],J={...Z,messages:[...Z.messages,...$]},B=Q,K=0,V=[],z=async(L)=>{return await Y({type:"agent_end",messages:X,reason:L}),{messages:X,reason:L}};await Y({type:"agent_start"});for(let L of $)await Y({type:"message_start",message:L}),await Y({type:"message_end",message:L});let F=await B.getSteeringMessages?.()??[];for(;;){let L=!0;while(L||F.length>0){if(G.aborted)return z("aborted");if(B.maxTurns!==void 0&&K>=B.maxTurns)return z("maxTurns");K++,await Y({type:"turn_start"});for(let O of F)await Y({type:"message_start",message:O}),await Y({type:"message_end",message:O}),J.messages.push(O),X.push(O);if(F=[],B.prepareContext){let O=await B.prepareContext(J.messages),C=Array.isArray(O)?{messages:O}:O;if(J={...J,messages:C.messages},C.stop)return z("budget")}let U=await yB(J,B,Y,G),q=U.message;if(J.messages.push(q),X.push(q),q.stopReason==="error"||q.stopReason==="aborted"){if(await Y({type:"turn_end",message:q,toolResults:[]}),q.stopReason==="error"&&await B.recoverFromError?.(q)===!0){L=!0;continue}return z(q.stopReason==="aborted"?"aborted":"error")}let A=RB(q),N=[];if(L=!1,A.length>0){let O=q.stopReason==="length"?await bB(A,Y):await fB(A,q,J,B,Y,G);N.push(...O.results),F.push(...O.steering),L=!O.terminate;for(let g of O.results)J.messages.push(g),X.push(g);let C=CB(A,V);if(C)J.messages.push(C),X.push(C),await Y({type:"message_start",message:C}),await Y({type:"message_end",message:C})}await Y({type:"turn_end",message:q,toolResults:N});let j={message:q,toolResults:N,context:J,requestMessages:U.messages,newMessages:X},P=await B.prepareNextTurn?.(j);if(P){if(P.context)J=P.context;B={...B,...P.model?{model:P.model}:{},...P.thinkingLevel!==void 0?{thinkingLevel:P.thinkingLevel}:{}}}if(await B.shouldStopAfterTurn?.(j))return z("done");F.push(...await B.getSteeringMessages?.()??[])}let D=await B.getFollowUpMessages?.()??[];if(D.length>0){F=D;continue}break}return z("done")}function CB($,Z){for(let Y of $){let W=EB(Y);if(Z[Z.length-1]===W)Z.push(W);else Z.length=0,Z.push(W)}if(Z.length<SQ)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 ${SQ} 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 SB($){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 yB($,Z,Q,Y){let W=Z.transformContext?await Z.transformContext($.messages):$.messages,G={...$.systemPrompt?{systemPrompt:$.systemPrompt}:{},messages:n6(W),...$.tools?{tools:$.tools.map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema}))}:{}},X=Z.provider.stream(Z.model,G,{...Z.streamOpts,...Z.thinkingLevel!==void 0?{thinkingLevel:Z.thinkingLevel}:{},signal:Y}),J=!1;for await(let K of X){if(K.type==="start"){J=!0,await Q({type:"message_start",message:{...K.partial}});continue}if(K.type==="done"||K.type==="error")break;let V=SB(K);if(V)await Q({type:"message_update",message:{...K.partial},delta:V})}let B=await X.result();if(!J)await Q({type:"message_start",message:{...B}});return await Q({type:"message_end",message:B}),{message:B,messages:W}}function r6($,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 oZ($,Z){await Z({type:"tool_execution_end",toolCallId:$.toolCallId,result:$}),await Z({type:"message_start",message:$}),await Z({type:"message_end",message:$})}async function bB($,Z){let Q=[];for(let Y of $){await Z({type:"tool_execution_start",toolCallId:Y.id,toolName:Y.name,args:Y.arguments});let W=r6(Y,S(`Tool call "${Y.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 oZ(W,Z),Q.push(W)}return{results:Q,terminate:!1,steering:[]}}async function _B($,Z){let Q=[];for(let Y of $){await Z({type:"tool_execution_start",toolCallId:Y.id,toolName:Y.name,args:Y.arguments});let W=r6(Y,S(`Tool call "${Y.name}" was not executed because a steering message interrupted the remaining tool calls. Re-evaluate the plan before re-issuing it.`),!0);await oZ(W,Z),Q.push(W)}return Q}async function xB($,Z,Q,Y,W){let G=Q.tools?.find((X)=>X.name===$.name);if(!G)return{kind:"immediate",result:S(`Tool ${$.name} not found`)};try{let X=$.arguments,J=await Y.beforeToolCall?.({assistantMessage:Z,toolCall:$,args:X,context:Q},W);if(W.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 kB($,Z,Q,Y,W,G){let X,J,B=Promise.resolve();try{X=await $.tool.execute($.call.id,$.args,G,(K)=>{B=B.then(()=>W({type:"tool_execution_update",toolCallId:$.call.id,partial:K}))}),await B,J=X.isError===!0}catch(K){X=S(K instanceof Error?K.message:String(K)),J=!0}if(Y.afterToolCall)try{let K=await Y.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=S(K instanceof Error?K.message:String(K)),J=!0}return{result:X,isError:J}}async function fB($,Z,Q,Y,W,G){let X=[],J=[],B=[],K=async(z)=>{await W({type:"tool_execution_start",toolCallId:z.id,toolName:z.name,args:z.arguments});let F=await xB(z,Z,Q,Y,G),L=F.kind==="immediate"?{result:F.result,isError:!0}:await kB(F.prepared,Z,Q,Y,W,G);return J.push(L.result.terminate===!0),r6(z,L.result,L.isError)},V=0;while(V<$.length){let z=$[V],F=Q.tools?.find((q)=>q.name===z.name);if(!(F?tZ(F,z.arguments):!1)){let q=await K(z);if(await oZ(q,W),X.push(q),V++,G.aborted)break;if(B=await Y.getSteeringMessages?.()??[],B.length>0)break;continue}let D=[];while(V<$.length&&D.length<TB){let q=$[V],A=Q.tools?.find((N)=>N.name===q.name);if(!A||!tZ(A,q.arguments))break;D.push(q),V++}let U=await Promise.all(D.map(K));for(let q of U)await oZ(q,W),X.push(q);if(G.aborted)break;if(B=await Y.getSteeringMessages?.()??[],B.length>0)break}if(B.length>0&&V<$.length)X.push(...await _B($.slice(V),W));return{results:X,terminate:J.length>0&&J.every(Boolean),steering:B}}var t6="[output cleared to save context \u2014 re-run the tool if you need it]",bQ="[image cleared to save context]";function yQ($){return $.type==="image"&&$.evictable!==!1}function sZ($,Z={}){let Q=Z.keepRecent??6,Y=l($),W=Z.targetTokens,G=[...$],X=Math.max(0,G.length-Q),J=0,B=()=>W!==void 0&&l(G)<=W;for(let K=0;K<X;K++){let V=G[K];if(!V||V.role!=="toolResult"||V.evicted)continue;if(B())break;if(!V.content.some(yQ))continue;G[K]={...V,content:V.content.map((F)=>yQ(F)?{type:"text",text:bQ}:F)},J++}for(let K=0;K<X;K++){let V=G[K];if(!V||V.role!=="toolResult"||V.evicted)continue;if(B())break;if(V.isError)continue;if(V.content.filter((F)=>F.type==="text").map((F)=>F.text).join("").length<t6.length)continue;G[K]={...V,content:[{type:"text",text:t6}],evicted:!0},J++}return{messages:G,evicted:J,tokensFreed:Math.max(0,Y-l(G))}}var o6=0.6;function _Q($,Z){if($==="*")return!0;let Q=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${Q}$`,"s").test(Z)}function s6($,Z,Q){let Y=typeof Z==="string"?[Z]:Z,W="ask";for(let G of $)if(Y.some((X)=>_Q(G.permission,X))&&_Q(G.pattern,Q))W=G.action;return W}var vB=new TextEncoder,y1=new TextDecoder;function xQ($,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 gB($,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 Y=$[Q]??0,W=Y<128?1:Y<224?2:Y<240?3:4;return Q+W<=Z?Q+W:Q}function hB($,Z){let Q=Math.max(0,Z);while(Q<$.length&&($[Q]??0)>=128&&($[Q]??0)<192)Q+=1;return Q}class b1{headLimit;tailLimit;head=new Uint8Array;tail=new Uint8Array;headComplete=!1;total=0;constructor($=8000,Z=8000){this.headLimit=$;this.tailLimit=Z}append($){let Z=vB.encode($);if(this.total+=Z.length,!this.headComplete&&this.head.length<this.headLimit){let Q=this.headLimit-this.head.length,Y=gB(Z,Q);if(this.head=xQ(this.head,Z.subarray(0,Y)),Z=Z.subarray(Y),Z.length===0)return;this.headComplete=!0}if(this.tail=xQ(this.tail,Z),this.tail.length>this.tailLimit){let Q=this.tail.length-this.tailLimit;this.tail=this.tail.slice(hB(this.tail,Q))}}get bytes(){return this.total}get truncated(){return this.droppedBytes>0}read(){let $=y1.decode(this.head),Z=y1.decode(this.tail);if(this.droppedBytes===0)return $+Z;return`${$}
|
|
60
|
+
</${Z}>`}:Y);return{role:"user",content:Q,timestamp:$.timestamp}}function l6($){return $.map((Z)=>Z.role==="custom"?MQ(Z):Z)}function Q$($){return{role:"user",content:[{type:"text",text:$}],timestamp:Date.now()}}function g$($,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 OQ($){return{content:[{type:"text",text:$}]}}function dZ($,Z){if($.executionMode==="sequential")return!1;if(!$.isConcurrencySafe)return!1;try{return $.isConcurrencySafe(Z)===!0}catch{return!1}}var FB=10,jQ=3;function LB($){return $.content.filter((Z)=>Z.type==="toolCall")}function DB($){return`${$.name}:${JSON.stringify($.arguments)}`}async function p6($,Z,Q,Y,W){let G=W??new AbortController().signal,X=[...$],J={...Z,messages:[...Z.messages,...$]},B=Q,K=0,V=[],z=async(D)=>{return await Y({type:"agent_end",messages:X,reason:D}),{messages:X,reason:D}};await Y({type:"agent_start"});for(let D of $)await Y({type:"message_start",message:D}),await Y({type:"message_end",message:D});let F=await B.getSteeringMessages?.()??[];for(;;){let D=!0;while(D||F.length>0){if(G.aborted)return z("aborted");if(B.maxTurns!==void 0&&K>=B.maxTurns)return z("maxTurns");K++,await Y({type:"turn_start"});for(let M of F)await Y({type:"message_start",message:M}),await Y({type:"message_end",message:M}),J.messages.push(M),X.push(M);if(F=[],B.prepareContext){let M=await B.prepareContext(J.messages),S=Array.isArray(M)?{messages:M}:M;if(J={...J,messages:S.messages},S.stop)return z("budget")}let U=await AB(J,B,Y,G),q=U.message;if(J.messages.push(q),X.push(q),q.stopReason==="error"||q.stopReason==="aborted"){if(await Y({type:"turn_end",message:q,toolResults:[]}),q.stopReason==="error"&&await B.recoverFromError?.(q)===!0){D=!0;continue}return z(q.stopReason==="aborted"?"aborted":"error")}let A=LB(q),N=[];if(D=!1,A.length>0){let M=q.stopReason==="length"?await NB(A,Y):await PB(A,q,J,B,Y,G);N.push(...M.results),F.push(...M.steering),D=!M.terminate;for(let g of M.results)J.messages.push(g),X.push(g);let S=UB(A,V);if(S)J.messages.push(S),X.push(S),await Y({type:"message_start",message:S}),await Y({type:"message_end",message:S})}await Y({type:"turn_end",message:q,toolResults:N});let j={message:q,toolResults:N,context:J,requestMessages:U.messages,newMessages:X},P=await B.prepareNextTurn?.(j);if(P){if(P.context)J=P.context;B={...B,...P.model?{model:P.model}:{},...P.thinkingLevel!==void 0?{thinkingLevel:P.thinkingLevel}:{}}}if(await B.shouldStopAfterTurn?.(j))return z("done");F.push(...await B.getSteeringMessages?.()??[])}let L=await B.getFollowUpMessages?.()??[];if(L.length>0){F=L;continue}break}return z("done")}function UB($,Z){for(let Y of $){let W=DB(Y);if(Z[Z.length-1]===W)Z.push(W);else Z.length=0,Z.push(W)}if(Z.length<jQ)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 ${jQ} 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 AB($,Z,Q,Y){let W=Z.transformContext?await Z.transformContext($.messages):$.messages,G={...$.systemPrompt?{systemPrompt:$.systemPrompt}:{},messages:l6(W),...$.tools?{tools:$.tools.map((K)=>({name:K.name,description:K.description,inputSchema:K.inputSchema}))}:{}},X=Z.provider.stream(Z.model,G,{...Z.streamOpts,...Z.thinkingLevel!==void 0?{thinkingLevel:Z.thinkingLevel}:{},signal:Y}),J=!1;for await(let K of X){if(K.type==="start"){J=!0,await Q({type:"message_start",message:{...K.partial}});continue}if(K.type==="done"||K.type==="error")break;let V=qB(K);if(V)await Q({type:"message_update",message:{...K.partial},delta:V})}let B=await X.result();if(!J)await Q({type:"message_start",message:{...B}});return await Q({type:"message_end",message:B}),{message:B,messages:W}}function c6($,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 iZ($,Z){await Z({type:"tool_execution_end",toolCallId:$.toolCallId,result:$}),await Z({type:"message_start",message:$}),await Z({type:"message_end",message:$})}async function NB($,Z){let Q=[];for(let Y of $){await Z({type:"tool_execution_start",toolCallId:Y.id,toolName:Y.name,args:Y.arguments});let W=c6(Y,y(`Tool call "${Y.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 iZ(W,Z),Q.push(W)}return{results:Q,terminate:!1,steering:[]}}async function MB($,Z){let Q=[];for(let Y of $){await Z({type:"tool_execution_start",toolCallId:Y.id,toolName:Y.name,args:Y.arguments});let W=c6(Y,y(`Tool call "${Y.name}" was not executed because a steering message interrupted the remaining tool calls. Re-evaluate the plan before re-issuing it.`),!0);await iZ(W,Z),Q.push(W)}return Q}async function OB($,Z,Q,Y,W){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 Y.beforeToolCall?.({assistantMessage:Z,toolCall:$,args:X,context:Q},W);if(W.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,Y,W,G){let X,J,B=Promise.resolve();try{X=await $.tool.execute($.call.id,$.args,G,(K)=>{B=B.then(()=>W({type:"tool_execution_update",toolCallId:$.call.id,partial:K}))}),await B,J=X.isError===!0}catch(K){X=y(K instanceof Error?K.message:String(K)),J=!0}if(Y.afterToolCall)try{let K=await Y.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 PB($,Z,Q,Y,W,G){let X=[],J=[],B=[],K=async(z)=>{await W({type:"tool_execution_start",toolCallId:z.id,toolName:z.name,args:z.arguments});let F=await OB(z,Z,Q,Y,G),D=F.kind==="immediate"?{result:F.result,isError:!0}:await jB(F.prepared,Z,Q,Y,W,G);return J.push(D.result.terminate===!0),c6(z,D.result,D.isError)},V=0;while(V<$.length){let z=$[V],F=Q.tools?.find((q)=>q.name===z.name);if(!(F?dZ(F,z.arguments):!1)){let q=await K(z);if(await iZ(q,W),X.push(q),V++,G.aborted)break;if(B=await Y.getSteeringMessages?.()??[],B.length>0)break;continue}let L=[];while(V<$.length&&L.length<FB){let q=$[V],A=Q.tools?.find((N)=>N.name===q.name);if(!A||!dZ(A,q.arguments))break;L.push(q),V++}let U=await Promise.all(L.map(K));for(let q of U)await iZ(q,W),X.push(q);if(G.aborted)break;if(B=await Y.getSteeringMessages?.()??[],B.length>0)break}if(B.length>0&&V<$.length)X.push(...await MB($.slice(V),W));return{results:X,terminate:J.length>0&&J.every(Boolean),steering:B}}var d6="[output cleared to save context \u2014 re-run the tool if you need it]",wQ="[image cleared to save context]";function PQ($){return $.type==="image"&&$.evictable!==!1}function nZ($,Z={}){let Q=Z.keepRecent??6,Y=l($),W=Z.targetTokens,G=[...$],X=Math.max(0,G.length-Q),J=0,B=()=>W!==void 0&&l(G)<=W;for(let K=0;K<X;K++){let V=G[K];if(!V||V.role!=="toolResult"||V.evicted)continue;if(B())break;if(!V.content.some(PQ))continue;G[K]={...V,content:V.content.map((F)=>PQ(F)?{type:"text",text:wQ}:F)},J++}for(let K=0;K<X;K++){let V=G[K];if(!V||V.role!=="toolResult"||V.evicted)continue;if(B())break;if(V.isError)continue;if(V.content.filter((F)=>F.type==="text").map((F)=>F.text).join("").length<d6.length)continue;G[K]={...V,content:[{type:"text",text:d6}],evicted:!0},J++}return{messages:G,evicted:J,tokensFreed:Math.max(0,Y-l(G))}}var i6=0.6;function TQ($,Z){if($==="*")return!0;let Q=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${Q}$`,"s").test(Z)}function n6($,Z,Q){let Y=typeof Z==="string"?[Z]:Z,W="ask";for(let G of $)if(Y.some((X)=>TQ(G.permission,X))&&TQ(G.pattern,Q))W=G.action;return W}var wB=new TextEncoder,S1=new TextDecoder;function IQ($,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 TB($,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 Y=$[Q]??0,W=Y<128?1:Y<224?2:Y<240?3:4;return Q+W<=Z?Q+W:Q}function IB($,Z){let Q=Math.max(0,Z);while(Q<$.length&&($[Q]??0)>=128&&($[Q]??0)<192)Q+=1;return Q}class C1{headLimit;tailLimit;head=new Uint8Array;tail=new Uint8Array;headComplete=!1;total=0;constructor($=8000,Z=8000){this.headLimit=$;this.tailLimit=Z}append($){let Z=wB.encode($);if(this.total+=Z.length,!this.headComplete&&this.head.length<this.headLimit){let Q=this.headLimit-this.head.length,Y=TB(Z,Q);if(this.head=IQ(this.head,Z.subarray(0,Y)),Z=Z.subarray(Y),Z.length===0)return;this.headComplete=!0}if(this.tail=IQ(this.tail,Z),this.tail.length>this.tailLimit){let Q=this.tail.length-this.tailLimit;this.tail=this.tail.slice(IB(this.tail,Q))}}get bytes(){return this.total}get truncated(){return this.droppedBytes>0}read(){let $=S1.decode(this.head),Z=S1.decode(this.tail);if(this.droppedBytes===0)return $+Z;return`${$}
|
|
61
61
|
|
|
62
62
|
\u2026 [${this.droppedBytes} bytes omitted] \u2026
|
|
63
63
|
|
|
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=
|
|
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=S1.decode(this.head.slice($)),Y=Z>this.head.length;return{text:Y?`${Q}
|
|
65
65
|
|
|
66
66
|
\u2026 [output omitted] \u2026
|
|
67
67
|
|
|
68
|
-
${
|
|
68
|
+
${S1.decode(this.tail)}`:Q+S1.decode(this.tail),offset:this.total,gap:Y}}if($<Z)return{text:`\u2026 [output omitted] \u2026
|
|
69
69
|
|
|
70
|
-
${
|
|
70
|
+
${S1.decode(this.tail)}`,offset:this.total,gap:!0};return{text:S1.decode(this.tail.slice($-Z)),offset:this.total,gap:!1}}get droppedBytes(){return this.total-this.head.length-this.tail.length}}class aZ{spawn;events;tasks=new Map;counter=0;constructor($,Z={}){this.spawn=$;this.events=Z}setEvents($){this.events=$}start($,Z={}){let Q=`task_${++this.counter}`,Y=new C1,W={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)=>{Y.append(J),W.outputBytes=Y.bytes,W.truncated=Y.truncated,this.events.onOutput?.(Q,J)}}),X={info:W,buffer:Y,handle:G,readOffset:0,killRequested:!1};return this.tasks.set(Q,X),this.events.onStarted?.({...W}),G.exited.then((J)=>{if(W.status==="running")W.status=X.killRequested||J===null?"killed":"exited";W.exitCode=J,W.endedAt=Date.now(),this.events.onExited?.({...W})}),{...W}}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:Y,offset:W}=Q.buffer.readSince(Q.readOffset);return Q.readOffset=W,{text:Y,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 Y=this.tasks.get($);if(!Y||Y.info.status!=="running"||Z<=0||Q<=0)return!1;return Y.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 a6($){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 h$=1;function y1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function v($){return typeof $==="string"}function rZ($){return typeof $==="string"&&$.length>0}function V0($){return typeof $==="number"&&Number.isFinite($)}function d($,Z){return $===void 0||Z($)}function r6($){if(!y1($))return!1;return V0($.inputTokens)&&$.inputTokens>=0&&V0($.outputTokens)&&$.outputTokens>=0&&V0($.cacheReadTokens)&&$.cacheReadTokens>=0&&V0($.cacheWriteTokens)&&$.cacheWriteTokens>=0&&d($.costUsd,(Z)=>V0(Z)&&Z>=0)}function tZ($,Z){if(!y1($)||!v($.type)||!Z.includes($.type))return!1;if($.type==="text")return v($.text);if($.type==="image")return v($.mimeType)&&v($.data)&&d($.evictable,(Q)=>typeof Q==="boolean");if($.type==="thinking")return v($.thinking)&&d($.signature,v)&&d($.redacted,(Q)=>typeof Q==="boolean");return v($.id)&&v($.name)&&y1($.arguments)&&d($.signature,v)}function RQ($){if(!y1($)||!v($.role)||!Array.isArray($.content))return!1;if(!V0($.timestamp))return!1;if($.role==="user")return $.content.every((Z)=>tZ(Z,["text","image"]));if($.role==="custom")return v($.customType)&&d($.display,(Z)=>typeof Z==="boolean")&&$.content.every((Z)=>tZ(Z,["text","image"]));if($.role==="toolResult")return v($.toolCallId)&&v($.toolName)&&typeof $.isError==="boolean"&&d($.evicted,(Z)=>typeof Z==="boolean")&&$.content.every((Z)=>tZ(Z,["text","image"]));if($.role==="assistant")return v($.model)&&r6($.usage)&&["end","toolUse","length","aborted","error"].includes(String($.stopReason))&&d($.errorMessage,v)&&$.content.every((Z)=>tZ(Z,["text","thinking","toolCall"]));return!1}function t6($){if(!y1($)||!v($.type))throw Error("Invalid session entry: expected an object with a type");if($.type==="session"){if(!V0($.version)||!rZ($.id)||!v($.createdAt)||!v($.profile)||!y1($.environment)||!Object.values($.environment).every(v))throw Error("Invalid session header");return}if(!rZ($.id)||!($.parentId===null||rZ($.parentId)))throw Error(`Invalid ${$.type} session entry identity`);switch($.type){case"message":if(!RQ($.message)||!d($.checkpointRef,v))throw Error("Invalid message session entry");return;case"compaction":if(!v($.summary)||!($.firstKeptEntryId===null||v($.firstKeptEntryId))||!d($.timestamp,V0)||!d($.contextTokensBefore,V0)||!d($.contextTokensAfter,V0)||!d($.model,v)||!d($.compactorModel,v)||!d($.windowNumber,V0)||!d($.keptTokens,V0)||!d($.toolResultsCleared,V0)||!d($.usage,r6))throw Error("Invalid compaction session entry");return;case"microcompaction":if(!Array.isArray($.replacements)||!$.replacements.every((Z)=>y1(Z)&&v(Z.entryId)&&RQ(Z.message)))throw Error("Invalid microcompaction session entry");return;case"compaction-attempt":if(!["failed","cancelled"].includes(String($.status))||!["manual","threshold","overflow","model-change"].includes(String($.trigger))||!v($.model)||!v($.compactorModel)||!V0($.timestamp)||!r6($.usage))throw Error("Invalid compaction-attempt session entry");return;case"checkpoint":if(!($.beforeEntryId===null||v($.beforeEntryId))||!v($.checkpointRef)||!v($.checkpointAfterRef)||!d($.label,v))throw Error("Invalid checkpoint session entry");return;case"settings-change":if(!d($.model,v)||!d($.thinkingLevel,v))throw Error("Invalid settings-change session entry");return;case"custom":if(!rZ($.customType)||!Object.hasOwn($,"data"))throw Error("Invalid custom session entry");return;default:throw Error(`Unknown session entry type: ${$.type}`)}}function SQ($){return $.type!=="session"}function CQ($){return JSON.stringify($)}function yQ($){let Z=JSON.parse($);return t6(Z),Z}function bQ($){return $.map(CQ).join(`
|
|
71
71
|
`)+($.length>0?`
|
|
72
|
-
`:"")}function
|
|
73
|
-
`).filter((Z)=>Z.trim().length>0).map(
|
|
74
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),await
|
|
75
|
-
`,"utf8"),(await this.git("rev-parse","--git-dir")).exitCode!==0)await this.git("init","--quiet");await
|
|
76
|
-
`,"utf8");let W=
|
|
72
|
+
`:"")}function _Q($){return $.split(`
|
|
73
|
+
`).filter((Z)=>Z.trim().length>0).map(yQ)}var EQ=0;function xQ(){return EQ+=1,`e${Date.now().toString(36)}${EQ.toString(36)}`}class o{entries=[];byId=new Map;headId=null;constructor($){if($)t6($),this.entries.push($)}static fromJsonl($){let Z=new o,Q=_Q($);if(Q.length===0||Q[0]?.type!=="session")throw Error("Invalid session: line 1 must be the session header");for(let Y of Q)Z.push(Y);return Z}toJsonl(){return bQ(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(t6($),$.type==="session"){if(this.entries.length!==0)throw Error("Invalid session: header must appear only on line 1")}else{if(this.entries.length===0||this.entries[0]?.type!=="session")throw Error("Invalid session: missing header");if(this.byId.has($.id))throw Error(`Invalid session: duplicate entry id ${$.id}`);if($.parentId!==null&&!this.byId.has($.parentId))throw Error(`Invalid session: unknown parent ${$.parentId}`)}if(this.entries.push($),SQ($))this.byId.set($.id,$),this.headId=$.id}append($){let Z={...$,id:$.id??xQ(),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,Y=$;while(Y){if(Q.has(Y))break;Q.add(Y);let W=this.byId.get(Y);if(!W)break;Z.push(W),Y=W.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 Y=Z[Q];if(Y?.type==="message"&&Y.message===$)return Y.id;if(Y?.type==="microcompaction"){let W=Y.replacements.find((G)=>G.message===$);if(W)return W.entryId}}return}messagesAt($=this.headId){if(!$)return[];let Z=this.pathTo($),Q=[];for(let Y of Z){if(Y.type==="message"){Q.push({message:Y.message,entryId:Y.id});continue}if(Y.type==="microcompaction"){for(let W of Y.replacements){let G=Q.findIndex((X)=>X.entryId===W.entryId);if(G!==-1)Q[G]={message:W.message,entryId:W.entryId}}continue}if(Y.type==="compaction"){if(Y.firstKeptEntryId===null){Q=[{message:v$(Y.summary,Y.carryover,Y.timestamp)}];continue}let W=Q.findIndex((G)=>G.entryId===Y.firstKeptEntryId);if(W===-1)continue;Q=[{message:v$(Y.summary,Y.carryover,Y.timestamp)},...Q.slice(W)]}}return Q.map((Y)=>Y.message)}fork($){if($!==null&&!this.byId.has($))throw Error(`Cannot fork from unknown entry: ${$}`);this.headId=$}}class u${sessions=new Map;async load($){let Z=this.sessions.get($);return Z===void 0?void 0:o.fromJsonl(Z)}async save($,Z){this.sessions.set($,Z.toJsonl())}async list(){return[...this.sessions.keys()]}}import{createHash as RB,randomUUID as EB}from"crypto";import{realpathSync as SB}from"fs";import{chmod as kQ,mkdir as m$,readFile as l$,rename as CB,rm as p$,stat as yB,writeFile as oZ}from"fs/promises";import{homedir as bB}from"os";import{basename as _B,dirname as xB,join as V1,relative as n0,resolve as s6}from"path";function gQ($=process.platform){return $==="win32"?"NUL":"/dev/null"}var kB=async($,Z,Q)=>{let Y=Bun.spawn(["git",...$],{cwd:Q,env:{...process.env,...Z},stdout:"pipe",stderr:"pipe",stdin:"ignore",windowsHide:!0}),[W,G,X]=await Promise.all([new Response(Y.stdout).text(),new Response(Y.stderr).text(),Y.exited]);return{stdout:W,stderr:G,exitCode:X}};function fB($){let Z=[];for(let Q of $.split("\x00")){if(Q.length===0)continue;let Y=Q.indexOf("\t"),W=Q.indexOf("\t",Y+1);if(Y===-1||W===-1)continue;let G=Q.slice(0,Y),X=Q.slice(Y+1,W),J=Q.slice(W+1);Z.push({path:J,added:G==="-"?0:Number(G),removed:X==="-"?0:Number(X),hunks:[]})}return Z}function vB($){let Z=s6($);try{return SB.native(Z)}catch{return Z}}function gB($,Z){let Q=(Z??_B($)).replace(/[^A-Za-z0-9._-]+/g,"-")||"workspace",Y=RB("sha256").update($).digest("hex").slice(0,16);return`${Q}-${Y}`}var hB=new Set([".venv","venv","node_modules","__pycache__",".pytest_cache",".mypy_cache",".ruff_cache",".next",".nuxt",".cache","coverage"]),fQ="2",uB=30000,mB=1000,o6=".mu";function lB($){let Z=$.replaceAll("\\","/").replace(/^\.\//,"").replace(/\/+$/,"").split("/"),Q=Z.findIndex((Y)=>hB.has(Y));if(Q===-1)return;return Z.slice(0,Q+1).join("/")}function vQ($){return`/${$.replaceAll("\\","\\\\").replace(/[?*[#]/g,"\\$&")}/`}class sZ{root;shadowDir;run;lockDir;excludedPathspecs;initialized=!1;constructor($){this.root=vB($.root);let Z=gB(this.root,$.scope);this.shadowDir=$.shadowDir??V1(bB(),".mu","checkpoints",Z),this.lockDir=`${this.shadowDir}.lock`,this.run=$.run??kB;let Q=n0(this.root,this.shadowDir).replaceAll("\\","/"),Y=n0(this.root,this.lockDir).replaceAll("\\","/");this.excludedPathspecs=[":(exclude,literal).git",":(exclude,glob).git/**",`:(exclude,literal)${o6}`,`:(exclude,glob)${o6}/**`,...Q.length>0&&!Q.startsWith("..")?[`:(exclude,literal)${Q}`,`:(exclude,glob)${Q}/**`]:[],...Y.length>0&&!Y.startsWith("..")?[`:(exclude,literal)${Y}`,`:(exclude,glob)${Y}/**`]:[]]}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:gQ(),GIT_CONFIG_NOSYSTEM:"1"}}async git(...$){return this.run($,this.env(),this.root)}async acquireLock(){await m$(xB(this.lockDir),{recursive:!0});let $=EB(),Z=Date.now()+uB;while(!0){try{await m$(this.lockDir,{mode:448});let X=V1(this.lockDir,"owner.json"),J=V1(this.lockDir,`owner.${$}.tmp`);try{await oZ(J,`${JSON.stringify({pid:process.pid,token:$,createdAt:Date.now()})}
|
|
74
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),await CB(J,X)}catch(B){throw await p$(this.lockDir,{recursive:!0,force:!0}).catch(()=>{}),B}return async()=>{let B=await l$(X,"utf8").catch(()=>{return});if(!B)return;try{if(JSON.parse(B).token===$)await p$(this.lockDir,{recursive:!0,force:!0})}catch{}}}catch(X){if(X.code!=="EEXIST")throw X}let Q=V1(this.lockDir,"owner.json"),Y=await l$(Q,"utf8").catch(()=>{return}),W=!1,G;if(Y)try{let X=JSON.parse(Y);if(G=typeof X.token==="string"?X.token:void 0,typeof X.pid==="number"&&Number.isSafeInteger(X.pid))try{process.kill(X.pid,0)}catch(J){W=J.code==="ESRCH"}else W=!0}catch{W=!0}else W=await yB(this.lockDir).then((J)=>Date.now()-J.mtimeMs).catch(()=>0)>=mB;if(W){let X=await l$(Q,"utf8").catch(()=>{return}),J;try{J=X?JSON.parse(X).token??void 0:void 0}catch{}if(J===G){await p$(this.lockDir,{recursive:!0,force:!0});continue}}if(Date.now()>=Z)throw Error(`Timed out waiting for checkpoint lock ${this.lockDir}`);await new Promise((X)=>setTimeout(X,20))}}async locked($){let Z=await this.acquireLock();try{return await $()}finally{await Z()}}async ensure(){if(this.initialized)return;if(await m$(this.shadowDir,{recursive:!0,mode:448}),process.platform!=="win32")await kQ(this.shadowDir,448);let $=V1(this.shadowDir,"mu-worktree"),Z=!1;try{let G=(await l$($,"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=V1(this.shadowDir,"mu-checkpoint-version");if(Z){if((await l$(Q,"utf8").catch((X)=>{if(X.code==="ENOENT")return;throw X}))?.trim()!==fQ){if(await p$(this.shadowDir,{recursive:!0,force:!0}),await m$(this.shadowDir,{recursive:!0,mode:448}),process.platform!=="win32")await kQ(this.shadowDir,448)}}if(await oZ($,`${this.root}
|
|
75
|
+
`,"utf8"),(await this.git("rev-parse","--git-dir")).exitCode!==0)await this.git("init","--quiet");await oZ(Q,`${fQ}
|
|
76
|
+
`,"utf8");let W=n0(this.root,this.shadowDir).replaceAll("\\","/");if(W.length>0&&!W.startsWith("..")){let G=n0(this.root,this.lockDir).replaceAll("\\","/");await m$(V1(this.shadowDir,"info"),{recursive:!0}),await oZ(V1(this.shadowDir,"info","exclude"),`/${W}/
|
|
77
77
|
${G.length>0&&!G.startsWith("..")?`/${G}/
|
|
78
|
-
`:""}`,"utf8")}this.initialized=!0}async ignoredDisposableDirectories(){let $=await this.git("ls-files","--cached","--others","--ignored","--exclude-standard","--directory","-z");if($.exitCode!==0)throw Error(`Could not enumerate ignored checkpoint paths: ${$.stderr.trim()}`);let Z=new Set;for(let Q of $.stdout.split("\x00")){if(Q.length===0)continue;let Y=
|
|
79
|
-
`)}return W})}}import{createHash as
|
|
78
|
+
`:""}`,"utf8")}this.initialized=!0}async ignoredDisposableDirectories(){let $=await this.git("ls-files","--cached","--others","--ignored","--exclude-standard","--directory","-z");if($.exitCode!==0)throw Error(`Could not enumerate ignored checkpoint paths: ${$.stderr.trim()}`);let Z=new Set;for(let Q of $.stdout.split("\x00")){if(Q.length===0)continue;let Y=lB(Q);if(Y)Z.add(Y)}return[...Z].sort()}checkpointPathspecs($){return[...this.excludedPathspecs,...$.map((Z)=>`:(exclude,literal)${Z}`)]}async snapshot($){return this.locked(async()=>{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.locked(async()=>{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(),Y=await this.git("clean","--force","-d","-x","--quiet","-e",".git","-e",vQ(o6),...n0(this.root,this.shadowDir).startsWith("..")?[]:["-e",n0(this.root,this.shadowDir).replaceAll("\\","/")],...n0(this.root,this.lockDir).startsWith("..")?[]:["-e",n0(this.root,this.lockDir).replaceAll("\\","/")],...Q.flatMap((W)=>["-e",vQ(W)]));if(Y.exitCode!==0)throw Error(`Could not clean checkpoint ${$}: ${Y.stderr.trim()}`)})}async restoreResources($,Z){await this.locked(async()=>{await this.ensure();let Q=[...new Set(Z.map((J)=>{let B=s6(this.root,J),K=n0(this.root,B).replaceAll("\\","/");if(K.length===0||K===".."||K.startsWith("../"))throw Error(`Checkpoint resource escapes the workspace: ${J}`);return K}))];if(Q.length===0)return;let Y=Q.map((J)=>`:(literal)${J}`),W=await this.git("reset","--quiet",$,"--",...Y);if(W.exitCode!==0)throw Error(`Could not reset checkpoint ${$}: ${W.stderr.trim()}`);let G=[],X=[];for(let J of Q){let B=await this.git("ls-tree","-z",$,"--",`:(literal)${J}`);if(B.exitCode!==0)throw Error(`Could not inspect checkpoint ${$}: ${B.stderr.trim()}`);(B.stdout.length>0?G:X).push(J)}if(G.length>0){let J=await this.git("checkout","--force",$,"--",...G.map((B)=>`:(literal)${B}`));if(J.exitCode!==0)throw Error(`Could not restore checkpoint ${$}: ${J.stderr.trim()}`)}await Promise.all(X.map((J)=>p$(s6(this.root,J),{recursive:!0,force:!0})))})}async diff($,Z){return this.locked(async()=>{if(await this.ensure(),!Z){let G=await this.ignoredDisposableDirectories(),X=await this.git("add","-A","--force","--",".",...this.checkpointPathspecs(G));if(X.exitCode!==0)throw Error(`Could not stage workspace for checkpoint diff: ${X.stderr.trim()}`)}let Q=Z?["diff","--no-renames","--numstat","-z",$,Z]:["diff","--no-renames","--cached","--numstat","-z",$],Y=await this.git(...Q);if(Y.exitCode!==0)throw Error(`Could not calculate checkpoint diff: ${Y.stderr.trim()}`);let W=fB(Y.stdout);for(let G of W){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)throw Error(`Could not calculate checkpoint patch for ${G.path}: ${J.stderr.trim()}`);G.hunks=J.stdout.split(`
|
|
79
|
+
`)}return W})}}import{createHash as pB}from"crypto";import{realpathSync as cB}from"fs";import{open as dB,readdir as dQ,readFile as iB,realpath as hQ,stat as e6}from"fs/promises";import{homedir as nB}from"os";import{basename as Q4,dirname as c$,extname as aB,isAbsolute as $5,join as M0,relative as W4,resolve as I0,sep as rB}from"path";var iQ=[".git"],nQ=[".mu/AGENTS.md","CLAUDE.local.md","CLAUDE.md","CLAUDE.MD",".claude/CLAUDE.md"],tB=["AGENTS.override.md","AGENTS.md","AGENTS.MD"],Y4="project-instructions-",uQ=5,oB=8192,sB=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 d$($,Z){let Q=W4(I0($),I0(Z));return Q===""||!Q.startsWith(`..${rB}`)&&Q!==".."&&!$5(Q)}function $4($){let Z=I0($);try{return cB.native(Z)}catch{return Z}}function eB($){if(!$||$5($))return!1;let Z=$.replaceAll("\\","/");return Z!==".."&&!Z.startsWith("../")&&!Z.includes("/../")}function $H($){return[...new Set($.filter(eB))]}function Z4($,Z){let Q=pB("sha256");Q.update(Z?"enabled\x00":"disabled\x00");for(let Y of $)Q.update(Y.path),Q.update("\x00"),Q.update(Y.scope),Q.update("\x00"),Q.update(Y.parent??""),Q.update("\x00"),Q.update(Y.content),Q.update("\x00");return Q.digest("hex").slice(0,16)}async function ZH($){let Z=await dB($,"r");try{let Q=Buffer.alloc(oB),{bytesRead:Y}=await Z.read(Q,0,Q.length,0);return Q.subarray(0,Y).toString("utf8")}finally{await Z.close()}}function QH($){for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q?.role!=="custom"||!Q.customType.startsWith(Y4))continue;return Q.customType.slice(Y4.length)}return}function eZ($,Z){if(d$(Z,$.path))return W4(Z,$.path)||Q4($.path);return $.path}function mQ($,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.",Y=$.sources.length===0?"No instruction files are currently active.":$.sources.map((W)=>{let G=W.scope==="import"&&W.parent?`imported by ${eZ({...W,path:W.parent},$.projectRoot)}`:`${W.scope} instructions`;return`Contents of ${eZ(W,$.projectRoot)} (${G}):
|
|
80
80
|
|
|
81
81
|
${W.content.trim()}`}).join(`
|
|
82
82
|
|
|
83
|
-
`);return
|
|
83
|
+
`);return g$(`${Y4}${$.signature}`,`${Q}
|
|
84
84
|
|
|
85
|
-
${Y}`)}function
|
|
85
|
+
${Y}`)}function lQ($){let Z=$.replaceAll(`\r
|
|
86
86
|
`,`
|
|
87
87
|
`);if(!Z.startsWith(`---
|
|
88
88
|
`))return{content:$};let Q=Z.indexOf(`
|
|
89
89
|
---
|
|
90
90
|
`,4);if(Q===-1)return{content:$};let Y=Z.slice(4,Q),W=Z.slice(Q+5),G=Y.split(`
|
|
91
|
-
`),X=[],J=!1;for(let B of G){let K=B.match(/^paths?\s*:\s*(.*)$/i);if(K){J=!0;let z=K[1]?.trim()??"";if(z){let F=z.startsWith("[")&&z.endsWith("]")?z.slice(1,-1):z;X.push(...F.split(",").map((
|
|
92
|
-
Use project/user config or remove --no-instructions to enable loading.`;let Z=[...this.current.sources,...this.nestedSources.values()],Q=this.current.bytes+[...this.nestedSources.values()].reduce((G,X)=>G+Buffer.byteLength(X.content),0),Y=l([
|
|
93
|
-
`)}async discoverPrimaryFiles($){let Z=[],Q=$?
|
|
94
|
-
`),sources:J.sources.map((K)=>K.path)}}}async function
|
|
91
|
+
`),X=[],J=!1;for(let B of G){let K=B.match(/^paths?\s*:\s*(.*)$/i);if(K){J=!0;let z=K[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=B.match(/^\s*-\s*(.+?)\s*$/);if(V?.[1]){X.push(V[1].replace(/^['"]|['"]$/g,""));continue}if(B.trim())J=!1}return{content:W,...X.length>0?{patterns:X}:{}}}function YH($){let Z="",Q=$.replaceAll("\\","/").replace(/^\.\//,"");if(!Q||Q.startsWith("!"))return;for(let Y=0;Y<Q.length;Y++){let W=Q[Y];if(W==="*")if(Q[Y+1]==="*")if(Y++,Q[Y+1]==="/")Y++,Z+="(?:.*/)?";else Z+=".*";else Z+="[^/]*";else if(W==="?")Z+="[^/]";else Z+=W?.replace(/[|\\{}()[\]^$+?.]/g,"\\$&")??""}try{return new RegExp(`^${Z}$`)}catch{return}}function WH($,Z){if(!$.patterns||$.patterns.length===0)return!0;let Q=W4($.base,Z).replaceAll("\\","/");if(!Q||Q===".."||Q.startsWith("../")||$5(Q))return!1;let Y=!1;for(let W of $.patterns){let G=W.startsWith("!");if(YH(G?W.slice(1):W)?.test(Q))Y=!G}return Y}function GH($){let Z=new Set,Q;for(let Y of $.split(/\r?\n/)){let W=Y.match(/^\s*(`{3,}|~{3,})/);if(W?.[1]){let J=W[1][0];Q=Q===J?void 0:Q??J;continue}if(Q)continue;let G=Y.split(/(`[^`]*`)/g).filter((J)=>!J.startsWith("`")).join(" "),X=/(?:^|\s)@((?:\\ |[^\s`])+)/g;for(let J of G.matchAll(X)){let B=J[1]?.replace(/\\ /g," ");if(!B)continue;B=B.replace(/[),.;:!?]+$/,"");let K=B.indexOf("#");if(K>=0)B=B.slice(0,K);if(B&&!B.startsWith("@"))Z.add(B)}}return[...Z]}function XH($){return $<1024?`${$} B`:`${($/1024).toFixed(1)} KiB`}function pQ($){return $<1000?`~${$} tokens`:`~${($/1000).toFixed(1)}k tokens`}class Z5{root;home;settings;managedPaths;settingDiagnostics;current;nestedSources=new Map;nestedSerial=Promise.resolve();activeSessionId;constructor($){this.root=$4($.root),this.home=$4($.home??nB());let Z=[],Q=(G,X,J)=>{if(G===void 0)return X;if(typeof G==="boolean")return G;return Z.push({level:"warning",message:`instructions.${J} must be a boolean; using ${X}`}),X},Y=(G,X,J)=>{if(G===void 0)return X;if(!Array.isArray(G)||G.some((K)=>typeof K!=="string"))return Z.push({level:"warning",message:`instructions.${J} must be an array of relative filenames; using defaults`}),X;let B=$H(G);if(B.length!==G.length)Z.push({level:"warning",message:`instructions.${J} ignored unsafe or duplicate entries`});return B};this.settings={enabled:Q($.enabled,!0,"enabled"),fallbackFilenames:Y($.fallbackFilenames,nQ,"fallbackFilenames"),projectRootMarkers:Y($.projectRootMarkers,iQ,"projectRootMarkers"),imports:Q($.imports,!0,"imports"),claudeRules:Q($.claudeRules,!0,"claudeRules")},this.settingDiagnostics=Z;let W=process.platform==="win32"?process.env.PROGRAMDATA?[M0(process.env.PROGRAMDATA,"mu","AGENTS.md")]:[]:["/etc/mu/AGENTS.md"];this.managedPaths=($.managedPaths??W).map((G)=>I0(G)),this.current={enabled:this.settings.enabled,projectRoot:this.root,sources:[],diagnostics:[],bytes:0,signature:Z4([],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)return this.current={enabled:!1,projectRoot:Q,sources:[],diagnostics:Z,bytes:0,signature:Z4([],!1)},this.snapshot;let Y={processed:new Set,diagnostics:Z,sources:[]};for(let J of this.managedPaths)await this.loadSource(J,"managed",Y,void 0,c$(J),0);let W=await this.firstReadableCandidate([M0(this.home,".mu","AGENTS.override.md"),M0(this.home,".mu","AGENTS.md"),M0(this.home,".mu","AGENTS.MD"),M0(this.home,".claude","CLAUDE.md")],Z);if(W)await this.loadSource(W,"global",Y,void 0,this.home,0);let G=this.dirsBetween(Q,this.root);for(let J of G){for(let K of await this.rulesForDirectory(J,Z))if(!K.patterns)await this.loadSource(K.path,"rule",Y,void 0,Q,0);let B=await this.primaryForDirectory(J,Z);if(B){let K=Q4(B)==="CLAUDE.local.md"?"local":"project";await this.loadSource(B,K,Y,void 0,Q,0)}}let X=Y.sources.reduce((J,B)=>J+Buffer.byteLength(B.content),0);return this.current={enabled:!0,projectRoot:Q,sources:Y.sources,diagnostics:Z,bytes:X,signature:Z4(Y.sources,!0)},this.snapshot}async refreshedMessages($,Z){let Q=QH($);if(Z!==void 0&&Z!==this.activeSessionId)this.activeSessionId=Z,this.nestedSources.clear();else if(Z===void 0&&$.length===0)this.nestedSources.clear();let Y=await this.reload();if(Y.sources.length===0&&Q===void 0)return[];if(Q===Y.signature)return[];return[mQ(Y,Q!==void 0)]}async instructionsForPath($){let Z={text:"",sources:[]},Q=this.nestedSerial,Y;this.nestedSerial=new Promise((W)=>{Y=W}),await Q;try{Z=await this.loadNested($)}finally{Y?.()}return Z}formatStatus($="instructions"){if(!this.current.enabled)return`${$} disabled
|
|
92
|
+
Use project/user config or remove --no-instructions to enable loading.`;let Z=[...this.current.sources,...this.nestedSources.values()],Q=this.current.bytes+[...this.nestedSources.values()].reduce((G,X)=>G+Buffer.byteLength(X.content),0),Y=l([mQ(this.current,!1)])+[...this.nestedSources.values()].reduce((G,X)=>G+pZ(X.content),0),W=[`${$} \xB7 ${Z.length} file${Z.length===1?"":"s"} \xB7 ${pQ(Y)} \xB7 ${XH(Q)}`,...Z.map((G)=>` ${G.scope.padEnd(7)} ${eZ(G,this.current.projectRoot)} \xB7 ${pQ(pZ(G.content))}`)];if(Z.length===0)W.push(" no instruction files found");if(this.current.diagnostics.length>0)W.push("warnings:",...this.current.diagnostics.map((G)=>` ${G.path?`${G.path}: `:""}${G.message}`));return W.push("precedence: managed < global < outer project < inner project; AGENTS.override.md wins within one directory"),W.join(`
|
|
93
|
+
`)}async discoverPrimaryFiles($){let Z=[],Q=$?I0($):await this.findProjectRoot(Z),Y=[];for(let W of this.dirsBetween(Q,this.root)){let G=await this.primaryForDirectory(W,Z);if(G)Y.push(G)}return Y}async findProjectRoot($){if(this.settings.projectRootMarkers.length===0)return this.root;let Z=this.root;for(;;){for(let Y of this.settings.projectRootMarkers){let W=M0(Z,Y);try{return await e6(W),Z}catch(G){let X=G.code;if(X!=="ENOENT"&&X!=="ENOTDIR")$.push({level:"warning",path:W,message:`could not inspect project-root marker: ${G instanceof Error?G.message:String(G)}`})}}let Q=c$(Z);if(Q===Z)return this.root;Z=Q}}dirsBetween($,Z){if(!d$($,Z))return[Z];let Q=[],Y=Z;for(;;){if(Q.push(Y),Y===$)break;let W=c$(Y);if(W===Y)break;Y=W}return Q.reverse()}async primaryForDirectory($,Z){return this.firstReadableCandidate([...tB.map((Q)=>M0($,Q)),...this.settings.fallbackFilenames.map((Q)=>M0($,Q))],Z)}async firstReadableCandidate($,Z){for(let Q of $)try{if((await e6(Q)).isFile())return Q;Z.push({level:"warning",path:Q,message:"instruction candidate is not a file"})}catch(Y){let W=Y.code;if(W==="ENOENT"||W==="ENOTDIR")continue;Z.push({level:"warning",path:Q,message:`could not inspect instruction file: ${Y instanceof Error?Y.message:String(Y)}`})}return}async ruleFiles($,Z){let Q=[],Y=async(W,G)=>{let X;try{X=await hQ(W)}catch(B){let K=B.code;if(K==="ENOENT"||K==="ENOTDIR")return;Z.push({level:"warning",path:W,message:`could not read rules directory: ${B instanceof Error?B.message:String(B)}`});return}if(G.has(X))return;G.add(X);let J;try{J=await dQ(W,{withFileTypes:!0})}catch(B){Z.push({level:"warning",path:W,message:`could not list rules directory: ${B instanceof Error?B.message:String(B)}`});return}for(let B of J.sort((K,V)=>K.name.localeCompare(V.name))){let K=M0(W,B.name),V=B.isDirectory(),z=B.isFile();if(B.isSymbolicLink())try{let F=await e6(K);V=F.isDirectory(),z=F.isFile()}catch(F){Z.push({level:"warning",path:K,message:`could not inspect rule symlink: ${F instanceof Error?F.message:String(F)}`});continue}if(V)await Y(K,G);else if(z&&B.name.toLowerCase().endsWith(".md"))Q.push(K)}};return await Y($,new Set),Q}async rulesForDirectory($,Z){let Q=[M0($,".mu","rules")];if(this.settings.claudeRules)Q.push(M0($,".claude","rules"));let Y=[];for(let W of Q)for(let G of await this.ruleFiles(W,Z))try{let X=lQ(await ZH(G));Y.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 Y}async loadSource($,Z,Q,Y,W,G){if(G>uQ){Q.diagnostics.push({level:"warning",path:$,message:`import depth exceeds ${uQ}`});return}let X;try{X=await hQ($)}catch(z){let F=z.code;if(Y||F!=="ENOENT"&&F!=="ENOTDIR")Q.diagnostics.push({level:"warning",path:$,message:F==="ENOENT"?`import referenced by ${Y} does not exist`:`could not resolve instruction file: ${z instanceof Error?z.message:String(z)}`});return}if(Q.processed.has(X))return;if(!d$(W,X)){Q.diagnostics.push({level:"warning",path:$,message:`external import is outside the allowed instruction root ${W}`});return}if(!sB.has(aB(X))){Q.diagnostics.push({level:"warning",path:$,message:"skipped non-text instruction import"});return}Q.processed.add(X);let J;try{J=await iB(X,"utf8")}catch(z){Q.diagnostics.push({level:"warning",path:$,message:`could not read instruction file: ${z instanceof Error?z.message:String(z)}`});return}if(J.includes("\x00")){Q.diagnostics.push({level:"warning",path:$,message:"skipped binary instruction file"});return}let B=lQ(J),K=B.content.trim(),V=K?{path:X,content:K,scope:Z,...Y?{parent:Y}:{}}:void 0;if(this.settings.imports)for(let z of GH(B.content)){let F=z.startsWith("~/")?M0(this.home,z.slice(2)):$5(z)?z:I0(c$(X),z);await this.loadSource(F,"import",Q,X,Z==="global"?this.home:W,G+1)}if(V)Q.sources.push(V)}async loadNested($){if(!this.settings.enabled)return{text:"",sources:[]};let Z=I0($);if(!d$(this.root,Z))return{text:"",sources:[]};let Q=c$(Z),Y=this.current.projectRoot,W=this.current.diagnostics,G=[];for(let K of this.dirsBetween(Y,Q)){for(let V of await this.rulesForDirectory(K,W))if(I0(V.path)!==Z&&WH(V,Z))G.push({path:V.path,scope:"rule",allowedRoot:Y});if(d$(this.root,K)&&K!==this.root){let V=await this.primaryForDirectory(K,W);if(V&&I0(V)!==Z)G.push({path:V,scope:Q4(V)==="CLAUDE.local.md"?"local":"project",allowedRoot:Y})}}let J={processed:new Set([...this.current.sources.map((K)=>$4(K.path)),...this.nestedSources.keys()]),diagnostics:W,sources:[]};for(let K of G)await this.loadSource(K.path,K.scope,J,void 0,K.allowedRoot,0);for(let K of J.sources)this.nestedSources.set(I0(K.path),K);if(J.sources.length===0)return{text:"",sources:[]};return{text:["<system-reminder>","Additional instructions apply to the file just read. Later sources have higher precedence:","",...J.sources.flatMap((K)=>[`Contents of ${eZ(K,Y)}:`,K.content.trim(),""]),"</system-reminder>"].join(`
|
|
94
|
+
`),sources:J.sources.map((K)=>K.path)}}}async function cQ($,Z){try{let Q=Bun.spawn(["git",...$],{cwd:Z,stdout:"pipe",stderr:"ignore",windowsHide:!0}),Y=await new Response(Q.stdout).text();return await Q.exited===0?Y:void 0}catch{return}}async function G4($){let Z={directory:I0($),platform:process.platform,date:new Date().toISOString().slice(0,10)},Y=(await cQ(["rev-parse","--abbrev-ref","HEAD"],$))?.trim().split(/\r?\n/)[0];if(Y){Z.branch=Y;let W=await cQ(["status","--porcelain"],$);if(W!==void 0)Z.uncommittedFiles=String(W.split(/\r?\n/).filter(Boolean).length)}try{let W=await dQ($);Z.topLevelEntries=W.filter((G)=>!G.startsWith(".")).sort().slice(0,40).join(", ")}catch{}return Z}function X4($){let Z=Object.entries($).map(([Q,Y])=>`${Q}: ${Y}`);return g$("environment",`Session environment:
|
|
95
95
|
${Z.join(`
|
|
96
|
-
`)}`)}import{mkdir as
|
|
97
|
-
`,"utf8")}function
|
|
96
|
+
`)}`)}import{mkdir as JH,readFile as KH,writeFile as BH}from"fs/promises";import{dirname as HH,join as VH}from"path";import{z as X0}from"zod";var K4=[{permission:"*",pattern:"*",action:"ask"},{permission:"read",pattern:"*",action:"allow"},{permission:"ls",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"}],B4=[{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"}]}],zH=X0.object({permission:X0.string().min(1),pattern:X0.string(),action:X0.enum(["allow","ask","deny"])}),H4=X0.object({enabled:X0.boolean().optional(),fallbackFilenames:X0.array(X0.string().min(1)).optional(),projectRootMarkers:X0.array(X0.string().min(1)).optional(),imports:X0.boolean().optional(),claudeRules:X0.boolean().optional()}),FH=X0.object({permissions:X0.array(zH).optional(),model:X0.string().min(1).optional(),instructions:H4.optional()}).loose();function J4($){return VH($,".mu","config.json")}async function Q5($,Z){try{let Q=await KH(J4($),"utf8"),Y=JSON.parse(Q),W=FH.safeParse(Y);if(!W.success){let V=W.error.issues.map((z)=>`${z.path.join(".")||"config"}: ${z.message}`).join("; ");throw Error(`Invalid project config at ${J4($)}: ${V}`)}let{permissions:G,model:X,instructions:J,...B}=W.data,K=J?{...J.enabled!==void 0?{enabled:J.enabled}:{},...J.fallbackFilenames!==void 0?{fallbackFilenames:J.fallbackFilenames}:{},...J.projectRootMarkers!==void 0?{projectRootMarkers:J.projectRootMarkers}:{},...J.imports!==void 0?{imports:J.imports}:{},...J.claudeRules!==void 0?{claudeRules:J.claudeRules}:{}}:void 0;return{...B,...G!==void 0?{permissions:G}:{},...X!==void 0?{model:X}:{},...K!==void 0?{instructions:K}:{}}}catch(Q){if(Q.code==="ENOENT")return{};if(!Z)throw Q;return Z(Q instanceof Error?Q.message:String(Q)),{}}}function V4(...$){return $.flatMap((Z)=>Z??[])}async function z4($,Z,Q){let Y=J4($),W=await Q5($),G=W.permissions??[];if(!G.some((J)=>J.permission===Z&&J.pattern===Q&&J.action==="allow"))G.push({permission:Z,pattern:Q,action:"allow"});await JH(HH(Y),{recursive:!0}),await BH(Y,`${JSON.stringify({...W,permissions:G},null,2)}
|
|
97
|
+
`,"utf8")}function F4($){let Z=[{text:`You are mu, an expert software engineer working in a codebase through tools.
|
|
98
98
|
|
|
99
99
|
Approach:
|
|
100
100
|
- Understand before you change: read the relevant files and search the codebase rather than guessing at names or APIs.
|
|
@@ -107,29 +107,33 @@ Tools:
|
|
|
107
107
|
- Prefer edit over write for existing files; write replaces the whole file.
|
|
108
108
|
- Change several places in one file with a single edit call carrying multiple edits,
|
|
109
109
|
rather than one call per change.
|
|
110
|
-
- Use
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
110
|
+
- Use rg for content search and rg --files for file discovery; if rg is unavailable, use
|
|
111
|
+
the platform's native search commands. Run search, builds, tests, and other inspection
|
|
112
|
+
through bash, which uses the shell named in the environment (PowerShell on Windows).
|
|
113
|
+
- Keep searches shell-simple and inspection-safe: do not add printf/echo headings, pipe to
|
|
114
|
+
sort, or redirect stderr. Use rg --sort path, --no-messages, and repeated -e arguments.
|
|
115
|
+
- Keep each shell pattern simply quoted; never splice quote characters inside a shell regex.
|
|
116
|
+
- During repository exploration, batch read-only bash inspection, search and narrow first,
|
|
117
|
+
then read only the relevant line ranges instead of whole files unless full context is needed.
|
|
114
118
|
- Independent read-only lookups can be issued together in one turn.
|
|
115
119
|
|
|
116
120
|
Communication:
|
|
117
121
|
- Lead with the outcome, then the detail. Answer what was asked without padding.
|
|
118
122
|
- When explaining, reviewing, or quoting existing repository code, cite each relevant
|
|
119
123
|
claim or excerpt with its workspace-relative \`path:line\` using the 1-based starting
|
|
120
|
-
line from tool output.
|
|
121
|
-
block
|
|
124
|
+
line from tool output. Cite the exact definition, assertion, or evidence line\u2014not the
|
|
125
|
+
surrounding block heading. Put citations beside claims and never invent a line number.
|
|
122
126
|
- Only write code comments that state something the code cannot \u2014 never narrate what a line does.
|
|
123
127
|
- 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:`
|
|
124
128
|
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:`
|
|
125
|
-
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{createHash as RH}from"crypto";import{readFileSync as EH,statSync as CH}from"fs";import{resolve as K5}from"path";function SH($){return RH("sha256").update($).digest("hex")}function Q7($,Z){try{let Q=CH($);return{exists:!0,device:Q.dev,inode:Q.ino,size:Q.size,mtimeMs:Q.mtimeMs,ctimeMs:Q.ctimeMs,digest:SH(Z??EH($))}}catch{return{exists:!1}}}class B5{reads=new Map;modified=new Set;markRead($,Z){let Q=K5($);this.reads.set(Q,Q7(Q,Z))}markWritten($){let Z=K5($);this.modified.add(Z),this.markRead(Z)}hasRead($){return this.reads.has(K5($))}isStale($,Z){let Q=K5($),Y=this.reads.get(Q);if(Y===void 0)return!1;let W=Q7(Q,Z);return W.exists!==Y.exists||W.device!==Y.device||W.inode!==Y.inode||W.size!==Y.size||W.mtimeMs!==Y.mtimeMs||W.ctimeMs!==Y.ctimeMs||W.digest!==Y.digest}readFiles(){return[...this.reads.keys()]}modifiedFiles(){return[...this.modified]}}import{randomUUID as bH}from"crypto";function Y7($){return $.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens}function N8($,Z){if(!$)return;if($.maxCostUsd!==void 0&&(Z.costUsd??0)>=$.maxCostUsd)return"maxCostUsd";if($.maxTokens!==void 0&&Y7(Z)>=$.maxTokens)return"maxTokens";return}import{z as yH}from"zod";var X$="structured_output";function O8($,Z){let Q=yH.toJSONSchema($,{io:"input"});return{name:X$,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(Y,W)=>{let G=$.safeParse(W);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 ${X$} again with corrected values.`}],isError:!0};return Z(G.data),{content:[{type:"text",text:"Final answer recorded."}],terminate:!0}}}}function M8(){return`When you have the final answer, call the ${X$} tool with it. That call ends the task.`}var _H=[{permission:"*",pattern:"*",action:"allow"}],xH="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 t$($,Z){if($&&typeof $!=="string")return $;let Q=$??Q$(),Y=Z?.findModel(Q)??iZ(Q);if(!Y)throw Error(`Unknown model: ${Q}. Pass a ModelInfo to use a custom model.`);return Y}function kH($){if($===void 0)return[{text:xH}];return typeof $==="string"?[{text:$}]:$}function fH($){for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q?.role!=="assistant")continue;let Y=Q.content.filter((W)=>W.type==="text").map((W)=>W.text).join("");if(Y.trim().length>0)return Y}return""}function W7(){return`s${Date.now().toString(36)}-${bH().slice(0,8)}`}class o${options;model;provider;store;tree;_sessionId;controller=new AbortController;steering=[];followUps=[];totals=_$();compactRequested=!1;compactRequestedFocus;queuedManualCompactionFocus;manualCompactionQueued=!1;compacting=!1;compactorOverride;lastContextPercent=0;lastContextTokens=0;lastContextUsage;checkpoints=new mZ;recoveryAttempted=!1;reactiveRecoveryPending=!1;pendingCheckpoint;currentThinking;running=!1;stopping=!1;activeEmit;activeExecution;autonomousScheduled=!1;subscribers=new Set;subscriberQueues=new Map;idleWaiters=new Set;shutdownPromise;sessionStarted=!1;permissionRules;constructor($={}){this.options=$,this.permissionRules=[...$.permissions??_H],this.model=t$($.model,$.extensions),this.currentThinking=a0(this.model,$.thinkingLevel),this.provider=this.providerFor(this.model),this.store=$.session??new c$,this._sessionId=$.sessionId??W7(),this.tree=new s({type:"session",version:p$,id:this._sessionId,createdAt:new Date().toISOString(),profile:$.sessionProfile??"default",environment:{...$.sessionEnvironment??{}}}),$.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 Y$(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=t$($,this.options.extensions),Y=this.tree.messagesAt();if(Y.length>0&&l(Y)>=Q.contextWindow*(this.options.compactThreshold??S1))this.compactRequested=!0,this.compactorOverride=Z;this.model=Q,this.provider=this.providerFor(Q);let W=a0(Q,this.currentThinking),G=W!==this.currentThinking;this.currentThinking=W,this.lastContextUsage=void 0,this.refreshContextAccounting(),this.tree.append({type:"settings-change",model:this.modelRef,...G?{thinkingLevel:W}:{}}),this.options.extensions?.emitLifecycle({type:"model_select",model:this.modelRef})}setThinking($){let Z=a0(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;try{Z=s.fromJsonl($.toJsonl())}catch(W){throw Error("Cannot resume an invalid or unsupported session.",{cause:W})}let Q=Z.header;if(!Q||Q.version!==p$)throw Error("Cannot resume an invalid or unsupported session.");this.tree=Z,this._sessionId=Q.id;let Y=_$();for(let W of Z.all())if(W.type==="message"&&W.message.role==="assistant")Y=B1(Y,W.message.usage);else if(W.type==="compaction"&&W.usage)Y=B1(Y,W.usage);else if(W.type==="compaction-attempt")Y=B1(Y,W.usage);this.totals=Y,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=t$(this.options.model,this.options.extensions),this.provider=this.providerFor(this.model),this.currentThinking=a0(this.model,this.options.thinkingLevel);for(let W of Z.activePath()){if(W.type!=="settings-change")continue;if(W.model)try{this.model=t$(W.model,this.options.extensions),this.provider=this.providerFor(this.model)}catch{}if(typeof W.thinkingLevel==="string"&&W.thinkingLevel.length>0)this.currentThinking=W.thinkingLevel}this.currentThinking=a0(this.model,this.currentThinking),this.rebuildCheckpointHistory(),this.refreshContextAccounting()}newSession($=W7()){if(this.running)throw Error("Cannot start a new session while a run is active.");this._sessionId=$,this.tree=new s({type:"session",version:p$,id:$,createdAt:new Date().toISOString(),profile:this.options.sessionProfile??"default",environment:{...this.options.sessionEnvironment??{}}}),this.tree.append({type:"settings-change",model:this.modelRef,thinkingLevel:this.currentThinking}),this.totals=_$(),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(G$($))}followUp($){if(this.stopping)return;if(this.followUps.push(G$($)),!this.running)this.scheduleAutonomousRun()}removeQueuedMessage($,Z){let Q=$==="steer"?this.steering:this.followUps;for(let Y=Q.length-1;Y>=0;Y--){let W=Q[Y];if(W?.role!=="user")continue;if(W.content.filter((X)=>X.type==="text").map((X)=>X.text).join("")!==Z)continue;return Q.splice(Y,1),this.resolveIdleIfDone(),!0}return!1}emitTaskEvent($){this.publishEvent($)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($),this.subscriberQueues.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=(W)=>{if(this.publishToSubscribers(W),W.type==="agent_start"&&!this.sessionStarted)this.sessionStarted=!0,this.options.extensions?.emitLifecycle({type:"session_start",sessionId:this._sessionId});this.options.extensions?.emit(W)};this.activeEmit=Q;let Y=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=Y,Y}async executeManualCompaction($,Z){Z({type:"agent_start"});let Q=this.tree.messagesAt(),Y=h$(this.model,Q,this.lastContextUsage?.usage,this.lastContextUsage?.estimatedTokensAtUsage).tokens;Z({type:"compaction_start",layer:2,trigger:"manual",contextTokensBefore:Y});let W=sZ(Q,{targetTokens:Math.floor(this.model.contextWindow*(this.options.compactThreshold??S1)*0.8)}),G=Q,X=[];if(W.evicted>0){Z({type:"compaction_update",layer:2,stage:"clearing-tool-output",toolResultsCleared:W.evicted}),X=W.messages.flatMap((z,F)=>{let L=Q[F];if(!L||z===L)return[];let D=this.tree.entryIdForMessage(L);return D?[{entryId:D,message:z}]:[]});let V=W.messages.filter((z,F)=>z!==Q[F]).length;if(X.length===V)G=W.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 B,K=!1;try{let V=this.options.getCredentials,z=await rZ(G,{provider:J.provider,model:J.model,keepRecentTokens:Math.min(W$,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}:{},...V?{getCredentials:()=>V(J.model.provider)}:{}}});if(B=z.usage,z.summary.length===0){let n=l(Q);return Z({type:"compaction_end",layer:2,trigger:"manual",status:"noop",tokensFreed:0,contextTokensBefore:Y,contextTokensAfter:n}),Z({type:"agent_end",messages:Q,reason:"done"}),{status:"noop",message:"Context is already compact enough \u2014 no changes made.",tokensBefore:Y,tokensAfter:n,tokensFreed:0}}Z({type:"compaction_update",layer:2,stage:"installing"});let F=u$(z),L=z.keptMessages[0],D=null;if(L){let n=G.indexOf(L),w=n===-1?L:Q[n],_=w?this.tree.entryIdForMessage(w):void 0;if(!_)throw Error("Compaction tail could not be mapped to the session");D=_}let U=F[0],q=await this.options.refreshContext?.(F,{sessionId:this._sessionId})??[],A=l([...F,...q]),N=s.fromJsonl(this.tree.toJsonl());if(X.length>0)N.append({type:"microcompaction",replacements:X});let j=N.activePath().filter((n)=>n.type==="compaction").length+1,P=N.append({type:"compaction",summary:z.summary,...z.carryover!==void 0?{carryover:z.carryover}:{},firstKeptEntryId:D,...U?{timestamp:U.timestamp}:{},trigger:"manual",contextTokensBefore:Y,contextTokensAfter:A,model:this.modelRef,compactorModel:`${J.model.provider}/${J.model.id}`,windowNumber:j,strategy:"summary-tail",keptTokens:l(z.keptMessages),toolResultsCleared:X.length,usage:z.usage});for(let n of q)N.appendMessage(n);let O=N.messagesAt(),C=l(O),g=Math.max(0,Y-C);return await this.store.save(this._sessionId,N),this.tree=N,this.totals=B1(this.totals,z.usage),K=!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:g,summaryEntryId:P.id,contextTokensBefore:Y,contextTokensAfter:C,toolResultsCleared:X.length,keptTokens:l(z.keptMessages)}),Z({type:"agent_end",messages:O,reason:"done"}),{status:"completed",message:`Context compacted: ${Y.toLocaleString()} \u2192 ${C.toLocaleString()} tokens (${g.toLocaleString()} freed).`,tokensBefore:Y,tokensAfter:C,tokensFreed:g,toolResultsCleared:X.length,summaryEntryId:P.id}}catch(V){let z=B??(V instanceof h0?V.usage:void 0);if(z&&!K)this.tree.append({type:"compaction-attempt",status:this.controller.signal.aborted?"cancelled":"failed",trigger:"manual",model:this.modelRef,compactorModel:`${J.model.provider}/${J.model.id}`,timestamp:Date.now(),usage:z}),await this.store.save(this._sessionId,this.tree).catch(()=>{}),this.totals=B1(this.totals,z),Z({type:"usage_updated",sessionTotals:this.totals,contextTokens:Y,contextPercent:this.model.contextWindow>0?Y/this.model.contextWindow:0});let F=this.controller.signal.aborted,L=F?"Compaction cancelled \u2014 original conversation preserved.":`Compaction failed: ${V instanceof Error?V.message:String(V)} Original conversation preserved.`;return Z({type:"compaction_end",layer:2,trigger:"manual",status:F?"cancelled":"failed",tokensFreed:0,contextTokensBefore:Y,contextTokensAfter:Y,errorMessage:L}),Z({type:"agent_end",messages:Q,reason:F?"aborted":"done"}),{status:F?"cancelled":"failed",message:L,tokensBefore:Y,tokensAfter:Y,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(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let Y;try{Y=await $.snapshot("before undo of last turn")}catch(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}if(!Y)return{ok:!1,message:"Could not undo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.beforeRef,Q)}catch(V){let z=await this.restoreCheckpointResources($,Y,Q).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 W=this.tree,G=s.fromJsonl(W.toJsonl());G.fork(Z.beforeEntryId);let X=this.checkpoints.state(),J=X.done.slice(0,-1),B=[...X.undone,{...Z,redoRef:Y}];this.appendCheckpointCursor(G,J,B);try{await this.store.save(this._sessionId,G)}catch(V){return await this.restoreCheckpointResources($,Y,Q).catch(()=>{}),await this.store.save(this._sessionId,W).catch(()=>{}),{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let K=this.checkpointDetails(Z);return this.checkpoints.restore(J,B),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Undid the last turn.",data:{kind:"checkpoint",action:"undo",files:Q,messageCount:K.messageCount,...K.prompt!==void 0?{prompt:K.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 Y;try{Y=await $.snapshot("before redo of last turn")}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}if(!Y)return{ok:!1,message:"Could not redo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.redoRef??Z.afterRef,Q)}catch(F){let L=await this.restoreCheckpointResources($,Y,Q).then(()=>{return}).catch((D)=>D);return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}${L?`; rollback failed: ${L instanceof Error?L.message:String(L)}`:""}`}}let W=this.tree,G=s.fromJsonl(W.toJsonl());G.fork(Z.id);let X=this.checkpoints.state(),{redoRef:J,...B}=Z,K=[...X.done,B],V=X.undone.slice(0,-1);this.appendCheckpointCursor(G,K,V);try{await this.store.save(this._sessionId,G)}catch(F){return await this.restoreCheckpointResources($,Y,Q).catch(()=>{}),await this.store.save(this._sessionId,W).catch(()=>{}),{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let z=this.checkpointDetails(Z);return this.checkpoints.restore(K,V),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Redid the turn.",data:{kind:"checkpoint",action:"redo",files:Q,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 Q=Z.message;if(Q.role==="toolResult")continue;if(Q.role==="assistant"&&Q.content.some((G)=>G.type==="toolCall"))continue;let Y=Q.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").replace(/\s+/g," ").trim(),W=Q.role==="assistant"?"mu":Q.role;$.push({id:Z.id,description:`${W} \xB7 ${Y.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=s.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=[],Y=[],W=!1,G=(J)=>{let B=Y.shift();if(B)B({value:J,done:!1});else Q.push(J)},X=this.execute($,Z,G).finally(()=>{W=!0;while(Y.length>0)Y.shift()?.({value:void 0,done:!0})});return{async*[Symbol.asyncIterator](){for(;;){if(Q.length>0){yield Q.shift();continue}if(W)return;let J=await new Promise((B)=>Y.push(B));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 W={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(W);let G=this.checkpoints.state();this.appendCheckpointCursor(this.tree,G.done,G.undone)}appendCheckpointCursor($,Z,Q){let Y=(W)=>({id:W.id,...W.redoRef?{redoRef:W.redoRef}:{}});$.append({type:"custom",customType:"checkpoint-cursor",data:{done:Z.map(Y),undone:Q.map(Y)}})}async restoreCheckpointResources($,Z,Q){if(Q.length===0)return;let Y=Q.map((W)=>W.path);if($.restoreResources){await $.restoreResources(Z,Y);return}await $.restore(Z)}checkpointDetails($){let Z=this.tree.pathTo($.id),Q=$.beforeEntryId?Z.findIndex((X)=>X.id===$.beforeEntryId):-1,Y=Z.slice(Q+1),W=Y.find((X)=>X.type==="message"&&X.message.role==="user"),G=W?.type==="message"?W.message.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
|
|
126
|
-
`):void 0;return{messageCount:Y.filter((X)=>X.type==="message").length,...G!==void 0?{prompt:G}:{}}}rebuildCheckpointHistory(){let $=new Map;for(let W of this.tree.all()){if(W.type!=="checkpoint")continue;$.set(W.id,{id:W.id,beforeEntryId:W.beforeEntryId,beforeRef:W.checkpointRef,afterRef:W.checkpointAfterRef,...W.label?{label:W.label}:{}})}let Z=this.tree.activePath(),Q=Z.findLastIndex((W)=>W.type==="custom"&&W.customType==="checkpoint-cursor"),Y=Q===-1?void 0:Z[Q];if(Y?.type==="custom"){let W=Y.data,G=(B)=>Array.isArray(B)?B.map((K)=>{let V=typeof K==="string"?K:typeof K==="object"&&K!==null&&typeof K.id==="string"?K.id:void 0,z=V?$.get(V):void 0;if(!z)return;let F=typeof K==="object"&&K!==null&&typeof K.redoRef==="string"?K.redoRef:void 0;return{...z,...F?{redoRef:F}:{}}}).filter((K)=>K!==void 0):[],X=G(W.done),J=G(W.undone);for(let B of Z.slice(Q+1)){if(B.type!=="checkpoint")continue;let K=$.get(B.id);if(K)X.push(K);J=[]}this.checkpoints.restore(X,J);return}this.checkpoints.restore(Z.filter((W)=>W.type==="checkpoint").map((W)=>$.get(W.id)).filter((W)=>W!==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 Y=(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=Y;let W=this.executeRun($,Z,Y).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=W,W}async executeRun($,Z,Q){this.controller=new AbortController,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1;let Y=this.options.extensions,W=$;if(typeof $==="string"&&Y){Y.emitLifecycle({type:"input",text:$});let w=await Y.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 o of _)Q(o);return{text:"",messages:[],usage:this.totals,reason:"done",sessionId:this._sessionId}}if(w?.text!==void 0)W=w.text}let G=typeof W==="string"?G$(W):{role:"user",content:W,timestamp:Date.now()},X,J=[...this.options.tools??[],...Y?[...Y.tools.values()]:[]];if(Z?.allowedTools){let w=new Set(J.map((h)=>h.name)),_=Z.allowedTools.filter((h)=>!w.has(h));if(_.length>0)throw Error(`Unknown allowed tool${_.length===1?"":"s"}: ${_.join(", ")}`);let o=new Set(Z.allowedTools);J=J.filter((h)=>o.has(h.name))}let B=Z?.model?t$(Z.model,this.options.extensions):this.model,K=Z?.model?this.providerFor(B):this.provider,V=a0(B,this.currentThinking),z=Z?.model?void 0:this.lastContextUsage;if(Z?.model)this.lastContextUsage=void 0;let F=kH(this.options.systemPrompt);if(Z?.output)J.push(O8(Z.output,(w)=>{X=w})),F.push({text:M8(),dynamic:!0});let L=this.tree.messagesAt(),D=L.length===0&&this.options.initialMessages?this.options.initialMessages:[];for(let w of D)this.tree.appendMessage(w);let U=await this.options.refreshContext?.([...L,...D],{sessionId:this._sessionId})??[];for(let w of U)this.tree.appendMessage(w);let q={systemPrompt:F,messages:[...L,...D,...U],...J.length>0?{tools:J}:{}};await this.beginCheckpoint(this.tree.head);let A,N=(w)=>h$(B,w,z?.usage,z?.estimatedTokensAtUsage),j=(w,_,o)=>{if(this.totals=B1(this.totals,w),o){if(z={usage:w,estimatedTokensAtUsage:l(o)},!Z?.model)this.lastContextUsage=z}let h=N(_);this.lastContextPercent=h.percent,this.lastContextTokens=h.tokens,Q({type:"usage_updated",sessionTotals:this.totals,contextTokens:h.tokens,contextPercent:h.percent});let t=N8(this.options.budget,this.totals);if(t)A=t;return t},P=this.options.getCredentials,O={provider:K,model:B,streamOpts:{sessionId:this._sessionId,...this.options.apiKey?{apiKey:this.options.apiKey}:{},...P?{getCredentials:()=>P(B.provider)}:{}},thinkingLevel:V,...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===X$)return;let _=w.args;if(Y){let A0=await Y.runToolCallHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,args:_});if(A0?.block)return{block:!0,reason:A0.reason??"Blocked by an extension"};if(A0?.args)_=A0.args}let o=J.find((A0)=>A0.name===w.toolCall.name),h=w.toolCall.name;try{h=o?.permissionScope?.(_)??h}catch{}let t=JSON.stringify(_);try{t=o?.permissionPattern?.(_)??t}catch{}let hZ=h===w.toolCall.name?[w.toolCall.name]:[w.toolCall.name,h],W1=s6(this.permissionRules,hZ,t),S$=_===w.args?void 0:{rewrittenArgs:_};if(W1==="allow")return S$;if(W1==="deny")return{block:!0,reason:`Permission denied for ${w.toolCall.name}`};let I0=await Promise.resolve(o?.permissionDetails?.(_)).catch(()=>{return}),l0={id:`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,toolCallId:w.toolCall.id,toolName:w.toolCall.name,permission:h,pattern:t,description:I0?.description??`Run ${w.toolCall.name}`,...I0?.preview?{preview:I0.preview}:{}};Q({type:"permission_asked",request:l0});let n1="deny";if(this.options.onPermission&&!this.controller.signal.aborted){let A0=this.controller.signal,u,H0=new Promise((R1)=>{u=()=>R1("deny"),A0.addEventListener("abort",u,{once:!0})});try{n1=await Promise.race([this.options.onPermission(l0),H0])}finally{if(u)A0.removeEventListener("abort",u)}}if(Q({type:"permission_resolved",requestId:l0.id,outcome:n1}),n1==="allow")return S$;return{block:!0,reason:`Permission denied for ${w.toolCall.name}`}},prepareContext:async(w)=>{let _=N(w);this.lastContextPercent=_.percent,this.lastContextTokens=_.tokens;let o=this.options.autoCompact!==!1,h=w;if(o&&_.percent>=o6&&!this.compactRequested){let u=sZ(h,{targetTokens:Math.floor(B.contextWindow*(this.options.compactThreshold??S1)*0.8)});if(u.evicted>0){let H0=u.messages.flatMap((v0,a1)=>{let r1=h[a1];if(!r1||v0===r1)return[];let T6=this.tree.entryIdForMessage(r1);return T6?[{entryId:T6,message:v0}]:[]}),R1=u.messages.filter((v0,a1)=>v0!==h[a1]).length;if(H0.length===R1){Q({type:"compaction_start",layer:1}),this.tree.append({type:"microcompaction",replacements:H0}),h=u.messages,z=void 0,this.lastContextUsage=void 0;let v0=N(h);this.lastContextPercent=v0.percent,this.lastContextTokens=v0.tokens,Q({type:"compaction_end",layer:1,tokensFreed:u.tokensFreed})}}}let t=N(h);if(!(this.compactRequested||o&&d6(t,this.options.compactThreshold??S1)))return{messages:h};let W1=this.reactiveRecoveryPending?"overflow":this.compactorOverride?"model-change":this.compactRequested?"manual":"threshold",S$=this.compactRequestedFocus,I0=this.compactorOverride??{model:B,provider:K};this.compactRequested=!1,this.compactRequestedFocus=void 0,this.compactorOverride=void 0;let l0=this.reactiveRecoveryPending?3:2;if(l0===2)Q({type:"compaction_start",layer:l0,trigger:W1,contextTokensBefore:t.tokens});let n1,A0=!1;try{Q({type:"compaction_update",layer:l0,stage:"summarizing"});let u=await rZ(h,{provider:I0.provider,model:I0.model,keepRecentTokens:Math.min(W$,Math.max(2,Math.floor(B.contextWindow*0.2))),...O.streamOpts?{streamOpts:{...O.streamOpts,...P?{getCredentials:()=>P(I0.model.provider)}:{}}}:{},...this.options.carryoverExtractor?{carryoverExtractor:this.options.carryoverExtractor}:{},...S$?{customInstructions:S$}:{},signal:this.controller.signal});n1=u.usage;let H0=u$(u),R1;if(u.summary.length>0){let v0=u.keptMessages[0],a1=null;if(v0){let uZ=this.tree.entryIdForMessage(v0);if(!uZ)throw Error("Compaction tail could not be mapped to the session");a1=uZ}let r1=H0[0];R1=this.tree.append({type:"compaction",summary:u.summary,...u.carryover!==void 0?{carryover:u.carryover}:{},firstKeptEntryId:a1,...r1?{timestamp:r1.timestamp}:{},trigger:W1,contextTokensBefore:t.tokens,contextTokensAfter:l(H0),model:`${B.provider}/${B.id}`,compactorModel:`${I0.model.provider}/${I0.model.id}`,windowNumber:this.tree.activePath().filter((uZ)=>uZ.type==="compaction").length+1,strategy:"summary-tail",keptTokens:l(u.keptMessages),usage:u.usage}).id}return z=void 0,this.lastContextUsage=void 0,j(u.usage,H0),A0=!0,Q({type:"compaction_end",layer:l0,tokensFreed:u.tokensFreed,trigger:W1,status:u.summary.length>0?"completed":"noop",contextTokensBefore:t.tokens,contextTokensAfter:N(H0).tokens,keptTokens:l(u.keptMessages),...R1?{summaryEntryId:R1}:{}}),this.reactiveRecoveryPending=!1,{messages:H0,stop:A!==void 0}}catch(u){let H0=n1??(u instanceof h0?u.usage:void 0);if(H0&&!A0)this.tree.append({type:"compaction-attempt",status:this.controller.signal.aborted?"cancelled":"failed",trigger:W1,model:`${B.provider}/${B.id}`,compactorModel:`${I0.model.provider}/${I0.model.id}`,timestamp:Date.now(),usage:H0}),j(H0,h);return Q({type:"compaction_end",layer:l0,tokensFreed:0,trigger:W1,status:this.controller.signal.aborted?"cancelled":"failed",contextTokensBefore:t.tokens,contextTokensAfter:t.tokens,errorMessage:u instanceof Error?u.message:"Compaction failed for an unknown reason"}),this.reactiveRecoveryPending=!1,{messages:h,stop:A!==void 0}}},...Y?{transformContext:(w)=>Y.runContextHooks(w)}:{},...Y?{afterToolCall:async(w)=>{let _=await Y.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||!v$(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 a6([G],q,O,async(w)=>{if(Q(w),w.type==="message_end")this.tree.appendMessage(w.message);if(w.type==="message_end"&&w.message===G||w.type==="turn_end")await this.store.save(this._sessionId,this.tree)},this.controller.signal)}finally{await this.finishCheckpoint()}})();await this.store.save(this._sessionId,this.tree);let g=A??(C.reason==="budget"?"maxCostUsd":C.reason),n={text:fH(C.messages),messages:C.messages,usage:this.totals,reason:g,sessionId:this._sessionId};if(!Z?.output)return n;if(X===void 0)throw Error(`Structured output was requested but the model never produced a valid one (run ended: ${g}).`);return{...n,output:X}}providerFor($){return this.options.provider??this.options.extensions?.providers.get($.provider)??f6($.provider)}publishEvent($){if(this.activeEmit){this.activeEmit($);return}this.publishToSubscribers($),this.options.extensions?.emit($)}refreshContextAccounting(){let $=h$(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){let Y=(this.subscriberQueues.get(Z)??Promise.resolve()).then(()=>Z($)).catch(()=>{});this.subscriberQueues.set(Z,Y),Y.finally(()=>{if(this.subscriberQueues.get(Z)===Y&&!this.subscribers.has(Z))this.subscriberQueues.delete(Z)})}}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 hH,randomBytes as F5}from"crypto";import{chmod as w8,mkdir as uH,readFile as mH,rename as lH,stat as pH,unlink as cH,writeFile as dH}from"fs/promises";import{createServer as H7}from"http";import{homedir as iH}from"os";import{dirname as nH,join as V7}from"path";var vH=[{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 j8($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function gH(){return`<svg class="mark" viewBox="0 0 10 5" role="img" aria-label="mu">${vH.map((Z)=>`<rect x="${Z.x}" y="${Z.y}" width="${Z.w}" height="${Z.h}"/>`).join("")}</svg>`}function P8($){let Z=$.status==="success"?"#fff":"#f87171";return`<!doctype html>
|
|
129
|
+
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{createHash as LH}from"crypto";import{readFileSync as DH,statSync as UH}from"fs";import{resolve as Y5}from"path";function qH($){return LH("sha256").update($).digest("hex")}function aQ($,Z){try{let Q=UH($);return{exists:!0,device:Q.dev,inode:Q.ino,size:Q.size,mtimeMs:Q.mtimeMs,ctimeMs:Q.ctimeMs,digest:qH(Z??DH($))}}catch{return{exists:!1}}}class W5{reads=new Map;modified=new Set;markRead($,Z){let Q=Y5($);this.reads.set(Q,aQ(Q,Z))}markWritten($){let Z=Y5($);this.modified.add(Z),this.markRead(Z)}hasRead($){return this.reads.has(Y5($))}isStale($,Z){let Q=Y5($),Y=this.reads.get(Q);if(Y===void 0)return!1;let W=aQ(Q,Z);return W.exists!==Y.exists||W.device!==Y.device||W.inode!==Y.inode||W.size!==Y.size||W.mtimeMs!==Y.mtimeMs||W.ctimeMs!==Y.ctimeMs||W.digest!==Y.digest}readFiles(){return[...this.reads.keys()]}modifiedFiles(){return[...this.modified]}}import{randomUUID as NH}from"crypto";function rQ($){return $.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens}function L4($,Z){if(!$)return;if($.maxCostUsd!==void 0&&(Z.costUsd??0)>=$.maxCostUsd)return"maxCostUsd";if($.maxTokens!==void 0&&rQ(Z)>=$.maxTokens)return"maxTokens";return}import{z as AH}from"zod";var Y$="structured_output";function D4($,Z){let Q=AH.toJSONSchema($,{io:"input"});return{name:Y$,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(Y,W)=>{let G=$.safeParse(W);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 ${Y$} again with corrected values.`}],isError:!0};return Z(G.data),{content:[{type:"text",text:"Final answer recorded."}],terminate:!0}}}}function U4(){return`When you have the final answer, call the ${Y$} tool with it. That call ends the task.`}var MH=[{permission:"*",pattern:"*",action:"allow"}],OH="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 i$($,Z){if($&&typeof $!=="string")return $;let Q=$??e1(),Y=Z?.findModel(Q)??mZ(Q);if(!Y)throw Error(`Unknown model: ${Q}. Pass a ModelInfo to use a custom model.`);return Y}function jH($){if($===void 0)return[{text:OH}];return typeof $==="string"?[{text:$}]:$}function PH($){for(let Z=$.length-1;Z>=0;Z--){let Q=$[Z];if(Q?.role!=="assistant")continue;let Y=Q.content.filter((W)=>W.type==="text").map((W)=>W.text).join("");if(Y.trim().length>0)return Y}return""}function tQ(){return`s${Date.now().toString(36)}-${NH().slice(0,8)}`}class n${options;model;provider;store;tree;_sessionId;controller=new AbortController;steering=[];followUps=[];totals=S$();compactRequested=!1;compactRequestedFocus;queuedManualCompactionFocus;manualCompactionQueued=!1;compacting=!1;compactorOverride;lastContextPercent=0;lastContextTokens=0;lastContextUsage;checkpoints=new fZ;recoveryAttempted=!1;reactiveRecoveryPending=!1;pendingCheckpoint;currentThinking;running=!1;stopping=!1;activeEmit;activeExecution;autonomousScheduled=!1;subscribers=new Set;subscriberQueues=new Map;idleWaiters=new Set;shutdownPromise;sessionStarted=!1;permissionRules;constructor($={}){this.options=$,this.permissionRules=[...$.permissions??MH],this.model=i$($.model,$.extensions),this.currentThinking=i0(this.model,$.thinkingLevel),this.provider=this.providerFor(this.model),this.store=$.session??new u$,this._sessionId=$.sessionId??tQ(),this.tree=new o({type:"session",version:h$,id:this._sessionId,createdAt:new Date().toISOString(),profile:$.sessionProfile??"default",environment:{...$.sessionEnvironment??{}}}),$.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 $$(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=i$($,this.options.extensions),Y=this.tree.messagesAt();if(Y.length>0&&l(Y)>=Q.contextWindow*(this.options.compactThreshold??E1))this.compactRequested=!0,this.compactorOverride=Z;this.model=Q,this.provider=this.providerFor(Q);let W=i0(Q,this.currentThinking),G=W!==this.currentThinking;this.currentThinking=W,this.lastContextUsage=void 0,this.refreshContextAccounting(),this.tree.append({type:"settings-change",model:this.modelRef,...G?{thinkingLevel:W}:{}}),this.options.extensions?.emitLifecycle({type:"model_select",model:this.modelRef})}setThinking($){let Z=i0(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;try{Z=o.fromJsonl($.toJsonl())}catch(W){throw Error("Cannot resume an invalid or unsupported session.",{cause:W})}let Q=Z.header;if(!Q||Q.version!==h$)throw Error("Cannot resume an invalid or unsupported session.");this.tree=Z,this._sessionId=Q.id;let Y=S$();for(let W of Z.all())if(W.type==="message"&&W.message.role==="assistant")Y=J1(Y,W.message.usage);else if(W.type==="compaction"&&W.usage)Y=J1(Y,W.usage);else if(W.type==="compaction-attempt")Y=J1(Y,W.usage);this.totals=Y,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=i$(this.options.model,this.options.extensions),this.provider=this.providerFor(this.model),this.currentThinking=i0(this.model,this.options.thinkingLevel);for(let W of Z.activePath()){if(W.type!=="settings-change")continue;if(W.model)try{this.model=i$(W.model,this.options.extensions),this.provider=this.providerFor(this.model)}catch{}if(typeof W.thinkingLevel==="string"&&W.thinkingLevel.length>0)this.currentThinking=W.thinkingLevel}this.currentThinking=i0(this.model,this.currentThinking),this.rebuildCheckpointHistory(),this.refreshContextAccounting()}newSession($=tQ()){if(this.running)throw Error("Cannot start a new session while a run is active.");this._sessionId=$,this.tree=new o({type:"session",version:h$,id:$,createdAt:new Date().toISOString(),profile:this.options.sessionProfile??"default",environment:{...this.options.sessionEnvironment??{}}}),this.tree.append({type:"settings-change",model:this.modelRef,thinkingLevel:this.currentThinking}),this.totals=S$(),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(Q$($))}followUp($){if(this.stopping)return;if(this.followUps.push(Q$($)),!this.running)this.scheduleAutonomousRun()}removeQueuedMessage($,Z){let Q=$==="steer"?this.steering:this.followUps;for(let Y=Q.length-1;Y>=0;Y--){let W=Q[Y];if(W?.role!=="user")continue;if(W.content.filter((X)=>X.type==="text").map((X)=>X.text).join("")!==Z)continue;return Q.splice(Y,1),this.resolveIdleIfDone(),!0}return!1}emitTaskEvent($){this.publishEvent($)}subscribe($){return this.subscribers.add($),()=>{this.subscribers.delete($),this.subscriberQueues.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=(W)=>{if(this.publishToSubscribers(W),W.type==="agent_start"&&!this.sessionStarted)this.sessionStarted=!0,this.options.extensions?.emitLifecycle({type:"session_start",sessionId:this._sessionId});this.options.extensions?.emit(W)};this.activeEmit=Q;let Y=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=Y,Y}async executeManualCompaction($,Z){Z({type:"agent_start"});let Q=this.tree.messagesAt(),Y=k$(this.model,Q,this.lastContextUsage?.usage,this.lastContextUsage?.estimatedTokensAtUsage).tokens;Z({type:"compaction_start",layer:2,trigger:"manual",contextTokensBefore:Y});let W=nZ(Q,{targetTokens:Math.floor(this.model.contextWindow*(this.options.compactThreshold??E1)*0.8)}),G=Q,X=[];if(W.evicted>0){Z({type:"compaction_update",layer:2,stage:"clearing-tool-output",toolResultsCleared:W.evicted}),X=W.messages.flatMap((z,F)=>{let D=Q[F];if(!D||z===D)return[];let L=this.tree.entryIdForMessage(D);return L?[{entryId:L,message:z}]:[]});let V=W.messages.filter((z,F)=>z!==Q[F]).length;if(X.length===V)G=W.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 B,K=!1;try{let V=this.options.getCredentials,z=await cZ(G,{provider:J.provider,model:J.model,keepRecentTokens:Math.min(Z$,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}:{},...V?{getCredentials:()=>V(J.model.provider)}:{}}});if(B=z.usage,z.summary.length===0){let n=l(Q);return Z({type:"compaction_end",layer:2,trigger:"manual",status:"noop",tokensFreed:0,contextTokensBefore:Y,contextTokensAfter:n}),Z({type:"agent_end",messages:Q,reason:"done"}),{status:"noop",message:"Context is already compact enough \u2014 no changes made.",tokensBefore:Y,tokensAfter:n,tokensFreed:0}}Z({type:"compaction_update",layer:2,stage:"installing"});let F=f$(z),D=z.keptMessages[0],L=null;if(D){let n=G.indexOf(D),w=n===-1?D:Q[n],_=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=l([...F,...q]),N=o.fromJsonl(this.tree.toJsonl());if(X.length>0)N.append({type:"microcompaction",replacements:X});let j=N.activePath().filter((n)=>n.type==="compaction").length+1,P=N.append({type:"compaction",summary:z.summary,...z.carryover!==void 0?{carryover:z.carryover}:{},firstKeptEntryId:L,...U?{timestamp:U.timestamp}:{},trigger:"manual",contextTokensBefore:Y,contextTokensAfter:A,model:this.modelRef,compactorModel:`${J.model.provider}/${J.model.id}`,windowNumber:j,strategy:"summary-tail",keptTokens:l(z.keptMessages),toolResultsCleared:X.length,usage:z.usage});for(let n of q)N.appendMessage(n);let M=N.messagesAt(),S=l(M),g=Math.max(0,Y-S);return await this.store.save(this._sessionId,N),this.tree=N,this.totals=J1(this.totals,z.usage),K=!0,this.lastContextUsage=void 0,this.lastContextPercent=this.model.contextWindow>0?S/this.model.contextWindow:0,this.lastContextTokens=S,Z({type:"usage_updated",sessionTotals:this.totals,contextTokens:S,contextPercent:this.lastContextPercent}),Z({type:"compaction_end",layer:2,trigger:"manual",status:"completed",tokensFreed:g,summaryEntryId:P.id,contextTokensBefore:Y,contextTokensAfter:S,toolResultsCleared:X.length,keptTokens:l(z.keptMessages)}),Z({type:"agent_end",messages:M,reason:"done"}),{status:"completed",message:`Context compacted: ${Y.toLocaleString()} \u2192 ${S.toLocaleString()} tokens (${g.toLocaleString()} freed).`,tokensBefore:Y,tokensAfter:S,tokensFreed:g,toolResultsCleared:X.length,summaryEntryId:P.id}}catch(V){let z=B??(V instanceof v0?V.usage:void 0);if(z&&!K)this.tree.append({type:"compaction-attempt",status:this.controller.signal.aborted?"cancelled":"failed",trigger:"manual",model:this.modelRef,compactorModel:`${J.model.provider}/${J.model.id}`,timestamp:Date.now(),usage:z}),await this.store.save(this._sessionId,this.tree).catch(()=>{}),this.totals=J1(this.totals,z),Z({type:"usage_updated",sessionTotals:this.totals,contextTokens:Y,contextPercent:this.model.contextWindow>0?Y/this.model.contextWindow:0});let F=this.controller.signal.aborted,D=F?"Compaction cancelled \u2014 original conversation preserved.":`Compaction failed: ${V instanceof Error?V.message:String(V)} Original conversation preserved.`;return Z({type:"compaction_end",layer:2,trigger:"manual",status:F?"cancelled":"failed",tokensFreed:0,contextTokensBefore:Y,contextTokensAfter:Y,errorMessage:D}),Z({type:"agent_end",messages:Q,reason:F?"aborted":"done"}),{status:F?"cancelled":"failed",message:D,tokensBefore:Y,tokensAfter:Y,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(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let Y;try{Y=await $.snapshot("before undo of last turn")}catch(V){return{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}if(!Y)return{ok:!1,message:"Could not undo: failed to capture current state."};try{await this.restoreCheckpointResources($,Z.beforeRef,Q)}catch(V){let z=await this.restoreCheckpointResources($,Y,Q).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 W=this.tree,G=o.fromJsonl(W.toJsonl());G.fork(Z.beforeEntryId);let X=this.checkpoints.state(),J=X.done.slice(0,-1),B=[...X.undone,{...Z,redoRef:Y}];this.appendCheckpointCursor(G,J,B);try{await this.store.save(this._sessionId,G)}catch(V){return await this.restoreCheckpointResources($,Y,Q).catch(()=>{}),await this.store.save(this._sessionId,W).catch(()=>{}),{ok:!1,message:`Could not undo: ${V instanceof Error?V.message:String(V)}`}}let K=this.checkpointDetails(Z);return this.checkpoints.restore(J,B),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Undid the last turn.",data:{kind:"checkpoint",action:"undo",files:Q,messageCount:K.messageCount,...K.prompt!==void 0?{prompt:K.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 Y;try{Y=await $.snapshot("before redo of last turn")}catch(F){return{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}if(!Y)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($,Y,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 W=this.tree,G=o.fromJsonl(W.toJsonl());G.fork(Z.id);let X=this.checkpoints.state(),{redoRef:J,...B}=Z,K=[...X.done,B],V=X.undone.slice(0,-1);this.appendCheckpointCursor(G,K,V);try{await this.store.save(this._sessionId,G)}catch(F){return await this.restoreCheckpointResources($,Y,Q).catch(()=>{}),await this.store.save(this._sessionId,W).catch(()=>{}),{ok:!1,message:`Could not redo: ${F instanceof Error?F.message:String(F)}`}}let z=this.checkpointDetails(Z);return this.checkpoints.restore(K,V),this.tree=G,this.refreshContextAccounting(),{ok:!0,message:"Redid the turn.",data:{kind:"checkpoint",action:"redo",files:Q,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 Q=Z.message;if(Q.role==="toolResult")continue;if(Q.role==="assistant"&&Q.content.some((G)=>G.type==="toolCall"))continue;let Y=Q.content.filter((G)=>G.type==="text").map((G)=>G.text).join("").replace(/\s+/g," ").trim(),W=Q.role==="assistant"?"mu":Q.role;$.push({id:Z.id,description:`${W} \xB7 ${Y.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=o.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=[],Y=[],W=!1,G=(J)=>{let B=Y.shift();if(B)B({value:J,done:!1});else Q.push(J)},X=this.execute($,Z,G).finally(()=>{W=!0;while(Y.length>0)Y.shift()?.({value:void 0,done:!0})});return{async*[Symbol.asyncIterator](){for(;;){if(Q.length>0){yield Q.shift();continue}if(W)return;let J=await new Promise((B)=>Y.push(B));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 W={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(W);let G=this.checkpoints.state();this.appendCheckpointCursor(this.tree,G.done,G.undone)}appendCheckpointCursor($,Z,Q){let Y=(W)=>({id:W.id,...W.redoRef?{redoRef:W.redoRef}:{}});$.append({type:"custom",customType:"checkpoint-cursor",data:{done:Z.map(Y),undone:Q.map(Y)}})}async restoreCheckpointResources($,Z,Q){if(Q.length===0)return;let Y=Q.map((W)=>W.path);if($.restoreResources){await $.restoreResources(Z,Y);return}await $.restore(Z)}checkpointDetails($){let Z=this.tree.pathTo($.id),Q=$.beforeEntryId?Z.findIndex((X)=>X.id===$.beforeEntryId):-1,Y=Z.slice(Q+1),W=Y.find((X)=>X.type==="message"&&X.message.role==="user"),G=W?.type==="message"?W.message.content.filter((X)=>X.type==="text").map((X)=>X.text).join(`
|
|
130
|
+
`):void 0;return{messageCount:Y.filter((X)=>X.type==="message").length,...G!==void 0?{prompt:G}:{}}}rebuildCheckpointHistory(){let $=new Map;for(let W of this.tree.all()){if(W.type!=="checkpoint")continue;$.set(W.id,{id:W.id,beforeEntryId:W.beforeEntryId,beforeRef:W.checkpointRef,afterRef:W.checkpointAfterRef,...W.label?{label:W.label}:{}})}let Z=this.tree.activePath(),Q=Z.findLastIndex((W)=>W.type==="custom"&&W.customType==="checkpoint-cursor"),Y=Q===-1?void 0:Z[Q];if(Y?.type==="custom"){let W=Y.data,G=(B)=>Array.isArray(B)?B.map((K)=>{let V=typeof K==="string"?K:typeof K==="object"&&K!==null&&typeof K.id==="string"?K.id:void 0,z=V?$.get(V):void 0;if(!z)return;let F=typeof K==="object"&&K!==null&&typeof K.redoRef==="string"?K.redoRef:void 0;return{...z,...F?{redoRef:F}:{}}}).filter((K)=>K!==void 0):[],X=G(W.done),J=G(W.undone);for(let B of Z.slice(Q+1)){if(B.type!=="checkpoint")continue;let K=$.get(B.id);if(K)X.push(K);J=[]}this.checkpoints.restore(X,J);return}this.checkpoints.restore(Z.filter((W)=>W.type==="checkpoint").map((W)=>$.get(W.id)).filter((W)=>W!==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 Y=(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=Y;let W=this.executeRun($,Z,Y).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=W,W}async executeRun($,Z,Q){this.controller=new AbortController,this.recoveryAttempted=!1,this.reactiveRecoveryPending=!1;let Y=this.options.extensions,W=$;if(typeof $==="string"&&Y){Y.emitLifecycle({type:"input",text:$});let w=await Y.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 t of _)Q(t);return{text:"",messages:[],usage:this.totals,reason:"done",sessionId:this._sessionId}}if(w?.text!==void 0)W=w.text}let G=typeof W==="string"?Q$(W):{role:"user",content:W,timestamp:Date.now()},X,J=[...this.options.tools??[],...Y?[...Y.tools.values()]:[]];if(Z?.allowedTools){let w=new Set(J.map((h)=>h.name)),_=Z.allowedTools.filter((h)=>!w.has(h));if(_.length>0)throw Error(`Unknown allowed tool${_.length===1?"":"s"}: ${_.join(", ")}`);let t=new Set(Z.allowedTools);J=J.filter((h)=>t.has(h.name))}let B=Z?.model?i$(Z.model,this.options.extensions):this.model,K=Z?.model?this.providerFor(B):this.provider,V=i0(B,this.currentThinking),z=Z?.model?void 0:this.lastContextUsage;if(Z?.model)this.lastContextUsage=void 0;let F=jH(this.options.systemPrompt);if(Z?.output)J.push(D4(Z.output,(w)=>{X=w})),F.push({text:U4(),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)=>k$(B,w,z?.usage,z?.estimatedTokensAtUsage),j=(w,_,t)=>{if(this.totals=J1(this.totals,w),t){if(z={usage:w,estimatedTokensAtUsage:l(t)},!Z?.model)this.lastContextUsage=z}let h=N(_);this.lastContextPercent=h.percent,this.lastContextTokens=h.tokens,Q({type:"usage_updated",sessionTotals:this.totals,contextTokens:h.tokens,contextPercent:h.percent});let r=L4(this.options.budget,this.totals);if(r)A=r;return r},P=this.options.getCredentials,M={provider:K,model:B,streamOpts:{sessionId:this._sessionId,...this.options.apiKey?{apiKey:this.options.apiKey}:{},...P?{getCredentials:()=>P(B.provider)}:{}},thinkingLevel:V,...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===Y$)return;let _=w.args;if(Y){let A0=await Y.runToolCallHooks({toolName:w.toolCall.name,toolCallId:w.toolCall.id,args:_});if(A0?.block)return{block:!0,reason:A0.reason??"Blocked by an extension"};if(A0?.args)_=A0.args}let t=J.find((A0)=>A0.name===w.toolCall.name),h=w.toolCall.name;try{h=t?.permissionScope?.(_)??h}catch{}let r=JSON.stringify(_);try{r=t?.permissionPattern?.(_)??r}catch{}let xZ=h===w.toolCall.name?[w.toolCall.name]:[w.toolCall.name,h],Q1=n6(this.permissionRules,xZ,r),I$=_===w.args?void 0:{rewrittenArgs:_};if(Q1==="allow")return I$;if(Q1==="deny")return{block:!0,reason:`Permission denied for ${w.toolCall.name}`};let T0=await Promise.resolve(t?.permissionDetails?.(_)).catch(()=>{return}),u0={id:`p${Date.now().toString(36)}${Math.random().toString(36).slice(2,6)}`,toolCallId:w.toolCall.id,toolName:w.toolCall.name,permission:h,pattern:r,description:T0?.description??`Run ${w.toolCall.name}`,...T0?.preview?{preview:T0.preview}:{}};Q({type:"permission_asked",request:u0});let c1="deny";if(this.options.onPermission&&!this.controller.signal.aborted){let A0=this.controller.signal,u,H0=new Promise((T1)=>{u=()=>T1("deny"),A0.addEventListener("abort",u,{once:!0})});try{c1=await Promise.race([this.options.onPermission(u0),H0])}finally{if(u)A0.removeEventListener("abort",u)}}if(Q({type:"permission_resolved",requestId:u0.id,outcome:c1}),c1==="allow")return I$;return{block:!0,reason:`Permission denied for ${w.toolCall.name}`}},prepareContext:async(w)=>{let _=N(w);this.lastContextPercent=_.percent,this.lastContextTokens=_.tokens;let t=this.options.autoCompact!==!1,h=w;if(t&&_.percent>=i6&&!this.compactRequested){let u=nZ(h,{targetTokens:Math.floor(B.contextWindow*(this.options.compactThreshold??E1)*0.8)});if(u.evicted>0){let H0=u.messages.flatMap((k0,d1)=>{let i1=h[d1];if(!i1||k0===i1)return[];let O6=this.tree.entryIdForMessage(i1);return O6?[{entryId:O6,message:k0}]:[]}),T1=u.messages.filter((k0,d1)=>k0!==h[d1]).length;if(H0.length===T1){Q({type:"compaction_start",layer:1}),this.tree.append({type:"microcompaction",replacements:H0}),h=u.messages,z=void 0,this.lastContextUsage=void 0;let k0=N(h);this.lastContextPercent=k0.percent,this.lastContextTokens=k0.tokens,Q({type:"compaction_end",layer:1,tokensFreed:u.tokensFreed})}}}let r=N(h);if(!(this.compactRequested||t&&u6(r,this.options.compactThreshold??E1)))return{messages:h};let Q1=this.reactiveRecoveryPending?"overflow":this.compactorOverride?"model-change":this.compactRequested?"manual":"threshold",I$=this.compactRequestedFocus,T0=this.compactorOverride??{model:B,provider:K};this.compactRequested=!1,this.compactRequestedFocus=void 0,this.compactorOverride=void 0;let u0=this.reactiveRecoveryPending?3:2;if(u0===2)Q({type:"compaction_start",layer:u0,trigger:Q1,contextTokensBefore:r.tokens});let c1,A0=!1;try{Q({type:"compaction_update",layer:u0,stage:"summarizing"});let u=await cZ(h,{provider:T0.provider,model:T0.model,keepRecentTokens:Math.min(Z$,Math.max(2,Math.floor(B.contextWindow*0.2))),...M.streamOpts?{streamOpts:{...M.streamOpts,...P?{getCredentials:()=>P(T0.model.provider)}:{}}}:{},...this.options.carryoverExtractor?{carryoverExtractor:this.options.carryoverExtractor}:{},...I$?{customInstructions:I$}:{},signal:this.controller.signal});c1=u.usage;let H0=f$(u),T1;if(u.summary.length>0){let k0=u.keptMessages[0],d1=null;if(k0){let kZ=this.tree.entryIdForMessage(k0);if(!kZ)throw Error("Compaction tail could not be mapped to the session");d1=kZ}let i1=H0[0];T1=this.tree.append({type:"compaction",summary:u.summary,...u.carryover!==void 0?{carryover:u.carryover}:{},firstKeptEntryId:d1,...i1?{timestamp:i1.timestamp}:{},trigger:Q1,contextTokensBefore:r.tokens,contextTokensAfter:l(H0),model:`${B.provider}/${B.id}`,compactorModel:`${T0.model.provider}/${T0.model.id}`,windowNumber:this.tree.activePath().filter((kZ)=>kZ.type==="compaction").length+1,strategy:"summary-tail",keptTokens:l(u.keptMessages),usage:u.usage}).id}return z=void 0,this.lastContextUsage=void 0,j(u.usage,H0),A0=!0,Q({type:"compaction_end",layer:u0,tokensFreed:u.tokensFreed,trigger:Q1,status:u.summary.length>0?"completed":"noop",contextTokensBefore:r.tokens,contextTokensAfter:N(H0).tokens,keptTokens:l(u.keptMessages),...T1?{summaryEntryId:T1}:{}}),this.reactiveRecoveryPending=!1,{messages:H0,stop:A!==void 0}}catch(u){let H0=c1??(u instanceof v0?u.usage:void 0);if(H0&&!A0)this.tree.append({type:"compaction-attempt",status:this.controller.signal.aborted?"cancelled":"failed",trigger:Q1,model:`${B.provider}/${B.id}`,compactorModel:`${T0.model.provider}/${T0.model.id}`,timestamp:Date.now(),usage:H0}),j(H0,h);return Q({type:"compaction_end",layer:u0,tokensFreed:0,trigger:Q1,status:this.controller.signal.aborted?"cancelled":"failed",contextTokensBefore:r.tokens,contextTokensAfter:r.tokens,errorMessage:u instanceof Error?u.message:"Compaction failed for an unknown reason"}),this.reactiveRecoveryPending=!1,{messages:h,stop:A!==void 0}}},...Y?{transformContext:(w)=>Y.runContextHooks(w)}:{},...Y?{afterToolCall:async(w)=>{let _=await Y.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||!_$(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}},S=await(async()=>{try{return await p6([G],q,M,async(w)=>{if(Q(w),w.type==="message_end")this.tree.appendMessage(w.message);if(w.type==="message_end"&&w.message===G||w.type==="turn_end")await this.store.save(this._sessionId,this.tree)},this.controller.signal)}finally{await this.finishCheckpoint()}})();await this.store.save(this._sessionId,this.tree);let g=A??(S.reason==="budget"?"maxCostUsd":S.reason),n={text:PH(S.messages),messages:S.messages,usage:this.totals,reason:g,sessionId:this._sessionId};if(!Z?.output)return n;if(X===void 0)throw Error(`Structured output was requested but the model never produced a valid one (run ended: ${g}).`);return{...n,output:X}}providerFor($){return this.options.provider??this.options.extensions?.providers.get($.provider)??y6($.provider)}publishEvent($){if(this.activeEmit){this.activeEmit($);return}this.publishToSubscribers($),this.options.extensions?.emit($)}refreshContextAccounting(){let $=k$(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){let Y=(this.subscriberQueues.get(Z)??Promise.resolve()).then(()=>Z($)).catch(()=>{});this.subscriberQueues.set(Z,Y),Y.finally(()=>{if(this.subscriberQueues.get(Z)===Y&&!this.subscribers.has(Z))this.subscriberQueues.delete(Z)})}}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 IH,randomBytes as K5}from"crypto";import{chmod as N4,mkdir as RH,readFile as EH,rename as SH,stat as CH,unlink as yH,writeFile as bH}from"fs/promises";import{createServer as QY}from"http";import{homedir as _H}from"os";import{dirname as xH,join as YY}from"path";var wH=[{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 q4($){return $.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function TH(){return`<svg class="mark" viewBox="0 0 10 5" role="img" aria-label="mu">${wH.map((Z)=>`<rect x="${Z.x}" y="${Z.y}" width="${Z.w}" height="${Z.h}"/>`).join("")}</svg>`}function A4($){let Z=$.status==="success"?"#fff":"#f87171";return`<!doctype html>
|
|
127
131
|
<html lang="en">
|
|
128
132
|
<head>
|
|
129
133
|
<meta charset="utf-8">
|
|
130
134
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
131
135
|
<meta name="color-scheme" content="dark">
|
|
132
|
-
<title>mu \u2014 ${
|
|
136
|
+
<title>mu \u2014 ${q4($.heading.toLowerCase())}</title>
|
|
133
137
|
<style>
|
|
134
138
|
:root { color-scheme: dark; }
|
|
135
139
|
html, body { height: 100%; }
|
|
@@ -181,97 +185,92 @@ Prefer a small number of well-chosen tool calls over many exploratory ones. When
|
|
|
181
185
|
</head>
|
|
182
186
|
<body>
|
|
183
187
|
<main>
|
|
184
|
-
${
|
|
185
|
-
<h1>${
|
|
186
|
-
<p>${
|
|
188
|
+
${TH()}
|
|
189
|
+
<h1>${q4($.heading)}</h1>
|
|
190
|
+
<p>${q4($.detail)}</p>
|
|
187
191
|
</main>
|
|
188
192
|
</body>
|
|
189
193
|
</html>
|
|
190
|
-
`}function
|
|
191
|
-
`,{encoding:"utf8",mode:384,flag:"wx"}),await lH(W,Q),process.platform!=="win32")await w8(Q,384)}catch(G){throw await cH(W).catch(()=>{}),G}}async function QV($,Z,Q={}){let Y=$.trim(),W=Z.trim();if(!Y)throw Error("Provider is required");if(!W)throw Error("API key cannot be empty");let G=await o0(Q);G.providers[Y]={type:"apiKey",apiKey:W},G.activeProvider=Y,await e$(G,Q)}async function YV($,Z={}){let Q=$.trim();if(!Q)throw Error("Provider is required");let Y=await o0(Z);if(!Y.providers[Q])return!1;if(delete Y.providers[Q],Y.activeProvider===Q){let W=Object.keys(Y.providers)[0];if(W)Y.activeProvider=W;else delete Y.activeProvider}return await e$(Y,Z),!0}async function WV($={}){return Object.keys((await o0($)).providers)}async function GV($={}){let Z=await o0($);return Z.activeProvider&&Z.providers[Z.activeProvider]?Z.activeProvider:Object.keys(Z.providers)[0]}async function L5($,Z,Q){let Y=await o0(Q);Y.providers[$]=Z,Y.activeProvider=$,await e$(Y,Q)}function F7($){let Z=$.split(".")[1];if(!Z)return;try{let Q=JSON.parse(Buffer.from(Z,"base64url").toString("utf8"));return s$(Q)?Q:void 0}catch{return}}function G7($){let Z=F7($)?.[rH]?.chatgpt_account_id;return typeof Z==="string"&&Z.length>0?Z:void 0}function XV($){let Z=F7($)?.exp;return typeof Z==="number"&&Number.isFinite(Z)?Z*1000:void 0}function JV($,Z,Q){let Y=Q.trim()?`: ${Q.trim().slice(0,1000)}`:"";return Error(`OpenAI token ${$} failed (${Z.status})${Y}`)}async function D7($,Z){if(!$.ok)throw JV(Z,$,await $.text().catch(()=>""));let Q=await $.json();if(!s$(Q))throw Error(`OpenAI token ${Z} returned invalid JSON`);return Q}function L7($,Z,Q){let Y=typeof $.access_token==="string"?$.access_token:Q?.accessToken,W=typeof $.refresh_token==="string"?$.refresh_token:Q?.refreshToken,G=typeof $.id_token==="string"?$.id_token:Q?.idToken;if(!Y||!W)throw Error("OpenAI token response is missing access or refresh token");let X=G7(Y)??(G?G7(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,B=XV(Y)??(J!==void 0?Z+J:Z+3600000);return{type:"oauth",accessToken:Y,refreshToken:W,...G?{idToken:G}:{},expiresAt:B,accountId:X}}async function KV($,Z){let Q=(Z.openAiIssuer??z7).replace(/\/+$/,""),Y=await(Z.fetch??fetch)(`${Q}/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:Z.openAiClientId??T8,grant_type:"refresh_token",refresh_token:$.refreshToken}),signal:AbortSignal.timeout(k1)});return L7(await D7(Y,"refresh"),(Z.now??Date.now)(),$)}function X7($){return{type:"oauth",accessToken:$.accessToken,...$.accountId?{accountId:$.accountId}:{},...$.baseUrl?{baseUrl:$.baseUrl}:{},...$.availableModelIds?{availableModelIds:$.availableModelIds}:{}}}function J7($,Z,Q){return Z.expiresAt>Q+oH&&($!==R8||Z.availableModelIds!==void 0)}async function L1($,Z){let Q=await $.text(),Y;try{Y=JSON.parse(Q)}catch{throw Error(`${Z} returned invalid JSON (${$.status})`)}if(!$.ok){let W=typeof Y==="object"&&Y!==null?Y:{},G=W.error_description??W.message??W.error;throw Error(`${Z} failed (${$.status})${typeof G==="string"?`: ${G}`:""}`)}if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw Error(`${Z} returned invalid JSON`);return Y}function K7($,Z,Q=60000){let Y=typeof $.access_token==="string"?$.access_token:Z.accessToken,W=typeof $.refresh_token==="string"?$.refresh_token:Z.refreshToken,G=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in:3600;if(!Y||!W)throw Error("OAuth response is missing tokens");return{...Z,accessToken:Y,refreshToken:W,expiresAt:Date.now()+G*1000-Q}}function U7($){let Z=$.match(/(?:^|;)proxy-ep=([^;]+)/)?.[1];return Z?`https://${Z.replace(/^proxy\./,"api.")}`:"https://api.individual.githubcopilot.com"}function BV($){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 HV($){let Z=typeof $.policy==="object"&&$.policy!==null?$.policy:void 0,Q=typeof $.capabilities==="object"&&$.capabilities!==null?$.capabilities:void 0,Y=typeof Q?.supports==="object"&&Q.supports!==null?Q.supports:void 0;return $.model_picker_enabled===!0&&Z?.state!=="disabled"&&Y?.tool_calls!==!1}async function q7($,Z,Q,Y){let W=await Q(`${Z.replace(/\/+$/,"")}/models`,{headers:{accept:"application/json",authorization:`Bearer ${$}`,...D5,"x-github-api-version":tH},...Y?{signal:Y}:{}});return BV(await L1(W,"GitHub Copilot model discovery"))}async function A7($,Z,Q,Y){return(await q7($,Z,Q,Y)).filter(HV).map((W)=>W.id).filter((W)=>typeof W==="string"&&W.length>0)}async function N7($,Z,Q,Y){let W=await q7($,Z,Q,Y);return await Promise.all(W.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 ${$}`,...D5,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"}),...Y?{signal:Y}:{}}).catch(()=>{return})})),A7($,Z,Q,Y)}async function VV($,Z,Q){let Y=Q.fetch??fetch;if($==="kimi-coding"){let W=await Y("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(k1)});return K7(await L1(W,"Kimi Code token refresh"),Z)}if($==="xai"){let W=await Y("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(k1)});return K7(await L1(W,"xAI token refresh"),Z,300000)}if($===R8){let W=await Y("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${Z.refreshToken}`,...D5},signal:AbortSignal.timeout(k1)}),G=await L1(W,"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=U7(X),B=AbortSignal.timeout(k1),K=Z.availableModelIds?await A7(X,J,Y,B):await N7(X,J,Y,B);return{...Z,accessToken:X,expiresAt:G.expires_at*1000-300000,baseUrl:J,availableModelIds:K}}if($===D1){if(!Z.accountId)throw Error("OpenAI login is missing its ChatGPT account");return KV(Z,Q)}throw Error(`OAuth refresh is not implemented for provider "${$}"`)}function zV($={}){let Z=new Map;return async(Q)=>{let W=(await o0($)).providers[Q];if(!W)return;if(W.type==="apiKey")return{type:"apiKey",apiKey:W.apiKey};let G=($.now??Date.now)();if(J7(Q,W,G))return X7(W);let X=Z.get(Q);if(X)return X;let J=(async()=>{let B=await o0($),K=B.providers[Q];if(!K||K.type!=="oauth")throw Error(`${Q} login is no longer available`);let V=($.now??Date.now)(),z=J7(Q,K,V)?K:await VV(Q,K,$);if(z!==K)B.providers[Q]=z,await e$(B,$);return X7(z)})().finally(()=>{Z.delete(Q)});return Z.set(Q,J),J}}function O7(){let $=F5(64).toString("base64url");return{verifier:$,challenge:hH("sha256").update($).digest("base64url")}}function M7($,Z){return new Promise((Q,Y)=>{let W=(X)=>{$.off("listening",G),Y(X)},G=()=>{$.off("error",W);let X=$.address();if(!X||typeof X==="string"){Y(Error("Could not determine OAuth callback port"));return}Q(X.port)};$.once("error",W),$.once("listening",G),$.listen(Z,"127.0.0.1")})}async function FV($,Z,Q){if(Q.aborted)throw Error("OpenAI login cancelled");let Y=Z===void 0?eH:[Z],W;for(let G of Y){let X=()=>{},J=()=>{},B=new Promise((z,F)=>{X=z,J=F}),K=!1,V=H7((z,F)=>{let L=new URL(z.url??"/","http://localhost");if(F.setHeader("content-type","text/html; charset=utf-8"),L.pathname!=="/auth/callback"){F.statusCode=404,F.end(x1(V5,"That page does not exist."));return}if(L.searchParams.get("state")!==$){F.statusCode=400,F.end(x1(V5,"State mismatch. Return to mu and try again."));return}let D=L.searchParams.get("error"),U=L.searchParams.get("code");if(D||!U){if(F.statusCode=400,F.end(x1(V5,"Return to mu and try again.")),!K)K=!0,J(Error(`OpenAI login failed: ${D??"missing authorization code"}`));return}if(F.end(H5(V5)),!K)K=!0,X(U)});try{let z=await M7(V,G),F=()=>{if(!K)K=!0,J(Error("OpenAI login cancelled"));V.close()};if(Q.addEventListener("abort",F,{once:!0}),Q.aborted)F();return{redirectUri:`http://localhost:${z}/auth/callback`,callback:B.finally(()=>Q.removeEventListener("abort",F)),close:()=>V.close()}}catch(z){W=z,V.close()}}throw Error(`Could not start OpenAI login callback server: ${W instanceof Error?W.message:String(W)}`)}async function DV($={}){let Z=new AbortController,Q=()=>Z.abort();if($.signal?.addEventListener("abort",Q,{once:!0}),$.signal?.aborted)Z.abort();let Y=setTimeout(Q,$.timeoutMs??sH);Y.unref?.();let W=F5(32).toString("base64url"),G=O7(),X=($.openAiIssuer??z7).replace(/\/+$/,""),J;try{J=$.callbackServer?await $.callbackServer(W,Z.signal):await FV(W,$.port,Z.signal);let B=new URL(`${X}/oauth/authorize`);B.search=new URLSearchParams({response_type:"code",client_id:$.openAiClientId??T8,redirect_uri:J.redirectUri,scope:aH,code_challenge:G.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:W,originator:"mu"}).toString(),await $.onAuthUrl?.(B.toString());let K=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??T8,code:K,code_verifier:G.verifier,redirect_uri:J.redirectUri}),signal:Z.signal}),z=L7(await D7(V,"exchange"),($.now??Date.now)()),F=await o0($);return F.providers[D1]=z,F.activeProvider=D1,await e$(F,$),{provider:D1,accountId:z.accountId}}finally{clearTimeout(Y),$.signal?.removeEventListener("abort",Q),J?.close()}}function Y0($,Z,Q){let Y=$[Z];if(typeof Y!=="string"||Y.length===0)throw Error(`${Q} response is missing ${Z}`);return Y}function z5($,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 B7($,Z){let Q=z5($,Z);if(!Q.startsWith("https:"))throw Error(`${Z} returned an unsafe authorization URL`);return Q}function t0($,Z,Q){let Y=$[Z];return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:Q}async function LV($,Z){if(Z?.aborted)throw Error("Login cancelled");await new Promise((Q,Y)=>{let G=setTimeout(()=>{Z?.removeEventListener("abort",X),Q()},$),X=()=>{clearTimeout(G),Z?.removeEventListener("abort",X),Y(Error("Login cancelled"))};if(Z?.addEventListener("abort",X,{once:!0}),Z?.aborted)X()})}async function C8($){let Z=Date.now()+$.expiresInSeconds*1000,Q=Math.max(0.05,$.intervalSeconds);while(Date.now()<Z){await LV(Q*1000,$.signal);let Y=await $.fetch($.url,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams($.fields),...$.signal?{signal:$.signal}:{}}),W=await L1(Y.status>=400&&Y.status<500?new Response(await Y.text(),{status:200,headers:Y.headers}):Y,`${$.provider} device token request`);if(Y.ok&&typeof W.access_token==="string")return W;if(W.error==="authorization_pending")continue;if(W.error==="slow_down"){Q=t0(W,"interval",Q+5);continue}throw Error(`${$.provider} login failed${typeof W.error_description==="string"?`: ${W.error_description}`:typeof W.error==="string"?`: ${W.error}`:""}`)}throw Error(`${$.provider} login timed out`)}async function S8($,Z,Q,Y){let W=await($.fetch??fetch)(Q,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y),...$.signal?{signal:$.signal}:{}});return L1(W,`${Z} device authorization`)}async function UV($={}){let Q=$.fetch??fetch,Y=await S8($,"Kimi Code","https://auth.kimi.com/api/oauth/device_authorization",{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098"}),W=typeof Y.verification_uri_complete==="string"?z5(Y.verification_uri_complete,"Kimi Code"):z5(Y0(Y,"verification_uri","Kimi Code"),"Kimi Code"),G=Y0(Y,"user_code","Kimi Code");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await C8({fetch:Q,url:"https://auth.kimi.com/api/oauth/token",fields:{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",device_code:Y0(Y,"device_code","Kimi Code"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:t0(Y,"interval",5),expiresInSeconds:t0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"Kimi Code"}),J=t0(X,"expires_in",3600);return await L5("kimi-coding",{type:"oauth",accessToken:Y0(X,"access_token","Kimi Code"),refreshToken:Y0(X,"refresh_token","Kimi Code"),expiresAt:($.now??Date.now)()+J*1000},$),{provider:"kimi-coding"}}async function qV($={}){let Q=$.fetch??fetch,Y=await S8($,"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"}),W=typeof Y.verification_uri_complete==="string"?B7(Y.verification_uri_complete,"xAI"):B7(Y0(Y,"verification_uri","xAI"),"xAI"),G=Y0(Y,"user_code","xAI");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await C8({fetch:Q,url:"https://auth.x.ai/oauth2/token",fields:{client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_code:Y0(Y,"device_code","xAI"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:t0(Y,"interval",5),expiresInSeconds:t0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"xAI"}),J=t0(X,"expires_in",3600);return await L5("xai",{type:"oauth",accessToken:Y0(X,"access_token","xAI"),refreshToken:Y0(X,"refresh_token","xAI"),expiresAt:($.now??Date.now)()+J*1000-300000},$),{provider:"xai"}}async function AV($={}){let Z=Buffer.from("SXYxLmI1MDdhMDhjODdlY2ZlOTg=","base64").toString("utf8"),Q=$.fetch??fetch,Y=await S8($,"GitHub Copilot","https://github.com/login/device/code",{client_id:Z,scope:"read:user"}),W=z5(Y0(Y,"verification_uri","GitHub Copilot"),"GitHub Copilot"),G=Y0(Y,"user_code","GitHub Copilot");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await C8({fetch:Q,url:"https://github.com/login/oauth/access_token",fields:{client_id:Z,device_code:Y0(Y,"device_code","GitHub Copilot"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:t0(Y,"interval",5),expiresInSeconds:t0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"GitHub Copilot"}),J=Y0(X,"access_token","GitHub Copilot"),B=await Q("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${J}`,...D5},...$.signal?{signal:$.signal}:{}}),K=await L1(B,"GitHub Copilot token exchange"),V=Y0(K,"token","GitHub Copilot"),z=K.expires_at;if(typeof z!=="number"||!Number.isFinite(z))throw Error("GitHub Copilot response is missing expires_at");let F=U7(V),L=$.signal?AbortSignal.any([$.signal,AbortSignal.timeout(k1)]):AbortSignal.timeout(k1),D=await N7(V,F,Q,L);return await L5(R8,{type:"oauth",accessToken:V,refreshToken:J,expiresAt:z*1000-300000,baseUrl:F,availableModelIds:D},$),{provider:"github-copilot"}}async function NV($,Z){let Q=`/oauth/callback/${F5(18).toString("base64url")}`,Y=()=>{},W=()=>{},G=new Promise((V,z)=>{Y=V,W=z}),X=!1,J=H7((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!==Q){z.statusCode=404,z.end(x1($,"That page does not exist."));return}let L=F.searchParams.get("error"),D=F.searchParams.get("code");if(L||!D){if(z.statusCode=400,z.end(x1($,"Authorization was not completed.")),!X)X=!0,W(Error(`${$} login failed: ${L??"missing authorization code"}`));return}if(z.end(H5($)),!X)X=!0,Y(D)});await M7(J,0);let B=J.address();if(!B||typeof B==="string")throw J.close(),Error(`Could not start the ${$} callback server`);let K=()=>{if(!X)X=!0,W(Error(`${$} login cancelled`));J.close()};if(Z?.addEventListener("abort",K,{once:!0}),Z?.aborted)K();return{callbackUrl:`http://127.0.0.1:${B.port}${Q}`,code:G.finally(()=>Z?.removeEventListener("abort",K)),close:()=>J.close()}}async function OV($={}){let Z=O7(),Q=$.callbackServer?await $.callbackServer("OpenRouter",$.signal):await NV("OpenRouter",$.signal);try{let Y=new URL("https://openrouter.ai/auth");Y.search=new URLSearchParams({callback_url:Q.callbackUrl,code_challenge:Z.challenge,code_challenge_method:"S256"}).toString(),await $.onAuthUrl?.(Y.toString());let W=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:W,code_verifier:Z.verifier,code_challenge_method:"S256"}),...$.signal?{signal:$.signal}:{}}),X=await L1(G,"OpenRouter key exchange");return await L5("openrouter",{type:"oauth",accessToken:Y0(X,"key","OpenRouter"),refreshToken:"",expiresAt:Number.MAX_SAFE_INTEGER},$),{provider:"openrouter"}}finally{Q.close()}}function MV($){let Z=$.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens,Q=(Y)=>Math.max(0,Math.trunc(Y)).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(`
|
|
192
|
-
`)}function
|
|
193
|
-
`),data:{kind:"fork-points",points:W}}}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?
|
|
194
|
+
`}function G5($){return A4({provider:$,status:"success",heading:"Authentication successful",detail:`${$} authentication completed. You can close this window.`})}function b1($,Z){return A4({provider:$,status:"error",heading:"Authentication failed",detail:Z})}var M4=1,O4="app_EMoamEEZ73f0CkXaXp7hrann",X5="OpenAI",WY="https://auth.openai.com",kH="openid profile email offline_access api.connectors.read api.connectors.invoke",fH="https://api.openai.com/auth",z1="openai-codex",j4="github-copilot",B5={"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"},vH="2026-06-01",gH=60000,_1=15000,hH=300000,uH=[1455,1457];function P4(){return YY(_H(),".mu","auth.json")}function mH(){return{version:M4,providers:{}}}function a$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function lH($,Z){if(!a$($))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((Q)=>typeof Q==="string")?{availableModelIds:$.availableModelIds}:{}}}throw Error(`Invalid stored credentials for "${Z}"`)}async function r0($={}){let Z=$.authFile??P4(),Q;try{Q=await EH(Z,"utf8")}catch(X){if(X.code==="ENOENT")return mH();throw X}let Y;try{Y=JSON.parse(Q)}catch{throw Error(`Could not parse authentication file: ${Z}`)}if(!a$(Y)||Y.version!==M4||!a$(Y.providers))throw Error(`Unsupported authentication file: ${Z}`);let W={};for(let[X,J]of Object.entries(Y.providers)){let B=lH(J,X),K=X==="openai"&&B.type==="oauth"?z1:X;if(K===X)W[K]=B;else W[K]??=B}let G=Y.activeProvider==="openai"&&!W.openai&&W[z1]?.type==="oauth"?z1:Y.activeProvider;if(process.platform!=="win32"){if(((await CH(Z)).mode&63)!==0)await N4(Z,384)}return{version:M4,...typeof G==="string"?{activeProvider:G}:{},providers:W}}async function r$($,Z={}){let Q=Z.authFile??P4(),Y=xH(Q);if(await RH(Y,{recursive:!0,mode:448}),process.platform!=="win32")await N4(Y,448);let W=YY(Y,`.auth-${process.pid}-${K5(8).toString("hex")}.tmp`);try{if(await bH(W,`${JSON.stringify($,null,2)}
|
|
195
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),await SH(W,Q),process.platform!=="win32")await N4(Q,384)}catch(G){throw await yH(W).catch(()=>{}),G}}async function pH($,Z,Q={}){let Y=$.trim(),W=Z.trim();if(!Y)throw Error("Provider is required");if(!W)throw Error("API key cannot be empty");let G=await r0(Q);G.providers[Y]={type:"apiKey",apiKey:W},G.activeProvider=Y,await r$(G,Q)}async function cH($,Z={}){let Q=$.trim();if(!Q)throw Error("Provider is required");let Y=await r0(Z);if(!Y.providers[Q])return!1;if(delete Y.providers[Q],Y.activeProvider===Q){let W=Object.keys(Y.providers)[0];if(W)Y.activeProvider=W;else delete Y.activeProvider}return await r$(Y,Z),!0}async function dH($={}){return Object.keys((await r0($)).providers)}async function iH($={}){let Z=await r0($);return Z.activeProvider&&Z.providers[Z.activeProvider]?Z.activeProvider:Object.keys(Z.providers)[0]}async function H5($,Z,Q){let Y=await r0(Q);Y.providers[$]=Z,Y.activeProvider=$,await r$(Y,Q)}function GY($){let Z=$.split(".")[1];if(!Z)return;try{let Q=JSON.parse(Buffer.from(Z,"base64url").toString("utf8"));return a$(Q)?Q:void 0}catch{return}}function oQ($){let Z=GY($)?.[fH]?.chatgpt_account_id;return typeof Z==="string"&&Z.length>0?Z:void 0}function nH($){let Z=GY($)?.exp;return typeof Z==="number"&&Number.isFinite(Z)?Z*1000:void 0}function aH($,Z,Q){let Y=Q.trim()?`: ${Q.trim().slice(0,1000)}`:"";return Error(`OpenAI token ${$} failed (${Z.status})${Y}`)}async function XY($,Z){if(!$.ok)throw aH(Z,$,await $.text().catch(()=>""));let Q=await $.json();if(!a$(Q))throw Error(`OpenAI token ${Z} returned invalid JSON`);return Q}function JY($,Z,Q){let Y=typeof $.access_token==="string"?$.access_token:Q?.accessToken,W=typeof $.refresh_token==="string"?$.refresh_token:Q?.refreshToken,G=typeof $.id_token==="string"?$.id_token:Q?.idToken;if(!Y||!W)throw Error("OpenAI token response is missing access or refresh token");let X=oQ(Y)??(G?oQ(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,B=nH(Y)??(J!==void 0?Z+J:Z+3600000);return{type:"oauth",accessToken:Y,refreshToken:W,...G?{idToken:G}:{},expiresAt:B,accountId:X}}async function rH($,Z){let Q=(Z.openAiIssuer??WY).replace(/\/+$/,""),Y=await(Z.fetch??fetch)(`${Q}/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({client_id:Z.openAiClientId??O4,grant_type:"refresh_token",refresh_token:$.refreshToken}),signal:AbortSignal.timeout(_1)});return JY(await XY(Y,"refresh"),(Z.now??Date.now)(),$)}function sQ($){return{type:"oauth",accessToken:$.accessToken,...$.accountId?{accountId:$.accountId}:{},...$.baseUrl?{baseUrl:$.baseUrl}:{},...$.availableModelIds?{availableModelIds:$.availableModelIds}:{}}}function eQ($,Z,Q){return Z.expiresAt>Q+gH&&($!==j4||Z.availableModelIds!==void 0)}async function F1($,Z){let Q=await $.text(),Y;try{Y=JSON.parse(Q)}catch{throw Error(`${Z} returned invalid JSON (${$.status})`)}if(!$.ok){let W=typeof Y==="object"&&Y!==null?Y:{},G=W.error_description??W.message??W.error;throw Error(`${Z} failed (${$.status})${typeof G==="string"?`: ${G}`:""}`)}if(typeof Y!=="object"||Y===null||Array.isArray(Y))throw Error(`${Z} returned invalid JSON`);return Y}function $Y($,Z,Q=60000){let Y=typeof $.access_token==="string"?$.access_token:Z.accessToken,W=typeof $.refresh_token==="string"?$.refresh_token:Z.refreshToken,G=typeof $.expires_in==="number"&&Number.isFinite($.expires_in)?$.expires_in:3600;if(!Y||!W)throw Error("OAuth response is missing tokens");return{...Z,accessToken:Y,refreshToken:W,expiresAt:Date.now()+G*1000-Q}}function KY($){let Z=$.match(/(?:^|;)proxy-ep=([^;]+)/)?.[1];return Z?`https://${Z.replace(/^proxy\./,"api.")}`:"https://api.individual.githubcopilot.com"}function tH($){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 oH($){let Z=typeof $.policy==="object"&&$.policy!==null?$.policy:void 0,Q=typeof $.capabilities==="object"&&$.capabilities!==null?$.capabilities:void 0,Y=typeof Q?.supports==="object"&&Q.supports!==null?Q.supports:void 0;return $.model_picker_enabled===!0&&Z?.state!=="disabled"&&Y?.tool_calls!==!1}async function BY($,Z,Q,Y){let W=await Q(`${Z.replace(/\/+$/,"")}/models`,{headers:{accept:"application/json",authorization:`Bearer ${$}`,...B5,"x-github-api-version":vH},...Y?{signal:Y}:{}});return tH(await F1(W,"GitHub Copilot model discovery"))}async function HY($,Z,Q,Y){return(await BY($,Z,Q,Y)).filter(oH).map((W)=>W.id).filter((W)=>typeof W==="string"&&W.length>0)}async function VY($,Z,Q,Y){let W=await BY($,Z,Q,Y);return await Promise.all(W.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 ${$}`,...B5,"openai-intent":"chat-policy","x-interaction-type":"chat-policy"},body:JSON.stringify({state:"enabled"}),...Y?{signal:Y}:{}}).catch(()=>{return})})),HY($,Z,Q,Y)}async function sH($,Z,Q){let Y=Q.fetch??fetch;if($==="kimi-coding"){let W=await Y("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(_1)});return $Y(await F1(W,"Kimi Code token refresh"),Z)}if($==="xai"){let W=await Y("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(_1)});return $Y(await F1(W,"xAI token refresh"),Z,300000)}if($===j4){let W=await Y("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${Z.refreshToken}`,...B5},signal:AbortSignal.timeout(_1)}),G=await F1(W,"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=KY(X),B=AbortSignal.timeout(_1),K=Z.availableModelIds?await HY(X,J,Y,B):await VY(X,J,Y,B);return{...Z,accessToken:X,expiresAt:G.expires_at*1000-300000,baseUrl:J,availableModelIds:K}}if($===z1){if(!Z.accountId)throw Error("OpenAI login is missing its ChatGPT account");return rH(Z,Q)}throw Error(`OAuth refresh is not implemented for provider "${$}"`)}function eH($={}){let Z=new Map;return async(Q)=>{let W=(await r0($)).providers[Q];if(!W)return;if(W.type==="apiKey")return{type:"apiKey",apiKey:W.apiKey};let G=($.now??Date.now)();if(eQ(Q,W,G))return sQ(W);let X=Z.get(Q);if(X)return X;let J=(async()=>{let B=await r0($),K=B.providers[Q];if(!K||K.type!=="oauth")throw Error(`${Q} login is no longer available`);let V=($.now??Date.now)(),z=eQ(Q,K,V)?K:await sH(Q,K,$);if(z!==K)B.providers[Q]=z,await r$(B,$);return sQ(z)})().finally(()=>{Z.delete(Q)});return Z.set(Q,J),J}}function zY(){let $=K5(64).toString("base64url");return{verifier:$,challenge:IH("sha256").update($).digest("base64url")}}function FY($,Z){return new Promise((Q,Y)=>{let W=(X)=>{$.off("listening",G),Y(X)},G=()=>{$.off("error",W);let X=$.address();if(!X||typeof X==="string"){Y(Error("Could not determine OAuth callback port"));return}Q(X.port)};$.once("error",W),$.once("listening",G),$.listen(Z,"127.0.0.1")})}async function $V($,Z,Q){if(Q.aborted)throw Error("OpenAI login cancelled");let Y=Z===void 0?uH:[Z],W;for(let G of Y){let X=()=>{},J=()=>{},B=new Promise((z,F)=>{X=z,J=F}),K=!1,V=QY((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(b1(X5,"That page does not exist."));return}if(D.searchParams.get("state")!==$){F.statusCode=400,F.end(b1(X5,"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(b1(X5,"Return to mu and try again.")),!K)K=!0,J(Error(`OpenAI login failed: ${L??"missing authorization code"}`));return}if(F.end(G5(X5)),!K)K=!0,X(U)});try{let z=await FY(V,G),F=()=>{if(!K)K=!0,J(Error("OpenAI login cancelled"));V.close()};if(Q.addEventListener("abort",F,{once:!0}),Q.aborted)F();return{redirectUri:`http://localhost:${z}/auth/callback`,callback:B.finally(()=>Q.removeEventListener("abort",F)),close:()=>V.close()}}catch(z){W=z,V.close()}}throw Error(`Could not start OpenAI login callback server: ${W instanceof Error?W.message:String(W)}`)}async function ZV($={}){let Z=new AbortController,Q=()=>Z.abort();if($.signal?.addEventListener("abort",Q,{once:!0}),$.signal?.aborted)Z.abort();let Y=setTimeout(Q,$.timeoutMs??hH);Y.unref?.();let W=K5(32).toString("base64url"),G=zY(),X=($.openAiIssuer??WY).replace(/\/+$/,""),J;try{J=$.callbackServer?await $.callbackServer(W,Z.signal):await $V(W,$.port,Z.signal);let B=new URL(`${X}/oauth/authorize`);B.search=new URLSearchParams({response_type:"code",client_id:$.openAiClientId??O4,redirect_uri:J.redirectUri,scope:kH,code_challenge:G.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:W,originator:"mu"}).toString(),await $.onAuthUrl?.(B.toString());let K=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??O4,code:K,code_verifier:G.verifier,redirect_uri:J.redirectUri}),signal:Z.signal}),z=JY(await XY(V,"exchange"),($.now??Date.now)()),F=await r0($);return F.providers[z1]=z,F.activeProvider=z1,await r$(F,$),{provider:z1,accountId:z.accountId}}finally{clearTimeout(Y),$.signal?.removeEventListener("abort",Q),J?.close()}}function Q0($,Z,Q){let Y=$[Z];if(typeof Y!=="string"||Y.length===0)throw Error(`${Q} response is missing ${Z}`);return Y}function J5($,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 ZY($,Z){let Q=J5($,Z);if(!Q.startsWith("https:"))throw Error(`${Z} returned an unsafe authorization URL`);return Q}function a0($,Z,Q){let Y=$[Z];return typeof Y==="number"&&Number.isFinite(Y)&&Y>0?Y:Q}async function QV($,Z){if(Z?.aborted)throw Error("Login cancelled");await new Promise((Q,Y)=>{let G=setTimeout(()=>{Z?.removeEventListener("abort",X),Q()},$),X=()=>{clearTimeout(G),Z?.removeEventListener("abort",X),Y(Error("Login cancelled"))};if(Z?.addEventListener("abort",X,{once:!0}),Z?.aborted)X()})}async function w4($){let Z=Date.now()+$.expiresInSeconds*1000,Q=Math.max(0.05,$.intervalSeconds);while(Date.now()<Z){await QV(Q*1000,$.signal);let Y=await $.fetch($.url,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams($.fields),...$.signal?{signal:$.signal}:{}}),W=await F1(Y.status>=400&&Y.status<500?new Response(await Y.text(),{status:200,headers:Y.headers}):Y,`${$.provider} device token request`);if(Y.ok&&typeof W.access_token==="string")return W;if(W.error==="authorization_pending")continue;if(W.error==="slow_down"){Q=a0(W,"interval",Q+5);continue}throw Error(`${$.provider} login failed${typeof W.error_description==="string"?`: ${W.error_description}`:typeof W.error==="string"?`: ${W.error}`:""}`)}throw Error(`${$.provider} login timed out`)}async function T4($,Z,Q,Y){let W=await($.fetch??fetch)(Q,{method:"POST",headers:{accept:"application/json","content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams(Y),...$.signal?{signal:$.signal}:{}});return F1(W,`${Z} device authorization`)}async function YV($={}){let Q=$.fetch??fetch,Y=await T4($,"Kimi Code","https://auth.kimi.com/api/oauth/device_authorization",{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098"}),W=typeof Y.verification_uri_complete==="string"?J5(Y.verification_uri_complete,"Kimi Code"):J5(Q0(Y,"verification_uri","Kimi Code"),"Kimi Code"),G=Q0(Y,"user_code","Kimi Code");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await w4({fetch:Q,url:"https://auth.kimi.com/api/oauth/token",fields:{client_id:"17e5f671-d194-4dfb-9706-5516cb48c098",device_code:Q0(Y,"device_code","Kimi Code"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:a0(Y,"interval",5),expiresInSeconds:a0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"Kimi Code"}),J=a0(X,"expires_in",3600);return await H5("kimi-coding",{type:"oauth",accessToken:Q0(X,"access_token","Kimi Code"),refreshToken:Q0(X,"refresh_token","Kimi Code"),expiresAt:($.now??Date.now)()+J*1000},$),{provider:"kimi-coding"}}async function WV($={}){let Q=$.fetch??fetch,Y=await T4($,"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"}),W=typeof Y.verification_uri_complete==="string"?ZY(Y.verification_uri_complete,"xAI"):ZY(Q0(Y,"verification_uri","xAI"),"xAI"),G=Q0(Y,"user_code","xAI");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await w4({fetch:Q,url:"https://auth.x.ai/oauth2/token",fields:{client_id:"b1a00492-073a-47ea-816f-4c329264a828",device_code:Q0(Y,"device_code","xAI"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:a0(Y,"interval",5),expiresInSeconds:a0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"xAI"}),J=a0(X,"expires_in",3600);return await H5("xai",{type:"oauth",accessToken:Q0(X,"access_token","xAI"),refreshToken:Q0(X,"refresh_token","xAI"),expiresAt:($.now??Date.now)()+J*1000-300000},$),{provider:"xai"}}async function GV($={}){let Z=Buffer.from("SXYxLmI1MDdhMDhjODdlY2ZlOTg=","base64").toString("utf8"),Q=$.fetch??fetch,Y=await T4($,"GitHub Copilot","https://github.com/login/device/code",{client_id:Z,scope:"read:user"}),W=J5(Q0(Y,"verification_uri","GitHub Copilot"),"GitHub Copilot"),G=Q0(Y,"user_code","GitHub Copilot");await $.onDeviceCode?.(W,G),await $.onAuthUrl?.(W);let X=await w4({fetch:Q,url:"https://github.com/login/oauth/access_token",fields:{client_id:Z,device_code:Q0(Y,"device_code","GitHub Copilot"),grant_type:"urn:ietf:params:oauth:grant-type:device_code"},intervalSeconds:a0(Y,"interval",5),expiresInSeconds:a0(Y,"expires_in",900),...$.signal?{signal:$.signal}:{},provider:"GitHub Copilot"}),J=Q0(X,"access_token","GitHub Copilot"),B=await Q("https://api.github.com/copilot_internal/v2/token",{headers:{accept:"application/json",authorization:`Bearer ${J}`,...B5},...$.signal?{signal:$.signal}:{}}),K=await F1(B,"GitHub Copilot token exchange"),V=Q0(K,"token","GitHub Copilot"),z=K.expires_at;if(typeof z!=="number"||!Number.isFinite(z))throw Error("GitHub Copilot response is missing expires_at");let F=KY(V),D=$.signal?AbortSignal.any([$.signal,AbortSignal.timeout(_1)]):AbortSignal.timeout(_1),L=await VY(V,F,Q,D);return await H5(j4,{type:"oauth",accessToken:V,refreshToken:J,expiresAt:z*1000-300000,baseUrl:F,availableModelIds:L},$),{provider:"github-copilot"}}async function XV($,Z){let Q=`/oauth/callback/${K5(18).toString("base64url")}`,Y=()=>{},W=()=>{},G=new Promise((V,z)=>{Y=V,W=z}),X=!1,J=QY((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!==Q){z.statusCode=404,z.end(b1($,"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(b1($,"Authorization was not completed.")),!X)X=!0,W(Error(`${$} login failed: ${D??"missing authorization code"}`));return}if(z.end(G5($)),!X)X=!0,Y(L)});await FY(J,0);let B=J.address();if(!B||typeof B==="string")throw J.close(),Error(`Could not start the ${$} callback server`);let K=()=>{if(!X)X=!0,W(Error(`${$} login cancelled`));J.close()};if(Z?.addEventListener("abort",K,{once:!0}),Z?.aborted)K();return{callbackUrl:`http://127.0.0.1:${B.port}${Q}`,code:G.finally(()=>Z?.removeEventListener("abort",K)),close:()=>J.close()}}async function JV($={}){let Z=zY(),Q=$.callbackServer?await $.callbackServer("OpenRouter",$.signal):await XV("OpenRouter",$.signal);try{let Y=new URL("https://openrouter.ai/auth");Y.search=new URLSearchParams({callback_url:Q.callbackUrl,code_challenge:Z.challenge,code_challenge_method:"S256"}).toString(),await $.onAuthUrl?.(Y.toString());let W=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:W,code_verifier:Z.verifier,code_challenge_method:"S256"}),...$.signal?{signal:$.signal}:{}}),X=await F1(G,"OpenRouter key exchange");return await H5("openrouter",{type:"oauth",accessToken:Q0(X,"key","OpenRouter"),refreshToken:"",expiresAt:Number.MAX_SAFE_INTEGER},$),{provider:"openrouter"}}finally{Q.close()}}function KV($){let Z=$.inputTokens+$.outputTokens+$.cacheReadTokens+$.cacheWriteTokens,Q=(Y)=>Math.max(0,Math.trunc(Y)).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(`
|
|
196
|
+
`)}function LY($={}){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};try{Z.setModel(Q)}catch(Y){return{handled:!0,message:Y instanceof Error?Y.message:String(Y)}}return{handled:!0,message:`Model set to ${Z.getModel()}`}}},{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 W=$.forkPoints?.()??[];if(W.length===0)return{handled:!0,message:"No branch points yet."};return{handled:!0,message:W.map((G)=>`${G.id} \xB7 ${G.description}`).join(`
|
|
197
|
+
`),data:{kind:"fork-points",points:W}}}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?KV(Z):"Usage is reported by the surface that owns the session."}}}]}function BV($={}){let Z=new I1;for(let Q of LY($))Z.register(Q);return Z.register({name:"help",description:"List available commands",run:(Q)=>{let Y=Z.list().map((W)=>` /${W.name.padEnd(12)} ${W.description}`);return Q.print(`Available commands:
|
|
194
198
|
${Y.join(`
|
|
195
|
-
`)}`),{handled:!0}}}),Z}import{readdir as
|
|
199
|
+
`)}`),{handled:!0}}}),Z}import{readdir as HV,stat as VV}from"fs/promises";import{homedir as zV}from"os";import{isAbsolute as FV,join as I4,resolve as LV}from"path";function DV($){return typeof $==="object"&&$!==null&&typeof $.name==="string"&&typeof $.activate==="function"}async function R4($){try{return(await HV($)).filter((Q)=>Q.endsWith(".ts")||Q.endsWith(".js")).sort().map((Q)=>I4($,Q))}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function UV($){try{return(await VV($)).isDirectory()?R4($):[$]}catch(Z){if(Z.code==="ENOENT")return[];throw Z}}async function DY($={}){let Z=[];if($.userDir!==!1)Z.push(...await R4(I4(zV(),".mu","extensions")));if($.projectDir)Z.push(...await R4(I4($.projectDir,".mu","extensions")));for(let Q of $.paths??[])Z.push(...await UV(FV(Q)?Q:LV(Q)));return Z}async function qV($,Z={}){let Q={loaded:[],failed:[]};for(let Y of await DY(Z))try{let W=await import(Y),G=W.default??W.extension;if(!DV(G)){Q.failed.push({file:Y,error:"no default export with { name, activate } found"});continue}await $.register(G),Q.loaded.push(Y)}catch(W){Q.failed.push({file:Y,error:W instanceof Error?W.message:String(W)})}return Q}import{randomUUID as AV}from"crypto";import{chmod as UY,mkdir as NV,readdir as MV,readFile as qY,rename as OV,rm as jV,writeFile as PV}from"fs/promises";import{homedir as wV}from"os";import{join as V5}from"path";class AY{dir;constructor($={}){let Z=$.root??V5(wV(),".mu","sessions");this.dir=$.scope?V5(Z,$.scope):Z}path($){let Z=Buffer.from($,"utf8").toString("base64url");return V5(this.dir,`${Z}.jsonl`)}fallbackId($){let Z=$.slice(0,-6);try{let Q=Buffer.from(Z,"base64url").toString("utf8");return this.path(Q).endsWith($)?Q:Z}catch{return Z}}async load($){try{return o.fromJsonl(await qY(this.path($),"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw Z}}async save($,Z){if(await NV(this.dir,{recursive:!0,mode:448}),process.platform!=="win32")await UY(this.dir,448);let Q=this.path($),Y=`${Q}.${process.pid}.${AV()}.tmp`;try{if(await PV(Y,Z.toJsonl(),{encoding:"utf8",mode:384,flag:"wx"}),await OV(Y,Q),process.platform!=="win32")await UY(Q,384)}catch(W){throw await jV(Y,{force:!0}).catch(()=>{}),W}}async list(){try{let $=await MV(this.dir),Z=await Promise.all($.filter((Q)=>Q.endsWith(".jsonl")).map(async(Q)=>{try{return o.fromJsonl(await qY(V5(this.dir,Q),"utf8")).header?.id??this.fallbackId(Q)}catch{return this.fallbackId(Q)}}));return[...new Set(Z)]}catch($){if($.code==="ENOENT")return[];throw $}}}import{readdir as TV,readFile as IV}from"fs/promises";import{homedir as RV}from"os";import{basename as EV,join as E4}from"path";function z5($){let Z=$.replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
196
200
|
`),Q=/^---\n([\s\S]*?)\n---\n?/.exec(Z);if(!Q)return{meta:{},body:Z.trim()};let Y={};for(let W of(Q[1]??"").split(`
|
|
197
|
-
`)){let G=W.indexOf(":");if(G===-1)continue;let X=W.slice(0,G).trim(),J=W.slice(G+1).trim();if(X.length===0)continue;Y[X]=J.startsWith("[")&&J.endsWith("]")?J.slice(1,-1).split(",").map((B)=>B.trim().replace(/^["']|["']$/g,"")).filter((B)=>B.length>0):J.replace(/^["']|["']$/g,"")}return{meta:Y,body:Z.slice(Q[0].length).trim()}}function
|
|
201
|
+
`)){let G=W.indexOf(":");if(G===-1)continue;let X=W.slice(0,G).trim(),J=W.slice(G+1).trim();if(X.length===0)continue;Y[X]=J.startsWith("[")&&J.endsWith("]")?J.slice(1,-1).split(",").map((B)=>B.trim().replace(/^["']|["']$/g,"")).filter((B)=>B.length>0):J.replace(/^["']|["']$/g,"")}return{meta:Y,body:Z.slice(Q[0].length).trim()}}function MY($,Z){let Q=Z.trim().length>0?Z.trim().split(/\s+/):[],Y=!1,W=$.replace(/\$ARGUMENTS\b/g,()=>{return Y=!0,Z.trim()});if(W=W.replace(/\$([1-9])\b/g,(G,X)=>{return Y=!0,Q[Number(X)-1]??""}),!Y&&Z.trim().length>0)return`${W}
|
|
198
202
|
|
|
199
|
-
${Z.trim()}`;return W}function C7($,Z){let{meta:Q,body:Y}=q5(Z),W=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((B)=>B.trim()):void 0;return{name:$,description:W,body:Y,...G?{model:G}:{},...J?{allowedTools:J}:{}}}async function R7($){let Z;try{Z=await gV($)}catch{return[]}let Q=[];for(let Y of Z.filter((W)=>W.endsWith(".md")).sort())try{let W=await hV(_8($,Y),"utf8");Q.push(C7(mV(Y,".md"),W))}catch{}return Q}async function lV($={}){let Z=await R7($.userDir??_8(uV(),".mu","commands")),Q=$.projectDir?await R7(_8($.projectDir,".mu","commands")):[],Y=new Map;for(let W of[...Z,...Q])Y.set(W.name,W);return[...Y.values()]}function pV($,Z){return{name:$.name,description:$.description,run:async(Q)=>{let Y={kind:"markdown-command",prompt:E7($.body,Q.args),...$.model?{model:$.model}:{},...$.allowedTools?{allowedTools:$.allowedTools}:{}};if(Z)return await Z(Y.prompt,{...Y.model?{model:Y.model}:{},...Y.allowedTools?{allowedTools:Y.allowedTools}:{}}),{handled:!0};return{handled:!0,data:Y}}}}import{readFile as Tj}from"fs/promises";import{homedir as Rj}from"os";import{dirname as Ej,isAbsolute as Cj,join as R3,resolve as Sj}from"path";import*as cV from"zod/v3";import*as A5 from"zod/v4-mini";function J$($){return!!$._zod}function R0($,Z){if(J$($))return A5.safeParse($,Z);return $.safeParse(Z)}function N5($){if(!$)return;let Z;if(J$($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function S7($){if(J$($)){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 Y=$.value;if(Y!==void 0)return Y;return}import*as H from"zod/v4";var x8="2025-11-25";var y7=[x8,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],U1="io.modelcontextprotocol/related-task",M5="2.0",a=H.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),b7=H.union([H.string(),H.number().int()]),_7=H.string(),BR=H.looseObject({ttl:H.number().optional(),pollInterval:H.number().optional()}),dV=H.object({ttl:H.number().optional()}),iV=H.object({taskId:H.string()}),k8=H.looseObject({progressToken:b7.optional(),[U1]:iV.optional()}),q0=H.object({_meta:k8.optional()}),$Z=q0.extend({task:dV.optional()}),x7=($)=>$Z.safeParse($).success,e=H.object({method:H.string(),params:q0.loose().optional()}),M0=H.object({_meta:k8.optional()}),j0=H.object({method:H.string(),params:M0.loose().optional()}),$0=H.looseObject({_meta:k8.optional()}),j5=H.union([H.string(),H.number().int()]),k7=H.object({jsonrpc:H.literal(M5),id:j5,...e.shape}).strict(),f8=($)=>k7.safeParse($).success,f7=H.object({jsonrpc:H.literal(M5),...j0.shape}).strict(),v7=($)=>f7.safeParse($).success,v8=H.object({jsonrpc:H.literal(M5),id:j5,result:$0}).strict(),ZZ=($)=>v8.safeParse($).success;var R;(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"})(R||(R={}));var g8=H.object({jsonrpc:H.literal(M5),id:j5.optional(),error:H.object({code:H.number().int(),message:H.string(),data:H.unknown().optional()})}).strict();var g7=($)=>g8.safeParse($).success;var h7=H.union([k7,f7,v8,g8]),HR=H.union([v8,g8]),f1=$0.strict(),nV=M0.extend({requestId:j5.optional(),reason:H.string().optional()}),P5=j0.extend({method:H.literal("notifications/cancelled"),params:nV}),aV=H.object({src:H.string(),mimeType:H.string().optional(),sizes:H.array(H.string()).optional(),theme:H.enum(["light","dark"]).optional()}),QZ=H.object({icons:H.array(aV).optional()}),K$=H.object({name:H.string(),title:H.string().optional()}),u7=K$.extend({...K$.shape,...QZ.shape,version:H.string(),websiteUrl:H.string().optional(),description:H.string().optional()}),rV=H.intersection(H.object({applyDefaults:H.boolean().optional()}),H.record(H.string(),H.unknown())),tV=H.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},H.intersection(H.object({form:rV.optional(),url:a.optional()}),H.record(H.string(),H.unknown()).optional())),oV=H.looseObject({list:a.optional(),cancel:a.optional(),requests:H.looseObject({sampling:H.looseObject({createMessage:a.optional()}).optional(),elicitation:H.looseObject({create:a.optional()}).optional()}).optional()}),sV=H.looseObject({list:a.optional(),cancel:a.optional(),requests:H.looseObject({tools:H.looseObject({call:a.optional()}).optional()}).optional()}),eV=H.object({experimental:H.record(H.string(),a).optional(),sampling:H.object({context:a.optional(),tools:a.optional()}).optional(),elicitation:tV.optional(),roots:H.object({listChanged:H.boolean().optional()}).optional(),tasks:oV.optional(),extensions:H.record(H.string(),a).optional()}),$z=q0.extend({protocolVersion:H.string(),capabilities:eV,clientInfo:u7}),Zz=e.extend({method:H.literal("initialize"),params:$z});var Qz=H.object({experimental:H.record(H.string(),a).optional(),logging:a.optional(),completions:a.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:sV.optional(),extensions:H.record(H.string(),a).optional()}),h8=$0.extend({protocolVersion:H.string(),capabilities:Qz,serverInfo:u7,instructions:H.string().optional()}),Yz=j0.extend({method:H.literal("notifications/initialized"),params:M0.optional()});var w5=e.extend({method:H.literal("ping"),params:q0.optional()}),Wz=H.object({progress:H.number(),total:H.optional(H.number()),message:H.optional(H.string())}),Gz=H.object({...M0.shape,...Wz.shape,progressToken:b7}),I5=j0.extend({method:H.literal("notifications/progress"),params:Gz}),Xz=q0.extend({cursor:_7.optional()}),YZ=e.extend({params:Xz.optional()}),WZ=$0.extend({nextCursor:_7.optional()}),Jz=H.enum(["working","input_required","completed","failed","cancelled"]),GZ=H.object({taskId:H.string(),status:Jz,ttl:H.union([H.number(),H.null()]),createdAt:H.string(),lastUpdatedAt:H.string(),pollInterval:H.optional(H.number()),statusMessage:H.optional(H.string())}),v1=$0.extend({task:GZ}),Kz=M0.merge(GZ),XZ=j0.extend({method:H.literal("notifications/tasks/status"),params:Kz}),T5=e.extend({method:H.literal("tasks/get"),params:q0.extend({taskId:H.string()})}),R5=$0.merge(GZ),E5=e.extend({method:H.literal("tasks/result"),params:q0.extend({taskId:H.string()})}),VR=$0.loose(),C5=YZ.extend({method:H.literal("tasks/list")}),S5=WZ.extend({tasks:H.array(GZ)}),y5=e.extend({method:H.literal("tasks/cancel"),params:q0.extend({taskId:H.string()})}),m7=$0.merge(GZ),l7=H.object({uri:H.string(),mimeType:H.optional(H.string()),_meta:H.record(H.string(),H.unknown()).optional()}),p7=l7.extend({text:H.string()}),u8=H.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),c7=l7.extend({blob:u8}),JZ=H.enum(["user","assistant"]),B$=H.object({audience:H.array(JZ).optional(),priority:H.number().min(0).max(1).optional(),lastModified:H.iso.datetime({offset:!0}).optional()}),d7=H.object({...K$.shape,...QZ.shape,uri:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),size:H.optional(H.number()),annotations:B$.optional(),_meta:H.optional(H.looseObject({}))}),Bz=H.object({...K$.shape,...QZ.shape,uriTemplate:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),annotations:B$.optional(),_meta:H.optional(H.looseObject({}))}),Hz=YZ.extend({method:H.literal("resources/list")}),m8=WZ.extend({resources:H.array(d7)}),Vz=YZ.extend({method:H.literal("resources/templates/list")}),l8=WZ.extend({resourceTemplates:H.array(Bz)}),p8=q0.extend({uri:H.string()}),zz=p8,Fz=e.extend({method:H.literal("resources/read"),params:zz}),c8=$0.extend({contents:H.array(H.union([p7,c7]))}),d8=j0.extend({method:H.literal("notifications/resources/list_changed"),params:M0.optional()}),Dz=p8,Lz=e.extend({method:H.literal("resources/subscribe"),params:Dz}),Uz=p8,qz=e.extend({method:H.literal("resources/unsubscribe"),params:Uz}),Az=M0.extend({uri:H.string()}),Nz=j0.extend({method:H.literal("notifications/resources/updated"),params:Az}),Oz=H.object({name:H.string(),description:H.optional(H.string()),required:H.optional(H.boolean())}),Mz=H.object({...K$.shape,...QZ.shape,description:H.optional(H.string()),arguments:H.optional(H.array(Oz)),_meta:H.optional(H.looseObject({}))}),jz=YZ.extend({method:H.literal("prompts/list")}),i8=WZ.extend({prompts:H.array(Mz)}),Pz=q0.extend({name:H.string(),arguments:H.record(H.string(),H.string()).optional()}),wz=e.extend({method:H.literal("prompts/get"),params:Pz}),n8=H.object({type:H.literal("text"),text:H.string(),annotations:B$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),a8=H.object({type:H.literal("image"),data:u8,mimeType:H.string(),annotations:B$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),r8=H.object({type:H.literal("audio"),data:u8,mimeType:H.string(),annotations:B$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Iz=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()}),Tz=H.object({type:H.literal("resource"),resource:H.union([p7,c7]),annotations:B$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Rz=d7.extend({type:H.literal("resource_link")}),t8=H.union([n8,a8,r8,Rz,Tz]),Ez=H.object({role:JZ,content:t8}),o8=$0.extend({description:H.string().optional(),messages:H.array(Ez)}),s8=j0.extend({method:H.literal("notifications/prompts/list_changed"),params:M0.optional()}),Cz=H.object({title:H.string().optional(),readOnlyHint:H.boolean().optional(),destructiveHint:H.boolean().optional(),idempotentHint:H.boolean().optional(),openWorldHint:H.boolean().optional()}),Sz=H.object({taskSupport:H.enum(["required","optional","forbidden"]).optional()}),i7=H.object({...K$.shape,...QZ.shape,description:H.string().optional(),inputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),a).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()),outputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),a).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()).optional(),annotations:Cz.optional(),execution:Sz.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),yz=YZ.extend({method:H.literal("tools/list")}),e8=WZ.extend({tools:H.array(i7)}),H$=$0.extend({content:H.array(t8).default([]),structuredContent:H.record(H.string(),H.unknown()).optional(),isError:H.boolean().optional()}),zR=H$.or($0.extend({toolResult:H.unknown()})),bz=$Z.extend({name:H.string(),arguments:H.record(H.string(),H.unknown()).optional()}),_z=e.extend({method:H.literal("tools/call"),params:bz}),$4=j0.extend({method:H.literal("notifications/tools/list_changed"),params:M0.optional()}),n7=H.object({autoRefresh:H.boolean().default(!0),debounceMs:H.number().int().nonnegative().default(300)}),a7=H.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),xz=q0.extend({level:a7}),kz=e.extend({method:H.literal("logging/setLevel"),params:xz}),fz=M0.extend({level:a7,logger:H.string().optional(),data:H.unknown()}),vz=j0.extend({method:H.literal("notifications/message"),params:fz}),gz=H.object({name:H.string().optional()}),hz=H.object({hints:H.array(gz).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()}),uz=H.object({mode:H.enum(["auto","required","none"]).optional()}),mz=H.object({type:H.literal("tool_result"),toolUseId:H.string().describe("The unique identifier for the corresponding tool call."),content:H.array(t8).default([]),structuredContent:H.object({}).loose().optional(),isError:H.boolean().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),lz=H.discriminatedUnion("type",[n8,a8,r8]),O5=H.discriminatedUnion("type",[n8,a8,r8,Iz,mz]),pz=H.object({role:JZ,content:H.union([O5,H.array(O5)]),_meta:H.record(H.string(),H.unknown()).optional()}),cz=$Z.extend({messages:H.array(pz),modelPreferences:hz.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:a.optional(),tools:H.array(i7).optional(),toolChoice:uz.optional()}),Z4=e.extend({method:H.literal("sampling/createMessage"),params:cz}),Q4=$0.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens"]).or(H.string())),role:JZ,content:lz}),Y4=$0.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(H.string())),role:JZ,content:H.union([O5,H.array(O5)])}),dz=H.object({type:H.literal("boolean"),title:H.string().optional(),description:H.string().optional(),default:H.boolean().optional()}),iz=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()}),nz=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()}),az=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),enum:H.array(H.string()),default:H.string().optional()}),rz=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()}),tz=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()}),oz=H.union([az,rz]),sz=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()}),ez=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()}),$F=H.union([sz,ez]),ZF=H.union([tz,oz,$F]),QF=H.union([ZF,dz,iz,nz]),YF=$Z.extend({mode:H.literal("form").optional(),message:H.string(),requestedSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),QF),required:H.array(H.string()).optional()})}),WF=$Z.extend({mode:H.literal("url"),message:H.string(),elicitationId:H.string(),url:H.string().url()}),GF=H.union([YF,WF]),W4=e.extend({method:H.literal("elicitation/create"),params:GF}),XF=M0.extend({elicitationId:H.string()}),JF=j0.extend({method:H.literal("notifications/elicitation/complete"),params:XF}),G4=$0.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())}),KF=H.object({type:H.literal("ref/resource"),uri:H.string()});var BF=H.object({type:H.literal("ref/prompt"),name:H.string()}),HF=q0.extend({ref:H.union([BF,KF]),argument:H.object({name:H.string(),value:H.string()}),context:H.object({arguments:H.record(H.string(),H.string()).optional()}).optional()}),VF=e.extend({method:H.literal("completion/complete"),params:HF});var X4=$0.extend({completion:H.looseObject({values:H.array(H.string()).max(100),total:H.optional(H.number().int()),hasMore:H.optional(H.boolean())})}),zF=H.object({uri:H.string().startsWith("file://"),name:H.string().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),FF=e.extend({method:H.literal("roots/list"),params:q0.optional()}),DF=$0.extend({roots:H.array(zF)}),LF=j0.extend({method:H.literal("notifications/roots/list_changed"),params:M0.optional()}),FR=H.union([w5,Zz,VF,kz,wz,jz,Hz,Vz,Fz,Lz,qz,_z,yz,T5,E5,C5,y5]),DR=H.union([P5,I5,Yz,LF,XZ]),LR=H.union([f1,Q4,Y4,G4,DF,R5,S5,v1]),UR=H.union([w5,Z4,W4,FF,T5,E5,C5,y5]),qR=H.union([P5,I5,vz,Nz,d8,$4,s8,XZ,JF]),AR=H.union([f1,h8,X4,o8,i8,m8,l8,c8,H$,e8,R5,S5,v1]);class T extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===R.UrlElicitationRequired&&Q){let Y=Q;if(Y.elicitations)return new r7(Y.elicitations,Z)}return new T($,Z,Q)}}class r7 extends T{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(R.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function q1($){return $==="completed"||$==="failed"||$==="cancelled"}import*as jF from"zod/v4-mini";var UF=Symbol("Let zodToJsonSchema decide on which parser to use");import{ZodFirstPartyTypeKind as AC}from"zod/v3";import{ZodFirstPartyTypeKind as SR}from"zod/v3";import{ZodFirstPartyTypeKind as QE}from"zod/v3";var eR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function J4($){let Q=N5($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=S7(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function K4($,Z){let Q=R0($,Z);if(!Q.success)throw Q.error;return Q.data}var PF=60000;class B4{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(P5,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(I5,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(w5,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(T5,async(Z,Q)=>{let Y=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!Y)throw new T(R.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(E5,async(Z,Q)=>{let Y=async()=>{let W=Z.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(W,Q.sessionId)){if(X.type==="response"||X.type==="error"){let J=X.message,B=J.id,K=this._requestResolvers.get(B);if(K)if(this._requestResolvers.delete(B),X.type==="response")K(J);else{let V=J,z=new T(V.error.code,V.error.message,V.error.data);K(z)}else{let V=X.type==="response"?"Response":"Error";this._onerror(Error(`${V} handler missing for request ${B}`))}continue}await this._transport?.send(X.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(W,Q.sessionId);if(!G)throw new T(R.InvalidParams,`Task not found: ${W}`);if(!q1(G.status))return await this._waitForTaskUpdate(W,Q.signal),await Y();if(q1(G.status)){let X=await this._taskStore.getTaskResult(W,Q.sessionId);return this._clearTaskQueue(W),{...X,_meta:{...X._meta,[U1]:{taskId:W}}}}return await Y()};return await Y()}),this.setRequestHandler(C5,async(Z,Q)=>{try{let{tasks:Y,nextCursor:W}=await this._taskStore.listTasks(Z.params?.cursor,Q.sessionId);return{tasks:Y,nextCursor:W,_meta:{}}}catch(Y){throw new T(R.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(y5,async(Z,Q)=>{try{let Y=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!Y)throw new T(R.InvalidParams,`Task not found: ${Z.params.taskId}`);if(q1(Y.status))throw new T(R.InvalidParams,`Cannot cancel task in terminal status: ${Y.status}`);await this._taskStore.updateTaskStatus(Z.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(Z.params.taskId);let W=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!W)throw new T(R.InvalidParams,`Task not found after cancellation: ${Z.params.taskId}`);return{_meta:{},...W}}catch(Y){if(Y instanceof T)throw Y;throw new T(R.InvalidRequest,`Failed to cancel task: ${Y instanceof Error?Y.message:String(Y)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,Q,Y,W=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:Q,resetTimeoutOnProgress:W,onTimeout:Y})}_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($),T.fromError(R.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=(W)=>{Q?.(W),this._onerror(W)};let Y=this._transport?.onmessage;this._transport.onmessage=(W,G)=>{if(Y?.(W,G),ZZ(W)||g7(W))this._onresponse(W);else if(f8(W))this._onrequest(W,G);else if(v7(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},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=T.fromError(R.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,Y=this._transport,W=$.params?._meta?.[U1]?.taskId;if(Q===void 0){let K={jsonrpc:"2.0",id:$.id,error:{code:R.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:K,timestamp:Date.now()},Y?.sessionId).catch((V)=>this._onerror(Error(`Failed to enqueue error response: ${V}`)));else Y?.send(K).catch((V)=>this._onerror(Error(`Failed to send an error response: ${V}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let X=x7($.params)?$.params.task:void 0,J=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,B={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(K)=>{if(G.signal.aborted)return;let V={relatedRequestId:$.id};if(W)V.relatedTask={taskId:W};await this.notification(K,V)},sendRequest:async(K,V,z)=>{if(G.signal.aborted)throw new T(R.ConnectionClosed,"Request was cancelled");let F={...z,relatedRequestId:$.id};if(W&&!F.relatedTask)F.relatedTask={taskId:W};let L=F.relatedTask?.taskId??W;if(L&&J)await J.updateTaskStatus(L,"input_required");return await this.request(K,V,F)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:W,taskStore:J,taskRequestedTtl:X?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,B)).then(async(K)=>{if(G.signal.aborted)return;let V={result:K,jsonrpc:"2.0",id:$.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:V,timestamp:Date.now()},Y?.sessionId);else await Y?.send(V)},async(K)=>{if(G.signal.aborted)return;let V={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(K.code)?K.code:R.InternalError,message:K.message??"Internal error",...K.data!==void 0&&{data:K.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:V,timestamp:Date.now()},Y?.sessionId);else await Y?.send(V)}).catch((K)=>this._onerror(Error(`Failed to send response: ${K}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...Q}=$.params,Y=Number(Z),W=this._progressHandlers.get(Y);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(Y),X=this._timeoutInfo.get(Y);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(J){this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),G(J);return}W(Q)}_onresponse($){let Z=Number($.id),Q=this._requestResolvers.get(Z);if(Q){if(this._requestResolvers.delete(Z),ZZ($))Q($);else{let G=new T($.error.code,$.error.message,$.error.data);Q(G)}return}let Y=this._responseHandlers.get(Z);if(Y===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(Z),this._cleanupTimeout(Z);let W=!1;if(ZZ($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")W=!0,this._taskProgressTokens.set(X.taskId,Z)}}if(!W)this._progressHandlers.delete(Z);if(ZZ($))Y($);else{let G=T.fromError($.error.code,$.error.message,$.error.data);Y(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,Q){let{task:Y}=Q??{};if(!Y){try{yield{type:"result",result:await this.request($,Z,Q)}}catch(G){yield{type:"error",error:G instanceof T?G:new T(R.InternalError,String(G))}}return}let W;try{let G=await this.request($,v1,Q);if(G.task)W=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new T(R.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:W},Q);if(yield{type:"taskStatus",task:X},q1(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},Z,Q)};else if(X.status==="failed")yield{type:"error",error:new T(R.InternalError,`Task ${W} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new T(R.InternalError,`Task ${W} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},Z,Q)};return}let J=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,J)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof T?G:new T(R.InternalError,String(G))}}}request($,Z,Q){let{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G,task:X,relatedTask:J}=Q??{};return new Promise((B,K)=>{let V=(A)=>{K(A)};if(!this._transport){V(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),X)this.assertTaskCapability($.method)}catch(A){V(A);return}Q?.signal?.throwIfAborted();let z=this._requestMessageId++,F={...$,jsonrpc:"2.0",id:z};if(Q?.onprogress)this._progressHandlers.set(z,Q.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||{},[U1]:J}};let L=(A)=>{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(A)}},{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G}).catch((j)=>this._onerror(Error(`Failed to send cancellation: ${j}`)));let N=A instanceof T?A:new T(R.RequestTimeout,String(A));K(N)};this._responseHandlers.set(z,(A)=>{if(Q?.signal?.aborted)return;if(A instanceof Error)return K(A);try{let N=R0(Z,A.result);if(!N.success)K(N.error);else B(N.data)}catch(N){K(N)}}),Q?.signal?.addEventListener("abort",()=>{L(Q?.signal?.reason)});let D=Q?.timeout??PF,U=()=>L(T.fromError(R.RequestTimeout,"Request timed out",{timeout:D}));this._setupTimeout(z,D,Q?.maxTotalTimeout,U,Q?.resetTimeoutOnProgress??!1);let q=J?.taskId;if(q){let A=(N)=>{let j=this._responseHandlers.get(z);if(j)j(N);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,A),this._enqueueTaskMessage(q,{type:"request",message:F,timestamp:Date.now()}).catch((N)=>{this._cleanupTimeout(z),K(N)})}else this._transport.send(F,{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G}).catch((A)=>{this._cleanupTimeout(z),K(A)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},R5,Z)}async getTaskResult($,Z,Q){return this.request({method:"tasks/result",params:$},Z,Q)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},S5,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},m7,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||{},[U1]: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||{},[U1]: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||{},[U1]:Z.relatedTask}}};await this._transport.send(G,Z)}setRequestHandler($,Z){let Q=J4($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,W)=>{let G=K4($,Y);return Promise.resolve(Z(G,W))})}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=J4($);this._notificationHandlers.set(Q,(Y)=>{let W=K4($,Y);return Promise.resolve(Z(W))})}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 Y=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,Q,Y)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,Z);for(let Y of Q)if(Y.type==="request"&&f8(Y.message)){let W=Y.message.id,G=this._requestResolvers.get(W);if(G)G(new T(R.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,Z){let Q=this._options?.defaultTaskPollInterval??1000;try{let Y=await this._taskStore?.getTask($);if(Y?.pollInterval)Q=Y.pollInterval}catch{}return new Promise((Y,W)=>{if(Z.aborted){W(new T(R.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);Z.addEventListener("abort",()=>{clearTimeout(G),W(new T(R.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,Z){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(Y)=>{if(!$)throw Error("No request provided");return await Q.createTask(Y,$.id,{method:$.method,params:$.params},Z)},getTask:async(Y)=>{let W=await Q.getTask(Y,Z);if(!W)throw new T(R.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(Y,W,G)=>{await Q.storeTaskResult(Y,W,G,Z);let X=await Q.getTask(Y,Z);if(X){let J=XZ.parse({method:"notifications/tasks/status",params:X});if(await this.notification(J),q1(X.status))this._cleanupTaskProgressHandler(Y)}},getTaskResult:(Y)=>{return Q.getTaskResult(Y,Z)},updateTaskStatus:async(Y,W,G)=>{let X=await Q.getTask(Y,Z);if(!X)throw new T(R.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(q1(X.status))throw new T(R.InvalidParams,`Cannot update task "${Y}" from terminal status "${X.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(Y,W,G,Z);let J=await Q.getTask(Y,Z);if(J){let B=XZ.parse({method:"notifications/tasks/status",params:J});if(await this.notification(B),q1(J.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,Z)}}}}function t7($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function o7($,Z){let Q={...$};for(let Y in Z){let W=Y,G=Z[W];if(G===void 0)continue;let X=Q[W];if(t7(X)&&t7(G))Q[W]={...X,...G};else Q[W]=G}return Q}var _J=R6(W9(),1),xJ=R6(bJ(),1);function iM(){let $=new _J.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return xJ.default($),$}class D9{constructor($){this._ajv=$??iM()}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 L9{constructor($){this._client=$}async*callToolStream($,Z=H$,Q){let Y=this._client,W={...Q,task:Q?.task??(Y.isToolTask($.name)?{}:void 0)},G=Y.requestStream({method:"tools/call",params:$},Z,W),X=Y.getToolOutputValidator($.name);for await(let J of G){if(J.type==="result"&&X){let B=J.result;if(!B.structuredContent&&!B.isError){yield{type:"error",error:new T(R.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`)};return}if(B.structuredContent)try{let K=X(B.structuredContent);if(!K.valid){yield{type:"error",error:new T(R.InvalidParams,`Structured content does not match the tool's output schema: ${K.errorMessage}`)};return}}catch(K){if(K instanceof T){yield{type:"error",error:K};return}yield{type:"error",error:new T(R.InvalidParams,`Failed to validate structured content: ${K instanceof Error?K.message:String(K)}`)};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 fJ($,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 D6($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let Q=Z,Y=$.properties;for(let W of Object.keys(Y)){let G=Y[W];if(Q[W]===void 0&&Object.prototype.hasOwnProperty.call(G,"default"))Q[W]=G.default;if(Q[W]!==void 0)D6(G,Q[W])}}if(Array.isArray($.anyOf)){for(let Q of $.anyOf)if(typeof Q!=="boolean")D6(Q,Z)}if(Array.isArray($.oneOf)){for(let Q of $.oneOf)if(typeof Q!=="boolean")D6(Q,Z)}}function nM($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,Q=$.url!==void 0;return{supportsFormMode:Z||!Z&&!Q,supportsUrlMode:Q}}class U9 extends B4{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 D9,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",$4,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",s8,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",d8,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new L9(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=o7(this._capabilities,$)}setRequestHandler($,Z){let Y=N5($)?.method;if(!Y)throw Error("Schema is missing a method literal");let W;if(J$(Y)){let X=Y;W=X._zod?.def?.value??X.value}else{let X=Y;W=X._def?.value??X.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");let G=W;if(G==="elicitation/create"){let X=async(J,B)=>{let K=R0(W4,J);if(!K.success){let A=K.error instanceof Error?K.error.message:String(K.error);throw new T(R.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:V}=K.data;V.mode=V.mode??"form";let{supportsFormMode:z,supportsUrlMode:F}=nM(this._capabilities.elicitation);if(V.mode==="form"&&!z)throw new T(R.InvalidParams,"Client does not support form-mode elicitation requests");if(V.mode==="url"&&!F)throw new T(R.InvalidParams,"Client does not support URL-mode elicitation requests");let L=await Promise.resolve(Z(J,B));if(V.task){let A=R0(v1,L);if(!A.success){let N=A.error instanceof Error?A.error.message:String(A.error);throw new T(R.InvalidParams,`Invalid task creation result: ${N}`)}return A.data}let D=R0(G4,L);if(!D.success){let A=D.error instanceof Error?D.error.message:String(D.error);throw new T(R.InvalidParams,`Invalid elicitation result: ${A}`)}let U=D.data,q=V.mode==="form"?V.requestedSchema:void 0;if(V.mode==="form"&&U.action==="accept"&&U.content&&q){if(this._capabilities.elicitation?.form?.applyDefaults)try{D6(q,U.content)}catch{}}return U};return super.setRequestHandler($,X)}if(G==="sampling/createMessage"){let X=async(J,B)=>{let K=R0(Z4,J);if(!K.success){let U=K.error instanceof Error?K.error.message:String(K.error);throw new T(R.InvalidParams,`Invalid sampling request: ${U}`)}let{params:V}=K.data,z=await Promise.resolve(Z(J,B));if(V.task){let U=R0(v1,z);if(!U.success){let q=U.error instanceof Error?U.error.message:String(U.error);throw new T(R.InvalidParams,`Invalid task creation result: ${q}`)}return U.data}let L=V.tools||V.toolChoice?Y4:Q4,D=R0(L,z);if(!D.success){let U=D.error instanceof Error?D.error.message:String(D.error);throw new T(R.InvalidParams,`Invalid sampling result: ${U}`)}return D.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:x8,capabilities:this._capabilities,clientInfo:this._clientInfo}},h8,Z);if(Q===void 0)throw Error(`Server sent invalid initialize result: ${Q}`);if(!y7.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;fJ(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},f1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},X4,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},f1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},o8,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},i8,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},m8,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},l8,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},c8,Z)}async subscribeResource($,Z){return this.request({method:"resources/subscribe",params:$},f1,Z)}async unsubscribeResource($,Z){return this.request({method:"resources/unsubscribe",params:$},f1,Z)}async callTool($,Z=H$,Q){if(this.isToolTaskRequired($.name))throw new T(R.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let Y=await this.request({method:"tools/call",params:$},Z,Q),W=this.getToolOutputValidator($.name);if(W){if(!Y.structuredContent&&!Y.isError)throw new T(R.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(Y.structuredContent)try{let G=W(Y.structuredContent);if(!G.valid)throw new T(R.InvalidParams,`Structured content does not match the tool's output schema: ${G.errorMessage}`)}catch(G){if(G instanceof T)throw G;throw new T(R.InvalidParams,`Failed to validate structured content: ${G instanceof Error?G.message:String(G)}`)}}return Y}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 Y=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,Y)}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:$},e8,Z);return this.cacheToolMetadata(Q.tools),Q}_setupListChangedHandler($,Z,Q,Y){let W=n7.safeParse(Q);if(!W.success)throw Error(`Invalid ${$} listChanged options: ${W.error.message}`);if(typeof Q.onChanged!=="function")throw Error(`Invalid ${$} listChanged options: onChanged must be a function`);let{autoRefresh:G,debounceMs:X}=W.data,{onChanged:J}=Q,B=async()=>{if(!G){J(null,null);return}try{let V=await Y();J(null,V)}catch(V){let z=V instanceof Error?V:Error(String(V));J(z,null)}},K=()=>{if(X){let V=this._listChangedDebounceTimers.get($);if(V)clearTimeout(V);let z=setTimeout(B,X);this._listChangedDebounceTimers.set($,z)}else B()};this.setNotificationHandler(Z,K)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var T3=R6(w3(),1);import R9 from"process";import{PassThrough as wj}from"stream";class T9{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
200
|
-
`);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),
|
|
201
|
-
`}var
|
|
203
|
+
${Z.trim()}`;return W}function OY($,Z){let{meta:Q,body:Y}=z5(Z),W=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((B)=>B.trim()):void 0;return{name:$,description:W,body:Y,...G?{model:G}:{},...J?{allowedTools:J}:{}}}async function NY($){let Z;try{Z=await TV($)}catch{return[]}let Q=[];for(let Y of Z.filter((W)=>W.endsWith(".md")).sort())try{let W=await IV(E4($,Y),"utf8");Q.push(OY(EV(Y,".md"),W))}catch{}return Q}async function SV($={}){let Z=await NY($.userDir??E4(RV(),".mu","commands")),Q=$.projectDir?await NY(E4($.projectDir,".mu","commands")):[],Y=new Map;for(let W of[...Z,...Q])Y.set(W.name,W);return[...Y.values()]}function CV($,Z){return{name:$.name,description:$.description,run:async(Q)=>{let Y={kind:"markdown-command",prompt:MY($.body,Q.args),...$.model?{model:$.model}:{},...$.allowedTools?{allowedTools:$.allowedTools}:{}};if(Z)return await Z(Y.prompt,{...Y.model?{model:Y.model}:{},...Y.allowedTools?{allowedTools:Y.allowedTools}:{}}),{handled:!0};return{handled:!0,data:Y}}}}import{readFile as Fj}from"fs/promises";import{homedir as Lj}from"os";import{dirname as Dj,isAbsolute as Uj,join as N3,resolve as qj}from"path";import*as yV from"zod/v3";import*as F5 from"zod/v4-mini";function W$($){return!!$._zod}function R0($,Z){if(W$($))return F5.safeParse($,Z);return $.safeParse(Z)}function L5($){if(!$)return;let Z;if(W$($))Z=$._zod?.def?.shape;else Z=$.shape;if(!Z)return;if(typeof Z==="function")try{return Z()}catch{return}return Z}function jY($){if(W$($)){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 Y=$.value;if(Y!==void 0)return Y;return}import*as H from"zod/v4";var S4="2025-11-25";var PY=[S4,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],L1="io.modelcontextprotocol/related-task",U5="2.0",a=H.custom(($)=>$!==null&&(typeof $==="object"||typeof $==="function")),wY=H.union([H.string(),H.number().int()]),TY=H.string(),mI=H.looseObject({ttl:H.number().optional(),pollInterval:H.number().optional()}),bV=H.object({ttl:H.number().optional()}),_V=H.object({taskId:H.string()}),C4=H.looseObject({progressToken:wY.optional(),[L1]:_V.optional()}),q0=H.object({_meta:C4.optional()}),t$=q0.extend({task:bV.optional()}),IY=($)=>t$.safeParse($).success,s=H.object({method:H.string(),params:q0.loose().optional()}),O0=H.object({_meta:C4.optional()}),j0=H.object({method:H.string(),params:O0.loose().optional()}),e=H.looseObject({_meta:C4.optional()}),q5=H.union([H.string(),H.number().int()]),RY=H.object({jsonrpc:H.literal(U5),id:q5,...s.shape}).strict(),y4=($)=>RY.safeParse($).success,EY=H.object({jsonrpc:H.literal(U5),...j0.shape}).strict(),SY=($)=>EY.safeParse($).success,b4=H.object({jsonrpc:H.literal(U5),id:q5,result:e}).strict(),o$=($)=>b4.safeParse($).success;var R;(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"})(R||(R={}));var _4=H.object({jsonrpc:H.literal(U5),id:q5.optional(),error:H.object({code:H.number().int(),message:H.string(),data:H.unknown().optional()})}).strict();var CY=($)=>_4.safeParse($).success;var yY=H.union([RY,EY,b4,_4]),lI=H.union([b4,_4]),x1=e.strict(),xV=O0.extend({requestId:q5.optional(),reason:H.string().optional()}),A5=j0.extend({method:H.literal("notifications/cancelled"),params:xV}),kV=H.object({src:H.string(),mimeType:H.string().optional(),sizes:H.array(H.string()).optional(),theme:H.enum(["light","dark"]).optional()}),s$=H.object({icons:H.array(kV).optional()}),G$=H.object({name:H.string(),title:H.string().optional()}),bY=G$.extend({...G$.shape,...s$.shape,version:H.string(),websiteUrl:H.string().optional(),description:H.string().optional()}),fV=H.intersection(H.object({applyDefaults:H.boolean().optional()}),H.record(H.string(),H.unknown())),vV=H.preprocess(($)=>{if($&&typeof $==="object"&&!Array.isArray($)){if(Object.keys($).length===0)return{form:{}}}return $},H.intersection(H.object({form:fV.optional(),url:a.optional()}),H.record(H.string(),H.unknown()).optional())),gV=H.looseObject({list:a.optional(),cancel:a.optional(),requests:H.looseObject({sampling:H.looseObject({createMessage:a.optional()}).optional(),elicitation:H.looseObject({create:a.optional()}).optional()}).optional()}),hV=H.looseObject({list:a.optional(),cancel:a.optional(),requests:H.looseObject({tools:H.looseObject({call:a.optional()}).optional()}).optional()}),uV=H.object({experimental:H.record(H.string(),a).optional(),sampling:H.object({context:a.optional(),tools:a.optional()}).optional(),elicitation:vV.optional(),roots:H.object({listChanged:H.boolean().optional()}).optional(),tasks:gV.optional(),extensions:H.record(H.string(),a).optional()}),mV=q0.extend({protocolVersion:H.string(),capabilities:uV,clientInfo:bY}),lV=s.extend({method:H.literal("initialize"),params:mV});var pV=H.object({experimental:H.record(H.string(),a).optional(),logging:a.optional(),completions:a.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(),a).optional()}),x4=e.extend({protocolVersion:H.string(),capabilities:pV,serverInfo:bY,instructions:H.string().optional()}),cV=j0.extend({method:H.literal("notifications/initialized"),params:O0.optional()});var N5=s.extend({method:H.literal("ping"),params:q0.optional()}),dV=H.object({progress:H.number(),total:H.optional(H.number()),message:H.optional(H.string())}),iV=H.object({...O0.shape,...dV.shape,progressToken:wY}),M5=j0.extend({method:H.literal("notifications/progress"),params:iV}),nV=q0.extend({cursor:TY.optional()}),e$=s.extend({params:nV.optional()}),$Z=e.extend({nextCursor:TY.optional()}),aV=H.enum(["working","input_required","completed","failed","cancelled"]),ZZ=H.object({taskId:H.string(),status:aV,ttl:H.union([H.number(),H.null()]),createdAt:H.string(),lastUpdatedAt:H.string(),pollInterval:H.optional(H.number()),statusMessage:H.optional(H.string())}),k1=e.extend({task:ZZ}),rV=O0.merge(ZZ),QZ=j0.extend({method:H.literal("notifications/tasks/status"),params:rV}),O5=s.extend({method:H.literal("tasks/get"),params:q0.extend({taskId:H.string()})}),j5=e.merge(ZZ),P5=s.extend({method:H.literal("tasks/result"),params:q0.extend({taskId:H.string()})}),pI=e.loose(),w5=e$.extend({method:H.literal("tasks/list")}),T5=$Z.extend({tasks:H.array(ZZ)}),I5=s.extend({method:H.literal("tasks/cancel"),params:q0.extend({taskId:H.string()})}),_Y=e.merge(ZZ),xY=H.object({uri:H.string(),mimeType:H.optional(H.string()),_meta:H.record(H.string(),H.unknown()).optional()}),kY=xY.extend({text:H.string()}),k4=H.string().refine(($)=>{try{return atob($),!0}catch{return!1}},{message:"Invalid Base64 string"}),fY=xY.extend({blob:k4}),YZ=H.enum(["user","assistant"]),X$=H.object({audience:H.array(YZ).optional(),priority:H.number().min(0).max(1).optional(),lastModified:H.iso.datetime({offset:!0}).optional()}),vY=H.object({...G$.shape,...s$.shape,uri:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),size:H.optional(H.number()),annotations:X$.optional(),_meta:H.optional(H.looseObject({}))}),tV=H.object({...G$.shape,...s$.shape,uriTemplate:H.string(),description:H.optional(H.string()),mimeType:H.optional(H.string()),annotations:X$.optional(),_meta:H.optional(H.looseObject({}))}),oV=e$.extend({method:H.literal("resources/list")}),f4=$Z.extend({resources:H.array(vY)}),sV=e$.extend({method:H.literal("resources/templates/list")}),v4=$Z.extend({resourceTemplates:H.array(tV)}),g4=q0.extend({uri:H.string()}),eV=g4,$z=s.extend({method:H.literal("resources/read"),params:eV}),h4=e.extend({contents:H.array(H.union([kY,fY]))}),u4=j0.extend({method:H.literal("notifications/resources/list_changed"),params:O0.optional()}),Zz=g4,Qz=s.extend({method:H.literal("resources/subscribe"),params:Zz}),Yz=g4,Wz=s.extend({method:H.literal("resources/unsubscribe"),params:Yz}),Gz=O0.extend({uri:H.string()}),Xz=j0.extend({method:H.literal("notifications/resources/updated"),params:Gz}),Jz=H.object({name:H.string(),description:H.optional(H.string()),required:H.optional(H.boolean())}),Kz=H.object({...G$.shape,...s$.shape,description:H.optional(H.string()),arguments:H.optional(H.array(Jz)),_meta:H.optional(H.looseObject({}))}),Bz=e$.extend({method:H.literal("prompts/list")}),m4=$Z.extend({prompts:H.array(Kz)}),Hz=q0.extend({name:H.string(),arguments:H.record(H.string(),H.string()).optional()}),Vz=s.extend({method:H.literal("prompts/get"),params:Hz}),l4=H.object({type:H.literal("text"),text:H.string(),annotations:X$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),p4=H.object({type:H.literal("image"),data:k4,mimeType:H.string(),annotations:X$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),c4=H.object({type:H.literal("audio"),data:k4,mimeType:H.string(),annotations:X$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),zz=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()}),Fz=H.object({type:H.literal("resource"),resource:H.union([kY,fY]),annotations:X$.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Lz=vY.extend({type:H.literal("resource_link")}),d4=H.union([l4,p4,c4,Lz,Fz]),Dz=H.object({role:YZ,content:d4}),i4=e.extend({description:H.string().optional(),messages:H.array(Dz)}),n4=j0.extend({method:H.literal("notifications/prompts/list_changed"),params:O0.optional()}),Uz=H.object({title:H.string().optional(),readOnlyHint:H.boolean().optional(),destructiveHint:H.boolean().optional(),idempotentHint:H.boolean().optional(),openWorldHint:H.boolean().optional()}),qz=H.object({taskSupport:H.enum(["required","optional","forbidden"]).optional()}),gY=H.object({...G$.shape,...s$.shape,description:H.string().optional(),inputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),a).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()),outputSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),a).optional(),required:H.array(H.string()).optional()}).catchall(H.unknown()).optional(),annotations:Uz.optional(),execution:qz.optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Az=e$.extend({method:H.literal("tools/list")}),a4=$Z.extend({tools:H.array(gY)}),J$=e.extend({content:H.array(d4).default([]),structuredContent:H.record(H.string(),H.unknown()).optional(),isError:H.boolean().optional()}),cI=J$.or(e.extend({toolResult:H.unknown()})),Nz=t$.extend({name:H.string(),arguments:H.record(H.string(),H.unknown()).optional()}),Mz=s.extend({method:H.literal("tools/call"),params:Nz}),r4=j0.extend({method:H.literal("notifications/tools/list_changed"),params:O0.optional()}),hY=H.object({autoRefresh:H.boolean().default(!0),debounceMs:H.number().int().nonnegative().default(300)}),uY=H.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),Oz=q0.extend({level:uY}),jz=s.extend({method:H.literal("logging/setLevel"),params:Oz}),Pz=O0.extend({level:uY,logger:H.string().optional(),data:H.unknown()}),wz=j0.extend({method:H.literal("notifications/message"),params:Pz}),Tz=H.object({name:H.string().optional()}),Iz=H.object({hints:H.array(Tz).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()}),Rz=H.object({mode:H.enum(["auto","required","none"]).optional()}),Ez=H.object({type:H.literal("tool_result"),toolUseId:H.string().describe("The unique identifier for the corresponding tool call."),content:H.array(d4).default([]),structuredContent:H.object({}).loose().optional(),isError:H.boolean().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),Sz=H.discriminatedUnion("type",[l4,p4,c4]),D5=H.discriminatedUnion("type",[l4,p4,c4,zz,Ez]),Cz=H.object({role:YZ,content:H.union([D5,H.array(D5)]),_meta:H.record(H.string(),H.unknown()).optional()}),yz=t$.extend({messages:H.array(Cz),modelPreferences:Iz.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:a.optional(),tools:H.array(gY).optional(),toolChoice:Rz.optional()}),t4=s.extend({method:H.literal("sampling/createMessage"),params:yz}),o4=e.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens"]).or(H.string())),role:YZ,content:Sz}),s4=e.extend({model:H.string(),stopReason:H.optional(H.enum(["endTurn","stopSequence","maxTokens","toolUse"]).or(H.string())),role:YZ,content:H.union([D5,H.array(D5)])}),bz=H.object({type:H.literal("boolean"),title:H.string().optional(),description:H.string().optional(),default:H.boolean().optional()}),_z=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()}),xz=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()}),kz=H.object({type:H.literal("string"),title:H.string().optional(),description:H.string().optional(),enum:H.array(H.string()),default:H.string().optional()}),fz=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()}),vz=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()}),gz=H.union([kz,fz]),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()}),uz=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()}),mz=H.union([hz,uz]),lz=H.union([vz,gz,mz]),pz=H.union([lz,bz,_z,xz]),cz=t$.extend({mode:H.literal("form").optional(),message:H.string(),requestedSchema:H.object({type:H.literal("object"),properties:H.record(H.string(),pz),required:H.array(H.string()).optional()})}),dz=t$.extend({mode:H.literal("url"),message:H.string(),elicitationId:H.string(),url:H.string().url()}),iz=H.union([cz,dz]),e4=s.extend({method:H.literal("elicitation/create"),params:iz}),nz=O0.extend({elicitationId:H.string()}),az=j0.extend({method:H.literal("notifications/elicitation/complete"),params:nz}),$8=e.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())}),rz=H.object({type:H.literal("ref/resource"),uri:H.string()});var tz=H.object({type:H.literal("ref/prompt"),name:H.string()}),oz=q0.extend({ref:H.union([tz,rz]),argument:H.object({name:H.string(),value:H.string()}),context:H.object({arguments:H.record(H.string(),H.string()).optional()}).optional()}),sz=s.extend({method:H.literal("completion/complete"),params:oz});var Z8=e.extend({completion:H.looseObject({values:H.array(H.string()).max(100),total:H.optional(H.number().int()),hasMore:H.optional(H.boolean())})}),ez=H.object({uri:H.string().startsWith("file://"),name:H.string().optional(),_meta:H.record(H.string(),H.unknown()).optional()}),$F=s.extend({method:H.literal("roots/list"),params:q0.optional()}),ZF=e.extend({roots:H.array(ez)}),QF=j0.extend({method:H.literal("notifications/roots/list_changed"),params:O0.optional()}),dI=H.union([N5,lV,sz,jz,Vz,Bz,oV,sV,$z,Qz,Wz,Mz,Az,O5,P5,w5,I5]),iI=H.union([A5,M5,cV,QF,QZ]),nI=H.union([x1,o4,s4,$8,ZF,j5,T5,k1]),aI=H.union([N5,t4,e4,$F,O5,P5,w5,I5]),rI=H.union([A5,M5,wz,Xz,u4,r4,n4,QZ,az]),tI=H.union([x1,x4,Z8,i4,m4,f4,v4,h4,J$,a4,j5,T5,k1]);class I extends Error{constructor($,Z,Q){super(`MCP error ${$}: ${Z}`);this.code=$,this.data=Q,this.name="McpError"}static fromError($,Z,Q){if($===R.UrlElicitationRequired&&Q){let Y=Q;if(Y.elicitations)return new mY(Y.elicitations,Z)}return new I($,Z,Q)}}class mY extends I{constructor($,Z=`URL elicitation${$.length>1?"s":""} required`){super(R.UrlElicitationRequired,Z,{elicitations:$})}get elicitations(){return this.data?.elicitations??[]}}function D1($){return $==="completed"||$==="failed"||$==="cancelled"}import*as BF from"zod/v4-mini";var YF=Symbol("Let zodToJsonSchema decide on which parser to use");import{ZodFirstPartyTypeKind as tE}from"zod/v3";import{ZodFirstPartyTypeKind as KR}from"zod/v3";import{ZodFirstPartyTypeKind as xR}from"zod/v3";var yR=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Q8($){let Q=L5($)?.method;if(!Q)throw Error("Schema is missing a method literal");let Y=jY(Q);if(typeof Y!=="string")throw Error("Schema method literal must be a string");return Y}function Y8($,Z){let Q=R0($,Z);if(!Q.success)throw Q.error;return Q.data}var HF=60000;class W8{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(A5,(Z)=>{this._oncancel(Z)}),this.setNotificationHandler(M5,(Z)=>{this._onprogress(Z)}),this.setRequestHandler(N5,(Z)=>({})),this._taskStore=$?.taskStore,this._taskMessageQueue=$?.taskMessageQueue,this._taskStore)this.setRequestHandler(O5,async(Z,Q)=>{let Y=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!Y)throw new I(R.InvalidParams,"Failed to retrieve task: Task not found");return{...Y}}),this.setRequestHandler(P5,async(Z,Q)=>{let Y=async()=>{let W=Z.params.taskId;if(this._taskMessageQueue){let X;while(X=await this._taskMessageQueue.dequeue(W,Q.sessionId)){if(X.type==="response"||X.type==="error"){let J=X.message,B=J.id,K=this._requestResolvers.get(B);if(K)if(this._requestResolvers.delete(B),X.type==="response")K(J);else{let V=J,z=new I(V.error.code,V.error.message,V.error.data);K(z)}else{let V=X.type==="response"?"Response":"Error";this._onerror(Error(`${V} handler missing for request ${B}`))}continue}await this._transport?.send(X.message,{relatedRequestId:Q.requestId})}}let G=await this._taskStore.getTask(W,Q.sessionId);if(!G)throw new I(R.InvalidParams,`Task not found: ${W}`);if(!D1(G.status))return await this._waitForTaskUpdate(W,Q.signal),await Y();if(D1(G.status)){let X=await this._taskStore.getTaskResult(W,Q.sessionId);return this._clearTaskQueue(W),{...X,_meta:{...X._meta,[L1]:{taskId:W}}}}return await Y()};return await Y()}),this.setRequestHandler(w5,async(Z,Q)=>{try{let{tasks:Y,nextCursor:W}=await this._taskStore.listTasks(Z.params?.cursor,Q.sessionId);return{tasks:Y,nextCursor:W,_meta:{}}}catch(Y){throw new I(R.InvalidParams,`Failed to list tasks: ${Y instanceof Error?Y.message:String(Y)}`)}}),this.setRequestHandler(I5,async(Z,Q)=>{try{let Y=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!Y)throw new I(R.InvalidParams,`Task not found: ${Z.params.taskId}`);if(D1(Y.status))throw new I(R.InvalidParams,`Cannot cancel task in terminal status: ${Y.status}`);await this._taskStore.updateTaskStatus(Z.params.taskId,"cancelled","Client cancelled task execution.",Q.sessionId),this._clearTaskQueue(Z.params.taskId);let W=await this._taskStore.getTask(Z.params.taskId,Q.sessionId);if(!W)throw new I(R.InvalidParams,`Task not found after cancellation: ${Z.params.taskId}`);return{_meta:{},...W}}catch(Y){if(Y instanceof I)throw Y;throw new I(R.InvalidRequest,`Failed to cancel task: ${Y instanceof Error?Y.message:String(Y)}`)}})}async _oncancel($){if(!$.params.requestId)return;this._requestHandlerAbortControllers.get($.params.requestId)?.abort($.params.reason)}_setupTimeout($,Z,Q,Y,W=!1){this._timeoutInfo.set($,{timeoutId:setTimeout(Y,Z),startTime:Date.now(),timeout:Z,maxTotalTimeout:Q,resetTimeoutOnProgress:W,onTimeout:Y})}_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(R.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=(W)=>{Q?.(W),this._onerror(W)};let Y=this._transport?.onmessage;this._transport.onmessage=(W,G)=>{if(Y?.(W,G),o$(W)||CY(W))this._onresponse(W);else if(y4(W))this._onrequest(W,G);else if(SY(W))this._onnotification(W);else this._onerror(Error(`Unknown message type: ${JSON.stringify(W)}`))},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(R.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,Y=this._transport,W=$.params?._meta?.[L1]?.taskId;if(Q===void 0){let K={jsonrpc:"2.0",id:$.id,error:{code:R.MethodNotFound,message:"Method not found"}};if(W&&this._taskMessageQueue)this._enqueueTaskMessage(W,{type:"error",message:K,timestamp:Date.now()},Y?.sessionId).catch((V)=>this._onerror(Error(`Failed to enqueue error response: ${V}`)));else Y?.send(K).catch((V)=>this._onerror(Error(`Failed to send an error response: ${V}`)));return}let G=new AbortController;this._requestHandlerAbortControllers.set($.id,G);let X=IY($.params)?$.params.task:void 0,J=this._taskStore?this.requestTaskStore($,Y?.sessionId):void 0,B={signal:G.signal,sessionId:Y?.sessionId,_meta:$.params?._meta,sendNotification:async(K)=>{if(G.signal.aborted)return;let V={relatedRequestId:$.id};if(W)V.relatedTask={taskId:W};await this.notification(K,V)},sendRequest:async(K,V,z)=>{if(G.signal.aborted)throw new I(R.ConnectionClosed,"Request was cancelled");let F={...z,relatedRequestId:$.id};if(W&&!F.relatedTask)F.relatedTask={taskId:W};let D=F.relatedTask?.taskId??W;if(D&&J)await J.updateTaskStatus(D,"input_required");return await this.request(K,V,F)},authInfo:Z?.authInfo,requestId:$.id,requestInfo:Z?.requestInfo,taskId:W,taskStore:J,taskRequestedTtl:X?.ttl,closeSSEStream:Z?.closeSSEStream,closeStandaloneSSEStream:Z?.closeStandaloneSSEStream};Promise.resolve().then(()=>{if(X)this.assertTaskHandlerCapability($.method)}).then(()=>Q($,B)).then(async(K)=>{if(G.signal.aborted)return;let V={result:K,jsonrpc:"2.0",id:$.id};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"response",message:V,timestamp:Date.now()},Y?.sessionId);else await Y?.send(V)},async(K)=>{if(G.signal.aborted)return;let V={jsonrpc:"2.0",id:$.id,error:{code:Number.isSafeInteger(K.code)?K.code:R.InternalError,message:K.message??"Internal error",...K.data!==void 0&&{data:K.data}}};if(W&&this._taskMessageQueue)await this._enqueueTaskMessage(W,{type:"error",message:V,timestamp:Date.now()},Y?.sessionId);else await Y?.send(V)}).catch((K)=>this._onerror(Error(`Failed to send response: ${K}`))).finally(()=>{if(this._requestHandlerAbortControllers.get($.id)===G)this._requestHandlerAbortControllers.delete($.id)})}_onprogress($){let{progressToken:Z,...Q}=$.params,Y=Number(Z),W=this._progressHandlers.get(Y);if(!W){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify($)}`));return}let G=this._responseHandlers.get(Y),X=this._timeoutInfo.get(Y);if(X&&G&&X.resetTimeoutOnProgress)try{this._resetTimeout(Y)}catch(J){this._responseHandlers.delete(Y),this._progressHandlers.delete(Y),this._cleanupTimeout(Y),G(J);return}W(Q)}_onresponse($){let Z=Number($.id),Q=this._requestResolvers.get(Z);if(Q){if(this._requestResolvers.delete(Z),o$($))Q($);else{let G=new I($.error.code,$.error.message,$.error.data);Q(G)}return}let Y=this._responseHandlers.get(Z);if(Y===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify($)}`));return}this._responseHandlers.delete(Z),this._cleanupTimeout(Z);let W=!1;if(o$($)&&$.result&&typeof $.result==="object"){let G=$.result;if(G.task&&typeof G.task==="object"){let X=G.task;if(typeof X.taskId==="string")W=!0,this._taskProgressTokens.set(X.taskId,Z)}}if(!W)this._progressHandlers.delete(Z);if(o$($))Y($);else{let G=I.fromError($.error.code,$.error.message,$.error.data);Y(G)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream($,Z,Q){let{task:Y}=Q??{};if(!Y){try{yield{type:"result",result:await this.request($,Z,Q)}}catch(G){yield{type:"error",error:G instanceof I?G:new I(R.InternalError,String(G))}}return}let W;try{let G=await this.request($,k1,Q);if(G.task)W=G.task.taskId,yield{type:"taskCreated",task:G.task};else throw new I(R.InternalError,"Task creation did not return a task");while(!0){let X=await this.getTask({taskId:W},Q);if(yield{type:"taskStatus",task:X},D1(X.status)){if(X.status==="completed")yield{type:"result",result:await this.getTaskResult({taskId:W},Z,Q)};else if(X.status==="failed")yield{type:"error",error:new I(R.InternalError,`Task ${W} failed`)};else if(X.status==="cancelled")yield{type:"error",error:new I(R.InternalError,`Task ${W} was cancelled`)};return}if(X.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:W},Z,Q)};return}let J=X.pollInterval??this._options?.defaultTaskPollInterval??1000;await new Promise((B)=>setTimeout(B,J)),Q?.signal?.throwIfAborted()}}catch(G){yield{type:"error",error:G instanceof I?G:new I(R.InternalError,String(G))}}}request($,Z,Q){let{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G,task:X,relatedTask:J}=Q??{};return new Promise((B,K)=>{let V=(A)=>{K(A)};if(!this._transport){V(Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{if(this.assertCapabilityForMethod($.method),X)this.assertTaskCapability($.method)}catch(A){V(A);return}Q?.signal?.throwIfAborted();let z=this._requestMessageId++,F={...$,jsonrpc:"2.0",id:z};if(Q?.onprogress)this._progressHandlers.set(z,Q.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||{},[L1]:J}};let D=(A)=>{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(A)}},{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G}).catch((j)=>this._onerror(Error(`Failed to send cancellation: ${j}`)));let N=A instanceof I?A:new I(R.RequestTimeout,String(A));K(N)};this._responseHandlers.set(z,(A)=>{if(Q?.signal?.aborted)return;if(A instanceof Error)return K(A);try{let N=R0(Z,A.result);if(!N.success)K(N.error);else B(N.data)}catch(N){K(N)}}),Q?.signal?.addEventListener("abort",()=>{D(Q?.signal?.reason)});let L=Q?.timeout??HF,U=()=>D(I.fromError(R.RequestTimeout,"Request timed out",{timeout:L}));this._setupTimeout(z,L,Q?.maxTotalTimeout,U,Q?.resetTimeoutOnProgress??!1);let q=J?.taskId;if(q){let A=(N)=>{let j=this._responseHandlers.get(z);if(j)j(N);else this._onerror(Error(`Response handler missing for side-channeled request ${z}`))};this._requestResolvers.set(z,A),this._enqueueTaskMessage(q,{type:"request",message:F,timestamp:Date.now()}).catch((N)=>{this._cleanupTimeout(z),K(N)})}else this._transport.send(F,{relatedRequestId:Y,resumptionToken:W,onresumptiontoken:G}).catch((A)=>{this._cleanupTimeout(z),K(A)})})}async getTask($,Z){return this.request({method:"tasks/get",params:$},j5,Z)}async getTaskResult($,Z,Q){return this.request({method:"tasks/result",params:$},Z,Q)}async listTasks($,Z){return this.request({method:"tasks/list",params:$},T5,Z)}async cancelTask($,Z){return this.request({method:"tasks/cancel",params:$},_Y,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||{},[L1]: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||{},[L1]: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||{},[L1]:Z.relatedTask}}};await this._transport.send(G,Z)}setRequestHandler($,Z){let Q=Q8($);this.assertRequestHandlerCapability(Q),this._requestHandlers.set(Q,(Y,W)=>{let G=Y8($,Y);return Promise.resolve(Z(G,W))})}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=Q8($);this._notificationHandlers.set(Q,(Y)=>{let W=Y8($,Y);return Promise.resolve(Z(W))})}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 Y=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue($,Z,Q,Y)}async _clearTaskQueue($,Z){if(this._taskMessageQueue){let Q=await this._taskMessageQueue.dequeueAll($,Z);for(let Y of Q)if(Y.type==="request"&&y4(Y.message)){let W=Y.message.id,G=this._requestResolvers.get(W);if(G)G(new I(R.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(W);else this._onerror(Error(`Resolver missing for request ${W} during task ${$} cleanup`))}}}async _waitForTaskUpdate($,Z){let Q=this._options?.defaultTaskPollInterval??1000;try{let Y=await this._taskStore?.getTask($);if(Y?.pollInterval)Q=Y.pollInterval}catch{}return new Promise((Y,W)=>{if(Z.aborted){W(new I(R.InvalidRequest,"Request cancelled"));return}let G=setTimeout(Y,Q);Z.addEventListener("abort",()=>{clearTimeout(G),W(new I(R.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore($,Z){let Q=this._taskStore;if(!Q)throw Error("No task store configured");return{createTask:async(Y)=>{if(!$)throw Error("No request provided");return await Q.createTask(Y,$.id,{method:$.method,params:$.params},Z)},getTask:async(Y)=>{let W=await Q.getTask(Y,Z);if(!W)throw new I(R.InvalidParams,"Failed to retrieve task: Task not found");return W},storeTaskResult:async(Y,W,G)=>{await Q.storeTaskResult(Y,W,G,Z);let X=await Q.getTask(Y,Z);if(X){let J=QZ.parse({method:"notifications/tasks/status",params:X});if(await this.notification(J),D1(X.status))this._cleanupTaskProgressHandler(Y)}},getTaskResult:(Y)=>{return Q.getTaskResult(Y,Z)},updateTaskStatus:async(Y,W,G)=>{let X=await Q.getTask(Y,Z);if(!X)throw new I(R.InvalidParams,`Task "${Y}" not found - it may have been cleaned up`);if(D1(X.status))throw new I(R.InvalidParams,`Cannot update task "${Y}" from terminal status "${X.status}" to "${W}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await Q.updateTaskStatus(Y,W,G,Z);let J=await Q.getTask(Y,Z);if(J){let B=QZ.parse({method:"notifications/tasks/status",params:J});if(await this.notification(B),D1(J.status))this._cleanupTaskProgressHandler(Y)}},listTasks:(Y)=>{return Q.listTasks(Y,Z)}}}}function lY($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function pY($,Z){let Q={...$};for(let Y in Z){let W=Y,G=Z[W];if(G===void 0)continue;let X=Q[W];if(lY(X)&&lY(G))Q[W]={...X,...G};else Q[W]=G}return Q}var TJ=j6(e8(),1),IJ=j6(wJ(),1);function _O(){let $=new TJ.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return IJ.default($),$}class B9{constructor($){this._ajv=$??_O()}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 H9{constructor($){this._client=$}async*callToolStream($,Z=J$,Q){let Y=this._client,W={...Q,task:Q?.task??(Y.isToolTask($.name)?{}:void 0)},G=Y.requestStream({method:"tools/call",params:$},Z,W),X=Y.getToolOutputValidator($.name);for await(let J of G){if(J.type==="result"&&X){let B=J.result;if(!B.structuredContent&&!B.isError){yield{type:"error",error:new I(R.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`)};return}if(B.structuredContent)try{let K=X(B.structuredContent);if(!K.valid){yield{type:"error",error:new I(R.InvalidParams,`Structured content does not match the tool's output schema: ${K.errorMessage}`)};return}}catch(K){if(K instanceof I){yield{type:"error",error:K};return}yield{type:"error",error:new I(R.InvalidParams,`Failed to validate structured content: ${K instanceof Error?K.message:String(K)}`)};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 RJ($,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 EJ($,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 B6($,Z){if(!$||Z===null||typeof Z!=="object")return;if($.type==="object"&&$.properties&&typeof $.properties==="object"){let Q=Z,Y=$.properties;for(let W of Object.keys(Y)){let G=Y[W];if(Q[W]===void 0&&Object.prototype.hasOwnProperty.call(G,"default"))Q[W]=G.default;if(Q[W]!==void 0)B6(G,Q[W])}}if(Array.isArray($.anyOf)){for(let Q of $.anyOf)if(typeof Q!=="boolean")B6(Q,Z)}if(Array.isArray($.oneOf)){for(let Q of $.oneOf)if(typeof Q!=="boolean")B6(Q,Z)}}function xO($){if(!$)return{supportsFormMode:!1,supportsUrlMode:!1};let Z=$.form!==void 0,Q=$.url!==void 0;return{supportsFormMode:Z||!Z&&!Q,supportsUrlMode:Q}}class V9 extends W8{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 B9,Z?.listChanged)this._pendingListChangedConfig=Z.listChanged}_setupListChangedHandlers($){if($.tools&&this._serverCapabilities?.tools?.listChanged)this._setupListChangedHandler("tools",r4,$.tools,async()=>{return(await this.listTools()).tools});if($.prompts&&this._serverCapabilities?.prompts?.listChanged)this._setupListChangedHandler("prompts",n4,$.prompts,async()=>{return(await this.listPrompts()).prompts});if($.resources&&this._serverCapabilities?.resources?.listChanged)this._setupListChangedHandler("resources",u4,$.resources,async()=>{return(await this.listResources()).resources})}get experimental(){if(!this._experimental)this._experimental={tasks:new H9(this)};return this._experimental}registerCapabilities($){if(this.transport)throw Error("Cannot register capabilities after connecting to transport");this._capabilities=pY(this._capabilities,$)}setRequestHandler($,Z){let Y=L5($)?.method;if(!Y)throw Error("Schema is missing a method literal");let W;if(W$(Y)){let X=Y;W=X._zod?.def?.value??X.value}else{let X=Y;W=X._def?.value??X.value}if(typeof W!=="string")throw Error("Schema method literal must be a string");let G=W;if(G==="elicitation/create"){let X=async(J,B)=>{let K=R0(e4,J);if(!K.success){let A=K.error instanceof Error?K.error.message:String(K.error);throw new I(R.InvalidParams,`Invalid elicitation request: ${A}`)}let{params:V}=K.data;V.mode=V.mode??"form";let{supportsFormMode:z,supportsUrlMode:F}=xO(this._capabilities.elicitation);if(V.mode==="form"&&!z)throw new I(R.InvalidParams,"Client does not support form-mode elicitation requests");if(V.mode==="url"&&!F)throw new I(R.InvalidParams,"Client does not support URL-mode elicitation requests");let D=await Promise.resolve(Z(J,B));if(V.task){let A=R0(k1,D);if(!A.success){let N=A.error instanceof Error?A.error.message:String(A.error);throw new I(R.InvalidParams,`Invalid task creation result: ${N}`)}return A.data}let L=R0($8,D);if(!L.success){let A=L.error instanceof Error?L.error.message:String(L.error);throw new I(R.InvalidParams,`Invalid elicitation result: ${A}`)}let U=L.data,q=V.mode==="form"?V.requestedSchema:void 0;if(V.mode==="form"&&U.action==="accept"&&U.content&&q){if(this._capabilities.elicitation?.form?.applyDefaults)try{B6(q,U.content)}catch{}}return U};return super.setRequestHandler($,X)}if(G==="sampling/createMessage"){let X=async(J,B)=>{let K=R0(t4,J);if(!K.success){let U=K.error instanceof Error?K.error.message:String(K.error);throw new I(R.InvalidParams,`Invalid sampling request: ${U}`)}let{params:V}=K.data,z=await Promise.resolve(Z(J,B));if(V.task){let U=R0(k1,z);if(!U.success){let q=U.error instanceof Error?U.error.message:String(U.error);throw new I(R.InvalidParams,`Invalid task creation result: ${q}`)}return U.data}let D=V.tools||V.toolChoice?s4:o4,L=R0(D,z);if(!L.success){let U=L.error instanceof Error?L.error.message:String(L.error);throw new I(R.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:S4,capabilities:this._capabilities,clientInfo:this._clientInfo}},x4,Z);if(Q===void 0)throw Error(`Server sent invalid initialize result: ${Q}`);if(!PY.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($){RJ(this._serverCapabilities?.tasks?.requests,$,"Server")}assertTaskHandlerCapability($){if(!this._capabilities)return;EJ(this._capabilities.tasks?.requests,$,"Client")}async ping($){return this.request({method:"ping"},x1,$)}async complete($,Z){return this.request({method:"completion/complete",params:$},Z8,Z)}async setLoggingLevel($,Z){return this.request({method:"logging/setLevel",params:{level:$}},x1,Z)}async getPrompt($,Z){return this.request({method:"prompts/get",params:$},i4,Z)}async listPrompts($,Z){return this.request({method:"prompts/list",params:$},m4,Z)}async listResources($,Z){return this.request({method:"resources/list",params:$},f4,Z)}async listResourceTemplates($,Z){return this.request({method:"resources/templates/list",params:$},v4,Z)}async readResource($,Z){return this.request({method:"resources/read",params:$},h4,Z)}async subscribeResource($,Z){return this.request({method:"resources/subscribe",params:$},x1,Z)}async unsubscribeResource($,Z){return this.request({method:"resources/unsubscribe",params:$},x1,Z)}async callTool($,Z=J$,Q){if(this.isToolTaskRequired($.name))throw new I(R.InvalidRequest,`Tool "${$.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let Y=await this.request({method:"tools/call",params:$},Z,Q),W=this.getToolOutputValidator($.name);if(W){if(!Y.structuredContent&&!Y.isError)throw new I(R.InvalidRequest,`Tool ${$.name} has an output schema but did not return structured content`);if(Y.structuredContent)try{let G=W(Y.structuredContent);if(!G.valid)throw new I(R.InvalidParams,`Structured content does not match the tool's output schema: ${G.errorMessage}`)}catch(G){if(G instanceof I)throw G;throw new I(R.InvalidParams,`Failed to validate structured content: ${G instanceof Error?G.message:String(G)}`)}}return Y}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 Y=this._jsonSchemaValidator.getValidator(Z.outputSchema);this._cachedToolOutputValidators.set(Z.name,Y)}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:$},a4,Z);return this.cacheToolMetadata(Q.tools),Q}_setupListChangedHandler($,Z,Q,Y){let W=hY.safeParse(Q);if(!W.success)throw Error(`Invalid ${$} listChanged options: ${W.error.message}`);if(typeof Q.onChanged!=="function")throw Error(`Invalid ${$} listChanged options: onChanged must be a function`);let{autoRefresh:G,debounceMs:X}=W.data,{onChanged:J}=Q,B=async()=>{if(!G){J(null,null);return}try{let V=await Y();J(null,V)}catch(V){let z=V instanceof Error?V:Error(String(V));J(z,null)}},K=()=>{if(X){let V=this._listChangedDebounceTimers.get($);if(V)clearTimeout(V);let z=setTimeout(B,X);this._listChangedDebounceTimers.set($,z)}else B()};this.setNotificationHandler(Z,K)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}}var A3=j6(U3(),1);import j9 from"process";import{PassThrough as Vj}from"stream";class O9{append($){this._buffer=this._buffer?Buffer.concat([this._buffer,$]):$}readMessage(){if(!this._buffer)return null;let $=this._buffer.indexOf(`
|
|
204
|
+
`);if($===-1)return null;let Z=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),Hj(Z)}clear(){this._buffer=void 0}}function Hj($){return yY.parse(JSON.parse($))}function q3($){return JSON.stringify($)+`
|
|
205
|
+
`}var zj=j9.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function P9(){let $={};for(let Z of zj){let Q=j9.env[Z];if(Q===void 0)continue;if(Q.startsWith("()"))continue;$[Z]=Q}return $}class w9{constructor($){if(this._readBuffer=new O9,this._stderrStream=null,this._serverParams=$,$.stderr==="pipe"||$.stderr==="overlapped")this._stderrStream=new Vj}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=A3.default(this._serverParams.command,this._serverParams.args??[],{env:{...P9(),...this._serverParams.env},stdio:["pipe","pipe",this._serverParams.stderr??"inherit"],shell:!1,windowsHide:j9.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=q3($);if(this._process.stdin.write(Q))Z();else this._process.stdin.once("drain",Z)})}}var Aj=1e4,Nj=60000,M3=50000;function p1($){if($.length<=M3)return $;let Z=Math.floor(M3/2);return`${$.slice(0,Z)}
|
|
202
206
|
|
|
203
207
|
\u2026 [${$.length-Z*2} characters omitted] \u2026
|
|
204
208
|
|
|
205
|
-
${$.slice(-Z)}`}function
|
|
206
|
-
${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
|
|
207
|
-
${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
|
|
208
|
-
`),V=JSON.stringify({event:"PostToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_output:K,is_error:J.isError}),z=await Z(B.command,V,B.timeoutMs??
|
|
209
|
+
${$.slice(-Z)}`}function V6($){try{return JSON.stringify($,null,2)}catch{return String($)}}function O3($,Z){return $.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"_").replace(/^_+|_+$/g,"")||Z}function Mj($){if($.type==="text")return[{type:"text",text:p1($.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:p1(V6({type:$.type,uri:$.uri,name:$.name,...$.description?{description:$.description}:{},...$.mimeType?{mimeType:$.mimeType}:{}}))}];let Z=$.resource;if("text"in Z)return[{type:"text",text:p1(`[resource ${Z.uri}]
|
|
210
|
+
${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 Oj($){let Z=$.content.flatMap(Mj);if(Z.length===0&&$.structuredContent!==void 0)Z.push({type:"text",text:p1(V6($.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 jj($){return typeof $==="object"&&$!==null&&Array.isArray($.content)}function j3($){return typeof $==="number"&&Number.isFinite($)&&$>0}function Pj($,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((W)=>typeof W!=="string")))return;if(Q.env!==void 0&&(typeof Q.env!=="object"||Q.env===null||Array.isArray(Q.env)||Object.values(Q.env).some((W)=>typeof W!=="string")))return;if(Q.cwd!==void 0&&typeof Q.cwd!=="string")return;if(Q.startupTimeoutMs!==void 0&&!j3(Q.startupTimeoutMs))return;if(Q.toolTimeoutMs!==void 0&&!j3(Q.toolTimeoutMs))return;let Y=typeof Q.cwd==="string"?Uj(Q.cwd)?Q.cwd:qj(Z,Q.cwd):void 0;return{command:Q.command,...Q.args?{args:Q.args}:{},...Q.env?{env:Q.env}:{},...Y?{cwd:Y}:{},...Q.startupTimeoutMs?{startupTimeoutMs:Q.startupTimeoutMs}:{},...Q.toolTimeoutMs?{toolTimeoutMs:Q.toolTimeoutMs}:{}}}async function wj($){let Z;try{Z=await Fj($,"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 Y={},W=[];for(let[G,X]of Object.entries(Q.mcpServers)){let J=Pj(X,Dj($));if(J)Y[G]=J;else W.push(G)}return{servers:Y,...W.length>0?{error:`invalid MCP server config${W.length===1?"":"s"}: ${W.join(", ")}`}:{}}}catch(Q){return{servers:{},error:Q instanceof Error?Q.message:String(Q)}}}async function Tj($={}){let Z=[$.userFile??N3(Lj(),".mu","config.json"),...$.projectDir?[N3($.projectDir,".mu","config.json")]:[]],Q={},Y=[];for(let W of Z){let G=await wj(W);if(Object.assign(Q,G.servers),G.error)Y.push({file:W,message:G.error})}return{servers:Q,errors:Y}}async function Ij($,Z,Q){let Y=[],W;do{let G=await $.listResources(W?{cursor:W}:void 0,{signal:Z,timeout:Q});Y.push(...G.resources),W=G.nextCursor}while(W);return Y}function Rj($){let Z=[];return{name:"mcp",activate:async(Q)=>{let Y=new Set;for(let[W,G]of Object.entries($)){let X=O3(W,"server"),J=new V9({name:"mu",version:"0.0.1"}),B=new w9({command:G.command,...G.args?{args:G.args}:{},env:{...P9(),...G.env??{}},...G.cwd?{cwd:G.cwd}:{},stderr:"pipe"});B.stderr?.on("data",(L)=>{let U=String(L).trim();if(U)Q.log(`${W}: ${U}`)});try{await J.connect(B,{timeout:G.startupTimeoutMs??Aj})}catch(L){await B.close().catch(()=>{}),Q.log(`could not connect ${W}: ${L instanceof Error?L.message:String(L)}`);continue}Z.push(J);let K=G.toolTimeoutMs??Nj,V=[],z;try{do{let L=await J.listTools(z?{cursor:z}:void 0,{timeout:K});V.push(...L.tools),z=L.nextCursor}while(z)}catch(L){Z.pop(),await J.close().catch(()=>{}),Q.log(`could not discover tools from ${W}: ${L instanceof Error?L.message:String(L)}`);continue}for(let L of V){let U=`mcp_${X}_${O3(L.name,"tool")}`,q=2;while(Y.has(U))U=`${U}_${q++}`;Y.add(U),Q.registerTool({name:U,description:L.description??`Run the ${L.name} tool provided by the ${W} MCP server.`,inputSchema:L.inputSchema,...L.annotations?.readOnlyHint&&!L.annotations.destructiveHint?{isConcurrencySafe:()=>!0}:{},execute:async(A,N,j,P)=>{try{let M=await J.callTool({name:L.name,arguments:N},void 0,{signal:j,timeout:K,resetTimeoutOnProgress:!0,maxTotalTimeout:K,onprogress:({progress:S,total:g})=>{P?.([{type:"text",text:`mcp progress ${S}${g===void 0?"":`/${g}`}`}])}});if(!jj(M))return{content:[{type:"text",text:p1(V6(M.toolResult))}]};return Oj(M)}catch(M){return y(`MCP tool ${W}/${L.name} failed: ${M instanceof Error?M.message:String(M)}`)}}})}if(!J.getServerCapabilities()?.resources)continue;let F=`mcp_${X}_resources_list`;if(!Y.has(F))Y.add(F),Q.registerTool({name:F,description:`List resources exposed by the ${W} MCP server.`,inputSchema:{type:"object",properties:{},additionalProperties:!1},isConcurrencySafe:()=>!0,execute:async(L,U,q)=>{try{return{content:[{type:"text",text:p1(V6(await Ij(J,q,K)))}]}}catch(A){return y(`Could not list MCP resources from ${W}: ${A instanceof Error?A.message:String(A)}`)}}});let D=`mcp_${X}_resource_read`;if(!Y.has(D))Y.add(D),Q.registerTool({name:D,description:`Read a resource exposed by the ${W} 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:K}),N=[];for(let j of A.contents){if("text"in j){N.push({type:"text",text:p1(`[resource ${j.uri}]
|
|
211
|
+
${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 T9($,Z,Q={}){let Y=await $.contextMessages?.()??[],W=await $.environment?.()??{};return{...Q,sessionProfile:Q.sessionProfile??$.name,sessionEnvironment:Q.sessionEnvironment??W,model:Q.model??Z,systemPrompt:Q.systemPrompt??$.promptFor(Z),tools:[...$.toolset,...Q.tools??[]],permissions:[...$.permissionDefaults,...Q.permissions??[]],...Y.length>0?{initialMessages:Y}:{},...$.refreshContext?{refreshContext:$.refreshContext}:{},...$.carryoverExtractor?{carryoverExtractor:$.carryoverExtractor}:{},...Q.runtime??$.runtime?{runtime:Q.runtime??$.runtime}:{},...Q.checkpointProvider??$.checkpointProvider?{checkpointProvider:Q.checkpointProvider??$.checkpointProvider}:{}}}async function Ej($,Z={},Q=(Y)=>import(Y)){let Y=await Q($),W=Y.default??Y.profile??Y.codingProfile;if(typeof W==="function")return await W(Z);if(W&&typeof W==="object"&&"toolset"in W)return W;throw Error(`Module "${$}" does not export a profile`)}var z6=30000,Sj=1000;async function P3($){let Z=$.getReader(),Q=new TextDecoder,Y=new C1;for(;;){let{done:W,value:G}=await Z.read();if(W)break;Y.append(Q.decode(G,{stream:!0}))}return Y.append(Q.decode()),Y.read()}function w3($,Z){if(process.platform==="win32"){try{Bun.spawn(["taskkill.exe","/PID",String($.pid),"/T","/F"],{stdin:"ignore",stdout:"ignore",stderr:"ignore",windowsHide:!0})}catch{$.kill(Z)}return}try{process.kill(-$.pid,Z)}catch{$.kill(Z)}}async function Cj($,Z,Q){let Y=Bun.spawn(["sh","-c",$],{stdin:new TextEncoder().encode(Z),stdout:"pipe",stderr:"pipe",detached:process.platform!=="win32"}),W,G=setTimeout(()=>{w3(Y,"SIGTERM"),W=setTimeout(()=>w3(Y,"SIGKILL"),Sj)},Q);try{let[X,J,B]=await Promise.all([P3(Y.stdout),P3(Y.stderr),Y.exited]);return{exitCode:B,stdout:X,stderr:J}}finally{if(clearTimeout(G),W)clearTimeout(W)}}function T3($,Z){if(!$||$==="*")return!0;let Q=$.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${Q}$`).test(Z)}function I9($){let Z=$.trim();if(!Z.startsWith("{"))return;try{return JSON.parse(Z)}catch{return}}function yj($,Z=Cj){let Q=(Y)=>$.filter((W)=>W.event===Y);return{name:"shell-hooks",activate(Y){let W=Q("PreToolUse");if(W.length>0)Y.onToolCall(async(J)=>{for(let B of W){if(!T3(B.matcher,J.toolName))continue;let K=JSON.stringify({event:"PreToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_input:J.args}),V=await Z(B.command,K,B.timeoutMs??z6),z=I9(V.stdout);if(V.exitCode===2)return{block:!0,reason:(typeof z?.reason==="string"?z.reason:void 0)??V.stderr.trim()??`Blocked by ${B.command}`};if(V.exitCode===0&&z?.tool_input&&typeof z.tool_input==="object")return{args:z.tool_input}}return});let G=Q("PostToolUse");if(G.length>0)Y.onToolResult(async(J)=>{for(let B of G){if(!T3(B.matcher,J.toolName))continue;let K=J.result.content.filter((D)=>D.type==="text").map((D)=>D.text).join(`
|
|
212
|
+
`),V=JSON.stringify({event:"PostToolUse",tool_name:J.toolName,tool_call_id:J.toolCallId,tool_output:K,is_error:J.isError}),z=await Z(B.command,V,B.timeoutMs??z6),F=I9(z.stdout);if(typeof F?.tool_output==="string")return{content:[{type:"text",text:F.tool_output}]}}return});let X=Q("UserPromptSubmit");if(X.length>0)Y.onInput(async(J)=>{for(let B of X){let K=await Z(B.command,JSON.stringify({event:"UserPromptSubmit",prompt:J}),B.timeoutMs??z6);if(K.exitCode===2)return{consume:!0};let V=I9(K.stdout);if(typeof V?.prompt==="string")return{text:V.prompt}}return});for(let J of["SessionStart","Stop"]){let B=Q(J);if(B.length===0)continue;let K=J==="SessionStart"?"session_start":"agent_end";Y.on(K,()=>{for(let V of B)Z(V.command,JSON.stringify({event:J}),V.timeoutMs??z6).catch((z)=>Y.log(`${J} hook failed: ${z instanceof Error?z.message:String(z)}`))})}}}}import{readdir as bj,readFile as _j,stat as xj}from"fs/promises";import{homedir as kj}from"os";import{basename as fj,join as F6}from"path";async function R9($){try{let Z=await _j(F6($,"SKILL.md"),"utf8"),{meta:Q,body:Y}=z5(Z),W=typeof Q.name==="string"&&Q.name?Q.name:fj($),G=typeof Q.description==="string"&&Q.description?Q.description:`The ${W} skill`;return{name:W,description:G,body:Y,directory:$}}catch{return}}async function vj($){let Z=[];for(let Q of $){let Y;try{Y=await bj(Q)}catch{continue}for(let W of Y.sort()){let G=F6(Q,W);try{if(!(await xj(G)).isDirectory())continue}catch{continue}let X=await R9(G);if(X)Z.push(X)}}return Z}function gj($){let Z=[F6(kj(),".mu","skills")];if($)Z.push(F6($,".mu","skills"));return Z}function I3($){if($.length===0)return"";return`Available skills (load one with the skill tool when it is relevant):
|
|
209
213
|
${$.map((Q)=>`- ${Q.name}: ${Q.description}`).join(`
|
|
210
|
-
`)}`}function
|
|
214
|
+
`)}`}function hj($){return{name:"skills",activate(Z){if($.length===0)return;let Q=new Map($.map((Y)=>[Y.name,Y]));Z.registerTool({name:"skill",description:`Load the full instructions for a skill. ${I3($)}`,inputSchema:{type:"object",properties:{name:{type:"string",description:"The skill to load"}},required:["name"]},isConcurrencySafe:()=>!0,execute:async(Y,W)=>{let G=W.name??"",X=Q.get(G),J=X?await R9(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}):
|
|
211
215
|
|
|
212
|
-
${J.body}`}],details:{skill:J.name}}}}),Z.onContext((Y)=>Y),Z.log(`loaded ${$.length} skill(s)`)}}}import{z as
|
|
216
|
+
${J.body}`}],details:{skill:J.name}}}}),Z.onContext((Y)=>Y),Z.log(`loaded ${$.length} skill(s)`)}}}import{z as uj}from"zod";function mj($){return typeof $==="string"?{content:[{type:"text",text:$}]}:$}function W0($){let Z=uj.toJSONSchema($.inputSchema,{io:"input"}),Q=(G)=>{let X=G;if($.coerceInput)try{X=$.coerceInput(G)}catch{X=G}return $.inputSchema.safeParse(X)},Y=$.isConcurrencySafe,W=$.changesState;return{name:$.name,description:$.description,inputSchema:Z,...Y?{isConcurrencySafe:(G)=>{let X=Q(G);if(!X.success)return!1;try{return Y(X.data)===!0}catch{return!1}}}:{},...$.executionMode?{executionMode:$.executionMode}:{},...W!==void 0?{changesState:typeof W==="function"?(G)=>{let X=Q(G);if(!X.success)return!0;try{return W(X.data)===!0}catch{return!0}}:W}:{},...$.permissionScope?{permissionScope:(G)=>{let X=Q(G);return X.success?$.permissionScope?.(X.data)??$.name:$.name}}:{},...$.permissionPattern?{permissionPattern:(G)=>{let X=Q(G);return X.success?$.permissionPattern?.(X.data)??JSON.stringify(G):JSON.stringify(G)}}:{},...$.permissionDetails?{permissionDetails:async(G)=>{let X=Q(G);return X.success?$.permissionDetails?.(X.data):void 0}}:{},execute:async(G,X,J,B)=>{let K=Q(X);if(!K.success){let z=K.error.issues.map((F)=>`${F.path.join(".")||"(root)"}: ${F.message}`).join("; ");return y(`Invalid arguments for ${$.name}: ${z}`)}let V=(z)=>B?.([{type:"text",text:z}]);return mj(await $.execute(K.data,{toolCallId:G,signal:J,update:V}))}}}function L6($,Z="text"){let Q=Math.max(0,...[...$.matchAll(/`+/g)].map((W)=>W[0].length)),Y="`".repeat(Math.max(3,Q+1));return`${Y}${Z}
|
|
213
217
|
${$}
|
|
214
|
-
${Y}`}function
|
|
215
|
-
`}function
|
|
216
|
-
`)}function
|
|
217
|
-
`);return["<details>",`<summary>Tool call: <code>${
|
|
218
|
-
`)});if($.errorMessage)Z.push(`> Error: ${$.errorMessage}`);return["## Mu",
|
|
219
|
-
`)}function
|
|
220
|
-
`),Q=$.details===void 0?[]:["","**Details**","",
|
|
221
|
-
`)}function
|
|
222
|
-
`)}function
|
|
218
|
+
${Y}`}function R3($){return $.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""")}function D6($){let Z=new Date($);return Number.isNaN(Z.getTime())?"":`_${Z.toISOString()}_
|
|
219
|
+
`}function E3($){return`> [Image omitted from text export: ${$}]`}function S3($){return $.content.map((Z)=>Z.type==="text"?Z.text:E3(Z.mimeType))}function lj($){return["## User",D6($.timestamp),...S3($)].filter(Boolean).join(`
|
|
220
|
+
`)}function pj($){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(`
|
|
221
|
+
`);return["<details>",`<summary>Tool call: <code>${R3(Q.name)}</code></summary>`,"",L6(JSON.stringify(Q.arguments,null,2)??"null","json"),"","</details>"].join(`
|
|
222
|
+
`)});if($.errorMessage)Z.push(`> Error: ${$.errorMessage}`);return["## Mu",D6($.timestamp),...Z].filter(Boolean).join(`
|
|
223
|
+
`)}function cj($){let Z=$.content.map((Y)=>Y.type==="text"?Y.text:E3(Y.mimeType)).join(`
|
|
224
|
+
`),Q=$.details===void 0?[]:["","**Details**","",L6(JSON.stringify($.details,null,2)??"null","json")];return["<details>",`<summary>Tool result: <code>${R3($.toolName)}</code>${$.isError?" (error)":""}</summary>`,"",D6($.timestamp),L6(Z||"(no output)"),...Q,"","</details>"].filter(Boolean).join(`
|
|
225
|
+
`)}function dj($){let Z=$.customType.replaceAll(/[^\p{L}\p{N} _-]/gu,"").trim();return[`## ${$.customType==="user_shell_command"?"User shell":Z||"Context"}`,D6($.timestamp),...S3($).map((Y)=>L6(Y))].filter(Boolean).join(`
|
|
226
|
+
`)}function ij($){return $.role!=="custom"||$.display===!0||$.customType==="user_shell_command"}function nj($){if($.role==="user")return lj($);if($.role==="assistant")return pj($);if($.role==="toolResult")return cj($);return dj($)}function aj($,Z={}){let Q=$.activePath().filter((X)=>X.type==="message").map((X)=>X.message).filter(ij),Y=Z.exportedAt??new Date,W=[Z.sessionId?`- Session: \`${Z.sessionId}\``:void 0,Z.model?`- Model: \`${Z.model}\``:void 0,`- Exported: ${Y.toISOString()}`].filter((X)=>X!==void 0),G=Q.map(nj);return{markdown:["# Mu chat transcript","",...W,...G.length>0?["",G.join(`
|
|
223
227
|
|
|
224
228
|
`)]:[],""].join(`
|
|
225
|
-
`),messageCount:Q.length}}import{z as
|
|
229
|
+
`),messageCount:Q.length}}import{z as CZ}from"zod";import{delimiter as sj,dirname as ej}from"path";import{accessSync as C3,constants as y3,statSync as b3}from"fs";import{dirname as E9,resolve as S9}from"path";function rj($,Z){let Q=Z==="win32"?"rg.exe":"rg",Y=S9(E9($),"..","mu-path",Q);try{if(!b3(Y).isFile())return;if(Z!=="win32")C3(Y,y3.X_OK);return Y}catch{return}}var tj={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,Q=process.argv[1]?E9(S9(process.argv[1])):process.cwd(),Y=(W,G)=>Bun.resolveSync(W,G)){let W=tj[$]?.[Z];if(!W)return;try{let G=Y(`${W}/package.json`,Q),X=$==="win32"?"rg.exe":"rg",J=S9(E9(G),"vendor",X);if(!b3(J).isFile())return;if($!=="win32")C3(J,y3.X_OK);return J}catch{return}}function _3($=process.execPath,Z=process.platform,Q=(W)=>Bun.which(W),Y=()=>oj(Z,process.arch)){return rj($,Z)??Y()??Q("rg")??void 0}var $P=2000;function P$($,Z={}){if((Z.platform??process.platform)==="win32")return["powershell.exe","-NoLogo","-NoProfile",...Z.interactive?[]:["-NonInteractive"],"-Command",$];return["bash","-c",$]}function x3($){return["taskkill.exe","/PID",String($),"/T","/F"]}var C9;function ZP(){if(C9===void 0){let $=_3(void 0,void 0,()=>null);C9=$?ej($):null}return C9??void 0}function EZ($={},Z=ZP){let Q={...process.env,...$},Y=Z();if(!Y)return Q;let W=Object.keys(Q).find((X)=>X.toUpperCase()==="PATH")??"PATH",G=Q[W];return Q[W]=G?`${Y}${sj}${G}`:Y,Q}function U6($,Z){try{$.kill(Z)}catch{}}async function Z1($,Z,Q=globalThis.process.platform){if(Q!=="win32"){try{globalThis.process.kill(-$.pid,Z)}catch{U6($,Z)}return}try{let Y=Bun.spawn(x3($.pid),{stdin:"ignore",stdout:"ignore",stderr:"ignore",windowsHide:!0}),W,G=await Promise.race([Y.exited,new Promise((X)=>{W=setTimeout(()=>X(void 0),$P)})]).finally(()=>{if(W)clearTimeout(W)});if(G===void 0){try{Y.kill("SIGKILL")}catch{}U6($,Z)}else if(G!==0&&$.exitCode===null)U6($,Z)}catch{U6($,Z)}}var QP=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"]),YP=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),WP=["--hostname-bin","--pre"],GP=["-C","-c","-p","--config-env","--exec-path","--git-dir","--namespace","--paginate","--super-prefix","--work-tree"],XP=["--exec","--ext-diff","--output","--textconv"];function k3($){return($.split(/[\\/]/).at(-1)?.toLowerCase()??$.toLowerCase()).replace(/\.(?:exe|cmd|bat|com)$/i,"")}function JP($,Z){if($===Z||$.startsWith(`${Z}=`))return!0;return Z.length===2&&$.startsWith(Z)&&$.length>Z.length}function q6($,Z){return $.some((Q)=>Z.some((Y)=>JP(Q,Y)))}function KP($){let Z=[],Q=-1,Y=!1;for(let X=1;X<$.length;X++){let J=$[X]??"";if(Y){Z.push(J),Y=!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))Y=!0;continue}Q=X;break}if(Q===-1||q6(Z,GP))return!1;let W=$[Q]?.toLowerCase(),G=$.slice(Q+1);if(!W||!["branch","diff","log","show","status"].includes(W))return!1;if(q6(G,XP))return!1;if(W!=="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 f3($){let Z=$[0]??"";if(Z.includes("/")||Z.includes("\\"))return!1;let Q=k3(Z);if(QP.has(Q)){if(Q!=="base64")return!0;return!q6($.slice(1),["-o","--output"])}if(Q==="find")return!$.slice(1).some((Y)=>YP.has(Y));if(Q==="rg")return!$.slice(1).some((Y)=>Y==="-z"||Y==="--search-zip")&&!q6($.slice(1),WP);if(Q==="git")return KP($);if(Q==="sed")return $.length>=3&&$.length<=4&&$[1]==="-n"&&/^(?:\d+,)?\d+p$/.test($[2]??"");return process.platform==="linux"&&(Q==="numfmt"||Q==="tac")}function y9($){let Z=[],Q=[],Y="",W=!1,G,X=!1,J=()=>{if(!W)return;Q.push(Y),Y="",W=!1},B=()=>{if(J(),Q.length===0)return!1;return Z.push(Q),Q=[],!0};for(let K=0;K<$.length;K++){let V=$[K]??"";if(G==="single"){if(V==="'")G=void 0;else Y+=V;continue}if(G==="double"){if(V==='"')G=void 0;else if(V==="$"||V==="`")return;else if(V==="\\"&&process.platform!=="win32"){let z=$[++K];if(z===void 0)return;if(z!==`
|
|
230
|
+
`)Y+=z}else Y+=V;continue}if(V==="'"||V==='"'){G=V==="'"?"single":"double",W=!0,X=!1;continue}if(V==="\\"&&process.platform!=="win32"){let z=$[++K];if(z===void 0)return;if(z!==`
|
|
231
|
+
`)W=!0,Y+=z,X=!1;continue}if(V==="$"||V==="`"||"<>(){}".includes(V))return;if(V==="#"&&!W)return;if(V===`
|
|
232
|
+
`||V==="\r"){if(V==="\r"&&$[K+1]===`
|
|
233
|
+
`)K++;if(!B())return;X=!0;continue}if(/\s/.test(V)){J();continue}if(V===";"){if(!B())return;X=!0;continue}if(V==="&"){if($[K+1]!=="&"||!B())return;K++,X=!1;continue}if(V==="|"){let z=$[K+1]==="|";if(!B())return;if(z)K++;X=!1;continue}W=!0,Y+=V,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=y9($);return Z?.length&&Z.every(f3)?"inspect":"other"}function SZ($){return v3($)==="inspect"}function g3($){let Z=y9($);if(Z?.length!==1)return!1;let Q=Z[0];return Q!==void 0&&f3(Q)&&k3(Q[0]??"")==="rg"}function P1($,Z=30000,Q=1000){let Y=$.split(`
|
|
226
234
|
`);if($.length<=Z&&Y.length<=Q)return{text:$,truncated:!1};if(Y.length>Q){let W=Y.slice(0,Math.floor(Q/2)),G=Y.slice(-Math.floor(Q/2)),X=Y.length-W.length-G.length,J=`${W.join(`
|
|
227
235
|
`)}
|
|
228
236
|
|
|
229
237
|
\u2026 [${X} lines omitted] \u2026
|
|
230
238
|
|
|
231
239
|
${G.join(`
|
|
232
|
-
`)}`;return{text:J.length>Z?
|
|
240
|
+
`)}`;return{text:J.length>Z?h3(J,Z):J,truncated:!0}}return{text:h3($,Z),truncated:!0}}function h3($,Z){let Q=Math.floor(Z/2),Y=$.length-Q*2;return`${$.slice(0,Q)}
|
|
233
241
|
|
|
234
242
|
\u2026 [${Y} characters omitted] \u2026
|
|
235
243
|
|
|
236
|
-
${$.slice(-Q)}`}function
|
|
244
|
+
${$.slice(-Q)}`}function w1($,Z){return $.truncated?`${$.text}
|
|
237
245
|
|
|
238
|
-
[output truncated \u2014 ${Z}. Narrow the request to see more.]`:$.text}
|
|
239
|
-
`);if(Z.at(-1)==="")Z.pop();return Z}function t3($,Z,Q){let Y=Z===void 0?[]:m3(Z),W=m3(Q),G=0;while(G<Y.length&&G<W.length&&Y[G]===W[G])G++;let X=0;while(X<Y.length-G&&X<W.length-G&&Y[Y.length-1-X]===W[W.length-1-X])X++;let J=Y.length-G-X,B=W.length-G-X;if(B===0&&J===0)return{path:$,added:B,removed:J,hunks:[]};let K=Math.min(3,G),V=Math.min(3,X),z=G-K,F=G-K,L=K+J+V,D=K+B+V,U=[`@@ -${Y.length===0?0:z+1},${L} +${W.length===0?0:F+1},${D} @@`,...Y.slice(z,G).map((q)=>` ${q}`),...Y.slice(G,Y.length-X).map((q)=>`-${q}`),...W.slice(G,W.length-X).map((q)=>`+${q}`),...W.slice(W.length-X,W.length-X+V).map((q)=>` ${q}`)];return{path:$,added:B,removed:J,hunks:U}}function f9($){return r({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:G0.object({path:G0.string().describe("Path to the file, absolute or relative to the session root"),offset:G0.number().int().min(1).optional().describe("First line to read (1-based)"),limit:G0.number().int().min(1).optional().describe("Maximum number of lines to read")}),isConcurrencySafe:()=>!0,execute:async({path:Z,offset:Q,limit:Y})=>{let W=R$($.root,Z),G;try{W=await i1($.root,Z);let L=await i3(W);if(L.size>h3)return S(`${B0($.root,W)} is ${L.size.toLocaleString()} bytes; read refuses files larger than ${h3.toLocaleString()} bytes. Use grep or a bounded shell command to inspect it.`);G=await _Z(W,"utf8")}catch(L){let D=L.code;if(D==="ENOENT")return S(`File not found: ${B0($.root,W)}`);if(D==="EISDIR")return S(`${B0($.root,W)} is a directory \u2014 use ls instead.`);throw L}$.state.markRead(W,G);let X=G.split(`
|
|
240
|
-
`),J=(Q??1)-1,K=X.slice(J,Y?J+Y:void 0).map((L,D)=>`${String(J+D+1).padStart(5)} ${L}`),V=k0(x0(K.join(`
|
|
241
|
-
`)),"file is large"),z=await $.instructions?.instructionsForPath(W);return{content:[{type:"text",text:[V||"(empty file)",z?.text].filter(Boolean).join(`
|
|
242
|
-
|
|
243
|
-
`)}],details:{path:W,lines:X.length,...z&&z.sources.length>0?{loadedInstructions:z.sources}:{}}}}})}function v9($){return r({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:G0.object({path:G0.string().describe("Path to the file"),content:G0.string().describe("The complete file contents")}),permissionDetails:async({path:Z,content:Q})=>{let Y=await u3($.root,Z),W;try{W=await _Z(Y,"utf8")}catch{W=void 0}let G=B0($.root,Y);return{description:`${W===void 0?"Create":"Overwrite"} ${G}`,preview:{kind:"diff",file:t3(G,W,Q)}}},execute:async({path:Z,content:Q})=>{let Y=await u3($.root,Z),W=!0,G;try{G=await _Z(Y,"utf8")}catch(J){if(J.code==="ENOENT")W=!1;else throw J}if(W&&!$.state.hasRead(Y))return S(`Refusing to overwrite ${B0($.root,Y)} because it has not been read in this session. Read it first, then write.`);if($.state.hasRead(Y)&&$.state.isStale(Y,G))return S(`${B0($.root,Y)} changed on disk since you read it. Read it again before writing.`);await KP(a3(Y),{recursive:!0}),await n3(Y,Q,"utf8"),$.state.markWritten(Y);let X=Q.split(`
|
|
244
|
-
`).length;return{content:[{type:"text",text:`${W?"Updated":"Created"} ${B0($.root,Y)} (${X} lines)`}],details:{path:Y,created:!W}}}})}var HP=G0.object({oldString:G0.string().describe("Exact text to replace, including indentation"),newString:G0.string().describe("Replacement text"),replaceAll:G0.boolean().optional().describe("Replace every occurrence of this oldString")}),_9=($)=>$.split(`
|
|
245
|
-
`).length-1,l3="\uFEFF";function p3($){return $.startsWith(l3)?{bom:l3,text:$.slice(1)}:{bom:"",text:$}}var c3=($)=>$.replace(/\r?\n/g,`\r
|
|
246
|
-
`),VP=($)=>$.replace(/\r\n/g,`
|
|
247
|
-
`);function zP($,Z,Q){if(Z.includes(`
|
|
248
|
-
`)&&!$.includes(Z)){for(let Y of[c3,VP]){let W=Y(Z);if(W!==Z&&$.includes(W))return{oldString:W,newString:Y(Q)}}return{oldString:Z,newString:Q}}return{oldString:Z,newString:$.includes(`\r
|
|
249
|
-
`)?c3(Q):Q}}function d3($,Z,Q){let Y=(z)=>Z.length>1?`edits[${z}]: `:"",W=[];for(let[z,F]of Z.entries()){let{replaceAll:L}=F,{oldString:D,newString:U}=zP($,F.oldString,F.newString);if(D==="")return{ok:!1,message:`${Y(z)}oldString is empty \u2014 nothing to match.`};if(D===U)return{ok:!1,message:`${Y(z)}oldString and newString are identical \u2014 nothing to do.`};let q=$.split(D).length-1;if(q===0)return{ok:!1,message:`${Y(z)}oldString was not found in ${Q}. The text must match exactly, including whitespace and indentation.`};if(q>1&&!L)return{ok:!1,message:`${Y(z)}oldString appears ${q} times in ${Q}. Include more surrounding context to make it unique, or set replaceAll.`};let A=0;for(;;){let N=$.indexOf(D,A);if(N===-1)break;if(W.push({start:N,end:N+D.length,newString:U,index:z}),!L)break;A=N+D.length}}W.sort((z,F)=>z.start-F.start);let G;for(let z of W){if(G&&G.end>z.start)return{ok:!1,message:G.start===z.start&&G.end===z.end?`edits[${G.index}] and edits[${z.index}] match the same text in ${Q}. Drop the duplicate, or give each edit different text to match.`:`edits[${G.index}] and edits[${z.index}] overlap in ${Q}. Merge them into one edit, or target text that does not overlap.`};G=z}let X="",J=0,B=1,K=1,V=[];for(let z of W){let F=$.slice(J,z.start),L=_9(F);B+=L,K+=L,V.push({edit:z.index,oldLine:B,newLine:K}),X+=F+z.newString,B+=_9($.slice(z.start,z.end)),K+=_9(z.newString),J=z.end}return X+=$.slice(J),{ok:!0,updated:X,replacements:W.length,hunks:V}}function FP($){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:Y,replaceAll:W,...G}=Z,X=Array.isArray(Z.edits)?Z.edits:[];return{...G,edits:[...X,{oldString:Q,newString:Y,...W===void 0?{}:{replaceAll:W}}]}}return Z}function g9($){return r({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:G0.object({path:G0.string().describe("Path to the file"),edits:G0.array(HP).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:FP,permissionDetails:async({path:Z,edits:Q})=>{let Y=await i1($.root,Z),W=B0($.root,Y),G;try{G=await _Z(Y,"utf8")}catch{return{description:`Edit ${W}`}}let{text:X}=p3(G),J=d3(X,Q,W);if(!J.ok)return{description:`Edit ${W}`};return{description:`Edit ${W}`,preview:{kind:"diff",file:t3(W,X,J.updated)}}},execute:async({path:Z,edits:Q})=>{let Y=R$($.root,Z);try{Y=await i1($.root,Z)}catch(z){if(z.code==="ENOENT")return S(`File not found: ${B0($.root,Y)}`);throw z}if(!$.state.hasRead(Y))return S(`Read ${B0($.root,Y)} before editing it, so you can see what you are changing.`);let W;try{W=await _Z(Y,"utf8")}catch(z){if(z.code==="ENOENT")return S(`File not found: ${B0($.root,Y)}`);throw z}if($.state.isStale(Y,W))return S(`${B0($.root,Y)} changed on disk since you read it. Read it again before editing.`);let{bom:G,text:X}=p3(W),J=d3(X,Q,B0($.root,Y));if(!J.ok)return S(J.message);let{updated:B,replacements:K,hunks:V}=J;return await n3(Y,G+B,"utf8"),$.state.markWritten(Y),{content:[{type:"text",text:`Edited ${B0($.root,Y)} (${K} replacement${K===1?"":"s"})`}],details:{path:Y,occurrences:K,edits:Q.length,hunks:V}}}})}function h9($){return r({name:"ls",description:"List the entries of a directory.",inputSchema:G0.object({path:G0.string().optional().describe("Directory to list; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({path:Z})=>{let Q=Z??".",Y=R$($.root,Q),W;try{Y=await i1($.root,Q),W=await BP(Y)}catch(X){if(X.code==="ENOENT")return S(`Directory not found: ${B0($.root,Y)}`);throw X}let G=await Promise.all(W.sort().map(async(X)=>{try{return(await i3(T$(Y,X))).isDirectory()?`${X}/`:X}catch{return X}}));return k0(x0(G.join(`
|
|
250
|
-
`)||"(empty directory)"),"directory has many entries")}})}var m9=new Set(["node_modules",".git","dist","build",".next","coverage",".venv"]),E$=200,o3=2000000;async function qP($,Z){let Q=await LP($,"r");try{let Y=await Q.stat(),W=Math.min(Y.size,Z),G=Buffer.alloc(W),{bytesRead:X}=await Q.read(G,0,W,0);return{content:new TextDecoder().decode(G.subarray(0,X)),truncated:Y.size>X}}finally{await Q.close()}}function AP($,Z){let Q=Z==="win32"?"rg.exe":"rg",Y=T1(u9($),"..","mu-path",Q);try{if(!ZK(Y).isFile())return;if(Z!=="win32")e3(Y,$K.X_OK);return Y}catch{return}}var NP={darwin:{arm64:"@mu-agent/ripgrep-darwin-arm64"},linux:{x64:"@mu-agent/ripgrep-linux-x64"},win32:{x64:"@mu-agent/ripgrep-windows-x64"}};function QK($=process.platform,Z=process.arch,Q=process.argv[1]?u9(T1(process.argv[1])):process.cwd(),Y=(W,G)=>Bun.resolveSync(W,G)){let W=NP[$]?.[Z];if(!W)return;try{let G=Y(`${W}/package.json`,Q),X=$==="win32"?"rg.exe":"rg",J=T1(u9(G),"vendor",X);if(!ZK(J).isFile())return;if($!=="win32")e3(J,$K.X_OK);return J}catch{return}}function j6($=process.execPath,Z=process.platform,Q=(W)=>Bun.which(W),Y=()=>QK(Z,process.arch)){return AP($,Z)??Y()??Q("rg")??void 0}async function OP($,Z,Q){let Y=$.getReader(),W=new TextDecoder,G="";while(!0){let{done:J,value:B}=await Y.read();if(J)break;G+=W.decode(B,{stream:!0});let K=G.indexOf(`
|
|
251
|
-
`);while(K!==-1){let V=G.slice(0,K).replace(/\r$/,"");if(G=G.slice(K+1),!Z(V))return Q(),await Y.cancel(),!1;K=G.indexOf(`
|
|
252
|
-
`)}}G+=W.decode();let X=G.length===0||Z(G.replace(/\r$/,""));if(!X)Q();return X}var MP=async($,Z,Q,Y)=>{Q.throwIfAborted();let W=j6();if(!W)return;let G;try{G=Bun.spawn([W,...$],{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,B,K]=await Promise.all([OP(G.stdout,Y,X),new Response(G.stderr).text(),G.exited]);return Q.throwIfAborted(),{exitCode:K,stderr:B,stopped:!J}}finally{Q.removeEventListener("abort",X)}};function YK($){return $.ripgrep===!1?void 0:$.ripgrep??MP}function WK(){let $=["--hidden","--no-ignore","--no-config","--no-messages","--sort","path"];for(let Z of m9)$.push("--glob",`!${Z}`,"--glob",`!${Z}/**`,"--glob",`!**/${Z}`,"--glob",`!**/${Z}/**`);return $}function GK($){return $.split(/[\\/]/).some((Z)=>m9.has(Z))}function XK($,Z,Q){return xZ(T1($),T1(Z,Q.replace(/^\.[\\/]/,"")))}function JK($){return $!==void 0&&($.stopped||$.exitCode===0||$.exitCode===1)}function l9($){let Z="";for(let Q=0;Q<$.length;Q++){let Y=$[Q];if(Y==="*")if($[Q+1]==="*")if($[Q+2]==="/")Z+="(?:.*/)?",Q+=2;else Z+=".*",Q+=1;else Z+="[^/]*";else if(Y==="?")Z+="[^/]";else if(".+^${}()|[]\\".includes(Y))Z+=`\\${Y}`;else Z+=Y}return new RegExp(`^${Z}$`)}async function*p9($,Z){Z.throwIfAborted();let Q;try{Q=await UP($)}catch{return}for(let Y of Q.sort()){if(Z.throwIfAborted(),m9.has(Y))continue;let W=T1($,Y),G;try{G=await DP(W)}catch{continue}if(G.isSymbolicLink())continue;if(G.isDirectory())yield*p9(W,Z);else yield W}}async function jP($,Z,Q,Y,W){if(!W)return;let G=[],X=await W(["--files",...WK()],Z,Y,(J)=>{if(!J||GK(J))return!0;let B=J.replaceAll("\\","/");if(Q.test(B))G.push(XK($,Z,J));return G.length<E$});return JK(X)?G:void 0}async function PP($,Z,Q,Y,W,G,X){if(!X)return;let J=[],B=["--json","--engine","auto",...WK(),...W?["--ignore-case"]:[],"--",Q,"."],K=await X(B,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,L=z.data?.lines?.text,D=z.data?.line_number;if(typeof F!=="string"||typeof L!=="string"||typeof D!=="number")return!0;let U=F.replace(/^\.[\\/]/,"");if(GK(U))return!0;let q=U.replaceAll("\\","/");if(Y&&!Y.test(q))return!0;return J.push(`${XK($,Z,U)}:${D}: ${L.trim()}`),J.length<E$});if(!JK(K))return;return{results:J,hitLimit:K?.stopped===!0||J.length>=E$}}function c9($,Z={}){return r({name:"glob",description:"Find files by glob pattern (e.g. 'src/**/*.ts'). Returns paths relative to the session root.",inputSchema:I1.object({pattern:I1.string().describe("Glob pattern, e.g. **/*.test.ts"),path:I1.string().optional().describe("Directory to search; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({pattern:Q,path:Y},{signal:W})=>{let G=await i1($.root,Y??"."),X=l9(Q),J=await jP($.root,G,X,W,YK(Z)),B=J??[];if(!J)for await(let K of p9(G,W)){let V=xZ(G,K).replaceAll("\\","/");if(X.test(V))B.push(xZ(T1($.root),K));if(B.length>=E$)break}if(B.length===0)return`No files matched ${Q}`;return k0(x0(B.join(`
|
|
253
|
-
`)),`showing the first ${E$} matches`)}})}function d9($,Z={}){return r({name:"grep",description:"Search file contents with a regular expression. Returns matching lines with file and line numbers for grounded path:line citations.",inputSchema:I1.object({pattern:I1.string().describe("Regular expression to search for"),path:I1.string().optional().describe("Directory to search; defaults to the session root"),include:I1.string().optional().describe("Only search files matching this glob"),ignoreCase:I1.boolean().optional()}),isConcurrencySafe:()=>!0,execute:async({pattern:Q,path:Y,include:W,ignoreCase:G},{signal:X})=>{let J=await i1($.root,Y??"."),B;try{B=new RegExp(Q,G?"i":"")}catch(D){return S(`Invalid regular expression: ${D instanceof Error?D.message:String(D)}`)}let K=W?l9(W):void 0,V=await PP($.root,J,Q,K,G,X,YK(Z));if(V)return s3(Q,V.results,V.hitLimit);let z=[],F=0,L=!1;for await(let D of p9(J,X)){let U=xZ(J,D).replaceAll("\\","/");if(K&&!K.test(U))continue;let q;try{let N=o3-F;if(N<=0){L=!0;break}let j=await qP(D,N);if(q=j.content,j.truncated)L=!0}catch{continue}if(F+=Buffer.byteLength(q),q.includes("\x00"))continue;let A=q.split(`
|
|
254
|
-
`);for(let N=0;N<A.length;N++){X.throwIfAborted();let j=A[N];if(!B.test(j))continue;if(z.push(`${xZ(T1($.root),D)}:${N+1}: ${j.trim()}`),z.length>=E$){L=!0;break}}if(L||F>=o3){L=!0;break}}return s3(Q,z,L)}})}function s3($,Z,Q){if(Z.length===0)return`No matches for ${$}`;let Y=Z.join(`
|
|
255
|
-
`);return Q?`${Y}
|
|
256
|
-
|
|
257
|
-
[search stopped early \u2014 narrow the pattern or scope to see the rest]`:k0(x0(Y),"many matches")}var TP=2000;function C$($,Z={}){if((Z.platform??process.platform)==="win32")return["powershell.exe","-NoLogo","-NoProfile",...Z.interactive?[]:["-NonInteractive"],"-Command",$];return["bash","-c",$]}function KK($){return["taskkill.exe","/PID",String($),"/T","/F"]}var i9;function RP(){if(i9===void 0){let $=j6(void 0,void 0,()=>null);i9=$?IP($):null}return i9??void 0}function kZ($={},Z=RP){let Q={...process.env,...$},Y=Z();if(!Y)return Q;let W=Object.keys(Q).find((X)=>X.toUpperCase()==="PATH")??"PATH",G=Q[W];return Q[W]=G?`${Y}${wP}${G}`:Y,Q}function P6($,Z){try{$.kill(Z)}catch{}}async function Y1($,Z,Q=globalThis.process.platform){if(Q!=="win32"){try{globalThis.process.kill(-$.pid,Z)}catch{P6($,Z)}return}try{let Y=Bun.spawn(KK($.pid),{stdin:"ignore",stdout:"ignore",stderr:"ignore",windowsHide:!0}),W,G=await Promise.race([Y.exited,new Promise((X)=>{W=setTimeout(()=>X(void 0),TP)})]).finally(()=>{if(W)clearTimeout(W)});if(G===void 0){try{Y.kill("SIGKILL")}catch{}P6($,Z)}else if(G!==0&&$.exitCode===null)P6($,Z)}catch{P6($,Z)}}var EP=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"]),CP=new Set(["-delete","-exec","-execdir","-fls","-fprint","-fprint0","-fprintf","-ok","-okdir"]),SP=["--hostname-bin","--pre"],yP=["-C","-c","-p","--config-env","--exec-path","--git-dir","--namespace","--paginate","--super-prefix","--work-tree"],bP=["--exec","--ext-diff","--output","--textconv"];function _P($){return($.split(/[\\/]/).at(-1)?.toLowerCase()??$.toLowerCase()).replace(/\.(?:exe|cmd|bat|com)$/i,"")}function xP($,Z){if($===Z||$.startsWith(`${Z}=`))return!0;return Z.length===2&&$.startsWith(Z)&&$.length>Z.length}function w6($,Z){return $.some((Q)=>Z.some((Y)=>xP(Q,Y)))}function kP($){let Z=[],Q=-1,Y=!1;for(let X=1;X<$.length;X++){let J=$[X]??"";if(Y){Z.push(J),Y=!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))Y=!0;continue}Q=X;break}if(Q===-1||w6(Z,yP))return!1;let W=$[Q]?.toLowerCase(),G=$.slice(Q+1);if(!W||!["branch","diff","log","show","status"].includes(W))return!1;if(w6(G,bP))return!1;if(W!=="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 fP($){let Z=$[0]??"";if(Z.includes("/")||Z.includes("\\"))return!1;let Q=_P(Z);if(EP.has(Q)){if(Q!=="base64")return!0;return!w6($.slice(1),["-o","--output"])}if(Q==="find")return!$.slice(1).some((Y)=>CP.has(Y));if(Q==="rg")return!$.slice(1).some((Y)=>Y==="-z"||Y==="--search-zip")&&!w6($.slice(1),SP);if(Q==="git")return kP($);if(Q==="sed")return $.length>=3&&$.length<=4&&$[1]==="-n"&&/^(?:\d+,)?\d+p$/.test($[2]??"");return process.platform==="linux"&&(Q==="numfmt"||Q==="tac")}function BK($){let Z=[],Q=[],Y="",W=!1,G,X=!1,J=()=>{if(!W)return;Q.push(Y),Y="",W=!1},B=()=>{if(J(),Q.length===0)return!1;return Z.push(Q),Q=[],!0};for(let K=0;K<$.length;K++){let V=$[K]??"";if(G==="single"){if(V==="'")G=void 0;else Y+=V;continue}if(G==="double"){if(V==='"')G=void 0;else if(V==="$"||V==="`")return;else if(V==="\\"&&process.platform!=="win32"){let z=$[++K];if(z===void 0)return;if(z!==`
|
|
258
|
-
`)Y+=z}else Y+=V;continue}if(V==="'"||V==='"'){G=V==="'"?"single":"double",W=!0,X=!1;continue}if(V==="\\"&&process.platform!=="win32"){let z=$[++K];if(z===void 0)return;if(z!==`
|
|
259
|
-
`)W=!0,Y+=z,X=!1;continue}if(V==="$"||V==="`"||"<>(){}".includes(V))return;if(V==="#"&&!W)return;if(V===`
|
|
260
|
-
`||V==="\r"){if(V==="\r"&&$[K+1]===`
|
|
261
|
-
`)K++;if(!B())return;X=!0;continue}if(/\s/.test(V)){J();continue}if(V===";"){if(!B())return;X=!0;continue}if(V==="&"){if($[K+1]!=="&"||!B())return;K++,X=!1;continue}if(V==="|"){let z=$[K+1]==="|";if(!B())return;if(z)K++;X=!1;continue}W=!0,Y+=V,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 HK($){let Z=BK($);return Z?.length&&Z.every(fP)?"inspect":"other"}function fZ($){return HK($)==="inspect"}var vP=120000,gP=600000,hP=80,uP=1000;async function VK($,Z,Q){let Y=$.getReader(),W=new TextDecoder,G=new b1;while(!0){let{done:J,value:B}=await Y.read();if(J)break;let K=W.decode(B,{stream:!0});if(!K)continue;G.append(K),Q?.(K,Z)}let X=W.decode();if(X)G.append(X),Q?.(X,Z);return G.read()}async function mP($,Z,Q,Y,W){let G=Bun.spawn(C$($),{cwd:Z,detached:process.platform!=="win32",env:kZ(),stdout:"pipe",stderr:"pipe",stdin:"ignore",windowsHide:!0}),X=!1,J,B=()=>{Y1(G,"SIGTERM"),J??=setTimeout(()=>Y1(G,"SIGKILL"),uP)},K=setTimeout(()=>{X=!0,B()},Y),V=B;Q.addEventListener("abort",V,{once:!0});try{let[z,F,L]=await Promise.all([VK(G.stdout,"stdout",W),VK(G.stderr,"stderr",W),G.exited]);return{stdout:z,stderr:F,exitCode:L,timedOut:X}}finally{if(clearTimeout(K),J)clearTimeout(J);Q.removeEventListener("abort",V)}}function lP($){let Z="",Q,Y=!1,W=()=>{if(Q)clearTimeout(Q);if(Q=void 0,!Z)return;$(Z),Z=""};return{push(G,X){if(X==="stderr"&&!Y)Z+=`${Z.endsWith(`
|
|
246
|
+
[output truncated \u2014 ${Z}. Narrow the request to see more.]`:$.text}var BP=120000,HP=600000,VP=80,zP=1000;async function u3($,Z,Q){let Y=$.getReader(),W=new TextDecoder,G=new C1;while(!0){let{done:J,value:B}=await Y.read();if(J)break;let K=W.decode(B,{stream:!0});if(!K)continue;G.append(K),Q?.(K,Z)}let X=W.decode();if(X)G.append(X),Q?.(X,Z);return G.read()}async function FP($,Z,Q,Y,W){let G=Bun.spawn(P$($),{cwd:Z,detached:process.platform!=="win32",env:EZ(),stdout:"pipe",stderr:"pipe",stdin:"ignore",windowsHide:!0}),X=!1,J,B=()=>{Z1(G,"SIGTERM"),J??=setTimeout(()=>Z1(G,"SIGKILL"),zP)},K=setTimeout(()=>{X=!0,B()},Y),V=B;Q.addEventListener("abort",V,{once:!0});try{let[z,F,D]=await Promise.all([u3(G.stdout,"stdout",W),u3(G.stderr,"stderr",W),G.exited]);return{stdout:z,stderr:F,exitCode:D,timedOut:X}}finally{if(clearTimeout(K),J)clearTimeout(J);Q.removeEventListener("abort",V)}}function LP($){let Z="",Q,Y=!1,W=()=>{if(Q)clearTimeout(Q);if(Q=void 0,!Z)return;$(Z),Z=""};return{push(G,X){if(X==="stderr"&&!Y)Z+=`${Z.endsWith(`
|
|
262
247
|
`)||Z.length===0?"":`
|
|
263
248
|
`}[stderr]
|
|
264
|
-
`,Y=!0;Z+=G,Q??=setTimeout(W,
|
|
265
|
-
${K.stderr.trimEnd()}`);let F=
|
|
249
|
+
`,Y=!0;Z+=G,Q??=setTimeout(W,VP)},flush:W}}function b9($){let Z=$.spawn??FP;return W0({name:"bash",changesState:({command:Q,run_in_background:Y})=>Y===!0||!SZ(Q),isConcurrencySafe:({command:Q,run_in_background:Y})=>Y!==!0&&SZ(Q),permissionScope:({command:Q,run_in_background:Y})=>Y!==!0&&SZ(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 inspection and narrow before reading. Keep searches inspection-safe: do not add printf/echo headings, pipe to sort, or redirect stderr; use rg --sort path, --no-messages, and repeated -e arguments. Keep each pattern simply quoted and never splice quote characters inside a shell regex. Read only relevant line ranges unless full context is needed. Use write/edit tools for file changes.",inputSchema:CZ.object({command:CZ.string().describe("The shell command to run"),description:CZ.string().optional().describe("A short description of what this command does, for the user"),timeoutMs:CZ.number().int().positive().max(HP).optional(),run_in_background:CZ.boolean().optional().describe("Start the command in the background and return a task id immediately")}),execute:async({command:Q,timeoutMs:Y,run_in_background:W},{signal:G,update:X})=>{if(G.aborted)return y("Aborted before the command started.");if(W){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(),B=LP(X),K;try{K=await Z(Q,$.root,G,Y??BP,B.push)}finally{B.flush()}let V=Date.now()-J,z=[];if(K.stdout.trim())z.push(K.stdout.trimEnd());if(K.stderr.trim())z.push(`[stderr]
|
|
250
|
+
${K.stderr.trimEnd()}`);let F=w1(P1(z.join(`
|
|
266
251
|
|
|
267
252
|
`)||"(no output)"),"command produced a lot of output");if(K.timedOut)return{content:[{type:"text",text:`${F}
|
|
268
253
|
|
|
269
|
-
[command timed out and was killed]`}],details:{command:Q,exitCode:K.exitCode,timedOut:!0,durationMs:V},isError:!0};
|
|
254
|
+
[command timed out and was killed]`}],details:{command:Q,exitCode:K.exitCode,timedOut:!0,durationMs:V},isError:!0};if(K.exitCode===1&&g3(Q))return{content:[{type:"text",text:z.length>0?`${F}
|
|
255
|
+
|
|
256
|
+
[no matches]`:"No matches"}],details:{command:Q,exitCode:K.exitCode,noMatches:!0,durationMs:V},isError:!1};let D=K.exitCode!==0;return{content:[{type:"text",text:D?`${F}
|
|
257
|
+
|
|
258
|
+
[exit code ${K.exitCode}]`:F}],details:{command:Q,exitCode:K.exitCode,durationMs:V},isError:D}}})}import{mkdir as DP,readdir as UP,readFile as bZ,realpath as yZ,stat as a3,writeFile as r3}from"fs/promises";import{dirname as t3,isAbsolute as x9,relative as N6,resolve as w$,sep as o3}from"path";import{z as G0}from"zod";var m3=16777216;function T$($,Z){let Q=x9(Z)?w$(Z):w$($,Z),Y=N6(w$($),Q);if(Y===".."||Y.startsWith(`..${o3}`)||x9(Y))throw Error(`Path escapes the session root: ${Z}`);return Q}function k9($,Z,Q){let Y=N6($,Z);if(Y===".."||Y.startsWith(`..${o3}`)||x9(Y))throw Error(`Path escapes the session root through a symbolic link: ${Q}`)}async function A6($,Z){let Q=T$($,Z),Y=await yZ($),W=await yZ(Q);return k9(Y,W,Z),W}async function l3($,Z){let Q=T$($,Z),Y=await yZ($);try{let X=await yZ(Q);return k9(Y,X,Z),X}catch(X){if(X.code!=="ENOENT")throw X}let W=[],G=Q;for(;;)try{let X=await yZ(G);return k9(Y,X,Z),w$(X,...W.reverse())}catch(X){if(X.code!=="ENOENT")throw X;let J=t3(G);if(J===G)throw X;W.push(N6(J,G)),G=J}}function B0($,Z){let Q=N6(w$($),Z);return Q===""?".":Q}function p3($){let Z=$.split(`
|
|
259
|
+
`);if(Z.at(-1)==="")Z.pop();return Z}function s3($,Z,Q){let Y=Z===void 0?[]:p3(Z),W=p3(Q),G=0;while(G<Y.length&&G<W.length&&Y[G]===W[G])G++;let X=0;while(X<Y.length-G&&X<W.length-G&&Y[Y.length-1-X]===W[W.length-1-X])X++;let J=Y.length-G-X,B=W.length-G-X;if(B===0&&J===0)return{path:$,added:B,removed:J,hunks:[]};let K=Math.min(3,G),V=Math.min(3,X),z=G-K,F=G-K,D=K+J+V,L=K+B+V,U=[`@@ -${Y.length===0?0:z+1},${D} +${W.length===0?0:F+1},${L} @@`,...Y.slice(z,G).map((q)=>` ${q}`),...Y.slice(G,Y.length-X).map((q)=>`-${q}`),...W.slice(G,W.length-X).map((q)=>`+${q}`),...W.slice(W.length-X,W.length-X+V).map((q)=>` ${q}`)];return{path:$,added:B,removed:J,hunks:U}}function f9($){return W0({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:G0.object({path:G0.string().describe("Path to the file, absolute or relative to the session root"),offset:G0.number().int().min(1).optional().describe("First line to read (1-based)"),limit:G0.number().int().min(1).optional().describe("Maximum number of lines to read")}),isConcurrencySafe:()=>!0,execute:async({path:Z,offset:Q,limit:Y})=>{let W=T$($.root,Z),G;try{W=await A6($.root,Z);let D=await a3(W);if(D.size>m3)return y(`${B0($.root,W)} is ${D.size.toLocaleString()} bytes; read refuses files larger than ${m3.toLocaleString()} bytes. Use rg through the bounded bash tool to inspect it.`);G=await bZ(W,"utf8")}catch(D){let L=D.code;if(L==="ENOENT")return y(`File not found: ${B0($.root,W)}`);if(L==="EISDIR")return y(`${B0($.root,W)} is a directory \u2014 use ls instead.`);throw D}$.state.markRead(W,G);let X=G.split(`
|
|
260
|
+
`),J=(Q??1)-1,K=X.slice(J,Y?J+Y:void 0).map((D,L)=>`${String(J+L+1).padStart(5)} ${D}`),V=w1(P1(K.join(`
|
|
261
|
+
`)),"file is large"),z=await $.instructions?.instructionsForPath(W);return{content:[{type:"text",text:[V||"(empty file)",z?.text].filter(Boolean).join(`
|
|
270
262
|
|
|
271
|
-
|
|
263
|
+
`)}],details:{path:W,lines:X.length,...z&&z.sources.length>0?{loadedInstructions:z.sources}:{}}}}})}function v9($){return W0({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:G0.object({path:G0.string().describe("Path to the file"),content:G0.string().describe("The complete file contents")}),permissionDetails:async({path:Z,content:Q})=>{let Y=await l3($.root,Z),W;try{W=await bZ(Y,"utf8")}catch{W=void 0}let G=B0($.root,Y);return{description:`${W===void 0?"Create":"Overwrite"} ${G}`,preview:{kind:"diff",file:s3(G,W,Q)}}},execute:async({path:Z,content:Q})=>{let Y=await l3($.root,Z),W=!0,G;try{G=await bZ(Y,"utf8")}catch(J){if(J.code==="ENOENT")W=!1;else throw J}if(W&&!$.state.hasRead(Y))return y(`Refusing to overwrite ${B0($.root,Y)} because it has not been read in this session. Read it first, then write.`);if($.state.hasRead(Y)&&$.state.isStale(Y,G))return y(`${B0($.root,Y)} changed on disk since you read it. Read it again before writing.`);await DP(t3(Y),{recursive:!0}),await r3(Y,Q,"utf8"),$.state.markWritten(Y);let X=Q.split(`
|
|
264
|
+
`).length;return{content:[{type:"text",text:`${W?"Updated":"Created"} ${B0($.root,Y)} (${X} lines)`}],details:{path:Y,created:!W}}}})}var qP=G0.object({oldString:G0.string().describe("Exact text to replace, including indentation"),newString:G0.string().describe("Replacement text"),replaceAll:G0.boolean().optional().describe("Replace every occurrence of this oldString")}),_9=($)=>$.split(`
|
|
265
|
+
`).length-1,c3="\uFEFF";function d3($){return $.startsWith(c3)?{bom:c3,text:$.slice(1)}:{bom:"",text:$}}var i3=($)=>$.replace(/\r?\n/g,`\r
|
|
266
|
+
`),AP=($)=>$.replace(/\r\n/g,`
|
|
267
|
+
`);function NP($,Z,Q){if(Z.includes(`
|
|
268
|
+
`)&&!$.includes(Z)){for(let Y of[i3,AP]){let W=Y(Z);if(W!==Z&&$.includes(W))return{oldString:W,newString:Y(Q)}}return{oldString:Z,newString:Q}}return{oldString:Z,newString:$.includes(`\r
|
|
269
|
+
`)?i3(Q):Q}}function n3($,Z,Q){let Y=(z)=>Z.length>1?`edits[${z}]: `:"",W=[];for(let[z,F]of Z.entries()){let{replaceAll:D}=F,{oldString:L,newString:U}=NP($,F.oldString,F.newString);if(L==="")return{ok:!1,message:`${Y(z)}oldString is empty \u2014 nothing to match.`};if(L===U)return{ok:!1,message:`${Y(z)}oldString and newString are identical \u2014 nothing to do.`};let q=$.split(L).length-1;if(q===0)return{ok:!1,message:`${Y(z)}oldString was not found in ${Q}. The text must match exactly, including whitespace and indentation.`};if(q>1&&!D)return{ok:!1,message:`${Y(z)}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(W.push({start:N,end:N+L.length,newString:U,index:z}),!D)break;A=N+L.length}}W.sort((z,F)=>z.start-F.start);let G;for(let z of W){if(G&&G.end>z.start)return{ok:!1,message:G.start===z.start&&G.end===z.end?`edits[${G.index}] and edits[${z.index}] match the same text in ${Q}. Drop the duplicate, or give each edit different text to match.`:`edits[${G.index}] and edits[${z.index}] overlap in ${Q}. Merge them into one edit, or target text that does not overlap.`};G=z}let X="",J=0,B=1,K=1,V=[];for(let z of W){let F=$.slice(J,z.start),D=_9(F);B+=D,K+=D,V.push({edit:z.index,oldLine:B,newLine:K}),X+=F+z.newString,B+=_9($.slice(z.start,z.end)),K+=_9(z.newString),J=z.end}return X+=$.slice(J),{ok:!0,updated:X,replacements:W.length,hunks:V}}function MP($){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:Y,replaceAll:W,...G}=Z,X=Array.isArray(Z.edits)?Z.edits:[];return{...G,edits:[...X,{oldString:Q,newString:Y,...W===void 0?{}:{replaceAll:W}}]}}return Z}function g9($){return W0({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:G0.object({path:G0.string().describe("Path to the file"),edits:G0.array(qP).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:MP,permissionDetails:async({path:Z,edits:Q})=>{let Y=await A6($.root,Z),W=B0($.root,Y),G;try{G=await bZ(Y,"utf8")}catch{return{description:`Edit ${W}`}}let{text:X}=d3(G),J=n3(X,Q,W);if(!J.ok)return{description:`Edit ${W}`};return{description:`Edit ${W}`,preview:{kind:"diff",file:s3(W,X,J.updated)}}},execute:async({path:Z,edits:Q})=>{let Y=T$($.root,Z);try{Y=await A6($.root,Z)}catch(z){if(z.code==="ENOENT")return y(`File not found: ${B0($.root,Y)}`);throw z}if(!$.state.hasRead(Y))return y(`Read ${B0($.root,Y)} before editing it, so you can see what you are changing.`);let W;try{W=await bZ(Y,"utf8")}catch(z){if(z.code==="ENOENT")return y(`File not found: ${B0($.root,Y)}`);throw z}if($.state.isStale(Y,W))return y(`${B0($.root,Y)} changed on disk since you read it. Read it again before editing.`);let{bom:G,text:X}=d3(W),J=n3(X,Q,B0($.root,Y));if(!J.ok)return y(J.message);let{updated:B,replacements:K,hunks:V}=J;return await r3(Y,G+B,"utf8"),$.state.markWritten(Y),{content:[{type:"text",text:`Edited ${B0($.root,Y)} (${K} replacement${K===1?"":"s"})`}],details:{path:Y,occurrences:K,edits:Q.length,hunks:V}}}})}function h9($){return W0({name:"ls",description:"List the entries of a directory.",inputSchema:G0.object({path:G0.string().optional().describe("Directory to list; defaults to the session root")}),isConcurrencySafe:()=>!0,execute:async({path:Z})=>{let Q=Z??".",Y=T$($.root,Q),W;try{Y=await A6($.root,Q),W=await UP(Y)}catch(X){if(X.code==="ENOENT")return y(`Directory not found: ${B0($.root,Y)}`);throw X}let G=await Promise.all(W.sort().map(async(X)=>{try{return(await a3(w$(Y,X))).isDirectory()?`${X}/`:X}catch{return X}}));return w1(P1(G.join(`
|
|
270
|
+
`)||"(empty directory)"),"directory has many entries")}})}import{z as x0}from"zod";function u9($){return({command:Z,onOutput:Q,cols:Y,rows:W})=>{if(process.platform==="win32"){let L=Bun.spawn(P$(Z,{interactive:!0}),{cwd:$,detached:!1,env:EZ(),stdin:"pipe",stdout:"pipe",stderr:"pipe",windowsHide:!0}),U=async(N)=>{let j=N.getReader(),P=new TextDecoder;while(!0){let{done:S,value:g}=await j.read();if(S)break;let n=P.decode(g,{stream:!0});if(n)Q(n)}let M=P.decode();if(M)Q(M)},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:()=>{Z1(L,"SIGTERM"),A=setTimeout(()=>{if(L.exitCode===null)Z1(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,B=new Promise((L)=>{J=L}),K=()=>{if(X)return;X=!0;let L=G.decode();if(L)Q(L)},V=Bun.spawn(P$(Z,{interactive:!0}),{cwd:$,detached:!0,env:EZ({TERM:"xterm-256color"}),terminal:{cols:Y,rows:W,data:(L,U)=>{let q=G.decode(U,{stream:!0});if(q)Q(q)},exit:()=>{K(),J?.()}}}),z=V.terminal;if(!z)throw Error("Could not allocate a pseudo-terminal.");let F=Promise.all([V.exited,B]).then(([L])=>{if(K(),!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:()=>{Z1(V,"SIGTERM"),D=setTimeout(()=>{if(V.exitCode===null)Z1(V,"SIGKILL")},1000),D.unref?.()},exited:F.finally(()=>{if(D)clearTimeout(D)})}}}function m9($){let Z=W0({name:"task_output",description:"Read output from a background task. Returns only what is new since the last read unless full is set.",inputSchema:x0.object({taskId:x0.string(),full:x0.boolean().optional().describe("Return all output rather than only what is new")}),isConcurrencySafe:()=>!0,execute:({taskId:X,full:J})=>{let B=$.get(X);if(!B)return y(`No such task: ${X}`);let K=$.output(X,J?"start":"new"),V=B.status==="running"?"still running":`${B.status}${B.exitCode!==null?` (exit ${B.exitCode})`:""}`,z=K?.text.trim().length?K.text:"(no new output)";return{content:[{type:"text",text:`${w1(P1(z),"task output is large")}
|
|
272
271
|
|
|
273
|
-
[${V}]`}],details:{taskId:X,status:B.status,exitCode:B.exitCode}}}}),Q=
|
|
274
|
-
`)}});return[Z,Q,Y,W,G]}import{z as
|
|
275
|
-
`)}function
|
|
272
|
+
[${V}]`}],details:{taskId:X,status:B.status,exitCode:B.exitCode}}}}),Q=W0({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:x0.object({taskId:x0.string(),data:x0.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.`)}}),Y=W0({name:"task_kill",description:"Stop a background task.",inputSchema:x0.object({taskId:x0.string()}),execute:({taskId:X})=>{if(!$.get(X))return y(`No such task: ${X}`);return $.kill(X)?`Killed ${X}.`:`Task ${X} had already stopped.`}}),W=W0({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:x0.object({taskId:x0.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=W0({name:"task_list",description:"List background tasks started in this session.",inputSchema:x0.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(`
|
|
273
|
+
`)}});return[Z,Q,Y,W,G]}import{z as _Z}from"zod";class M6{items=[];replace($){this.items=$}all(){return[...this.items]}}var OP={pending:"[ ]",in_progress:"[~]",completed:"[x]"};function e3($){if($.length===0)return"(no tasks)";return $.map((Z)=>`${OP[Z.status]} ${Z.content}`).join(`
|
|
274
|
+
`)}function l9($){return W0({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:_Z.object({items:_Z.array(_Z.object({content:_Z.string().describe("What needs doing"),status:_Z.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 Y=e3(Z),W=Q>1?`
|
|
276
275
|
|
|
277
|
-
[note: more than one task is in_progress \u2014 work on one at a time]`:"";return{content:[{type:"text",text:`${Y}${W}`}],details:{items:Z}}}})}async function
|
|
276
|
+
[note: more than one task is in_progress \u2014 work on one at a time]`:"";return{content:[{type:"text",text:`${Y}${W}`}],details:{items:Z}}}})}async function TP($,Z){let Q=wP($,".mu","config.json");try{let Y=JSON.parse(await jP(Q,"utf8"));if(typeof Y!=="object"||Y===null||Array.isArray(Y))return Z(`Invalid user config at ${Q}: config must be an object`),{};let W=Y.instructions;if(W===void 0)return{};let G=H4.safeParse(W);if(!G.success)return Z(`Invalid user config at ${Q}: ${G.error.issues.map((z)=>`instructions.${z.path.join(".")}: ${z.message}`).join("; ")}`),{};let{enabled:X,fallbackFilenames:J,projectRootMarkers:B,imports:K,claudeRules:V}=G.data;return{...X!==void 0?{enabled:X}:{},...J!==void 0?{fallbackFilenames:J}:{},...B!==void 0?{projectRootMarkers:B}:{},...K!==void 0?{imports:K}:{},...V!==void 0?{claudeRules:V}:{}}}catch(Y){if(Y.code!=="ENOENT")Z(`Invalid user config at ${Q}: ${Y instanceof Error?Y.message:Y}`);return{}}}async function ZK($={}){let Z=$K($.root??process.cwd()),Q=$K($.home??PP()),Y=new W5,W=new M6,G=[],X=await Q5(Z,(L)=>G.push(L)),J=new Z5({root:Z,home:Q,...await TP(Q,(L)=>G.push(L)),...X.instructions??{},...$.instructions??{},...$.managedInstructionPaths?{managedPaths:$.managedInstructionPaths}:{}});await J.reload();let B={root:Z,state:Y,instructions:J},K=new aZ($.spawner??u9(Z),$.processEvents??{}),V=[f9(B),v9(B),g9(B),h9(B),b9({root:Z,processes:K,...$.spawn?{spawn:$.spawn}:{}}),l9(W),...m9(K)],z={attach:(L)=>{K.setEvents({onStarted:(U)=>{$.processEvents?.onStarted?.(U),L.emit({type:"task_started",taskId:U.id,command:U.command,background:!0})},onOutput:(U,q)=>{$.processEvents?.onOutput?.(U,q),L.emit({type:"task_output",taskId:U,chunk:q})},onExited:(U)=>{if($.processEvents?.onExited?.(U),L.emit({type:"task_exited",taskId:U.id,exitCode:U.exitCode,status:U.status==="killed"?"killed":"exited"}),!U.detached)L.followUp(a6(U))}})},resize:(L,U)=>K.resizeAll(L,U),stop:()=>K.stopAll(),shutdown:()=>K.killAll()},F,D=()=>{if(!F)F=G4(Z);return F};return{name:"coding",toolset:V,promptFor:F4,permissionDefaults:V4(K4,X.permissions),permissionModes:B4,defaultPermissionMode:"default",rememberPermission:(L,U)=>z4(Z,L,U),environment:D,contextMessages:async()=>[X4(await D())],refreshContext:(L,U)=>J.refreshedMessages(L,U.sessionId),diagnostics:[...G,...J.snapshot.diagnostics.map((L)=>L.path?`${L.path}: ${L.message}`:L.message)],commands:[{name:"instructions",description:"Show or reload instruction files",run:async(L)=>{let U=L.args.trim();if(U&&U!=="reload")return{handled:!0,message:"Usage: /instructions [reload]"};if(U==="reload")await J.reload({resetNested:!0});return{handled:!0,message:J.formatStatus(U==="reload"?"instructions reloaded":"instructions")}}},{name:"reload",description:"Reload instruction files",run:async()=>{return await J.reload({resetNested:!0}),{handled:!0,message:J.formatStatus("instructions reloaded")}}}],carryoverExtractor:()=>({readFiles:Y.readFiles(),modifiedFiles:Y.modifiedFiles(),todos:W.all()}),scope:()=>Z.replace(/[^A-Za-z0-9]+/g,"-").replace(/^-|-$/g,""),checkpointProvider:new sZ({root:Z}),runtime:z,fileState:Y,todos:W,processes:K,instructions:J}}function IP($){if(typeof $.model==="string")return $.model;if($.model)return`${$.model.provider}/${$.model.id}`;return e1()}async function m_($={}){let{profile:Z,profileOptions:Q,...Y}=$;if(!Z)return new n$(Y);let W=Z==="coding"?await ZK(Q):Z;return new n$(await T9(W,IP(Y),Y))}export{Q$ as userMessage,rQ as totalTokens,W0 as tool,CV as toCommand,i0 as thinkingLevelForModel,OQ as textResult,$$ as supportedThinkingLevels,MY as substituteArguments,D4 as structuredOutputTool,U4 as structuredOutputPrompt,dH as storedAuthProviders,hj as skillsExtension,I3 as skillListing,yj as shellHooksExtension,aj as sessionToMarkdown,pH as saveApiKey,DY as resolveExtensionFiles,A4 as renderAuthPage,cH as removeStoredCredential,BV as registryWithCoreCommands,WQ as registerProvider,zQ as registerModels,VQ as refreshModels,r0 as readAuthFile,k6 as providerHasCredentials,iH as preferredAuthProvider,OY as parseMarkdownCommand,z5 as parseFrontmatter,T9 as optionsFromProfile,Rj as mcpExtension,WV as loginXai,JV as loginOpenRouter,ZV as loginOpenAI,YV as loginKimiCoding,GV as loginGitHubCopilot,R9 as loadSkill,Ej as loadProfile,Tj as loadMcpConfig,SV as loadMarkdownCommands,qV as loadExtensions,x6 as listModels,mZ as findModel,y as errorResult,vj as discoverSkills,HQ as discoverModels,v6 as defaultThinkingLevel,gj as defaultSkillRoots,e1 as defaultModelRef,LQ as defaultModelId,P4 as defaultAuthFile,g$ as customMessage,eH as createCredentialResolver,m_ as createAgent,LY as coreCommands,ZK as codingProfile,L4 as checkBudget,m0 as builtinProviderConfigs,G5 as authSuccessPage,b1 as authErrorPage,o as SessionTree,Y$ as STRUCTURED_OUTPUT_TOOL,u$ as MemorySessionStore,AY as FileSessionStore,m6 as ExtensionHost,I1 as CommandRegistry,n$ as Agent};
|