@ai-setting/roy-task-plugin 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,120 +1,120 @@
1
1
  // @bun
2
- var V9=Object.create;var{getPrototypeOf:O9,defineProperty:M1,getOwnPropertyNames:A9}=Object;var M9=Object.prototype.hasOwnProperty;function R9(_){return this[_]}var f9,L9,F9=(_,w,$)=>{var X=_!=null&&typeof _==="object";if(X){var Y=w?f9??=new WeakMap:L9??=new WeakMap,J=Y.get(_);if(J)return J}$=_!=null?V9(O9(_)):{};let W=w||!_||!_.__esModule?M1($,"default",{value:_,enumerable:!0}):$;for(let Q of A9(_))if(!M9.call(W,Q))M1(W,Q,{get:R9.bind(_,Q),enumerable:!0});if(X)Y.set(_,W);return W};var P=(_,w)=>()=>(w||_((w={exports:{}}).exports,w),w.exports);var K9=(_)=>_;function N9(_,w){this[_]=K9.bind(null,w)}var b9=(_,w)=>{for(var $ in w)M1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:N9.bind(w,$)})};var $2=import.meta.require;var p=P((o7)=>{var p1=Symbol.for("yaml.alias"),K8=Symbol.for("yaml.document"),U2=Symbol.for("yaml.map"),N8=Symbol.for("yaml.pair"),i1=Symbol.for("yaml.scalar"),z2=Symbol.for("yaml.seq"),u_=Symbol.for("yaml.node.type"),c7=(_)=>!!_&&typeof _==="object"&&_[u_]===p1,d7=(_)=>!!_&&typeof _==="object"&&_[u_]===K8,p7=(_)=>!!_&&typeof _==="object"&&_[u_]===U2,i7=(_)=>!!_&&typeof _==="object"&&_[u_]===N8,b8=(_)=>!!_&&typeof _==="object"&&_[u_]===i1,n7=(_)=>!!_&&typeof _==="object"&&_[u_]===z2;function j8(_){if(_&&typeof _==="object")switch(_[u_]){case U2:case z2:return!0}return!1}function r7(_){if(_&&typeof _==="object")switch(_[u_]){case p1:case U2:case i1:case z2:return!0}return!1}var a7=(_)=>(b8(_)||j8(_))&&!!_.anchor;o7.ALIAS=p1;o7.DOC=K8;o7.MAP=U2;o7.NODE_TYPE=u_;o7.PAIR=N8;o7.SCALAR=i1;o7.SEQ=z2;o7.hasAnchor=a7;o7.isAlias=c7;o7.isCollection=j8;o7.isDocument=d7;o7.isMap=p7;o7.isNode=r7;o7.isPair=i7;o7.isScalar=b8;o7.isSeq=n7});var U0=P((UY)=>{var Y_=p(),H_=Symbol("break visit"),E8=Symbol("skip children"),k_=Symbol("remove node");function V2(_,w){let $=S8(w);if(Y_.isDocument(_)){if(uw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else uw(null,_,$,Object.freeze([]))}V2.BREAK=H_;V2.SKIP=E8;V2.REMOVE=k_;function uw(_,w,$,X){let Y=P8(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return Z8(_,X,Y),uw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let W=uw(J,w.items[J],$,X);if(typeof W==="number")J=W-1;else if(W===H_)return H_;else if(W===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=uw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let W=uw("value",w.value,$,X);if(W===H_)return H_;else if(W===k_)w.value=null}}return Y}async function O2(_,w){let $=S8(w);if(Y_.isDocument(_)){if(await lw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else await lw(null,_,$,Object.freeze([]))}O2.BREAK=H_;O2.SKIP=E8;O2.REMOVE=k_;async function lw(_,w,$,X){let Y=await P8(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return Z8(_,X,Y),lw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let W=await lw(J,w.items[J],$,X);if(typeof W==="number")J=W-1;else if(W===H_)return H_;else if(W===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=await lw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let W=await lw("value",w.value,$,X);if(W===H_)return H_;else if(W===k_)w.value=null}}return Y}function S8(_){if(typeof _==="object"&&(_.Collection||_.Node||_.Value))return Object.assign({Alias:_.Node,Map:_.Node,Scalar:_.Node,Seq:_.Node},_.Value&&{Map:_.Value,Scalar:_.Value,Seq:_.Value},_.Collection&&{Map:_.Collection,Seq:_.Collection},_);return _}function P8(_,w,$,X){if(typeof $==="function")return $(_,w,X);if(Y_.isMap(w))return $.Map?.(_,w,X);if(Y_.isSeq(w))return $.Seq?.(_,w,X);if(Y_.isPair(w))return $.Pair?.(_,w,X);if(Y_.isScalar(w))return $.Scalar?.(_,w,X);if(Y_.isAlias(w))return $.Alias?.(_,w,X);return}function Z8(_,w,$){let X=w[w.length-1];if(Y_.isCollection(X))X.items[_]=$;else if(Y_.isPair(X))if(_==="key")X.key=$;else X.value=$;else if(Y_.isDocument(X))X.contents=$;else{let Y=Y_.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${Y} parent`)}}UY.visit=V2;UY.visitAsync=O2});var n1=P((RY)=>{var C8=p(),OY=U0(),AY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},MY=(_)=>_.replace(/[!,[\]{}]/g,(w)=>AY[w]);class O_{constructor(_,w){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},O_.defaultYaml,_),this.tags=Object.assign({},O_.defaultTags,w)}clone(){let _=new O_(this.yaml,this.tags);return _.docStart=this.docStart,_}atDocument(){let _=new O_(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:O_.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},O_.defaultTags);break}return _}add(_,w){if(this.atNextDocument)this.yaml={explicit:O_.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},O_.defaultTags),this.atNextDocument=!1;let $=_.trim().split(/[ \t]+/),X=$.shift();switch(X){case"%TAG":{if($.length!==2){if(w(0,"%TAG directive should contain exactly two parts"),$.length<2)return!1}let[Y,J]=$;return this.tags[Y]=J,!0}case"%YAML":{if(this.yaml.explicit=!0,$.length!==1)return w(0,"%YAML directive should contain exactly one part"),!1;let[Y]=$;if(Y==="1.1"||Y==="1.2")return this.yaml.version=Y,!0;else{let J=/^\d+\.\d+$/.test(Y);return w(6,`Unsupported YAML version ${Y}`,J),!1}}default:return w(0,`Unknown directive ${X}`,!0),!1}}tagName(_,w){if(_==="!")return"!";if(_[0]!=="!")return w(`Not a valid tag: ${_}`),null;if(_[1]==="<"){let J=_.slice(2,-1);if(J==="!"||J==="!!")return w(`Verbatim tags aren't resolved, so ${_} is invalid.`),null;if(_[_.length-1]!==">")w("Verbatim tags must end with a >");return J}let[,$,X]=_.match(/^(.*!)([^!]*)$/s);if(!X)w(`The ${_} tag has no suffix`);let Y=this.tags[$];if(Y)try{return Y+decodeURIComponent(X)}catch(J){return w(String(J)),null}if($==="!")return _;return w(`Could not resolve tag: ${_}`),null}tagString(_){for(let[w,$]of Object.entries(this.tags))if(_.startsWith($))return w+MY(_.substring($.length));return _[0]==="!"?_:`!<${_}>`}toString(_){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],$=Object.entries(this.tags),X;if(_&&$.length>0&&C8.isNode(_.contents)){let Y={};OY.visit(_.contents,(J,W)=>{if(C8.isNode(W)&&W.tag)Y[W.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,J]of $){if(Y==="!!"&&J==="tag:yaml.org,2002:")continue;if(!_||X.some((W)=>W.startsWith(J)))w.push(`%TAG ${Y} ${J}`)}return w.join(`
3
- `)}}O_.defaultYaml={explicit:!1,version:"1.2"};O_.defaultTags={"!!":"tag:yaml.org,2002:"};RY.Directives=O_});var A2=P((NY)=>{var T8=p(),LY=U0();function FY(_){if(/[\x00-\x19\s,[\]{}]/.test(_)){let $=`Anchor must not contain whitespace or control characters: ${JSON.stringify(_)}`;throw Error($)}return!0}function I8(_){let w=new Set;return LY.visit(_,{Value($,X){if(X.anchor)w.add(X.anchor)}}),w}function k8(_,w){for(let $=1;;++$){let X=`${_}${$}`;if(!w.has(X))return X}}function KY(_,w){let $=[],X=new Map,Y=null;return{onAnchor:(J)=>{$.push(J),Y??(Y=I8(_));let W=k8(w,Y);return Y.add(W),W},setAnchors:()=>{for(let J of $){let W=X.get(J);if(typeof W==="object"&&W.anchor&&(T8.isScalar(W.node)||T8.isCollection(W.node)))W.node.anchor=W.anchor;else{let Q=Error("Failed to resolve repeated object (this should not happen)");throw Q.source=J,Q}}},sourceObjects:X}}NY.anchorIsValid=FY;NY.anchorNames=I8;NY.createNodeAnchors=KY;NY.findNewAnchor=k8});var r1=P((PY)=>{function z0(_,w,$,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,J=X.length;Y<J;++Y){let W=X[Y],Q=z0(_,X,String(Y),W);if(Q===void 0)delete X[Y];else if(Q!==W)X[Y]=Q}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let J=X.get(Y),W=z0(_,X,Y,J);if(W===void 0)X.delete(Y);else if(W!==J)X.set(Y,W)}else if(X instanceof Set)for(let Y of Array.from(X)){let J=z0(_,X,Y,Y);if(J===void 0)X.delete(Y);else if(J!==Y)X.delete(Y),X.add(J)}else for(let[Y,J]of Object.entries(X)){let W=z0(_,X,Y,J);if(W===void 0)delete X[Y];else if(W!==J)X[Y]=W}return _.call(w,$,X)}PY.applyReviver=z0});var o_=P((TY)=>{var CY=p();function g8(_,w,$){if(Array.isArray(_))return _.map((X,Y)=>g8(X,String(Y),$));if(_&&typeof _.toJSON==="function"){if(!$||!CY.hasAnchor(_))return _.toJSON(w,$);let X={aliasCount:0,count:1,res:void 0};$.anchors.set(_,X),$.onCreate=(J)=>{X.res=J,delete $.onCreate};let Y=_.toJSON(w,$);if($.onCreate)$.onCreate(Y);return Y}if(typeof _==="bigint"&&!$?.keep)return Number(_);return _}TY.toJS=g8});var M2=P((hY)=>{var kY=r1(),h8=p(),gY=o_();class y8{constructor(_){Object.defineProperty(this,h8.NODE_TYPE,{value:_})}clone(){let _=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)_.range=this.range.slice();return _}toJS(_,{mapAsMap:w,maxAliasCount:$,onAnchor:X,reviver:Y}={}){if(!h8.isDocument(_))throw TypeError("A document argument is required");let J={anchors:new Map,doc:_,keep:!0,mapAsMap:w===!0,mapKeyWarned:!1,maxAliasCount:typeof $==="number"?$:100},W=gY.toJS(this,"",J);if(typeof X==="function")for(let{count:Q,res:G}of J.anchors.values())X(G,Q);return typeof Y==="function"?kY.applyReviver(Y,{"":W},"",W):W}}hY.NodeBase=y8});var V0=P((lY)=>{var vY=A2(),xY=U0(),cw=p(),mY=M2(),uY=o_();class v8 extends mY.NodeBase{constructor(_){super(cw.ALIAS);this.source=_,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(_,w){if(w?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let $;if(w?.aliasResolveCache)$=w.aliasResolveCache;else if($=[],xY.visit(_,{Node:(Y,J)=>{if(cw.isAlias(J)||cw.hasAnchor(J))$.push(J)}}),w)w.aliasResolveCache=$;let X=void 0;for(let Y of $){if(Y===this)break;if(Y.anchor===this.source)X=Y}if(X&&w){let{anchors:Y,doc:J,maxAliasCount:W}=w,Q=Y.get(X);if(!Q)uY.toJS(X,null,w),Q=Y.get(X);if(Q?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(W>=0){if(Q.count+=1,Q.aliasCount===0)Q.aliasCount=R2(J,X,Y);if(Q.count*Q.aliasCount>W)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON(_,w){if(!w)return{source:this.source};let $=this.resolve(w.doc,w);if(!$){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return w.anchors.get($).res}toString(_,w,$){let X=`*${this.source}`;if(_){if(vY.anchorIsValid(this.source),_.options.verifyAliasOrder&&!_.anchors.has(this.source)){let Y=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(Y)}if(_.implicitKey)return`${X} `}return X}}function R2(_,w,$){if(cw.isAlias(w)){let X=w.resolve(_),Y=$&&X&&$.get(X);return Y?Y.count*Y.aliasCount:0}else if(cw.isCollection(w)){let X=0;for(let Y of w.items){let J=R2(_,Y,$);if(J>X)X=J}return X}else if(cw.isPair(w)){let X=R2(_,w.key,$),Y=R2(_,w.value,$);return Math.max(X,Y)}return 1}lY.Alias=v8});var X_=P((rY)=>{var dY=p(),pY=M2(),iY=o_(),nY=(_)=>!_||typeof _!=="function"&&typeof _!=="object";class Bw extends pY.NodeBase{constructor(_){super(dY.SCALAR);this.value=_}toJSON(_,w){return w?.keep?this.value:iY.toJS(this.value,_,w)}toString(){return String(this.value)}}Bw.BLOCK_FOLDED="BLOCK_FOLDED";Bw.BLOCK_LITERAL="BLOCK_LITERAL";Bw.PLAIN="PLAIN";Bw.QUOTE_DOUBLE="QUOTE_DOUBLE";Bw.QUOTE_SINGLE="QUOTE_SINGLE";rY.Scalar=Bw;rY.isScalarValue=nY});var O0=P((wJ)=>{var sY=V0(),Uw=p(),x8=X_(),tY="tag:yaml.org,2002:";function eY(_,w,$){if(w){let X=$.filter((J)=>J.tag===w),Y=X.find((J)=>!J.format)??X[0];if(!Y)throw Error(`Tag ${w} not found`);return Y}return $.find((X)=>X.identify?.(_)&&!X.format)}function _J(_,w,$){if(Uw.isDocument(_))_=_.contents;if(Uw.isNode(_))return _;if(Uw.isPair(_)){let B=$.schema[Uw.MAP].createNode?.($.schema,null,$);return B.items.push(_),B}if(_ instanceof String||_ instanceof Number||_ instanceof Boolean||typeof BigInt<"u"&&_ instanceof BigInt)_=_.valueOf();let{aliasDuplicateObjects:X,onAnchor:Y,onTagObj:J,schema:W,sourceObjects:Q}=$,G=void 0;if(X&&_&&typeof _==="object")if(G=Q.get(_),G)return G.anchor??(G.anchor=Y(_)),new sY.Alias(G.anchor);else G={anchor:null,node:null},Q.set(_,G);if(w?.startsWith("!!"))w=tY+w.slice(2);let q=eY(_,w,W.tags);if(!q){if(_&&typeof _.toJSON==="function")_=_.toJSON();if(!_||typeof _!=="object"){let B=new x8.Scalar(_);if(G)G.node=B;return B}q=_ instanceof Map?W[Uw.MAP]:(Symbol.iterator in Object(_))?W[Uw.SEQ]:W[Uw.MAP]}if(J)J(q),delete $.onTagObj;let H=q?.createNode?q.createNode($.schema,_,$):typeof q?.nodeClass?.from==="function"?q.nodeClass.from($.schema,_,$):new x8.Scalar(_);if(w)H.tag=w;else if(!q.default)H.tag=q.tag;if(G)G.node=H;return H}wJ.createNode=_J});var f2=P((JJ)=>{var XJ=O0(),g_=p(),YJ=M2();function a1(_,w,$){let X=$;for(let Y=w.length-1;Y>=0;--Y){let J=w[Y];if(typeof J==="number"&&Number.isInteger(J)&&J>=0){let W=[];W[J]=X,X=W}else X=new Map([[J,X]])}return XJ.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:_,sourceObjects:new Map})}var m8=(_)=>_==null||typeof _==="object"&&!!_[Symbol.iterator]().next().done;class u8 extends YJ.NodeBase{constructor(_,w){super(_);Object.defineProperty(this,"schema",{value:w,configurable:!0,enumerable:!1,writable:!0})}clone(_){let w=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(_)w.schema=_;if(w.items=w.items.map(($)=>g_.isNode($)||g_.isPair($)?$.clone(_):$),this.range)w.range=this.range.slice();return w}addIn(_,w){if(m8(_))this.add(w);else{let[$,...X]=_,Y=this.get($,!0);if(g_.isCollection(Y))Y.addIn(X,w);else if(Y===void 0&&this.schema)this.set($,a1(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}deleteIn(_){let[w,...$]=_;if($.length===0)return this.delete(w);let X=this.get(w,!0);if(g_.isCollection(X))return X.deleteIn($);else throw Error(`Expected YAML collection at ${w}. Remaining path: ${$}`)}getIn(_,w){let[$,...X]=_,Y=this.get($,!0);if(X.length===0)return!w&&g_.isScalar(Y)?Y.value:Y;else return g_.isCollection(Y)?Y.getIn(X,w):void 0}hasAllNullValues(_){return this.items.every((w)=>{if(!g_.isPair(w))return!1;let $=w.value;return $==null||_&&g_.isScalar($)&&$.value==null&&!$.commentBefore&&!$.comment&&!$.tag})}hasIn(_){let[w,...$]=_;if($.length===0)return this.has(w);let X=this.get(w,!0);return g_.isCollection(X)?X.hasIn($):!1}setIn(_,w){let[$,...X]=_;if(X.length===0)this.set($,w);else{let Y=this.get($,!0);if(g_.isCollection(Y))Y.setIn(X,w);else if(Y===void 0&&this.schema)this.set($,a1(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}}JJ.Collection=u8;JJ.collectionFromPath=a1;JJ.isEmptyPath=m8});var A0=P((DJ)=>{var qJ=(_)=>_.replace(/^(?!$)(?: $)?/gm,"#");function o1(_,w){if(/^\n+$/.test(_))return _.substring(1);return w?_.replace(/^(?! *$)/gm,w):_}var HJ=(_,w,$)=>_.endsWith(`
4
- `)?o1($,w):$.includes(`
2
+ var OX=Object.create;var{getPrototypeOf:AX,defineProperty:M2,getOwnPropertyNames:MX}=Object;var RX=Object.prototype.hasOwnProperty;function fX(_){return this[_]}var LX,FX,KX=(_,w,$)=>{var X=_!=null&&typeof _==="object";if(X){var Y=w?LX??=new WeakMap:FX??=new WeakMap,J=Y.get(_);if(J)return J}$=_!=null?OX(AX(_)):{};let D=w||!_||!_.__esModule?M2($,"default",{value:_,enumerable:!0}):$;for(let W of MX(_))if(!RX.call(D,W))M2(D,W,{get:fX.bind(_,W),enumerable:!0});if(X)Y.set(_,D);return D};var P=(_,w)=>()=>(w||_((w={exports:{}}).exports,w),w.exports);var NX=(_)=>_;function bX(_,w){this[_]=NX.bind(null,w)}var jX=(_,w)=>{for(var $ in w)M2(_,$,{get:w[$],enumerable:!0,configurable:!0,set:bX.bind(w,$)})};var $1=import.meta.require;var p=P((e7)=>{var p2=Symbol.for("yaml.alias"),j4=Symbol.for("yaml.document"),U1=Symbol.for("yaml.map"),E4=Symbol.for("yaml.pair"),i2=Symbol.for("yaml.scalar"),z1=Symbol.for("yaml.seq"),u_=Symbol.for("yaml.node.type"),i7=(_)=>!!_&&typeof _==="object"&&_[u_]===p2,n7=(_)=>!!_&&typeof _==="object"&&_[u_]===j4,r7=(_)=>!!_&&typeof _==="object"&&_[u_]===U1,a7=(_)=>!!_&&typeof _==="object"&&_[u_]===E4,S4=(_)=>!!_&&typeof _==="object"&&_[u_]===i2,o7=(_)=>!!_&&typeof _==="object"&&_[u_]===z1;function P4(_){if(_&&typeof _==="object")switch(_[u_]){case U1:case z1:return!0}return!1}function s7(_){if(_&&typeof _==="object")switch(_[u_]){case p2:case U1:case i2:case z1:return!0}return!1}var t7=(_)=>(S4(_)||P4(_))&&!!_.anchor;e7.ALIAS=p2;e7.DOC=j4;e7.MAP=U1;e7.NODE_TYPE=u_;e7.PAIR=E4;e7.SCALAR=i2;e7.SEQ=z1;e7.hasAnchor=t7;e7.isAlias=i7;e7.isCollection=P4;e7.isDocument=n7;e7.isMap=r7;e7.isNode=s7;e7.isPair=a7;e7.isScalar=S4;e7.isSeq=o7});var U0=P((OY)=>{var Y_=p(),H_=Symbol("break visit"),Z4=Symbol("skip children"),k_=Symbol("remove node");function V1(_,w){let $=C4(w);if(Y_.isDocument(_)){if(uw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else uw(null,_,$,Object.freeze([]))}V1.BREAK=H_;V1.SKIP=Z4;V1.REMOVE=k_;function uw(_,w,$,X){let Y=T4(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return I4(_,X,Y),uw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let D=uw(J,w.items[J],$,X);if(typeof D==="number")J=D-1;else if(D===H_)return H_;else if(D===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=uw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let D=uw("value",w.value,$,X);if(D===H_)return H_;else if(D===k_)w.value=null}}return Y}async function O1(_,w){let $=C4(w);if(Y_.isDocument(_)){if(await lw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else await lw(null,_,$,Object.freeze([]))}O1.BREAK=H_;O1.SKIP=Z4;O1.REMOVE=k_;async function lw(_,w,$,X){let Y=await T4(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return I4(_,X,Y),lw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let D=await lw(J,w.items[J],$,X);if(typeof D==="number")J=D-1;else if(D===H_)return H_;else if(D===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=await lw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let D=await lw("value",w.value,$,X);if(D===H_)return H_;else if(D===k_)w.value=null}}return Y}function C4(_){if(typeof _==="object"&&(_.Collection||_.Node||_.Value))return Object.assign({Alias:_.Node,Map:_.Node,Scalar:_.Node,Seq:_.Node},_.Value&&{Map:_.Value,Scalar:_.Value,Seq:_.Value},_.Collection&&{Map:_.Collection,Seq:_.Collection},_);return _}function T4(_,w,$,X){if(typeof $==="function")return $(_,w,X);if(Y_.isMap(w))return $.Map?.(_,w,X);if(Y_.isSeq(w))return $.Seq?.(_,w,X);if(Y_.isPair(w))return $.Pair?.(_,w,X);if(Y_.isScalar(w))return $.Scalar?.(_,w,X);if(Y_.isAlias(w))return $.Alias?.(_,w,X);return}function I4(_,w,$){let X=w[w.length-1];if(Y_.isCollection(X))X.items[_]=$;else if(Y_.isPair(X))if(_==="key")X.key=$;else X.value=$;else if(Y_.isDocument(X))X.contents=$;else{let Y=Y_.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${Y} parent`)}}OY.visit=V1;OY.visitAsync=O1});var n2=P((FY)=>{var k4=p(),RY=U0(),fY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},LY=(_)=>_.replace(/[!,[\]{}]/g,(w)=>fY[w]);class O_{constructor(_,w){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},O_.defaultYaml,_),this.tags=Object.assign({},O_.defaultTags,w)}clone(){let _=new O_(this.yaml,this.tags);return _.docStart=this.docStart,_}atDocument(){let _=new O_(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:O_.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},O_.defaultTags);break}return _}add(_,w){if(this.atNextDocument)this.yaml={explicit:O_.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},O_.defaultTags),this.atNextDocument=!1;let $=_.trim().split(/[ \t]+/),X=$.shift();switch(X){case"%TAG":{if($.length!==2){if(w(0,"%TAG directive should contain exactly two parts"),$.length<2)return!1}let[Y,J]=$;return this.tags[Y]=J,!0}case"%YAML":{if(this.yaml.explicit=!0,$.length!==1)return w(0,"%YAML directive should contain exactly one part"),!1;let[Y]=$;if(Y==="1.1"||Y==="1.2")return this.yaml.version=Y,!0;else{let J=/^\d+\.\d+$/.test(Y);return w(6,`Unsupported YAML version ${Y}`,J),!1}}default:return w(0,`Unknown directive ${X}`,!0),!1}}tagName(_,w){if(_==="!")return"!";if(_[0]!=="!")return w(`Not a valid tag: ${_}`),null;if(_[1]==="<"){let J=_.slice(2,-1);if(J==="!"||J==="!!")return w(`Verbatim tags aren't resolved, so ${_} is invalid.`),null;if(_[_.length-1]!==">")w("Verbatim tags must end with a >");return J}let[,$,X]=_.match(/^(.*!)([^!]*)$/s);if(!X)w(`The ${_} tag has no suffix`);let Y=this.tags[$];if(Y)try{return Y+decodeURIComponent(X)}catch(J){return w(String(J)),null}if($==="!")return _;return w(`Could not resolve tag: ${_}`),null}tagString(_){for(let[w,$]of Object.entries(this.tags))if(_.startsWith($))return w+LY(_.substring($.length));return _[0]==="!"?_:`!<${_}>`}toString(_){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],$=Object.entries(this.tags),X;if(_&&$.length>0&&k4.isNode(_.contents)){let Y={};RY.visit(_.contents,(J,D)=>{if(k4.isNode(D)&&D.tag)Y[D.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,J]of $){if(Y==="!!"&&J==="tag:yaml.org,2002:")continue;if(!_||X.some((D)=>D.startsWith(J)))w.push(`%TAG ${Y} ${J}`)}return w.join(`
3
+ `)}}O_.defaultYaml={explicit:!1,version:"1.2"};O_.defaultTags={"!!":"tag:yaml.org,2002:"};FY.Directives=O_});var A1=P((EY)=>{var g4=p(),NY=U0();function bY(_){if(/[\x00-\x19\s,[\]{}]/.test(_)){let $=`Anchor must not contain whitespace or control characters: ${JSON.stringify(_)}`;throw Error($)}return!0}function h4(_){let w=new Set;return NY.visit(_,{Value($,X){if(X.anchor)w.add(X.anchor)}}),w}function y4(_,w){for(let $=1;;++$){let X=`${_}${$}`;if(!w.has(X))return X}}function jY(_,w){let $=[],X=new Map,Y=null;return{onAnchor:(J)=>{$.push(J),Y??(Y=h4(_));let D=y4(w,Y);return Y.add(D),D},setAnchors:()=>{for(let J of $){let D=X.get(J);if(typeof D==="object"&&D.anchor&&(g4.isScalar(D.node)||g4.isCollection(D.node)))D.node.anchor=D.anchor;else{let W=Error("Failed to resolve repeated object (this should not happen)");throw W.source=J,W}}},sourceObjects:X}}EY.anchorIsValid=bY;EY.anchorNames=h4;EY.createNodeAnchors=jY;EY.findNewAnchor=y4});var r2=P((TY)=>{function z0(_,w,$,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,J=X.length;Y<J;++Y){let D=X[Y],W=z0(_,X,String(Y),D);if(W===void 0)delete X[Y];else if(W!==D)X[Y]=W}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let J=X.get(Y),D=z0(_,X,Y,J);if(D===void 0)X.delete(Y);else if(D!==J)X.set(Y,D)}else if(X instanceof Set)for(let Y of Array.from(X)){let J=z0(_,X,Y,Y);if(J===void 0)X.delete(Y);else if(J!==Y)X.delete(Y),X.add(J)}else for(let[Y,J]of Object.entries(X)){let D=z0(_,X,Y,J);if(D===void 0)delete X[Y];else if(D!==J)X[Y]=D}return _.call(w,$,X)}TY.applyReviver=z0});var s_=P((gY)=>{var kY=p();function v4(_,w,$){if(Array.isArray(_))return _.map((X,Y)=>v4(X,String(Y),$));if(_&&typeof _.toJSON==="function"){if(!$||!kY.hasAnchor(_))return _.toJSON(w,$);let X={aliasCount:0,count:1,res:void 0};$.anchors.set(_,X),$.onCreate=(J)=>{X.res=J,delete $.onCreate};let Y=_.toJSON(w,$);if($.onCreate)$.onCreate(Y);return Y}if(typeof _==="bigint"&&!$?.keep)return Number(_);return _}gY.toJS=v4});var M1=P((xY)=>{var yY=r2(),x4=p(),vY=s_();class m4{constructor(_){Object.defineProperty(this,x4.NODE_TYPE,{value:_})}clone(){let _=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)_.range=this.range.slice();return _}toJS(_,{mapAsMap:w,maxAliasCount:$,onAnchor:X,reviver:Y}={}){if(!x4.isDocument(_))throw TypeError("A document argument is required");let J={anchors:new Map,doc:_,keep:!0,mapAsMap:w===!0,mapKeyWarned:!1,maxAliasCount:typeof $==="number"?$:100},D=vY.toJS(this,"",J);if(typeof X==="function")for(let{count:W,res:G}of J.anchors.values())X(G,W);return typeof Y==="function"?yY.applyReviver(Y,{"":D},"",D):D}}xY.NodeBase=m4});var V0=P((pY)=>{var uY=A1(),lY=U0(),cw=p(),cY=M1(),dY=s_();class u4 extends cY.NodeBase{constructor(_){super(cw.ALIAS);this.source=_,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(_,w){if(w?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let $;if(w?.aliasResolveCache)$=w.aliasResolveCache;else if($=[],lY.visit(_,{Node:(Y,J)=>{if(cw.isAlias(J)||cw.hasAnchor(J))$.push(J)}}),w)w.aliasResolveCache=$;let X=void 0;for(let Y of $){if(Y===this)break;if(Y.anchor===this.source)X=Y}if(X&&w){let{anchors:Y,doc:J,maxAliasCount:D}=w,W=Y.get(X);if(!W)dY.toJS(X,null,w),W=Y.get(X);if(W?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(D>=0){if(W.count+=1,W.aliasCount===0)W.aliasCount=R1(J,X,Y);if(W.count*W.aliasCount>D)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON(_,w){if(!w)return{source:this.source};let $=this.resolve(w.doc,w);if(!$){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return w.anchors.get($).res}toString(_,w,$){let X=`*${this.source}`;if(_){if(uY.anchorIsValid(this.source),_.options.verifyAliasOrder&&!_.anchors.has(this.source)){let Y=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(Y)}if(_.implicitKey)return`${X} `}return X}}function R1(_,w,$){if(cw.isAlias(w)){let X=w.resolve(_),Y=$&&X&&$.get(X);return Y?Y.count*Y.aliasCount:0}else if(cw.isCollection(w)){let X=0;for(let Y of w.items){let J=R1(_,Y,$);if(J>X)X=J}return X}else if(cw.isPair(w)){let X=R1(_,w.key,$),Y=R1(_,w.value,$);return Math.max(X,Y)}return 1}pY.Alias=u4});var X_=P((sY)=>{var nY=p(),rY=M1(),aY=s_(),oY=(_)=>!_||typeof _!=="function"&&typeof _!=="object";class Uw extends rY.NodeBase{constructor(_){super(nY.SCALAR);this.value=_}toJSON(_,w){return w?.keep?this.value:aY.toJS(this.value,_,w)}toString(){return String(this.value)}}Uw.BLOCK_FOLDED="BLOCK_FOLDED";Uw.BLOCK_LITERAL="BLOCK_LITERAL";Uw.PLAIN="PLAIN";Uw.QUOTE_DOUBLE="QUOTE_DOUBLE";Uw.QUOTE_SINGLE="QUOTE_SINGLE";sY.Scalar=Uw;sY.isScalarValue=oY});var O0=P((YJ)=>{var _J=V0(),zw=p(),l4=X_(),wJ="tag:yaml.org,2002:";function $J(_,w,$){if(w){let X=$.filter((J)=>J.tag===w),Y=X.find((J)=>!J.format)??X[0];if(!Y)throw Error(`Tag ${w} not found`);return Y}return $.find((X)=>X.identify?.(_)&&!X.format)}function XJ(_,w,$){if(zw.isDocument(_))_=_.contents;if(zw.isNode(_))return _;if(zw.isPair(_)){let H=$.schema[zw.MAP].createNode?.($.schema,null,$);return H.items.push(_),H}if(_ instanceof String||_ instanceof Number||_ instanceof Boolean||typeof BigInt<"u"&&_ instanceof BigInt)_=_.valueOf();let{aliasDuplicateObjects:X,onAnchor:Y,onTagObj:J,schema:D,sourceObjects:W}=$,G=void 0;if(X&&_&&typeof _==="object")if(G=W.get(_),G)return G.anchor??(G.anchor=Y(_)),new _J.Alias(G.anchor);else G={anchor:null,node:null},W.set(_,G);if(w?.startsWith("!!"))w=wJ+w.slice(2);let Q=$J(_,w,D.tags);if(!Q){if(_&&typeof _.toJSON==="function")_=_.toJSON();if(!_||typeof _!=="object"){let H=new l4.Scalar(_);if(G)G.node=H;return H}Q=_ instanceof Map?D[zw.MAP]:(Symbol.iterator in Object(_))?D[zw.SEQ]:D[zw.MAP]}if(J)J(Q),delete $.onTagObj;let q=Q?.createNode?Q.createNode($.schema,_,$):typeof Q?.nodeClass?.from==="function"?Q.nodeClass.from($.schema,_,$):new l4.Scalar(_);if(w)q.tag=w;else if(!Q.default)q.tag=Q.tag;if(G)G.node=q;return q}YJ.createNode=XJ});var f1=P((GJ)=>{var DJ=O0(),g_=p(),WJ=M1();function a2(_,w,$){let X=$;for(let Y=w.length-1;Y>=0;--Y){let J=w[Y];if(typeof J==="number"&&Number.isInteger(J)&&J>=0){let D=[];D[J]=X,X=D}else X=new Map([[J,X]])}return DJ.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:_,sourceObjects:new Map})}var c4=(_)=>_==null||typeof _==="object"&&!!_[Symbol.iterator]().next().done;class d4 extends WJ.NodeBase{constructor(_,w){super(_);Object.defineProperty(this,"schema",{value:w,configurable:!0,enumerable:!1,writable:!0})}clone(_){let w=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(_)w.schema=_;if(w.items=w.items.map(($)=>g_.isNode($)||g_.isPair($)?$.clone(_):$),this.range)w.range=this.range.slice();return w}addIn(_,w){if(c4(_))this.add(w);else{let[$,...X]=_,Y=this.get($,!0);if(g_.isCollection(Y))Y.addIn(X,w);else if(Y===void 0&&this.schema)this.set($,a2(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}deleteIn(_){let[w,...$]=_;if($.length===0)return this.delete(w);let X=this.get(w,!0);if(g_.isCollection(X))return X.deleteIn($);else throw Error(`Expected YAML collection at ${w}. Remaining path: ${$}`)}getIn(_,w){let[$,...X]=_,Y=this.get($,!0);if(X.length===0)return!w&&g_.isScalar(Y)?Y.value:Y;else return g_.isCollection(Y)?Y.getIn(X,w):void 0}hasAllNullValues(_){return this.items.every((w)=>{if(!g_.isPair(w))return!1;let $=w.value;return $==null||_&&g_.isScalar($)&&$.value==null&&!$.commentBefore&&!$.comment&&!$.tag})}hasIn(_){let[w,...$]=_;if($.length===0)return this.has(w);let X=this.get(w,!0);return g_.isCollection(X)?X.hasIn($):!1}setIn(_,w){let[$,...X]=_;if(X.length===0)this.set($,w);else{let Y=this.get($,!0);if(g_.isCollection(Y))Y.setIn(X,w);else if(Y===void 0&&this.schema)this.set($,a2(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}}GJ.Collection=d4;GJ.collectionFromPath=a2;GJ.isEmptyPath=c4});var A0=P((zJ)=>{var BJ=(_)=>_.replace(/^(?!$)(?: $)?/gm,"#");function o2(_,w){if(/^\n+$/.test(_))return _.substring(1);return w?_.replace(/^(?! *$)/gm,w):_}var UJ=(_,w,$)=>_.endsWith(`
4
+ `)?o2($,w):$.includes(`
5
5
  `)?`
6
- `+o1($,w):(_.endsWith(" ")?"":" ")+$;DJ.indentComment=o1;DJ.lineComment=HJ;DJ.stringifyComment=qJ});var c8=P((OJ)=>{function VJ(_,w,$="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:J=20,onFold:W,onOverflow:Q}={}){if(!Y||Y<0)return _;if(Y<J)J=0;let G=Math.max(1+J,1+Y-w.length);if(_.length<=G)return _;let q=[],H={},B=Y-w.length;if(typeof X==="number")if(X>Y-Math.max(2,J))q.push(0);else B=Y-X;let D=void 0,O=void 0,z=!1,U=-1,V=-1,M=-1;if($==="block"){if(U=l8(_,U,w.length),U!==-1)B=U+G}for(let N;N=_[U+=1];){if($==="quoted"&&N==="\\"){switch(V=U,_[U+1]){case"x":U+=3;break;case"u":U+=5;break;case"U":U+=9;break;default:U+=1}M=U}if(N===`
7
- `){if($==="block")U=l8(_,U,w.length);B=U+w.length+G,D=void 0}else{if(N===" "&&O&&O!==" "&&O!==`
8
- `&&O!=="\t"){let R=_[U+1];if(R&&R!==" "&&R!==`
9
- `&&R!=="\t")D=U}if(U>=B)if(D)q.push(D),B=D+G,D=void 0;else if($==="quoted"){while(O===" "||O==="\t")O=N,N=_[U+=1],z=!0;let R=U>M+1?U-2:V-1;if(H[R])return _;q.push(R),H[R]=!0,B=R+G,D=void 0}else z=!0}O=N}if(z&&Q)Q();if(q.length===0)return _;if(W)W();let f=_.slice(0,q[0]);for(let N=0;N<q.length;++N){let R=q[N],b=q[N+1]||_.length;if(R===0)f=`
10
- ${w}${_.slice(0,b)}`;else{if($==="quoted"&&H[R])f+=`${_[R]}\\`;f+=`
11
- ${w}${_.slice(R+1,b)}`}}return f}function l8(_,w,$){let X=w,Y=w+1,J=_[Y];while(J===" "||J==="\t")if(w<Y+$)J=_[++w];else{do J=_[++w];while(J&&J!==`
12
- `);X=w,Y=w+1,J=_[Y]}return X}OJ.FOLD_BLOCK="block";OJ.FOLD_FLOW="flow";OJ.FOLD_QUOTED="quoted";OJ.foldFlowLines=VJ});var R0=P((NJ)=>{var b_=X_(),s_=c8(),F2=(_,w)=>({indentAtStart:w?_.indent.length:_.indentAtStart,lineWidth:_.options.lineWidth,minContentWidth:_.options.minContentWidth}),K2=(_)=>/^(%|---|\.\.\.)/m.test(_);function LJ(_,w,$){if(!w||w<0)return!1;let X=w-$,Y=_.length;if(Y<=X)return!1;for(let J=0,W=0;J<Y;++J)if(_[J]===`
13
- `){if(J-W>X)return!0;if(W=J+1,Y-W<=X)return!1}return!0}function M0(_,w){let $=JSON.stringify(_);if(w.options.doubleQuotedAsJSON)return $;let{implicitKey:X}=w,Y=w.options.doubleQuotedMinMultiLineLength,J=w.indent||(K2(_)?" ":""),W="",Q=0;for(let G=0,q=$[G];q;q=$[++G]){if(q===" "&&$[G+1]==="\\"&&$[G+2]==="n")W+=$.slice(Q,G)+"\\ ",G+=1,Q=G,q="\\";if(q==="\\")switch($[G+1]){case"u":{W+=$.slice(Q,G);let H=$.substr(G+2,4);switch(H){case"0000":W+="\\0";break;case"0007":W+="\\a";break;case"000b":W+="\\v";break;case"001b":W+="\\e";break;case"0085":W+="\\N";break;case"00a0":W+="\\_";break;case"2028":W+="\\L";break;case"2029":W+="\\P";break;default:if(H.substr(0,2)==="00")W+="\\x"+H.substr(2);else W+=$.substr(G,6)}G+=5,Q=G+1}break;case"n":if(X||$[G+2]==='"'||$.length<Y)G+=1;else{W+=$.slice(Q,G)+`
14
-
15
- `;while($[G+2]==="\\"&&$[G+3]==="n"&&$[G+4]!=='"')W+=`
16
- `,G+=2;if(W+=J,$[G+2]===" ")W+="\\";G+=1,Q=G+1}break;default:G+=1}}return W=Q?W+$.slice(Q):$,X?W:s_.foldFlowLines(W,J,s_.FOLD_QUOTED,F2(w,!1))}function s1(_,w){if(w.options.singleQuote===!1||w.implicitKey&&_.includes(`
17
- `)||/[ \t]\n|\n[ \t]/.test(_))return M0(_,w);let $=w.indent||(K2(_)?" ":""),X="'"+_.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${$}`)+"'";return w.implicitKey?X:s_.foldFlowLines(X,$,s_.FOLD_FLOW,F2(w,!1))}function dw(_,w){let{singleQuote:$}=w.options,X;if($===!1)X=M0;else{let Y=_.includes('"'),J=_.includes("'");if(Y&&!J)X=s1;else if(J&&!Y)X=M0;else X=$?s1:M0}return X(_,w)}var t1;try{t1=new RegExp(`(^|(?<!
6
+ `+o2($,w):(_.endsWith(" ")?"":" ")+$;zJ.indentComment=o2;zJ.lineComment=UJ;zJ.stringifyComment=BJ});var i4=P((RJ)=>{function MJ(_,w,$="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:J=20,onFold:D,onOverflow:W}={}){if(!Y||Y<0)return _;if(Y<J)J=0;let G=Math.max(1+J,1+Y-w.length);if(_.length<=G)return _;let Q=[],q={},H=Y-w.length;if(typeof X==="number")if(X>Y-Math.max(2,J))Q.push(0);else H=Y-X;let B=void 0,O=void 0,z=!1,U=-1,V=-1,M=-1;if($==="block"){if(U=p4(_,U,w.length),U!==-1)H=U+G}for(let N;N=_[U+=1];){if($==="quoted"&&N==="\\"){switch(V=U,_[U+1]){case"x":U+=3;break;case"u":U+=5;break;case"U":U+=9;break;default:U+=1}M=U}if(N===`
7
+ `){if($==="block")U=p4(_,U,w.length);H=U+w.length+G,B=void 0}else{if(N===" "&&O&&O!==" "&&O!==`
8
+ `&&O!=="\t"){let b=_[U+1];if(b&&b!==" "&&b!==`
9
+ `&&b!=="\t")B=U}if(U>=H)if(B)Q.push(B),H=B+G,B=void 0;else if($==="quoted"){while(O===" "||O==="\t")O=N,N=_[U+=1],z=!0;let b=U>M+1?U-2:V-1;if(q[b])return _;Q.push(b),q[b]=!0,H=b+G,B=void 0}else z=!0}O=N}if(z&&W)W();if(Q.length===0)return _;if(D)D();let R=_.slice(0,Q[0]);for(let N=0;N<Q.length;++N){let b=Q[N],E=Q[N+1]||_.length;if(b===0)R=`
10
+ ${w}${_.slice(0,E)}`;else{if($==="quoted"&&q[b])R+=`${_[b]}\\`;R+=`
11
+ ${w}${_.slice(b+1,E)}`}}return R}function p4(_,w,$){let X=w,Y=w+1,J=_[Y];while(J===" "||J==="\t")if(w<Y+$)J=_[++w];else{do J=_[++w];while(J&&J!==`
12
+ `);X=w,Y=w+1,J=_[Y]}return X}RJ.FOLD_BLOCK="block";RJ.FOLD_FLOW="flow";RJ.FOLD_QUOTED="quoted";RJ.foldFlowLines=MJ});var R0=P((EJ)=>{var b_=X_(),t_=i4(),F1=(_,w)=>({indentAtStart:w?_.indent.length:_.indentAtStart,lineWidth:_.options.lineWidth,minContentWidth:_.options.minContentWidth}),K1=(_)=>/^(%|---|\.\.\.)/m.test(_);function NJ(_,w,$){if(!w||w<0)return!1;let X=w-$,Y=_.length;if(Y<=X)return!1;for(let J=0,D=0;J<Y;++J)if(_[J]===`
13
+ `){if(J-D>X)return!0;if(D=J+1,Y-D<=X)return!1}return!0}function M0(_,w){let $=JSON.stringify(_);if(w.options.doubleQuotedAsJSON)return $;let{implicitKey:X}=w,Y=w.options.doubleQuotedMinMultiLineLength,J=w.indent||(K1(_)?" ":""),D="",W=0;for(let G=0,Q=$[G];Q;Q=$[++G]){if(Q===" "&&$[G+1]==="\\"&&$[G+2]==="n")D+=$.slice(W,G)+"\\ ",G+=1,W=G,Q="\\";if(Q==="\\")switch($[G+1]){case"u":{D+=$.slice(W,G);let q=$.substr(G+2,4);switch(q){case"0000":D+="\\0";break;case"0007":D+="\\a";break;case"000b":D+="\\v";break;case"001b":D+="\\e";break;case"0085":D+="\\N";break;case"00a0":D+="\\_";break;case"2028":D+="\\L";break;case"2029":D+="\\P";break;default:if(q.substr(0,2)==="00")D+="\\x"+q.substr(2);else D+=$.substr(G,6)}G+=5,W=G+1}break;case"n":if(X||$[G+2]==='"'||$.length<Y)G+=1;else{D+=$.slice(W,G)+`
14
+
15
+ `;while($[G+2]==="\\"&&$[G+3]==="n"&&$[G+4]!=='"')D+=`
16
+ `,G+=2;if(D+=J,$[G+2]===" ")D+="\\";G+=1,W=G+1}break;default:G+=1}}return D=W?D+$.slice(W):$,X?D:t_.foldFlowLines(D,J,t_.FOLD_QUOTED,F1(w,!1))}function s2(_,w){if(w.options.singleQuote===!1||w.implicitKey&&_.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(_))return M0(_,w);let $=w.indent||(K1(_)?" ":""),X="'"+_.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${$}`)+"'";return w.implicitKey?X:t_.foldFlowLines(X,$,t_.FOLD_FLOW,F1(w,!1))}function dw(_,w){let{singleQuote:$}=w.options,X;if($===!1)X=M0;else{let Y=_.includes('"'),J=_.includes("'");if(Y&&!J)X=s2;else if(J&&!Y)X=M0;else X=$?s2:M0}return X(_,w)}var t2;try{t2=new RegExp(`(^|(?<!
19
19
  ))
20
20
  +(?!
21
- |$)`,"g")}catch{t1=/\n+(?!\n|$)/g}function L2({comment:_,type:w,value:$},X,Y,J){let{blockQuote:W,commentString:Q,lineWidth:G}=X.options;if(!W||/\n[\t ]+$/.test($))return dw($,X);let q=X.indent||(X.forceBlockIndent||K2($)?" ":""),H=W==="literal"?!0:W==="folded"||w===b_.Scalar.BLOCK_FOLDED?!1:w===b_.Scalar.BLOCK_LITERAL?!0:!LJ($,G,q.length);if(!$)return H?`|
21
+ |$)`,"g")}catch{t2=/\n+(?!\n|$)/g}function L1({comment:_,type:w,value:$},X,Y,J){let{blockQuote:D,commentString:W,lineWidth:G}=X.options;if(!D||/\n[\t ]+$/.test($))return dw($,X);let Q=X.indent||(X.forceBlockIndent||K1($)?" ":""),q=D==="literal"?!0:D==="folded"||w===b_.Scalar.BLOCK_FOLDED?!1:w===b_.Scalar.BLOCK_LITERAL?!0:!NJ($,G,Q.length);if(!$)return q?`|
22
22
  `:`>
23
- `;let B,D;for(D=$.length;D>0;--D){let b=$[D-1];if(b!==`
24
- `&&b!=="\t"&&b!==" ")break}let O=$.substring(D),z=O.indexOf(`
25
- `);if(z===-1)B="-";else if($===O||z!==O.length-1){if(B="+",J)J()}else B="";if(O){if($=$.slice(0,-O.length),O[O.length-1]===`
26
- `)O=O.slice(0,-1);O=O.replace(t1,`$&${q}`)}let U=!1,V,M=-1;for(V=0;V<$.length;++V){let b=$[V];if(b===" ")U=!0;else if(b===`
27
- `)M=V;else break}let f=$.substring(0,M<V?M+1:V);if(f)$=$.substring(f.length),f=f.replace(/\n+/g,`$&${q}`);let R=(U?q?"2":"1":"")+B;if(_){if(R+=" "+Q(_.replace(/ ?[\r\n]+/g," ")),Y)Y()}if(!H){let b=$.replace(/\n+/g,`
28
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${q}`),F=!1,T=F2(X,!0);if(W!=="folded"&&w!==b_.Scalar.BLOCK_FOLDED)T.onOverflow=()=>{F=!0};let j=s_.foldFlowLines(`${f}${b}${O}`,q,s_.FOLD_BLOCK,T);if(!F)return`>${R}
29
- ${q}${j}`}return $=$.replace(/\n+/g,`$&${q}`),`|${R}
30
- ${q}${f}${$}${O}`}function FJ(_,w,$,X){let{type:Y,value:J}=_,{actualString:W,implicitKey:Q,indent:G,indentStep:q,inFlow:H}=w;if(Q&&J.includes(`
31
- `)||H&&/[[\]{},]/.test(J))return dw(J,w);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(J))return Q||H||!J.includes(`
32
- `)?dw(J,w):L2(_,w,$,X);if(!Q&&!H&&Y!==b_.Scalar.PLAIN&&J.includes(`
33
- `))return L2(_,w,$,X);if(K2(J)){if(G==="")return w.forceBlockIndent=!0,L2(_,w,$,X);else if(Q&&G===q)return dw(J,w)}let B=J.replace(/\n+/g,`$&
34
- ${G}`);if(W){let D=(U)=>U.default&&U.tag!=="tag:yaml.org,2002:str"&&U.test?.test(B),{compat:O,tags:z}=w.doc.schema;if(z.some(D)||O?.some(D))return dw(J,w)}return Q?B:s_.foldFlowLines(B,G,s_.FOLD_FLOW,F2(w,!1))}function KJ(_,w,$,X){let{implicitKey:Y,inFlow:J}=w,W=typeof _.value==="string"?_:Object.assign({},_,{value:String(_.value)}),{type:Q}=_;if(Q!==b_.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(W.value))Q=b_.Scalar.QUOTE_DOUBLE}let G=(H)=>{switch(H){case b_.Scalar.BLOCK_FOLDED:case b_.Scalar.BLOCK_LITERAL:return Y||J?dw(W.value,w):L2(W,w,$,X);case b_.Scalar.QUOTE_DOUBLE:return M0(W.value,w);case b_.Scalar.QUOTE_SINGLE:return s1(W.value,w);case b_.Scalar.PLAIN:return FJ(W,w,$,X);default:return null}},q=G(Q);if(q===null){let{defaultKeyType:H,defaultStringType:B}=w.options,D=Y&&H||B;if(q=G(D),q===null)throw Error(`Unsupported default string type ${D}`)}return q}NJ.stringifyString=KJ});var f0=P((IJ)=>{var jJ=A2(),t_=p(),EJ=A0(),SJ=R0();function PJ(_,w){let $=Object.assign({blockQuote:!0,commentString:EJ.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},_.schema.toStringOptions,w),X;switch($.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:_,flowCollectionPadding:$.flowCollectionPadding?" ":"",indent:"",indentStep:typeof $.indent==="number"?" ".repeat($.indent):" ",inFlow:X,options:$}}function ZJ(_,w){if(w.tag){let Y=_.filter((J)=>J.tag===w.tag);if(Y.length>0)return Y.find((J)=>J.format===w.format)??Y[0]}let $=void 0,X;if(t_.isScalar(w)){X=w.value;let Y=_.filter((J)=>J.identify?.(X));if(Y.length>1){let J=Y.filter((W)=>W.test);if(J.length>0)Y=J}$=Y.find((J)=>J.format===w.format)??Y.find((J)=>!J.format)}else X=w,$=_.find((Y)=>Y.nodeClass&&X instanceof Y.nodeClass);if(!$){let Y=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${Y} value`)}return $}function CJ(_,w,{anchors:$,doc:X}){if(!X.directives)return"";let Y=[],J=(t_.isScalar(_)||t_.isCollection(_))&&_.anchor;if(J&&jJ.anchorIsValid(J))$.add(J),Y.push(`&${J}`);let W=_.tag??(w.default?null:w.tag);if(W)Y.push(X.directives.tagString(W));return Y.join(" ")}function TJ(_,w,$,X){if(t_.isPair(_))return _.toString(w,$,X);if(t_.isAlias(_)){if(w.doc.directives)return _.toString(w);if(w.resolvedAliases?.has(_))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(w.resolvedAliases)w.resolvedAliases.add(_);else w.resolvedAliases=new Set([_]);_=_.resolve(w.doc)}}let Y=void 0,J=t_.isNode(_)?_:w.doc.createNode(_,{onTagObj:(G)=>Y=G});Y??(Y=ZJ(w.doc.schema.tags,J));let W=CJ(J,Y,w);if(W.length>0)w.indentAtStart=(w.indentAtStart??0)+W.length+1;let Q=typeof Y.stringify==="function"?Y.stringify(J,w,$,X):t_.isScalar(J)?SJ.stringifyString(J,w,$,X):J.toString(w,$,X);if(!W)return Q;return t_.isScalar(J)||Q[0]==="{"||Q[0]==="["?`${W} ${Q}`:`${W}
35
- ${w.indent}${Q}`}IJ.createStringifyContext=PJ;IJ.stringify=TJ});var i8=P((yJ)=>{var l_=p(),d8=X_(),p8=f0(),L0=A0();function hJ({key:_,value:w},$,X,Y){let{allNullValues:J,doc:W,indent:Q,indentStep:G,options:{commentString:q,indentSeq:H,simpleKeys:B}}=$,D=l_.isNode(_)&&_.comment||null;if(B){if(D)throw Error("With simple keys, key nodes cannot have comments");if(l_.isCollection(_)||!l_.isNode(_)&&typeof _==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!B&&(!_||D&&w==null&&!$.inFlow||l_.isCollection(_)||(l_.isScalar(_)?_.type===d8.Scalar.BLOCK_FOLDED||_.type===d8.Scalar.BLOCK_LITERAL:typeof _==="object"));$=Object.assign({},$,{allNullValues:!1,implicitKey:!O&&(B||!J),indent:Q+G});let z=!1,U=!1,V=p8.stringify(_,$,()=>z=!0,()=>U=!0);if(!O&&!$.inFlow&&V.length>1024){if(B)throw Error("With simple keys, single line scalar must not span more than 1024 characters");O=!0}if($.inFlow){if(J||w==null){if(z&&X)X();return V===""?"?":O?`? ${V}`:V}}else if(J&&!B||w==null&&O){if(V=`? ${V}`,D&&!z)V+=L0.lineComment(V,$.indent,q(D));else if(U&&Y)Y();return V}if(z)D=null;if(O){if(D)V+=L0.lineComment(V,$.indent,q(D));V=`? ${V}
36
- ${Q}:`}else if(V=`${V}:`,D)V+=L0.lineComment(V,$.indent,q(D));let M,f,N;if(l_.isNode(w))M=!!w.spaceBefore,f=w.commentBefore,N=w.comment;else if(M=!1,f=null,N=null,w&&typeof w==="object")w=W.createNode(w);if($.implicitKey=!1,!O&&!D&&l_.isScalar(w))$.indentAtStart=V.length+1;if(U=!1,!H&&G.length>=2&&!$.inFlow&&!O&&l_.isSeq(w)&&!w.flow&&!w.tag&&!w.anchor)$.indent=$.indent.substring(2);let R=!1,b=p8.stringify(w,$,()=>R=!0,()=>U=!0),F=" ";if(D||M||f){if(F=M?`
37
- `:"",f){let T=q(f);F+=`
38
- ${L0.indentComment(T,$.indent)}`}if(b===""&&!$.inFlow){if(F===`
39
- `&&N)F=`
40
-
41
- `}else F+=`
42
- ${$.indent}`}else if(!O&&l_.isCollection(w)){let T=b[0],j=b.indexOf(`
43
- `),C=j!==-1,y=$.inFlow??w.flow??w.items.length===0;if(C||!y){let i=!1;if(C&&(T==="&"||T==="!")){let v=b.indexOf(" ");if(T==="&"&&v!==-1&&v<j&&b[v+1]==="!")v=b.indexOf(" ",v+1);if(v===-1||j<v)i=!0}if(!i)F=`
44
- ${$.indent}`}}else if(b===""||b[0]===`
45
- `)F="";if(V+=F+b,$.inFlow){if(R&&X)X()}else if(N&&!R)V+=L0.lineComment(V,$.indent,q(N));else if(U&&Y)Y();return V}yJ.stringifyPair=hJ});var e1=P((uJ)=>{var n8=$2("process");function xJ(_,...w){if(_==="debug")console.log(...w)}function mJ(_,w){if(_==="debug"||_==="warn")if(typeof n8.emitWarning==="function")n8.emitWarning(w);else console.warn(w)}uJ.debug=xJ;uJ.warn=mJ});var E2=P((pJ)=>{var j2=p(),r8=X_(),N2="<<",b2={identify:(_)=>_===N2||typeof _==="symbol"&&_.description===N2,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new r8.Scalar(Symbol(N2)),{addToJSMap:a8}),stringify:()=>N2},dJ=(_,w)=>(b2.identify(w)||j2.isScalar(w)&&(!w.type||w.type===r8.Scalar.PLAIN)&&b2.identify(w.value))&&_?.doc.schema.tags.some(($)=>$.tag===b2.tag&&$.default);function a8(_,w,$){let X=o8(_,$);if(j2.isSeq(X))for(let Y of X.items)_3(_,w,Y);else if(Array.isArray(X))for(let Y of X)_3(_,w,Y);else _3(_,w,X)}function _3(_,w,$){let X=o8(_,$);if(!j2.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,_,Map);for(let[J,W]of Y)if(w instanceof Map){if(!w.has(J))w.set(J,W)}else if(w instanceof Set)w.add(J);else if(!Object.prototype.hasOwnProperty.call(w,J))Object.defineProperty(w,J,{value:W,writable:!0,enumerable:!0,configurable:!0});return w}function o8(_,w){return _&&j2.isAlias(w)?w.resolve(_.doc,_):w}pJ.addMergeToJSMap=a8;pJ.isMergeKey=dJ;pJ.merge=b2});var $3=P((eJ)=>{var aJ=e1(),s8=E2(),oJ=f0(),t8=p(),w3=o_();function sJ(_,w,{key:$,value:X}){if(t8.isNode($)&&$.addToJSMap)$.addToJSMap(_,w,X);else if(s8.isMergeKey(_,$))s8.addMergeToJSMap(_,w,X);else{let Y=w3.toJS($,"",_);if(w instanceof Map)w.set(Y,w3.toJS(X,Y,_));else if(w instanceof Set)w.add(Y);else{let J=tJ($,Y,_),W=w3.toJS(X,J,_);if(J in w)Object.defineProperty(w,J,{value:W,writable:!0,enumerable:!0,configurable:!0});else w[J]=W}}return w}function tJ(_,w,$){if(w===null)return"";if(typeof w!=="object")return String(w);if(t8.isNode(_)&&$?.doc){let X=oJ.createStringifyContext($.doc,{});X.anchors=new Set;for(let J of $.anchors.keys())X.anchors.add(J.anchor);X.inFlow=!0,X.inStringifyKey=!0;let Y=_.toString(X);if(!$.mapKeyWarned){let J=JSON.stringify(Y);if(J.length>40)J=J.substring(0,36)+'..."';aJ.warn($.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${J}. Set mapAsMap: true to use object keys.`),$.mapKeyWarned=!0}return Y}return JSON.stringify(w)}eJ.addPairToJSMap=sJ});var e_=P((YW)=>{var e8=O0(),wW=i8(),$W=$3(),S2=p();function XW(_,w,$){let X=e8.createNode(_,void 0,$),Y=e8.createNode(w,void 0,$);return new P2(X,Y)}class P2{constructor(_,w=null){Object.defineProperty(this,S2.NODE_TYPE,{value:S2.PAIR}),this.key=_,this.value=w}clone(_){let{key:w,value:$}=this;if(S2.isNode(w))w=w.clone(_);if(S2.isNode($))$=$.clone(_);return new P2(w,$)}toJSON(_,w){let $=w?.mapAsMap?new Map:{};return $W.addPairToJSMap(w,$,this)}toString(_,w,$){return _?.doc?wW.stringifyPair(this,_,w,$):JSON.stringify(this)}}YW.Pair=P2;YW.createPair=XW});var X3=P((HW)=>{var zw=p(),_$=f0(),Z2=A0();function QW(_,w,$){return(w.inFlow??_.flow?qW:GW)(_,w,$)}function GW({comment:_,items:w},$,{blockItemPrefix:X,flowChars:Y,itemIndent:J,onChompKeep:W,onComment:Q}){let{indent:G,options:{commentString:q}}=$,H=Object.assign({},$,{indent:J,type:null}),B=!1,D=[];for(let z=0;z<w.length;++z){let U=w[z],V=null;if(zw.isNode(U)){if(!B&&U.spaceBefore)D.push("");if(C2($,D,U.commentBefore,B),U.comment)V=U.comment}else if(zw.isPair(U)){let f=zw.isNode(U.key)?U.key:null;if(f){if(!B&&f.spaceBefore)D.push("");C2($,D,f.commentBefore,B)}}B=!1;let M=_$.stringify(U,H,()=>V=null,()=>B=!0);if(V)M+=Z2.lineComment(M,J,q(V));if(B&&V)B=!1;D.push(X+M)}let O;if(D.length===0)O=Y.start+Y.end;else{O=D[0];for(let z=1;z<D.length;++z){let U=D[z];O+=U?`
23
+ `;let H,B;for(B=$.length;B>0;--B){let E=$[B-1];if(E!==`
24
+ `&&E!=="\t"&&E!==" ")break}let O=$.substring(B),z=O.indexOf(`
25
+ `);if(z===-1)H="-";else if($===O||z!==O.length-1){if(H="+",J)J()}else H="";if(O){if($=$.slice(0,-O.length),O[O.length-1]===`
26
+ `)O=O.slice(0,-1);O=O.replace(t2,`$&${Q}`)}let U=!1,V,M=-1;for(V=0;V<$.length;++V){let E=$[V];if(E===" ")U=!0;else if(E===`
27
+ `)M=V;else break}let R=$.substring(0,M<V?M+1:V);if(R)$=$.substring(R.length),R=R.replace(/\n+/g,`$&${Q}`);let b=(U?Q?"2":"1":"")+H;if(_){if(b+=" "+W(_.replace(/ ?[\r\n]+/g," ")),Y)Y()}if(!q){let E=$.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${Q}`),f=!1,Z=F1(X,!0);if(D!=="folded"&&w!==b_.Scalar.BLOCK_FOLDED)Z.onOverflow=()=>{f=!0};let L=t_.foldFlowLines(`${R}${E}${O}`,Q,t_.FOLD_BLOCK,Z);if(!f)return`>${b}
29
+ ${Q}${L}`}return $=$.replace(/\n+/g,`$&${Q}`),`|${b}
30
+ ${Q}${R}${$}${O}`}function bJ(_,w,$,X){let{type:Y,value:J}=_,{actualString:D,implicitKey:W,indent:G,indentStep:Q,inFlow:q}=w;if(W&&J.includes(`
31
+ `)||q&&/[[\]{},]/.test(J))return dw(J,w);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(J))return W||q||!J.includes(`
32
+ `)?dw(J,w):L1(_,w,$,X);if(!W&&!q&&Y!==b_.Scalar.PLAIN&&J.includes(`
33
+ `))return L1(_,w,$,X);if(K1(J)){if(G==="")return w.forceBlockIndent=!0,L1(_,w,$,X);else if(W&&G===Q)return dw(J,w)}let H=J.replace(/\n+/g,`$&
34
+ ${G}`);if(D){let B=(U)=>U.default&&U.tag!=="tag:yaml.org,2002:str"&&U.test?.test(H),{compat:O,tags:z}=w.doc.schema;if(z.some(B)||O?.some(B))return dw(J,w)}return W?H:t_.foldFlowLines(H,G,t_.FOLD_FLOW,F1(w,!1))}function jJ(_,w,$,X){let{implicitKey:Y,inFlow:J}=w,D=typeof _.value==="string"?_:Object.assign({},_,{value:String(_.value)}),{type:W}=_;if(W!==b_.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(D.value))W=b_.Scalar.QUOTE_DOUBLE}let G=(q)=>{switch(q){case b_.Scalar.BLOCK_FOLDED:case b_.Scalar.BLOCK_LITERAL:return Y||J?dw(D.value,w):L1(D,w,$,X);case b_.Scalar.QUOTE_DOUBLE:return M0(D.value,w);case b_.Scalar.QUOTE_SINGLE:return s2(D.value,w);case b_.Scalar.PLAIN:return bJ(D,w,$,X);default:return null}},Q=G(W);if(Q===null){let{defaultKeyType:q,defaultStringType:H}=w.options,B=Y&&q||H;if(Q=G(B),Q===null)throw Error(`Unsupported default string type ${B}`)}return Q}EJ.stringifyString=jJ});var f0=P((hJ)=>{var PJ=A1(),e_=p(),ZJ=A0(),CJ=R0();function TJ(_,w){let $=Object.assign({blockQuote:!0,commentString:ZJ.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},_.schema.toStringOptions,w),X;switch($.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:_,flowCollectionPadding:$.flowCollectionPadding?" ":"",indent:"",indentStep:typeof $.indent==="number"?" ".repeat($.indent):" ",inFlow:X,options:$}}function IJ(_,w){if(w.tag){let Y=_.filter((J)=>J.tag===w.tag);if(Y.length>0)return Y.find((J)=>J.format===w.format)??Y[0]}let $=void 0,X;if(e_.isScalar(w)){X=w.value;let Y=_.filter((J)=>J.identify?.(X));if(Y.length>1){let J=Y.filter((D)=>D.test);if(J.length>0)Y=J}$=Y.find((J)=>J.format===w.format)??Y.find((J)=>!J.format)}else X=w,$=_.find((Y)=>Y.nodeClass&&X instanceof Y.nodeClass);if(!$){let Y=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${Y} value`)}return $}function kJ(_,w,{anchors:$,doc:X}){if(!X.directives)return"";let Y=[],J=(e_.isScalar(_)||e_.isCollection(_))&&_.anchor;if(J&&PJ.anchorIsValid(J))$.add(J),Y.push(`&${J}`);let D=_.tag??(w.default?null:w.tag);if(D)Y.push(X.directives.tagString(D));return Y.join(" ")}function gJ(_,w,$,X){if(e_.isPair(_))return _.toString(w,$,X);if(e_.isAlias(_)){if(w.doc.directives)return _.toString(w);if(w.resolvedAliases?.has(_))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(w.resolvedAliases)w.resolvedAliases.add(_);else w.resolvedAliases=new Set([_]);_=_.resolve(w.doc)}}let Y=void 0,J=e_.isNode(_)?_:w.doc.createNode(_,{onTagObj:(G)=>Y=G});Y??(Y=IJ(w.doc.schema.tags,J));let D=kJ(J,Y,w);if(D.length>0)w.indentAtStart=(w.indentAtStart??0)+D.length+1;let W=typeof Y.stringify==="function"?Y.stringify(J,w,$,X):e_.isScalar(J)?CJ.stringifyString(J,w,$,X):J.toString(w,$,X);if(!D)return W;return e_.isScalar(J)||W[0]==="{"||W[0]==="["?`${D} ${W}`:`${D}
35
+ ${w.indent}${W}`}hJ.createStringifyContext=TJ;hJ.stringify=gJ});var a4=P((mJ)=>{var l_=p(),n4=X_(),r4=f0(),L0=A0();function xJ({key:_,value:w},$,X,Y){let{allNullValues:J,doc:D,indent:W,indentStep:G,options:{commentString:Q,indentSeq:q,simpleKeys:H}}=$,B=l_.isNode(_)&&_.comment||null;if(H){if(B)throw Error("With simple keys, key nodes cannot have comments");if(l_.isCollection(_)||!l_.isNode(_)&&typeof _==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!H&&(!_||B&&w==null&&!$.inFlow||l_.isCollection(_)||(l_.isScalar(_)?_.type===n4.Scalar.BLOCK_FOLDED||_.type===n4.Scalar.BLOCK_LITERAL:typeof _==="object"));$=Object.assign({},$,{allNullValues:!1,implicitKey:!O&&(H||!J),indent:W+G});let z=!1,U=!1,V=r4.stringify(_,$,()=>z=!0,()=>U=!0);if(!O&&!$.inFlow&&V.length>1024){if(H)throw Error("With simple keys, single line scalar must not span more than 1024 characters");O=!0}if($.inFlow){if(J||w==null){if(z&&X)X();return V===""?"?":O?`? ${V}`:V}}else if(J&&!H||w==null&&O){if(V=`? ${V}`,B&&!z)V+=L0.lineComment(V,$.indent,Q(B));else if(U&&Y)Y();return V}if(z)B=null;if(O){if(B)V+=L0.lineComment(V,$.indent,Q(B));V=`? ${V}
36
+ ${W}:`}else if(V=`${V}:`,B)V+=L0.lineComment(V,$.indent,Q(B));let M,R,N;if(l_.isNode(w))M=!!w.spaceBefore,R=w.commentBefore,N=w.comment;else if(M=!1,R=null,N=null,w&&typeof w==="object")w=D.createNode(w);if($.implicitKey=!1,!O&&!B&&l_.isScalar(w))$.indentAtStart=V.length+1;if(U=!1,!q&&G.length>=2&&!$.inFlow&&!O&&l_.isSeq(w)&&!w.flow&&!w.tag&&!w.anchor)$.indent=$.indent.substring(2);let b=!1,E=r4.stringify(w,$,()=>b=!0,()=>U=!0),f=" ";if(B||M||R){if(f=M?`
37
+ `:"",R){let Z=Q(R);f+=`
38
+ ${L0.indentComment(Z,$.indent)}`}if(E===""&&!$.inFlow){if(f===`
39
+ `&&N)f=`
40
+
41
+ `}else f+=`
42
+ ${$.indent}`}else if(!O&&l_.isCollection(w)){let Z=E[0],L=E.indexOf(`
43
+ `),C=L!==-1,y=$.inFlow??w.flow??w.items.length===0;if(C||!y){let i=!1;if(C&&(Z==="&"||Z==="!")){let v=E.indexOf(" ");if(Z==="&"&&v!==-1&&v<L&&E[v+1]==="!")v=E.indexOf(" ",v+1);if(v===-1||L<v)i=!0}if(!i)f=`
44
+ ${$.indent}`}}else if(E===""||E[0]===`
45
+ `)f="";if(V+=f+E,$.inFlow){if(b&&X)X()}else if(N&&!b)V+=L0.lineComment(V,$.indent,Q(N));else if(U&&Y)Y();return V}mJ.stringifyPair=xJ});var e2=P((dJ)=>{var o4=$1("process");function lJ(_,...w){if(_==="debug")console.log(...w)}function cJ(_,w){if(_==="debug"||_==="warn")if(typeof o4.emitWarning==="function")o4.emitWarning(w);else console.warn(w)}dJ.debug=lJ;dJ.warn=cJ});var E1=P((rJ)=>{var j1=p(),s4=X_(),N1="<<",b1={identify:(_)=>_===N1||typeof _==="symbol"&&_.description===N1,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new s4.Scalar(Symbol(N1)),{addToJSMap:t4}),stringify:()=>N1},nJ=(_,w)=>(b1.identify(w)||j1.isScalar(w)&&(!w.type||w.type===s4.Scalar.PLAIN)&&b1.identify(w.value))&&_?.doc.schema.tags.some(($)=>$.tag===b1.tag&&$.default);function t4(_,w,$){let X=e4(_,$);if(j1.isSeq(X))for(let Y of X.items)_3(_,w,Y);else if(Array.isArray(X))for(let Y of X)_3(_,w,Y);else _3(_,w,X)}function _3(_,w,$){let X=e4(_,$);if(!j1.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,_,Map);for(let[J,D]of Y)if(w instanceof Map){if(!w.has(J))w.set(J,D)}else if(w instanceof Set)w.add(J);else if(!Object.prototype.hasOwnProperty.call(w,J))Object.defineProperty(w,J,{value:D,writable:!0,enumerable:!0,configurable:!0});return w}function e4(_,w){return _&&j1.isAlias(w)?w.resolve(_.doc,_):w}rJ.addMergeToJSMap=t4;rJ.isMergeKey=nJ;rJ.merge=b1});var $3=P(($D)=>{var tJ=e2(),_8=E1(),eJ=f0(),w8=p(),w3=s_();function _D(_,w,{key:$,value:X}){if(w8.isNode($)&&$.addToJSMap)$.addToJSMap(_,w,X);else if(_8.isMergeKey(_,$))_8.addMergeToJSMap(_,w,X);else{let Y=w3.toJS($,"",_);if(w instanceof Map)w.set(Y,w3.toJS(X,Y,_));else if(w instanceof Set)w.add(Y);else{let J=wD($,Y,_),D=w3.toJS(X,J,_);if(J in w)Object.defineProperty(w,J,{value:D,writable:!0,enumerable:!0,configurable:!0});else w[J]=D}}return w}function wD(_,w,$){if(w===null)return"";if(typeof w!=="object")return String(w);if(w8.isNode(_)&&$?.doc){let X=eJ.createStringifyContext($.doc,{});X.anchors=new Set;for(let J of $.anchors.keys())X.anchors.add(J.anchor);X.inFlow=!0,X.inStringifyKey=!0;let Y=_.toString(X);if(!$.mapKeyWarned){let J=JSON.stringify(Y);if(J.length>40)J=J.substring(0,36)+'..."';tJ.warn($.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${J}. Set mapAsMap: true to use object keys.`),$.mapKeyWarned=!0}return Y}return JSON.stringify(w)}$D.addPairToJSMap=_D});var _w=P((WD)=>{var $8=O0(),YD=a4(),JD=$3(),S1=p();function DD(_,w,$){let X=$8.createNode(_,void 0,$),Y=$8.createNode(w,void 0,$);return new P1(X,Y)}class P1{constructor(_,w=null){Object.defineProperty(this,S1.NODE_TYPE,{value:S1.PAIR}),this.key=_,this.value=w}clone(_){let{key:w,value:$}=this;if(S1.isNode(w))w=w.clone(_);if(S1.isNode($))$=$.clone(_);return new P1(w,$)}toJSON(_,w){let $=w?.mapAsMap?new Map:{};return JD.addPairToJSMap(w,$,this)}toString(_,w,$){return _?.doc?YD.stringifyPair(this,_,w,$):JSON.stringify(this)}}WD.Pair=P1;WD.createPair=DD});var X3=P((UD)=>{var Vw=p(),X8=f0(),Z1=A0();function qD(_,w,$){return(w.inFlow??_.flow?BD:HD)(_,w,$)}function HD({comment:_,items:w},$,{blockItemPrefix:X,flowChars:Y,itemIndent:J,onChompKeep:D,onComment:W}){let{indent:G,options:{commentString:Q}}=$,q=Object.assign({},$,{indent:J,type:null}),H=!1,B=[];for(let z=0;z<w.length;++z){let U=w[z],V=null;if(Vw.isNode(U)){if(!H&&U.spaceBefore)B.push("");if(C1($,B,U.commentBefore,H),U.comment)V=U.comment}else if(Vw.isPair(U)){let R=Vw.isNode(U.key)?U.key:null;if(R){if(!H&&R.spaceBefore)B.push("");C1($,B,R.commentBefore,H)}}H=!1;let M=X8.stringify(U,q,()=>V=null,()=>H=!0);if(V)M+=Z1.lineComment(M,J,Q(V));if(H&&V)H=!1;B.push(X+M)}let O;if(B.length===0)O=Y.start+Y.end;else{O=B[0];for(let z=1;z<B.length;++z){let U=B[z];O+=U?`
46
46
  ${G}${U}`:`
47
47
  `}}if(_){if(O+=`
48
- `+Z2.indentComment(q(_),G),Q)Q()}else if(B&&W)W();return O}function qW({items:_},w,{flowChars:$,itemIndent:X}){let{indent:Y,indentStep:J,flowCollectionPadding:W,options:{commentString:Q}}=w;X+=J;let G=Object.assign({},w,{indent:X,inFlow:!0,type:null}),q=!1,H=0,B=[];for(let z=0;z<_.length;++z){let U=_[z],V=null;if(zw.isNode(U)){if(U.spaceBefore)B.push("");if(C2(w,B,U.commentBefore,!1),U.comment)V=U.comment}else if(zw.isPair(U)){let f=zw.isNode(U.key)?U.key:null;if(f){if(f.spaceBefore)B.push("");if(C2(w,B,f.commentBefore,!1),f.comment)q=!0}let N=zw.isNode(U.value)?U.value:null;if(N){if(N.comment)V=N.comment;if(N.commentBefore)q=!0}else if(U.value==null&&f?.comment)V=f.comment}if(V)q=!0;let M=_$.stringify(U,G,()=>V=null);if(q||(q=B.length>H||M.includes(`
49
- `)),z<_.length-1)M+=",";else if(w.options.trailingComma){if(w.options.lineWidth>0)q||(q=B.reduce((f,N)=>f+N.length+2,2)+(M.length+2)>w.options.lineWidth);if(q)M+=","}if(V)M+=Z2.lineComment(M,X,Q(V));B.push(M),H=B.length}let{start:D,end:O}=$;if(B.length===0)return D+O;else{if(!q){let z=B.reduce((U,V)=>U+V.length+2,2);q=w.options.lineWidth>0&&z>w.options.lineWidth}if(q){let z=D;for(let U of B)z+=U?`
48
+ `+Z1.indentComment(Q(_),G),W)W()}else if(H&&D)D();return O}function BD({items:_},w,{flowChars:$,itemIndent:X}){let{indent:Y,indentStep:J,flowCollectionPadding:D,options:{commentString:W}}=w;X+=J;let G=Object.assign({},w,{indent:X,inFlow:!0,type:null}),Q=!1,q=0,H=[];for(let z=0;z<_.length;++z){let U=_[z],V=null;if(Vw.isNode(U)){if(U.spaceBefore)H.push("");if(C1(w,H,U.commentBefore,!1),U.comment)V=U.comment}else if(Vw.isPair(U)){let R=Vw.isNode(U.key)?U.key:null;if(R){if(R.spaceBefore)H.push("");if(C1(w,H,R.commentBefore,!1),R.comment)Q=!0}let N=Vw.isNode(U.value)?U.value:null;if(N){if(N.comment)V=N.comment;if(N.commentBefore)Q=!0}else if(U.value==null&&R?.comment)V=R.comment}if(V)Q=!0;let M=X8.stringify(U,G,()=>V=null);if(Q||(Q=H.length>q||M.includes(`
49
+ `)),z<_.length-1)M+=",";else if(w.options.trailingComma){if(w.options.lineWidth>0)Q||(Q=H.reduce((R,N)=>R+N.length+2,2)+(M.length+2)>w.options.lineWidth);if(Q)M+=","}if(V)M+=Z1.lineComment(M,X,W(V));H.push(M),q=H.length}let{start:B,end:O}=$;if(H.length===0)return B+O;else{if(!Q){let z=H.reduce((U,V)=>U+V.length+2,2);Q=w.options.lineWidth>0&&z>w.options.lineWidth}if(Q){let z=B;for(let U of H)z+=U?`
50
50
  ${J}${Y}${U}`:`
51
51
  `;return`${z}
52
- ${Y}${O}`}else return`${D}${W}${B.join(" ")}${W}${O}`}}function C2({indent:_,options:{commentString:w}},$,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let J=Z2.indentComment(w(X),_);$.push(J.trimStart())}}HW.stringifyCollection=QW});var ww=P((OW)=>{var BW=X3(),UW=$3(),zW=f2(),_w=p(),T2=e_(),VW=X_();function F0(_,w){let $=_w.isScalar(w)?w.value:w;for(let X of _)if(_w.isPair(X)){if(X.key===w||X.key===$)return X;if(_w.isScalar(X.key)&&X.key.value===$)return X}return}class w$ extends zW.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(_){super(_w.MAP,_);this.items=[]}static from(_,w,$){let{keepUndefined:X,replacer:Y}=$,J=new this(_),W=(Q,G)=>{if(typeof Y==="function")G=Y.call(w,Q,G);else if(Array.isArray(Y)&&!Y.includes(Q))return;if(G!==void 0||X)J.items.push(T2.createPair(Q,G,$))};if(w instanceof Map)for(let[Q,G]of w)W(Q,G);else if(w&&typeof w==="object")for(let Q of Object.keys(w))W(Q,w[Q]);if(typeof _.sortMapEntries==="function")J.items.sort(_.sortMapEntries);return J}add(_,w){let $;if(_w.isPair(_))$=_;else if(!_||typeof _!=="object"||!("key"in _))$=new T2.Pair(_,_?.value);else $=new T2.Pair(_.key,_.value);let X=F0(this.items,$.key),Y=this.schema?.sortMapEntries;if(X){if(!w)throw Error(`Key ${$.key} already set`);if(_w.isScalar(X.value)&&VW.isScalarValue($.value))X.value.value=$.value;else X.value=$.value}else if(Y){let J=this.items.findIndex((W)=>Y($,W)<0);if(J===-1)this.items.push($);else this.items.splice(J,0,$)}else this.items.push($)}delete(_){let w=F0(this.items,_);if(!w)return!1;return this.items.splice(this.items.indexOf(w),1).length>0}get(_,w){let X=F0(this.items,_)?.value;return(!w&&_w.isScalar(X)?X.value:X)??void 0}has(_){return!!F0(this.items,_)}set(_,w){this.add(new T2.Pair(_,w),!0)}toJSON(_,w,$){let X=$?new $:w?.mapAsMap?new Map:{};if(w?.onCreate)w.onCreate(X);for(let Y of this.items)UW.addPairToJSMap(w,X,Y);return X}toString(_,w,$){if(!_)return JSON.stringify(this);for(let X of this.items)if(!_w.isPair(X))throw Error(`Map items must all be pairs; found ${JSON.stringify(X)} instead`);if(!_.allNullValues&&this.hasAllNullValues(!1))_=Object.assign({},_,{allNullValues:!0});return BW.stringifyCollection(this,_,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:_.indent||"",onChompKeep:$,onComment:w})}}OW.YAMLMap=w$;OW.findPair=F0});var pw=P((LW)=>{var RW=p(),$$=ww(),fW={collection:"map",default:!0,nodeClass:$$.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(_,w){if(!RW.isMap(_))w("Expected a mapping for this tag");return _},createNode:(_,w,$)=>$$.YAMLMap.from(_,w,$)};LW.map=fW});var $w=P((SW)=>{var KW=O0(),NW=X3(),bW=f2(),k2=p(),jW=X_(),EW=o_();class X$ extends bW.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(_){super(k2.SEQ,_);this.items=[]}add(_){this.items.push(_)}delete(_){let w=I2(_);if(typeof w!=="number")return!1;return this.items.splice(w,1).length>0}get(_,w){let $=I2(_);if(typeof $!=="number")return;let X=this.items[$];return!w&&k2.isScalar(X)?X.value:X}has(_){let w=I2(_);return typeof w==="number"&&w<this.items.length}set(_,w){let $=I2(_);if(typeof $!=="number")throw Error(`Expected a valid index, not ${_}.`);let X=this.items[$];if(k2.isScalar(X)&&jW.isScalarValue(w))X.value=w;else this.items[$]=w}toJSON(_,w){let $=[];if(w?.onCreate)w.onCreate($);let X=0;for(let Y of this.items)$.push(EW.toJS(Y,String(X++),w));return $}toString(_,w,$){if(!_)return JSON.stringify(this);return NW.stringifyCollection(this,_,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(_.indent||"")+" ",onChompKeep:$,onComment:w})}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w)){let J=0;for(let W of w){if(typeof X==="function"){let Q=w instanceof Set?W:String(J++);W=X.call(w,Q,W)}Y.items.push(KW.createNode(W,void 0,$))}}return Y}}function I2(_){let w=k2.isScalar(_)?_.value:_;if(w&&typeof w==="string")w=Number(w);return typeof w==="number"&&Number.isInteger(w)&&w>=0?w:null}SW.YAMLSeq=X$});var iw=P((TW)=>{var ZW=p(),Y$=$w(),CW={collection:"seq",default:!0,nodeClass:Y$.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(_,w){if(!ZW.isSeq(_))w("Expected a sequence for this tag");return _},createNode:(_,w,$)=>Y$.YAMLSeq.from(_,w,$)};TW.seq=CW});var K0=P((hW)=>{var kW=R0(),gW={identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify(_,w,$,X){return w=Object.assign({actualString:!0},w),kW.stringifyString(_,w,$,X)}};hW.string=gW});var g2=P((vW)=>{var J$=X_(),W$={identify:(_)=>_==null,createNode:()=>new J$.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new J$.Scalar(null),stringify:({source:_},w)=>typeof _==="string"&&W$.test.test(_)?_:w.options.nullStr};vW.nullTag=W$});var Y3=P((uW)=>{var mW=X_(),Q$={identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(_)=>new mW.Scalar(_[0]==="t"||_[0]==="T"),stringify({source:_,value:w},$){if(_&&Q$.test.test(_)){let X=_[0]==="t"||_[0]==="T";if(w===X)return _}return w?$.options.trueStr:$.options.falseStr}};uW.boolTag=Q$});var nw=P((dW)=>{function cW({format:_,minFractionDigits:w,tag:$,value:X}){if(typeof X==="bigint")return String(X);let Y=typeof X==="number"?X:Number(X);if(!isFinite(Y))return isNaN(Y)?".nan":Y<0?"-.inf":".inf";let J=Object.is(X,-0)?"-0":JSON.stringify(X);if(!_&&w&&(!$||$==="tag:yaml.org,2002:float")&&/^-?\d/.test(J)&&!J.includes("e")){let W=J.indexOf(".");if(W<0)W=J.length,J+=".";let Q=w-(J.length-W-1);while(Q-- >0)J+="0"}return J}dW.stringifyNumber=cW});var W3=P((oW)=>{var iW=X_(),J3=nw(),nW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:J3.stringifyNumber},rW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():J3.stringifyNumber(_)}},aW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(_){let w=new iW.Scalar(parseFloat(_)),$=_.indexOf(".");if($!==-1&&_[_.length-1]==="0")w.minFractionDigits=_.length-$-1;return w},stringify:J3.stringifyNumber};oW.float=aW;oW.floatExp=rW;oW.floatNaN=nW});var G3=P((XQ)=>{var G$=nw(),h2=(_)=>typeof _==="bigint"||Number.isInteger(_),Q3=(_,w,$,{intAsBigInt:X})=>X?BigInt(_):parseInt(_.substring(w),$);function q$(_,w,$){let{value:X}=_;if(h2(X)&&X>=0)return $+X.toString(w);return G$.stringifyNumber(_)}var _Q={identify:(_)=>h2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(_,w,$)=>Q3(_,2,8,$),stringify:(_)=>q$(_,8,"0o")},wQ={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(_,w,$)=>Q3(_,0,10,$),stringify:G$.stringifyNumber},$Q={identify:(_)=>h2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(_,w,$)=>Q3(_,2,16,$),stringify:(_)=>q$(_,16,"0x")};XQ.int=wQ;XQ.intHex=$Q;XQ.intOct=_Q});var H$=P((UQ)=>{var QQ=pw(),GQ=g2(),qQ=iw(),HQ=K0(),DQ=Y3(),q3=W3(),H3=G3(),BQ=[QQ.map,qQ.seq,HQ.string,GQ.nullTag,DQ.boolTag,H3.intOct,H3.int,H3.intHex,q3.floatNaN,q3.floatExp,q3.float];UQ.schema=BQ});var B$=P((LQ)=>{var VQ=X_(),OQ=pw(),AQ=iw();function D$(_){return typeof _==="bigint"||Number.isInteger(_)}var y2=({value:_})=>JSON.stringify(_),MQ=[{identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify:y2},{identify:(_)=>_==null,createNode:()=>new VQ.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:y2},{identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(_)=>_==="true",stringify:y2},{identify:D$,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(_,w,{intAsBigInt:$})=>$?BigInt(_):parseInt(_,10),stringify:({value:_})=>D$(_)?_.toString():JSON.stringify(_)},{identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(_)=>parseFloat(_),stringify:y2}],RQ={default:!0,tag:"",test:/^/,resolve(_,w){return w(`Unresolved plain scalar ${JSON.stringify(_)}`),_}},fQ=[OQ.map,AQ.seq].concat(MQ,RQ);LQ.schema=fQ});var B3=P((bQ)=>{var N0=$2("buffer"),D3=X_(),KQ=R0(),NQ={identify:(_)=>_ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(_,w){if(typeof N0.Buffer==="function")return N0.Buffer.from(_,"base64");else if(typeof atob==="function"){let $=atob(_.replace(/[\n\r]/g,"")),X=new Uint8Array($.length);for(let Y=0;Y<$.length;++Y)X[Y]=$.charCodeAt(Y);return X}else return w("This environment does not support reading binary tags; either Buffer or atob is required"),_},stringify({comment:_,type:w,value:$},X,Y,J){if(!$)return"";let W=$,Q;if(typeof N0.Buffer==="function")Q=W instanceof N0.Buffer?W.toString("base64"):N0.Buffer.from(W.buffer).toString("base64");else if(typeof btoa==="function"){let G="";for(let q=0;q<W.length;++q)G+=String.fromCharCode(W[q]);Q=btoa(G)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(w??(w=D3.Scalar.BLOCK_LITERAL),w!==D3.Scalar.QUOTE_DOUBLE){let G=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),q=Math.ceil(Q.length/G),H=Array(q);for(let B=0,D=0;B<q;++B,D+=G)H[B]=Q.substr(D,G);Q=H.join(w===D3.Scalar.BLOCK_LITERAL?`
53
- `:" ")}return KQ.stringifyString({comment:_,type:w,value:Q},X,Y,J)}};bQ.binary=NQ});var x2=P((ZQ)=>{var v2=p(),U3=e_(),EQ=X_(),SQ=$w();function U$(_,w){if(v2.isSeq(_))for(let $=0;$<_.items.length;++$){let X=_.items[$];if(v2.isPair(X))continue;else if(v2.isMap(X)){if(X.items.length>1)w("Each pair must have its own sequence indicator");let Y=X.items[0]||new U3.Pair(new EQ.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
52
+ ${Y}${O}`}else return`${B}${D}${H.join(" ")}${D}${O}`}}function C1({indent:_,options:{commentString:w}},$,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let J=Z1.indentComment(w(X),_);$.push(J.trimStart())}}UD.stringifyCollection=qD});var $w=P((RD)=>{var VD=X3(),OD=$3(),AD=f1(),ww=p(),T1=_w(),MD=X_();function F0(_,w){let $=ww.isScalar(w)?w.value:w;for(let X of _)if(ww.isPair(X)){if(X.key===w||X.key===$)return X;if(ww.isScalar(X.key)&&X.key.value===$)return X}return}class Y8 extends AD.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(_){super(ww.MAP,_);this.items=[]}static from(_,w,$){let{keepUndefined:X,replacer:Y}=$,J=new this(_),D=(W,G)=>{if(typeof Y==="function")G=Y.call(w,W,G);else if(Array.isArray(Y)&&!Y.includes(W))return;if(G!==void 0||X)J.items.push(T1.createPair(W,G,$))};if(w instanceof Map)for(let[W,G]of w)D(W,G);else if(w&&typeof w==="object")for(let W of Object.keys(w))D(W,w[W]);if(typeof _.sortMapEntries==="function")J.items.sort(_.sortMapEntries);return J}add(_,w){let $;if(ww.isPair(_))$=_;else if(!_||typeof _!=="object"||!("key"in _))$=new T1.Pair(_,_?.value);else $=new T1.Pair(_.key,_.value);let X=F0(this.items,$.key),Y=this.schema?.sortMapEntries;if(X){if(!w)throw Error(`Key ${$.key} already set`);if(ww.isScalar(X.value)&&MD.isScalarValue($.value))X.value.value=$.value;else X.value=$.value}else if(Y){let J=this.items.findIndex((D)=>Y($,D)<0);if(J===-1)this.items.push($);else this.items.splice(J,0,$)}else this.items.push($)}delete(_){let w=F0(this.items,_);if(!w)return!1;return this.items.splice(this.items.indexOf(w),1).length>0}get(_,w){let X=F0(this.items,_)?.value;return(!w&&ww.isScalar(X)?X.value:X)??void 0}has(_){return!!F0(this.items,_)}set(_,w){this.add(new T1.Pair(_,w),!0)}toJSON(_,w,$){let X=$?new $:w?.mapAsMap?new Map:{};if(w?.onCreate)w.onCreate(X);for(let Y of this.items)OD.addPairToJSMap(w,X,Y);return X}toString(_,w,$){if(!_)return JSON.stringify(this);for(let X of this.items)if(!ww.isPair(X))throw Error(`Map items must all be pairs; found ${JSON.stringify(X)} instead`);if(!_.allNullValues&&this.hasAllNullValues(!1))_=Object.assign({},_,{allNullValues:!0});return VD.stringifyCollection(this,_,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:_.indent||"",onChompKeep:$,onComment:w})}}RD.YAMLMap=Y8;RD.findPair=F0});var pw=P((ND)=>{var FD=p(),J8=$w(),KD={collection:"map",default:!0,nodeClass:J8.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(_,w){if(!FD.isMap(_))w("Expected a mapping for this tag");return _},createNode:(_,w,$)=>J8.YAMLMap.from(_,w,$)};ND.map=KD});var Xw=P((CD)=>{var jD=O0(),ED=X3(),SD=f1(),k1=p(),PD=X_(),ZD=s_();class D8 extends SD.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(_){super(k1.SEQ,_);this.items=[]}add(_){this.items.push(_)}delete(_){let w=I1(_);if(typeof w!=="number")return!1;return this.items.splice(w,1).length>0}get(_,w){let $=I1(_);if(typeof $!=="number")return;let X=this.items[$];return!w&&k1.isScalar(X)?X.value:X}has(_){let w=I1(_);return typeof w==="number"&&w<this.items.length}set(_,w){let $=I1(_);if(typeof $!=="number")throw Error(`Expected a valid index, not ${_}.`);let X=this.items[$];if(k1.isScalar(X)&&PD.isScalarValue(w))X.value=w;else this.items[$]=w}toJSON(_,w){let $=[];if(w?.onCreate)w.onCreate($);let X=0;for(let Y of this.items)$.push(ZD.toJS(Y,String(X++),w));return $}toString(_,w,$){if(!_)return JSON.stringify(this);return ED.stringifyCollection(this,_,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(_.indent||"")+" ",onChompKeep:$,onComment:w})}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w)){let J=0;for(let D of w){if(typeof X==="function"){let W=w instanceof Set?D:String(J++);D=X.call(w,W,D)}Y.items.push(jD.createNode(D,void 0,$))}}return Y}}function I1(_){let w=k1.isScalar(_)?_.value:_;if(w&&typeof w==="string")w=Number(w);return typeof w==="number"&&Number.isInteger(w)&&w>=0?w:null}CD.YAMLSeq=D8});var iw=P((gD)=>{var ID=p(),W8=Xw(),kD={collection:"seq",default:!0,nodeClass:W8.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(_,w){if(!ID.isSeq(_))w("Expected a sequence for this tag");return _},createNode:(_,w,$)=>W8.YAMLSeq.from(_,w,$)};gD.seq=kD});var K0=P((xD)=>{var yD=R0(),vD={identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify(_,w,$,X){return w=Object.assign({actualString:!0},w),yD.stringifyString(_,w,$,X)}};xD.string=vD});var g1=P((uD)=>{var G8=X_(),Q8={identify:(_)=>_==null,createNode:()=>new G8.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new G8.Scalar(null),stringify:({source:_},w)=>typeof _==="string"&&Q8.test.test(_)?_:w.options.nullStr};uD.nullTag=Q8});var Y3=P((dD)=>{var cD=X_(),q8={identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(_)=>new cD.Scalar(_[0]==="t"||_[0]==="T"),stringify({source:_,value:w},$){if(_&&q8.test.test(_)){let X=_[0]==="t"||_[0]==="T";if(w===X)return _}return w?$.options.trueStr:$.options.falseStr}};dD.boolTag=q8});var nw=P((nD)=>{function iD({format:_,minFractionDigits:w,tag:$,value:X}){if(typeof X==="bigint")return String(X);let Y=typeof X==="number"?X:Number(X);if(!isFinite(Y))return isNaN(Y)?".nan":Y<0?"-.inf":".inf";let J=Object.is(X,-0)?"-0":JSON.stringify(X);if(!_&&w&&(!$||$==="tag:yaml.org,2002:float")&&/^-?\d/.test(J)&&!J.includes("e")){let D=J.indexOf(".");if(D<0)D=J.length,J+=".";let W=w-(J.length-D-1);while(W-- >0)J+="0"}return J}nD.stringifyNumber=iD});var D3=P((eD)=>{var aD=X_(),J3=nw(),oD={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:J3.stringifyNumber},sD={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():J3.stringifyNumber(_)}},tD={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(_){let w=new aD.Scalar(parseFloat(_)),$=_.indexOf(".");if($!==-1&&_[_.length-1]==="0")w.minFractionDigits=_.length-$-1;return w},stringify:J3.stringifyNumber};eD.float=tD;eD.floatExp=sD;eD.floatNaN=oD});var G3=P((DW)=>{var H8=nw(),h1=(_)=>typeof _==="bigint"||Number.isInteger(_),W3=(_,w,$,{intAsBigInt:X})=>X?BigInt(_):parseInt(_.substring(w),$);function B8(_,w,$){let{value:X}=_;if(h1(X)&&X>=0)return $+X.toString(w);return H8.stringifyNumber(_)}var XW={identify:(_)=>h1(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(_,w,$)=>W3(_,2,8,$),stringify:(_)=>B8(_,8,"0o")},YW={identify:h1,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(_,w,$)=>W3(_,0,10,$),stringify:H8.stringifyNumber},JW={identify:(_)=>h1(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(_,w,$)=>W3(_,2,16,$),stringify:(_)=>B8(_,16,"0x")};DW.int=YW;DW.intHex=JW;DW.intOct=XW});var U8=P((OW)=>{var qW=pw(),HW=g1(),BW=iw(),UW=K0(),zW=Y3(),Q3=D3(),q3=G3(),VW=[qW.map,BW.seq,UW.string,HW.nullTag,zW.boolTag,q3.intOct,q3.int,q3.intHex,Q3.floatNaN,Q3.floatExp,Q3.float];OW.schema=VW});var V8=P((NW)=>{var MW=X_(),RW=pw(),fW=iw();function z8(_){return typeof _==="bigint"||Number.isInteger(_)}var y1=({value:_})=>JSON.stringify(_),LW=[{identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify:y1},{identify:(_)=>_==null,createNode:()=>new MW.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:y1},{identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(_)=>_==="true",stringify:y1},{identify:z8,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(_,w,{intAsBigInt:$})=>$?BigInt(_):parseInt(_,10),stringify:({value:_})=>z8(_)?_.toString():JSON.stringify(_)},{identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:(_)=>parseFloat(_),stringify:y1}],FW={default:!0,tag:"",test:/^/,resolve(_,w){return w(`Unresolved plain scalar ${JSON.stringify(_)}`),_}},KW=[RW.map,fW.seq].concat(LW,FW);NW.schema=KW});var B3=P((SW)=>{var N0=$1("buffer"),H3=X_(),jW=R0(),EW={identify:(_)=>_ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(_,w){if(typeof N0.Buffer==="function")return N0.Buffer.from(_,"base64");else if(typeof atob==="function"){let $=atob(_.replace(/[\n\r]/g,"")),X=new Uint8Array($.length);for(let Y=0;Y<$.length;++Y)X[Y]=$.charCodeAt(Y);return X}else return w("This environment does not support reading binary tags; either Buffer or atob is required"),_},stringify({comment:_,type:w,value:$},X,Y,J){if(!$)return"";let D=$,W;if(typeof N0.Buffer==="function")W=D instanceof N0.Buffer?D.toString("base64"):N0.Buffer.from(D.buffer).toString("base64");else if(typeof btoa==="function"){let G="";for(let Q=0;Q<D.length;++Q)G+=String.fromCharCode(D[Q]);W=btoa(G)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(w??(w=H3.Scalar.BLOCK_LITERAL),w!==H3.Scalar.QUOTE_DOUBLE){let G=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),Q=Math.ceil(W.length/G),q=Array(Q);for(let H=0,B=0;H<Q;++H,B+=G)q[H]=W.substr(B,G);W=q.join(w===H3.Scalar.BLOCK_LITERAL?`
53
+ `:" ")}return jW.stringifyString({comment:_,type:w,value:W},X,Y,J)}};SW.binary=EW});var x1=P((IW)=>{var v1=p(),U3=_w(),ZW=X_(),CW=Xw();function O8(_,w){if(v1.isSeq(_))for(let $=0;$<_.items.length;++$){let X=_.items[$];if(v1.isPair(X))continue;else if(v1.isMap(X)){if(X.items.length>1)w("Each pair must have its own sequence indicator");let Y=X.items[0]||new U3.Pair(new ZW.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
54
54
  ${Y.key.commentBefore}`:X.commentBefore;if(X.comment){let J=Y.value??Y.key;J.comment=J.comment?`${X.comment}
55
- ${J.comment}`:X.comment}X=Y}_.items[$]=v2.isPair(X)?X:new U3.Pair(X)}else w("Expected a sequence for this tag");return _}function z$(_,w,$){let{replacer:X}=$,Y=new SQ.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let W of w){if(typeof X==="function")W=X.call(w,String(J++),W);let Q,G;if(Array.isArray(W))if(W.length===2)Q=W[0],G=W[1];else throw TypeError(`Expected [key, value] tuple: ${W}`);else if(W&&W instanceof Object){let q=Object.keys(W);if(q.length===1)Q=q[0],G=W[Q];else throw TypeError(`Expected tuple with one key, not ${q.length} keys`)}else Q=W;Y.items.push(U3.createPair(Q,G,$))}return Y}var PQ={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:U$,createNode:z$};ZQ.createPairs=z$;ZQ.pairs=PQ;ZQ.resolvePairs=U$});var V3=P((hQ)=>{var V$=p(),z3=o_(),b0=ww(),kQ=$w(),O$=x2();class Vw extends kQ.YAMLSeq{constructor(){super();this.add=b0.YAMLMap.prototype.add.bind(this),this.delete=b0.YAMLMap.prototype.delete.bind(this),this.get=b0.YAMLMap.prototype.get.bind(this),this.has=b0.YAMLMap.prototype.has.bind(this),this.set=b0.YAMLMap.prototype.set.bind(this),this.tag=Vw.tag}toJSON(_,w){if(!w)return super.toJSON(_);let $=new Map;if(w?.onCreate)w.onCreate($);for(let X of this.items){let Y,J;if(V$.isPair(X))Y=z3.toJS(X.key,"",w),J=z3.toJS(X.value,Y,w);else Y=z3.toJS(X,"",w);if($.has(Y))throw Error("Ordered maps must not include duplicate keys");$.set(Y,J)}return $}static from(_,w,$){let X=O$.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Vw.tag="tag:yaml.org,2002:omap";var gQ={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Vw,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=O$.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(V$.isScalar(Y))if(X.includes(Y.value))w(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new Vw,$)},createNode:(_,w,$)=>Vw.from(_,w,$)};hQ.YAMLOMap=Vw;hQ.omap=gQ});var L$=P((xQ)=>{var A$=X_();function M$({value:_,source:w},$){if(w&&(_?R$:f$).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var R$={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new A$.Scalar(!0),stringify:M$},f$={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new A$.Scalar(!1),stringify:M$};xQ.falseTag=f$;xQ.trueTag=R$});var F$=P((iQ)=>{var lQ=X_(),O3=nw(),cQ={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:O3.stringifyNumber},dQ={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_.replace(/_/g,"")),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():O3.stringifyNumber(_)}},pQ={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new lQ.Scalar(parseFloat(_.replace(/_/g,""))),$=_.indexOf(".");if($!==-1){let X=_.substring($+1).replace(/_/g,"");if(X[X.length-1]==="0")w.minFractionDigits=X.length}return w},stringify:O3.stringifyNumber};iQ.float=pQ;iQ.floatExp=dQ;iQ.floatNaN=cQ});var N$=P((_G)=>{var K$=nw(),j0=(_)=>typeof _==="bigint"||Number.isInteger(_);function m2(_,w,$,{intAsBigInt:X}){let Y=_[0];if(Y==="-"||Y==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let W=BigInt(_);return Y==="-"?BigInt(-1)*W:W}let J=parseInt(_,$);return Y==="-"?-1*J:J}function A3(_,w,$){let{value:X}=_;if(j0(X)){let Y=X.toString(w);return X<0?"-"+$+Y.substr(1):$+Y}return K$.stringifyNumber(_)}var oQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>m2(_,2,2,$),stringify:(_)=>A3(_,2,"0b")},sQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>m2(_,1,8,$),stringify:(_)=>A3(_,8,"0")},tQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>m2(_,0,10,$),stringify:K$.stringifyNumber},eQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>m2(_,2,16,$),stringify:(_)=>A3(_,16,"0x")};_G.int=tQ;_G.intBin=oQ;_G.intHex=eQ;_G.intOct=sQ});var M3=P((WG)=>{var c2=p(),u2=e_(),l2=ww();class Ow extends l2.YAMLMap{constructor(_){super(_);this.tag=Ow.tag}add(_){let w;if(c2.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new u2.Pair(_.key,null);else w=new u2.Pair(_,null);if(!l2.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=l2.findPair(this.items,_);return!w&&c2.isPair($)?c2.isScalar($.key)?$.key.value:$.key:$}set(_,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let $=l2.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new u2.Pair(_))}toJSON(_,w){return super.toJSON(_,w,Set)}toString(_,w,$){if(!_)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},_,{allNullValues:!0}),w,$);else throw Error("Set items must all have null values")}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof X==="function")J=X.call(w,J,J);Y.items.push(u2.createPair(J,null,$))}return Y}}Ow.tag="tag:yaml.org,2002:set";var JG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Ow,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Ow.from(_,w,$),resolve(_,w){if(c2.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Ow,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};WG.YAMLSet=Ow;WG.set=JG});var f3=P((BG)=>{var qG=nw();function R3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(W)=>w?BigInt(W):Number(W),J=X.replace(/_/g,"").split(":").reduce((W,Q)=>W*Y(60)+Y(Q),Y(0));return $==="-"?Y(-1)*J:J}function b$(_){let{value:w}=_,$=(W)=>W;if(typeof w==="bigint")$=(W)=>BigInt(W);else if(isNaN(w)||!isFinite(w))return qG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let Y=$(60),J=[w%Y];if(w<60)J.unshift(0);else if(w=(w-J[0])/Y,J.unshift(w%Y),w>=60)w=(w-J[0])/Y,J.unshift(w);return X+J.map((W)=>String(W).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var HG={identify:(_)=>typeof _==="bigint"||Number.isInteger(_),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(_,w,{intAsBigInt:$})=>R3(_,$),stringify:b$},DG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(_)=>R3(_,!1),stringify:b$},j$={identify:(_)=>_ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(_){let w=_.match(j$.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,W,Q]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,q=Date.UTC($,X-1,Y,J||0,W||0,Q||0,G),H=w[8];if(H&&H!=="Z"){let B=R3(H,!1);if(Math.abs(B)<30)B*=60;q-=60000*B}return new Date(q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};BG.floatTime=DG;BG.intTime=HG;BG.timestamp=j$});var S$=P((jG)=>{var OG=pw(),AG=g2(),MG=iw(),RG=K0(),fG=B3(),E$=L$(),L3=F$(),d2=N$(),LG=E2(),FG=V3(),KG=x2(),NG=M3(),F3=f3(),bG=[OG.map,MG.seq,RG.string,AG.nullTag,E$.trueTag,E$.falseTag,d2.intBin,d2.intOct,d2.int,d2.intHex,L3.floatNaN,L3.floatExp,L3.float,fG.binary,LG.merge,FG.omap,KG.pairs,NG.set,F3.intTime,F3.floatTime,F3.timestamp];jG.schema=bG});var v$=P((gG)=>{var T$=pw(),SG=g2(),I$=iw(),PG=K0(),ZG=Y3(),K3=W3(),N3=G3(),CG=H$(),TG=B$(),k$=B3(),E0=E2(),g$=V3(),h$=x2(),P$=S$(),y$=M3(),p2=f3(),Z$=new Map([["core",CG.schema],["failsafe",[T$.map,I$.seq,PG.string]],["json",TG.schema],["yaml11",P$.schema],["yaml-1.1",P$.schema]]),C$={binary:k$.binary,bool:ZG.boolTag,float:K3.float,floatExp:K3.floatExp,floatNaN:K3.floatNaN,floatTime:p2.floatTime,int:N3.int,intHex:N3.intHex,intOct:N3.intOct,intTime:p2.intTime,map:T$.map,merge:E0.merge,null:SG.nullTag,omap:g$.omap,pairs:h$.pairs,seq:I$.seq,set:y$.set,timestamp:p2.timestamp},IG={"tag:yaml.org,2002:binary":k$.binary,"tag:yaml.org,2002:merge":E0.merge,"tag:yaml.org,2002:omap":g$.omap,"tag:yaml.org,2002:pairs":h$.pairs,"tag:yaml.org,2002:set":y$.set,"tag:yaml.org,2002:timestamp":p2.timestamp};function kG(_,w,$){let X=Z$.get(w);if(X&&!_)return $&&!X.includes(E0.merge)?X.concat(E0.merge):X.slice();let Y=X;if(!Y)if(Array.isArray(_))Y=[];else{let J=Array.from(Z$.keys()).filter((W)=>W!=="yaml11").map((W)=>JSON.stringify(W)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${J} or define customTags array`)}if(Array.isArray(_))for(let J of _)Y=Y.concat(J);else if(typeof _==="function")Y=_(Y.slice());if($)Y=Y.concat(E0.merge);return Y.reduce((J,W)=>{let Q=typeof W==="string"?C$[W]:W;if(!Q){let G=JSON.stringify(W),q=Object.keys(C$).map((H)=>JSON.stringify(H)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${q}`)}if(!J.includes(Q))J.push(Q);return J},[])}gG.coreKnownTags=IG;gG.getTags=kG});var E3=P((lG)=>{var b3=p(),vG=pw(),xG=iw(),mG=K0(),i2=v$(),uG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class j3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:W}){this.compat=Array.isArray(_)?i2.getTags(_,"compat"):_?i2.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?i2.coreKnownTags:{},this.tags=i2.getTags(w,this.name,$),this.toStringOptions=W??null,Object.defineProperty(this,b3.MAP,{value:vG.map}),Object.defineProperty(this,b3.SCALAR,{value:mG.string}),Object.defineProperty(this,b3.SEQ,{value:xG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?uG:null}clone(){let _=Object.create(j3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}lG.Schema=j3});var x$=P((iG)=>{var dG=p(),S3=f0(),S0=A0();function pG(_,w){let $=[],X=w.directives===!0;if(w.directives!==!1&&_.directives){let G=_.directives.toString(_);if(G)$.push(G),X=!0;else if(_.directives.docStart)X=!0}if(X)$.push("---");let Y=S3.createStringifyContext(_,w),{commentString:J}=Y.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=J(_.commentBefore);$.unshift(S0.indentComment(G,""))}let W=!1,Q=null;if(_.contents){if(dG.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let H=J(_.contents.commentBefore);$.push(S0.indentComment(H,""))}Y.forceBlockIndent=!!_.comment,Q=_.contents.comment}let G=Q?void 0:()=>W=!0,q=S3.stringify(_.contents,Y,()=>Q=null,G);if(Q)q+=S0.lineComment(q,"",J(Q));if((q[0]==="|"||q[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${q}`;else $.push(q)}else $.push(S3.stringify(_.contents,Y));if(_.directives?.docEnd)if(_.comment){let G=J(_.comment);if(G.includes(`
56
- `))$.push("..."),$.push(S0.indentComment(G,""));else $.push(`... ${G}`)}else $.push("...");else{let G=_.comment;if(G&&W)G=G.replace(/^\n+/,"");if(G){if((!W||Q)&&$[$.length-1]!=="")$.push("");$.push(S0.indentComment(J(G),""))}}return $.join(`
55
+ ${J.comment}`:X.comment}X=Y}_.items[$]=v1.isPair(X)?X:new U3.Pair(X)}else w("Expected a sequence for this tag");return _}function A8(_,w,$){let{replacer:X}=$,Y=new CW.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let D of w){if(typeof X==="function")D=X.call(w,String(J++),D);let W,G;if(Array.isArray(D))if(D.length===2)W=D[0],G=D[1];else throw TypeError(`Expected [key, value] tuple: ${D}`);else if(D&&D instanceof Object){let Q=Object.keys(D);if(Q.length===1)W=Q[0],G=D[W];else throw TypeError(`Expected tuple with one key, not ${Q.length} keys`)}else W=D;Y.items.push(U3.createPair(W,G,$))}return Y}var TW={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:O8,createNode:A8};IW.createPairs=A8;IW.pairs=TW;IW.resolvePairs=O8});var V3=P((xW)=>{var M8=p(),z3=s_(),b0=$w(),yW=Xw(),R8=x1();class Ow extends yW.YAMLSeq{constructor(){super();this.add=b0.YAMLMap.prototype.add.bind(this),this.delete=b0.YAMLMap.prototype.delete.bind(this),this.get=b0.YAMLMap.prototype.get.bind(this),this.has=b0.YAMLMap.prototype.has.bind(this),this.set=b0.YAMLMap.prototype.set.bind(this),this.tag=Ow.tag}toJSON(_,w){if(!w)return super.toJSON(_);let $=new Map;if(w?.onCreate)w.onCreate($);for(let X of this.items){let Y,J;if(M8.isPair(X))Y=z3.toJS(X.key,"",w),J=z3.toJS(X.value,Y,w);else Y=z3.toJS(X,"",w);if($.has(Y))throw Error("Ordered maps must not include duplicate keys");$.set(Y,J)}return $}static from(_,w,$){let X=R8.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Ow.tag="tag:yaml.org,2002:omap";var vW={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Ow,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=R8.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(M8.isScalar(Y))if(X.includes(Y.value))w(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new Ow,$)},createNode:(_,w,$)=>Ow.from(_,w,$)};xW.YAMLOMap=Ow;xW.omap=vW});var N8=P((lW)=>{var f8=X_();function L8({value:_,source:w},$){if(w&&(_?F8:K8).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var F8={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new f8.Scalar(!0),stringify:L8},K8={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new f8.Scalar(!1),stringify:L8};lW.falseTag=K8;lW.trueTag=F8});var b8=P((aW)=>{var pW=X_(),O3=nw(),iW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:O3.stringifyNumber},nW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_.replace(/_/g,"")),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():O3.stringifyNumber(_)}},rW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new pW.Scalar(parseFloat(_.replace(/_/g,""))),$=_.indexOf(".");if($!==-1){let X=_.substring($+1).replace(/_/g,"");if(X[X.length-1]==="0")w.minFractionDigits=X.length}return w},stringify:O3.stringifyNumber};aW.float=rW;aW.floatExp=nW;aW.floatNaN=iW});var E8=P((XG)=>{var j8=nw(),j0=(_)=>typeof _==="bigint"||Number.isInteger(_);function m1(_,w,$,{intAsBigInt:X}){let Y=_[0];if(Y==="-"||Y==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let D=BigInt(_);return Y==="-"?BigInt(-1)*D:D}let J=parseInt(_,$);return Y==="-"?-1*J:J}function A3(_,w,$){let{value:X}=_;if(j0(X)){let Y=X.toString(w);return X<0?"-"+$+Y.substr(1):$+Y}return j8.stringifyNumber(_)}var eW={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>m1(_,2,2,$),stringify:(_)=>A3(_,2,"0b")},_G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>m1(_,1,8,$),stringify:(_)=>A3(_,8,"0")},wG={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>m1(_,0,10,$),stringify:j8.stringifyNumber},$G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>m1(_,2,16,$),stringify:(_)=>A3(_,16,"0x")};XG.int=wG;XG.intBin=eW;XG.intHex=$G;XG.intOct=_G});var M3=P((QG)=>{var c1=p(),u1=_w(),l1=$w();class Aw extends l1.YAMLMap{constructor(_){super(_);this.tag=Aw.tag}add(_){let w;if(c1.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new u1.Pair(_.key,null);else w=new u1.Pair(_,null);if(!l1.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=l1.findPair(this.items,_);return!w&&c1.isPair($)?c1.isScalar($.key)?$.key.value:$.key:$}set(_,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let $=l1.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new u1.Pair(_))}toJSON(_,w){return super.toJSON(_,w,Set)}toString(_,w,$){if(!_)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},_,{allNullValues:!0}),w,$);else throw Error("Set items must all have null values")}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof X==="function")J=X.call(w,J,J);Y.items.push(u1.createPair(J,null,$))}return Y}}Aw.tag="tag:yaml.org,2002:set";var GG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Aw,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Aw.from(_,w,$),resolve(_,w){if(c1.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Aw,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};QG.YAMLSet=Aw;QG.set=GG});var f3=P((VG)=>{var BG=nw();function R3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(D)=>w?BigInt(D):Number(D),J=X.replace(/_/g,"").split(":").reduce((D,W)=>D*Y(60)+Y(W),Y(0));return $==="-"?Y(-1)*J:J}function S8(_){let{value:w}=_,$=(D)=>D;if(typeof w==="bigint")$=(D)=>BigInt(D);else if(isNaN(w)||!isFinite(w))return BG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let Y=$(60),J=[w%Y];if(w<60)J.unshift(0);else if(w=(w-J[0])/Y,J.unshift(w%Y),w>=60)w=(w-J[0])/Y,J.unshift(w);return X+J.map((D)=>String(D).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var UG={identify:(_)=>typeof _==="bigint"||Number.isInteger(_),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(_,w,{intAsBigInt:$})=>R3(_,$),stringify:S8},zG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(_)=>R3(_,!1),stringify:S8},P8={identify:(_)=>_ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(_){let w=_.match(P8.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,D,W]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,Q=Date.UTC($,X-1,Y,J||0,D||0,W||0,G),q=w[8];if(q&&q!=="Z"){let H=R3(q,!1);if(Math.abs(H)<30)H*=60;Q-=60000*H}return new Date(Q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};VG.floatTime=zG;VG.intTime=UG;VG.timestamp=P8});var C8=P((PG)=>{var RG=pw(),fG=g1(),LG=iw(),FG=K0(),KG=B3(),Z8=N8(),L3=b8(),d1=E8(),NG=E1(),bG=V3(),jG=x1(),EG=M3(),F3=f3(),SG=[RG.map,LG.seq,FG.string,fG.nullTag,Z8.trueTag,Z8.falseTag,d1.intBin,d1.intOct,d1.int,d1.intHex,L3.floatNaN,L3.floatExp,L3.float,KG.binary,NG.merge,bG.omap,jG.pairs,EG.set,F3.intTime,F3.floatTime,F3.timestamp];PG.schema=SG});var u8=P((vG)=>{var g8=pw(),CG=g1(),h8=iw(),TG=K0(),IG=Y3(),K3=D3(),N3=G3(),kG=U8(),gG=V8(),y8=B3(),E0=E1(),v8=V3(),x8=x1(),T8=C8(),m8=M3(),p1=f3(),I8=new Map([["core",kG.schema],["failsafe",[g8.map,h8.seq,TG.string]],["json",gG.schema],["yaml11",T8.schema],["yaml-1.1",T8.schema]]),k8={binary:y8.binary,bool:IG.boolTag,float:K3.float,floatExp:K3.floatExp,floatNaN:K3.floatNaN,floatTime:p1.floatTime,int:N3.int,intHex:N3.intHex,intOct:N3.intOct,intTime:p1.intTime,map:g8.map,merge:E0.merge,null:CG.nullTag,omap:v8.omap,pairs:x8.pairs,seq:h8.seq,set:m8.set,timestamp:p1.timestamp},hG={"tag:yaml.org,2002:binary":y8.binary,"tag:yaml.org,2002:merge":E0.merge,"tag:yaml.org,2002:omap":v8.omap,"tag:yaml.org,2002:pairs":x8.pairs,"tag:yaml.org,2002:set":m8.set,"tag:yaml.org,2002:timestamp":p1.timestamp};function yG(_,w,$){let X=I8.get(w);if(X&&!_)return $&&!X.includes(E0.merge)?X.concat(E0.merge):X.slice();let Y=X;if(!Y)if(Array.isArray(_))Y=[];else{let J=Array.from(I8.keys()).filter((D)=>D!=="yaml11").map((D)=>JSON.stringify(D)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${J} or define customTags array`)}if(Array.isArray(_))for(let J of _)Y=Y.concat(J);else if(typeof _==="function")Y=_(Y.slice());if($)Y=Y.concat(E0.merge);return Y.reduce((J,D)=>{let W=typeof D==="string"?k8[D]:D;if(!W){let G=JSON.stringify(D),Q=Object.keys(k8).map((q)=>JSON.stringify(q)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${Q}`)}if(!J.includes(W))J.push(W);return J},[])}vG.coreKnownTags=hG;vG.getTags=yG});var E3=P((pG)=>{var b3=p(),uG=pw(),lG=iw(),cG=K0(),i1=u8(),dG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class j3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:D}){this.compat=Array.isArray(_)?i1.getTags(_,"compat"):_?i1.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?i1.coreKnownTags:{},this.tags=i1.getTags(w,this.name,$),this.toStringOptions=D??null,Object.defineProperty(this,b3.MAP,{value:uG.map}),Object.defineProperty(this,b3.SCALAR,{value:cG.string}),Object.defineProperty(this,b3.SEQ,{value:lG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?dG:null}clone(){let _=Object.create(j3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}pG.Schema=j3});var l8=P((aG)=>{var nG=p(),S3=f0(),S0=A0();function rG(_,w){let $=[],X=w.directives===!0;if(w.directives!==!1&&_.directives){let G=_.directives.toString(_);if(G)$.push(G),X=!0;else if(_.directives.docStart)X=!0}if(X)$.push("---");let Y=S3.createStringifyContext(_,w),{commentString:J}=Y.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=J(_.commentBefore);$.unshift(S0.indentComment(G,""))}let D=!1,W=null;if(_.contents){if(nG.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let q=J(_.contents.commentBefore);$.push(S0.indentComment(q,""))}Y.forceBlockIndent=!!_.comment,W=_.contents.comment}let G=W?void 0:()=>D=!0,Q=S3.stringify(_.contents,Y,()=>W=null,G);if(W)Q+=S0.lineComment(Q,"",J(W));if((Q[0]==="|"||Q[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${Q}`;else $.push(Q)}else $.push(S3.stringify(_.contents,Y));if(_.directives?.docEnd)if(_.comment){let G=J(_.comment);if(G.includes(`
56
+ `))$.push("..."),$.push(S0.indentComment(G,""));else $.push(`... ${G}`)}else $.push("...");else{let G=_.comment;if(G&&D)G=G.replace(/^\n+/,"");if(G){if((!D||W)&&$[$.length-1]!=="")$.push("");$.push(S0.indentComment(J(G),""))}}return $.join(`
57
57
  `)+`
58
- `}iG.stringifyDocument=pG});var P0=P((wq)=>{var rG=V0(),rw=f2(),A_=p(),aG=e_(),oG=o_(),sG=E3(),tG=x$(),P3=A2(),eG=r1(),_q=O0(),Z3=n1();class C3{constructor(_,w,$){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,A_.NODE_TYPE,{value:A_.DOC});let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w,w=void 0;let Y=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},$);this.options=Y;let{version:J}=Y;if($?._directives){if(this.directives=$._directives.atDocument(),this.directives.yaml.explicit)J=this.directives.yaml.version}else this.directives=new Z3.Directives({version:J});this.setSchema(J,$),this.contents=_===void 0?null:this.createNode(_,X,$)}clone(){let _=Object.create(C3.prototype,{[A_.NODE_TYPE]:{value:A_.DOC}});if(_.commentBefore=this.commentBefore,_.comment=this.comment,_.errors=this.errors.slice(),_.warnings=this.warnings.slice(),_.options=Object.assign({},this.options),this.directives)_.directives=this.directives.clone();if(_.schema=this.schema.clone(),_.contents=A_.isNode(this.contents)?this.contents.clone(_.schema):this.contents,this.range)_.range=this.range.slice();return _}add(_){if(aw(this.contents))this.contents.add(_)}addIn(_,w){if(aw(this.contents))this.contents.addIn(_,w)}createAlias(_,w){if(!_.anchor){let $=P3.anchorNames(this);_.anchor=!w||$.has(w)?P3.findNewAnchor(w||"a",$):w}return new rG.Alias(_.anchor)}createNode(_,w,$){let X=void 0;if(typeof w==="function")_=w.call({"":_},"",_),X=w;else if(Array.isArray(w)){let U=(M)=>typeof M==="number"||M instanceof String||M instanceof Number,V=w.filter(U).map(String);if(V.length>0)w=w.concat(V);X=w}else if($===void 0&&w)$=w,w=void 0;let{aliasDuplicateObjects:Y,anchorPrefix:J,flow:W,keepUndefined:Q,onTagObj:G,tag:q}=$??{},{onAnchor:H,setAnchors:B,sourceObjects:D}=P3.createNodeAnchors(this,J||"a"),O={aliasDuplicateObjects:Y??!0,keepUndefined:Q??!1,onAnchor:H,onTagObj:G,replacer:X,schema:this.schema,sourceObjects:D},z=_q.createNode(_,q,O);if(W&&A_.isCollection(z))z.flow=!0;return B(),z}createPair(_,w,$={}){let X=this.createNode(_,null,$),Y=this.createNode(w,null,$);return new aG.Pair(X,Y)}delete(_){return aw(this.contents)?this.contents.delete(_):!1}deleteIn(_){if(rw.isEmptyPath(_)){if(this.contents==null)return!1;return this.contents=null,!0}return aw(this.contents)?this.contents.deleteIn(_):!1}get(_,w){return A_.isCollection(this.contents)?this.contents.get(_,w):void 0}getIn(_,w){if(rw.isEmptyPath(_))return!w&&A_.isScalar(this.contents)?this.contents.value:this.contents;return A_.isCollection(this.contents)?this.contents.getIn(_,w):void 0}has(_){return A_.isCollection(this.contents)?this.contents.has(_):!1}hasIn(_){if(rw.isEmptyPath(_))return this.contents!==void 0;return A_.isCollection(this.contents)?this.contents.hasIn(_):!1}set(_,w){if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,[_],w);else if(aw(this.contents))this.contents.set(_,w)}setIn(_,w){if(rw.isEmptyPath(_))this.contents=w;else if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,Array.from(_),w);else if(aw(this.contents))this.contents.setIn(_,w)}setSchema(_,w={}){if(typeof _==="number")_=String(_);let $;switch(_){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new Z3.Directives({version:"1.1"});$={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=_;else this.directives=new Z3.Directives({version:_});$={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;$=null;break;default:{let X=JSON.stringify(_);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${X}`)}}if(w.schema instanceof Object)this.schema=w.schema;else if($)this.schema=new sG.Schema(Object.assign($,w));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:_,jsonArg:w,mapAsMap:$,maxAliasCount:X,onAnchor:Y,reviver:J}={}){let W={anchors:new Map,doc:this,keep:!_,mapAsMap:$===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},Q=oG.toJS(this.contents,w??"",W);if(typeof Y==="function")for(let{count:G,res:q}of W.anchors.values())Y(q,G);return typeof J==="function"?eG.applyReviver(J,{"":Q},"",Q):Q}toJSON(_,w){return this.toJS({json:!0,jsonArg:_,mapAsMap:!1,onAnchor:w})}toString(_={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in _&&(!Number.isInteger(_.indent)||Number(_.indent)<=0)){let w=JSON.stringify(_.indent);throw Error(`"indent" option must be a positive integer, not ${w}`)}return tG.stringifyDocument(this,_)}}function aw(_){if(A_.isCollection(_))return!0;throw Error("Expected a YAML collection as document contents")}wq.Document=C3});var Z0=P((Yq)=>{class n2 extends Error{constructor(_,w,$,X){super();this.name=_,this.code=$,this.message=X,this.pos=w}}class m$ extends n2{constructor(_,w,$){super("YAMLParseError",_,w,$)}}class u$ extends n2{constructor(_,w,$){super("YAMLWarning",_,w,$)}}var Xq=(_,w)=>($)=>{if($.pos[0]===-1)return;$.linePos=$.pos.map((Q)=>w.linePos(Q));let{line:X,col:Y}=$.linePos[0];$.message+=` at line ${X}, column ${Y}`;let J=Y-1,W=_.substring(w.lineStarts[X-1],w.lineStarts[X]).replace(/[\n\r]+$/,"");if(J>=60&&W.length>80){let Q=Math.min(J-39,W.length-79);W="\u2026"+W.substring(Q),J-=Q-1}if(W.length>80)W=W.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(W.substring(0,J))){let Q=_.substring(w.lineStarts[X-2],w.lineStarts[X-1]);if(Q.length>80)Q=Q.substring(0,79)+`\u2026
59
- `;W=Q+W}if(/[^ ]/.test(W)){let Q=1,G=$.linePos[1];if(G?.line===X&&G.col>Y)Q=Math.max(1,Math.min(G.col-Y,80-J));let q=" ".repeat(J)+"^".repeat(Q);$.message+=`:
60
-
61
- ${W}
62
- ${q}
63
- `}};Yq.YAMLError=n2;Yq.YAMLParseError=m$;Yq.YAMLWarning=u$;Yq.prettifyError=Xq});var C0=P((Hq)=>{function qq(_,{flow:w,indicator:$,next:X,offset:Y,onError:J,parentIndent:W,startOnNewline:Q}){let G=!1,q=Q,H=Q,B="",D="",O=!1,z=!1,U=null,V=null,M=null,f=null,N=null,R=null,b=null;for(let j of _){if(z){if(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma")J(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");z=!1}if(U){if(q&&j.type!=="comment"&&j.type!=="newline")J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");U=null}switch(j.type){case"space":if(!w&&($!=="doc-start"||X?.type!=="flow-collection")&&j.source.includes("\t"))U=j;H=!0;break;case"comment":{if(!H)J(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=j.source.substring(1)||" ";if(!B)B=C;else B+=D+C;D="",q=!1;break}case"newline":if(q){if(B)B+=j.source;else if(!R||$!=="seq-item-ind")G=!0}else D+=j.source;if(q=!0,O=!0,V||M)f=j;H=!0;break;case"anchor":if(V)J(j,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(j.source.endsWith(":"))J(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);V=j,b??(b=j.offset),q=!1,H=!1,z=!0;break;case"tag":{if(M)J(j,"MULTIPLE_TAGS","A node can have at most one tag");M=j,b??(b=j.offset),q=!1,H=!1,z=!0;break}case $:if(V||M)J(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`);if(R)J(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${w??"collection"}`);R=j,q=$==="seq-item-ind"||$==="explicit-key-ind",H=!1;break;case"comma":if(w){if(N)J(j,"UNEXPECTED_TOKEN",`Unexpected , in ${w}`);N=j,q=!1,H=!1;break}default:J(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),q=!1,H=!1}}let F=_[_.length-1],T=F?F.offset+F.source.length:Y;if(z&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))J(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(U&&(q&&U.indent<=W||X?.type==="block-map"||X?.type==="block-seq"))J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:N,found:R,spaceBefore:G,comment:B,hasNewline:O,anchor:V,tag:M,newlineAfterProp:f,end:T,start:b??T}}Hq.resolveProps=qq});var r2=P((Bq)=>{function T3(_){if(!_)return null;switch(_.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(_.source.includes(`
64
- `))return!0;if(_.end){for(let w of _.end)if(w.type==="newline")return!0}return!1;case"flow-collection":for(let w of _.items){for(let $ of w.start)if($.type==="newline")return!0;if(w.sep){for(let $ of w.sep)if($.type==="newline")return!0}if(T3(w.key)||T3(w.value))return!0}return!1;default:return!0}}Bq.containsNewline=T3});var I3=P((Oq)=>{var zq=r2();function Vq(_,w,$){if(w?.type==="flow-collection"){let X=w.end[0];if(X.indent===_&&(X.source==="]"||X.source==="}")&&zq.containsNewline(w))$(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Oq.flowIndentCheck=Vq});var k3=P((Rq)=>{var l$=p();function Mq(_,w,$){let{uniqueKeys:X}=_.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(J,W)=>J===W||l$.isScalar(J)&&l$.isScalar(W)&&J.value===W.value;return w.some((J)=>Y(J.key,$))}Rq.mapIncludes=Mq});var n$=P((bq)=>{var c$=e_(),Lq=ww(),d$=C0(),Fq=r2(),p$=I3(),Kq=k3(),i$="All mapping items must start at the same column";function Nq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let Q=new(J?.nodeClass??Lq.YAMLMap)($.schema);if($.atRoot)$.atRoot=!1;let G=X.offset,q=null;for(let H of X.items){let{start:B,key:D,sep:O,value:z}=H,U=d$.resolveProps(B,{indicator:"explicit-key-ind",next:D??O?.[0],offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0}),V=!U.found;if(V){if(D){if(D.type==="block-seq")Y(G,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in D&&D.indent!==X.indent)Y(G,"BAD_INDENT",i$)}if(!U.anchor&&!U.tag&&!O){if(q=U.end,U.comment)if(Q.comment)Q.comment+=`
65
- `+U.comment;else Q.comment=U.comment;continue}if(U.newlineAfterProp||Fq.containsNewline(D))Y(D??B[B.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(U.found?.indent!==X.indent)Y(G,"BAD_INDENT",i$);$.atKey=!0;let M=U.end,f=D?_($,D,U,Y):w($,M,B,null,U,Y);if($.schema.compat)p$.flowIndentCheck(X.indent,D,Y);if($.atKey=!1,Kq.mapIncludes($,Q.items,f))Y(M,"DUPLICATE_KEY","Map keys must be unique");let N=d$.resolveProps(O??[],{indicator:"map-value-ind",next:z,offset:f.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!D||D.type==="block-scalar"});if(G=N.end,N.found){if(V){if(z?.type==="block-map"&&!N.hasNewline)Y(G,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if($.options.strict&&U.start<N.found.offset-1024)Y(f.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let R=z?_($,z,N,Y):w($,G,O,null,N,Y);if($.schema.compat)p$.flowIndentCheck(X.indent,z,Y);G=R.range[2];let b=new c$.Pair(f,R);if($.options.keepSourceTokens)b.srcToken=H;Q.items.push(b)}else{if(V)Y(f.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(N.comment)if(f.comment)f.comment+=`
66
- `+N.comment;else f.comment=N.comment;let R=new c$.Pair(f);if($.options.keepSourceTokens)R.srcToken=H;Q.items.push(R)}}if(q&&q<G)Y(q,"IMPOSSIBLE","Map comment with trailing content");return Q.range=[X.offset,G,q??G],Q}bq.resolveBlockMap=Nq});var r$=P((Cq)=>{var Eq=$w(),Sq=C0(),Pq=I3();function Zq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let Q=new(J?.nodeClass??Eq.YAMLSeq)($.schema);if($.atRoot)$.atRoot=!1;if($.atKey)$.atKey=!1;let G=X.offset,q=null;for(let{start:H,value:B}of X.items){let D=Sq.resolveProps(H,{indicator:"seq-item-ind",next:B,offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!D.found)if(D.anchor||D.tag||B)if(B?.type==="block-seq")Y(D.end,"BAD_INDENT","All sequence items must start at the same column");else Y(G,"MISSING_CHAR","Sequence item without - indicator");else{if(q=D.end,D.comment)Q.comment=D.comment;continue}let O=B?_($,B,D,Y):w($,D.end,H,null,D,Y);if($.schema.compat)Pq.flowIndentCheck(X.indent,B,Y);G=O.range[2],Q.items.push(O)}return Q.range=[X.offset,G,q??G],Q}Cq.resolveBlockSeq=Zq});var ow=P((kq)=>{function Iq(_,w,$,X){let Y="";if(_){let J=!1,W="";for(let Q of _){let{source:G,type:q}=Q;switch(q){case"space":J=!0;break;case"comment":{if($&&!J)X(Q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let H=G.substring(1)||" ";if(!Y)Y=H;else Y+=W+H;W="";break}case"newline":if(Y)W+=G;J=!0;break;default:X(Q,"UNEXPECTED_TOKEN",`Unexpected ${q} at node end`)}w+=G.length}}return{comment:Y,offset:w}}kq.resolveEnd=Iq});var s$=P((cq)=>{var hq=p(),yq=e_(),a$=ww(),vq=$w(),xq=ow(),o$=C0(),mq=r2(),uq=k3(),g3="Block collections are not allowed within flow collections",h3=(_)=>_&&(_.type==="block-map"||_.type==="block-seq");function lq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=X.start.source==="{",Q=W?"flow map":"flow sequence",q=new(J?.nodeClass??(W?a$.YAMLMap:vq.YAMLSeq))($.schema);q.flow=!0;let H=$.atRoot;if(H)$.atRoot=!1;if($.atKey)$.atKey=!1;let B=X.offset+X.start.source.length;for(let V=0;V<X.items.length;++V){let M=X.items[V],{start:f,key:N,sep:R,value:b}=M,F=o$.resolveProps(f,{flow:Q,indicator:"explicit-key-ind",next:N??R?.[0],offset:B,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!F.found){if(!F.anchor&&!F.tag&&!R&&!b){if(V===0&&F.comma)Y(F.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`);else if(V<X.items.length-1)Y(F.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${Q}`);if(F.comment)if(q.comment)q.comment+=`
67
- `+F.comment;else q.comment=F.comment;B=F.end;continue}if(!W&&$.options.strict&&mq.containsNewline(N))Y(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(V===0){if(F.comma)Y(F.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`)}else{if(!F.comma)Y(F.start,"MISSING_CHAR",`Missing , between ${Q} items`);if(F.comment){let T="";_:for(let j of f)switch(j.type){case"comma":case"space":break;case"comment":T=j.source.substring(1);break _;default:break _}if(T){let j=q.items[q.items.length-1];if(hq.isPair(j))j=j.value??j.key;if(j.comment)j.comment+=`
68
- `+T;else j.comment=T;F.comment=F.comment.substring(T.length+1)}}}if(!W&&!R&&!F.found){let T=b?_($,b,F,Y):w($,F.end,R,null,F,Y);if(q.items.push(T),B=T.range[2],h3(b))Y(T.range,"BLOCK_IN_FLOW",g3)}else{$.atKey=!0;let T=F.end,j=N?_($,N,F,Y):w($,T,f,null,F,Y);if(h3(N))Y(j.range,"BLOCK_IN_FLOW",g3);$.atKey=!1;let C=o$.resolveProps(R??[],{flow:Q,indicator:"map-value-ind",next:b,offset:j.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(C.found){if(!W&&!F.found&&$.options.strict){if(R)for(let v of R){if(v===C.found)break;if(v.type==="newline"){Y(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(F.start<C.found.offset-1024)Y(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(b)if("source"in b&&b.source?.[0]===":")Y(b,"MISSING_CHAR",`Missing space after : in ${Q}`);else Y(C.start,"MISSING_CHAR",`Missing , or : between ${Q} items`);let y=b?_($,b,C,Y):C.found?w($,C.end,R,null,C,Y):null;if(y){if(h3(b))Y(y.range,"BLOCK_IN_FLOW",g3)}else if(C.comment)if(j.comment)j.comment+=`
69
- `+C.comment;else j.comment=C.comment;let i=new yq.Pair(j,y);if($.options.keepSourceTokens)i.srcToken=M;if(W){let v=q;if(uq.mapIncludes($,v.items,j))Y(T,"DUPLICATE_KEY","Map keys must be unique");v.items.push(i)}else{let v=new a$.YAMLMap($.schema);v.flow=!0,v.items.push(i);let c=(y??j).range;v.range=[j.range[0],c[1],c[2]],q.items.push(v)}B=y?y.range[2]:C.end}}let D=W?"}":"]",[O,...z]=X.end,U=B;if(O?.source===D)U=O.offset+O.source.length;else{let V=Q[0].toUpperCase()+Q.substring(1),M=H?`${V} must end with a ${D}`:`${V} in block collection must be sufficiently indented and end with a ${D}`;if(Y(B,H?"MISSING_CHAR":"BAD_INDENT",M),O&&O.source.length!==1)z.unshift(O)}if(z.length>0){let V=xq.resolveEnd(z,U,$.options.strict,Y);if(V.comment)if(q.comment)q.comment+=`
70
- `+V.comment;else q.comment=V.comment;q.range=[X.offset,U,V.offset]}else q.range=[X.offset,U,U];return q}cq.resolveFlowCollection=lq});var t$=P((eq)=>{var pq=p(),iq=X_(),nq=ww(),rq=$w(),aq=n$(),oq=r$(),sq=s$();function y3(_,w,$,X,Y,J){let W=$.type==="block-map"?aq.resolveBlockMap(_,w,$,X,J):$.type==="block-seq"?oq.resolveBlockSeq(_,w,$,X,J):sq.resolveFlowCollection(_,w,$,X,J),Q=W.constructor;if(Y==="!"||Y===Q.tagName)return W.tag=Q.tagName,W;if(Y)W.tag=Y;return W}function tq(_,w,$,X,Y){let J=X.tag,W=!J?null:w.directives.tagName(J.source,(D)=>Y(J,"TAG_RESOLVE_FAILED",D));if($.type==="block-seq"){let{anchor:D,newlineAfterProp:O}=X,z=D&&J?D.offset>J.offset?D:J:D??J;if(z&&(!O||O.offset<z.offset))Y(z,"MISSING_CHAR","Missing newline after block sequence props")}let Q=$.type==="block-map"?"map":$.type==="block-seq"?"seq":$.start.source==="{"?"map":"seq";if(!J||!W||W==="!"||W===nq.YAMLMap.tagName&&Q==="map"||W===rq.YAMLSeq.tagName&&Q==="seq")return y3(_,w,$,Y,W);let G=w.schema.tags.find((D)=>D.tag===W&&D.collection===Q);if(!G){let D=w.schema.knownTags[W];if(D?.collection===Q)w.schema.tags.push(Object.assign({},D,{default:!1})),G=D;else{if(D)Y(J,"BAD_COLLECTION_TYPE",`${D.tag} used for ${Q} collection, but expects ${D.collection??"scalar"}`,!0);else Y(J,"TAG_RESOLVE_FAILED",`Unresolved tag: ${W}`,!0);return y3(_,w,$,Y,W)}}let q=y3(_,w,$,Y,W,G),H=G.resolve?.(q,(D)=>Y(J,"TAG_RESOLVE_FAILED",D),w.options)??q,B=pq.isNode(H)?H:new iq.Scalar(H);if(B.range=q.range,B.tag=W,G?.format)B.format=G.format;return B}eq.composeCollection=tq});var x3=P((YH)=>{var v3=X_();function wH(_,w,$){let X=w.offset,Y=$H(w,_.options.strict,$);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let J=Y.mode===">"?v3.Scalar.BLOCK_FOLDED:v3.Scalar.BLOCK_LITERAL,W=w.source?XH(w.source):[],Q=W.length;for(let U=W.length-1;U>=0;--U){let V=W[U][1];if(V===""||V==="\r")Q=U;else break}if(Q===0){let U=Y.chomp==="+"&&W.length>0?`
71
- `.repeat(Math.max(1,W.length-1)):"",V=X+Y.length;if(w.source)V+=w.source.length;return{value:U,type:J,comment:Y.comment,range:[X,V,V]}}let G=w.indent+Y.indent,q=w.offset+Y.length,H=0;for(let U=0;U<Q;++U){let[V,M]=W[U];if(M===""||M==="\r"){if(Y.indent===0&&V.length>G)G=V.length}else{if(V.length<G)$(q+V.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(Y.indent===0)G=V.length;if(H=U,G===0&&!_.atRoot)$(q,"BAD_INDENT","Block scalar values in collections must be indented");break}q+=V.length+M.length+1}for(let U=W.length-1;U>=Q;--U)if(W[U][0].length>G)Q=U+1;let B="",D="",O=!1;for(let U=0;U<H;++U)B+=W[U][0].slice(G)+`
72
- `;for(let U=H;U<Q;++U){let[V,M]=W[U];q+=V.length+M.length+1;let f=M[M.length-1]==="\r";if(f)M=M.slice(0,-1);if(M&&V.length<G){let R=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;$(q-M.length-(f?2:1),"BAD_INDENT",R),V=""}if(J===v3.Scalar.BLOCK_LITERAL)B+=D+V.slice(G)+M,D=`
73
- `;else if(V.length>G||M[0]==="\t"){if(D===" ")D=`
74
- `;else if(!O&&D===`
75
- `)D=`
76
-
77
- `;B+=D+V.slice(G)+M,D=`
78
- `,O=!0}else if(M==="")if(D===`
79
- `)B+=`
80
- `;else D=`
81
- `;else B+=D+M,D=" ",O=!1}switch(Y.chomp){case"-":break;case"+":for(let U=Q;U<W.length;++U)B+=`
82
- `+W[U][0].slice(G);if(B[B.length-1]!==`
83
- `)B+=`
84
- `;break;default:B+=`
85
- `}let z=X+Y.length+w.source.length;return{value:B,type:J,comment:Y.comment,range:[X,z,z]}}function $H({offset:_,props:w},$,X){if(w[0].type!=="block-scalar-header")return X(w[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:Y}=w[0],J=Y[0],W=0,Q="",G=-1;for(let D=1;D<Y.length;++D){let O=Y[D];if(!Q&&(O==="-"||O==="+"))Q=O;else{let z=Number(O);if(!W&&z)W=z;else if(G===-1)G=_+D}}if(G!==-1)X(G,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let q=!1,H="",B=Y.length;for(let D=1;D<w.length;++D){let O=w[D];switch(O.type){case"space":q=!0;case"newline":B+=O.source.length;break;case"comment":if($&&!q)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");B+=O.source.length,H=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),B+=O.source.length;break;default:{let z=`Unexpected token in block scalar header: ${O.type}`;X(O,"UNEXPECTED_TOKEN",z);let U=O.source;if(U&&typeof U==="string")B+=U.length}}}return{mode:J,indent:W,chomp:Q,comment:H,length:B}}function XH(_){let w=_.split(/\n( *)/),$=w[0],X=$.match(/^( *)/),J=[X?.[1]?[X[1],$.slice(X[1].length)]:["",$]];for(let W=1;W<w.length;W+=2)J.push([w[W],w[W+1]]);return J}YH.resolveBlockScalar=wH});var u3=P((zH)=>{var m3=X_(),WH=ow();function QH(_,w,$){let{offset:X,type:Y,source:J,end:W}=_,Q,G,q=(D,O,z)=>$(X+D,O,z);switch(Y){case"scalar":Q=m3.Scalar.PLAIN,G=GH(J,q);break;case"single-quoted-scalar":Q=m3.Scalar.QUOTE_SINGLE,G=qH(J,q);break;case"double-quoted-scalar":Q=m3.Scalar.QUOTE_DOUBLE,G=HH(J,q);break;default:return $(_,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${Y}`),{value:"",type:null,comment:"",range:[X,X+J.length,X+J.length]}}let H=X+J.length,B=WH.resolveEnd(W,H,w,$);return{value:G,type:Q,comment:B.comment,range:[X,H,B.offset]}}function GH(_,w){let $="";switch(_[0]){case"\t":$="a tab character";break;case",":$="flow indicator character ,";break;case"%":$="directive indicator character %";break;case"|":case">":{$=`block scalar indicator ${_[0]}`;break}case"@":case"`":{$=`reserved character ${_[0]}`;break}}if($)w(0,"BAD_SCALAR_START",`Plain value cannot start with ${$}`);return e$(_)}function qH(_,w){if(_[_.length-1]!=="'"||_.length===1)w(_.length,"MISSING_CHAR","Missing closing 'quote");return e$(_.slice(1,-1)).replace(/''/g,"'")}function e$(_){let w=/(.*?)\r?\n/sy,$=w.exec(_);if(!$)return _;let X,Y;try{X=new RegExp("(?<![ \t])[ \t]+$"),Y=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,Y=/^[ \t]+|[ \t]+$/g}let J=$[1].replace(X,""),W=" ",Q=w.lastIndex;while($=w.exec(_)){let q=$[1].replace(Y,"");if(q==="")if(W===`
86
- `)J+=W;else W=`
87
- `;else J+=W+q,W=" ";Q=w.lastIndex}let G=/[ \t]*(.*)/sy;return G.lastIndex=Q,$=G.exec(_),J+W+($?.[1]??"")}function HH(_,w){let $="";for(let X=1;X<_.length-1;++X){let Y=_[X];if(Y==="\r"&&_[X+1]===`
58
+ `}aG.stringifyDocument=rG});var P0=P((YQ)=>{var sG=V0(),rw=f1(),A_=p(),tG=_w(),eG=s_(),_Q=E3(),wQ=l8(),P3=A1(),$Q=r2(),XQ=O0(),Z3=n2();class C3{constructor(_,w,$){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,A_.NODE_TYPE,{value:A_.DOC});let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w,w=void 0;let Y=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},$);this.options=Y;let{version:J}=Y;if($?._directives){if(this.directives=$._directives.atDocument(),this.directives.yaml.explicit)J=this.directives.yaml.version}else this.directives=new Z3.Directives({version:J});this.setSchema(J,$),this.contents=_===void 0?null:this.createNode(_,X,$)}clone(){let _=Object.create(C3.prototype,{[A_.NODE_TYPE]:{value:A_.DOC}});if(_.commentBefore=this.commentBefore,_.comment=this.comment,_.errors=this.errors.slice(),_.warnings=this.warnings.slice(),_.options=Object.assign({},this.options),this.directives)_.directives=this.directives.clone();if(_.schema=this.schema.clone(),_.contents=A_.isNode(this.contents)?this.contents.clone(_.schema):this.contents,this.range)_.range=this.range.slice();return _}add(_){if(aw(this.contents))this.contents.add(_)}addIn(_,w){if(aw(this.contents))this.contents.addIn(_,w)}createAlias(_,w){if(!_.anchor){let $=P3.anchorNames(this);_.anchor=!w||$.has(w)?P3.findNewAnchor(w||"a",$):w}return new sG.Alias(_.anchor)}createNode(_,w,$){let X=void 0;if(typeof w==="function")_=w.call({"":_},"",_),X=w;else if(Array.isArray(w)){let U=(M)=>typeof M==="number"||M instanceof String||M instanceof Number,V=w.filter(U).map(String);if(V.length>0)w=w.concat(V);X=w}else if($===void 0&&w)$=w,w=void 0;let{aliasDuplicateObjects:Y,anchorPrefix:J,flow:D,keepUndefined:W,onTagObj:G,tag:Q}=$??{},{onAnchor:q,setAnchors:H,sourceObjects:B}=P3.createNodeAnchors(this,J||"a"),O={aliasDuplicateObjects:Y??!0,keepUndefined:W??!1,onAnchor:q,onTagObj:G,replacer:X,schema:this.schema,sourceObjects:B},z=XQ.createNode(_,Q,O);if(D&&A_.isCollection(z))z.flow=!0;return H(),z}createPair(_,w,$={}){let X=this.createNode(_,null,$),Y=this.createNode(w,null,$);return new tG.Pair(X,Y)}delete(_){return aw(this.contents)?this.contents.delete(_):!1}deleteIn(_){if(rw.isEmptyPath(_)){if(this.contents==null)return!1;return this.contents=null,!0}return aw(this.contents)?this.contents.deleteIn(_):!1}get(_,w){return A_.isCollection(this.contents)?this.contents.get(_,w):void 0}getIn(_,w){if(rw.isEmptyPath(_))return!w&&A_.isScalar(this.contents)?this.contents.value:this.contents;return A_.isCollection(this.contents)?this.contents.getIn(_,w):void 0}has(_){return A_.isCollection(this.contents)?this.contents.has(_):!1}hasIn(_){if(rw.isEmptyPath(_))return this.contents!==void 0;return A_.isCollection(this.contents)?this.contents.hasIn(_):!1}set(_,w){if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,[_],w);else if(aw(this.contents))this.contents.set(_,w)}setIn(_,w){if(rw.isEmptyPath(_))this.contents=w;else if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,Array.from(_),w);else if(aw(this.contents))this.contents.setIn(_,w)}setSchema(_,w={}){if(typeof _==="number")_=String(_);let $;switch(_){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new Z3.Directives({version:"1.1"});$={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=_;else this.directives=new Z3.Directives({version:_});$={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;$=null;break;default:{let X=JSON.stringify(_);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${X}`)}}if(w.schema instanceof Object)this.schema=w.schema;else if($)this.schema=new _Q.Schema(Object.assign($,w));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:_,jsonArg:w,mapAsMap:$,maxAliasCount:X,onAnchor:Y,reviver:J}={}){let D={anchors:new Map,doc:this,keep:!_,mapAsMap:$===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},W=eG.toJS(this.contents,w??"",D);if(typeof Y==="function")for(let{count:G,res:Q}of D.anchors.values())Y(Q,G);return typeof J==="function"?$Q.applyReviver(J,{"":W},"",W):W}toJSON(_,w){return this.toJS({json:!0,jsonArg:_,mapAsMap:!1,onAnchor:w})}toString(_={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in _&&(!Number.isInteger(_.indent)||Number(_.indent)<=0)){let w=JSON.stringify(_.indent);throw Error(`"indent" option must be a positive integer, not ${w}`)}return wQ.stringifyDocument(this,_)}}function aw(_){if(A_.isCollection(_))return!0;throw Error("Expected a YAML collection as document contents")}YQ.Document=C3});var Z0=P((WQ)=>{class n1 extends Error{constructor(_,w,$,X){super();this.name=_,this.code=$,this.message=X,this.pos=w}}class c8 extends n1{constructor(_,w,$){super("YAMLParseError",_,w,$)}}class d8 extends n1{constructor(_,w,$){super("YAMLWarning",_,w,$)}}var DQ=(_,w)=>($)=>{if($.pos[0]===-1)return;$.linePos=$.pos.map((W)=>w.linePos(W));let{line:X,col:Y}=$.linePos[0];$.message+=` at line ${X}, column ${Y}`;let J=Y-1,D=_.substring(w.lineStarts[X-1],w.lineStarts[X]).replace(/[\n\r]+$/,"");if(J>=60&&D.length>80){let W=Math.min(J-39,D.length-79);D="\u2026"+D.substring(W),J-=W-1}if(D.length>80)D=D.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(D.substring(0,J))){let W=_.substring(w.lineStarts[X-2],w.lineStarts[X-1]);if(W.length>80)W=W.substring(0,79)+`\u2026
59
+ `;D=W+D}if(/[^ ]/.test(D)){let W=1,G=$.linePos[1];if(G?.line===X&&G.col>Y)W=Math.max(1,Math.min(G.col-Y,80-J));let Q=" ".repeat(J)+"^".repeat(W);$.message+=`:
60
+
61
+ ${D}
62
+ ${Q}
63
+ `}};WQ.YAMLError=n1;WQ.YAMLParseError=c8;WQ.YAMLWarning=d8;WQ.prettifyError=DQ});var C0=P((UQ)=>{function BQ(_,{flow:w,indicator:$,next:X,offset:Y,onError:J,parentIndent:D,startOnNewline:W}){let G=!1,Q=W,q=W,H="",B="",O=!1,z=!1,U=null,V=null,M=null,R=null,N=null,b=null,E=null;for(let L of _){if(z){if(L.type!=="space"&&L.type!=="newline"&&L.type!=="comma")J(L.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");z=!1}if(U){if(Q&&L.type!=="comment"&&L.type!=="newline")J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");U=null}switch(L.type){case"space":if(!w&&($!=="doc-start"||X?.type!=="flow-collection")&&L.source.includes("\t"))U=L;q=!0;break;case"comment":{if(!q)J(L,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=L.source.substring(1)||" ";if(!H)H=C;else H+=B+C;B="",Q=!1;break}case"newline":if(Q){if(H)H+=L.source;else if(!b||$!=="seq-item-ind")G=!0}else B+=L.source;if(Q=!0,O=!0,V||M)R=L;q=!0;break;case"anchor":if(V)J(L,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(L.source.endsWith(":"))J(L.offset+L.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);V=L,E??(E=L.offset),Q=!1,q=!1,z=!0;break;case"tag":{if(M)J(L,"MULTIPLE_TAGS","A node can have at most one tag");M=L,E??(E=L.offset),Q=!1,q=!1,z=!0;break}case $:if(V||M)J(L,"BAD_PROP_ORDER",`Anchors and tags must be after the ${L.source} indicator`);if(b)J(L,"UNEXPECTED_TOKEN",`Unexpected ${L.source} in ${w??"collection"}`);b=L,Q=$==="seq-item-ind"||$==="explicit-key-ind",q=!1;break;case"comma":if(w){if(N)J(L,"UNEXPECTED_TOKEN",`Unexpected , in ${w}`);N=L,Q=!1,q=!1;break}default:J(L,"UNEXPECTED_TOKEN",`Unexpected ${L.type} token`),Q=!1,q=!1}}let f=_[_.length-1],Z=f?f.offset+f.source.length:Y;if(z&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))J(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(U&&(Q&&U.indent<=D||X?.type==="block-map"||X?.type==="block-seq"))J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:N,found:b,spaceBefore:G,comment:H,hasNewline:O,anchor:V,tag:M,newlineAfterProp:R,end:Z,start:E??Z}}UQ.resolveProps=BQ});var r1=P((VQ)=>{function T3(_){if(!_)return null;switch(_.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(_.source.includes(`
64
+ `))return!0;if(_.end){for(let w of _.end)if(w.type==="newline")return!0}return!1;case"flow-collection":for(let w of _.items){for(let $ of w.start)if($.type==="newline")return!0;if(w.sep){for(let $ of w.sep)if($.type==="newline")return!0}if(T3(w.key)||T3(w.value))return!0}return!1;default:return!0}}VQ.containsNewline=T3});var I3=P((RQ)=>{var AQ=r1();function MQ(_,w,$){if(w?.type==="flow-collection"){let X=w.end[0];if(X.indent===_&&(X.source==="]"||X.source==="}")&&AQ.containsNewline(w))$(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}RQ.flowIndentCheck=MQ});var k3=P((FQ)=>{var p8=p();function LQ(_,w,$){let{uniqueKeys:X}=_.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(J,D)=>J===D||p8.isScalar(J)&&p8.isScalar(D)&&J.value===D.value;return w.some((J)=>Y(J.key,$))}FQ.mapIncludes=LQ});var o8=P((SQ)=>{var i8=_w(),NQ=$w(),n8=C0(),bQ=r1(),r8=I3(),jQ=k3(),a8="All mapping items must start at the same column";function EQ({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=new(J?.nodeClass??NQ.YAMLMap)($.schema);if($.atRoot)$.atRoot=!1;let G=X.offset,Q=null;for(let q of X.items){let{start:H,key:B,sep:O,value:z}=q,U=n8.resolveProps(H,{indicator:"explicit-key-ind",next:B??O?.[0],offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0}),V=!U.found;if(V){if(B){if(B.type==="block-seq")Y(G,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in B&&B.indent!==X.indent)Y(G,"BAD_INDENT",a8)}if(!U.anchor&&!U.tag&&!O){if(Q=U.end,U.comment)if(W.comment)W.comment+=`
65
+ `+U.comment;else W.comment=U.comment;continue}if(U.newlineAfterProp||bQ.containsNewline(B))Y(B??H[H.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(U.found?.indent!==X.indent)Y(G,"BAD_INDENT",a8);$.atKey=!0;let M=U.end,R=B?_($,B,U,Y):w($,M,H,null,U,Y);if($.schema.compat)r8.flowIndentCheck(X.indent,B,Y);if($.atKey=!1,jQ.mapIncludes($,W.items,R))Y(M,"DUPLICATE_KEY","Map keys must be unique");let N=n8.resolveProps(O??[],{indicator:"map-value-ind",next:z,offset:R.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!B||B.type==="block-scalar"});if(G=N.end,N.found){if(V){if(z?.type==="block-map"&&!N.hasNewline)Y(G,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if($.options.strict&&U.start<N.found.offset-1024)Y(R.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let b=z?_($,z,N,Y):w($,G,O,null,N,Y);if($.schema.compat)r8.flowIndentCheck(X.indent,z,Y);G=b.range[2];let E=new i8.Pair(R,b);if($.options.keepSourceTokens)E.srcToken=q;W.items.push(E)}else{if(V)Y(R.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(N.comment)if(R.comment)R.comment+=`
66
+ `+N.comment;else R.comment=N.comment;let b=new i8.Pair(R);if($.options.keepSourceTokens)b.srcToken=q;W.items.push(b)}}if(Q&&Q<G)Y(Q,"IMPOSSIBLE","Map comment with trailing content");return W.range=[X.offset,G,Q??G],W}SQ.resolveBlockMap=EQ});var s8=P((kQ)=>{var ZQ=Xw(),CQ=C0(),TQ=I3();function IQ({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=new(J?.nodeClass??ZQ.YAMLSeq)($.schema);if($.atRoot)$.atRoot=!1;if($.atKey)$.atKey=!1;let G=X.offset,Q=null;for(let{start:q,value:H}of X.items){let B=CQ.resolveProps(q,{indicator:"seq-item-ind",next:H,offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!B.found)if(B.anchor||B.tag||H)if(H?.type==="block-seq")Y(B.end,"BAD_INDENT","All sequence items must start at the same column");else Y(G,"MISSING_CHAR","Sequence item without - indicator");else{if(Q=B.end,B.comment)W.comment=B.comment;continue}let O=H?_($,H,B,Y):w($,B.end,q,null,B,Y);if($.schema.compat)TQ.flowIndentCheck(X.indent,H,Y);G=O.range[2],W.items.push(O)}return W.range=[X.offset,G,Q??G],W}kQ.resolveBlockSeq=IQ});var ow=P((yQ)=>{function hQ(_,w,$,X){let Y="";if(_){let J=!1,D="";for(let W of _){let{source:G,type:Q}=W;switch(Q){case"space":J=!0;break;case"comment":{if($&&!J)X(W,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let q=G.substring(1)||" ";if(!Y)Y=q;else Y+=D+q;D="";break}case"newline":if(Y)D+=G;J=!0;break;default:X(W,"UNEXPECTED_TOKEN",`Unexpected ${Q} at node end`)}w+=G.length}}return{comment:Y,offset:w}}yQ.resolveEnd=hQ});var _5=P((iQ)=>{var xQ=p(),mQ=_w(),t8=$w(),uQ=Xw(),lQ=ow(),e8=C0(),cQ=r1(),dQ=k3(),g3="Block collections are not allowed within flow collections",h3=(_)=>_&&(_.type==="block-map"||_.type==="block-seq");function pQ({composeNode:_,composeEmptyNode:w},$,X,Y,J){let D=X.start.source==="{",W=D?"flow map":"flow sequence",Q=new(J?.nodeClass??(D?t8.YAMLMap:uQ.YAMLSeq))($.schema);Q.flow=!0;let q=$.atRoot;if(q)$.atRoot=!1;if($.atKey)$.atKey=!1;let H=X.offset+X.start.source.length;for(let V=0;V<X.items.length;++V){let M=X.items[V],{start:R,key:N,sep:b,value:E}=M,f=e8.resolveProps(R,{flow:W,indicator:"explicit-key-ind",next:N??b?.[0],offset:H,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!f.found){if(!f.anchor&&!f.tag&&!b&&!E){if(V===0&&f.comma)Y(f.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`);else if(V<X.items.length-1)Y(f.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${W}`);if(f.comment)if(Q.comment)Q.comment+=`
67
+ `+f.comment;else Q.comment=f.comment;H=f.end;continue}if(!D&&$.options.strict&&cQ.containsNewline(N))Y(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(V===0){if(f.comma)Y(f.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`)}else{if(!f.comma)Y(f.start,"MISSING_CHAR",`Missing , between ${W} items`);if(f.comment){let Z="";_:for(let L of R)switch(L.type){case"comma":case"space":break;case"comment":Z=L.source.substring(1);break _;default:break _}if(Z){let L=Q.items[Q.items.length-1];if(xQ.isPair(L))L=L.value??L.key;if(L.comment)L.comment+=`
68
+ `+Z;else L.comment=Z;f.comment=f.comment.substring(Z.length+1)}}}if(!D&&!b&&!f.found){let Z=E?_($,E,f,Y):w($,f.end,b,null,f,Y);if(Q.items.push(Z),H=Z.range[2],h3(E))Y(Z.range,"BLOCK_IN_FLOW",g3)}else{$.atKey=!0;let Z=f.end,L=N?_($,N,f,Y):w($,Z,R,null,f,Y);if(h3(N))Y(L.range,"BLOCK_IN_FLOW",g3);$.atKey=!1;let C=e8.resolveProps(b??[],{flow:W,indicator:"map-value-ind",next:E,offset:L.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(C.found){if(!D&&!f.found&&$.options.strict){if(b)for(let v of b){if(v===C.found)break;if(v.type==="newline"){Y(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(f.start<C.found.offset-1024)Y(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(E)if("source"in E&&E.source?.[0]===":")Y(E,"MISSING_CHAR",`Missing space after : in ${W}`);else Y(C.start,"MISSING_CHAR",`Missing , or : between ${W} items`);let y=E?_($,E,C,Y):C.found?w($,C.end,b,null,C,Y):null;if(y){if(h3(E))Y(y.range,"BLOCK_IN_FLOW",g3)}else if(C.comment)if(L.comment)L.comment+=`
69
+ `+C.comment;else L.comment=C.comment;let i=new mQ.Pair(L,y);if($.options.keepSourceTokens)i.srcToken=M;if(D){let v=Q;if(dQ.mapIncludes($,v.items,L))Y(Z,"DUPLICATE_KEY","Map keys must be unique");v.items.push(i)}else{let v=new t8.YAMLMap($.schema);v.flow=!0,v.items.push(i);let c=(y??L).range;v.range=[L.range[0],c[1],c[2]],Q.items.push(v)}H=y?y.range[2]:C.end}}let B=D?"}":"]",[O,...z]=X.end,U=H;if(O?.source===B)U=O.offset+O.source.length;else{let V=W[0].toUpperCase()+W.substring(1),M=q?`${V} must end with a ${B}`:`${V} in block collection must be sufficiently indented and end with a ${B}`;if(Y(H,q?"MISSING_CHAR":"BAD_INDENT",M),O&&O.source.length!==1)z.unshift(O)}if(z.length>0){let V=lQ.resolveEnd(z,U,$.options.strict,Y);if(V.comment)if(Q.comment)Q.comment+=`
70
+ `+V.comment;else Q.comment=V.comment;Q.range=[X.offset,U,V.offset]}else Q.range=[X.offset,U,U];return Q}iQ.resolveFlowCollection=pQ});var w5=P(($q)=>{var rQ=p(),aQ=X_(),oQ=$w(),sQ=Xw(),tQ=o8(),eQ=s8(),_q=_5();function y3(_,w,$,X,Y,J){let D=$.type==="block-map"?tQ.resolveBlockMap(_,w,$,X,J):$.type==="block-seq"?eQ.resolveBlockSeq(_,w,$,X,J):_q.resolveFlowCollection(_,w,$,X,J),W=D.constructor;if(Y==="!"||Y===W.tagName)return D.tag=W.tagName,D;if(Y)D.tag=Y;return D}function wq(_,w,$,X,Y){let J=X.tag,D=!J?null:w.directives.tagName(J.source,(B)=>Y(J,"TAG_RESOLVE_FAILED",B));if($.type==="block-seq"){let{anchor:B,newlineAfterProp:O}=X,z=B&&J?B.offset>J.offset?B:J:B??J;if(z&&(!O||O.offset<z.offset))Y(z,"MISSING_CHAR","Missing newline after block sequence props")}let W=$.type==="block-map"?"map":$.type==="block-seq"?"seq":$.start.source==="{"?"map":"seq";if(!J||!D||D==="!"||D===oQ.YAMLMap.tagName&&W==="map"||D===sQ.YAMLSeq.tagName&&W==="seq")return y3(_,w,$,Y,D);let G=w.schema.tags.find((B)=>B.tag===D&&B.collection===W);if(!G){let B=w.schema.knownTags[D];if(B?.collection===W)w.schema.tags.push(Object.assign({},B,{default:!1})),G=B;else{if(B)Y(J,"BAD_COLLECTION_TYPE",`${B.tag} used for ${W} collection, but expects ${B.collection??"scalar"}`,!0);else Y(J,"TAG_RESOLVE_FAILED",`Unresolved tag: ${D}`,!0);return y3(_,w,$,Y,D)}}let Q=y3(_,w,$,Y,D,G),q=G.resolve?.(Q,(B)=>Y(J,"TAG_RESOLVE_FAILED",B),w.options)??Q,H=rQ.isNode(q)?q:new aQ.Scalar(q);if(H.range=Q.range,H.tag=D,G?.format)H.format=G.format;return H}$q.composeCollection=wq});var x3=P((Wq)=>{var v3=X_();function Yq(_,w,$){let X=w.offset,Y=Jq(w,_.options.strict,$);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let J=Y.mode===">"?v3.Scalar.BLOCK_FOLDED:v3.Scalar.BLOCK_LITERAL,D=w.source?Dq(w.source):[],W=D.length;for(let U=D.length-1;U>=0;--U){let V=D[U][1];if(V===""||V==="\r")W=U;else break}if(W===0){let U=Y.chomp==="+"&&D.length>0?`
71
+ `.repeat(Math.max(1,D.length-1)):"",V=X+Y.length;if(w.source)V+=w.source.length;return{value:U,type:J,comment:Y.comment,range:[X,V,V]}}let G=w.indent+Y.indent,Q=w.offset+Y.length,q=0;for(let U=0;U<W;++U){let[V,M]=D[U];if(M===""||M==="\r"){if(Y.indent===0&&V.length>G)G=V.length}else{if(V.length<G)$(Q+V.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(Y.indent===0)G=V.length;if(q=U,G===0&&!_.atRoot)$(Q,"BAD_INDENT","Block scalar values in collections must be indented");break}Q+=V.length+M.length+1}for(let U=D.length-1;U>=W;--U)if(D[U][0].length>G)W=U+1;let H="",B="",O=!1;for(let U=0;U<q;++U)H+=D[U][0].slice(G)+`
72
+ `;for(let U=q;U<W;++U){let[V,M]=D[U];Q+=V.length+M.length+1;let R=M[M.length-1]==="\r";if(R)M=M.slice(0,-1);if(M&&V.length<G){let b=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;$(Q-M.length-(R?2:1),"BAD_INDENT",b),V=""}if(J===v3.Scalar.BLOCK_LITERAL)H+=B+V.slice(G)+M,B=`
73
+ `;else if(V.length>G||M[0]==="\t"){if(B===" ")B=`
74
+ `;else if(!O&&B===`
75
+ `)B=`
76
+
77
+ `;H+=B+V.slice(G)+M,B=`
78
+ `,O=!0}else if(M==="")if(B===`
79
+ `)H+=`
80
+ `;else B=`
81
+ `;else H+=B+M,B=" ",O=!1}switch(Y.chomp){case"-":break;case"+":for(let U=W;U<D.length;++U)H+=`
82
+ `+D[U][0].slice(G);if(H[H.length-1]!==`
83
+ `)H+=`
84
+ `;break;default:H+=`
85
+ `}let z=X+Y.length+w.source.length;return{value:H,type:J,comment:Y.comment,range:[X,z,z]}}function Jq({offset:_,props:w},$,X){if(w[0].type!=="block-scalar-header")return X(w[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:Y}=w[0],J=Y[0],D=0,W="",G=-1;for(let B=1;B<Y.length;++B){let O=Y[B];if(!W&&(O==="-"||O==="+"))W=O;else{let z=Number(O);if(!D&&z)D=z;else if(G===-1)G=_+B}}if(G!==-1)X(G,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let Q=!1,q="",H=Y.length;for(let B=1;B<w.length;++B){let O=w[B];switch(O.type){case"space":Q=!0;case"newline":H+=O.source.length;break;case"comment":if($&&!Q)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");H+=O.source.length,q=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),H+=O.source.length;break;default:{let z=`Unexpected token in block scalar header: ${O.type}`;X(O,"UNEXPECTED_TOKEN",z);let U=O.source;if(U&&typeof U==="string")H+=U.length}}}return{mode:J,indent:D,chomp:W,comment:q,length:H}}function Dq(_){let w=_.split(/\n( *)/),$=w[0],X=$.match(/^( *)/),J=[X?.[1]?[X[1],$.slice(X[1].length)]:["",$]];for(let D=1;D<w.length;D+=2)J.push([w[D],w[D+1]]);return J}Wq.resolveBlockScalar=Yq});var u3=P((Aq)=>{var m3=X_(),Qq=ow();function qq(_,w,$){let{offset:X,type:Y,source:J,end:D}=_,W,G,Q=(B,O,z)=>$(X+B,O,z);switch(Y){case"scalar":W=m3.Scalar.PLAIN,G=Hq(J,Q);break;case"single-quoted-scalar":W=m3.Scalar.QUOTE_SINGLE,G=Bq(J,Q);break;case"double-quoted-scalar":W=m3.Scalar.QUOTE_DOUBLE,G=Uq(J,Q);break;default:return $(_,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${Y}`),{value:"",type:null,comment:"",range:[X,X+J.length,X+J.length]}}let q=X+J.length,H=Qq.resolveEnd(D,q,w,$);return{value:G,type:W,comment:H.comment,range:[X,q,H.offset]}}function Hq(_,w){let $="";switch(_[0]){case"\t":$="a tab character";break;case",":$="flow indicator character ,";break;case"%":$="directive indicator character %";break;case"|":case">":{$=`block scalar indicator ${_[0]}`;break}case"@":case"`":{$=`reserved character ${_[0]}`;break}}if($)w(0,"BAD_SCALAR_START",`Plain value cannot start with ${$}`);return $5(_)}function Bq(_,w){if(_[_.length-1]!=="'"||_.length===1)w(_.length,"MISSING_CHAR","Missing closing 'quote");return $5(_.slice(1,-1)).replace(/''/g,"'")}function $5(_){let w=/(.*?)\r?\n/sy,$=w.exec(_);if(!$)return _;let X,Y;try{X=new RegExp("(?<![ \t])[ \t]+$"),Y=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,Y=/^[ \t]+|[ \t]+$/g}let J=$[1].replace(X,""),D=" ",W=w.lastIndex;while($=w.exec(_)){let Q=$[1].replace(Y,"");if(Q==="")if(D===`
86
+ `)J+=D;else D=`
87
+ `;else J+=D+Q,D=" ";W=w.lastIndex}let G=/[ \t]*(.*)/sy;return G.lastIndex=W,$=G.exec(_),J+D+($?.[1]??"")}function Uq(_,w){let $="";for(let X=1;X<_.length-1;++X){let Y=_[X];if(Y==="\r"&&_[X+1]===`
88
88
  `)continue;if(Y===`
89
- `){let{fold:J,offset:W}=DH(_,X);$+=J,X=W}else if(Y==="\\"){let J=_[++X],W=BH[J];if(W)$+=W;else if(J===`
89
+ `){let{fold:J,offset:D}=zq(_,X);$+=J,X=D}else if(Y==="\\"){let J=_[++X],D=Vq[J];if(D)$+=D;else if(J===`
90
90
  `){J=_[X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="\r"&&_[X+1]===`
91
- `){J=_[++X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="x"||J==="u"||J==="U"){let Q=J==="x"?2:J==="u"?4:8;$+=UH(_,X+1,Q,w),X+=Q}else{let Q=_.substr(X-1,2);w(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),$+=Q}}else if(Y===" "||Y==="\t"){let J=X,W=_[X+1];while(W===" "||W==="\t")W=_[++X+1];if(W!==`
92
- `&&!(W==="\r"&&_[X+2]===`
93
- `))$+=X>J?_.slice(J,X+1):Y}else $+=Y}if(_[_.length-1]!=='"'||_.length===1)w(_.length,"MISSING_CHAR",'Missing closing "quote');return $}function DH(_,w){let $="",X=_[w+1];while(X===" "||X==="\t"||X===`
91
+ `){J=_[++X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="x"||J==="u"||J==="U"){let W=J==="x"?2:J==="u"?4:8;$+=Oq(_,X+1,W,w),X+=W}else{let W=_.substr(X-1,2);w(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),$+=W}}else if(Y===" "||Y==="\t"){let J=X,D=_[X+1];while(D===" "||D==="\t")D=_[++X+1];if(D!==`
92
+ `&&!(D==="\r"&&_[X+2]===`
93
+ `))$+=X>J?_.slice(J,X+1):Y}else $+=Y}if(_[_.length-1]!=='"'||_.length===1)w(_.length,"MISSING_CHAR",'Missing closing "quote');return $}function zq(_,w){let $="",X=_[w+1];while(X===" "||X==="\t"||X===`
94
94
  `||X==="\r"){if(X==="\r"&&_[w+2]!==`
95
95
  `)break;if(X===`
96
96
  `)$+=`
97
- `;w+=1,X=_[w+1]}if(!$)$=" ";return{fold:$,offset:w}}var BH={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
98
- `,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function UH(_,w,$,X){let Y=_.substr(w,$),W=Y.length===$&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(W)}catch{let Q=_.substr(w-2,$+2);return X(w-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),Q}}zH.resolveFlowScalar=QH});var w5=P((LH)=>{var Aw=p(),_5=X_(),OH=x3(),AH=u3();function MH(_,w,$,X){let{value:Y,type:J,comment:W,range:Q}=w.type==="block-scalar"?OH.resolveBlockScalar(_,w,X):AH.resolveFlowScalar(w,_.options.strict,X),G=$?_.directives.tagName($.source,(B)=>X($,"TAG_RESOLVE_FAILED",B)):null,q;if(_.options.stringKeys&&_.atKey)q=_.schema[Aw.SCALAR];else if(G)q=RH(_.schema,Y,G,$,X);else if(w.type==="scalar")q=fH(_,Y,w,X);else q=_.schema[Aw.SCALAR];let H;try{let B=q.resolve(Y,(D)=>X($??w,"TAG_RESOLVE_FAILED",D),_.options);H=Aw.isScalar(B)?B:new _5.Scalar(B)}catch(B){let D=B instanceof Error?B.message:String(B);X($??w,"TAG_RESOLVE_FAILED",D),H=new _5.Scalar(Y)}if(H.range=Q,H.source=Y,J)H.type=J;if(G)H.tag=G;if(q.format)H.format=q.format;if(W)H.comment=W;return H}function RH(_,w,$,X,Y){if($==="!")return _[Aw.SCALAR];let J=[];for(let Q of _.tags)if(!Q.collection&&Q.tag===$)if(Q.default&&Q.test)J.push(Q);else return Q;for(let Q of J)if(Q.test?.test(w))return Q;let W=_.knownTags[$];if(W&&!W.collection)return _.tags.push(Object.assign({},W,{default:!1,test:void 0})),W;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${$}`,$!=="tag:yaml.org,2002:str"),_[Aw.SCALAR]}function fH({atKey:_,directives:w,schema:$},X,Y,J){let W=$.tags.find((Q)=>(Q.default===!0||_&&Q.default==="key")&&Q.test?.test(X))||$[Aw.SCALAR];if($.compat){let Q=$.compat.find((G)=>G.default&&G.test?.test(X))??$[Aw.SCALAR];if(W.tag!==Q.tag){let G=w.tagString(W.tag),q=w.tagString(Q.tag),H=`Value may be parsed as either ${G} or ${q}`;J(Y,"TAG_RESOLVE_FAILED",H,!0)}}return W}LH.composeScalar=MH});var $5=P((NH)=>{function KH(_,w,$){if(w){$??($=w.length);for(let X=$-1;X>=0;--X){let Y=w[X];switch(Y.type){case"space":case"comment":case"newline":_-=Y.source.length;continue}Y=w[++X];while(Y?.type==="space")_+=Y.source.length,Y=w[++X];break}}return _}NH.emptyScalarPosition=KH});var J5=P((IH)=>{var jH=V0(),EH=p(),SH=t$(),X5=w5(),PH=ow(),ZH=$5(),CH={composeNode:Y5,composeEmptyNode:l3};function Y5(_,w,$,X){let Y=_.atKey,{spaceBefore:J,comment:W,anchor:Q,tag:G}=$,q,H=!0;switch(w.type){case"alias":if(q=TH(_,w,X),Q||G)X(w,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(q=X5.composeScalar(_,w,G,X),Q)q.anchor=Q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(q=SH.composeCollection(CH,_,w,$,X),Q)q.anchor=Q.source.substring(1)}catch(B){let D=B instanceof Error?B.message:String(B);X(w,"RESOURCE_EXHAUSTION",D)}break;default:{let B=w.type==="error"?w.message:`Unsupported token (type: ${w.type})`;X(w,"UNEXPECTED_TOKEN",B),H=!1}}if(q??(q=l3(_,w.offset,void 0,null,$,X)),Q&&q.anchor==="")X(Q,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&_.options.stringKeys&&(!EH.isScalar(q)||typeof q.value!=="string"||q.tag&&q.tag!=="tag:yaml.org,2002:str"))X(G??w,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(J)q.spaceBefore=!0;if(W)if(w.type==="scalar"&&w.source==="")q.comment=W;else q.commentBefore=W;if(_.options.keepSourceTokens&&H)q.srcToken=w;return q}function l3(_,w,$,X,{spaceBefore:Y,comment:J,anchor:W,tag:Q,end:G},q){let H={type:"scalar",offset:ZH.emptyScalarPosition(w,$,X),indent:-1,source:""},B=X5.composeScalar(_,H,Q,q);if(W){if(B.anchor=W.source.substring(1),B.anchor==="")q(W,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)B.spaceBefore=!0;if(J)B.comment=J,B.range[2]=G;return B}function TH({options:_},{offset:w,source:$,end:X},Y){let J=new jH.Alias($.substring(1));if(J.source==="")Y(w,"BAD_ALIAS","Alias cannot be an empty string");if(J.source.endsWith(":"))Y(w+$.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let W=w+$.length,Q=PH.resolveEnd(X,W,_.strict,Y);if(J.range=[w,W,Q.offset],Q.comment)J.comment=Q.comment;return J}IH.composeEmptyNode=l3;IH.composeNode=Y5});var Q5=P((mH)=>{var hH=P0(),W5=J5(),yH=ow(),vH=C0();function xH(_,w,{offset:$,start:X,value:Y,end:J},W){let Q=Object.assign({_directives:w},_),G=new hH.Document(void 0,Q),q={atKey:!1,atRoot:!0,directives:G.directives,options:G.options,schema:G.schema},H=vH.resolveProps(X,{indicator:"doc-start",next:Y??J?.[0],offset:$,onError:W,parentIndent:0,startOnNewline:!0});if(H.found){if(G.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!H.hasNewline)W(H.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}G.contents=Y?W5.composeNode(q,Y,H,W):W5.composeEmptyNode(q,H.end,X,null,H,W);let B=G.contents.range[2],D=yH.resolveEnd(J,B,!1,W);if(D.comment)G.comment=D.comment;return G.range=[$,B,D.offset],G}mH.composeDoc=xH});var c3=P((nH)=>{var lH=$2("process"),cH=n1(),dH=P0(),T0=Z0(),G5=p(),pH=Q5(),iH=ow();function I0(_){if(typeof _==="number")return[_,_+1];if(Array.isArray(_))return _.length===2?_:[_[0],_[1]];let{offset:w,source:$}=_;return[w,w+(typeof $==="string"?$.length:1)]}function q5(_){let w="",$=!1,X=!1;for(let Y=0;Y<_.length;++Y){let J=_[Y];switch(J[0]){case"#":w+=(w===""?"":X?`
97
+ `;w+=1,X=_[w+1]}if(!$)$=" ";return{fold:$,offset:w}}var Vq={"0":"\x00",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
98
+ `,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function Oq(_,w,$,X){let Y=_.substr(w,$),D=Y.length===$&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(D)}catch{let W=_.substr(w-2,$+2);return X(w-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),W}}Aq.resolveFlowScalar=qq});var Y5=P((Nq)=>{var Mw=p(),X5=X_(),Rq=x3(),fq=u3();function Lq(_,w,$,X){let{value:Y,type:J,comment:D,range:W}=w.type==="block-scalar"?Rq.resolveBlockScalar(_,w,X):fq.resolveFlowScalar(w,_.options.strict,X),G=$?_.directives.tagName($.source,(H)=>X($,"TAG_RESOLVE_FAILED",H)):null,Q;if(_.options.stringKeys&&_.atKey)Q=_.schema[Mw.SCALAR];else if(G)Q=Fq(_.schema,Y,G,$,X);else if(w.type==="scalar")Q=Kq(_,Y,w,X);else Q=_.schema[Mw.SCALAR];let q;try{let H=Q.resolve(Y,(B)=>X($??w,"TAG_RESOLVE_FAILED",B),_.options);q=Mw.isScalar(H)?H:new X5.Scalar(H)}catch(H){let B=H instanceof Error?H.message:String(H);X($??w,"TAG_RESOLVE_FAILED",B),q=new X5.Scalar(Y)}if(q.range=W,q.source=Y,J)q.type=J;if(G)q.tag=G;if(Q.format)q.format=Q.format;if(D)q.comment=D;return q}function Fq(_,w,$,X,Y){if($==="!")return _[Mw.SCALAR];let J=[];for(let W of _.tags)if(!W.collection&&W.tag===$)if(W.default&&W.test)J.push(W);else return W;for(let W of J)if(W.test?.test(w))return W;let D=_.knownTags[$];if(D&&!D.collection)return _.tags.push(Object.assign({},D,{default:!1,test:void 0})),D;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${$}`,$!=="tag:yaml.org,2002:str"),_[Mw.SCALAR]}function Kq({atKey:_,directives:w,schema:$},X,Y,J){let D=$.tags.find((W)=>(W.default===!0||_&&W.default==="key")&&W.test?.test(X))||$[Mw.SCALAR];if($.compat){let W=$.compat.find((G)=>G.default&&G.test?.test(X))??$[Mw.SCALAR];if(D.tag!==W.tag){let G=w.tagString(D.tag),Q=w.tagString(W.tag),q=`Value may be parsed as either ${G} or ${Q}`;J(Y,"TAG_RESOLVE_FAILED",q,!0)}}return D}Nq.composeScalar=Lq});var J5=P((Eq)=>{function jq(_,w,$){if(w){$??($=w.length);for(let X=$-1;X>=0;--X){let Y=w[X];switch(Y.type){case"space":case"comment":case"newline":_-=Y.source.length;continue}Y=w[++X];while(Y?.type==="space")_+=Y.source.length,Y=w[++X];break}}return _}Eq.emptyScalarPosition=jq});var G5=P((hq)=>{var Pq=V0(),Zq=p(),Cq=w5(),D5=Y5(),Tq=ow(),Iq=J5(),kq={composeNode:W5,composeEmptyNode:l3};function W5(_,w,$,X){let Y=_.atKey,{spaceBefore:J,comment:D,anchor:W,tag:G}=$,Q,q=!0;switch(w.type){case"alias":if(Q=gq(_,w,X),W||G)X(w,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(Q=D5.composeScalar(_,w,G,X),W)Q.anchor=W.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(Q=Cq.composeCollection(kq,_,w,$,X),W)Q.anchor=W.source.substring(1)}catch(H){let B=H instanceof Error?H.message:String(H);X(w,"RESOURCE_EXHAUSTION",B)}break;default:{let H=w.type==="error"?w.message:`Unsupported token (type: ${w.type})`;X(w,"UNEXPECTED_TOKEN",H),q=!1}}if(Q??(Q=l3(_,w.offset,void 0,null,$,X)),W&&Q.anchor==="")X(W,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&_.options.stringKeys&&(!Zq.isScalar(Q)||typeof Q.value!=="string"||Q.tag&&Q.tag!=="tag:yaml.org,2002:str"))X(G??w,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(J)Q.spaceBefore=!0;if(D)if(w.type==="scalar"&&w.source==="")Q.comment=D;else Q.commentBefore=D;if(_.options.keepSourceTokens&&q)Q.srcToken=w;return Q}function l3(_,w,$,X,{spaceBefore:Y,comment:J,anchor:D,tag:W,end:G},Q){let q={type:"scalar",offset:Iq.emptyScalarPosition(w,$,X),indent:-1,source:""},H=D5.composeScalar(_,q,W,Q);if(D){if(H.anchor=D.source.substring(1),H.anchor==="")Q(D,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)H.spaceBefore=!0;if(J)H.comment=J,H.range[2]=G;return H}function gq({options:_},{offset:w,source:$,end:X},Y){let J=new Pq.Alias($.substring(1));if(J.source==="")Y(w,"BAD_ALIAS","Alias cannot be an empty string");if(J.source.endsWith(":"))Y(w+$.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let D=w+$.length,W=Tq.resolveEnd(X,D,_.strict,Y);if(J.range=[w,D,W.offset],W.comment)J.comment=W.comment;return J}hq.composeEmptyNode=l3;hq.composeNode=W5});var q5=P((cq)=>{var xq=P0(),Q5=G5(),mq=ow(),uq=C0();function lq(_,w,{offset:$,start:X,value:Y,end:J},D){let W=Object.assign({_directives:w},_),G=new xq.Document(void 0,W),Q={atKey:!1,atRoot:!0,directives:G.directives,options:G.options,schema:G.schema},q=uq.resolveProps(X,{indicator:"doc-start",next:Y??J?.[0],offset:$,onError:D,parentIndent:0,startOnNewline:!0});if(q.found){if(G.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!q.hasNewline)D(q.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}G.contents=Y?Q5.composeNode(Q,Y,q,D):Q5.composeEmptyNode(Q,q.end,X,null,q,D);let H=G.contents.range[2],B=mq.resolveEnd(J,H,!1,D);if(B.comment)G.comment=B.comment;return G.range=[$,H,B.offset],G}cq.composeDoc=lq});var c3=P((oq)=>{var pq=$1("process"),iq=n2(),nq=P0(),T0=Z0(),H5=p(),rq=q5(),aq=ow();function I0(_){if(typeof _==="number")return[_,_+1];if(Array.isArray(_))return _.length===2?_:[_[0],_[1]];let{offset:w,source:$}=_;return[w,w+(typeof $==="string"?$.length:1)]}function B5(_){let w="",$=!1,X=!1;for(let Y=0;Y<_.length;++Y){let J=_[Y];switch(J[0]){case"#":w+=(w===""?"":X?`
99
99
 
100
100
  `:`
101
- `)+(J.substring(1)||" "),$=!0,X=!1;break;case"%":if(_[Y+1]?.[0]!=="#")Y+=1;$=!1;break;default:if(!$)X=!0;$=!1}}return{comment:w,afterEmptyLine:X}}class H5{constructor(_={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(w,$,X,Y)=>{let J=I0(w);if(Y)this.warnings.push(new T0.YAMLWarning(J,$,X));else this.errors.push(new T0.YAMLParseError(J,$,X))},this.directives=new cH.Directives({version:_.version||"1.2"}),this.options=_}decorate(_,w){let{comment:$,afterEmptyLine:X}=q5(this.prelude);if($){let Y=_.contents;if(w)_.comment=_.comment?`${_.comment}
102
- ${$}`:$;else if(X||_.directives.docStart||!Y)_.commentBefore=$;else if(G5.isCollection(Y)&&!Y.flow&&Y.items.length>0){let J=Y.items[0];if(G5.isPair(J))J=J.key;let W=J.commentBefore;J.commentBefore=W?`${$}
103
- ${W}`:$}else{let J=Y.commentBefore;Y.commentBefore=J?`${$}
104
- ${J}`:$}}if(w){for(let Y=0;Y<this.errors.length;++Y)_.errors.push(this.errors[Y]);for(let Y=0;Y<this.warnings.length;++Y)_.warnings.push(this.warnings[Y])}else _.errors=this.errors,_.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:q5(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(_,w=!1,$=-1){for(let X of _)yield*this.next(X);yield*this.end(w,$)}*next(_){if(lH.env.LOG_STREAM)console.dir(_,{depth:null});switch(_.type){case"directive":this.directives.add(_.source,(w,$,X)=>{let Y=I0(_);Y[0]+=w,this.onError(Y,"BAD_DIRECTIVE",$,X)}),this.prelude.push(_.source),this.atDirectives=!0;break;case"document":{let w=pH.composeDoc(this.options,this.directives,_,this.onError);if(this.atDirectives&&!w.directives.docStart)this.onError(_,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(w,!1),this.doc)yield this.doc;this.doc=w,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(_.source);break;case"error":{let w=_.source?`${_.message}: ${JSON.stringify(_.source)}`:_.message,$=new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN",w);if(this.atDirectives||!this.doc)this.errors.push($);else this.doc.errors.push($);break}case"doc-end":{if(!this.doc){this.errors.push(new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let w=iH.resolveEnd(_.end,_.offset+_.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),w.comment){let $=this.doc.comment;this.doc.comment=$?`${$}
105
- ${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN",`Unsupported token ${_.type}`))}}*end(_=!1,w=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(_){let $=Object.assign({_directives:this.directives},this.options),X=new dH.Document(void 0,$);if(this.atDirectives)this.onError(w,"MISSING_CHAR","Missing directives-end indicator line");X.range=[0,w,w],this.decorate(X,!1),yield X}}}nH.Composer=H5});var U5=P(($D)=>{var aH=x3(),oH=u3(),sH=Z0(),D5=R0();function tH(_,w=!0,$){if(_){let X=(Y,J,W)=>{let Q=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if($)$(Q,J,W);else throw new sH.YAMLParseError([Q,Q+1],J,W)};switch(_.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return oH.resolveFlowScalar(_,w,X);case"block-scalar":return aH.resolveBlockScalar({options:{strict:w}},_,X)}}return null}function eH(_,w){let{implicitKey:$=!1,indent:X,inFlow:Y=!1,offset:J=-1,type:W="PLAIN"}=w,Q=D5.stringifyString({type:W,value:_},{implicitKey:$,indent:X>0?" ".repeat(X):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}}),G=w.end??[{type:"newline",offset:-1,indent:X,source:`
106
- `}];switch(Q[0]){case"|":case">":{let q=Q.indexOf(`
107
- `),H=Q.substring(0,q),B=Q.substring(q+1)+`
108
- `,D=[{type:"block-scalar-header",offset:J,indent:X,source:H}];if(!B5(D,G))D.push({type:"newline",offset:-1,indent:X,source:`
109
- `});return{type:"block-scalar",offset:J,indent:X,props:D,source:B}}case'"':return{type:"double-quoted-scalar",offset:J,indent:X,source:Q,end:G};case"'":return{type:"single-quoted-scalar",offset:J,indent:X,source:Q,end:G};default:return{type:"scalar",offset:J,indent:X,source:Q,end:G}}}function _D(_,w,$={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:J=!1,type:W}=$,Q="indent"in _?_.indent:null;if(X&&typeof Q==="number")Q+=2;if(!W)switch(_.type){case"single-quoted-scalar":W="QUOTE_SINGLE";break;case"double-quoted-scalar":W="QUOTE_DOUBLE";break;case"block-scalar":{let q=_.props[0];if(q.type!=="block-scalar-header")throw Error("Invalid block scalar header");W=q.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:W="PLAIN"}let G=D5.stringifyString({type:W,value:w},{implicitKey:Y||Q===null,indent:Q!==null&&Q>0?" ".repeat(Q):"",inFlow:J,options:{blockQuote:!0,lineWidth:-1}});switch(G[0]){case"|":case">":wD(_,G);break;case'"':d3(_,G,"double-quoted-scalar");break;case"'":d3(_,G,"single-quoted-scalar");break;default:d3(_,G,"scalar")}}function wD(_,w){let $=w.indexOf(`
101
+ `)+(J.substring(1)||" "),$=!0,X=!1;break;case"%":if(_[Y+1]?.[0]!=="#")Y+=1;$=!1;break;default:if(!$)X=!0;$=!1}}return{comment:w,afterEmptyLine:X}}class U5{constructor(_={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(w,$,X,Y)=>{let J=I0(w);if(Y)this.warnings.push(new T0.YAMLWarning(J,$,X));else this.errors.push(new T0.YAMLParseError(J,$,X))},this.directives=new iq.Directives({version:_.version||"1.2"}),this.options=_}decorate(_,w){let{comment:$,afterEmptyLine:X}=B5(this.prelude);if($){let Y=_.contents;if(w)_.comment=_.comment?`${_.comment}
102
+ ${$}`:$;else if(X||_.directives.docStart||!Y)_.commentBefore=$;else if(H5.isCollection(Y)&&!Y.flow&&Y.items.length>0){let J=Y.items[0];if(H5.isPair(J))J=J.key;let D=J.commentBefore;J.commentBefore=D?`${$}
103
+ ${D}`:$}else{let J=Y.commentBefore;Y.commentBefore=J?`${$}
104
+ ${J}`:$}}if(w){for(let Y=0;Y<this.errors.length;++Y)_.errors.push(this.errors[Y]);for(let Y=0;Y<this.warnings.length;++Y)_.warnings.push(this.warnings[Y])}else _.errors=this.errors,_.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:B5(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(_,w=!1,$=-1){for(let X of _)yield*this.next(X);yield*this.end(w,$)}*next(_){if(pq.env.LOG_STREAM)console.dir(_,{depth:null});switch(_.type){case"directive":this.directives.add(_.source,(w,$,X)=>{let Y=I0(_);Y[0]+=w,this.onError(Y,"BAD_DIRECTIVE",$,X)}),this.prelude.push(_.source),this.atDirectives=!0;break;case"document":{let w=rq.composeDoc(this.options,this.directives,_,this.onError);if(this.atDirectives&&!w.directives.docStart)this.onError(_,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(w,!1),this.doc)yield this.doc;this.doc=w,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(_.source);break;case"error":{let w=_.source?`${_.message}: ${JSON.stringify(_.source)}`:_.message,$=new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN",w);if(this.atDirectives||!this.doc)this.errors.push($);else this.doc.errors.push($);break}case"doc-end":{if(!this.doc){this.errors.push(new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let w=aq.resolveEnd(_.end,_.offset+_.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),w.comment){let $=this.doc.comment;this.doc.comment=$?`${$}
105
+ ${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new T0.YAMLParseError(I0(_),"UNEXPECTED_TOKEN",`Unsupported token ${_.type}`))}}*end(_=!1,w=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(_){let $=Object.assign({_directives:this.directives},this.options),X=new nq.Document(void 0,$);if(this.atDirectives)this.onError(w,"MISSING_CHAR","Missing directives-end indicator line");X.range=[0,w,w],this.decorate(X,!1),yield X}}}oq.Composer=U5});var O5=P((JH)=>{var tq=x3(),eq=u3(),_H=Z0(),z5=R0();function wH(_,w=!0,$){if(_){let X=(Y,J,D)=>{let W=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if($)$(W,J,D);else throw new _H.YAMLParseError([W,W+1],J,D)};switch(_.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return eq.resolveFlowScalar(_,w,X);case"block-scalar":return tq.resolveBlockScalar({options:{strict:w}},_,X)}}return null}function $H(_,w){let{implicitKey:$=!1,indent:X,inFlow:Y=!1,offset:J=-1,type:D="PLAIN"}=w,W=z5.stringifyString({type:D,value:_},{implicitKey:$,indent:X>0?" ".repeat(X):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}}),G=w.end??[{type:"newline",offset:-1,indent:X,source:`
106
+ `}];switch(W[0]){case"|":case">":{let Q=W.indexOf(`
107
+ `),q=W.substring(0,Q),H=W.substring(Q+1)+`
108
+ `,B=[{type:"block-scalar-header",offset:J,indent:X,source:q}];if(!V5(B,G))B.push({type:"newline",offset:-1,indent:X,source:`
109
+ `});return{type:"block-scalar",offset:J,indent:X,props:B,source:H}}case'"':return{type:"double-quoted-scalar",offset:J,indent:X,source:W,end:G};case"'":return{type:"single-quoted-scalar",offset:J,indent:X,source:W,end:G};default:return{type:"scalar",offset:J,indent:X,source:W,end:G}}}function XH(_,w,$={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:J=!1,type:D}=$,W="indent"in _?_.indent:null;if(X&&typeof W==="number")W+=2;if(!D)switch(_.type){case"single-quoted-scalar":D="QUOTE_SINGLE";break;case"double-quoted-scalar":D="QUOTE_DOUBLE";break;case"block-scalar":{let Q=_.props[0];if(Q.type!=="block-scalar-header")throw Error("Invalid block scalar header");D=Q.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:D="PLAIN"}let G=z5.stringifyString({type:D,value:w},{implicitKey:Y||W===null,indent:W!==null&&W>0?" ".repeat(W):"",inFlow:J,options:{blockQuote:!0,lineWidth:-1}});switch(G[0]){case"|":case">":YH(_,G);break;case'"':d3(_,G,"double-quoted-scalar");break;case"'":d3(_,G,"single-quoted-scalar");break;default:d3(_,G,"scalar")}}function YH(_,w){let $=w.indexOf(`
110
110
  `),X=w.substring(0,$),Y=w.substring($+1)+`
111
- `;if(_.type==="block-scalar"){let J=_.props[0];if(J.type!=="block-scalar-header")throw Error("Invalid block scalar header");J.source=X,_.source=Y}else{let{offset:J}=_,W="indent"in _?_.indent:-1,Q=[{type:"block-scalar-header",offset:J,indent:W,source:X}];if(!B5(Q,"end"in _?_.end:void 0))Q.push({type:"newline",offset:-1,indent:W,source:`
112
- `});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:W,props:Q,source:Y})}}function B5(_,w){if(w)for(let $ of w)switch($.type){case"space":case"comment":_.push($);break;case"newline":return _.push($),!0}return!1}function d3(_,w,$){switch(_.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":_.type=$,_.source=w;break;case"block-scalar":{let X=_.props.slice(1),Y=w.length;if(_.props[0].type==="block-scalar-header")Y-=_.props[0].source.length;for(let J of X)J.offset+=Y;delete _.props,Object.assign(_,{type:$,source:w,end:X});break}case"block-map":case"block-seq":{let Y={type:"newline",offset:_.offset+w.length,indent:_.indent,source:`
113
- `};delete _.items,Object.assign(_,{type:$,source:w,end:[Y]});break}default:{let X="indent"in _?_.indent:-1,Y="end"in _&&Array.isArray(_.end)?_.end.filter((J)=>J.type==="space"||J.type==="comment"||J.type==="newline"):[];for(let J of Object.keys(_))if(J!=="type"&&J!=="offset")delete _[J];Object.assign(_,{type:$,indent:X,source:w,end:Y})}}}$D.createScalarToken=eH;$D.resolveAsScalar=tH;$D.setScalarValue=_D});var z5=P((QD)=>{var WD=(_)=>("type"in _)?o2(_):a2(_);function o2(_){switch(_.type){case"block-scalar":{let w="";for(let $ of _.props)w+=o2($);return w+_.source}case"block-map":case"block-seq":{let w="";for(let $ of _.items)w+=a2($);return w}case"flow-collection":{let w=_.start.source;for(let $ of _.items)w+=a2($);for(let $ of _.end)w+=$.source;return w}case"document":{let w=a2(_);if(_.end)for(let $ of _.end)w+=$.source;return w}default:{let w=_.source;if("end"in _&&_.end)for(let $ of _.end)w+=$.source;return w}}}function a2({start:_,key:w,sep:$,value:X}){let Y="";for(let J of _)Y+=J.source;if(w)Y+=o2(w);if($)for(let J of $)Y+=J.source;if(X)Y+=o2(X);return Y}QD.stringify=WD});var A5=P((HD)=>{var p3=Symbol("break visit"),qD=Symbol("skip children"),V5=Symbol("remove item");function Mw(_,w){if("type"in _&&_.type==="document")_={start:_.start,value:_.value};O5(Object.freeze([]),_,w)}Mw.BREAK=p3;Mw.SKIP=qD;Mw.REMOVE=V5;Mw.itemAtPath=(_,w)=>{let $=_;for(let[X,Y]of w){let J=$?.[X];if(J&&"items"in J)$=J.items[Y];else return}return $};Mw.parentCollection=(_,w)=>{let $=Mw.itemAtPath(_,w.slice(0,-1)),X=w[w.length-1][0],Y=$?.[X];if(Y&&"items"in Y)return Y;throw Error("Parent collection not found")};function O5(_,w,$){let X=$(w,_);if(typeof X==="symbol")return X;for(let Y of["key","value"]){let J=w[Y];if(J&&"items"in J){for(let W=0;W<J.items.length;++W){let Q=O5(Object.freeze(_.concat([[Y,W]])),J.items[W],$);if(typeof Q==="number")W=Q-1;else if(Q===p3)return p3;else if(Q===V5)J.items.splice(W,1),W-=1}if(typeof X==="function"&&Y==="key")X=X(w,_)}}return typeof X==="function"?X(w,_):X}HD.visit=Mw});var s2=P((MD)=>{var i3=U5(),BD=z5(),UD=A5(),n3="\uFEFF",r3="\x02",a3="\x18",o3="\x1F",zD=(_)=>!!_&&("items"in _),VD=(_)=>!!_&&(_.type==="scalar"||_.type==="single-quoted-scalar"||_.type==="double-quoted-scalar"||_.type==="block-scalar");function OD(_){switch(_){case n3:return"<BOM>";case r3:return"<DOC>";case a3:return"<FLOW_END>";case o3:return"<SCALAR>";default:return JSON.stringify(_)}}function AD(_){switch(_){case n3:return"byte-order-mark";case r3:return"doc-mode";case a3:return"flow-error-end";case o3:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
111
+ `;if(_.type==="block-scalar"){let J=_.props[0];if(J.type!=="block-scalar-header")throw Error("Invalid block scalar header");J.source=X,_.source=Y}else{let{offset:J}=_,D="indent"in _?_.indent:-1,W=[{type:"block-scalar-header",offset:J,indent:D,source:X}];if(!V5(W,"end"in _?_.end:void 0))W.push({type:"newline",offset:-1,indent:D,source:`
112
+ `});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:D,props:W,source:Y})}}function V5(_,w){if(w)for(let $ of w)switch($.type){case"space":case"comment":_.push($);break;case"newline":return _.push($),!0}return!1}function d3(_,w,$){switch(_.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":_.type=$,_.source=w;break;case"block-scalar":{let X=_.props.slice(1),Y=w.length;if(_.props[0].type==="block-scalar-header")Y-=_.props[0].source.length;for(let J of X)J.offset+=Y;delete _.props,Object.assign(_,{type:$,source:w,end:X});break}case"block-map":case"block-seq":{let Y={type:"newline",offset:_.offset+w.length,indent:_.indent,source:`
113
+ `};delete _.items,Object.assign(_,{type:$,source:w,end:[Y]});break}default:{let X="indent"in _?_.indent:-1,Y="end"in _&&Array.isArray(_.end)?_.end.filter((J)=>J.type==="space"||J.type==="comment"||J.type==="newline"):[];for(let J of Object.keys(_))if(J!=="type"&&J!=="offset")delete _[J];Object.assign(_,{type:$,indent:X,source:w,end:Y})}}}JH.createScalarToken=$H;JH.resolveAsScalar=wH;JH.setScalarValue=XH});var A5=P((qH)=>{var QH=(_)=>("type"in _)?o1(_):a1(_);function o1(_){switch(_.type){case"block-scalar":{let w="";for(let $ of _.props)w+=o1($);return w+_.source}case"block-map":case"block-seq":{let w="";for(let $ of _.items)w+=a1($);return w}case"flow-collection":{let w=_.start.source;for(let $ of _.items)w+=a1($);for(let $ of _.end)w+=$.source;return w}case"document":{let w=a1(_);if(_.end)for(let $ of _.end)w+=$.source;return w}default:{let w=_.source;if("end"in _&&_.end)for(let $ of _.end)w+=$.source;return w}}}function a1({start:_,key:w,sep:$,value:X}){let Y="";for(let J of _)Y+=J.source;if(w)Y+=o1(w);if($)for(let J of $)Y+=J.source;if(X)Y+=o1(X);return Y}qH.stringify=QH});var f5=P((UH)=>{var p3=Symbol("break visit"),BH=Symbol("skip children"),M5=Symbol("remove item");function Rw(_,w){if("type"in _&&_.type==="document")_={start:_.start,value:_.value};R5(Object.freeze([]),_,w)}Rw.BREAK=p3;Rw.SKIP=BH;Rw.REMOVE=M5;Rw.itemAtPath=(_,w)=>{let $=_;for(let[X,Y]of w){let J=$?.[X];if(J&&"items"in J)$=J.items[Y];else return}return $};Rw.parentCollection=(_,w)=>{let $=Rw.itemAtPath(_,w.slice(0,-1)),X=w[w.length-1][0],Y=$?.[X];if(Y&&"items"in Y)return Y;throw Error("Parent collection not found")};function R5(_,w,$){let X=$(w,_);if(typeof X==="symbol")return X;for(let Y of["key","value"]){let J=w[Y];if(J&&"items"in J){for(let D=0;D<J.items.length;++D){let W=R5(Object.freeze(_.concat([[Y,D]])),J.items[D],$);if(typeof W==="number")D=W-1;else if(W===p3)return p3;else if(W===M5)J.items.splice(D,1),D-=1}if(typeof X==="function"&&Y==="key")X=X(w,_)}}return typeof X==="function"?X(w,_):X}UH.visit=Rw});var s1=P((LH)=>{var i3=O5(),VH=A5(),OH=f5(),n3="\uFEFF",r3="\x02",a3="\x18",o3="\x1F",AH=(_)=>!!_&&("items"in _),MH=(_)=>!!_&&(_.type==="scalar"||_.type==="single-quoted-scalar"||_.type==="double-quoted-scalar"||_.type==="block-scalar");function RH(_){switch(_){case n3:return"<BOM>";case r3:return"<DOC>";case a3:return"<FLOW_END>";case o3:return"<SCALAR>";default:return JSON.stringify(_)}}function fH(_){switch(_){case n3:return"byte-order-mark";case r3:return"doc-mode";case a3:return"flow-error-end";case o3:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
114
114
  `:case`\r
115
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(_[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}MD.createScalarToken=i3.createScalarToken;MD.resolveAsScalar=i3.resolveAsScalar;MD.setScalarValue=i3.setScalarValue;MD.stringify=BD.stringify;MD.visit=UD.visit;MD.BOM=n3;MD.DOCUMENT=r3;MD.FLOW_END=a3;MD.SCALAR=o3;MD.isCollection=zD;MD.isScalar=VD;MD.prettyToken=OD;MD.tokenType=AD});var t3=P((kD)=>{var k0=s2();function j_(_){switch(_){case void 0:case" ":case`
116
- `:case"\r":case"\t":return!0;default:return!1}}var M5=new Set("0123456789ABCDEFabcdef"),TD=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),t2=new Set(",[]{}"),ID=new Set(` ,[]{}
117
- \r `),s3=(_)=>!_||ID.has(_);class R5{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(_,w=!1){if(_){if(typeof _!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+_:_,this.lineEndPos=null}this.atEnd=!w;let $=this.next??"stream";while($&&(w||this.hasChars(1)))$=yield*this.parseNext($)}atLineEnd(){let _=this.pos,w=this.buffer[_];while(w===" "||w==="\t")w=this.buffer[++_];if(!w||w==="#"||w===`
115
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(_[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}LH.createScalarToken=i3.createScalarToken;LH.resolveAsScalar=i3.resolveAsScalar;LH.setScalarValue=i3.setScalarValue;LH.stringify=VH.stringify;LH.visit=OH.visit;LH.BOM=n3;LH.DOCUMENT=r3;LH.FLOW_END=a3;LH.SCALAR=o3;LH.isCollection=AH;LH.isScalar=MH;LH.prettyToken=RH;LH.tokenType=fH});var t3=P((yH)=>{var k0=s1();function j_(_){switch(_){case void 0:case" ":case`
116
+ `:case"\r":case"\t":return!0;default:return!1}}var L5=new Set("0123456789ABCDEFabcdef"),gH=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),t1=new Set(",[]{}"),hH=new Set(` ,[]{}
117
+ \r `),s3=(_)=>!_||hH.has(_);class F5{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(_,w=!1){if(_){if(typeof _!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+_:_,this.lineEndPos=null}this.atEnd=!w;let $=this.next??"stream";while($&&(w||this.hasChars(1)))$=yield*this.parseNext($)}atLineEnd(){let _=this.pos,w=this.buffer[_];while(w===" "||w==="\t")w=this.buffer[++_];if(!w||w==="#"||w===`
118
118
  `)return!0;if(w==="\r")return this.buffer[_+1]===`
119
119
  `;return!1}charAt(_){return this.buffer[this.pos+_]}continueScalar(_){let w=this.buffer[_];if(this.indentNext>0){let $=0;while(w===" ")w=this.buffer[++$+_];if(w==="\r"){let X=this.buffer[$+_+1];if(X===`
120
120
  `||!X&&!this.atEnd)return _+$+1}return w===`
@@ -125,17 +125,17 @@ ${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.pus
125
125
  `:_=Y,w=0;break;case"\r":{let J=this.buffer[Y+1];if(!J&&!this.atEnd)return this.setNext("block-scalar");if(J===`
126
126
  `)break}default:break _}if(!$&&!this.atEnd)return this.setNext("block-scalar");if(w>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=w;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let Y=this.continueScalar(_+1);if(Y===-1)break;_=this.buffer.indexOf(`
127
127
  `,Y)}while(_!==-1);if(_===-1){if(!this.atEnd)return this.setNext("block-scalar");_=this.buffer.length}}let X=_+1;$=this.buffer[X];while($===" ")$=this.buffer[++X];if($==="\t"){while($==="\t"||$===" "||$==="\r"||$===`
128
- `)$=this.buffer[++X];_=X-1}else if(!this.blockScalarKeep)do{let Y=_-1,J=this.buffer[Y];if(J==="\r")J=this.buffer[--Y];let W=Y;while(J===" ")J=this.buffer[--Y];if(J===`
129
- `&&Y>=this.pos&&Y+1+w>W)_=Y;else break}while(!0);return yield k0.SCALAR,yield*this.pushToIndex(_+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let _=this.flowLevel>0,w=this.pos-1,$=this.pos-1,X;while(X=this.buffer[++$])if(X===":"){let Y=this.buffer[$+1];if(j_(Y)||_&&t2.has(Y))break;w=$}else if(j_(X)){let Y=this.buffer[$+1];if(X==="\r")if(Y===`
128
+ `)$=this.buffer[++X];_=X-1}else if(!this.blockScalarKeep)do{let Y=_-1,J=this.buffer[Y];if(J==="\r")J=this.buffer[--Y];let D=Y;while(J===" ")J=this.buffer[--Y];if(J===`
129
+ `&&Y>=this.pos&&Y+1+w>D)_=Y;else break}while(!0);return yield k0.SCALAR,yield*this.pushToIndex(_+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let _=this.flowLevel>0,w=this.pos-1,$=this.pos-1,X;while(X=this.buffer[++$])if(X===":"){let Y=this.buffer[$+1];if(j_(Y)||_&&t1.has(Y))break;w=$}else if(j_(X)){let Y=this.buffer[$+1];if(X==="\r")if(Y===`
130
130
  `)$+=1,X=`
131
- `,Y=this.buffer[$+1];else w=$;if(Y==="#"||_&&t2.has(Y))break;if(X===`
132
- `){let J=this.continueScalar($+1);if(J===-1)break;$=Math.max($,J-2)}}else{if(_&&t2.has(X))break;w=$}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield k0.SCALAR,yield*this.pushToIndex(w+1,!0),_?"flow":"doc"}*pushCount(_){if(_>0)return yield this.buffer.substr(this.pos,_),this.pos+=_,_;return 0}*pushToIndex(_,w){let $=this.buffer.slice(this.pos,_);if($)return yield $,this.pos+=$.length,$.length;else if(w)yield"";return 0}*pushIndicators(){let _=0;_:while(!0){switch(this.charAt(0)){case"!":_+=yield*this.pushTag(),_+=yield*this.pushSpaces(!0);continue _;case"&":_+=yield*this.pushUntil(s3),_+=yield*this.pushSpaces(!0);continue _;case"-":case"?":case":":{let w=this.flowLevel>0,$=this.charAt(1);if(j_($)||w&&t2.has($)){if(!w)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;_+=yield*this.pushCount(1),_+=yield*this.pushSpaces(!0);continue _}}}break _}return _}*pushTag(){if(this.charAt(1)==="<"){let _=this.pos+2,w=this.buffer[_];while(!j_(w)&&w!==">")w=this.buffer[++_];return yield*this.pushToIndex(w===">"?_+1:_,!1)}else{let _=this.pos+1,w=this.buffer[_];while(w)if(TD.has(w))w=this.buffer[++_];else if(w==="%"&&M5.has(this.buffer[_+1])&&M5.has(this.buffer[_+2]))w=this.buffer[_+=3];else break;return yield*this.pushToIndex(_,!1)}}*pushNewline(){let _=this.buffer[this.pos];if(_===`
131
+ `,Y=this.buffer[$+1];else w=$;if(Y==="#"||_&&t1.has(Y))break;if(X===`
132
+ `){let J=this.continueScalar($+1);if(J===-1)break;$=Math.max($,J-2)}}else{if(_&&t1.has(X))break;w=$}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield k0.SCALAR,yield*this.pushToIndex(w+1,!0),_?"flow":"doc"}*pushCount(_){if(_>0)return yield this.buffer.substr(this.pos,_),this.pos+=_,_;return 0}*pushToIndex(_,w){let $=this.buffer.slice(this.pos,_);if($)return yield $,this.pos+=$.length,$.length;else if(w)yield"";return 0}*pushIndicators(){let _=0;_:while(!0){switch(this.charAt(0)){case"!":_+=yield*this.pushTag(),_+=yield*this.pushSpaces(!0);continue _;case"&":_+=yield*this.pushUntil(s3),_+=yield*this.pushSpaces(!0);continue _;case"-":case"?":case":":{let w=this.flowLevel>0,$=this.charAt(1);if(j_($)||w&&t1.has($)){if(!w)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;_+=yield*this.pushCount(1),_+=yield*this.pushSpaces(!0);continue _}}}break _}return _}*pushTag(){if(this.charAt(1)==="<"){let _=this.pos+2,w=this.buffer[_];while(!j_(w)&&w!==">")w=this.buffer[++_];return yield*this.pushToIndex(w===">"?_+1:_,!1)}else{let _=this.pos+1,w=this.buffer[_];while(w)if(gH.has(w))w=this.buffer[++_];else if(w==="%"&&L5.has(this.buffer[_+1])&&L5.has(this.buffer[_+2]))w=this.buffer[_+=3];else break;return yield*this.pushToIndex(_,!1)}}*pushNewline(){let _=this.buffer[this.pos];if(_===`
133
133
  `)return yield*this.pushCount(1);else if(_==="\r"&&this.charAt(1)===`
134
- `)return yield*this.pushCount(2);else return 0}*pushSpaces(_){let w=this.pos-1,$;do $=this.buffer[++w];while($===" "||_&&$==="\t");let X=w-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=w;return X}*pushUntil(_){let w=this.pos,$=this.buffer[w];while(!_($))$=this.buffer[++w];return yield*this.pushToIndex(w,!1)}}kD.Lexer=R5});var e3=P((hD)=>{class f5{constructor(){this.lineStarts=[],this.addNewLine=(_)=>this.lineStarts.push(_),this.linePos=(_)=>{let w=0,$=this.lineStarts.length;while(w<$){let Y=w+$>>1;if(this.lineStarts[Y]<_)w=Y+1;else $=Y}if(this.lineStarts[w]===_)return{line:w+1,col:1};if(w===0)return{line:0,col:_};let X=this.lineStarts[w-1];return{line:w,col:_-X+1}}}}hD.LineCounter=f5});var _4=P((mD)=>{var vD=$2("process"),L5=s2(),xD=t3();function Xw(_,w){for(let $=0;$<_.length;++$)if(_[$].type===w)return!0;return!1}function F5(_){for(let w=0;w<_.length;++w)switch(_[w].type){case"space":case"comment":case"newline":break;default:return w}return-1}function N5(_){switch(_?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function e2(_){switch(_.type){case"document":return _.start;case"block-map":{let w=_.items[_.items.length-1];return w.sep??w.start}case"block-seq":return _.items[_.items.length-1].start;default:return[]}}function sw(_){if(_.length===0)return[];let w=_.length;_:while(--w>=0)switch(_[w].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break _}while(_[++w]?.type==="space");return _.splice(w,_.length)}function _1(_,w){if(w.length<1e5)Array.prototype.push.apply(_,w);else for(let $=0;$<w.length;++$)_.push(w[$])}function K5(_){if(_.start.type==="flow-seq-start"){for(let w of _.items)if(w.sep&&!w.value&&!Xw(w.start,"explicit-key-ind")&&!Xw(w.sep,"map-value-ind")){if(w.key)w.value=w.key;if(delete w.key,N5(w.value))if(w.value.end)_1(w.value.end,w.sep);else w.value.end=w.sep;else _1(w.start,w.sep);delete w.sep}}}class b5{constructor(_){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new xD.Lexer,this.onNewLine=_}*parse(_,w=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let $ of this.lexer.lex(_,w))yield*this.next($);if(!w)yield*this.end()}*next(_){if(this.source=_,vD.env.LOG_TOKENS)console.log("|",L5.prettyToken(_));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=_.length;return}let w=L5.tokenType(_);if(!w){let $=`Not a YAML token: ${_}`;yield*this.pop({type:"error",offset:this.offset,message:$,source:_}),this.offset+=_.length}else if(w==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=w,yield*this.step(),w){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+_.length);break;case"space":if(this.atNewLine&&_[0]===" ")this.indent+=_.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=_.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=_.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let _=this.peek(1);if(this.type==="doc-end"&&_?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!_)return yield*this.stream();switch(_.type){case"document":return yield*this.document(_);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(_);case"block-scalar":return yield*this.blockScalar(_);case"block-map":return yield*this.blockMap(_);case"block-seq":return yield*this.blockSequence(_);case"flow-collection":return yield*this.flowCollection(_);case"doc-end":return yield*this.documentEnd(_)}yield*this.pop()}peek(_){return this.stack[this.stack.length-_]}*pop(_){let w=_??this.stack.pop();if(!w)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield w;else{let $=this.peek(1);if(w.type==="block-scalar")w.indent="indent"in $?$.indent:0;else if(w.type==="flow-collection"&&$.type==="document")w.indent=0;if(w.type==="flow-collection")K5(w);switch($.type){case"document":$.value=w;break;case"block-scalar":$.props.push(w);break;case"block-map":{let X=$.items[$.items.length-1];if(X.value){$.items.push({start:[],key:w,sep:[]}),this.onKeyLine=!0;return}else if(X.sep)X.value=w;else{Object.assign(X,{key:w,sep:[]}),this.onKeyLine=!X.explicitKey;return}break}case"block-seq":{let X=$.items[$.items.length-1];if(X.value)$.items.push({start:[],value:w});else X.value=w;break}case"flow-collection":{let X=$.items[$.items.length-1];if(!X||X.value)$.items.push({start:[],key:w,sep:[]});else if(X.sep)X.value=w;else Object.assign(X,{key:w,sep:[]});return}default:yield*this.pop(),yield*this.pop(w)}if(($.type==="document"||$.type==="block-map"||$.type==="block-seq")&&(w.type==="block-map"||w.type==="block-seq")){let X=w.items[w.items.length-1];if(X&&!X.sep&&!X.value&&X.start.length>0&&F5(X.start)===-1&&(w.indent===0||X.start.every((Y)=>Y.type!=="comment"||Y.indent<w.indent))){if($.type==="document")$.end=X.start;else $.items.push({start:X.start});w.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let _={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")_.start.push(this.sourceToken);this.stack.push(_);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(_){if(_.value)return yield*this.lineEnd(_);switch(this.type){case"doc-start":{if(F5(_.start)!==-1)yield*this.pop(),yield*this.step();else _.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":_.start.push(this.sourceToken);return}let w=this.startBlockValue(_);if(w)this.stack.push(w);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(_){if(this.type==="map-value-ind"){let w=e2(this.peek(2)),$=sw(w),X;if(_.end)X=_.end,X.push(this.sourceToken),delete _.end;else X=[this.sourceToken];let Y={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:$,key:_,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}else yield*this.lineEnd(_)}*blockScalar(_){switch(this.type){case"space":case"comment":case"newline":_.props.push(this.sourceToken);return;case"scalar":if(_.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let w=this.source.indexOf(`
134
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces(_){let w=this.pos-1,$;do $=this.buffer[++w];while($===" "||_&&$==="\t");let X=w-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=w;return X}*pushUntil(_){let w=this.pos,$=this.buffer[w];while(!_($))$=this.buffer[++w];return yield*this.pushToIndex(w,!1)}}yH.Lexer=F5});var e3=P((xH)=>{class K5{constructor(){this.lineStarts=[],this.addNewLine=(_)=>this.lineStarts.push(_),this.linePos=(_)=>{let w=0,$=this.lineStarts.length;while(w<$){let Y=w+$>>1;if(this.lineStarts[Y]<_)w=Y+1;else $=Y}if(this.lineStarts[w]===_)return{line:w+1,col:1};if(w===0)return{line:0,col:_};let X=this.lineStarts[w-1];return{line:w,col:_-X+1}}}}xH.LineCounter=K5});var _$=P((cH)=>{var uH=$1("process"),N5=s1(),lH=t3();function Yw(_,w){for(let $=0;$<_.length;++$)if(_[$].type===w)return!0;return!1}function b5(_){for(let w=0;w<_.length;++w)switch(_[w].type){case"space":case"comment":case"newline":break;default:return w}return-1}function E5(_){switch(_?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function e1(_){switch(_.type){case"document":return _.start;case"block-map":{let w=_.items[_.items.length-1];return w.sep??w.start}case"block-seq":return _.items[_.items.length-1].start;default:return[]}}function sw(_){if(_.length===0)return[];let w=_.length;_:while(--w>=0)switch(_[w].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break _}while(_[++w]?.type==="space");return _.splice(w,_.length)}function _2(_,w){if(w.length<1e5)Array.prototype.push.apply(_,w);else for(let $=0;$<w.length;++$)_.push(w[$])}function j5(_){if(_.start.type==="flow-seq-start"){for(let w of _.items)if(w.sep&&!w.value&&!Yw(w.start,"explicit-key-ind")&&!Yw(w.sep,"map-value-ind")){if(w.key)w.value=w.key;if(delete w.key,E5(w.value))if(w.value.end)_2(w.value.end,w.sep);else w.value.end=w.sep;else _2(w.start,w.sep);delete w.sep}}}class S5{constructor(_){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new lH.Lexer,this.onNewLine=_}*parse(_,w=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let $ of this.lexer.lex(_,w))yield*this.next($);if(!w)yield*this.end()}*next(_){if(this.source=_,uH.env.LOG_TOKENS)console.log("|",N5.prettyToken(_));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=_.length;return}let w=N5.tokenType(_);if(!w){let $=`Not a YAML token: ${_}`;yield*this.pop({type:"error",offset:this.offset,message:$,source:_}),this.offset+=_.length}else if(w==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=w,yield*this.step(),w){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+_.length);break;case"space":if(this.atNewLine&&_[0]===" ")this.indent+=_.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=_.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=_.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let _=this.peek(1);if(this.type==="doc-end"&&_?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!_)return yield*this.stream();switch(_.type){case"document":return yield*this.document(_);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(_);case"block-scalar":return yield*this.blockScalar(_);case"block-map":return yield*this.blockMap(_);case"block-seq":return yield*this.blockSequence(_);case"flow-collection":return yield*this.flowCollection(_);case"doc-end":return yield*this.documentEnd(_)}yield*this.pop()}peek(_){return this.stack[this.stack.length-_]}*pop(_){let w=_??this.stack.pop();if(!w)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield w;else{let $=this.peek(1);if(w.type==="block-scalar")w.indent="indent"in $?$.indent:0;else if(w.type==="flow-collection"&&$.type==="document")w.indent=0;if(w.type==="flow-collection")j5(w);switch($.type){case"document":$.value=w;break;case"block-scalar":$.props.push(w);break;case"block-map":{let X=$.items[$.items.length-1];if(X.value){$.items.push({start:[],key:w,sep:[]}),this.onKeyLine=!0;return}else if(X.sep)X.value=w;else{Object.assign(X,{key:w,sep:[]}),this.onKeyLine=!X.explicitKey;return}break}case"block-seq":{let X=$.items[$.items.length-1];if(X.value)$.items.push({start:[],value:w});else X.value=w;break}case"flow-collection":{let X=$.items[$.items.length-1];if(!X||X.value)$.items.push({start:[],key:w,sep:[]});else if(X.sep)X.value=w;else Object.assign(X,{key:w,sep:[]});return}default:yield*this.pop(),yield*this.pop(w)}if(($.type==="document"||$.type==="block-map"||$.type==="block-seq")&&(w.type==="block-map"||w.type==="block-seq")){let X=w.items[w.items.length-1];if(X&&!X.sep&&!X.value&&X.start.length>0&&b5(X.start)===-1&&(w.indent===0||X.start.every((Y)=>Y.type!=="comment"||Y.indent<w.indent))){if($.type==="document")$.end=X.start;else $.items.push({start:X.start});w.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let _={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")_.start.push(this.sourceToken);this.stack.push(_);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(_){if(_.value)return yield*this.lineEnd(_);switch(this.type){case"doc-start":{if(b5(_.start)!==-1)yield*this.pop(),yield*this.step();else _.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":_.start.push(this.sourceToken);return}let w=this.startBlockValue(_);if(w)this.stack.push(w);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(_){if(this.type==="map-value-ind"){let w=e1(this.peek(2)),$=sw(w),X;if(_.end)X=_.end,X.push(this.sourceToken),delete _.end;else X=[this.sourceToken];let Y={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:$,key:_,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}else yield*this.lineEnd(_)}*blockScalar(_){switch(this.type){case"space":case"comment":case"newline":_.props.push(this.sourceToken);return;case"scalar":if(_.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let w=this.source.indexOf(`
135
135
  `)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
136
- `,w)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){_1(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return}if(this.indent>=_.indent){let $=!this.onKeyLine&&this.indent===_.indent,X=$&&(w.sep||w.explicitKey)&&this.type!=="seq-item-ind",Y=[];if(X&&w.sep&&!w.value){let J=[];for(let W=0;W<w.sep.length;++W){let Q=w.sep[W];switch(Q.type){case"newline":J.push(W);break;case"space":break;case"comment":if(Q.indent>_.indent)J.length=0;break;default:J.length=0}}if(J.length>=2)Y=w.sep.splice(J[1])}switch(this.type){case"anchor":case"tag":if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y}),this.onKeyLine=!0;else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"explicit-key-ind":if(!w.sep&&!w.explicitKey)w.start.push(this.sourceToken),w.explicitKey=!0;else if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(w.explicitKey)if(!w.sep)if(Xw(w.start,"newline"))Object.assign(w,{key:null,sep:[this.sourceToken]});else{let J=sw(w.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:null,sep:[this.sourceToken]}]})}else if(w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Xw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]});else if(N5(w.key)&&!Xw(w.sep,"newline")){let J=sw(w.start),W=w.key,Q=w.sep;Q.push(this.sourceToken),delete w.key,delete w.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:W,sep:Q}]})}else if(Y.length>0)w.sep=w.sep.concat(Y,this.sourceToken);else w.sep.push(this.sourceToken);else if(!w.sep)Object.assign(w,{key:null,sep:[this.sourceToken]});else if(w.value||X)_.items.push({start:Y,key:null,sep:[this.sourceToken]});else if(Xw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else w.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let J=this.flowScalar(this.type);if(X||w.value)_.items.push({start:Y,key:J,sep:[]}),this.onKeyLine=!0;else if(w.sep)this.stack.push(J);else Object.assign(w,{key:J,sep:[]}),this.onKeyLine=!0;return}default:{let J=this.startBlockValue(_);if(J){if(J.type==="block-seq"){if(!w.explicitKey&&w.sep&&!Xw(w.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if($)_.items.push({start:Y});this.stack.push(J);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){_1(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return;case"anchor":case"tag":if(w.value||this.indent<=_.indent)break;w.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==_.indent)break;if(w.value||Xw(w.start,"seq-item-ind"))_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return}if(this.indent>_.indent){let $=this.startBlockValue(_);if($){this.stack.push($);return}}yield*this.pop(),yield*this.step()}*flowCollection(_){let w=_.items[_.items.length-1];if(this.type==="flow-error-end"){let $;do yield*this.pop(),$=this.peek(1);while($?.type==="flow-collection")}else if(_.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!w||w.sep)_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return;case"map-value-ind":if(!w||w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else Object.assign(w,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!w||w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!w||w.value)_.items.push({start:[],key:X,sep:[]});else if(w.sep)this.stack.push(X);else Object.assign(w,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":_.end.push(this.sourceToken);return}let $=this.startBlockValue(_);if($)this.stack.push($);else yield*this.pop(),yield*this.step()}else{let $=this.peek(2);if($.type==="block-map"&&(this.type==="map-value-ind"&&$.indent===_.indent||this.type==="newline"&&!$.items[$.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&$.type!=="flow-collection"){let X=e2($),Y=sw(X);K5(_);let J=_.end.splice(1,_.end.length);J.push(this.sourceToken);let W={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:Y,key:_,sep:J}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}else yield*this.lineEnd(_)}}flowScalar(_){if(this.onNewLine){let w=this.source.indexOf(`
136
+ `,w)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){_2(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return}if(this.indent>=_.indent){let $=!this.onKeyLine&&this.indent===_.indent,X=$&&(w.sep||w.explicitKey)&&this.type!=="seq-item-ind",Y=[];if(X&&w.sep&&!w.value){let J=[];for(let D=0;D<w.sep.length;++D){let W=w.sep[D];switch(W.type){case"newline":J.push(D);break;case"space":break;case"comment":if(W.indent>_.indent)J.length=0;break;default:J.length=0}}if(J.length>=2)Y=w.sep.splice(J[1])}switch(this.type){case"anchor":case"tag":if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y}),this.onKeyLine=!0;else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"explicit-key-ind":if(!w.sep&&!w.explicitKey)w.start.push(this.sourceToken),w.explicitKey=!0;else if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(w.explicitKey)if(!w.sep)if(Yw(w.start,"newline"))Object.assign(w,{key:null,sep:[this.sourceToken]});else{let J=sw(w.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:null,sep:[this.sourceToken]}]})}else if(w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Yw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]});else if(E5(w.key)&&!Yw(w.sep,"newline")){let J=sw(w.start),D=w.key,W=w.sep;W.push(this.sourceToken),delete w.key,delete w.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:D,sep:W}]})}else if(Y.length>0)w.sep=w.sep.concat(Y,this.sourceToken);else w.sep.push(this.sourceToken);else if(!w.sep)Object.assign(w,{key:null,sep:[this.sourceToken]});else if(w.value||X)_.items.push({start:Y,key:null,sep:[this.sourceToken]});else if(Yw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else w.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let J=this.flowScalar(this.type);if(X||w.value)_.items.push({start:Y,key:J,sep:[]}),this.onKeyLine=!0;else if(w.sep)this.stack.push(J);else Object.assign(w,{key:J,sep:[]}),this.onKeyLine=!0;return}default:{let J=this.startBlockValue(_);if(J){if(J.type==="block-seq"){if(!w.explicitKey&&w.sep&&!Yw(w.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if($)_.items.push({start:Y});this.stack.push(J);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){_2(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return;case"anchor":case"tag":if(w.value||this.indent<=_.indent)break;w.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==_.indent)break;if(w.value||Yw(w.start,"seq-item-ind"))_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return}if(this.indent>_.indent){let $=this.startBlockValue(_);if($){this.stack.push($);return}}yield*this.pop(),yield*this.step()}*flowCollection(_){let w=_.items[_.items.length-1];if(this.type==="flow-error-end"){let $;do yield*this.pop(),$=this.peek(1);while($?.type==="flow-collection")}else if(_.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!w||w.sep)_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return;case"map-value-ind":if(!w||w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else Object.assign(w,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!w||w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!w||w.value)_.items.push({start:[],key:X,sep:[]});else if(w.sep)this.stack.push(X);else Object.assign(w,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":_.end.push(this.sourceToken);return}let $=this.startBlockValue(_);if($)this.stack.push($);else yield*this.pop(),yield*this.step()}else{let $=this.peek(2);if($.type==="block-map"&&(this.type==="map-value-ind"&&$.indent===_.indent||this.type==="newline"&&!$.items[$.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&$.type!=="flow-collection"){let X=e1($),Y=sw(X);j5(_);let J=_.end.splice(1,_.end.length);J.push(this.sourceToken);let D={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:Y,key:_,sep:J}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=D}else yield*this.lineEnd(_)}}flowScalar(_){if(this.onNewLine){let w=this.source.indexOf(`
137
137
  `)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
138
- `,w)+1}return{type:_,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(_){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let w=e2(_),$=sw(w);return $.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let w=e2(_),$=sw(w);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(_,w){if(this.type!=="comment")return!1;if(this.indent<=w)return!1;return _.every(($)=>$.type==="newline"||$.type==="space")}*documentEnd(_){if(this.type!=="doc-mode"){if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(_){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}mD.Parser=b5});var Z5=P((aD)=>{var j5=c3(),lD=P0(),g0=Z0(),cD=e1(),dD=p(),pD=e3(),E5=_4();function S5(_){let w=_.prettyErrors!==!1;return{lineCounter:_.lineCounter||w&&new pD.LineCounter||null,prettyErrors:w}}function iD(_,w={}){let{lineCounter:$,prettyErrors:X}=S5(w),Y=new E5.Parser($?.addNewLine),J=new j5.Composer(w),W=Array.from(J.compose(Y.parse(_)));if(X&&$)for(let Q of W)Q.errors.forEach(g0.prettifyError(_,$)),Q.warnings.forEach(g0.prettifyError(_,$));if(W.length>0)return W;return Object.assign([],{empty:!0},J.streamInfo())}function P5(_,w={}){let{lineCounter:$,prettyErrors:X}=S5(w),Y=new E5.Parser($?.addNewLine),J=new j5.Composer(w),W=null;for(let Q of J.compose(Y.parse(_),!0,_.length))if(!W)W=Q;else if(W.options.logLevel!=="silent"){W.errors.push(new g0.YAMLParseError(Q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&$)W.errors.forEach(g0.prettifyError(_,$)),W.warnings.forEach(g0.prettifyError(_,$));return W}function nD(_,w,$){let X=void 0;if(typeof w==="function")X=w;else if($===void 0&&w&&typeof w==="object")$=w;let Y=P5(_,$);if(!Y)return null;if(Y.warnings.forEach((J)=>cD.warn(Y.options.logLevel,J)),Y.errors.length>0)if(Y.options.logLevel!=="silent")throw Y.errors[0];else Y.errors=[];return Y.toJS(Object.assign({reviver:X},$))}function rD(_,w,$){let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w;if(typeof $==="string")$=$.length;if(typeof $==="number"){let Y=Math.round($);$=Y<1?void 0:Y>8?{indent:8}:{indent:Y}}if(_===void 0){let{keepUndefined:Y}=$??w??{};if(!Y)return}if(dD.isDocument(_)&&!X)return _.toString($);return new lD.Document(_,X,$).toString($)}aD.parse=nD;aD.parseAllDocuments=iD;aD.parseDocument=P5;aD.stringify=rD});var T5=P((BB)=>{var _B=c3(),wB=P0(),$B=E3(),w4=Z0(),XB=V0(),Yw=p(),YB=e_(),JB=X_(),WB=ww(),QB=$w(),GB=s2(),qB=t3(),HB=e3(),DB=_4(),w1=Z5(),C5=U0();BB.Composer=_B.Composer;BB.Document=wB.Document;BB.Schema=$B.Schema;BB.YAMLError=w4.YAMLError;BB.YAMLParseError=w4.YAMLParseError;BB.YAMLWarning=w4.YAMLWarning;BB.Alias=XB.Alias;BB.isAlias=Yw.isAlias;BB.isCollection=Yw.isCollection;BB.isDocument=Yw.isDocument;BB.isMap=Yw.isMap;BB.isNode=Yw.isNode;BB.isPair=Yw.isPair;BB.isScalar=Yw.isScalar;BB.isSeq=Yw.isSeq;BB.Pair=YB.Pair;BB.Scalar=JB.Scalar;BB.YAMLMap=WB.YAMLMap;BB.YAMLSeq=QB.YAMLSeq;BB.CST=GB;BB.Lexer=qB.Lexer;BB.LineCounter=HB.LineCounter;BB.Parser=DB.Parser;BB.parse=w1.parse;BB.parseAllDocuments=w1.parseAllDocuments;BB.parseDocument=w1.parseDocument;BB.stringify=w1.stringify;BB.visit=C5.visit;BB.visitAsync=C5.visitAsync});var j9=(_)=>_.payload.title?.trim()||`session:${_.payload.id}`;function X2(_){let{store:w,agent:$}=_;return{async session(X){let Y=X.payload.id,J=await x4(w,Y);switch(X.type){case"session.created":{if(J)return{task_id:J.id};let W=j9(X);return{task_id:(await w.createTask({title:W,session_id:Y,owner:$,priority:3})).id}}case"session.idle":{if(!J)return null;if(J.status==="pending"){let W=await w.updateTask(J.id,{status:"in_progress"});return W?{task_id:W.id}:null}return null}case"session.deleted":{if(!J)return null;return await w.updateTask(J.id,{status:"cancelled"}),{task_id:J.id}}case"session.error":case"session.compacted":return await w.appendOperation({task_id:J?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:Y,agent:$}}),null;default:return null}},async tool(X){let Y=X.payload.sessionID,J=await x4(w,Y);if(!J)return await w.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:Y,tool:X.payload.tool}}),{task_id:(await w.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:$,priority:3})).id};let W=E9(X),G=(await w.listTasks({parent_id:J.id,limit:20})).tasks.find((H)=>H.title===W&&Date.now()-new Date(H.created_at).getTime()<60000);if(G)return{task_id:G.id};let q=await w.createTask({title:W,parent_id:J.id,session_id:Y,owner:$,priority:3});return await w.updateTask(q.id,{status:"in_progress"}),{task_id:q.id}},async catchAll(X){try{await w.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:$}})}catch{}}}}async function x4(_,w){return(await _.listTasks({session_id:w,limit:1})).tasks[0]??null}function E9(_){let w=_.payload.tool,$=_.payload.args??{};switch(w){case"write":case"edit":return`${w} ${$.filePath??"?"}`;case"bash":case"shell":{let X=String($.command??$.cmd??"");return`${w} ${X.slice(0,40)}`}case"read":return`read ${$.filePath??"?"}`;default:return`${w} ${JSON.stringify($).slice(0,40)}`}}var R1="Roy \u2014 task-as-first-class-citizen agent. Uses the roy-agent task lifecycle "+"(task_tree \u2192 task_create \u2192 task_update \u2192 task_operation_create \u2192 task_complete) "+"so every piece of work is tracked in the local task store.",f1=`# Roy \u2014 task-first-class-citizen agent
138
+ `,w)+1}return{type:_,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(_){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let w=e1(_),$=sw(w);return $.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let w=e1(_),$=sw(w);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(_,w){if(this.type!=="comment")return!1;if(this.indent<=w)return!1;return _.every(($)=>$.type==="newline"||$.type==="space")}*documentEnd(_){if(this.type!=="doc-mode"){if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(_){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}cH.Parser=S5});var I5=P((tH)=>{var P5=c3(),pH=P0(),g0=Z0(),iH=e2(),nH=p(),rH=e3(),Z5=_$();function C5(_){let w=_.prettyErrors!==!1;return{lineCounter:_.lineCounter||w&&new rH.LineCounter||null,prettyErrors:w}}function aH(_,w={}){let{lineCounter:$,prettyErrors:X}=C5(w),Y=new Z5.Parser($?.addNewLine),J=new P5.Composer(w),D=Array.from(J.compose(Y.parse(_)));if(X&&$)for(let W of D)W.errors.forEach(g0.prettifyError(_,$)),W.warnings.forEach(g0.prettifyError(_,$));if(D.length>0)return D;return Object.assign([],{empty:!0},J.streamInfo())}function T5(_,w={}){let{lineCounter:$,prettyErrors:X}=C5(w),Y=new Z5.Parser($?.addNewLine),J=new P5.Composer(w),D=null;for(let W of J.compose(Y.parse(_),!0,_.length))if(!D)D=W;else if(D.options.logLevel!=="silent"){D.errors.push(new g0.YAMLParseError(W.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&$)D.errors.forEach(g0.prettifyError(_,$)),D.warnings.forEach(g0.prettifyError(_,$));return D}function oH(_,w,$){let X=void 0;if(typeof w==="function")X=w;else if($===void 0&&w&&typeof w==="object")$=w;let Y=T5(_,$);if(!Y)return null;if(Y.warnings.forEach((J)=>iH.warn(Y.options.logLevel,J)),Y.errors.length>0)if(Y.options.logLevel!=="silent")throw Y.errors[0];else Y.errors=[];return Y.toJS(Object.assign({reviver:X},$))}function sH(_,w,$){let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w;if(typeof $==="string")$=$.length;if(typeof $==="number"){let Y=Math.round($);$=Y<1?void 0:Y>8?{indent:8}:{indent:Y}}if(_===void 0){let{keepUndefined:Y}=$??w??{};if(!Y)return}if(nH.isDocument(_)&&!X)return _.toString($);return new pH.Document(_,X,$).toString($)}tH.parse=oH;tH.parseAllDocuments=aH;tH.parseDocument=T5;tH.stringify=sH});var g5=P((VB)=>{var XB=c3(),YB=P0(),JB=E3(),w$=Z0(),DB=V0(),Jw=p(),WB=_w(),GB=X_(),QB=$w(),qB=Xw(),HB=s1(),BB=t3(),UB=e3(),zB=_$(),w2=I5(),k5=U0();VB.Composer=XB.Composer;VB.Document=YB.Document;VB.Schema=JB.Schema;VB.YAMLError=w$.YAMLError;VB.YAMLParseError=w$.YAMLParseError;VB.YAMLWarning=w$.YAMLWarning;VB.Alias=DB.Alias;VB.isAlias=Jw.isAlias;VB.isCollection=Jw.isCollection;VB.isDocument=Jw.isDocument;VB.isMap=Jw.isMap;VB.isNode=Jw.isNode;VB.isPair=Jw.isPair;VB.isScalar=Jw.isScalar;VB.isSeq=Jw.isSeq;VB.Pair=WB.Pair;VB.Scalar=GB.Scalar;VB.YAMLMap=QB.YAMLMap;VB.YAMLSeq=qB.YAMLSeq;VB.CST=HB;VB.Lexer=BB.Lexer;VB.LineCounter=UB.LineCounter;VB.Parser=zB.Parser;VB.parse=w2.parse;VB.parseAllDocuments=w2.parseAllDocuments;VB.parseDocument=w2.parseDocument;VB.stringify=w2.stringify;VB.visit=k5.visit;VB.visitAsync=k5.visitAsync});var EX=(_)=>_.payload.title?.trim()||`session:${_.payload.id}`;function X1(_){let{store:w,agent:$}=_;return{async session(X){let Y=X.payload.id,J=await m$(w,Y);switch(X.type){case"session.created":{if(J)return{task_id:J.id};let D=EX(X);return{task_id:(await w.createTask({title:D,session_id:Y,owner:$,priority:3})).id}}case"session.idle":{if(!J)return null;if(J.status==="pending"){let D=await w.updateTask(J.id,{status:"in_progress"});return D?{task_id:D.id}:null}return null}case"session.deleted":{if(!J)return null;return await w.updateTask(J.id,{status:"cancelled"}),{task_id:J.id}}case"session.error":case"session.compacted":return await w.appendOperation({task_id:J?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:Y,agent:$}}),null;default:return null}},async tool(X){let Y=X.payload.sessionID,J=await m$(w,Y);if(!J)return await w.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:Y,tool:X.payload.tool}}),{task_id:(await w.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:$,priority:3})).id};let D=SX(X),G=(await w.listTasks({parent_id:J.id,limit:20})).tasks.find((q)=>q.title===D&&Date.now()-new Date(q.created_at).getTime()<60000);if(G)return{task_id:G.id};let Q=await w.createTask({title:D,parent_id:J.id,session_id:Y,owner:$,priority:3});return await w.updateTask(Q.id,{status:"in_progress"}),{task_id:Q.id}},async catchAll(X){try{await w.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:$}})}catch{}}}}async function m$(_,w){return(await _.listTasks({session_id:w,limit:1})).tasks[0]??null}function SX(_){let w=_.payload.tool,$=_.payload.args??{};switch(w){case"write":case"edit":return`${w} ${$.filePath??"?"}`;case"bash":case"shell":{let X=String($.command??$.cmd??"");return`${w} ${X.slice(0,40)}`}case"read":return`read ${$.filePath??"?"}`;default:return`${w} ${JSON.stringify($).slice(0,40)}`}}var R2="Roy \u2014 task-as-first-class-citizen agent. Uses the roy-agent task lifecycle "+"(task_tree \u2192 task_create \u2192 task_update \u2192 task_operation_create \u2192 task_complete) "+"so every piece of work is tracked in the local task store.",f2=`# Roy \u2014 task-first-class-citizen agent
139
139
 
140
140
  You are **Roy**, an agent whose defining rule is simple:
141
141
 
@@ -222,7 +222,7 @@ if it is not in the task store, it is not tracked.
222
222
  - Be direct and concrete; the user is reading task titles and milestones.
223
223
  - Report the task id and its state whenever you finish a step.
224
224
  - If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
225
- \`problem\` milestone explaining the blocker instead of going silent.`;var X0="roy",m4={action:"execute",resource:"*",effect:"deny"};function u4(){return{id:X0,mode:"primary",description:R1,system:f1,permissions:[{...m4}]}}function S9(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((Y)=>Y.action===$.action&&Y.resource===$.resource&&Y.effect===$.effect))_.permissions.push({...$})}function L1(_){let w=u4();return _.update(X0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;S9($,w.permissions)}),w}var A={};b9(A,{void:()=>B6,util:()=>l,unknown:()=>H6,union:()=>O6,undefined:()=>Q6,tuple:()=>R6,transformer:()=>P6,symbol:()=>W6,string:()=>o4,strictObject:()=>V6,setErrorMap:()=>C9,set:()=>F6,record:()=>f6,quotelessJson:()=>P9,promise:()=>S6,preprocess:()=>T6,pipeline:()=>I6,ostring:()=>k6,optional:()=>Z6,onumber:()=>g6,oboolean:()=>h6,objectUtil:()=>F1,object:()=>z6,number:()=>s4,nullable:()=>C6,null:()=>G6,never:()=>D6,nativeEnum:()=>E6,nan:()=>X6,map:()=>L6,makeIssue:()=>Y0,literal:()=>b6,lazy:()=>N6,late:()=>w6,isValid:()=>d_,isDirty:()=>J2,isAsync:()=>jw,isAborted:()=>Y2,intersection:()=>M6,instanceof:()=>$6,getParsedType:()=>Z_,getErrorMap:()=>bw,function:()=>K6,enum:()=>j6,effect:()=>P6,discriminatedUnion:()=>A6,defaultErrorMap:()=>y_,datetimeRegex:()=>n4,date:()=>J6,custom:()=>a4,coerce:()=>y6,boolean:()=>t4,bigint:()=>Y6,array:()=>U6,any:()=>q6,addIssueToContext:()=>S,ZodVoid:()=>W0,ZodUnknown:()=>p_,ZodUnion:()=>Tw,ZodUndefined:()=>Zw,ZodType:()=>x,ZodTuple:()=>T_,ZodTransformer:()=>K_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>Q0,ZodReadonly:()=>xw,ZodPromise:()=>Dw,ZodPipeline:()=>H0,ZodParsedType:()=>E,ZodOptional:()=>L_,ZodObject:()=>t,ZodNumber:()=>i_,ZodNullable:()=>x_,ZodNull:()=>Cw,ZodNever:()=>C_,ZodNativeEnum:()=>hw,ZodNaN:()=>q0,ZodMap:()=>G0,ZodLiteral:()=>gw,ZodLazy:()=>kw,ZodIssueCode:()=>L,ZodIntersection:()=>Iw,ZodFunction:()=>Sw,ZodFirstPartyTypeKind:()=>K,ZodError:()=>W_,ZodEnum:()=>r_,ZodEffects:()=>K_,ZodDiscriminatedUnion:()=>W2,ZodDefault:()=>yw,ZodDate:()=>Gw,ZodCatch:()=>vw,ZodBranded:()=>Q2,ZodBoolean:()=>Pw,ZodBigInt:()=>n_,ZodArray:()=>f_,ZodAny:()=>qw,Schema:()=>x,ParseStatus:()=>Q_,OK:()=>G_,NEVER:()=>v6,INVALID:()=>I,EMPTY_PATH:()=>T9,DIRTY:()=>Qw,BRAND:()=>_6});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let W of Y)J[W]=W;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((Q)=>typeof Y[Y[Q]]!=="number"),W={};for(let Q of J)W[Q]=Y[Q];return _.objectValues(W)},_.objectValues=(Y)=>{return _.objectKeys(Y).map(function(J){return Y[J]})},_.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let J=[];for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))J.push(W);return J},_.find=(Y,J)=>{for(let W of Y)if(J(W))return W;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var F1;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(F1||(F1={}));var E=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z_=(_)=>{switch(typeof _){case"undefined":return E.undefined;case"string":return E.string;case"number":return Number.isNaN(_)?E.nan:E.number;case"boolean":return E.boolean;case"function":return E.function;case"bigint":return E.bigint;case"symbol":return E.symbol;case"object":if(Array.isArray(_))return E.array;if(_===null)return E.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return E.promise;if(typeof Map<"u"&&_ instanceof Map)return E.map;if(typeof Set<"u"&&_ instanceof Set)return E.set;if(typeof Date<"u"&&_ instanceof Date)return E.date;return E.object;default:return E.unknown}};var L=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),P9=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class W_ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=_}format(_){let w=_||function(Y){return Y.message},$={_errors:[]},X=(Y)=>{for(let J of Y.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)$._errors.push(w(J));else{let W=$,Q=0;while(Q<J.path.length){let G=J.path[Q];if(Q!==J.path.length-1)W[G]=W[G]||{_errors:[]};else W[G]=W[G]||{_errors:[]},W[G]._errors.push(w(J));W=W[G],Q++}}};return X(this),$}static assert(_){if(!(_ instanceof W_))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(w)=>w.message){let w={},$=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];w[Y]=w[Y]||[],w[Y].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}W_.create=(_)=>{return new W_(_)};var Z9=(_,w)=>{let $;switch(_.code){case L.invalid_type:if(_.received===E.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case L.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case L.invalid_union:$="Invalid input";break;case L.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case L.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case L.invalid_arguments:$="Invalid function arguments";break;case L.invalid_return_type:$="Invalid function return type";break;case L.invalid_date:$="Invalid date";break;case L.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if($=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)$=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)$=`Invalid input: must end with "${_.validation.endsWith}"`;else l.assertNever(_.validation);else if(_.validation!=="regex")$=`Invalid ${_.validation}`;else $="Invalid";break;case L.too_small:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else $="Invalid input";break;case L.too_big:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")$=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else $="Invalid input";break;case L.custom:$="Invalid input";break;case L.invalid_intersection_types:$="Intersection results could not be merged";break;case L.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case L.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},y_=Z9;var l4=y_;function C9(_){l4=_}function bw(){return l4}var Y0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],W={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let Q="",G=X.filter((q)=>!!q).slice().reverse();for(let q of G)Q=q(W,{data:w,defaultError:Q}).message;return{...Y,path:J,message:Q}},T9=[];function S(_,w){let $=bw(),X=Y0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===y_?void 0:y_].filter((Y)=>!!Y)});_.common.issues.push(X)}class Q_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,w){let $=[];for(let X of w){if(X.status==="aborted")return I;if(X.status==="dirty")_.dirty();$.push(X.value)}return{status:_.value,value:$}}static async mergeObjectAsync(_,w){let $=[];for(let X of w){let Y=await X.key,J=await X.value;$.push({key:Y,value:J})}return Q_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:Y,value:J}=X;if(Y.status==="aborted")return I;if(J.status==="aborted")return I;if(Y.status==="dirty")_.dirty();if(J.status==="dirty")_.dirty();if(Y.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))$[Y.value]=J.value}return{status:_.value,value:$}}}var I=Object.freeze({status:"aborted"}),Qw=(_)=>({status:"dirty",value:_}),G_=(_)=>({status:"valid",value:_}),Y2=(_)=>_.status==="aborted",J2=(_)=>_.status==="dirty",d_=(_)=>_.status==="valid",jw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var Z;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(Z||(Z={}));class F_{constructor(_,w,$,X){this._cachedPath=[],this.parent=_,this.data=w,this._path=$,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var c4=(_,w)=>{if(d_(w))return{success:!0,data:w.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new W_(_.common.issues);return this._error=$,this._error}}}};function g(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:Y}=_;if(w&&($||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:Y};return{errorMap:(W,Q)=>{let{message:G}=_;if(W.code==="invalid_enum_value")return{message:G??Q.defaultError};if(typeof Q.data>"u")return{message:G??X??Q.defaultError};if(W.code!=="invalid_type")return{message:Q.defaultError};return{message:G??$??Q.defaultError}},description:Y}}class x{get description(){return this._def.description}_getType(_){return Z_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new Q_,ctx:{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(jw(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync(_){let w=this._parse(_);return Promise.resolve(w)}parse(_,w){let $=this.safeParse(_,w);if($.success)return $.data;throw $.error}safeParse(_,w){let $={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return c4($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return d_($)?{value:$.value}:{issues:w.common.issues}}catch($){if($?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:w}).then(($)=>d_($)?{value:$.value}:{issues:w.common.issues})}async parseAsync(_,w){let $=await this.safeParseAsync(_,w);if($.success)return $.data;throw $.error}async safeParseAsync(_,w){let $={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parse({data:_,path:$.path,parent:$}),Y=await(jw(X)?X:Promise.resolve(X));return c4($,Y)}refine(_,w){let $=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,Y)=>{let J=_(X),W=()=>Y.addIssue({code:L.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((Q)=>{if(!Q)return W(),!1;else return!0});if(!J)return W(),!1;else return!0})}refinement(_,w){return this._refinement(($,X)=>{if(!_($))return X.addIssue(typeof w==="function"?w($,X):w),!1;else return!0})}_refinement(_){return new K_({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(w)=>this["~validate"](w)}}optional(){return L_.create(this,this._def)}nullable(){return x_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f_.create(this)}promise(){return Dw.create(this,this._def)}or(_){return Tw.create([this,_],this._def)}and(_){return Iw.create(this,_,this._def)}transform(_){return new K_({...g(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new yw({...g(this._def),innerType:this,defaultValue:w,typeName:K.ZodDefault})}brand(){return new Q2({typeName:K.ZodBranded,type:this,...g(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new vw({...g(this._def),innerType:this,catchValue:w,typeName:K.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return H0.create(this,_)}readonly(){return xw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var I9=/^c[^\s-]{8,}$/i,k9=/^[0-9a-z]+$/,g9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,h9=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,y9=/^[a-z0-9_-]{21}$/i,v9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,x9=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,m9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,u9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K1,l9=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,c9=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,d9=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,p9=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,i9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p4="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",r9=new RegExp(`^${p4}$`);function i4(_){let w="[0-5]\\d";if(_.precision)w=`${w}\\.\\d{${_.precision}}`;else if(_.precision==null)w=`${w}(\\.\\d+)?`;let $=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${$}`}function a9(_){return new RegExp(`^${i4(_)}$`)}function n4(_){let w=`${p4}T${i4(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function o9(_,w){if((w==="v4"||!w)&&l9.test(_))return!0;if((w==="v6"||!w)&&d9.test(_))return!0;return!1}function s9(_,w){if(!v9.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(w&&Y.alg!==w)return!1;return!0}catch{return!1}}function t9(_,w){if((w==="v4"||!w)&&c9.test(_))return!0;if((w==="v6"||!w)&&p9.test(_))return!0;return!1}class R_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==E.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.string,received:Y.parsedType}),I}let $=new Q_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.length<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:L.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="max"){if(_.data.length>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:L.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="length"){let J=_.data.length>Y.value,W=_.data.length<Y.value;if(J||W){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:L.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)S(X,{code:L.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!m9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!K1)K1=new RegExp(u9,"u");if(!K1.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!h9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!y9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!I9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!k9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!g9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),S(X,{validation:"url",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"regex",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="trim")_.data=_.data.trim();else if(Y.kind==="includes"){if(!_.data.includes(Y.value,Y.position))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),$.dirty()}else if(Y.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(Y.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(Y.kind==="startsWith"){if(!_.data.startsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:{startsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="endsWith"){if(!_.data.endsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!n4(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!r9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!a9(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!x9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!o9(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!s9(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!t9(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!i9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!n9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:L.invalid_string,message:Y.message}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:L.invalid_string,...Z.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...Z.errToObj(_)})}url(_){return this._addCheck({kind:"url",...Z.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...Z.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...Z.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...Z.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...Z.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...Z.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...Z.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...Z.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...Z.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...Z.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...Z.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...Z.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...Z.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...Z.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...Z.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...Z.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...Z.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...Z.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...Z.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...Z.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...Z.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...Z.errToObj(w)})}nonempty(_){return this.min(1,Z.errToObj(_))}trim(){return new R_({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxLength(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}R_.create=(_)=>{return new R_({checks:[],typeName:K.ZodString,coerce:_?.coerce??!1,...g(_)})};function e9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),W=Number.parseInt(w.toFixed(Y).replace(".",""));return J%W/10**Y}class i_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==E.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.number,received:Y.parsedType}),I}let $=void 0,X=new Q_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:L.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:L.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:L.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(e9(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:L.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:L.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new i_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new i_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:Z.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:Z.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.toString(_)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&l.isInteger(_.value))}get isFinite(){let _=null,w=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(w===null||$.value>w)w=$.value}else if($.kind==="max"){if(_===null||$.value<_)_=$.value}return Number.isFinite(w)&&Number.isFinite(_)}}i_.create=(_)=>{return new i_({checks:[],typeName:K.ZodNumber,coerce:_?.coerce||!1,...g(_)})};class n_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==E.bigint)return this._getInvalidInput(_);let $=void 0,X=new Q_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:L.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:L.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_.data%Y.value!==BigInt(0))$=this._getOrReturnCtx(_,$),S($,{code:L.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return S(w,{code:L.invalid_type,expected:E.bigint,received:w.parsedType}),I}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new n_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new n_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.toString(w)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}n_.create=(_)=>{return new n_({checks:[],typeName:K.ZodBigInt,coerce:_?.coerce??!1,...g(_)})};class Pw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==E.boolean){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.boolean,received:$.parsedType}),I}return G_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:K.ZodBoolean,coerce:_?.coerce||!1,...g(_)})};class Gw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==E.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.date,received:Y.parsedType}),I}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_date}),I}let $=new Q_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.getTime()<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:L.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),$.dirty()}else if(Y.kind==="max"){if(_.data.getTime()>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:L.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new Gw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:Z.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:Z.toString(w)})}get minDate(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _!=null?new Date(_):null}}Gw.create=(_)=>{return new Gw({checks:[],coerce:_?.coerce||!1,typeName:K.ZodDate,...g(_)})};class J0 extends x{_parse(_){if(this._getType(_)!==E.symbol){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.symbol,received:$.parsedType}),I}return G_(_.data)}}J0.create=(_)=>{return new J0({typeName:K.ZodSymbol,...g(_)})};class Zw extends x{_parse(_){if(this._getType(_)!==E.undefined){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.undefined,received:$.parsedType}),I}return G_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:K.ZodUndefined,...g(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==E.null){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.null,received:$.parsedType}),I}return G_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:K.ZodNull,...g(_)})};class qw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return G_(_.data)}}qw.create=(_)=>{return new qw({typeName:K.ZodAny,...g(_)})};class p_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return G_(_.data)}}p_.create=(_)=>{return new p_({typeName:K.ZodUnknown,...g(_)})};class C_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:L.invalid_type,expected:E.never,received:w.parsedType}),I}}C_.create=(_)=>{return new C_({typeName:K.ZodNever,...g(_)})};class W0 extends x{_parse(_){if(this._getType(_)!==E.undefined){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.void,received:$.parsedType}),I}return G_(_.data)}}W0.create=(_)=>{return new W0({typeName:K.ZodVoid,...g(_)})};class f_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==E.array)return S(w,{code:L.invalid_type,expected:E.array,received:w.parsedType}),I;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,W=w.data.length<X.exactLength.value;if(J||W)S(w,{code:J?L.too_big:L.too_small,minimum:W?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),$.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)S(w,{code:L.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),$.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)S(w,{code:L.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),$.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,W)=>{return X.type._parseAsync(new F_(w,J,w.path,W))})).then((J)=>{return Q_.mergeArray($,J)});let Y=[...w.data].map((J,W)=>{return X.type._parseSync(new F_(w,J,w.path,W))});return Q_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new f_({...this._def,minLength:{value:_,message:Z.toString(w)}})}max(_,w){return new f_({...this._def,maxLength:{value:_,message:Z.toString(w)}})}length(_,w){return new f_({...this._def,exactLength:{value:_,message:Z.toString(w)}})}nonempty(_){return this.min(1,_)}}f_.create=(_,w)=>{return new f_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...g(w)})};function Ew(_){if(_ instanceof t){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=L_.create(Ew(X))}return new t({..._._def,shape:()=>w})}else if(_ instanceof f_)return new f_({..._._def,type:Ew(_.element)});else if(_ instanceof L_)return L_.create(Ew(_.unwrap()));else if(_ instanceof x_)return x_.create(Ew(_.unwrap()));else if(_ instanceof T_)return T_.create(_.items.map((w)=>Ew(w)));else return _}class t extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),w=l.objectKeys(_);return this._cached={shape:_,keys:w},this._cached}_parse(_){if(this._getType(_)!==E.object){let G=this._getOrReturnCtx(_);return S(G,{code:L.invalid_type,expected:E.object,received:G.parsedType}),I}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),W=[];if(!(this._def.catchall instanceof C_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))W.push(G)}let Q=[];for(let G of J){let q=Y[G],H=X.data[G];Q.push({key:{status:"valid",value:G},value:q._parse(new F_(X,H,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof C_){let G=this._def.unknownKeys;if(G==="passthrough")for(let q of W)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:X.data[q]}});else if(G==="strict"){if(W.length>0)S(X,{code:L.unrecognized_keys,keys:W}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let q of W){let H=X.data[q];Q.push({key:{status:"valid",value:q},value:G._parse(new F_(X,H,X.path,q)),alwaysSet:q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let q of Q){let H=await q.key,B=await q.value;G.push({key:H,value:B,alwaysSet:q.alwaysSet})}return G}).then((G)=>{return Q_.mergeObjectSync($,G)});else return Q_.mergeObjectSync($,Q)}get shape(){return this._def.shape()}strict(_){return Z.errToObj,new t({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message:Z.errToObj(_).message??X};return{message:X}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(_){return new t({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new t({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:K.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new t({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}deepPartial(){return Ew(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new t({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let Y=this.shape[$];while(Y instanceof L_)Y=Y._def.innerType;w[$]=Y}return new t({...this._def,shape:()=>w})}keyof(){return r4(l.objectKeys(this.shape))}}t.create=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.strictCreate=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strict",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.lazycreate=(_,w)=>{return new t({shape:_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};class Tw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(Y){for(let W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return w.common.issues.push(...W.ctx.common.issues),W.result;let J=Y.map((W)=>new W_(W.ctx.common.issues));return S(w,{code:L.invalid_union,unionErrors:J}),I}if(w.common.async)return Promise.all($.map(async(Y)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let Y=void 0,J=[];for(let Q of $){let G={...w,common:{...w.common,issues:[]},parent:null},q=Q._parseSync({data:w.data,path:w.path,parent:G});if(q.status==="valid")return q;else if(q.status==="dirty"&&!Y)Y={result:q,ctx:G};if(G.common.issues.length)J.push(G.common.issues)}if(Y)return w.common.issues.push(...Y.ctx.common.issues),Y.result;let W=J.map((Q)=>new W_(Q));return S(w,{code:L.invalid_union,unionErrors:W}),I}}get options(){return this._def.options}}Tw.create=(_,w)=>{return new Tw({options:_,typeName:K.ZodUnion,...g(w)})};var v_=(_)=>{if(_ instanceof kw)return v_(_.schema);else if(_ instanceof K_)return v_(_.innerType());else if(_ instanceof gw)return[_.value];else if(_ instanceof r_)return _.options;else if(_ instanceof hw)return l.objectValues(_.enum);else if(_ instanceof yw)return v_(_._def.innerType);else if(_ instanceof Zw)return[void 0];else if(_ instanceof Cw)return[null];else if(_ instanceof L_)return[void 0,...v_(_.unwrap())];else if(_ instanceof x_)return[null,...v_(_.unwrap())];else if(_ instanceof Q2)return v_(_.unwrap());else if(_ instanceof xw)return v_(_.unwrap());else if(_ instanceof vw)return v_(_._def.innerType);else return[]};class W2 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==E.object)return S(w,{code:L.invalid_type,expected:E.object,received:w.parsedType}),I;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),I;if(w.common.async)return Y._parseAsync({data:w.data,path:w.path,parent:w});else return Y._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,w,$){let X=new Map;for(let Y of w){let J=v_(Y.shape[_]);if(!J.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let W of J){if(X.has(W))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(W)}`);X.set(W,Y)}}return new W2({typeName:K.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...g($)})}}function N1(_,w){let $=Z_(_),X=Z_(w);if(_===w)return{valid:!0,data:_};else if($===E.object&&X===E.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((Q)=>Y.indexOf(Q)!==-1),W={..._,...w};for(let Q of J){let G=N1(_[Q],w[Q]);if(!G.valid)return{valid:!1};W[Q]=G.data}return{valid:!0,data:W}}else if($===E.array&&X===E.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let W=_[J],Q=w[J],G=N1(W,Q);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===E.date&&X===E.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class Iw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(Y,J)=>{if(Y2(Y)||Y2(J))return I;let W=N1(Y.value,J.value);if(!W.valid)return S($,{code:L.invalid_intersection_types}),I;if(J2(Y)||J2(J))w.dirty();return{status:w.value,value:W.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([Y,J])=>X(Y,J));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}Iw.create=(_,w,$)=>{return new Iw({left:_,right:w,typeName:K.ZodIntersection,...g($)})};class T_ extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==E.array)return S($,{code:L.invalid_type,expected:E.array,received:$.parsedType}),I;if($.data.length<this._def.items.length)return S($,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&$.data.length>this._def.items.length)S($,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,W)=>{let Q=this._def.items[W]||this._def.rest;if(!Q)return null;return Q._parse(new F_($,J,$.path,W))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return Q_.mergeArray(w,J)});else return Q_.mergeArray(w,Y)}get items(){return this._def.items}rest(_){return new T_({...this._def,rest:_})}}T_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new T_({items:_,typeName:K.ZodTuple,rest:null,...g(w)})};class Q0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==E.object)return S($,{code:L.invalid_type,expected:E.object,received:$.parsedType}),I;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let W in $.data)X.push({key:Y._parse(new F_($,W,$.path,W)),value:J._parse(new F_($,$.data[W],$.path,W)),alwaysSet:W in $.data});if($.common.async)return Q_.mergeObjectAsync(w,X);else return Q_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new Q0({keyType:_,valueType:w,typeName:K.ZodRecord,...g($)});return new Q0({keyType:R_.create(),valueType:_,typeName:K.ZodRecord,...g(w)})}}class G0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==E.map)return S($,{code:L.invalid_type,expected:E.map,received:$.parsedType}),I;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([W,Q],G)=>{return{key:X._parse(new F_($,W,$.path,[G,"key"])),value:Y._parse(new F_($,Q,$.path,[G,"value"]))}});if($.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let Q of J){let G=await Q.key,q=await Q.value;if(G.status==="aborted"||q.status==="aborted")return I;if(G.status==="dirty"||q.status==="dirty")w.dirty();W.set(G.value,q.value)}return{status:w.value,value:W}})}else{let W=new Map;for(let Q of J){let{key:G,value:q}=Q;if(G.status==="aborted"||q.status==="aborted")return I;if(G.status==="dirty"||q.status==="dirty")w.dirty();W.set(G.value,q.value)}return{status:w.value,value:W}}}}G0.create=(_,w,$)=>{return new G0({valueType:w,keyType:_,typeName:K.ZodMap,...g($)})};class Hw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==E.set)return S($,{code:L.invalid_type,expected:E.set,received:$.parsedType}),I;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:L.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if($.data.size>X.maxSize.value)S($,{code:L.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let Y=this._def.valueType;function J(Q){let G=new Set;for(let q of Q){if(q.status==="aborted")return I;if(q.status==="dirty")w.dirty();G.add(q.value)}return{status:w.value,value:G}}let W=[...$.data.values()].map((Q,G)=>Y._parse(new F_($,Q,$.path,G)));if($.common.async)return Promise.all(W).then((Q)=>J(Q));else return J(W)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:Z.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:Z.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Hw.create=(_,w)=>{return new Hw({valueType:_,minSize:null,maxSize:null,typeName:K.ZodSet,...g(w)})};class Sw extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==E.function)return S(w,{code:L.invalid_type,expected:E.function,received:w.parsedType}),I;function $(W,Q){return Y0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:L.invalid_arguments,argumentsError:Q}})}function X(W,Q){return Y0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:L.invalid_return_type,returnTypeError:Q}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Dw){let W=this;return G_(async function(...Q){let G=new W_([]),q=await W._def.args.parseAsync(Q,Y).catch((D)=>{throw G.addIssue($(Q,D)),G}),H=await Reflect.apply(J,this,q);return await W._def.returns._def.type.parseAsync(H,Y).catch((D)=>{throw G.addIssue(X(H,D)),G})})}else{let W=this;return G_(function(...Q){let G=W._def.args.safeParse(Q,Y);if(!G.success)throw new W_([$(Q,G.error)]);let q=Reflect.apply(J,this,G.data),H=W._def.returns.safeParse(q,Y);if(!H.success)throw new W_([X(q,H.error)]);return H.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Sw({...this._def,args:T_.create(_).rest(p_.create())})}returns(_){return new Sw({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Sw({args:_?_:T_.create([]).rest(p_.create()),returns:w||p_.create(),typeName:K.ZodFunction,...g($)})}}class kw extends x{get schema(){return this._def.getter()}_parse(_){let{ctx:w}=this._processInputParams(_);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}}kw.create=(_,w)=>{return new kw({getter:_,typeName:K.ZodLazy,...g(w)})};class gw extends x{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return S(w,{received:w.data,code:L.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:_.data}}get value(){return this._def.value}}gw.create=(_,w)=>{return new gw({value:_,typeName:K.ZodLiteral,...g(w)})};function r4(_,w){return new r_({values:_,typeName:K.ZodEnum,...g(w)})}class r_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:L.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{received:w.data,code:L.invalid_enum_value,options:$}),I}return G_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let w of this._def.values)_[w]=w;return _}get Values(){let _={};for(let w of this._def.values)_[w]=w;return _}get Enum(){let _={};for(let w of this._def.values)_[w]=w;return _}extract(_,w=this._def){return r_.create(_,{...this._def,...w})}exclude(_,w=this._def){return r_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}r_.create=r4;class hw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==E.string&&$.parsedType!==E.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:L.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:L.invalid_enum_value,options:X}),I}return G_(_.data)}get enum(){return this._def.values}}hw.create=(_,w)=>{return new hw({values:_,typeName:K.ZodNativeEnum,...g(w)})};class Dw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==E.promise&&w.common.async===!1)return S(w,{code:L.invalid_type,expected:E.promise,received:w.parsedType}),I;let $=w.parsedType===E.promise?w.data:Promise.resolve(w.data);return G_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Dw.create=(_,w)=>{return new Dw({type:_,typeName:K.ZodPromise,...g(w)})};class K_ extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=this._def.effect||null,Y={addIssue:(J)=>{if(S($,J),J.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let J=X.transform($.data,Y);if($.common.async)return Promise.resolve(J).then(async(W)=>{if(w.value==="aborted")return I;let Q=await this._def.schema._parseAsync({data:W,path:$.path,parent:$});if(Q.status==="aborted")return I;if(Q.status==="dirty")return Qw(Q.value);if(w.value==="dirty")return Qw(Q.value);return Q});else{if(w.value==="aborted")return I;let W=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")return Qw(W.value);if(w.value==="dirty")return Qw(W.value);return W}}if(X.type==="refinement"){let J=(W)=>{let Q=X.refinement(W,Y);if($.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if($.common.async===!1){let W=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")w.dirty();return J(W.value),{status:w.value,value:W.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((W)=>{if(W.status==="aborted")return I;if(W.status==="dirty")w.dirty();return J(W.value).then(()=>{return{status:w.value,value:W.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!d_(J))return I;let W=X.transform(J.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:W}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!d_(J))return I;return Promise.resolve(X.transform(J.value,Y)).then((W)=>({status:w.value,value:W}))});l.assertNever(X)}}K_.create=(_,w,$)=>{return new K_({schema:_,typeName:K.ZodEffects,effect:w,...g($)})};K_.createWithPreprocess=(_,w,$)=>{return new K_({schema:w,effect:{type:"preprocess",transform:_},typeName:K.ZodEffects,...g($)})};class L_ extends x{_parse(_){if(this._getType(_)===E.undefined)return G_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}L_.create=(_,w)=>{return new L_({innerType:_,typeName:K.ZodOptional,...g(w)})};class x_ extends x{_parse(_){if(this._getType(_)===E.null)return G_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}x_.create=(_,w)=>{return new x_({innerType:_,typeName:K.ZodNullable,...g(w)})};class yw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===E.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}yw.create=(_,w)=>{return new yw({innerType:_,typeName:K.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...g(w)})};class vw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(jw(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new W_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new W_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:K.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...g(w)})};class q0 extends x{_parse(_){if(this._getType(_)!==E.nan){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.nan,received:$.parsedType}),I}return{status:"valid",value:_.data}}}q0.create=(_)=>{return new q0({typeName:K.ZodNaN,...g(_)})};var _6=Symbol("zod_brand");class Q2 extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;return this._def.type._parse({data:$,path:w.path,parent:w})}unwrap(){return this._def.type}}class H0 extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(Y.status==="aborted")return I;if(Y.status==="dirty")return w.dirty(),Qw(Y.value);else return this._def.out._parseAsync({data:Y.value,path:$.path,parent:$})})();else{let X=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(X.status==="aborted")return I;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:$.path,parent:$})}}static create(_,w){return new H0({in:_,out:w,typeName:K.ZodPipeline})}}class xw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(d_(X))X.value=Object.freeze(X.value);return X};return jw(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}xw.create=(_,w)=>{return new xw({innerType:_,typeName:K.ZodReadonly,...g(w)})};function d4(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function a4(_,w={},$){if(_)return qw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((W)=>{if(!W){let Q=d4(w,X),G=Q.fatal??$??!0;Y.addIssue({code:"custom",...Q,fatal:G})}});if(!J){let W=d4(w,X),Q=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:Q})}return});return qw.create()}var w6={object:t.lazycreate},K;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(K||(K={}));var $6=(_,w={message:`Input not instance of ${_.name}`})=>a4(($)=>$ instanceof _,w),o4=R_.create,s4=i_.create,X6=q0.create,Y6=n_.create,t4=Pw.create,J6=Gw.create,W6=J0.create,Q6=Zw.create,G6=Cw.create,q6=qw.create,H6=p_.create,D6=C_.create,B6=W0.create,U6=f_.create,z6=t.create,V6=t.strictCreate,O6=Tw.create,A6=W2.create,M6=Iw.create,R6=T_.create,f6=Q0.create,L6=G0.create,F6=Hw.create,K6=Sw.create,N6=kw.create,b6=gw.create,j6=r_.create,E6=hw.create,S6=Dw.create,P6=K_.create,Z6=L_.create,C6=x_.create,T6=K_.createWithPreprocess,I6=H0.create,k6=()=>o4().optional(),g6=()=>s4().optional(),h6=()=>t4().optional(),y6={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>i_.create({..._,coerce:!0}),boolean:(_)=>Pw.create({..._,coerce:!0}),bigint:(_)=>n_.create({..._,coerce:!0}),date:(_)=>Gw.create({..._,coerce:!0})};var v6=I;var b1=A.object({bgProcessId:A.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function x6(_){return{alive:_.status==="pending"||_.status==="running",status:_.status,createdAt:_.createdAt,lastUpdatedAt:_.lastUpdatedAt??_.completedAt??_.startedAt??_.createdAt,description:_.description,..._.result!==void 0?{result:_.result}:{},..._.error!==void 0?{error:_.error}:{}}}function e4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var jV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
225
+ \`problem\` milestone explaining the blocker instead of going silent.`;var X0="roy",u$={action:"execute",resource:"*",effect:"deny"};function l$(){return{id:X0,mode:"primary",description:R2,system:f2,permissions:[{...u$}]}}function PX(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((Y)=>Y.action===$.action&&Y.resource===$.resource&&Y.effect===$.effect))_.permissions.push({...$})}function L2(_){let w=l$();return _.update(X0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;PX($,w.permissions)}),w}var A={};jX(A,{void:()=>U9,util:()=>l,unknown:()=>H9,union:()=>A9,undefined:()=>G9,tuple:()=>f9,transformer:()=>Z9,symbol:()=>W9,string:()=>s$,strictObject:()=>O9,setErrorMap:()=>TX,set:()=>K9,record:()=>L9,quotelessJson:()=>ZX,promise:()=>P9,preprocess:()=>I9,pipeline:()=>k9,ostring:()=>g9,optional:()=>C9,onumber:()=>h9,oboolean:()=>y9,objectUtil:()=>F2,object:()=>V9,number:()=>t$,nullable:()=>T9,null:()=>Q9,never:()=>B9,nativeEnum:()=>S9,nan:()=>Y9,map:()=>F9,makeIssue:()=>Y0,literal:()=>j9,lazy:()=>b9,late:()=>$9,isValid:()=>p_,isDirty:()=>J1,isAsync:()=>jw,isAborted:()=>Y1,intersection:()=>R9,instanceof:()=>X9,getParsedType:()=>Z_,getErrorMap:()=>bw,function:()=>N9,enum:()=>E9,effect:()=>Z9,discriminatedUnion:()=>M9,defaultErrorMap:()=>y_,datetimeRegex:()=>r$,date:()=>D9,custom:()=>o$,coerce:()=>v9,boolean:()=>e$,bigint:()=>J9,array:()=>z9,any:()=>q9,addIssueToContext:()=>S,ZodVoid:()=>D0,ZodUnknown:()=>i_,ZodUnion:()=>Tw,ZodUndefined:()=>Zw,ZodType:()=>x,ZodTuple:()=>T_,ZodTransformer:()=>K_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>W0,ZodReadonly:()=>xw,ZodPromise:()=>Bw,ZodPipeline:()=>q0,ZodParsedType:()=>j,ZodOptional:()=>L_,ZodObject:()=>t,ZodNumber:()=>n_,ZodNullable:()=>x_,ZodNull:()=>Cw,ZodNever:()=>C_,ZodNativeEnum:()=>hw,ZodNaN:()=>Q0,ZodMap:()=>G0,ZodLiteral:()=>gw,ZodLazy:()=>kw,ZodIssueCode:()=>F,ZodIntersection:()=>Iw,ZodFunction:()=>Sw,ZodFirstPartyTypeKind:()=>K,ZodError:()=>D_,ZodEnum:()=>a_,ZodEffects:()=>K_,ZodDiscriminatedUnion:()=>D1,ZodDefault:()=>yw,ZodDate:()=>Qw,ZodCatch:()=>vw,ZodBranded:()=>W1,ZodBoolean:()=>Pw,ZodBigInt:()=>r_,ZodArray:()=>f_,ZodAny:()=>qw,Schema:()=>x,ParseStatus:()=>W_,OK:()=>Q_,NEVER:()=>x9,INVALID:()=>I,EMPTY_PATH:()=>IX,DIRTY:()=>Gw,BRAND:()=>w9});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let D of Y)J[D]=D;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((W)=>typeof Y[Y[W]]!=="number"),D={};for(let W of J)D[W]=Y[W];return _.objectValues(D)},_.objectValues=(Y)=>{return _.objectKeys(Y).map(function(J){return Y[J]})},_.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let J=[];for(let D in Y)if(Object.prototype.hasOwnProperty.call(Y,D))J.push(D);return J},_.find=(Y,J)=>{for(let D of Y)if(J(D))return D;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((D)=>typeof D==="string"?`'${D}'`:D).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var F2;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(F2||(F2={}));var j=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z_=(_)=>{switch(typeof _){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(_)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray(_))return j.array;if(_===null)return j.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return j.promise;if(typeof Map<"u"&&_ instanceof Map)return j.map;if(typeof Set<"u"&&_ instanceof Set)return j.set;if(typeof Date<"u"&&_ instanceof Date)return j.date;return j.object;default:return j.unknown}};var F=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZX=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class D_ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=_}format(_){let w=_||function(Y){return Y.message},$={_errors:[]},X=(Y)=>{for(let J of Y.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)$._errors.push(w(J));else{let D=$,W=0;while(W<J.path.length){let G=J.path[W];if(W!==J.path.length-1)D[G]=D[G]||{_errors:[]};else D[G]=D[G]||{_errors:[]},D[G]._errors.push(w(J));D=D[G],W++}}};return X(this),$}static assert(_){if(!(_ instanceof D_))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(w)=>w.message){let w={},$=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];w[Y]=w[Y]||[],w[Y].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}D_.create=(_)=>{return new D_(_)};var CX=(_,w)=>{let $;switch(_.code){case F.invalid_type:if(_.received===j.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case F.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case F.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case F.invalid_union:$="Invalid input";break;case F.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case F.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case F.invalid_arguments:$="Invalid function arguments";break;case F.invalid_return_type:$="Invalid function return type";break;case F.invalid_date:$="Invalid date";break;case F.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if($=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)$=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)$=`Invalid input: must end with "${_.validation.endsWith}"`;else l.assertNever(_.validation);else if(_.validation!=="regex")$=`Invalid ${_.validation}`;else $="Invalid";break;case F.too_small:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else $="Invalid input";break;case F.too_big:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")$=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else $="Invalid input";break;case F.custom:$="Invalid input";break;case F.invalid_intersection_types:$="Intersection results could not be merged";break;case F.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case F.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},y_=CX;var c$=y_;function TX(_){c$=_}function bw(){return c$}var Y0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],D={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let W="",G=X.filter((Q)=>!!Q).slice().reverse();for(let Q of G)W=Q(D,{data:w,defaultError:W}).message;return{...Y,path:J,message:W}},IX=[];function S(_,w){let $=bw(),X=Y0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===y_?void 0:y_].filter((Y)=>!!Y)});_.common.issues.push(X)}class W_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,w){let $=[];for(let X of w){if(X.status==="aborted")return I;if(X.status==="dirty")_.dirty();$.push(X.value)}return{status:_.value,value:$}}static async mergeObjectAsync(_,w){let $=[];for(let X of w){let Y=await X.key,J=await X.value;$.push({key:Y,value:J})}return W_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:Y,value:J}=X;if(Y.status==="aborted")return I;if(J.status==="aborted")return I;if(Y.status==="dirty")_.dirty();if(J.status==="dirty")_.dirty();if(Y.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))$[Y.value]=J.value}return{status:_.value,value:$}}}var I=Object.freeze({status:"aborted"}),Gw=(_)=>({status:"dirty",value:_}),Q_=(_)=>({status:"valid",value:_}),Y1=(_)=>_.status==="aborted",J1=(_)=>_.status==="dirty",p_=(_)=>_.status==="valid",jw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var T;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(T||(T={}));class F_{constructor(_,w,$,X){this._cachedPath=[],this.parent=_,this.data=w,this._path=$,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var d$=(_,w)=>{if(p_(w))return{success:!0,data:w.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new D_(_.common.issues);return this._error=$,this._error}}}};function g(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:Y}=_;if(w&&($||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:Y};return{errorMap:(D,W)=>{let{message:G}=_;if(D.code==="invalid_enum_value")return{message:G??W.defaultError};if(typeof W.data>"u")return{message:G??X??W.defaultError};if(D.code!=="invalid_type")return{message:W.defaultError};return{message:G??$??W.defaultError}},description:Y}}class x{get description(){return this._def.description}_getType(_){return Z_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new W_,ctx:{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(jw(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync(_){let w=this._parse(_);return Promise.resolve(w)}parse(_,w){let $=this.safeParse(_,w);if($.success)return $.data;throw $.error}safeParse(_,w){let $={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return d$($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return p_($)?{value:$.value}:{issues:w.common.issues}}catch($){if($?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:w}).then(($)=>p_($)?{value:$.value}:{issues:w.common.issues})}async parseAsync(_,w){let $=await this.safeParseAsync(_,w);if($.success)return $.data;throw $.error}async safeParseAsync(_,w){let $={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parse({data:_,path:$.path,parent:$}),Y=await(jw(X)?X:Promise.resolve(X));return d$($,Y)}refine(_,w){let $=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,Y)=>{let J=_(X),D=()=>Y.addIssue({code:F.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((W)=>{if(!W)return D(),!1;else return!0});if(!J)return D(),!1;else return!0})}refinement(_,w){return this._refinement(($,X)=>{if(!_($))return X.addIssue(typeof w==="function"?w($,X):w),!1;else return!0})}_refinement(_){return new K_({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(w)=>this["~validate"](w)}}optional(){return L_.create(this,this._def)}nullable(){return x_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f_.create(this)}promise(){return Bw.create(this,this._def)}or(_){return Tw.create([this,_],this._def)}and(_){return Iw.create(this,_,this._def)}transform(_){return new K_({...g(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new yw({...g(this._def),innerType:this,defaultValue:w,typeName:K.ZodDefault})}brand(){return new W1({typeName:K.ZodBranded,type:this,...g(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new vw({...g(this._def),innerType:this,catchValue:w,typeName:K.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return q0.create(this,_)}readonly(){return xw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var kX=/^c[^\s-]{8,}$/i,gX=/^[0-9a-z]+$/,hX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vX=/^[a-z0-9_-]{21}$/i,xX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mX=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,uX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K2,cX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,dX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,pX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i$="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aX=new RegExp(`^${i$}$`);function n$(_){let w="[0-5]\\d";if(_.precision)w=`${w}\\.\\d{${_.precision}}`;else if(_.precision==null)w=`${w}(\\.\\d+)?`;let $=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${$}`}function oX(_){return new RegExp(`^${n$(_)}$`)}function r$(_){let w=`${i$}T${n$(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function sX(_,w){if((w==="v4"||!w)&&cX.test(_))return!0;if((w==="v6"||!w)&&pX.test(_))return!0;return!1}function tX(_,w){if(!xX.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(w&&Y.alg!==w)return!1;return!0}catch{return!1}}function eX(_,w){if((w==="v4"||!w)&&dX.test(_))return!0;if((w==="v6"||!w)&&iX.test(_))return!0;return!1}class R_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==j.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.string,received:Y.parsedType}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.length<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="max"){if(_.data.length>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="length"){let J=_.data.length>Y.value,D=_.data.length<Y.value;if(J||D){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(D)S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!uX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!K2)K2=new RegExp(lX,"u");if(!K2.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!yX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!vX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!kX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!gX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!hX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),S(X,{validation:"url",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"regex",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="trim")_.data=_.data.trim();else if(Y.kind==="includes"){if(!_.data.includes(Y.value,Y.position))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),$.dirty()}else if(Y.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(Y.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(Y.kind==="startsWith"){if(!_.data.startsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{startsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="endsWith"){if(!_.data.endsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!r$(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!aX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!oX(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!mX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!sX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!tX(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!eX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!nX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!rX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:F.invalid_string,message:Y.message}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:F.invalid_string,...T.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...T.errToObj(_)})}url(_){return this._addCheck({kind:"url",...T.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...T.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...T.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...T.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...T.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...T.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...T.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...T.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...T.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...T.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...T.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...T.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...T.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...T.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...T.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...T.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...T.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...T.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...T.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...T.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...T.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...T.errToObj(w)})}nonempty(_){return this.min(1,T.errToObj(_))}trim(){return new R_({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxLength(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}R_.create=(_)=>{return new R_({checks:[],typeName:K.ZodString,coerce:_?.coerce??!1,...g(_)})};function _9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),D=Number.parseInt(w.toFixed(Y).replace(".",""));return J%D/10**Y}class n_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==j.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.number,received:Y.parsedType}),I}let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_9(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new n_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new n_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:T.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:T.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(_)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&l.isInteger(_.value))}get isFinite(){let _=null,w=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(w===null||$.value>w)w=$.value}else if($.kind==="max"){if(_===null||$.value<_)_=$.value}return Number.isFinite(w)&&Number.isFinite(_)}}n_.create=(_)=>{return new n_({checks:[],typeName:K.ZodNumber,coerce:_?.coerce||!1,...g(_)})};class r_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==j.bigint)return this._getInvalidInput(_);let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_.data%Y.value!==BigInt(0))$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.bigint,received:w.parsedType}),I}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new r_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new r_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}r_.create=(_)=>{return new r_({checks:[],typeName:K.ZodBigInt,coerce:_?.coerce??!1,...g(_)})};class Pw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==j.boolean){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.boolean,received:$.parsedType}),I}return Q_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:K.ZodBoolean,coerce:_?.coerce||!1,...g(_)})};class Qw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==j.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.date,received:Y.parsedType}),I}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_date}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.getTime()<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),$.dirty()}else if(Y.kind==="max"){if(_.data.getTime()>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new Qw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:T.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:T.toString(w)})}get minDate(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _!=null?new Date(_):null}}Qw.create=(_)=>{return new Qw({checks:[],coerce:_?.coerce||!1,typeName:K.ZodDate,...g(_)})};class J0 extends x{_parse(_){if(this._getType(_)!==j.symbol){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.symbol,received:$.parsedType}),I}return Q_(_.data)}}J0.create=(_)=>{return new J0({typeName:K.ZodSymbol,...g(_)})};class Zw extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.undefined,received:$.parsedType}),I}return Q_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:K.ZodUndefined,...g(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==j.null){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.null,received:$.parsedType}),I}return Q_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:K.ZodNull,...g(_)})};class qw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return Q_(_.data)}}qw.create=(_)=>{return new qw({typeName:K.ZodAny,...g(_)})};class i_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return Q_(_.data)}}i_.create=(_)=>{return new i_({typeName:K.ZodUnknown,...g(_)})};class C_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.never,received:w.parsedType}),I}}C_.create=(_)=>{return new C_({typeName:K.ZodNever,...g(_)})};class D0 extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.void,received:$.parsedType}),I}return Q_(_.data)}}D0.create=(_)=>{return new D0({typeName:K.ZodVoid,...g(_)})};class f_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==j.array)return S(w,{code:F.invalid_type,expected:j.array,received:w.parsedType}),I;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,D=w.data.length<X.exactLength.value;if(J||D)S(w,{code:J?F.too_big:F.too_small,minimum:D?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),$.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)S(w,{code:F.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),$.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)S(w,{code:F.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),$.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,D)=>{return X.type._parseAsync(new F_(w,J,w.path,D))})).then((J)=>{return W_.mergeArray($,J)});let Y=[...w.data].map((J,D)=>{return X.type._parseSync(new F_(w,J,w.path,D))});return W_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new f_({...this._def,minLength:{value:_,message:T.toString(w)}})}max(_,w){return new f_({...this._def,maxLength:{value:_,message:T.toString(w)}})}length(_,w){return new f_({...this._def,exactLength:{value:_,message:T.toString(w)}})}nonempty(_){return this.min(1,_)}}f_.create=(_,w)=>{return new f_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...g(w)})};function Ew(_){if(_ instanceof t){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=L_.create(Ew(X))}return new t({..._._def,shape:()=>w})}else if(_ instanceof f_)return new f_({..._._def,type:Ew(_.element)});else if(_ instanceof L_)return L_.create(Ew(_.unwrap()));else if(_ instanceof x_)return x_.create(Ew(_.unwrap()));else if(_ instanceof T_)return T_.create(_.items.map((w)=>Ew(w)));else return _}class t extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),w=l.objectKeys(_);return this._cached={shape:_,keys:w},this._cached}_parse(_){if(this._getType(_)!==j.object){let G=this._getOrReturnCtx(_);return S(G,{code:F.invalid_type,expected:j.object,received:G.parsedType}),I}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),D=[];if(!(this._def.catchall instanceof C_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))D.push(G)}let W=[];for(let G of J){let Q=Y[G],q=X.data[G];W.push({key:{status:"valid",value:G},value:Q._parse(new F_(X,q,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof C_){let G=this._def.unknownKeys;if(G==="passthrough")for(let Q of D)W.push({key:{status:"valid",value:Q},value:{status:"valid",value:X.data[Q]}});else if(G==="strict"){if(D.length>0)S(X,{code:F.unrecognized_keys,keys:D}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let Q of D){let q=X.data[Q];W.push({key:{status:"valid",value:Q},value:G._parse(new F_(X,q,X.path,Q)),alwaysSet:Q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let Q of W){let q=await Q.key,H=await Q.value;G.push({key:q,value:H,alwaysSet:Q.alwaysSet})}return G}).then((G)=>{return W_.mergeObjectSync($,G)});else return W_.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(_){return T.errToObj,new t({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message:T.errToObj(_).message??X};return{message:X}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(_){return new t({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new t({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:K.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new t({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}deepPartial(){return Ew(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new t({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let Y=this.shape[$];while(Y instanceof L_)Y=Y._def.innerType;w[$]=Y}return new t({...this._def,shape:()=>w})}keyof(){return a$(l.objectKeys(this.shape))}}t.create=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.strictCreate=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strict",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.lazycreate=(_,w)=>{return new t({shape:_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};class Tw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(Y){for(let D of Y)if(D.result.status==="valid")return D.result;for(let D of Y)if(D.result.status==="dirty")return w.common.issues.push(...D.ctx.common.issues),D.result;let J=Y.map((D)=>new D_(D.ctx.common.issues));return S(w,{code:F.invalid_union,unionErrors:J}),I}if(w.common.async)return Promise.all($.map(async(Y)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let Y=void 0,J=[];for(let W of $){let G={...w,common:{...w.common,issues:[]},parent:null},Q=W._parseSync({data:w.data,path:w.path,parent:G});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!Y)Y={result:Q,ctx:G};if(G.common.issues.length)J.push(G.common.issues)}if(Y)return w.common.issues.push(...Y.ctx.common.issues),Y.result;let D=J.map((W)=>new D_(W));return S(w,{code:F.invalid_union,unionErrors:D}),I}}get options(){return this._def.options}}Tw.create=(_,w)=>{return new Tw({options:_,typeName:K.ZodUnion,...g(w)})};var v_=(_)=>{if(_ instanceof kw)return v_(_.schema);else if(_ instanceof K_)return v_(_.innerType());else if(_ instanceof gw)return[_.value];else if(_ instanceof a_)return _.options;else if(_ instanceof hw)return l.objectValues(_.enum);else if(_ instanceof yw)return v_(_._def.innerType);else if(_ instanceof Zw)return[void 0];else if(_ instanceof Cw)return[null];else if(_ instanceof L_)return[void 0,...v_(_.unwrap())];else if(_ instanceof x_)return[null,...v_(_.unwrap())];else if(_ instanceof W1)return v_(_.unwrap());else if(_ instanceof xw)return v_(_.unwrap());else if(_ instanceof vw)return v_(_._def.innerType);else return[]};class D1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.object)return S(w,{code:F.invalid_type,expected:j.object,received:w.parsedType}),I;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:F.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),I;if(w.common.async)return Y._parseAsync({data:w.data,path:w.path,parent:w});else return Y._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,w,$){let X=new Map;for(let Y of w){let J=v_(Y.shape[_]);if(!J.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let D of J){if(X.has(D))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(D)}`);X.set(D,Y)}}return new D1({typeName:K.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...g($)})}}function N2(_,w){let $=Z_(_),X=Z_(w);if(_===w)return{valid:!0,data:_};else if($===j.object&&X===j.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((W)=>Y.indexOf(W)!==-1),D={..._,...w};for(let W of J){let G=N2(_[W],w[W]);if(!G.valid)return{valid:!1};D[W]=G.data}return{valid:!0,data:D}}else if($===j.array&&X===j.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let D=_[J],W=w[J],G=N2(D,W);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===j.date&&X===j.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class Iw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(Y,J)=>{if(Y1(Y)||Y1(J))return I;let D=N2(Y.value,J.value);if(!D.valid)return S($,{code:F.invalid_intersection_types}),I;if(J1(Y)||J1(J))w.dirty();return{status:w.value,value:D.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([Y,J])=>X(Y,J));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}Iw.create=(_,w,$)=>{return new Iw({left:_,right:w,typeName:K.ZodIntersection,...g($)})};class T_ extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.array)return S($,{code:F.invalid_type,expected:j.array,received:$.parsedType}),I;if($.data.length<this._def.items.length)return S($,{code:F.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&$.data.length>this._def.items.length)S($,{code:F.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,D)=>{let W=this._def.items[D]||this._def.rest;if(!W)return null;return W._parse(new F_($,J,$.path,D))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return W_.mergeArray(w,J)});else return W_.mergeArray(w,Y)}get items(){return this._def.items}rest(_){return new T_({...this._def,rest:_})}}T_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new T_({items:_,typeName:K.ZodTuple,rest:null,...g(w)})};class W0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.object)return S($,{code:F.invalid_type,expected:j.object,received:$.parsedType}),I;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let D in $.data)X.push({key:Y._parse(new F_($,D,$.path,D)),value:J._parse(new F_($,$.data[D],$.path,D)),alwaysSet:D in $.data});if($.common.async)return W_.mergeObjectAsync(w,X);else return W_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new W0({keyType:_,valueType:w,typeName:K.ZodRecord,...g($)});return new W0({keyType:R_.create(),valueType:_,typeName:K.ZodRecord,...g(w)})}}class G0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.map)return S($,{code:F.invalid_type,expected:j.map,received:$.parsedType}),I;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([D,W],G)=>{return{key:X._parse(new F_($,D,$.path,[G,"key"])),value:Y._parse(new F_($,W,$.path,[G,"value"]))}});if($.common.async){let D=new Map;return Promise.resolve().then(async()=>{for(let W of J){let G=await W.key,Q=await W.value;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}})}else{let D=new Map;for(let W of J){let{key:G,value:Q}=W;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}}}}G0.create=(_,w,$)=>{return new G0({valueType:w,keyType:_,typeName:K.ZodMap,...g($)})};class Hw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.set)return S($,{code:F.invalid_type,expected:j.set,received:$.parsedType}),I;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:F.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if($.data.size>X.maxSize.value)S($,{code:F.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let Y=this._def.valueType;function J(W){let G=new Set;for(let Q of W){if(Q.status==="aborted")return I;if(Q.status==="dirty")w.dirty();G.add(Q.value)}return{status:w.value,value:G}}let D=[...$.data.values()].map((W,G)=>Y._parse(new F_($,W,$.path,G)));if($.common.async)return Promise.all(D).then((W)=>J(W));else return J(D)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:T.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:T.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Hw.create=(_,w)=>{return new Hw({valueType:_,minSize:null,maxSize:null,typeName:K.ZodSet,...g(w)})};class Sw extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.function)return S(w,{code:F.invalid_type,expected:j.function,received:w.parsedType}),I;function $(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_arguments,argumentsError:W}})}function X(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_return_type,returnTypeError:W}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Bw){let D=this;return Q_(async function(...W){let G=new D_([]),Q=await D._def.args.parseAsync(W,Y).catch((B)=>{throw G.addIssue($(W,B)),G}),q=await Reflect.apply(J,this,Q);return await D._def.returns._def.type.parseAsync(q,Y).catch((B)=>{throw G.addIssue(X(q,B)),G})})}else{let D=this;return Q_(function(...W){let G=D._def.args.safeParse(W,Y);if(!G.success)throw new D_([$(W,G.error)]);let Q=Reflect.apply(J,this,G.data),q=D._def.returns.safeParse(Q,Y);if(!q.success)throw new D_([X(Q,q.error)]);return q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Sw({...this._def,args:T_.create(_).rest(i_.create())})}returns(_){return new Sw({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Sw({args:_?_:T_.create([]).rest(i_.create()),returns:w||i_.create(),typeName:K.ZodFunction,...g($)})}}class kw extends x{get schema(){return this._def.getter()}_parse(_){let{ctx:w}=this._processInputParams(_);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}}kw.create=(_,w)=>{return new kw({getter:_,typeName:K.ZodLazy,...g(w)})};class gw extends x{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return S(w,{received:w.data,code:F.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:_.data}}get value(){return this._def.value}}gw.create=(_,w)=>{return new gw({value:_,typeName:K.ZodLiteral,...g(w)})};function a$(_,w){return new a_({values:_,typeName:K.ZodEnum,...g(w)})}class a_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{received:w.data,code:F.invalid_enum_value,options:$}),I}return Q_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let w of this._def.values)_[w]=w;return _}get Values(){let _={};for(let w of this._def.values)_[w]=w;return _}get Enum(){let _={};for(let w of this._def.values)_[w]=w;return _}extract(_,w=this._def){return a_.create(_,{...this._def,...w})}exclude(_,w=this._def){return a_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}a_.create=a$;class hw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==j.string&&$.parsedType!==j.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:F.invalid_enum_value,options:X}),I}return Q_(_.data)}get enum(){return this._def.values}}hw.create=(_,w)=>{return new hw({values:_,typeName:K.ZodNativeEnum,...g(w)})};class Bw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.promise&&w.common.async===!1)return S(w,{code:F.invalid_type,expected:j.promise,received:w.parsedType}),I;let $=w.parsedType===j.promise?w.data:Promise.resolve(w.data);return Q_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Bw.create=(_,w)=>{return new Bw({type:_,typeName:K.ZodPromise,...g(w)})};class K_ extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=this._def.effect||null,Y={addIssue:(J)=>{if(S($,J),J.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let J=X.transform($.data,Y);if($.common.async)return Promise.resolve(J).then(async(D)=>{if(w.value==="aborted")return I;let W=await this._def.schema._parseAsync({data:D,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")return Gw(W.value);if(w.value==="dirty")return Gw(W.value);return W});else{if(w.value==="aborted")return I;let D=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")return Gw(D.value);if(w.value==="dirty")return Gw(D.value);return D}}if(X.type==="refinement"){let J=(D)=>{let W=X.refinement(D,Y);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return D};if($.common.async===!1){let D=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value),{status:w.value,value:D.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((D)=>{if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value).then(()=>{return{status:w.value,value:D.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!p_(J))return I;let D=X.transform(J.value,Y);if(D instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:D}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!p_(J))return I;return Promise.resolve(X.transform(J.value,Y)).then((D)=>({status:w.value,value:D}))});l.assertNever(X)}}K_.create=(_,w,$)=>{return new K_({schema:_,typeName:K.ZodEffects,effect:w,...g($)})};K_.createWithPreprocess=(_,w,$)=>{return new K_({schema:w,effect:{type:"preprocess",transform:_},typeName:K.ZodEffects,...g($)})};class L_ extends x{_parse(_){if(this._getType(_)===j.undefined)return Q_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}L_.create=(_,w)=>{return new L_({innerType:_,typeName:K.ZodOptional,...g(w)})};class x_ extends x{_parse(_){if(this._getType(_)===j.null)return Q_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}x_.create=(_,w)=>{return new x_({innerType:_,typeName:K.ZodNullable,...g(w)})};class yw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===j.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}yw.create=(_,w)=>{return new yw({innerType:_,typeName:K.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...g(w)})};class vw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(jw(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:K.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...g(w)})};class Q0 extends x{_parse(_){if(this._getType(_)!==j.nan){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.nan,received:$.parsedType}),I}return{status:"valid",value:_.data}}}Q0.create=(_)=>{return new Q0({typeName:K.ZodNaN,...g(_)})};var w9=Symbol("zod_brand");class W1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;return this._def.type._parse({data:$,path:w.path,parent:w})}unwrap(){return this._def.type}}class q0 extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(Y.status==="aborted")return I;if(Y.status==="dirty")return w.dirty(),Gw(Y.value);else return this._def.out._parseAsync({data:Y.value,path:$.path,parent:$})})();else{let X=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(X.status==="aborted")return I;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:$.path,parent:$})}}static create(_,w){return new q0({in:_,out:w,typeName:K.ZodPipeline})}}class xw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(p_(X))X.value=Object.freeze(X.value);return X};return jw(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}xw.create=(_,w)=>{return new xw({innerType:_,typeName:K.ZodReadonly,...g(w)})};function p$(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function o$(_,w={},$){if(_)return qw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((D)=>{if(!D){let W=p$(w,X),G=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:G})}});if(!J){let D=p$(w,X),W=D.fatal??$??!0;Y.addIssue({code:"custom",...D,fatal:W})}return});return qw.create()}var $9={object:t.lazycreate},K;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(K||(K={}));var X9=(_,w={message:`Input not instance of ${_.name}`})=>o$(($)=>$ instanceof _,w),s$=R_.create,t$=n_.create,Y9=Q0.create,J9=r_.create,e$=Pw.create,D9=Qw.create,W9=J0.create,G9=Zw.create,Q9=Cw.create,q9=qw.create,H9=i_.create,B9=C_.create,U9=D0.create,z9=f_.create,V9=t.create,O9=t.strictCreate,A9=Tw.create,M9=D1.create,R9=Iw.create,f9=T_.create,L9=W0.create,F9=G0.create,K9=Hw.create,N9=Sw.create,b9=kw.create,j9=gw.create,E9=a_.create,S9=hw.create,P9=Bw.create,Z9=K_.create,C9=L_.create,T9=x_.create,I9=K_.createWithPreprocess,k9=q0.create,g9=()=>s$().optional(),h9=()=>t$().optional(),y9=()=>e$().optional(),v9={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>n_.create({..._,coerce:!0}),boolean:(_)=>Pw.create({..._,coerce:!0}),bigint:(_)=>r_.create({..._,coerce:!0}),date:(_)=>Qw.create({..._,coerce:!0})};var x9=I;var b2=A.object({bgProcessId:A.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function m9(_){return{alive:_.status==="pending"||_.status==="running",status:_.status,createdAt:_.createdAt,lastUpdatedAt:_.lastUpdatedAt??_.completedAt??_.startedAt??_.createdAt,description:_.description,..._.result!==void 0?{result:_.result}:{},..._.error!==void 0?{error:_.error}:{}}}function _4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var EV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
226
226
 
227
227
  Use this tool when:
228
228
  - You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
@@ -239,7 +239,7 @@ Use this tool when:
239
239
  - result: present when status is 'completed'
240
240
  - error: present when status is 'failed'
241
241
 
242
- Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:b1,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(_,w)=>G2(null).execute(_,w)};function G2(_=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
242
+ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:b2,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(_,w)=>G1(null).execute(_,w)};function G1(_=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
243
243
 
244
244
  Use this tool when:
245
245
  - You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
@@ -256,7 +256,20 @@ Use this tool when:
256
256
  - result: present when status is 'completed'
257
257
  - error: present when status is 'failed'
258
258
 
259
- Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:b1,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(w,$)=>{let X=Date.now(),Y=b1.parse(w),{bgProcessId:J}=Y;if(!_)return{success:!1,output:"",error:"query_background_process is not initialized: no BackgroundTaskManager has been bound. TaskComponent should call createQueryBackgroundProcessTool(manager) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-X}};let W;try{W=_.getTask(J)}catch(G){return{success:!1,output:"",error:`failed to query background task: ${G.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(W){let G=$.session_id;if(!G||W.parentSessionId!==G)return{success:!0,output:JSON.stringify(e4(J),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:"not_found",alive:!1}}}let Q=W?x6(W):e4(J);return{success:!0,output:JSON.stringify(Q,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:Q.status,alive:Q.alive}}}}}import{createRequire as m6}from"module";var{defineProperty:j1,getOwnPropertyNames:u6,getOwnPropertyDescriptor:l6}=Object,c6=Object.prototype.hasOwnProperty;function d6(_){return this[_]}var mw=(_)=>{var w=(_8??=new WeakMap).get(_),$;if(w)return w;if(w=j1({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var X of u6(_))if(!c6.call(w,X))j1(w,X,{get:d6.bind(_,X),enumerable:!($=l6(_,X))||$.enumerable})}return _8.set(_,w),w},_8,p6=(_)=>_;function i6(_,w){this[_]=p6.bind(null,w)}var a_=(_,w)=>{for(var $ in w)j1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:i6.bind(w,$)})},m=function(_,w,$,X){var Y=arguments.length,J=Y<3?w:X===null?X=Object.getOwnPropertyDescriptor(w,$):X,W;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")J=Reflect.decorate(_,w,$,X);else for(var Q=_.length-1;Q>=0;Q--)if(W=_[Q])J=(Y<3?W(J):Y>3?W(w,$,J):W(w,$))||J;return Y>3&&J&&Object.defineProperty(w,$,J),J},r=(_,w)=>()=>(_&&(w=_(_=0)),w),w_=m6(import.meta.url);function E1(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function w8(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if("$typeof"in X||"type"in X&&"props"in X&&"key"in X)return"[ReactElement]";if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch($){return`[Unserializable: ${$ instanceof Error?$.message:String($)}]`}}function n6(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}else return w_("better-sqlite3")}function r6(_){let $=new(n6())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class S1{db=null;dbPath;initialized=!1;constructor(_){if(!_)throw Error("SQLiteSpanStorage requires a valid dbPath parameter");if(_===":memory:")throw Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");this.dbPath=_}async initialize(){if(this.initialized)return;let _=w_("fs"),$=w_("path").dirname(this.dbPath);if(!_.existsSync($))_.mkdirSync($,{recursive:!0});this.db=r6(this.dbPath),this.db.run("PRAGMA journal_mode=WAL"),this.db.run("PRAGMA busy_timeout=5000"),this.db.run("PRAGMA synchronous=NORMAL"),this.db.run(`
259
+ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:b2,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(w,$)=>{let X=Date.now(),Y=b2.parse(w),{bgProcessId:J}=Y;if(!_)return{success:!1,output:"",error:"query_background_process is not initialized: no BackgroundTaskManager has been bound. TaskComponent should call createQueryBackgroundProcessTool(manager) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-X}};let D;try{D=_.getTask(J)}catch(G){return{success:!1,output:"",error:`failed to query background task: ${G.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(D){let G=$.session_id;if(!G||D.parentSessionId!==G)return{success:!0,output:JSON.stringify(_4(J),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:"not_found",alive:!1}}}let W=D?m9(D):_4(J);return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:W.status,alive:W.alive}}}}}var w4=A.object({task_id:A.string().describe("The ID of the background task to stop")}),u9=`Stop a running background task.
260
+
261
+ Use this tool to stop a background task that is currently running. This is useful when:
262
+ - The user wants to cancel a long-running task
263
+ - The task is taking too long and needs to be stopped
264
+ - The user wants to change direction and doesn't need the task result anymore
265
+
266
+ When stopped, the task will be terminated immediately and you will receive a confirmation.
267
+
268
+ Parameters:
269
+ - task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function l9(_){let w=Math.floor(_/1000),$=Math.floor(w/60),X=Math.floor($/60);if(X>0)return`${X}h ${$%60}m ${w%60}s`;else if($>0)return`${$}m ${w%60}s`;else return`${w}s`}function $4(_){return{name:"stop_task",description:u9,parameters:w4,execute:async(w,$)=>{let X=Date.now(),Y=w4.parse(w),{task_id:J}=Y,D=await _.stopTask(J);if(D.success){let W=D.task,G=W.startedAt?Date.now()-W.startedAt:Date.now()-W.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Status: ${W.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${l9(G)}`,"",D.message].join(`
270
+ `),metadata:{execution_time_ms:Date.now()-X,task_id:J,previous_status:W.status}}}else{let W=D.task,G;if(W)G=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Current Status: ${W.status}`,"",D.message].join(`
271
+ `);else G=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${J}`,"",D.message].join(`
272
+ `);return{success:!1,output:G,error:D.message,metadata:{execution_time_ms:Date.now()-X,task_id:J}}}}}}import{createRequire as c9}from"module";var{defineProperty:j2,getOwnPropertyNames:d9,getOwnPropertyDescriptor:p9}=Object,i9=Object.prototype.hasOwnProperty;function n9(_){return this[_]}var mw=(_)=>{var w=(X4??=new WeakMap).get(_),$;if(w)return w;if(w=j2({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var X of d9(_))if(!i9.call(w,X))j2(w,X,{get:n9.bind(_,X),enumerable:!($=p9(_,X))||$.enumerable})}return X4.set(_,w),w},X4,r9=(_)=>_;function a9(_,w){this[_]=r9.bind(null,w)}var o_=(_,w)=>{for(var $ in w)j2(_,$,{get:w[$],enumerable:!0,configurable:!0,set:a9.bind(w,$)})},m=function(_,w,$,X){var Y=arguments.length,J=Y<3?w:X===null?X=Object.getOwnPropertyDescriptor(w,$):X,D;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")J=Reflect.decorate(_,w,$,X);else for(var W=_.length-1;W>=0;W--)if(D=_[W])J=(Y<3?D(J):Y>3?D(w,$,J):D(w,$))||J;return Y>3&&J&&Object.defineProperty(w,$,J),J},r=(_,w)=>()=>(_&&(w=_(_=0)),w),e=c9(import.meta.url);function E2(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function Y4(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if("$typeof"in X||"type"in X&&"props"in X&&"key"in X)return"[ReactElement]";if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch($){return`[Unserializable: ${$ instanceof Error?$.message:String($)}]`}}function o9(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function s9(_){let $=new(o9())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class S2{db=null;dbPath;initialized=!1;constructor(_){if(!_)throw Error("SQLiteSpanStorage requires a valid dbPath parameter");if(_===":memory:")throw Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");this.dbPath=_}async initialize(){if(this.initialized)return;let _=e("fs"),$=e("path").dirname(this.dbPath);if(!_.existsSync($))_.mkdirSync($,{recursive:!0});this.db=s9(this.dbPath),this.db.run("PRAGMA journal_mode=WAL"),this.db.run("PRAGMA busy_timeout=5000"),this.db.run("PRAGMA synchronous=NORMAL"),this.db.run(`
260
273
  CREATE TABLE IF NOT EXISTS span (
261
274
  span_id TEXT PRIMARY KEY,
262
275
  trace_id TEXT NOT NULL,
@@ -271,11 +284,11 @@ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-
271
284
  error TEXT,
272
285
  time_created INTEGER NOT NULL
273
286
  )
274
- `),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save(_){if(!this.db){if(E1())console.log(`[SpanStorage] save() skipped: db not initialized for span "${_.name}" traceId=${_.traceId}`);return}let w=this.db.prepare(`
287
+ `),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save(_){if(!this.db){if(E2())console.log(`[SpanStorage] save() skipped: db not initialized for span "${_.name}" traceId=${_.traceId}`);return}let w=this.db.prepare(`
275
288
  INSERT OR REPLACE INTO span
276
289
  (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
277
290
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
278
- `),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:w8(_.result):null;if(E1())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${_.name}" traceId=${_.traceId} spanId=${_.spanId} status=${_.status}`);try{let X=w.run(_.spanId,_.traceId,_.parentSpanId||null,_.name,_.kind,_.status,_.startTime,_.endTime||null,w8(_.attributes),$,_.error||null,Date.now());if(E1())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch(_){for(let w of _)this.save(w)}findByTraceId(_){if(!this.db)return[];let w=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(_);return this.buildTree(w.map(this.rowToSpan))}findBySpanId(_){if(!this.db)return;let w=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(_);return w?this.rowToSpan(w):void 0}listTraces(_=10){if(!this.db)return[];return this.db.prepare(`
291
+ `),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:Y4(_.result):null;if(E2())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${_.name}" traceId=${_.traceId} spanId=${_.spanId} status=${_.status}`);try{let X=w.run(_.spanId,_.traceId,_.parentSpanId||null,_.name,_.kind,_.status,_.startTime,_.endTime||null,Y4(_.attributes),$,_.error||null,Date.now());if(E2())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch(_){for(let w of _)this.save(w)}findByTraceId(_){if(!this.db)return[];let w=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(_);return this.buildTree(w.map(this.rowToSpan))}findBySpanId(_){if(!this.db)return;let w=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(_);return w?this.rowToSpan(w):void 0}listTraces(_=10){if(!this.db)return[];return this.db.prepare(`
279
292
  SELECT trace_id,
280
293
  MIN(start_time) as start_time,
281
294
  MAX(end_time) as end_time,
@@ -290,10 +303,10 @@ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-
290
303
  GROUP BY trace_id
291
304
  ORDER BY start_time DESC
292
305
  LIMIT ?
293
- `).all(_).map(($)=>{let X=Number($.span_count)||0,Y=Number($.error_count)||0,J=$.end_time??void 0,W=Y===0?"ok":Y>=X?"error":"mixed";return{traceId:$.trace_id,rootSpanName:$.root_name??"unknown",startTime:$.start_time,endTime:J,duration:J!==void 0?J-$.start_time:void 0,spanCount:X,status:W}})}deleteByTraceId(_){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(_)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan(_){return{traceId:_.trace_id,spanId:_.span_id,parentSpanId:_.parent_span_id,name:_.name,kind:_.kind,status:_.status,startTime:_.start_time,endTime:_.end_time,attributes:_.attributes?JSON.parse(_.attributes):{},result:_.result||void 0,error:_.error||void 0}}buildTree(_){let w=new Map,$=[];for(let X of _)w.set(X.spanId,{...X,children:[]});for(let X of w.values())if(X.parentSpanId){let Y=w.get(X.parentSpanId);if(Y)Y.children.push(X);else $.push(X)}else $.push(X);return $}}var $8=()=>{};import{appendFileSync as X7,existsSync as Y7,mkdirSync as J7}from"fs";import{join as D0}from"path";import{AsyncLocalStorage as Y8}from"async_hooks";function X8(_,w){return _.padStart(w,"0")}function P1(_){return/^[0-9a-f]+$/i.test(_)}function a6(_){let w=X8(_.traceId.toLowerCase(),G8),$=X8(_.spanId.toLowerCase(),q8);return[T1,w,$,s6].join("-")}function o6(_){if(!_||typeof _!=="string")return;let $=_.trim().split("-");if($.length!==4)return;let[X,Y,J,W]=$;if(X!==T1){if(X>T1)return}if(Y.length!==G8||!P1(Y))return;if(J.length!==q8||!P1(J))return;if(W.length!==t6||!P1(W))return;return{traceId:Y.toLowerCase(),spanId:J.toLowerCase()}}var T1="00",s6="01",Z1="TRACEPARENT",G8=32,q8=16,t6=2,g1,e6=r(()=>{g1={inject(_,w){_[Z1]=a6(w)},extract(_){let w=_[Z1];if(!w)return;return o6(w)},getTraceparentHeader(){return Z1}}}),_7,w7,$7=r(()=>{((_)=>{_.CLIENT="client",_.SERVER="server",_.INTERNAL="internal"})(_7||={}),((_)=>{_.OK="ok",_.ERROR="error"})(w7||={})});function h1(_){let w=_.replace(/\\/g,"/"),$=w.match(/\/\$bunfs\/root\/(.+)$/);if($){let W=$[1],Q=W.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Q)return Q[1];return W}let X=w.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let W=X[1].replace(/\+/g,"/"),Q=X[2],G=W,q=Q.startsWith("src/")?Q:`src/${Q}`;return`${G}/${q}`}let Y=w.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let J=["packages/core/src","packages/core","packages"];for(let W of J){let Q=w.indexOf(W);if(Q!==-1)return w.substring(Q)}return w}function W7(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let w=w_("xdg-basedir");if(w.xdgData)return D0(w.xdgData,"roy-agent","logs")}catch{}return D0(_,".local","share","roy-agent","logs")}function Q7(){return z7}function G7(){if(N_){let w=N_.get("log_trace.logging.level");if(w&&["debug","info","warn","error"].includes(w))return w}let _=process.env.LOG_LEVEL;if(_&&["debug","info","warn","error"].includes(_))return _;return"info"}function q7(_){if(N_){let X=N_.get("log_trace.logging.levels");if(X&&typeof X==="object"){let J=X[_];if(J&&["debug","info","warn","error"].includes(J))return J}let Y=N_.get(`log_trace.logging.levels.${_}`);if(Y&&["debug","info","warn","error"].includes(Y))return Y}let w=`LOG_LEVEL_${_.toUpperCase().replace(/:/g,"_")}`,$=process.env[w];if($&&["debug","info","warn","error"].includes($))return $;return G7()}function H7(_){if(_.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(_))return!0;return!1}function D7(_){if(_.startsWith("~")){let w=process.env.HOME||process.env.USERPROFILE||"/tmp";return D0(w,_.slice(1))}return _}function B7(){if(N_){let _=N_.get("log-trace.logging.file");if(_)return _}return"app.log"}function U7(){if(N_){let _=N_.get("log-trace.logging.dir");if(_)return _}return W7()}function y1(){if(N_){let _=N_.get("log-trace.logging.maxOutput");if(typeof _==="number")return _}return}class H8{prefix;constructor(_){this.prefix=_}shouldLog(_){let w=q7(this.prefix);return I1[_]>=I1[w]}ensureLogDirectory(_){if(!Y7(_))try{J7(_,{recursive:!0})}catch(w){console.error("[Logger] Failed to create log directory:",_,w)}}getCallerLocation(){let _=Error.stackTraceLimit;Error.stackTraceLimit=10;let w=Error();Error.captureStackTrace(w,this.formatMessage);let $=w.stack?.split(`
294
- `)||[];Error.stackTraceLimit=_;for(let X=1;X<$.length;X++){let Y=$[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let J=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(J){let W=J[1];return{file:this.getRelativePath(W),line:parseInt(J[2],10)}}}}return null}getRelativePath(_){return h1(_)}formatMessage(_,w,$){let X=new Date,Y=X.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).replace(/\//g,"-")+"."+String(X.getMilliseconds()).padStart(3,"0"),J=this.prefix?`[${this.prefix}]`:"",W="";try{let D=B0().getTracer("roy-tracer").getCurrentContext();if(D?.traceId)W=`[traceId=${D.traceId}]`}catch{}let Q="";if($&&typeof $==="object"&&"callerLocation"in $){let H=$;Q=H.callerLocation?` [${H.callerLocation}]`:"";let{callerLocation:B,...D}=H;$=Object.keys(D).length>0?D:void 0}else{let H=this.getCallerLocation();if(H)Q=` [${H.file}:${H.line}]`}let G=`${Y} [${_.toUpperCase()}]${W}${Q}${J} ${w}`;if($!==void 0)if(typeof $==="object")G+=" "+JSON.stringify($).replace(/\n/g,"");else G+=" "+String($);let q=y1();if(q&&q>0&&G.length>q)G=G.substring(0,q)+" [TRUNCATED]";return G}writeToFile(_){try{let w=U7(),$=B7(),X=D7(w),Y=H7(X)?X:D0(process.cwd(),X);this.ensureLogDirectory(Y);let J=D0(Y,$);X7(J,_+`
295
- `,"utf-8")}catch(w){console.error("[Logger] Failed to write to log file:",w)}}log(_,w,$){if(!this.shouldLog(_))return;let X=this.formatMessage(_,w,$);if(this.writeToFile(X),!Q7())if(V7)console.error(X);else(_==="error"?console.error:_==="warn"?console.warn:_==="info"?console.log:console.debug)(X)}debug(_,w){this.log("debug",_,w)}info(_,w){this.log("info",_,w)}warn(_,w){this.log("warn",_,w)}error(_,w){this.log("error",_,w)}}function n(_){if(!q2.has(_))q2.set(_,new H8(_));return q2.get(_)}var N_=null,z7=!1,V7=!1;var I1,q2,a=r(()=>{m1(),I1={debug:0,info:1,warn:2,error:3},q2=new Map}),O7={};a_(O7,{setTracerProvider:()=>M7,resetTracerProvider:()=>A7,getTracerProvider:()=>B0,OTelTracerProvider:()=>x1});function v1(){if(!C1)C1=n("otel-tracer");return C1}function D8(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function B8(_,...w){v1().info(_,...w)}function J8(_,...w){v1().warn(_,...w)}function W8(_,...w){v1().error(_,...w)}class k1{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,Y){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=Y}setAttribute(_,w){this.attributes[_]=w}addEvent(_,w){let $=this.attributes._events||[];$.push({name:_,attributes:w}),this.attributes._events=$}end(_,w){if(this.endTime=Date.now(),w)this.error=w.message;let $=this.endTime-(this.startTime||0);if(D8())B8(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${$}ms status=${w?"ERROR":"OK"}`);let X=this.storage;if(!X)J8(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=B0().getStorage();if(X){if(!(X.db||X.initialized))J8(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{W8("[OTelSpan] Failed to initialize storage:",J)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else W8(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class U8{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext(_){this.provider.setTracerCurrentContext(this.instanceId,_)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor(_,w,$,X){this.name=_,this.version=w,this.storage=$,this.provider=X,this.instanceId=`${_}@${X.instanceId}`}setOnSpanEndCallback(_){this.onSpanEndCallback=_}getActiveSpanCount(){return this.activeSpans.size}startSpan(_,w){let $=w?.parent,X=w&&"parent"in w,Y=w&&"context"in w,J=this.provider.getGlobalContext(),W,Q,G,q,H;if(Y&&w?.context){let D=w.context;Q=D.traceId,G=this.generateSpanId(),q=D.spanId,H={traceId:Q,spanId:G,parentSpanId:q},this.currentContext={traceId:Q,spanId:G,parentSpanId:q};let O=new k1(_,H,this.storage,D,()=>this.handleSpanEnd(H.spanId,D.spanId));if(w?.attributes)for(let[z,U]of Object.entries(w.attributes))O.setAttribute(z,U);return this.activeSpans.set(G,O),O}if(X)W=$;else if(this.currentContext)W=this.currentContext;else if(J)W=J;if(Q=W?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)q=$.parentSpanId||$.spanId;else if(this.currentContext)q=this.currentContext.spanId;else if(J)q=J.spanId;H={traceId:Q,spanId:G,parentSpanId:q},this.currentContext={traceId:Q,spanId:G,parentSpanId:q};let B=new k1(_,H,this.storage,W,()=>this.handleSpanEnd(H.spanId,W?.spanId));if(w?.attributes)for(let[D,O]of Object.entries(w.attributes))B.setAttribute(D,O);if(this.activeSpans.set(G,B),D8())B8(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${Q} spanId=${G} parentSpanId=${q||"-"}`);return B}injectToEnv(_){if(this.currentContext)g1.inject(_,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext(_){this.currentContext=_}findStackParentSpan(_){for(let[,w]of this.activeSpans)if(w.spanContext.parentSpanId===_)return w;return}endSpan(_){let w=_.spanContext;this.activeSpans.delete(w.spanId);let $=this.currentContext?.traceId;if(w.parentSpanId){let Y=this.activeSpans.get(w.parentSpanId);if(Y){let J={traceId:w.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=J,J}if($){let J={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=J,J}}let X=this.findStackParentSpan(w.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let _=Date.now().toString(16).padStart(12,"0"),w=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return(_+w).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd(_,w){if(this.activeSpans.delete(_),w){let X=this.activeSpans.get(w);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:w,parentSpanId:void 0};return}}let $=this.findStackParentSpan(_);if($){this.currentContext={traceId:$.spanContext.traceId,spanId:$.spanContext.spanId,parentSpanId:$.spanContext.parentSpanId};return}this.currentContext=void 0}}class x1{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new Y8;tracerContexts=new Map;tracerContextScope=new Y8;instanceId;constructor(_,w){Q8++,this.instanceId=`Provider#${Q8}`,this.storage=_||new S1(w||R7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){let _=this.globalContextScope.getStore();if(_)return _.value;return this.globalContext}setGlobalContext(_){this.globalContext=_}withGlobalContext(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}runInGlobalContextSync(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}getTracerCurrentContext(_){let w=this.tracerContextScope.getStore();if(w)return w.contexts.get(_);return this.tracerContexts.get(_)}setTracerCurrentContext(_,w){let $=this.tracerContextScope.getStore();if($){$.contexts.set(_,w);return}this.tracerContexts.set(_,w)}clearAllTracerCurrentContexts(){let _=this.tracerContextScope.getStore();if(_){_.contexts.clear();return}this.tracerContexts.clear()}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new U8(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=g1.extract(process.env);if(w)_.setCurrentContext({traceId:w.traceId,spanId:w.spanId,parentSpanId:void 0})}shutdown(){for(let _ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function B0(){if(!m_)m_=new x1;return m_}function A7(){if(m_)m_.shutdown(),m_=null}function M7(_){if(m_)m_.shutdown();m_=_}function R7(){let _=w_("os"),w=w_("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var C1=null,m_=null,Q8=0,m1=r(()=>{$8(),e6(),$7(),a()});import{AsyncLocalStorage as f7}from"async_hooks";a();var H2=n("process-tree-killer");function O8(){return w_("child_process")}var z8;function L7(_,w,$){if(z8)return z8(_,w,$);return O8().spawn(_,w,$)}var V8;function F7(_,w,$){if(V8)return V8(_,w,$);let X=O8();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var K7;function N7(){return K7??process.platform}function b7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function j7(_){try{let w=F7("tasklist",["/fi",`PID eq ${_}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!w)return!0;return w.stdout.toString().includes(String(_))}catch{return!0}}function E7(_){return new Promise((w)=>setTimeout(w,_))}async function S7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=N7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;H2.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let W=1;W<=Y;W++){let Q=$==="win32"?P7(_):Z7(_,X,$);if(await E7(J),!($==="win32"?j7(_):b7(_)))return H2.info(`[bg-process:kill-done] pid=${_} attempts=${W} stillAlive=false`),{pid:_,platform:$,signal:Q.signal,success:!0,attempts:W,stillAlive:!1};if(W<Y)H2.warn(`[bg-process:kill-retry] pid=${_} attempt=${W}/${Y}`)}return H2.error(`[bg-process:kill-failed] pid=${_} attempts=${Y} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function P7(_){try{return L7("taskkill",["/pid",String(_),"/f","/t"],{stdio:"ignore",windowsHide:!0}),{pid:_,platform:"win32",signal:"taskkill /f /t",success:!0}}catch{return{pid:_,platform:"win32",signal:"taskkill /f /t",success:!1}}}function Z7(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var u1=n("task:process-registry");class l1{pids=new Set;register(_){if(!Number.isInteger(_)||_<=0)return;this.pids.add(_)}unregister(_){if(!Number.isInteger(_))return;this.pids.delete(_)}size(){return this.pids.size}async killAll(){if(this.pids.size===0)return;let _=Array.from(this.pids);u1.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await S7(w,{retry:3,retryDelayMs:500});if($.stillAlive)u1.error(`\u8FDB\u7A0B PID ${w} \u7ECF\u8FC7 ${$.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(w)}catch{}u1.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var C7=new f7;function A8(_,w){return C7.run(_,w)}function T7(){if(D2!==void 0)return D2;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return D2=_==="1"||_==="true"||_==="yes",D2}var D2;var I7=()=>{};function k7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordResultToDb:_?.recordResultToDb??!1,logResult:_?.logResult,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let Q=Y.value,G=_?.name||String(X);return Y.value=I_(Q,G,w()),Y}let J=$,W=X||{};if(typeof J==="function"){let Q=_?.name||(W?.name?String(W.name):"anonymous");return I_(J,Q,w())}return J}}function u(_,w){return k7({name:_,...w})}function I_(_,w,$){let X={recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!0,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter??!1,errorIf:$?.errorIf},Y=X.log,J=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let z=y1();return z!==void 0?z:500},W=(z)=>{if(z===void 0)return;if(z===null)return null;let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}if(U>0&&V.length>U)return V.slice(0,U)+" [TRUNCATED]";try{return JSON.parse(V)}catch{return V}},Q=(z)=>{if(z===void 0)return"undefined";if(z===null)return"null";let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}return U>0&&V.length>U?V.slice(0,U)+" [TRUNCATED]":V},G=(z)=>{if(z===void 0)return;if(z===null)return null;if(typeof z==="string")return z;try{return JSON.parse(JSON.stringify(z))}catch(U){return`[Object with circular reference: ${U instanceof Error?U.message:String(U)}]`}},q="[TRACE]",H=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},B=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(T7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:H(()=>X.resultFilter(z));if(V&&typeof V==="object"&&!Array.isArray(V))return{value:V,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:z,store:!0}},D=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,D);let V=U.stack?.split(`
296
- `)||[];Error.stackTraceLimit=z;for(let M=1;M<V.length;M++){let f=V[M];if(f.includes("decorator.ts")||f.includes("decorator.js")||f.includes("logFn")||f.includes("getCallerLocation"))continue;let N=f.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||f.match(/at\s+(.+):(\d+):\d+/);if(N){let R=N[1];if(!R||R==="native")continue;return`${h1(R)}:${N[2]}`}}return""},O=(z,U,V)=>{if(!Y)return;let M=n("traced:"+w),N=`[TRACE] ${z==="enter"?">>>":z==="quit"?"<<<":"!!!"} ${w}`,R=V||D(),b=(F,T)=>{if(T!==void 0)M.info(`${N} ${F}: ${Q(T)}`,{callerLocation:R});else M.info(`${N} ${F}`,{callerLocation:R})};if(z==="enter")b("enter",U);else if(z==="quit")b("quit",X.logResult??X.recordResult?U:void 0);else b("error",U)};return function(...z){let U=B0().getTracer("roy-tracer"),V={};if(X.recordParams!==!1)if(X.paramFilter){let N=H(()=>X.paramFilter(z));if(V.params=G(N),X.flattenParamFilter&&N&&typeof N==="object"&&!Array.isArray(N)){for(let[R,b]of Object.entries(N))if(!(R in V))V[R]=G(b)}}else V.params=G(z);let M=D(),f;try{f=U.startSpan(w,{attributes:V})}catch{}O("enter",z,M);try{let N=_.call(this,...z);if(N&&typeof N==="object"&&typeof N.then==="function")return N.then((R)=>{if(f){let b=X.resultFilter!==void 0,F=X.resultFilter?H(()=>X.resultFilter(R)):void 0;if(F&&typeof F==="object"&&!Array.isArray(F))for(let[C,y]of Object.entries(F))f.setAttribute(C,G(y));let T=B(R,{ran:b,value:F});if(T.store)f.setAttribute("result",JSON.stringify(G(T.value)));let j=X.errorIf?H(()=>X.errorIf(R)):void 0;if(j){let C=j instanceof Error?j:Error(String(j));f.setAttribute("error",C.message),f.end(void 0,C)}else f.end(T.store?T.value:void 0)}return O("quit",X.logResult??X.recordResult?R:void 0,M),R},(R)=>{if(f)f.setAttribute("error",String(R)),f.end(void 0,R instanceof Error?R:Error(String(R)));throw O("error",R.message,M),R});if(f){let R=X.resultFilter!==void 0,b=X.resultFilter?H(()=>X.resultFilter(N)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[j,C]of Object.entries(b))f.setAttribute(j,G(C));let F=B(N,{ran:R,value:b});if(F.store)f.setAttribute("result",JSON.stringify(G(F.value)));let T=X.errorIf?H(()=>X.errorIf(N)):void 0;if(T){let j=T instanceof Error?T:Error(String(T));f.setAttribute("error",j.message),f.end(void 0,j)}else f.end(F.store?F.value:void 0)}return O("quit",X.logResult??X.recordResult?N:void 0,M),N}catch(N){if(f)f.setAttribute("error",String(N)),f.end(void 0,N instanceof Error?N:Error(String(N)));throw O("error",N.message,M),N}}}var V_=r(()=>{m1(),a(),I7()});import{randomUUID as g7}from"crypto";V_();function h7(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}else return w_("better-sqlite3")}function y7(_){let $=new(h7())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class c1{db;insertStmt;getByIdStmt;recentStmt;constructor(_){this.db=y7(_.dbPath);try{this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA synchronous=NORMAL"),this.db.exec("PRAGMA busy_timeout=5000")}catch{}this.db.exec(`CREATE TABLE IF NOT EXISTS event_store (
306
+ `).all(_).map(($)=>{let X=Number($.span_count)||0,Y=Number($.error_count)||0,J=$.end_time??void 0,D=Y===0?"ok":Y>=X?"error":"mixed";return{traceId:$.trace_id,rootSpanName:$.root_name??"unknown",startTime:$.start_time,endTime:J,duration:J!==void 0?J-$.start_time:void 0,spanCount:X,status:D}})}deleteByTraceId(_){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(_)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan(_){return{traceId:_.trace_id,spanId:_.span_id,parentSpanId:_.parent_span_id,name:_.name,kind:_.kind,status:_.status,startTime:_.start_time,endTime:_.end_time,attributes:_.attributes?JSON.parse(_.attributes):{},result:_.result||void 0,error:_.error||void 0}}buildTree(_){let w=new Map,$=[];for(let X of _)w.set(X.spanId,{...X,children:[]});for(let X of w.values())if(X.parentSpanId){let Y=w.get(X.parentSpanId);if(Y)Y.children.push(X);else $.push(X)}else $.push(X);return $}}var J4=()=>{};import{appendFileSync as D7,existsSync as W7,mkdirSync as G7}from"fs";import{join as H0}from"path";import{AsyncLocalStorage as W4}from"async_hooks";function D4(_,w){return _.padStart(w,"0")}function P2(_){return/^[0-9a-f]+$/i.test(_)}function t9(_){let w=D4(_.traceId.toLowerCase(),H4),$=D4(_.spanId.toLowerCase(),B4);return[T2,w,$,_7].join("-")}function e9(_){if(!_||typeof _!=="string")return;let $=_.trim().split("-");if($.length!==4)return;let[X,Y,J,D]=$;if(X!==T2){if(X>T2)return}if(Y.length!==H4||!P2(Y))return;if(J.length!==B4||!P2(J))return;if(D.length!==w7||!P2(D))return;return{traceId:Y.toLowerCase(),spanId:J.toLowerCase()}}var T2="00",_7="01",Z2="TRACEPARENT",H4=32,B4=16,w7=2,g2,$7=r(()=>{g2={inject(_,w){_[Z2]=t9(w)},extract(_){let w=_[Z2];if(!w)return;return e9(w)},getTraceparentHeader(){return Z2}}}),X7,Y7,J7=r(()=>{((_)=>{_.CLIENT="client",_.SERVER="server",_.INTERNAL="internal"})(X7||={}),((_)=>{_.OK="ok",_.ERROR="error"})(Y7||={})});function h2(_){let w=_.replace(/\\/g,"/"),$=w.match(/\/\$bunfs\/root\/(.+)$/);if($){let D=$[1],W=D.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];return D}let X=w.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let D=X[1].replace(/\+/g,"/"),W=X[2],G=D,Q=W.startsWith("src/")?W:`src/${W}`;return`${G}/${Q}`}let Y=w.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let J=["packages/core/src","packages/core","packages"];for(let D of J){let W=w.indexOf(D);if(W!==-1)return w.substring(W)}return w}function Q7(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let w=e("xdg-basedir");if(w.xdgData)return H0(w.xdgData,"roy-agent","logs")}catch{}return H0(_,".local","share","roy-agent","logs")}function q7(){return A7}function H7(){if(N_){let w=N_.get("log_trace.logging.level");if(w&&["debug","info","warn","error"].includes(w))return w}let _=process.env.LOG_LEVEL;if(_&&["debug","info","warn","error"].includes(_))return _;return"info"}function B7(_){if(N_){let X=N_.get("log_trace.logging.levels");if(X&&typeof X==="object"){let J=X[_];if(J&&["debug","info","warn","error"].includes(J))return J}let Y=N_.get(`log_trace.logging.levels.${_}`);if(Y&&["debug","info","warn","error"].includes(Y))return Y}let w=`LOG_LEVEL_${_.toUpperCase().replace(/:/g,"_")}`,$=process.env[w];if($&&["debug","info","warn","error"].includes($))return $;return H7()}function U7(_){if(_.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(_))return!0;return!1}function z7(_){if(_.startsWith("~")){let w=process.env.HOME||process.env.USERPROFILE||"/tmp";return H0(w,_.slice(1))}return _}function V7(){if(N_){let _=N_.get("log-trace.logging.file");if(_)return _}return"app.log"}function O7(){if(N_){let _=N_.get("log-trace.logging.dir");if(_)return _}return Q7()}function y2(){if(N_){let _=N_.get("log-trace.logging.maxOutput");if(typeof _==="number")return _}return}class U4{prefix;constructor(_){this.prefix=_}shouldLog(_){let w=B7(this.prefix);return I2[_]>=I2[w]}ensureLogDirectory(_){if(!W7(_))try{G7(_,{recursive:!0})}catch(w){console.error("[Logger] Failed to create log directory:",_,w)}}getCallerLocation(){let _=Error.stackTraceLimit;Error.stackTraceLimit=10;let w=Error();Error.captureStackTrace(w,this.formatMessage);let $=w.stack?.split(`
307
+ `)||[];Error.stackTraceLimit=_;for(let X=1;X<$.length;X++){let Y=$[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let J=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(J){let D=J[1];return{file:this.getRelativePath(D),line:parseInt(J[2],10)}}}}return null}getRelativePath(_){return h2(_)}formatMessage(_,w,$){let X=new Date,Y=X.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).replace(/\//g,"-")+"."+String(X.getMilliseconds()).padStart(3,"0"),J=this.prefix?`[${this.prefix}]`:"",D="";try{let B=B0().getTracer("roy-tracer").getCurrentContext();if(B?.traceId)D=`[traceId=${B.traceId}]`}catch{}let W="";if($&&typeof $==="object"&&"callerLocation"in $){let q=$;W=q.callerLocation?` [${q.callerLocation}]`:"";let{callerLocation:H,...B}=q;$=Object.keys(B).length>0?B:void 0}else{let q=this.getCallerLocation();if(q)W=` [${q.file}:${q.line}]`}let G=`${Y} [${_.toUpperCase()}]${D}${W}${J} ${w}`;if($!==void 0)if(typeof $==="object")G+=" "+JSON.stringify($).replace(/\n/g,"");else G+=" "+String($);let Q=y2();if(Q&&Q>0&&G.length>Q)G=G.substring(0,Q)+" [TRUNCATED]";return G}writeToFile(_){try{let w=O7(),$=V7(),X=z7(w),Y=U7(X)?X:H0(process.cwd(),X);this.ensureLogDirectory(Y);let J=H0(Y,$);D7(J,_+`
308
+ `,"utf-8")}catch(w){console.error("[Logger] Failed to write to log file:",w)}}log(_,w,$){if(!this.shouldLog(_))return;let X=this.formatMessage(_,w,$);if(this.writeToFile(X),!q7())if(M7)console.error(X);else(_==="error"?console.error:_==="warn"?console.warn:_==="info"?console.log:console.debug)(X)}debug(_,w){this.log("debug",_,w)}info(_,w){this.log("info",_,w)}warn(_,w){this.log("warn",_,w)}error(_,w){this.log("error",_,w)}}function n(_){if(!Q1.has(_))Q1.set(_,new U4(_));return Q1.get(_)}var N_=null,A7=!1,M7=!1;var I2,Q1,a=r(()=>{m2(),I2={debug:0,info:1,warn:2,error:3},Q1=new Map}),R7={};o_(R7,{setTracerProvider:()=>L7,resetTracerProvider:()=>f7,getTracerProvider:()=>B0,OTelTracerProvider:()=>x2});function v2(){if(!C2)C2=n("otel-tracer");return C2}function z4(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function V4(_,...w){v2().info(_,...w)}function G4(_,...w){v2().warn(_,...w)}function Q4(_,...w){v2().error(_,...w)}class k2{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,Y){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=Y}setAttribute(_,w){this.attributes[_]=w}addEvent(_,w){let $=this.attributes._events||[];$.push({name:_,attributes:w}),this.attributes._events=$}end(_,w){if(this.endTime=Date.now(),w)this.error=w.message;let $=this.endTime-(this.startTime||0);if(z4())V4(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${$}ms status=${w?"ERROR":"OK"}`);let X=this.storage;if(!X)G4(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=B0().getStorage();if(X){if(!(X.db||X.initialized))G4(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{Q4("[OTelSpan] Failed to initialize storage:",J)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else Q4(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class O4{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext(_){this.provider.setTracerCurrentContext(this.instanceId,_)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor(_,w,$,X){this.name=_,this.version=w,this.storage=$,this.provider=X,this.instanceId=`${_}@${X.instanceId}`}setOnSpanEndCallback(_){this.onSpanEndCallback=_}getActiveSpanCount(){return this.activeSpans.size}startSpan(_,w){let $=w?.parent,X=w&&"parent"in w,Y=w&&"context"in w,J=this.provider.getGlobalContext(),D,W,G,Q,q;if(Y&&w?.context){let B=w.context;W=B.traceId,G=this.generateSpanId(),Q=B.spanId,q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let O=new k2(_,q,this.storage,B,()=>this.handleSpanEnd(q.spanId,B.spanId));if(w?.attributes)for(let[z,U]of Object.entries(w.attributes))O.setAttribute(z,U);return this.activeSpans.set(G,O),O}if(X)D=$;else if(this.currentContext)D=this.currentContext;else if(J)D=J;if(W=D?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)Q=$.parentSpanId||$.spanId;else if(this.currentContext)Q=this.currentContext.spanId;else if(J)Q=J.spanId;q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let H=new k2(_,q,this.storage,D,()=>this.handleSpanEnd(q.spanId,D?.spanId));if(w?.attributes)for(let[B,O]of Object.entries(w.attributes))H.setAttribute(B,O);if(this.activeSpans.set(G,H),z4())V4(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${W} spanId=${G} parentSpanId=${Q||"-"}`);return H}injectToEnv(_){if(this.currentContext)g2.inject(_,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext(_){this.currentContext=_}findStackParentSpan(_){for(let[,w]of this.activeSpans)if(w.spanContext.parentSpanId===_)return w;return}endSpan(_){let w=_.spanContext;this.activeSpans.delete(w.spanId);let $=this.currentContext?.traceId;if(w.parentSpanId){let Y=this.activeSpans.get(w.parentSpanId);if(Y){let J={traceId:w.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=J,J}if($){let J={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=J,J}}let X=this.findStackParentSpan(w.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let _=Date.now().toString(16).padStart(12,"0"),w=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return(_+w).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd(_,w){if(this.activeSpans.delete(_),w){let X=this.activeSpans.get(w);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:w,parentSpanId:void 0};return}}let $=this.findStackParentSpan(_);if($){this.currentContext={traceId:$.spanContext.traceId,spanId:$.spanContext.spanId,parentSpanId:$.spanContext.parentSpanId};return}this.currentContext=void 0}}class x2{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new W4;tracerContexts=new Map;tracerContextScope=new W4;instanceId;constructor(_,w){q4++,this.instanceId=`Provider#${q4}`,this.storage=_||new S2(w||F7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){let _=this.globalContextScope.getStore();if(_)return _.value;return this.globalContext}setGlobalContext(_){this.globalContext=_}withGlobalContext(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}runInGlobalContextSync(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}getTracerCurrentContext(_){let w=this.tracerContextScope.getStore();if(w)return w.contexts.get(_);return this.tracerContexts.get(_)}setTracerCurrentContext(_,w){let $=this.tracerContextScope.getStore();if($){$.contexts.set(_,w);return}this.tracerContexts.set(_,w)}clearAllTracerCurrentContexts(){let _=this.tracerContextScope.getStore();if(_){_.contexts.clear();return}this.tracerContexts.clear()}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new O4(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=g2.extract(process.env);if(w)_.setCurrentContext({traceId:w.traceId,spanId:w.spanId,parentSpanId:void 0})}shutdown(){for(let _ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function B0(){if(!m_)m_=new x2;return m_}function f7(){if(m_)m_.shutdown(),m_=null}function L7(_){if(m_)m_.shutdown();m_=_}function F7(){let _=e("os"),w=e("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var C2=null,m_=null,q4=0,m2=r(()=>{J4(),$7(),J7(),a()});import{AsyncLocalStorage as K7}from"async_hooks";a();var q1=n("process-tree-killer");function R4(){return e("child_process")}var A4;function N7(_,w,$){if(A4)return A4(_,w,$);return R4().spawn(_,w,$)}var M4;function b7(_,w,$){if(M4)return M4(_,w,$);let X=R4();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var j7;function E7(){return j7??process.platform}function S7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function P7(_){try{let w=b7("tasklist",["/fi",`PID eq ${_}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!w)return!0;return w.stdout.toString().includes(String(_))}catch{return!0}}function Z7(_){return new Promise((w)=>setTimeout(w,_))}async function C7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=E7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;q1.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let D=1;D<=Y;D++){let W=$==="win32"?T7(_):I7(_,X,$);if(await Z7(J),!($==="win32"?P7(_):S7(_)))return q1.info(`[bg-process:kill-done] pid=${_} attempts=${D} stillAlive=false`),{pid:_,platform:$,signal:W.signal,success:!0,attempts:D,stillAlive:!1};if(D<Y)q1.warn(`[bg-process:kill-retry] pid=${_} attempt=${D}/${Y}`)}return q1.error(`[bg-process:kill-failed] pid=${_} attempts=${Y} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function T7(_){try{return N7("taskkill",["/pid",String(_),"/f","/t"],{stdio:"ignore",windowsHide:!0}),{pid:_,platform:"win32",signal:"taskkill /f /t",success:!0}}catch{return{pid:_,platform:"win32",signal:"taskkill /f /t",success:!1}}}function I7(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var u2=n("task:process-registry");class l2{pids=new Set;register(_){if(!Number.isInteger(_)||_<=0)return;this.pids.add(_)}unregister(_){if(!Number.isInteger(_))return;this.pids.delete(_)}size(){return this.pids.size}async killAll(){if(this.pids.size===0)return;let _=Array.from(this.pids);u2.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await C7(w,{retry:3,retryDelayMs:500});if($.stillAlive)u2.error(`\u8FDB\u7A0B PID ${w} \u7ECF\u8FC7 ${$.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(w)}catch{}u2.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var k7=new K7;function f4(_,w){return k7.run(_,w)}function g7(){if(H1!==void 0)return H1;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return H1=_==="1"||_==="true"||_==="yes",H1}var H1;var h7=()=>{};function y7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordResultToDb:_?.recordResultToDb??!1,logResult:_?.logResult,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let W=Y.value,G=_?.name||String(X);return Y.value=I_(W,G,w()),Y}let J=$,D=X||{};if(typeof J==="function"){let W=_?.name||(D?.name?String(D.name):"anonymous");return I_(J,W,w())}return J}}function u(_,w){return y7({name:_,...w})}function I_(_,w,$){let X={recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!0,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter??!1,errorIf:$?.errorIf},Y=X.log,J=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let z=y2();return z!==void 0?z:500},D=(z)=>{if(z===void 0)return;if(z===null)return null;let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}if(U>0&&V.length>U)return V.slice(0,U)+" [TRUNCATED]";try{return JSON.parse(V)}catch{return V}},W=(z)=>{if(z===void 0)return"undefined";if(z===null)return"null";let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}return U>0&&V.length>U?V.slice(0,U)+" [TRUNCATED]":V},G=(z)=>{if(z===void 0)return;if(z===null)return null;if(typeof z==="string")return z;try{return JSON.parse(JSON.stringify(z))}catch(U){return`[Object with circular reference: ${U instanceof Error?U.message:String(U)}]`}},Q="[TRACE]",q=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},H=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(g7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:q(()=>X.resultFilter(z));if(V&&typeof V==="object"&&!Array.isArray(V))return{value:V,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:z,store:!0}},B=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,B);let V=U.stack?.split(`
309
+ `)||[];Error.stackTraceLimit=z;for(let M=1;M<V.length;M++){let R=V[M];if(R.includes("decorator.ts")||R.includes("decorator.js")||R.includes("logFn")||R.includes("getCallerLocation"))continue;let N=R.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||R.match(/at\s+(.+):(\d+):\d+/);if(N){let b=N[1];if(!b||b==="native")continue;return`${h2(b)}:${N[2]}`}}return""},O=(z,U,V)=>{if(!Y)return;let M=n("traced:"+w),N=`[TRACE] ${z==="enter"?">>>":z==="quit"?"<<<":"!!!"} ${w}`,b=V||B(),E=(f,Z)=>{if(Z!==void 0)M.info(`${N} ${f}: ${W(Z)}`,{callerLocation:b});else M.info(`${N} ${f}`,{callerLocation:b})};if(z==="enter")E("enter",U);else if(z==="quit")E("quit",X.logResult??X.recordResult?U:void 0);else E("error",U)};return function(...z){let U=B0().getTracer("roy-tracer"),V={};if(X.recordParams!==!1)if(X.paramFilter){let N=q(()=>X.paramFilter(z));if(V.params=G(N),X.flattenParamFilter&&N&&typeof N==="object"&&!Array.isArray(N)){for(let[b,E]of Object.entries(N))if(!(b in V))V[b]=G(E)}}else V.params=G(z);let M=B(),R;try{R=U.startSpan(w,{attributes:V})}catch{}O("enter",z,M);try{let N=_.call(this,...z);if(N&&typeof N==="object"&&typeof N.then==="function")return N.then((b)=>{if(R){let E=X.resultFilter!==void 0,f=X.resultFilter?q(()=>X.resultFilter(b)):void 0;if(f&&typeof f==="object"&&!Array.isArray(f))for(let[C,y]of Object.entries(f))R.setAttribute(C,G(y));let Z=H(b,{ran:E,value:f});if(Z.store)R.setAttribute("result",JSON.stringify(G(Z.value)));let L=X.errorIf?q(()=>X.errorIf(b)):void 0;if(L){let C=L instanceof Error?L:Error(String(L));R.setAttribute("error",C.message),R.end(void 0,C)}else R.end(Z.store?Z.value:void 0)}return O("quit",X.logResult??X.recordResult?b:void 0,M),b},(b)=>{if(R)R.setAttribute("error",String(b)),R.end(void 0,b instanceof Error?b:Error(String(b)));throw O("error",b.message,M),b});if(R){let b=X.resultFilter!==void 0,E=X.resultFilter?q(()=>X.resultFilter(N)):void 0;if(E&&typeof E==="object"&&!Array.isArray(E))for(let[L,C]of Object.entries(E))R.setAttribute(L,G(C));let f=H(N,{ran:b,value:E});if(f.store)R.setAttribute("result",JSON.stringify(G(f.value)));let Z=X.errorIf?q(()=>X.errorIf(N)):void 0;if(Z){let L=Z instanceof Error?Z:Error(String(Z));R.setAttribute("error",L.message),R.end(void 0,L)}else R.end(f.store?f.value:void 0)}return O("quit",X.logResult??X.recordResult?N:void 0,M),N}catch(N){if(R)R.setAttribute("error",String(N)),R.end(void 0,N instanceof Error?N:Error(String(N)));throw O("error",N.message,M),N}}}var V_=r(()=>{m2(),a(),h7()});import{randomUUID as v7}from"crypto";V_();function x7(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}else return e("better-sqlite3")}function m7(_){let $=new(x7())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class c2{db;insertStmt;getByIdStmt;recentStmt;constructor(_){this.db=m7(_.dbPath);try{this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA synchronous=NORMAL"),this.db.exec("PRAGMA busy_timeout=5000")}catch{}this.db.exec(`CREATE TABLE IF NOT EXISTS event_store (
297
310
  event_id TEXT PRIMARY KEY,
298
311
  es_type TEXT NOT NULL,
299
312
  sender_id TEXT NOT NULL,
@@ -308,7 +321,7 @@ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-
308
321
  FROM event_store
309
322
  WHERE es_type = ? AND sender_id = ?
310
323
  ORDER BY created_at DESC
311
- LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${g7()}`,X=Date.now(),Y=JSON.stringify(_.metadata??{}),J=_.rawEvent===void 0?null:v7(_.rawEvent);return this.insertStmt.run($,w,_.senderId,_.text??null,Y,J,X),$}async getEventById(_){let w=this.getByIdStmt.get(_);if(!w)return null;return M8(w)}async getRecentEvents(_,w,$){return this.recentStmt.all(_,w,$).map((Y)=>M8(Y))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],c1.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],c1.prototype,"getEventById",null);function M8(_){let w;try{w=_.metadata?JSON.parse(_.metadata):{}}catch{w={}}let $;if(_.raw_event)try{$=JSON.parse(_.raw_event)}catch{$=null}else $=null;return{eventId:_.event_id,esType:_.es_type,senderId:_.sender_id,text:_.text??null,metadata:w,rawEvent:$,createdAt:typeof _.created_at==="bigint"?Number(_.created_at):_.created_at}}function v7(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch{return"{}"}}var x7=null;function R8(){return x7}var $_={BEFORE_CREATE:"task:before.create",AFTER_CREATE:"task:after.create",BEFORE_UPDATE:"task:before.update",AFTER_UPDATE:"task:after.update",BEFORE_DELETE:"task:before.delete",AFTER_DELETE:"task:after.delete",AFTER_COMPLETE:"task:after.complete",DELEGATE_BEFORE:"task:delegate:before",DELEGATE_AFTER:"task:delegate:after",OPERATION_BEFORE_CREATE:"task:operation:before.create",OPERATION_AFTER_CREATE:"task:operation:after.create"};var d1={default:`\u4F60\u662F {{agent_name}} \u63A5\u5F85\u667A\u80FD\u4F53\uFF08Receptionist Agent\uFF09\u2014\u2014 {{agent_name}} \u7CFB\u7EDF\u7684\u667A\u80FD\u5165\u53E3\u3002
324
+ LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${v7()}`,X=Date.now(),Y=JSON.stringify(_.metadata??{}),J=_.rawEvent===void 0?null:u7(_.rawEvent);return this.insertStmt.run($,w,_.senderId,_.text??null,Y,J,X),$}async getEventById(_){let w=this.getByIdStmt.get(_);if(!w)return null;return L4(w)}async getRecentEvents(_,w,$){return this.recentStmt.all(_,w,$).map((Y)=>L4(Y))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],c2.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],c2.prototype,"getEventById",null);function L4(_){let w;try{w=_.metadata?JSON.parse(_.metadata):{}}catch{w={}}let $;if(_.raw_event)try{$=JSON.parse(_.raw_event)}catch{$=null}else $=null;return{eventId:_.event_id,esType:_.es_type,senderId:_.sender_id,text:_.text??null,metadata:w,rawEvent:$,createdAt:typeof _.created_at==="bigint"?Number(_.created_at):_.created_at}}function u7(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch{return"{}"}}var l7=null;function F4(){return l7}var $_={BEFORE_CREATE:"task:before.create",AFTER_CREATE:"task:after.create",BEFORE_UPDATE:"task:before.update",AFTER_UPDATE:"task:after.update",BEFORE_DELETE:"task:before.delete",AFTER_DELETE:"task:after.delete",AFTER_COMPLETE:"task:after.complete",DELEGATE_BEFORE:"task:delegate:before",DELEGATE_AFTER:"task:delegate:after",OPERATION_BEFORE_CREATE:"task:operation:before.create",OPERATION_AFTER_CREATE:"task:operation:after.create"};var d2={default:`\u4F60\u662F {{agent_name}} \u63A5\u5F85\u667A\u80FD\u4F53\uFF08Receptionist Agent\uFF09\u2014\u2014 {{agent_name}} \u7CFB\u7EDF\u7684\u667A\u80FD\u5165\u53E3\u3002
312
325
 
313
326
  ## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
314
327
 
@@ -2045,8 +2058,8 @@ task_operation_create({
2045
2058
  \u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
2046
2059
 
2047
2060
  > \u2705 \u4EFB\u52A1\u6811\u5F62\u6001\u826F\u597D\uFF08root=N, depth=X, non_longterm_root=0, health_score=health\uFF09\u3002\u65E0\u9700\u64CD\u4F5C\u3002
2048
- `},oV=d1["workflow-extract"];import f8 from"os";import z_ from"path";var B2="roy-agent";function m7(){let _=f8.homedir();try{let w=w_("xdg-basedir");return{config:w.xdgConfig||z_.join(_,".config"),state:w.xdgState||z_.join(_,".local","state"),data:w.xdgData||z_.join(_,".local","share"),cache:w.xdgCache||z_.join(_,".cache")}}catch{return{config:z_.join(_,".config"),state:z_.join(_,".local","state"),data:z_.join(_,".local","share"),cache:z_.join(_,".cache")}}}function u7(){let _=f8.homedir(),w=m7();return{home:_,config:z_.join(w.config,B2),state:z_.join(w.state,B2),data:z_.join(w.data,B2),cache:z_.join(w.cache,B2)}}class L8{_paths;get paths(){if(!this._paths)this._paths=u7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return z_.join(this.paths[_],w)}reset(){this._paths=void 0}}var l7=new L8;function F8(_){return l7.getPath(_)}import*as lB from"fs/promises";import*as cB from"fs";import{join as tw}from"path";var X4=F9(T5(),1);a();V_();var e=n("agent:registry"),$4=A.object({name:A.string(),type:A.enum(["primary","sub","workflow"]),workflow:A.string().optional(),entryAgent:A.string().optional(),description:A.string().optional(),systemPromptRef:A.string().optional(),systemPrompt:A.string().optional(),model:A.string().optional(),maxIterations:A.number().optional(),maxErrorRetries:A.number().optional(),allowedTools:A.array(A.string()).optional(),deniedTools:A.array(A.string()).optional(),toolTimeout:A.number().optional(),toolRetries:A.number().optional(),doomLoopThreshold:A.number().optional(),filterHistory:A.boolean().optional()}).refine((_)=>_.type!=="workflow"||_.workflow&&_.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class M_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||cB,this.fsPromises=_.fsPromises||lB;let w=this.configComponent?.get?.("agent.configDir");if(w&&typeof w==="string"&&w.length>0)this.configDir=w;else if(_.baseDir)this.configDir=tw(_.baseDir,"agents");else this.configDir=tw(F8("data"),"agents");e.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=$4.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),e.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)e.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),e.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt(_){let w=this.agents.get(_);if(!w)return;let $=this.getActivePromptComponent();if(w.systemPromptRef)try{if($?.getPrompt){let Y=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(Y)return e.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return e.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return e.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return e.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${w.systemPromptRef}`,{error:X}),w.systemPrompt}return w.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt(_){let w=this.agents.get(_);if(!w)return;return w.systemPrompt}getWorkflowName(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.workflow}getEntryAgent(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let w={name:"workflow-runner",type:"sub",description:"Workflow runner \u2014 \u63A5\u53D7\u5E26 workflow_name\uFF08\u5FC5\u586B\uFF09\u7684\u59D4\u6258\uFF0C\u6216\u6307\u793A\u5176\u6309 search-first \u6D41\u7A0B\u81EA\u884C\u9009\u5B9A\uFF08workflow_tag_list + workflow_search + workflow_list + workflow_get\uFF09\uFF0C\u7136\u540E\u901A\u8FC7 workflow_run \u6267\u884C workflow\uFF1B\u652F\u6301 session resume \u548C stop\uFF1B\u5931\u8D25\u63A5\u7BA1\u7531 prompt \u63A8\u7406\u89E6\u53D1 (Task #2251)\u3002**\u8C03\u7528\u65B9\u5FC5\u987B\u5728 prompt \u4E2D\u660E\u786E\u6307\u5B9A workflow \u540D\uFF0C\u6216\u6307\u793A sub-agent \u81EA\u884C\u641C\u7D22\u9009\u62E9\uFF1B\u7981\u6B62\u76F2\u731C/\u7ED5\u8FC7/\u8DF3\u8FC7 schema \u9A8C\u8BC1** (Task #2486)\u3002",systemPromptRef:"workflow-runner",deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("workflow-runner",w)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let w={name:"task-organizer",type:"sub",description:"\u4EFB\u52A1\u6811\u6574\u7406\u5B50\u667A\u80FD\u4F53 \u2014 \u628A\u975E longterm \u7C7B\u578B\u7684\u6839\u4EFB\u52A1\u91CD\u65B0\u6302\u8F7D\u5230 longterm \u7236\u4EFB\u52A1\u4E0B\uFF0C\u6839\u4EFB\u52A1\u6536\u655B\u5230 10-20 \u4E2A\uFF1B\u7EF4\u62A4\u4EFB\u52A1\u6811\u5F62\u6001\u5065\u5EB7\uFF08re-parent / merge / archive / delete\uFF09\u3002Task #2348\u3002",systemPromptRef:"task-organizer",allowedTools:["task_create","task_get","task_list","task_update","task_delete","task_complete","task_tree","task_search","task_batch_archive","task_batch_delete","task_operation_create","task_operation_get","task_operation_list","task_operation_update","task_operation_delete"],deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("task-organizer",w)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let w={name:"json-extract",type:"sub",description:"JSON \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u5BF9\u8BDD\u5386\u53F2\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 JSON\uFF0C\u901A\u8FC7 workflow_submit_output \u5DE5\u5177\u63D0\u4EA4",systemPromptRef:"json-extract",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:5,filterHistory:!1};this.agents.set("json-extract",w)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let w={name:"workflow-extract",type:"sub",description:"Workflow \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 task \u7684\u5BF9\u8BDD\u5386\u53F2\u4E2D\u5206\u6790\u9700\u6C42\uFF0C\u8FED\u4EE3\u5F0F\u751F\u6210\u5E76\u9A8C\u8BC1 Workflow YAML",systemPromptRef:"workflow-extract",allowedTools:["workflow_get","workflow_list","workflow_add","workflow_validate"],deniedTools:[],maxIterations:10,filterHistory:!1};this.agents.set("workflow-extract",w)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let w={name:"workflow-creator",type:"sub",description:"Workflow \u6784\u5EFA\u5B50\u667A\u80FD\u4F53 \u2014 \u4E0E\u7528\u6237\u591A\u8F6E\u4EA4\u4E92\u5F0F\u534F\u4F5C\u8BBE\u8BA1\u3001\u9A8C\u8BC1\u5E76\u6CE8\u518C workflow",systemPromptRef:"workflow-creator",allowedTools:["workflow_list","workflow_get","workflow_search","workflow_tag_list","workflow_validate","workflow_add","bash","read_file","workflow_run","workflow_run_status"],deniedTools:["delegate_task","stop_task"],maxIterations:60};this.agents.set("workflow-creator",w)}registerCompactAgent(){if(this.agents.has("compact"))return;let w={name:"compact",type:"sub",description:"\u538B\u7F29\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 session \u7684\u5386\u53F2\u6D88\u606F\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 checkpoint JSON",systemPromptRef:"compact",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",w)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;let w={name:"compact-hint",type:"sub",description:"\u538B\u7F29\u63D0\u793A\u5B50\u667A\u80FD\u4F53 \u2014 \u5206\u6790\u7236 session \u5386\u53F2\uFF0C\u751F\u6210\u573A\u666F\u5316\u538B\u7F29\u6307\u5BFC\u63D0\u793A",systemPromptRef:"compact-hint",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact-hint",w)}registerRoyAgent(){if(this.agents.has("roy"))return;let w={name:"roy",type:"sub",description:"Roy \u2014 versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.",systemPromptRef:"roy",deniedTools:["delegate_task","stop_task"]};this.agents.set("roy",w)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch(_){return e.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return e.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let Y=tw(_,X.name);if(X.isDirectory())continue;if(!dB(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),W=this.parseAgentConfig(J,Y);if(W)this.agents.set(W.name,W),e.info(`[AgentRegistry] Loaded agent: ${W.name} from ${X.name}`),w++}catch(J){e.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}e.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){e.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=X4.default.parse(_),X=$4.safeParse($);if(!X.success)return e.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return e.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=$4.safeParse(_);if(!w.success)return e.error(`[AgentRegistry] Invalid agent config for "${_.name}": ${w.error.message}`),!1;await this.ensureConfigDir();let $=this.agentToYaml(_),X=tw(this.configDir,`${_.name}.yaml`);return await this.fsPromises.writeFile(X,$,"utf-8"),this.agents.set(_.name,_),e.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return e.error(`[AgentRegistry] Failed to save agent: ${_.name}`,{error:w}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),e.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml(_){let w={name:_.name,type:_.type,..._.description!==void 0?{description:_.description}:{},..._.systemPromptRef!==void 0?{systemPromptRef:_.systemPromptRef}:{},..._.systemPrompt!==void 0?{systemPrompt:_.systemPrompt}:{},..._.model!==void 0?{model:_.model}:{},..._.maxIterations!==void 0?{maxIterations:_.maxIterations}:{},..._.maxErrorRetries!==void 0?{maxErrorRetries:_.maxErrorRetries}:{},..._.allowedTools!==void 0?{allowedTools:_.allowedTools}:{},..._.deniedTools!==void 0?{deniedTools:_.deniedTools}:{},..._.toolTimeout!==void 0?{toolTimeout:_.toolTimeout}:{},..._.toolRetries!==void 0?{toolRetries:_.toolRetries}:{},..._.doomLoopThreshold!==void 0?{doomLoopThreshold:_.doomLoopThreshold}:{},..._.filterHistory!==void 0?{filterHistory:_.filterHistory}:{},..._.workflow!==void 0?{workflow:_.workflow}:{},..._.entryAgent!==void 0?{entryAgent:_.entryAgent}:{}};return X4.default.stringify(w).trimEnd()+`
2049
- `}async deleteAgent(_){if(!this.agents.get(_))return e.warn(`[AgentRegistry] Agent not found: ${_}`),!1;try{let $=tw(this.configDir,`${_}.yaml`);if(this.fs.existsSync($))await this.fsPromises.unlink($),e.info(`[AgentRegistry] Deleted agent file: ${$}`);return this.agents.delete(_),!0}catch($){return e.error(`[AgentRegistry] Failed to delete agent: ${_}`,{error:$}),!1}}exportAgents(_={}){let w=this.list();if(_.format==="json")return w;return w}exportAgentsAsJson(){return JSON.stringify(this.list(),null,2)}size(){return this.agents.size}configDirExists(){return this.fs.existsSync(this.configDir)}getAgentFilePath(_){return tw(this.configDir,`${_}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],M_.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],M_.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],M_.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"loadFromDirectory",null);function dB(_){return _.endsWith(".yaml")||_.endsWith(".yml")}var Y4=`You are a subagent created by the main agent to handle a specific task.
2061
+ `},eV=d2["workflow-extract"];import K4 from"os";import z_ from"path";var B1="roy-agent";function c7(){let _=K4.homedir();try{let w=e("xdg-basedir");return{config:w.xdgConfig||z_.join(_,".config"),state:w.xdgState||z_.join(_,".local","state"),data:w.xdgData||z_.join(_,".local","share"),cache:w.xdgCache||z_.join(_,".cache")}}catch{return{config:z_.join(_,".config"),state:z_.join(_,".local","state"),data:z_.join(_,".local","share"),cache:z_.join(_,".cache")}}}function d7(){let _=K4.homedir(),w=c7();return{home:_,config:z_.join(w.config,B1),state:z_.join(w.state,B1),data:z_.join(w.data,B1),cache:z_.join(w.cache,B1)}}class N4{_paths;get paths(){if(!this._paths)this._paths=d7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return z_.join(this.paths[_],w)}reset(){this._paths=void 0}}var p7=new N4;function b4(_){return p7.getPath(_)}import*as pB from"fs/promises";import*as iB from"fs";import{join as tw}from"path";var X$=KX(g5(),1);a();V_();var __=n("agent:registry"),$$=A.object({name:A.string(),type:A.enum(["primary","sub","workflow"]),workflow:A.string().optional(),entryAgent:A.string().optional(),description:A.string().optional(),systemPromptRef:A.string().optional(),systemPrompt:A.string().optional(),model:A.string().optional(),maxIterations:A.number().optional(),maxErrorRetries:A.number().optional(),allowedTools:A.array(A.string()).optional(),deniedTools:A.array(A.string()).optional(),toolTimeout:A.number().optional(),toolRetries:A.number().optional(),doomLoopThreshold:A.number().optional(),filterHistory:A.boolean().optional()}).refine((_)=>_.type!=="workflow"||_.workflow&&_.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class M_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||iB,this.fsPromises=_.fsPromises||pB;let w=this.configComponent?.get?.("agent.configDir");if(w&&typeof w==="string"&&w.length>0)this.configDir=w;else if(_.baseDir)this.configDir=tw(_.baseDir,"agents");else this.configDir=tw(b4("data"),"agents");__.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=$$.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),__.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)__.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),__.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt(_){let w=this.agents.get(_);if(!w)return;let $=this.getActivePromptComponent();if(w.systemPromptRef)try{if($?.getPrompt){let Y=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(Y)return __.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return __.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return __.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return __.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${w.systemPromptRef}`,{error:X}),w.systemPrompt}return w.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt(_){let w=this.agents.get(_);if(!w)return;return w.systemPrompt}getWorkflowName(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.workflow}getEntryAgent(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let w={name:"workflow-runner",type:"sub",description:"Workflow runner \u2014 \u63A5\u53D7\u5E26 workflow_name\uFF08\u5FC5\u586B\uFF09\u7684\u59D4\u6258\uFF0C\u6216\u6307\u793A\u5176\u6309 search-first \u6D41\u7A0B\u81EA\u884C\u9009\u5B9A\uFF08workflow_tag_list + workflow_search + workflow_list + workflow_get\uFF09\uFF0C\u7136\u540E\u901A\u8FC7 workflow_run \u6267\u884C workflow\uFF1B\u652F\u6301 session resume \u548C stop\uFF1B\u5931\u8D25\u63A5\u7BA1\u7531 prompt \u63A8\u7406\u89E6\u53D1 (Task #2251)\u3002**\u8C03\u7528\u65B9\u5FC5\u987B\u5728 prompt \u4E2D\u660E\u786E\u6307\u5B9A workflow \u540D\uFF0C\u6216\u6307\u793A sub-agent \u81EA\u884C\u641C\u7D22\u9009\u62E9\uFF1B\u7981\u6B62\u76F2\u731C/\u7ED5\u8FC7/\u8DF3\u8FC7 schema \u9A8C\u8BC1** (Task #2486)\u3002",systemPromptRef:"workflow-runner",deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("workflow-runner",w)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let w={name:"task-organizer",type:"sub",description:"\u4EFB\u52A1\u6811\u6574\u7406\u5B50\u667A\u80FD\u4F53 \u2014 \u628A\u975E longterm \u7C7B\u578B\u7684\u6839\u4EFB\u52A1\u91CD\u65B0\u6302\u8F7D\u5230 longterm \u7236\u4EFB\u52A1\u4E0B\uFF0C\u6839\u4EFB\u52A1\u6536\u655B\u5230 10-20 \u4E2A\uFF1B\u7EF4\u62A4\u4EFB\u52A1\u6811\u5F62\u6001\u5065\u5EB7\uFF08re-parent / merge / archive / delete\uFF09\u3002Task #2348\u3002",systemPromptRef:"task-organizer",allowedTools:["task_create","task_get","task_list","task_update","task_delete","task_complete","task_tree","task_search","task_batch_archive","task_batch_delete","task_operation_create","task_operation_get","task_operation_list","task_operation_update","task_operation_delete"],deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("task-organizer",w)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let w={name:"json-extract",type:"sub",description:"JSON \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u5BF9\u8BDD\u5386\u53F2\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 JSON\uFF0C\u901A\u8FC7 workflow_submit_output \u5DE5\u5177\u63D0\u4EA4",systemPromptRef:"json-extract",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:5,filterHistory:!1};this.agents.set("json-extract",w)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let w={name:"workflow-extract",type:"sub",description:"Workflow \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 task \u7684\u5BF9\u8BDD\u5386\u53F2\u4E2D\u5206\u6790\u9700\u6C42\uFF0C\u8FED\u4EE3\u5F0F\u751F\u6210\u5E76\u9A8C\u8BC1 Workflow YAML",systemPromptRef:"workflow-extract",allowedTools:["workflow_get","workflow_list","workflow_add","workflow_validate"],deniedTools:[],maxIterations:10,filterHistory:!1};this.agents.set("workflow-extract",w)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let w={name:"workflow-creator",type:"sub",description:"Workflow \u6784\u5EFA\u5B50\u667A\u80FD\u4F53 \u2014 \u4E0E\u7528\u6237\u591A\u8F6E\u4EA4\u4E92\u5F0F\u534F\u4F5C\u8BBE\u8BA1\u3001\u9A8C\u8BC1\u5E76\u6CE8\u518C workflow",systemPromptRef:"workflow-creator",allowedTools:["workflow_list","workflow_get","workflow_search","workflow_tag_list","workflow_validate","workflow_add","bash","read_file","workflow_run","workflow_run_status"],deniedTools:["delegate_task","stop_task"],maxIterations:60};this.agents.set("workflow-creator",w)}registerCompactAgent(){if(this.agents.has("compact"))return;let w={name:"compact",type:"sub",description:"\u538B\u7F29\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 session \u7684\u5386\u53F2\u6D88\u606F\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 checkpoint JSON",systemPromptRef:"compact",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",w)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;let w={name:"compact-hint",type:"sub",description:"\u538B\u7F29\u63D0\u793A\u5B50\u667A\u80FD\u4F53 \u2014 \u5206\u6790\u7236 session \u5386\u53F2\uFF0C\u751F\u6210\u573A\u666F\u5316\u538B\u7F29\u6307\u5BFC\u63D0\u793A",systemPromptRef:"compact-hint",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact-hint",w)}registerRoyAgent(){if(this.agents.has("roy"))return;let w={name:"roy",type:"sub",description:"Roy \u2014 versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.",systemPromptRef:"roy",deniedTools:["delegate_task","stop_task"]};this.agents.set("roy",w)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch(_){return __.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return __.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let Y=tw(_,X.name);if(X.isDirectory())continue;if(!nB(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),D=this.parseAgentConfig(J,Y);if(D)this.agents.set(D.name,D),__.info(`[AgentRegistry] Loaded agent: ${D.name} from ${X.name}`),w++}catch(J){__.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}__.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){__.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=X$.default.parse(_),X=$$.safeParse($);if(!X.success)return __.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return __.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=$$.safeParse(_);if(!w.success)return __.error(`[AgentRegistry] Invalid agent config for "${_.name}": ${w.error.message}`),!1;await this.ensureConfigDir();let $=this.agentToYaml(_),X=tw(this.configDir,`${_.name}.yaml`);return await this.fsPromises.writeFile(X,$,"utf-8"),this.agents.set(_.name,_),__.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return __.error(`[AgentRegistry] Failed to save agent: ${_.name}`,{error:w}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),__.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml(_){let w={name:_.name,type:_.type,..._.description!==void 0?{description:_.description}:{},..._.systemPromptRef!==void 0?{systemPromptRef:_.systemPromptRef}:{},..._.systemPrompt!==void 0?{systemPrompt:_.systemPrompt}:{},..._.model!==void 0?{model:_.model}:{},..._.maxIterations!==void 0?{maxIterations:_.maxIterations}:{},..._.maxErrorRetries!==void 0?{maxErrorRetries:_.maxErrorRetries}:{},..._.allowedTools!==void 0?{allowedTools:_.allowedTools}:{},..._.deniedTools!==void 0?{deniedTools:_.deniedTools}:{},..._.toolTimeout!==void 0?{toolTimeout:_.toolTimeout}:{},..._.toolRetries!==void 0?{toolRetries:_.toolRetries}:{},..._.doomLoopThreshold!==void 0?{doomLoopThreshold:_.doomLoopThreshold}:{},..._.filterHistory!==void 0?{filterHistory:_.filterHistory}:{},..._.workflow!==void 0?{workflow:_.workflow}:{},..._.entryAgent!==void 0?{entryAgent:_.entryAgent}:{}};return X$.default.stringify(w).trimEnd()+`
2062
+ `}async deleteAgent(_){if(!this.agents.get(_))return __.warn(`[AgentRegistry] Agent not found: ${_}`),!1;try{let $=tw(this.configDir,`${_}.yaml`);if(this.fs.existsSync($))await this.fsPromises.unlink($),__.info(`[AgentRegistry] Deleted agent file: ${$}`);return this.agents.delete(_),!0}catch($){return __.error(`[AgentRegistry] Failed to delete agent: ${_}`,{error:$}),!1}}exportAgents(_={}){let w=this.list();if(_.format==="json")return w;return w}exportAgentsAsJson(){return JSON.stringify(this.list(),null,2)}size(){return this.agents.size}configDirExists(){return this.fs.existsSync(this.configDir)}getAgentFilePath(_){return tw(this.configDir,`${_}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],M_.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],M_.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],M_.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"loadFromDirectory",null);function nB(_){return _.endsWith(".yaml")||_.endsWith(".yml")}var Y$=`You are a subagent created by the main agent to handle a specific task.
2050
2063
 
2051
2064
  ## Your Role
2052
2065
  - You were created to handle: {task_description}
@@ -2063,14 +2076,14 @@ task_operation_create({
2063
2076
  ## Execution
2064
2077
  - Use the available tools to complete the task
2065
2078
  - If you need more information, ask the main agent through the result
2066
- - Return a clear summary of what you did and the results`;import{AsyncLocalStorage as pB}from"async_hooks";var iB=new pB;function J4(_,w){return iB.run(_,w)}import{AsyncLocalStorage as nB}from"async_hooks";var W4=()=>{};function ew(){return h0.getStore()}function $1(){return h0.getStore()||{}}function y0(){return h0.getStore()?.agentContext?.currentTaskId}function I5(_){return typeof _==="number"&&Number.isInteger(_)&&_>0?_:void 0}var k5,h0,rB,v0,Jw=r(()=>{a(),V_(),W4(),k5=n("env:context:env-context"),h0=new nB,rB=I_(function(w,$){return I5(w?.metadata?.parentTaskId)??I5($?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:(_)=>({parentTaskId:_??null})}),v0=I_(function(w){let $=y0(),X=h0.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=w}k5.info(`[setCurrentTaskId] taskId=${w??"undefined"} (was: ${$??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var X1=r(()=>{Jw(),W4()});class Y1{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor(_={}){this.componentName=_.componentName??"unknown",this.componentVersion=_.componentVersion??"0.0.0",this.defaultPriority=_.defaultPriority??0}register(_,w){this.getOrCreateHooks(_).push(w)}registerMany(_,w){this.getOrCreateHooks(_).push(...w)}unregister(_,w){let $=this._hooks.get(_);if(!$)return!1;let X=$.findIndex((Y)=>Y.name===w);if(X===-1)return!1;return $.splice(X,1),!0}unregisterAll(_){this._hooks.delete(_)}async execute(_,w,$={}){let X=this._hooks.get(_),Y=process.env.ROY_HOOK_DEBUG==="1";if(Y)console.error(`[DEBUG hook-manager.execute] hookPoint=${_}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${_})`);return}let J=ew();if(Y){if(console.error(`[DEBUG hook-manager.execute] envContext=${J?"present":"absent"}`),J)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(J.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${J.sourceId}`)}if(J){if($.envContext=J,!$.pluginEnabled&&J.pluginEnabled)$.pluginEnabled=J.pluginEnabled}let W=this.sortHooks(X),Q=this.createContext(_,w,$,"before"),G=$.pluginEnabled||{};if(Y){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(G)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${W.length}:`);for(let q of W)console.error(`[DEBUG hook-manager.execute] - name=${q.name} pluginName=${q.pluginName} sourceId=${q.sourceId}`)}for(let q of W){if(q.pluginName&&q.sourceId){let H=`${q.sourceId}:${q.pluginName}`,B=G[H];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${q.name} (${H}) enabled=${B}`);if(B!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${H}] !== true, got ${JSON.stringify(B)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${q.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${q.name}`);await this.safeExecute(q,Q)}}async executeAndCollect(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return[];let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),W=[];for(let Q of Y){let G=await this.safeExecuteAndReturn(Q,J);if(G!==void 0)W.push(G)}return W}count(_){return this._hooks.get(_)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks(_){return this.count(_)>0}setComponentInfo(_,w){this.componentName=_,this.componentVersion=w}get hooks(){return this._hooks}async executeWithIntervention(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return{stopped:!1,results:[]};let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),W=[],Q=!1,G;for(let q of Y){if(Q)break;let H=await this.safeExecuteAndReturn(q,J);if(W.push(H),H&&typeof H==="object"&&"stopped"in H){let B=H;if(B.stopped)Q=!0,G=B.action}}return{stopped:Q,action:G,results:W}}getOrCreateHooks(_){let w=this._hooks.get(_);if(!w)w=[],this._hooks.set(_,w);return w}sortHooks(_){return[..._].sort((w,$)=>{let X=w.priority??this.defaultPriority,Y=$.priority??this.defaultPriority;return X-Y})}createContext(_,w,$,X){return{component:{name:this.componentName,version:this.componentVersion},data:w,metadata:$,phase:X,hookPoint:_}}async safeExecute(_,w){try{let $=_.execute(w);if($&&typeof $==="object"&&typeof $.then==="function")await $}catch($){console.error(`Hook "${_.name}" failed:`,$)}}async safeExecuteAndReturn(_,w){try{return await _.execute(w)}catch($){console.error(`Hook "${_.name}" failed:`,$);return}}}var Q4=r(()=>{X1()});function aB(){let _=E_.register.bind(E_);E_.register=function(w,$){_(w,$);let X=g5[w];if(X)_(X,$)}}var E_,oB,sB,tB,g5,_0=r(()=>{Q4(),E_=new Y1,oB={BEFORE_START:"agent:before.start",BEFORE_LLM:"agent:before.llm",AFTER_LLM:"agent:after.llm",BEFORE_TOOL:"agent:before.tool",AFTER_TOOL:"agent:after.tool",ON_ITERATION:"agent:on.iteration",ON_THRESHOLD:"agent:on.threshold",AFTER_COMPLETE:"agent:after.complete",ON_ERROR:"agent:on.error"},sB={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},tB={BEFORE_EXECUTE:"tool:before.execute",AFTER_EXECUTE:"tool:after.execute",BEFORE_REGISTER:"tool:before.register",AFTER_REGISTER:"tool:after.register",ON_ERROR:"tool:on.error"},g5={"before.tool":"tool:before.execute","after.tool":"tool:after.execute","llm.before-invoke":"llm:before.invoke","llm.after-invoke":"llm:after.invoke","llm.stream":"llm:on.stream","prompt.before-render":"prompt:before.render","prompt.after-render":"prompt:after.render","prompt:before.render":"prompt.before-render","prompt:after.render":"prompt.after-render","prompt:after-render":"prompt.after-render","prompt:before-render":"prompt.before-render"},aB()});a();V_();X1();function eB(_,w){if(D4(_))return!0;return w?.hasAgent(_)??!1}async function _U(_,w={}){let X=(w.getBuiltIn??D4)(_),Y=w.registry?.get(_);if(!X&&!Y)return;if(Y)return wU(_,Y,X,w.registry);return{subagentType:_,description:X.description,basePrompt:X.promptOverride||Y4,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function wU(_,w,$,X){let Y=X?await X.getSystemPrompt(_):w.systemPrompt;return{subagentType:_,description:w.description||$?.description||"Custom agent",basePrompt:Y||$?.promptOverride||Y4,allowedTools:w.allowedTools??$?.allowedTools,deniedTools:w.deniedTools??$?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function $U(_){return`
2079
+ - Return a clear summary of what you did and the results`;import{AsyncLocalStorage as rB}from"async_hooks";var aB=new rB;function J$(_,w){return aB.run(_,w)}import{AsyncLocalStorage as oB}from"async_hooks";var D$=()=>{};function ew(){return h0.getStore()}function $2(){return h0.getStore()||{}}function y0(){return h0.getStore()?.agentContext?.currentTaskId}function h5(_){return typeof _==="number"&&Number.isInteger(_)&&_>0?_:void 0}var y5,h0,sB,v0,Dw=r(()=>{a(),V_(),D$(),y5=n("env:context:env-context"),h0=new oB,sB=I_(function(w,$){return h5(w?.metadata?.parentTaskId)??h5($?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:(_)=>({parentTaskId:_??null})}),v0=I_(function(w){let $=y0(),X=h0.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=w}y5.info(`[setCurrentTaskId] taskId=${w??"undefined"} (was: ${$??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var X2=r(()=>{Dw(),D$()});class Y2{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor(_={}){this.componentName=_.componentName??"unknown",this.componentVersion=_.componentVersion??"0.0.0",this.defaultPriority=_.defaultPriority??0}register(_,w){this.getOrCreateHooks(_).push(w)}registerMany(_,w){this.getOrCreateHooks(_).push(...w)}unregister(_,w){let $=this._hooks.get(_);if(!$)return!1;let X=$.findIndex((Y)=>Y.name===w);if(X===-1)return!1;return $.splice(X,1),!0}unregisterAll(_){this._hooks.delete(_)}async execute(_,w,$={}){let X=this._hooks.get(_),Y=process.env.ROY_HOOK_DEBUG==="1";if(Y)console.error(`[DEBUG hook-manager.execute] hookPoint=${_}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${_})`);return}let J=ew();if(Y){if(console.error(`[DEBUG hook-manager.execute] envContext=${J?"present":"absent"}`),J)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(J.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${J.sourceId}`)}if(J){if($.envContext=J,!$.pluginEnabled&&J.pluginEnabled)$.pluginEnabled=J.pluginEnabled}let D=this.sortHooks(X),W=this.createContext(_,w,$,"before"),G=$.pluginEnabled||{};if(Y){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(G)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${D.length}:`);for(let Q of D)console.error(`[DEBUG hook-manager.execute] - name=${Q.name} pluginName=${Q.pluginName} sourceId=${Q.sourceId}`)}for(let Q of D){if(Q.pluginName&&Q.sourceId){let q=`${Q.sourceId}:${Q.pluginName}`,H=G[q];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${Q.name} (${q}) enabled=${H}`);if(H!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${q}] !== true, got ${JSON.stringify(H)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${Q.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${Q.name}`);await this.safeExecute(Q,W)}}async executeAndCollect(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return[];let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),D=[];for(let W of Y){let G=await this.safeExecuteAndReturn(W,J);if(G!==void 0)D.push(G)}return D}count(_){return this._hooks.get(_)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks(_){return this.count(_)>0}setComponentInfo(_,w){this.componentName=_,this.componentVersion=w}get hooks(){return this._hooks}async executeWithIntervention(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return{stopped:!1,results:[]};let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),D=[],W=!1,G;for(let Q of Y){if(W)break;let q=await this.safeExecuteAndReturn(Q,J);if(D.push(q),q&&typeof q==="object"&&"stopped"in q){let H=q;if(H.stopped)W=!0,G=H.action}}return{stopped:W,action:G,results:D}}getOrCreateHooks(_){let w=this._hooks.get(_);if(!w)w=[],this._hooks.set(_,w);return w}sortHooks(_){return[..._].sort((w,$)=>{let X=w.priority??this.defaultPriority,Y=$.priority??this.defaultPriority;return X-Y})}createContext(_,w,$,X){return{component:{name:this.componentName,version:this.componentVersion},data:w,metadata:$,phase:X,hookPoint:_}}async safeExecute(_,w){try{let $=_.execute(w);if($&&typeof $==="object"&&typeof $.then==="function")await $}catch($){console.error(`Hook "${_.name}" failed:`,$)}}async safeExecuteAndReturn(_,w){try{return await _.execute(w)}catch($){console.error(`Hook "${_.name}" failed:`,$);return}}}var W$=r(()=>{X2()});function tB(){let _=E_.register.bind(E_);E_.register=function(w,$){_(w,$);let X=v5[w];if(X)_(X,$)}}var E_,eB,_U,wU,v5,_0=r(()=>{W$(),E_=new Y2,eB={BEFORE_START:"agent:before.start",BEFORE_LLM:"agent:before.llm",AFTER_LLM:"agent:after.llm",BEFORE_TOOL:"agent:before.tool",AFTER_TOOL:"agent:after.tool",ON_ITERATION:"agent:on.iteration",ON_THRESHOLD:"agent:on.threshold",AFTER_COMPLETE:"agent:after.complete",ON_ERROR:"agent:on.error"},_U={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},wU={BEFORE_EXECUTE:"tool:before.execute",AFTER_EXECUTE:"tool:after.execute",BEFORE_REGISTER:"tool:before.register",AFTER_REGISTER:"tool:after.register",ON_ERROR:"tool:on.error"},v5={"before.tool":"tool:before.execute","after.tool":"tool:after.execute","llm.before-invoke":"llm:before.invoke","llm.after-invoke":"llm:after.invoke","llm.stream":"llm:on.stream","prompt.before-render":"prompt:before.render","prompt.after-render":"prompt:after.render","prompt:before.render":"prompt.before-render","prompt:after.render":"prompt.after-render","prompt:after-render":"prompt.after-render","prompt:before-render":"prompt.before-render"},tB()});a();V_();X2();function $U(_,w){if(H$(_))return!0;return w?.hasAgent(_)??!1}async function XU(_,w={}){let X=(w.getBuiltIn??H$)(_),Y=w.registry?.get(_);if(!X&&!Y)return;if(Y)return YU(_,Y,X,w.registry);return{subagentType:_,description:X.description,basePrompt:X.promptOverride||Y$,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function YU(_,w,$,X){let Y=X?await X.getSystemPrompt(_):w.systemPrompt;return{subagentType:_,description:w.description||$?.description||"Custom agent",basePrompt:Y||$?.promptOverride||Y$,allowedTools:w.allowedTools??$?.allowedTools,deniedTools:w.deniedTools??$?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function JU(_){return`
2067
2080
  ## Agent Selection Guide
2068
2081
 
2069
2082
  - Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
2070
2083
  ${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
2071
- - For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function XU(_){let w=q4.map((W)=>`- ${W.id}: ${W.description}`),X=(_?.list()??[]).filter((W)=>!q4.some((Q)=>Q.id===W.name)).map((W)=>{if(W.type==="workflow"){let Q=W.workflow?` (workflow: ${W.workflow})`:"";return`- ${W.name}: ${W.description||"Workflow agent"}${Q}`}return`- ${W.name}: ${W.description||"Custom agent"}`}),Y=[...w,...X],J=$U({hasCustomAgents:X.length>0});return Y.join(`
2072
- `)+J}_0();var YU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function JU(_){let w=_;for(let $ of YU)w=w.replace($,"<redacted>");return w}function WU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function h5(_,w){return WU(JU(_),w)}class H4{maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor(_={}){this.maxEntries=_.maxEntries??500,this.ttlMs=_.ttlMs??86400000,this.maxDescriptionChars=_.maxDescriptionChars??240}record(_,w={}){let $=new Date().toISOString(),X=this.toRecord(_,w,$);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update(_,w){let $=this.records.get(_.id);if(!$)return;let X=new Date().toISOString();this.records.delete(_.id);let Y={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove(_){let w=this.records.get(_);if(!w)return!1;if(this.records.delete(_),w.parentTaskId!==void 0){let $=this.childrenIndex.get(w.parentTaskId);if($?.delete(_),$&&$.size===0)this.childrenIndex.delete(w.parentTaskId)}return!0}getById(_){let w=this.records.get(_);if(!w)return;if(Date.now()-Date.parse(w.updatedAt)>this.ttlMs){this.remove(_);return}return w}peekById(_){return this.records.get(_)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent(_={}){let w=_.limit??10,$=_.statuses,X=new Set(_.excludeIds??[]),Y=_.excludeAncestorOf??_.excludeSelfOrDescendant,J=Y?this.collectSubtree(Y):new Set,W=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,Q=Date.now(),G=new Set([...X,...J]),q=[];for(let H of this.records.values()){if(Q-Date.parse(H.updatedAt)>this.ttlMs)continue;if(W>0&&Date.parse(H.updatedAt)<W)continue;if(G.has(H.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&H.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&H.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&H.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(H.status))continue}else if(H.status==="archived")continue;q.push(H)}if(_.activeChildFirst){let H=new Map;for(let B of q)H.set(B.taskId,this.hasActiveChild(B.taskId));q.sort((B,D)=>{let O=H.get(B.taskId)?1:0,z=H.get(D.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(D.updatedAt)-Date.parse(B.updatedAt);if(U!==0)return U;return D.taskId-B.taskId})}else q.sort((H,B)=>{let D=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(D!==0)return D;return B.taskId-H.taskId});return q.slice(0,w)}getSubtreeSummary(_,w={}){let $=w.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has(_)&&!this.childrenIndex.has(_))return X;let Y=this.childrenIndex.get(_),J=Y?Array.from(Y):[],W=J.length>0?1:0;X.maxDepth=W;let Q=J;while(Q.length>0){let G=[];for(let q of Q){let H=this.records.get(q);if(!H)continue;if(!$&&H.status==="archived")continue;if(X.descendantCount++,H.status==="active")X.activeCount++;else if(H.status==="completed")X.completedCount++;let B=this.childrenIndex.get(q);if(B&&B.size>0)for(let D of B)G.push(D)}if(G.length>0)W++,X.maxDepth=W;Q=G}return X}hasActiveChild(_){let w=this.childrenIndex.get(_);if(!w)return!1;for(let $ of w){let X=this.records.get($);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord(_,w,$){let X=this.safeParseContext(_.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:h5(_.description||"",this.maxDescriptionChars),goals:h5(_.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:_.tags??[],status:_.status,priority:_.priority,type:_.type,parentTaskId:_.parent_task_id,source:w,createdAt:_.createdAt||$,updatedAt:_.updatedAt||$,operationCount:0,project_path:_.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext(_){if(!_||!_.trim())return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}pickString(_,w){if(!_)return;let $=_[w];return typeof $==="string"?$:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>this.stripSensitiveKeys(X));if(typeof _!=="object")return _;let w={},$=H4.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((W)=>J.includes(W)))continue;w[X]=this.stripSensitiveKeys(Y)}return w}upsert(_){this.records.set(_.taskId,_)}indexParentChild(_){if(_.parentTaskId===void 0||_.parentTaskId===null)return;let w=_.parentTaskId,$=this.childrenIndex.get(w);if(!$)$=new Set,this.childrenIndex.set(w,$);$.add(_.taskId)}collectSubtree(_){let w=new Set([_]),$=[_];while($.length>0){let X=$.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let J of Y)if(!w.has(J))w.add(J),$.push(J)}return w}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let _=this.records.size-this.maxEntries,w=Array.from(this.records.keys()).slice(0,_);for(let $ of w)this.remove($)}}a();var J1=n("registry-hook-installer");function QU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,J=$.priority??100,W=!1,Q=(U,V)=>{try{w.record(U,V)}catch(M){J1.warn(`[registry-hook-installer] record failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(M){J1.warn(`[registry-hook-installer] update failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},q=(U)=>{try{w.remove(U)}catch(V){J1.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},H=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),B={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)Q(V.task,H())}},D={name:`${Y}:after-update`,priority:J,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,H());else Q(V.task,H())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,H())}},z={name:`${Y}:after-delete`,priority:J,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")q(V.id)}};return _.registerHook($_.AFTER_CREATE,B),_.registerHook($_.AFTER_UPDATE,D),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(W)return;W=!0,_.unregisterHook($_.AFTER_CREATE,B.name),_.unregisterHook($_.AFTER_UPDATE,D.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),J1.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var G4=n("task-reuse-registry"),GU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},y5=new WeakMap;function qU(_){let w=y5.get(_);if(w)return w.registry;let $=new H4(GU),X={uninstall:()=>{}};try{let J=_.getComponent?.("task");if(J?.registerHook)X=QU(J,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),G4.debug("[task-reuse-registry] hook installed");else G4.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){G4.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return y5.set(_,Y),$}var HU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function DU(_){let w=_;for(let $ of HU)w=w.replace($,"<redacted>");return w}function v5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function BU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,Y=_.heading??"Recent task context (reuse candidates)",J=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(J.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let W=[];W.push(`## ${Y}`),W.push(""),W.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),W.push("");for(let G of J){if(W.push(`### Task #${G.taskId}: ${G.title}`),W.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)W.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)W.push(`- Created by: ${G.source.subagentType}`);if(W.push(`- Updated: ${G.updatedAt}`),G.project_path)W.push(`- Project: ${G.project_path}`);if(G.worktree_path)W.push(`- Worktree: ${G.worktree_path}`);if(G.branch)W.push(`- Branch: ${G.branch}`);if(G.parentBranch)W.push(`- Parent branch: ${G.parentBranch}`);let q;try{q=_.registry.getSubtreeSummary(G.taskId)}catch{q=void 0}if(q&&q.descendantCount>0)W.push(`- Children: ${q.descendantCount} (active: ${q.activeCount}, completed: ${q.completedCount}, max depth: ${q.maxDepth})`);let H=q!==void 0&&q.activeCount>0;if(G.status==="completed"&&H)W.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let B=DU(v5(G.description,X));if(B)W.push(`- Description: ${B}`);if(G.tags&&G.tags.length>0)W.push(`- Tags: ${G.tags.join(", ")}`);W.push("")}W.push("---"),W.push(""),W.push("### Reuse instructions"),W.push(""),W.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),W.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),W.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),W.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),W.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),W.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),W.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),W.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),W.push(""),W.push("### Decision matrix \u2014 three legal paths"),W.push(""),W.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),W.push("remains the default, but the matrix adds two new paths for independent work."),W.push(""),W.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),W.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),W.push("append description/goals. Do **not** create a new task id."),W.push(""),W.push("```"),W.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),W.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),W.push(' milestone_title: "Reopened for <new-scope>",'),W.push(' milestone_description: "<why this is the same work>" })'),W.push("```"),W.push(""),W.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),W.push("distinct: an independent bug fix, optimization, parallel delivery or"),W.push("independent acceptance item under the same feature. Create a child task so"),W.push("the audit trail is preserved. Always pair with an audit operation."),W.push(""),W.push("```");for(let G of J){let q=G.project_path??"<project_path>";W.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${q}", context=<inherit or override>)`);break}W.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),W.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),W.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),W.push("```"),W.push(""),W.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),W.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),W.push("should stay \u2264 ~10 to keep the tree readable."),W.push(""),W.push("```"),W.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),W.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),W.push(' milestone_title: "New root: <topic>",'),W.push(' milestone_description: "<why this is not a child of any existing task>" })'),W.push("```"),W.push(""),W.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),W.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),W.push("chosen. Use the appropriate `milestone_type`:"),W.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),W.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),W.push(" - new root \u2192 `create` (then `progress` per phase)"),W.push(""),W.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),W.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),W.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),W.push("tokens, secrets) are stripped automatically. Use the helper:"),W.push(""),W.push("```"),W.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),W.push("```"),W.push("");let Q=W.join(`
2073
- `);if(Q.length>$)Q=v5(Q,$);return{markdown:Q,candidateIds:J.map((G)=>G.taskId),isEmpty:!1}}var h=n("task:delegate"),c_={STARTED:"task.background.started",PROGRESS:"task.background.progress",COMPLETED:"task.background.completed",FAILED:"task.background.failed",TIMEOUT:"task.background.timeout",STOPPED:"task.background.stopped",ASK_USER:"task.background.ask_user"},q4=[{id:"general",name:"general",mode:"subagent",description:"General-purpose agent for researching complex questions and executing multi-step tasks.",promptOverride:`You are a subagent created by the main agent to handle a specific task.
2084
+ - For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function DU(_){let w=Q$.map((D)=>`- ${D.id}: ${D.description}`),X=(_?.list()??[]).filter((D)=>!Q$.some((W)=>W.id===D.name)).map((D)=>{if(D.type==="workflow"){let W=D.workflow?` (workflow: ${D.workflow})`:"";return`- ${D.name}: ${D.description||"Workflow agent"}${W}`}return`- ${D.name}: ${D.description||"Custom agent"}`}),Y=[...w,...X],J=JU({hasCustomAgents:X.length>0});return Y.join(`
2085
+ `)+J}_0();var WU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function GU(_){let w=_;for(let $ of WU)w=w.replace($,"<redacted>");return w}function QU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function x5(_,w){return QU(GU(_),w)}class q${maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor(_={}){this.maxEntries=_.maxEntries??500,this.ttlMs=_.ttlMs??86400000,this.maxDescriptionChars=_.maxDescriptionChars??240}record(_,w={}){let $=new Date().toISOString(),X=this.toRecord(_,w,$);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update(_,w){let $=this.records.get(_.id);if(!$)return;let X=new Date().toISOString();this.records.delete(_.id);let Y={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove(_){let w=this.records.get(_);if(!w)return!1;if(this.records.delete(_),w.parentTaskId!==void 0){let $=this.childrenIndex.get(w.parentTaskId);if($?.delete(_),$&&$.size===0)this.childrenIndex.delete(w.parentTaskId)}return!0}getById(_){let w=this.records.get(_);if(!w)return;if(Date.now()-Date.parse(w.updatedAt)>this.ttlMs){this.remove(_);return}return w}peekById(_){return this.records.get(_)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent(_={}){let w=_.limit??10,$=_.statuses,X=new Set(_.excludeIds??[]),Y=_.excludeAncestorOf??_.excludeSelfOrDescendant,J=Y?this.collectSubtree(Y):new Set,D=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,W=Date.now(),G=new Set([...X,...J]),Q=[];for(let q of this.records.values()){if(W-Date.parse(q.updatedAt)>this.ttlMs)continue;if(D>0&&Date.parse(q.updatedAt)<D)continue;if(G.has(q.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&q.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&q.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&q.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(q.status))continue}else if(q.status==="archived")continue;Q.push(q)}if(_.activeChildFirst){let q=new Map;for(let H of Q)q.set(H.taskId,this.hasActiveChild(H.taskId));Q.sort((H,B)=>{let O=q.get(H.taskId)?1:0,z=q.get(B.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(U!==0)return U;return B.taskId-H.taskId})}else Q.sort((q,H)=>{let B=Date.parse(H.updatedAt)-Date.parse(q.updatedAt);if(B!==0)return B;return H.taskId-q.taskId});return Q.slice(0,w)}getSubtreeSummary(_,w={}){let $=w.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has(_)&&!this.childrenIndex.has(_))return X;let Y=this.childrenIndex.get(_),J=Y?Array.from(Y):[],D=J.length>0?1:0;X.maxDepth=D;let W=J;while(W.length>0){let G=[];for(let Q of W){let q=this.records.get(Q);if(!q)continue;if(!$&&q.status==="archived")continue;if(X.descendantCount++,q.status==="active")X.activeCount++;else if(q.status==="completed")X.completedCount++;let H=this.childrenIndex.get(Q);if(H&&H.size>0)for(let B of H)G.push(B)}if(G.length>0)D++,X.maxDepth=D;W=G}return X}hasActiveChild(_){let w=this.childrenIndex.get(_);if(!w)return!1;for(let $ of w){let X=this.records.get($);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord(_,w,$){let X=this.safeParseContext(_.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:x5(_.description||"",this.maxDescriptionChars),goals:x5(_.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:_.tags??[],status:_.status,priority:_.priority,type:_.type,parentTaskId:_.parent_task_id,source:w,createdAt:_.createdAt||$,updatedAt:_.updatedAt||$,operationCount:0,project_path:_.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext(_){if(!_||!_.trim())return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}pickString(_,w){if(!_)return;let $=_[w];return typeof $==="string"?$:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>this.stripSensitiveKeys(X));if(typeof _!=="object")return _;let w={},$=q$.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((D)=>J.includes(D)))continue;w[X]=this.stripSensitiveKeys(Y)}return w}upsert(_){this.records.set(_.taskId,_)}indexParentChild(_){if(_.parentTaskId===void 0||_.parentTaskId===null)return;let w=_.parentTaskId,$=this.childrenIndex.get(w);if(!$)$=new Set,this.childrenIndex.set(w,$);$.add(_.taskId)}collectSubtree(_){let w=new Set([_]),$=[_];while($.length>0){let X=$.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let J of Y)if(!w.has(J))w.add(J),$.push(J)}return w}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let _=this.records.size-this.maxEntries,w=Array.from(this.records.keys()).slice(0,_);for(let $ of w)this.remove($)}}a();var J2=n("registry-hook-installer");function qU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,J=$.priority??100,D=!1,W=(U,V)=>{try{w.record(U,V)}catch(M){J2.warn(`[registry-hook-installer] record failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(M){J2.warn(`[registry-hook-installer] update failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},Q=(U)=>{try{w.remove(U)}catch(V){J2.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},q=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),H={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)W(V.task,q())}},B={name:`${Y}:after-update`,priority:J,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,q());else W(V.task,q())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,q())}},z={name:`${Y}:after-delete`,priority:J,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")Q(V.id)}};return _.registerHook($_.AFTER_CREATE,H),_.registerHook($_.AFTER_UPDATE,B),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(D)return;D=!0,_.unregisterHook($_.AFTER_CREATE,H.name),_.unregisterHook($_.AFTER_UPDATE,B.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),J2.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var G$=n("task-reuse-registry"),HU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},m5=new WeakMap;function BU(_){let w=m5.get(_);if(w)return w.registry;let $=new q$(HU),X={uninstall:()=>{}};try{let J=_.getComponent?.("task");if(J?.registerHook)X=qU(J,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),G$.debug("[task-reuse-registry] hook installed");else G$.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){G$.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return m5.set(_,Y),$}var UU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function zU(_){let w=_;for(let $ of UU)w=w.replace($,"<redacted>");return w}function u5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function VU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,Y=_.heading??"Recent task context (reuse candidates)",J=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(J.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let D=[];D.push(`## ${Y}`),D.push(""),D.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),D.push("");for(let G of J){if(D.push(`### Task #${G.taskId}: ${G.title}`),D.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)D.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)D.push(`- Created by: ${G.source.subagentType}`);if(D.push(`- Updated: ${G.updatedAt}`),G.project_path)D.push(`- Project: ${G.project_path}`);if(G.worktree_path)D.push(`- Worktree: ${G.worktree_path}`);if(G.branch)D.push(`- Branch: ${G.branch}`);if(G.parentBranch)D.push(`- Parent branch: ${G.parentBranch}`);let Q;try{Q=_.registry.getSubtreeSummary(G.taskId)}catch{Q=void 0}if(Q&&Q.descendantCount>0)D.push(`- Children: ${Q.descendantCount} (active: ${Q.activeCount}, completed: ${Q.completedCount}, max depth: ${Q.maxDepth})`);let q=Q!==void 0&&Q.activeCount>0;if(G.status==="completed"&&q)D.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let H=zU(u5(G.description,X));if(H)D.push(`- Description: ${H}`);if(G.tags&&G.tags.length>0)D.push(`- Tags: ${G.tags.join(", ")}`);D.push("")}D.push("---"),D.push(""),D.push("### Reuse instructions"),D.push(""),D.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),D.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),D.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),D.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),D.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),D.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),D.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),D.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),D.push(""),D.push("### Decision matrix \u2014 three legal paths"),D.push(""),D.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),D.push("remains the default, but the matrix adds two new paths for independent work."),D.push(""),D.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),D.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),D.push("append description/goals. Do **not** create a new task id."),D.push(""),D.push("```"),D.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),D.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),D.push(' milestone_title: "Reopened for <new-scope>",'),D.push(' milestone_description: "<why this is the same work>" })'),D.push("```"),D.push(""),D.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),D.push("distinct: an independent bug fix, optimization, parallel delivery or"),D.push("independent acceptance item under the same feature. Create a child task so"),D.push("the audit trail is preserved. Always pair with an audit operation."),D.push(""),D.push("```");for(let G of J){let Q=G.project_path??"<project_path>";D.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${Q}", context=<inherit or override>)`);break}D.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),D.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),D.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),D.push("```"),D.push(""),D.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),D.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),D.push("should stay \u2264 ~10 to keep the tree readable."),D.push(""),D.push("```"),D.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),D.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),D.push(' milestone_title: "New root: <topic>",'),D.push(' milestone_description: "<why this is not a child of any existing task>" })'),D.push("```"),D.push(""),D.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),D.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),D.push("chosen. Use the appropriate `milestone_type`:"),D.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),D.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),D.push(" - new root \u2192 `create` (then `progress` per phase)"),D.push(""),D.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),D.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),D.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),D.push("tokens, secrets) are stripped automatically. Use the helper:"),D.push(""),D.push("```"),D.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),D.push("```"),D.push("");let W=D.join(`
2086
+ `);if(W.length>$)W=u5(W,$);return{markdown:W,candidateIds:J.map((G)=>G.taskId),isEmpty:!1}}var h=n("task:delegate"),c_={STARTED:"task.background.started",PROGRESS:"task.background.progress",COMPLETED:"task.background.completed",FAILED:"task.background.failed",TIMEOUT:"task.background.timeout",STOPPED:"task.background.stopped",ASK_USER:"task.background.ask_user"},Q$=[{id:"general",name:"general",mode:"subagent",description:"General-purpose agent for researching complex questions and executing multi-step tasks.",promptOverride:`You are a subagent created by the main agent to handle a specific task.
2074
2087
 
2075
2088
  ## Your Role
2076
2089
  - You were created to handle: {task_description}
@@ -2121,7 +2134,7 @@ ${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
2121
2134
  ## Execution
2122
2135
  - Use the available tools to complete the task
2123
2136
  - If you need more information, ask the main agent through the result
2124
- - Return a clear summary of what you did and the results`,deniedTools:["delegate_task","stop_task"]},{id:"explore",name:"explore",mode:"subagent",description:"Fast agent specialized for exploring codebases, finding files, and searching for patterns.",allowedTools:["read_file","glob","grep","bash"],deniedTools:["delegate_task","stop_task"]},{id:"roy",name:"Roy",mode:"subagent",description:"Versatile AI assistant inspired by Jarvis \u2014 intelligent, proactive, and capable. Use for general-purpose tasks, coding, research, and complex multi-step work. Always available (built-in) without `agent add roy`.",promptOverride:d1.roy,deniedTools:["delegate_task","stop_task"]}];function D4(_){return q4.find((w)=>w.id===_)}function UU(_,w,$,X,Y){let J=_.getRegistry?.();if(J){if(J.get(w)?.type==="workflow")return h.debug(`[delegate] Skipping registration for workflow agent: ${w}`),null}let W=_.getAgent(w);if(!W){let Q={type:"sub",systemPrompt:$};if(X?.allowedTools&&X.allowedTools.length>0)Q.allowedTools=X.allowedTools;if(Y.length>0)Q.deniedTools=Y;W=_.registerAgent(w,Q),h.debug(`[delegate] Registered subagent: ${w}`)}return W}var x5=A.object({description:A.string().describe("A short (3-5 words) description of the task"),prompt:A.string().describe("The task for the agent to perform"),subagent_type:A.string().describe("The type of specialized agent to use for this task").default("general"),timeout:A.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:A.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:A.array(A.number()).max(3).describe("Similar task IDs (max 3) to reference for improving task execution. Search for similar tasks before calling this tool."),sub_session_id:A.string().describe("Existing sub-agent session ID to resume. If provided, the sub-agent will continue from the previous conversation context (used for retry on timeout/failure). Leave empty for a new session.").optional(),triggerEventId:A.string().describe("EventStore trigger event ID (ESPlugin v2). Pass it when this delegate_task is triggered by an external event source (e.g. Feishu message) so the completion notification can reply to the original chat instead of a fallback channel. Leave empty if not triggered by an event source.").optional()});function zU(_){let{workflowName:w,originalPrompt:$,description:X}=_;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
2137
+ - Return a clear summary of what you did and the results`,deniedTools:["delegate_task","stop_task"]},{id:"explore",name:"explore",mode:"subagent",description:"Fast agent specialized for exploring codebases, finding files, and searching for patterns.",allowedTools:["read_file","glob","grep","bash"],deniedTools:["delegate_task","stop_task"]},{id:"roy",name:"Roy",mode:"subagent",description:"Versatile AI assistant inspired by Jarvis \u2014 intelligent, proactive, and capable. Use for general-purpose tasks, coding, research, and complex multi-step work. Always available (built-in) without `agent add roy`.",promptOverride:d2.roy,deniedTools:["delegate_task","stop_task"]}];function H$(_){return Q$.find((w)=>w.id===_)}function OU(_,w,$,X,Y){let J=_.getRegistry?.();if(J){if(J.get(w)?.type==="workflow")return h.debug(`[delegate] Skipping registration for workflow agent: ${w}`),null}let D=_.getAgent(w);if(!D){let W={type:"sub",systemPrompt:$};if(X?.allowedTools&&X.allowedTools.length>0)W.allowedTools=X.allowedTools;if(Y.length>0)W.deniedTools=Y;D=_.registerAgent(w,W),h.debug(`[delegate] Registered subagent: ${w}`)}return D}var l5=A.object({description:A.string().describe("A short (3-5 words) description of the task"),prompt:A.string().describe("The task for the agent to perform"),subagent_type:A.string().describe("The type of specialized agent to use for this task").default("general"),timeout:A.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:A.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:A.array(A.number()).max(3).describe("Similar task IDs (max 3) to reference for improving task execution. Search for similar tasks before calling this tool."),sub_session_id:A.string().describe("Existing sub-agent session ID to resume. If provided, the sub-agent will continue from the previous conversation context (used for retry on timeout/failure). Leave empty for a new session.").optional(),triggerEventId:A.string().describe("EventStore trigger event ID (ESPlugin v2). Pass it when this delegate_task is triggered by an external event source (e.g. Feishu message) so the completion notification can reply to the original chat instead of a fallback channel. Leave empty if not triggered by an event source.").optional()});function AU(_){let{workflowName:w,originalPrompt:$,description:X}=_;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
2125
2138
 
2126
2139
  \u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${w}**\u3002
2127
2140
  \u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
@@ -2145,13 +2158,13 @@ ${$}
2145
2158
  4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
2146
2159
 
2147
2160
  \u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
2148
- `}var VU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),W1=1800000,OU=1200000;class __{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor(_){this.env=_}setWorkflowService(_){this.workflowService=_}attachWorkflowRun(_,w){if(!_||!w)return;let $=this.workflowRunRegistries.get(_);if(!$)$=new Set,this.workflowRunRegistries.set(_,$);$.add(w)}detachWorkflowRun(_,w){this.workflowRunRegistries.get(_)?.delete(w)}replaceWorkflowRun(_,w,$){if(!_)return;let X=this.workflowRunRegistries.get(_);if(!X)return;if(w)X.delete(w);if($)X.add($)}async propagateStopToWorkflowRuns(_,w){let $=this.workflowRunRegistries.get(_);if(!$||$.size===0)return{runIds:[],stopResults:[]};let X=Array.from($);h.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${_}`);let Y=[];for(let J of X){if(typeof this.workflowService?.stopRun!=="function"){h.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${J}`),Y.push({runId:J,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(J,w),Y.push({runId:J,success:!0})}catch(W){let Q=W instanceof Error?W.message:String(W);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${Q}`),Y.push({runId:J,success:!1,error:Q})}}return $.clear(),{runIds:X,stopResults:Y}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let J=this.terminalTasks.keys().next().value;if(J!==void 0)this.terminalTasks.delete(J)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let Y=this.processRegistries.get(_);if(Y&&Y.size()>0)h.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${Y.size()}, reason=${w})`);h.debug(`[BackgroundTaskManager] finalizeTask taskId=${_} reason=${w}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let _=0;for(let[w,$]of this.processRegistries)if($.size()===0)this.processRegistries.delete(w),_++;return _}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent(_){try{if(__.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${__.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),__.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??__.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=I_((_)=>VU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return __._detectWorkflowShortcutWrapped(_)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession(_){if(!_)return;try{let $=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.(_);return typeof $==="number"&&$>0?$:void 0}catch(w){h.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${_}: ${w instanceof Error?w.message:String(w)}`);return}}publishBackgroundEvent(_,w,$,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),h.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,Y){this.publishBackgroundEvent(_,w,$,X,Y)}static parseAskUserErrorFromMessage(_){let w=_ instanceof Error?_.message:String(_);if(_&&typeof _==="object"&&_.name==="AskUserError"&&_.query){let X=_;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:w}}let $="__ASK_USER_ERROR__:";if(w.includes($))try{let X=w.substring(w.indexOf($)+$.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:w}}catch(X){return h.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask(_){let{parentSessionId:w,description:$,prompt:X,subagentType:Y,timeout:J,similarTaskIds:W,existingSubSessionId:Q,triggerEventId:G}=_,q=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,H=this.getSessionComponent();if(!H)throw Error("SessionComponent not found");if(!await H.get(w))throw Error(`Parent session not found: ${w}`);let D;if(Q){let R=await H.get(Q);if(!R)throw Error(`Sub session not found for resume: ${Q}`);let b=R?.metadata?.created_by;if(b&&b!=="subagent")h.warn(`[BackgroundTaskManager] Session ${Q} was not created by a sub-agent (created_by=${b}); reusing anyway`);D=R;try{let F=R?.metadata??{};await H.update(Q,{metadata:{...F,reused_sub_session:!0,reused_at:Date.now()}})}catch(F){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:Q,error:F instanceof Error?F.message:String(F)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${Q} for task ${q}`)}else{let R={subagent_type:Y,created_by:"subagent",task_description:$},b=ew();if(b){if(b.messageId)R.messageId=b.messageId;let F=b.replyChannel;if(F?.messageId)R.larkMessageId=F.messageId;if(F?.chatId)R.chatId=F.chatId;if(F?.userId)R.larkUserId=F.userId;let T=F?.profile;if(T)R.larkProfile=T}if(G)R.triggerEventId=G;if(D=await H.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:R}),!D)throw Error("Failed to create sub-session")}let O=fU(),z=new AbortController;if(this.processRegistries.size>=this.maxProcessRegistries){if(this.cleanupEmptyProcessRegistries(),this.processRegistries.size>=this.maxProcessRegistries)throw Error(`BackgroundTaskManager.processRegistries \u8FBE\u5230\u4E0A\u9650 ${this.maxProcessRegistries}\uFF08\u542B\u6B8B\u7559 PID\uFF09\uFF0C\u62D2\u7EDD\u521B\u5EFA\u65B0 task\uFF08taskId=${q}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let U=new l1;this.processRegistries.set(q,U);let V=Date.now(),M=`${Y}:bg_${q}`,f={id:q,runId:M,subSessionId:D.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:V,lastUpdatedAt:V,timeoutMs:J||W1,abortController:z,similarTaskIds:W,triggerEventId:G,replyChannel:O};this.tasks.set(q,f),this.abortControllers.set(q,z);let N={backgroundTaskId:q,subSessionId:D.id,parentSessionId:w,description:$,subagentType:Y,startedAt:V,timeoutMs:J||W1};return this.publishBackgroundEvent(c_.STARTED,N,w,G,O),this.executeTask(q,X,J,w).catch((R)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:q,error:R instanceof Error?R.message:String(R)})}),{taskId:q,subSessionId:D.id}}async executeTask(_,w,$,X){let Y=this.tasks.get(_);if(!Y){h.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let J=Date.now();Y.status="running",Y.startedAt=J,Y.lastUpdatedAt=J;let W=$||W1,Q=this.abortControllers.get(_);this.startProgressReporter(_,X||Y.parentSessionId);try{let q=await this.getSessionComponent().get(Y.subSessionId);if(!q)throw Error(`Sub session not found: ${Y.subSessionId}`);let H=this.processRegistries.get(_),B=await this.executeWithAbort(q,w,W,_,Q?.signal,Y.similarTaskIds,H,()=>Q?.abort(),Y.subagentType);if(Q?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let D=Date.now();Y.status="completed",Y.completedAt=D,Y.lastUpdatedAt=D,Y.result=B;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:O,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.COMPLETED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:O})}catch(G){let q=G instanceof Error?G.message:String(G),H=__.parseAskUserErrorFromMessage(G),B=q.toLowerCase().includes("stopped")||q.toLowerCase().includes("aborted"),D=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(H){Y.status="awaiting-user",Y.error=H.rawErrorMessage,Y.pendingAskUserQuery=H.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:H.query,sessionId:H.sessionId,nodeId:H.nodeId,nodeType:H.nodeType,agentSessionId:H.agentSessionId,error:H.rawErrorMessage,executionTimeMs:D,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.ASK_USER,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:Y.subSessionId,nodeId:H.nodeId,queryPreview:H.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(B){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:q,executionTimeMs:D,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(q.startsWith("Task execution timeout after")){Y.status="timeout";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:q,executionTimeMs:D,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.TIMEOUT,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:q,executionTimeMs:D,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.FAILED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=q,h.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:Y.status,error:q})}finally{this.finalizeTask(_,Y.status);let G=Y?._preserveSubSessionOnExit===!0,q=this.getSessionComponent();if(!G&&q?.endSessionCleanup&&Y?.subSessionId)try{await q.endSessionCleanup(Y.subSessionId)}catch(H){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:H instanceof Error?H.message:String(H)})}else if(G)h.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let Y=y0();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let J={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(c_.PROGRESS,J,w,X.triggerEventId,X.replyChannel)},OU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,W,Q,G){let q=_?.metadata??{},H=q.task_id,B=q.task_description||"",D=_.id,O=q.subagent_type,z=O||G||"general";if(!O&&!G)h.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${D}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),M=await _U(z,{registry:V}),f=D4(z),N=M?.basePrompt||f?.promptOverride||"You are a subagent. Complete this task: {task_description}",R=M?.deniedTools||f?.deniedTools||[],b=M?.allowedTools||f?.allowedTools,F=N.replace(/{task_description}/g,B||"N/A");if(F+=`
2161
+ `}var MU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),D2=1800000,RU=1200000;class w_{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor(_){this.env=_}setWorkflowService(_){this.workflowService=_}attachWorkflowRun(_,w){if(!_||!w)return;let $=this.workflowRunRegistries.get(_);if(!$)$=new Set,this.workflowRunRegistries.set(_,$);$.add(w)}detachWorkflowRun(_,w){this.workflowRunRegistries.get(_)?.delete(w)}replaceWorkflowRun(_,w,$){if(!_)return;let X=this.workflowRunRegistries.get(_);if(!X)return;if(w)X.delete(w);if($)X.add($)}async propagateStopToWorkflowRuns(_,w){let $=this.workflowRunRegistries.get(_);if(!$||$.size===0)return{runIds:[],stopResults:[]};let X=Array.from($);h.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${_}`);let Y=[];for(let J of X){if(typeof this.workflowService?.stopRun!=="function"){h.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${J}`),Y.push({runId:J,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(J,w),Y.push({runId:J,success:!0})}catch(D){let W=D instanceof Error?D.message:String(D);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${W}`),Y.push({runId:J,success:!1,error:W})}}return $.clear(),{runIds:X,stopResults:Y}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let J=this.terminalTasks.keys().next().value;if(J!==void 0)this.terminalTasks.delete(J)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let Y=this.processRegistries.get(_);if(Y&&Y.size()>0)h.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${Y.size()}, reason=${w})`);h.debug(`[BackgroundTaskManager] finalizeTask taskId=${_} reason=${w}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let _=0;for(let[w,$]of this.processRegistries)if($.size()===0)this.processRegistries.delete(w),_++;return _}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent(_){try{if(w_.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${w_.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),w_.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??w_.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=I_((_)=>MU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return w_._detectWorkflowShortcutWrapped(_)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession(_){if(!_)return;try{let $=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.(_);return typeof $==="number"&&$>0?$:void 0}catch(w){h.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${_}: ${w instanceof Error?w.message:String(w)}`);return}}publishBackgroundEvent(_,w,$,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),h.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,Y){this.publishBackgroundEvent(_,w,$,X,Y)}static parseAskUserErrorFromMessage(_){let w=_ instanceof Error?_.message:String(_);if(_&&typeof _==="object"&&_.name==="AskUserError"&&_.query){let X=_;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:w}}let $="__ASK_USER_ERROR__:";if(w.includes($))try{let X=w.substring(w.indexOf($)+$.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:w}}catch(X){return h.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask(_){let{parentSessionId:w,description:$,prompt:X,subagentType:Y,timeout:J,similarTaskIds:D,existingSubSessionId:W,triggerEventId:G,model:Q,fallbackModel:q}=_,H=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,B=this.getSessionComponent();if(!B)throw Error("SessionComponent not found");if(!await B.get(w))throw Error(`Parent session not found: ${w}`);let z;if(W){let f=await B.get(W);if(!f)throw Error(`Sub session not found for resume: ${W}`);let Z=f?.metadata?.created_by;if(Z&&Z!=="subagent")h.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${Z}); reusing anyway`);z=f;try{let L=f?.metadata??{};await B.update(W,{metadata:{...L,reused_sub_session:!0,reused_at:Date.now()}})}catch(L){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:L instanceof Error?L.message:String(L)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${H}`)}else{let f={subagent_type:Y,created_by:"subagent",task_description:$},Z=ew();if(Z){if(Z.messageId)f.messageId=Z.messageId;let L=Z.replyChannel;if(L?.messageId)f.larkMessageId=L.messageId;if(L?.chatId)f.chatId=L.chatId;if(L?.userId)f.larkUserId=L.userId;let C=L?.profile;if(C)f.larkProfile=C}if(G)f.triggerEventId=G;if(z=await B.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:f}),!z)throw Error("Failed to create sub-session")}let U=KU(),V=new AbortController;if(this.processRegistries.size>=this.maxProcessRegistries){if(this.cleanupEmptyProcessRegistries(),this.processRegistries.size>=this.maxProcessRegistries)throw Error(`BackgroundTaskManager.processRegistries \u8FBE\u5230\u4E0A\u9650 ${this.maxProcessRegistries}\uFF08\u542B\u6B8B\u7559 PID\uFF09\uFF0C\u62D2\u7EDD\u521B\u5EFA\u65B0 task\uFF08taskId=${H}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let M=new l2;this.processRegistries.set(H,M);let R=Date.now(),N=`${Y}:bg_${H}`,b={id:H,runId:N,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:R,lastUpdatedAt:R,timeoutMs:J||D2,abortController:V,similarTaskIds:D,triggerEventId:G,model:Q,fallbackModel:q,replyChannel:U};this.tasks.set(H,b),this.abortControllers.set(H,V);let E={backgroundTaskId:H,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,startedAt:R,timeoutMs:J||D2};return this.publishBackgroundEvent(c_.STARTED,E,w,G,U),this.executeTask(H,X,J,w).catch((f)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:H,error:f instanceof Error?f.message:String(f)})}),{taskId:H,subSessionId:z.id}}async executeTask(_,w,$,X){let Y=this.tasks.get(_);if(!Y){h.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let J=Date.now();Y.status="running",Y.startedAt=J,Y.lastUpdatedAt=J;let D=$||D2,W=this.abortControllers.get(_);this.startProgressReporter(_,X||Y.parentSessionId);try{let Q=await this.getSessionComponent().get(Y.subSessionId);if(!Q)throw Error(`Sub session not found: ${Y.subSessionId}`);let q=this.processRegistries.get(_),H=await this.executeWithAbort(Q,w,D,_,W?.signal,Y.similarTaskIds,q,()=>W?.abort(),Y.subagentType);if(W?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let B=Date.now();Y.status="completed",Y.completedAt=B,Y.lastUpdatedAt=B,Y.result=H;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:O,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.COMPLETED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:O})}catch(G){let Q=G instanceof Error?G.message:String(G),q=w_.parseAskUserErrorFromMessage(G),H=Q.toLowerCase().includes("stopped")||Q.toLowerCase().includes("aborted"),B=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(q){Y.status="awaiting-user",Y.error=q.rawErrorMessage,Y.pendingAskUserQuery=q.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:q.query,sessionId:q.sessionId,nodeId:q.nodeId,nodeType:q.nodeType,agentSessionId:q.agentSessionId,error:q.rawErrorMessage,executionTimeMs:B,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.ASK_USER,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:Y.subSessionId,nodeId:q.nodeId,queryPreview:q.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(H){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(Q.startsWith("Task execution timeout after")){Y.status="timeout";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.TIMEOUT,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.FAILED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=Q,h.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:Y.status,error:Q})}finally{this.finalizeTask(_,Y.status);let G=Y?._preserveSubSessionOnExit===!0,Q=this.getSessionComponent();if(!G&&Q?.endSessionCleanup&&Y?.subSessionId)try{await Q.endSessionCleanup(Y.subSessionId)}catch(q){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:q instanceof Error?q.message:String(q)})}else if(G)h.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let Y=y0();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let J={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(c_.PROGRESS,J,w,X.triggerEventId,X.replyChannel)},RU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,D,W,G){let Q=_?.metadata??{},q=Q.task_id,H=Q.task_description||"",B=_.id,O=Q.subagent_type,z=O||G||"general";if(!O&&!G)h.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${B}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),M=await XU(z,{registry:V}),R=H$(z),N=M?.basePrompt||R?.promptOverride||"You are a subagent. Complete this task: {task_description}",b=M?.deniedTools||R?.deniedTools||[],E=M?.allowedTools||R?.allowedTools,f=N.replace(/{task_description}/g,H||"N/A");if(f+=`
2149
2162
 
2150
2163
  ---
2151
2164
 
2152
2165
  # Session Info
2153
- - task_id: ${H||"N/A"}
2154
- - session_id: ${D}
2166
+ - task_id: ${q||"N/A"}
2167
+ - session_id: ${B}
2155
2168
 
2156
2169
  ---
2157
2170
 
@@ -2164,13 +2177,13 @@ ${w}
2164
2177
  - \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
2165
2178
  - \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
2166
2179
  - \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
2167
- - \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,J&&J.length>0)try{let y=this.env?.getComponent?.("task");if(y){let i=[];for(let v of J)try{let c=await y.getTask(v);if(!c){h.warn(`[delegate] Similar task #${v} not found, skipping`);continue}let D_=await y.listOperations({taskId:v,limit:10}),B_=`### Task #${c.id}: ${c.title}
2168
- `;if(B_+=`- Status: ${c.status}
2169
- `,c.description)B_+=`- Description: ${c.description}
2170
- `;if(c.goals_and_expected_deliverables)B_+=`- Goals: ${c.goals_and_expected_deliverables}
2171
- `;if(D_&&D_.length>0){B_+=`- Recent Operations:
2172
- `;for(let Nw of D_)B_+=` - [${Nw.actionType}] ${Nw.actionTitle}: ${Nw.actionDescription||""}
2173
- `}i.push(B_)}catch(c){h.warn(`[delegate] Failed to fetch similar task #${v}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)F+=`
2180
+ - \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,J&&J.length>0)try{let y=this.env?.getComponent?.("task");if(y){let i=[];for(let v of J)try{let c=await y.getTask(v);if(!c){h.warn(`[delegate] Similar task #${v} not found, skipping`);continue}let B_=await y.listOperations({taskId:v,limit:10}),U_=`### Task #${c.id}: ${c.title}
2181
+ `;if(U_+=`- Status: ${c.status}
2182
+ `,c.description)U_+=`- Description: ${c.description}
2183
+ `;if(c.goals_and_expected_deliverables)U_+=`- Goals: ${c.goals_and_expected_deliverables}
2184
+ `;if(B_&&B_.length>0){U_+=`- Recent Operations:
2185
+ `;for(let d_ of B_)U_+=` - [${d_.actionType}] ${d_.actionTitle}: ${d_.actionDescription||""}
2186
+ `}i.push(U_)}catch(c){h.warn(`[delegate] Failed to fetch similar task #${v}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)f+=`
2174
2187
 
2175
2188
  ---
2176
2189
 
@@ -2178,19 +2191,19 @@ ${w}
2178
2191
 
2179
2192
  The following similar tasks and their operation records can serve as reference:
2180
2193
 
2181
- `,F+=i.join(`
2182
- `),F+=`
2194
+ `,f+=i.join(`
2195
+ `),f+=`
2183
2196
 
2184
2197
  ---
2185
2198
 
2186
- Use these as guidance to improve task execution efficiency.`}}catch(y){h.warn("[delegate] Failed to inject similar tasks reference",{error:y instanceof Error?y.message:String(y)})}if(!U)throw Error("AgentComponent not found");try{if(this.env){let y=qU(this.env),i=BU({registry:y,similarTaskIds:J??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)F+=`
2199
+ Use these as guidance to improve task execution efficiency.`}}catch(y){h.warn("[delegate] Failed to inject similar tasks reference",{error:y instanceof Error?y.message:String(y)})}if(!U)throw Error("AgentComponent not found");try{if(this.env){let y=BU(this.env),i=VU({registry:y,similarTaskIds:J??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)f+=`
2187
2200
 
2188
2201
  ---
2189
2202
 
2190
- ${i.markdown}`}}catch(y){h.warn("[delegate] Failed to inject reuse candidate section",{error:y instanceof Error?y.message:String(y)})}let T=f?{...f,allowedTools:b}:b?{id:z,name:z,mode:"subagent",description:M?.description||"Custom agent",allowedTools:b,deniedTools:R}:void 0;UU(U,z,N,T,R);let C=V?.get(z)?.type==="workflow"?w:F;return new Promise((y,i)=>{let v=async()=>{try{await W?.killAll()}catch(U_){h.warn("[delegate] ProcessRegistry.killAll failed",{error:U_ instanceof Error?U_.message:String(U_)})}},c=!1,D_,B_,Nw=this.tasks.get(X);if(Nw?.runId)B_=Nw.runId;let _2=()=>{if(Y&&w2)try{Y.removeEventListener("abort",w2)}catch{}},w2;if(w2=()=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2();try{let U_=this.env?.getComponent?.("agent");if(U_?.abortRun&&B_)U_.abortRun(B_,"task_signal_abort")}catch{}v().catch(()=>{}).then(()=>{i(Error("Task execution stopped"))})},D_=setTimeout(()=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2();try{Q?.()}catch{}try{let U_=this.env?.getComponent?.("agent");if(U_?.abortRun&&B_)U_.abortRun(B_,"task_timeout")}catch{}v().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${$}ms`))})},$),Y)Y.addEventListener("abort",w2);let v4=()=>this.env.handle_query?.(C,{sessionId:D,deniedTools:R.length>0?R:void 0,agentType:z,abort:Y,runId:B_});(W?A8(W,()=>J4(X,()=>v4())):J4(X,()=>v4()))?.then((U_)=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2(),y(U_)}).catch((U_)=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2(),i(U_)})})}async stopTask(_){let w=this.tasks.get(_)??this.terminalTasks.get(_);if(!w)return{success:!1,message:"Task not found"};if(this.terminalTasks.has(_))return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};if(w.status==="completed"||w.status==="failed"||w.status==="stopped"||w.status==="timeout")return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};let $=Date.now();if(w.status="stopped",w.abortController?.abort(),w.runId)try{this.env?.getComponent?.("agent")?.abortRun?.(w.runId,"stop_task")}catch(W){h.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:_,runId:w.runId,error:W instanceof Error?W.message:String(W)})}w.completedAt=$,w.lastUpdatedAt=$;try{await this.processRegistries.get(_)?.killAll()}catch(W){h.warn("[delegate] stopTask killAll failed",{taskId:_,error:W instanceof Error?W.message:String(W)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns(_,"Task stopped by user"),J={backgroundTaskId:w.id,subSessionId:w.subSessionId,parentSessionId:w.parentSessionId,status:"stopped",description:w.description,error:"Task stopped by user",executionTimeMs:w.startedAt?w.completedAt-w.startedAt:0,associatedTaskId:w.associatedTaskId};return this.publishBackgroundEvent(c_.STOPPED,J,w.parentSessionId,w.triggerEventId,w.replyChannel),this.finalizeTask(_,"stopped"),{success:!0,task:w,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:Y}}getTask(_){return this.tasks.get(_)??this.terminalTasks.get(_)}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent(_){if(!_)return!1;for(let w of this.tasks.values())if(w.parentSessionId===_&&(w.status==="pending"||w.status==="running"))return!0;return!1}async stopAllForParent(_){if(!_)return{stoppedTaskIds:[]};let w=[];for(let[$,X]of this.tasks)if(X.parentSessionId===_&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask($))?.success)w.push($)}catch(Y){h.warn(`[BackgroundTaskManager] stopAllForParent failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`)}return{stoppedTaskIds:w}}async forceStopAllAcrossParents(){let _=new Set,w=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let $ of w){if(_.has($))continue;_.add($);let Y=this.tasks.get($)??this.terminalTasks.get($);try{await this.processRegistries.get($)?.killAll()}catch(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}try{await this.propagateStopToWorkflowRuns($,"force stop all")}catch(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}let J=!1;if(Y&&(Y.status==="running"||Y.status==="pending"))try{Y.status="stopped",Y.completedAt=Date.now(),Y.lastUpdatedAt=Y.completedAt,Y.abortController?.abort(),J=!0}catch(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}if(J&&Y){let W={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:Y.parentSessionId,status:"stopped",description:Y.description,error:"force stop all",executionTimeMs:Y.startedAt&&Y.completedAt?Y.completedAt-Y.startedAt:0,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,W,Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose(){for(let[,_]of this.progressTimers)try{clearInterval(_)}catch{}this.progressTimers.clear();for(let[,_]of this.abortControllers)try{_.abort()}catch{}this.abortControllers.clear();for(let[,_]of this.processRegistries)try{await _.killAll()}catch(w){h.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:w instanceof Error?w.message:String(w)})}this.processRegistries.clear();for(let _ of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(_,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),h.info("[BackgroundTaskManager] Disposed")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],__.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"forceStopAllAcrossParents",null);function m5(_){return _.env?.getComponent?.("agent")?.getRegistry?.()}function l5(_){let w=_.env,X=_.backgroundTaskManager??new __(w),Y=m5(_);_._backgroundTaskManager=X;let J={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
2203
+ ${i.markdown}`}}catch(y){h.warn("[delegate] Failed to inject reuse candidate section",{error:y instanceof Error?y.message:String(y)})}let Z=R?{...R,allowedTools:E}:E?{id:z,name:z,mode:"subagent",description:M?.description||"Custom agent",allowedTools:E,deniedTools:b}:void 0;OU(U,z,N,Z,b);let C=V?.get(z)?.type==="workflow"?w:f;return new Promise((y,i)=>{let v=async()=>{try{await D?.killAll()}catch(G_){h.warn("[delegate] ProcessRegistry.killAll failed",{error:G_ instanceof Error?G_.message:String(G_)})}},c=!1,B_,U_,d_=this.tasks.get(X);if(d_?.runId)U_=d_.runId;let _1=()=>{if(Y&&w1)try{Y.removeEventListener("abort",w1)}catch{}},w1;if(w1=()=>{if(c)return;if(c=!0,B_)clearTimeout(B_);_1();try{let G_=this.env?.getComponent?.("agent");if(G_?.abortRun&&U_)G_.abortRun(U_,"task_signal_abort")}catch{}v().catch(()=>{}).then(()=>{i(Error("Task execution stopped"))})},B_=setTimeout(()=>{if(c)return;if(c=!0,B_)clearTimeout(B_);_1();try{W?.()}catch{}try{let G_=this.env?.getComponent?.("agent");if(G_?.abortRun&&U_)G_.abortRun(U_,"task_timeout")}catch{}v().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${$}ms`))})},$),Y)Y.addEventListener("abort",w1);let v$=()=>{let G_=d_?.model,x$=d_?.fallbackModel;return this.env.handle_query?.(C,{sessionId:B,deniedTools:b.length>0?b:void 0,agentType:z,abort:Y,runId:U_,...G_?{model:G_}:{},...x$?{fallbackModel:x$}:{}})};(D?f4(D,()=>J$(X,()=>v$())):J$(X,()=>v$()))?.then((G_)=>{if(c)return;if(c=!0,B_)clearTimeout(B_);_1(),y(G_)}).catch((G_)=>{if(c)return;if(c=!0,B_)clearTimeout(B_);_1(),i(G_)})})}async stopTask(_){let w=this.tasks.get(_)??this.terminalTasks.get(_);if(!w)return{success:!1,message:"Task not found"};if(this.terminalTasks.has(_))return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};if(w.status==="completed"||w.status==="failed"||w.status==="stopped"||w.status==="timeout")return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};let $=Date.now();if(w.status="stopped",w.abortController?.abort(),w.runId)try{this.env?.getComponent?.("agent")?.abortRun?.(w.runId,"stop_task")}catch(D){h.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:_,runId:w.runId,error:D instanceof Error?D.message:String(D)})}w.completedAt=$,w.lastUpdatedAt=$;try{await this.processRegistries.get(_)?.killAll()}catch(D){h.warn("[delegate] stopTask killAll failed",{taskId:_,error:D instanceof Error?D.message:String(D)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns(_,"Task stopped by user"),J={backgroundTaskId:w.id,subSessionId:w.subSessionId,parentSessionId:w.parentSessionId,status:"stopped",description:w.description,error:"Task stopped by user",executionTimeMs:w.startedAt?w.completedAt-w.startedAt:0,associatedTaskId:w.associatedTaskId};return this.publishBackgroundEvent(c_.STOPPED,J,w.parentSessionId,w.triggerEventId,w.replyChannel),this.finalizeTask(_,"stopped"),{success:!0,task:w,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:Y}}getTask(_){return this.tasks.get(_)??this.terminalTasks.get(_)}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent(_){if(!_)return!1;for(let w of this.tasks.values())if(w.parentSessionId===_&&(w.status==="pending"||w.status==="running"))return!0;return!1}async stopAllForParent(_){if(!_)return{stoppedTaskIds:[]};let w=[];for(let[$,X]of this.tasks)if(X.parentSessionId===_&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask($))?.success)w.push($)}catch(Y){h.warn(`[BackgroundTaskManager] stopAllForParent failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`)}return{stoppedTaskIds:w}}async forceStopAllAcrossParents(){let _=new Set,w=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let $ of w){if(_.has($))continue;_.add($);let Y=this.tasks.get($)??this.terminalTasks.get($);try{await this.processRegistries.get($)?.killAll()}catch(D){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${$}: ${D instanceof Error?D.message:String(D)}`)}try{await this.propagateStopToWorkflowRuns($,"force stop all")}catch(D){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${$}: ${D instanceof Error?D.message:String(D)}`)}let J=!1;if(Y&&(Y.status==="running"||Y.status==="pending"))try{Y.status="stopped",Y.completedAt=Date.now(),Y.lastUpdatedAt=Y.completedAt,Y.abortController?.abort(),J=!0}catch(D){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${$}: ${D instanceof Error?D.message:String(D)}`)}if(J&&Y){let D={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:Y.parentSessionId,status:"stopped",description:Y.description,error:"force stop all",executionTimeMs:Y.startedAt&&Y.completedAt?Y.completedAt-Y.startedAt:0,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,D,Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose(){for(let[,_]of this.progressTimers)try{clearInterval(_)}catch{}this.progressTimers.clear();for(let[,_]of this.abortControllers)try{_.abort()}catch{}this.abortControllers.clear();for(let[,_]of this.processRegistries)try{await _.killAll()}catch(w){h.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:w instanceof Error?w.message:String(w)})}this.processRegistries.clear();for(let _ of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(_,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),h.info("[BackgroundTaskManager] Disposed")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],w_.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"forceStopAllAcrossParents",null);function c5(_){return _.env?.getComponent?.("agent")?.getRegistry?.()}function d5(_){let w=_.env,X=_.backgroundTaskManager??new w_(w),Y=c5(_);_._backgroundTaskManager=X;let J={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
2191
2204
 
2192
2205
  Available agent types:
2193
- ${XU(Y)}
2206
+ ${DU(Y)}
2194
2207
 
2195
2208
  When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
2196
2209
 
@@ -2219,21 +2232,8 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
2219
2232
  - **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
2220
2233
  - **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
2221
2234
  - **reason**: Brief reason for calling this tool (optional)
2222
- - **similar_task_ids**: Similar task IDs (max 3) to reference for improving sub-agent execution efficiency. Search for similar tasks using \`task_search\` or \`task_list\` before calling this tool.`,parameters:x5,execute:async(W,Q)=>{let G=Date.now(),q=x5.parse(W),{description:H,prompt:B,subagent_type:D="general",timeout:O,reason:z,similar_task_ids:U}=q,V=Q.session_id||"default",M=q.triggerEventId??MU();if(M&&M!==q.triggerEventId)h.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${M}`);if(h.info(`[delegate_task] Called: description=${H}, subagent_type=${D}, triggerEventId=${M??"(none)"}`),M){let T=R8();if(T)try{if(!await T.getEventById(M))return{success:!1,output:"",error:`Unknown triggerEventId: ${M} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-G}}}catch(j){return{success:!1,output:"",error:`Failed to verify triggerEventId ${M}: ${j instanceof Error?j.message:String(j)}`,metadata:{execution_time_ms:Date.now()-G}}}else h.warn(`[delegate_task] triggerEventId=${M} supplied but no shared EventStore registered; skipping verification`)}let f=m5(_);if(!eB(D,f))return{success:!1,output:"",error:`Unknown subagent type: ${D}`,metadata:{execution_time_ms:Date.now()-G}};let N=_.getTagService(),R=B,b={prompt:R,subagentType:D,timeout:O,reason:z,tagService:N},F={component:{name:"task",version:"1.0.0"},data:b,metadata:{sessionId:V},phase:"before",hookPoint:$_.DELEGATE_BEFORE};return await E_.execute($_.DELEGATE_BEFORE,b,{sessionId:V}),R=b.prompt,await LU(X,V,H,R,b.subagentType,b.timeout,U,q.sub_session_id,M)}};return J.execute=I_(J.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),J}function AU(){let _=ew();if(!_)return;let w=_.envEvent,$=w?.metadata?.triggerEventId;if(typeof $==="string"&&$.length>0)return $;let X=w?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var MU=I_(AU,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function RU(){let _=ew()?.replyChannel;if(!_)return;if(!_.chatId&&!_.messageId)return;let w={..._.params??{}};if(_.userId&&w.userId===void 0)w.userId=_.userId;return{type:_.type,appId:_.appId,chatId:_.chatId,messageId:_.messageId,profile:_.profile,params:Object.keys(w).length>0?w:void 0}}var fU=I_(RU,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function LU(_,w,$,X,Y,J,W,Q,G){let q=Date.now();try{let H=Y,B=X,D,O=_.resolveEntryAgent(Y);if(O)D=Y,H=O,B=zU({workflowName:D,originalPrompt:X,description:$}),h.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${O}'`);let{taskId:z,subSessionId:U}=await _.createTask({parentSessionId:w,description:$,prompt:B,subagentType:H,timeout:J,similarTaskIds:W,originalWorkflowName:D,existingSubSessionId:Q,triggerEventId:G});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${z}`,`\uD83D\uDCDD Description: ${$}`,`\uD83E\uDD16 Sub-agent: ${H}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(J||W1)/1000}s`,"",`Use stop_task with task_id="${z}" to cancel this task.`].join(`
2223
- `),metadata:{execution_time_ms:Date.now()-q,sessionId:U,background:!0,status:"accepted",bgProcessId:z}}}catch(H){return{success:!1,output:"",error:H instanceof Error?H.message:String(H),metadata:{execution_time_ms:Date.now()-q}}}}var u5=A.object({task_id:A.string().describe("The ID of the background task to stop")}),FU=`Stop a running background task.
2224
-
2225
- Use this tool to stop a background task that is currently running. This is useful when:
2226
- - The user wants to cancel a long-running task
2227
- - The task is taking too long and needs to be stopped
2228
- - The user wants to change direction and doesn't need the task result anymore
2229
-
2230
- When stopped, the task will be terminated immediately and you will receive a confirmation.
2231
-
2232
- Parameters:
2233
- - task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function KU(_){let w=Math.floor(_/1000),$=Math.floor(w/60),X=Math.floor($/60);if(X>0)return`${X}h ${$%60}m ${w%60}s`;else if($>0)return`${$}m ${w%60}s`;else return`${w}s`}function c5(_){return{name:"stop_task",description:FU,parameters:u5,execute:async(w,$)=>{let X=Date.now(),Y=u5.parse(w),{task_id:J}=Y,W=await _.stopTask(J);if(W.success){let Q=W.task,G=Q.startedAt?Date.now()-Q.startedAt:Date.now()-Q.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${Q.description}`,`\uD83D\uDD04 Status: ${Q.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${KU(G)}`,"",W.message].join(`
2234
- `),metadata:{execution_time_ms:Date.now()-X,task_id:J,previous_status:Q.status}}}else{let Q=W.task,G;if(Q)G=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${Q.description}`,`\uD83D\uDD04 Current Status: ${Q.status}`,"",W.message].join(`
2235
- `);else G=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${J}`,"",W.message].join(`
2236
- `);return{success:!1,output:G,error:W.message,metadata:{execution_time_ms:Date.now()-X,task_id:J}}}}}}var Rw={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};import{execSync as EU}from"child_process";var d5="unknown",NU='{"type":"unknown"}';function bU(){return{task_id:A.number().describe("Task ID")}}function jU(_){if(typeof _!=="object"||_===null||Array.isArray(_))return _;let w=_;if(w.task_id===void 0&&w.id!==void 0)return{...w,task_id:w.id};return w}function U4(_){return A.preprocess(jU,A.object({...bU(),..._}))}var p5=A.object({title:A.string().describe("Task title"),description:A.string().optional().describe("Task description"),priority:A.enum(["low","medium","high"]).optional().describe("Task priority"),type:A.enum(["normal","cycle","longterm"]).optional().default("normal").describe("Task type. normal: \u5E38\u89C4\u4EFB\u52A1\uFF0C\u9700\u8981\u8DDF\u8E2A\u5B8C\u6210. cycle: \u5468\u671F\u4EFB\u52A1\uFF08\u5982\u6BCF\u5468\u53D1\u5468\u62A5\uFF09\uFF0C\u65E0\u9700 complete\uFF0C\u5B9A\u671F\u6267\u884C. longterm: \u957F\u671F\u4EFB\u52A1/\u613F\u666F\u76EE\u6807\uFF08\u5982\u63D0\u5347\u516C\u53F8\u5F71\u54CD\u529B\uFF09\uFF0C\u96BE\u4EE5\u4E00\u6B21\u6027\u5B8C\u6210\uFF0C\u6301\u7EED\u8DDF\u8FDB"),goals_and_expected_deliverables:A.string().optional().describe("Goals and expected deliverables"),due_date:A.string().optional().describe("Due date (ISO format)"),tags:A.array(A.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:A.string().default("unknown").describe("Project root path for task positioning. Used to locate the project space for this task. Use 'unknown' if unknown. (Defaults to 'unknown'.)"),parent_task_id:A.union([A.number(),A.null()]).optional().describe(`\u7236\u4EFB\u52A1 ID\uFF08\u53EF\u9009\uFF09\u3002\u4E0D\u4F20\u6216\u4F20 null \u65F6\uFF0C\u521B\u5EFA\u6839\u4EFB\u52A1\uFF08root task\uFF09\u3002
2235
+ - **similar_task_ids**: Similar task IDs (max 3) to reference for improving sub-agent execution efficiency. Search for similar tasks using \`task_search\` or \`task_list\` before calling this tool.`,parameters:l5,execute:async(D,W)=>{let G=Date.now(),Q=l5.parse(D),{description:q,prompt:H,subagent_type:B="general",timeout:O,reason:z,similar_task_ids:U}=Q,V=W.session_id||"default",M=Q.triggerEventId??LU();if(M&&M!==Q.triggerEventId)h.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${M}`);if(h.info(`[delegate_task] Called: description=${q}, subagent_type=${B}, triggerEventId=${M??"(none)"}`),M){let Z=F4();if(Z)try{if(!await Z.getEventById(M))return{success:!1,output:"",error:`Unknown triggerEventId: ${M} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-G}}}catch(L){return{success:!1,output:"",error:`Failed to verify triggerEventId ${M}: ${L instanceof Error?L.message:String(L)}`,metadata:{execution_time_ms:Date.now()-G}}}else h.warn(`[delegate_task] triggerEventId=${M} supplied but no shared EventStore registered; skipping verification`)}let R=c5(_);if(!$U(B,R))return{success:!1,output:"",error:`Unknown subagent type: ${B}`,metadata:{execution_time_ms:Date.now()-G}};let N=_.getTagService(),b=H,E={prompt:b,subagentType:B,timeout:O,reason:z,tagService:N},f={component:{name:"task",version:"1.0.0"},data:E,metadata:{sessionId:V},phase:"before",hookPoint:$_.DELEGATE_BEFORE};return await E_.execute($_.DELEGATE_BEFORE,E,{sessionId:V}),b=E.prompt,await NU(X,V,q,b,E.subagentType,E.timeout,U,Q.sub_session_id,M,W.model,W.fallbackModel)}};return J.execute=I_(J.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),J}function fU(){let _=ew();if(!_)return;let w=_.envEvent,$=w?.metadata?.triggerEventId;if(typeof $==="string"&&$.length>0)return $;let X=w?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var LU=I_(fU,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function FU(){let _=ew()?.replyChannel;if(!_)return;if(!_.chatId&&!_.messageId)return;let w={..._.params??{}};if(_.userId&&w.userId===void 0)w.userId=_.userId;return{type:_.type,appId:_.appId,chatId:_.chatId,messageId:_.messageId,profile:_.profile,params:Object.keys(w).length>0?w:void 0}}var KU=I_(FU,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function NU(_,w,$,X,Y,J,D,W,G,Q,q){let H=Date.now();try{let B=Y,O=X,z,U=_.resolveEntryAgent(Y);if(U)z=Y,B=U,O=AU({workflowName:z,originalPrompt:X,description:$}),h.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${U}'`);let{taskId:V,subSessionId:M}=await _.createTask({parentSessionId:w,description:$,prompt:O,subagentType:B,timeout:J,similarTaskIds:D,originalWorkflowName:z,existingSubSessionId:W,triggerEventId:G,model:Q,fallbackModel:q});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${V}`,`\uD83D\uDCDD Description: ${$}`,`\uD83E\uDD16 Sub-agent: ${B}${z?` (workflow: ${z})`:""}`,`\u23F1\uFE0F Timeout: ${(J||D2)/1000}s`,"",`Use stop_task with task_id="${V}" to cancel this task.`].join(`
2236
+ `),metadata:{execution_time_ms:Date.now()-H,sessionId:M,background:!0,status:"accepted",bgProcessId:V}}}catch(B){return{success:!1,output:"",error:B instanceof Error?B.message:String(B),metadata:{execution_time_ms:Date.now()-H}}}}var fw={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};import{execSync as SU}from"child_process";var p5="unknown",bU='{"type":"unknown"}';function jU(){return{task_id:A.number().describe("Task ID")}}function EU(_){if(typeof _!=="object"||_===null||Array.isArray(_))return _;let w=_;if(w.task_id===void 0&&w.id!==void 0)return{...w,task_id:w.id};return w}function U$(_){return A.preprocess(EU,A.object({...jU(),..._}))}var i5=A.object({title:A.string().describe("Task title"),description:A.string().optional().describe("Task description"),priority:A.enum(["low","medium","high"]).optional().describe("Task priority"),type:A.enum(["normal","cycle","longterm"]).optional().default("normal").describe("Task type. normal: \u5E38\u89C4\u4EFB\u52A1\uFF0C\u9700\u8981\u8DDF\u8E2A\u5B8C\u6210. cycle: \u5468\u671F\u4EFB\u52A1\uFF08\u5982\u6BCF\u5468\u53D1\u5468\u62A5\uFF09\uFF0C\u65E0\u9700 complete\uFF0C\u5B9A\u671F\u6267\u884C. longterm: \u957F\u671F\u4EFB\u52A1/\u613F\u666F\u76EE\u6807\uFF08\u5982\u63D0\u5347\u516C\u53F8\u5F71\u54CD\u529B\uFF09\uFF0C\u96BE\u4EE5\u4E00\u6B21\u6027\u5B8C\u6210\uFF0C\u6301\u7EED\u8DDF\u8FDB"),goals_and_expected_deliverables:A.string().optional().describe("Goals and expected deliverables"),due_date:A.string().optional().describe("Due date (ISO format)"),tags:A.array(A.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:A.string().default("unknown").describe("Project root path for task positioning. Used to locate the project space for this task. Use 'unknown' if unknown. (Defaults to 'unknown'.)"),parent_task_id:A.union([A.number(),A.null()]).optional().describe(`\u7236\u4EFB\u52A1 ID\uFF08\u53EF\u9009\uFF09\u3002\u4E0D\u4F20\u6216\u4F20 null \u65F6\uFF0C\u521B\u5EFA\u6839\u4EFB\u52A1\uFF08root task\uFF09\u3002
2237
2237
  `+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
2238
2238
  `+`**\u8C03\u7528\u524D\u5FC5\u987B\u5148\u8C03\u7528 task_tree(depth=2)** \u67E5\u770B\u73B0\u6709\u4EFB\u52A1\u6811\u7ED3\u6784\uFF0C\u907F\u514D\u91CD\u590D\u521B\u5EFA\u6839\u4EFB\u52A1\u3001\u907F\u514D\u5B64\u513F\u4EFB\u52A1\u3002
2239
2239
  `+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
@@ -2241,7 +2241,7 @@ Parameters:
2241
2241
  `+` B. \u5F52\u5C5E\u5230\u73B0\u6709\u4E3B\u9898\u805A\u7C7B\uFF08\u975E longterm \u6839\uFF0C\u4F46\u540C\u4E3B\u9898\uFF09\u2192 parent_task_id = \u8BE5\u6839 ID
2242
2242
  `+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
2243
2243
  `+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
2244
- `+"\u6839\u636E\u8282\u70B9 id \u9009\u62E9\u5408\u9002\u7684\u7236\u4EFB\u52A1 ID\uFF08\u6765\u81EA tree \u8F93\u51FA\uFF0C**\u4E0D\u8981\u786C\u7F16\u7801**\u6570\u5B57\uFF09\u3002"),context:A.string().default('{"type":"unknown"}').describe(`JSON string with time-space positioning information for task continuity. This field is crucial for Agent task handoff. Core fields: worktree_path (git worktree path), branch (current branch), type (feature/bug/refactor/chore). Example for coding: {"worktree_path": "/path/worktree", "branch": "feature/xyz", "type": "feature"}. Example for other: {"type": "general"}. If unknown, use '{}' or '{"type":"unknown"}'. IMPORTANT: Must be a valid JSON string!`)}),i5=U4({include_operations:A.boolean().optional().default(!0).describe("Include operation records (milestones / process log) with the task. "+"Defaults to true \u2014 the task's operation history is part of its detail. "+"Pass false for a lean task-only response.")}),n5=A.object({status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:A.number().optional().default(20),offset:A.number().optional().default(0),depth:A.number().optional().describe("\u68C0\u7D22\u5C42\u7EA7\u6DF1\u5EA6\uFF1A0=\u53EA\u6839\u4EFB\u52A1\uFF08\u65E0\u7236\u4EFB\u52A1\uFF09\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08status=archived \u7684\u4EFB\u52A1\u9ED8\u8BA4\u88AB\u6392\u9664\uFF09")}),r5=A.object({keywords:A.array(A.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:A.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:A.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:A.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:A.number().optional().describe("\u68C0\u7D22\u5C42\u7EA7\u6DF1\u5EA6\uFF1A0=\u53EA\u6839\u4EFB\u52A1\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08status=archived \u7684\u4EFB\u52A1\u9ED8\u8BA4\u88AB\u6392\u9664\uFF09")}),a5=U4({title:A.string().optional(),description:A.string().optional(),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:A.number().min(0).max(100).optional(),current_status:A.string().optional(),goals_and_expected_deliverables:A.string().optional(),due_date:A.string().optional(),tags:A.array(A.string()).optional(),project_path:A.string().optional().describe("Project path, identifies which project this task belongs to"),context:A.string().optional().describe("Task context information for storing additional context"),parent_task_id:A.union([A.number(),A.null()]).optional().describe("Parent task ID (set to null to make it a root task)")}),o5=A.object({task_id:A.number().describe("Task ID")}),s5=U4({deliverable_storage_path:A.string().optional().describe("\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\uFF08\u8DEF\u5F84 / URL / \u5206\u652F\u540D\u7B49\uFF09\u3002"+"\u8C03\u7528\u672C\u5DE5\u5177\u524D\uFF0C\u8BF7\u5148\u8BFB\u53D6\u4EFB\u52A1\u7684 goal\uFF08description\uFF09\u548C delivery\uFF08goals_and_expected_deliverables\uFF09\u680F\u4F4D\uFF0C"+"\u5EFA\u8BAE\u9A8C\u8BC1\u76EE\u6807\u548C\u4EA4\u4ED8\u7269\u662F\u5426\u7B26\u5408\u9884\u671F\uFF0C\u7136\u540E\u5C06\u5B9E\u9645\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\u586B\u5165\u6B64\u53C2\u6570\u3002")}),t5=A.object({task_ids:A.array(A.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:A.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),e5=A.object({task_ids:A.array(A.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),_X=A.object({depth:A.number().optional().default(2).describe("\u6811\u7684\u5C55\u5F00\u6DF1\u5EA6\u3002\u9ED8\u8BA4 2 (\u6839 + \u4E00\u5C42\u5B50\u4EFB\u52A1 + \u4E8C\u5C42\u5B59\u4EFB\u52A1)\u3002"+"0 = \u53EA\u8FD4\u56DE\u6839\u4EFB\u52A1\uFF0C\u4E0D\u5C55\u5F00\u4EFB\u4F55\u5B50\u8282\u70B9\u3002"+"-1 \u6216\u8D1F\u6570 = \u65E0\u9650\u5C42\u7EA7\uFF08\u5168\u90E8\u5C55\u5F00\uFF09\u3002"),parent_task_id:A.number().optional().describe("\u53EA\u770B\u6307\u5B9A\u7236\u4EFB\u52A1\u7684\u5B50\u6811\u3002\u4E0D\u4F20\u5219\u4ECE\u6240\u6709\u6839\u4EFB\u52A1\uFF08forest\uFF09\u5F00\u59CB\u3002"),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08\u9ED8\u8BA4 false\uFF0C\u4E0E task_list \u4E00\u81F4\uFF09\u3002")});Jw();a();a();var SU=n("task-child-context"),PU=["commit","token","secret","password","api_key"];function B4(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map(B4);if(typeof _!=="object")return _;let w={};for(let[$,X]of Object.entries(_)){let Y=$.toLowerCase();if(PU.some((J)=>Y.includes(J)))continue;w[$]=B4(X)}return w}function ZU(_){let{parent:w,overrides:$={}}=_,X=$.contextInherit!==!1,Y=$.inheritTags===!0,J=$.projectPath??w.projectPath??"unknown",W={};if(w.contextJson&&w.contextJson.trim().length>0)try{let H=JSON.parse(w.contextJson);if(H&&typeof H==="object"&&!Array.isArray(H))W=H}catch(H){SU.debug(`[task-child-context] parent #${w.taskId} context is malformed JSON; continuing with empty inherited context (${H instanceof Error?H.message:String(H)})`),W={}}let Q={};if(X){if(W.worktree_path!==void 0&&$.worktreePath===void 0)Q.worktree_path=W.worktree_path;if(W.branch!==void 0&&$.branch===void 0)Q.branch=W.branch;if(W.parent_branch!==void 0)Q.parent_branch=W.parent_branch;if(W.type!==void 0)Q.type=W.type;if(W.prior_context&&typeof W.prior_context==="object"){let B=W.prior_context,D={};for(let[O,z]of Object.entries(B)){if(O.toLowerCase()==="commit")continue;D[O]=z}if(Object.keys(D).length>0)Q.prior_context=D}let H=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[B,D]of Object.entries(W)){if(H.has(B))continue;Q[B]=D}}if($.worktreePath!==void 0)Q.worktree_path=$.worktreePath;if($.branch!==void 0)Q.branch=$.branch;let G=$.createdAt??new Date().toISOString();Q.created_at=G,Q.child_of=w.taskId;let q=B4(Q);return{project_path:J,context:JSON.stringify(q),inheritedTags:Y?w.tags??[]:[]}}var wX=n("task:tools:create");function CU(){try{let _=EU("git rev-parse --show-toplevel",{stdio:["ignore","pipe","ignore"]}).toString().trim(),w=process.cwd();if(!_)return null;if(w!==_)return w;if(w.includes(".worktrees/")||w.includes(".worktree/"))return w;return null}catch{return null}}function x0(_){return{name:"task_create",description:`
2244
+ `+"\u6839\u636E\u8282\u70B9 id \u9009\u62E9\u5408\u9002\u7684\u7236\u4EFB\u52A1 ID\uFF08\u6765\u81EA tree \u8F93\u51FA\uFF0C**\u4E0D\u8981\u786C\u7F16\u7801**\u6570\u5B57\uFF09\u3002"),context:A.string().default('{"type":"unknown"}').describe(`JSON string with time-space positioning information for task continuity. This field is crucial for Agent task handoff. Core fields: worktree_path (git worktree path), branch (current branch), type (feature/bug/refactor/chore). Example for coding: {"worktree_path": "/path/worktree", "branch": "feature/xyz", "type": "feature"}. Example for other: {"type": "general"}. If unknown, use '{}' or '{"type":"unknown"}'. IMPORTANT: Must be a valid JSON string!`)}),n5=U$({include_operations:A.boolean().optional().default(!0).describe("Include operation records (milestones / process log) with the task. "+"Defaults to true \u2014 the task's operation history is part of its detail. "+"Pass false for a lean task-only response.")}),r5=A.object({status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:A.number().optional().default(20),offset:A.number().optional().default(0),depth:A.number().optional().describe("\u68C0\u7D22\u5C42\u7EA7\u6DF1\u5EA6\uFF1A0=\u53EA\u6839\u4EFB\u52A1\uFF08\u65E0\u7236\u4EFB\u52A1\uFF09\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08status=archived \u7684\u4EFB\u52A1\u9ED8\u8BA4\u88AB\u6392\u9664\uFF09")}),a5=A.object({keywords:A.array(A.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:A.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:A.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:A.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:A.number().optional().describe("\u68C0\u7D22\u5C42\u7EA7\u6DF1\u5EA6\uFF1A0=\u53EA\u6839\u4EFB\u52A1\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08status=archived \u7684\u4EFB\u52A1\u9ED8\u8BA4\u88AB\u6392\u9664\uFF09")}),o5=U$({title:A.string().optional(),description:A.string().optional(),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:A.number().min(0).max(100).optional(),current_status:A.string().optional(),goals_and_expected_deliverables:A.string().optional(),due_date:A.string().optional(),tags:A.array(A.string()).optional(),project_path:A.string().optional().describe("Project path, identifies which project this task belongs to"),context:A.string().optional().describe("Task context information for storing additional context"),parent_task_id:A.union([A.number(),A.null()]).optional().describe("Parent task ID (set to null to make it a root task)")}),s5=A.object({task_id:A.number().describe("Task ID")}),t5=U$({deliverable_storage_path:A.string().optional().describe("\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\uFF08\u8DEF\u5F84 / URL / \u5206\u652F\u540D\u7B49\uFF09\u3002"+"\u8C03\u7528\u672C\u5DE5\u5177\u524D\uFF0C\u8BF7\u5148\u8BFB\u53D6\u4EFB\u52A1\u7684 goal\uFF08description\uFF09\u548C delivery\uFF08goals_and_expected_deliverables\uFF09\u680F\u4F4D\uFF0C"+"\u5EFA\u8BAE\u9A8C\u8BC1\u76EE\u6807\u548C\u4EA4\u4ED8\u7269\u662F\u5426\u7B26\u5408\u9884\u671F\uFF0C\u7136\u540E\u5C06\u5B9E\u9645\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\u586B\u5165\u6B64\u53C2\u6570\u3002")}),e5=A.object({task_ids:A.array(A.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:A.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),_6=A.object({task_ids:A.array(A.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),w6=A.object({depth:A.number().optional().default(2).describe("\u6811\u7684\u5C55\u5F00\u6DF1\u5EA6\u3002\u9ED8\u8BA4 2 (\u6839 + \u4E00\u5C42\u5B50\u4EFB\u52A1 + \u4E8C\u5C42\u5B59\u4EFB\u52A1)\u3002"+"0 = \u53EA\u8FD4\u56DE\u6839\u4EFB\u52A1\uFF0C\u4E0D\u5C55\u5F00\u4EFB\u4F55\u5B50\u8282\u70B9\u3002"+"-1 \u6216\u8D1F\u6570 = \u65E0\u9650\u5C42\u7EA7\uFF08\u5168\u90E8\u5C55\u5F00\uFF09\u3002"),parent_task_id:A.number().optional().describe("\u53EA\u770B\u6307\u5B9A\u7236\u4EFB\u52A1\u7684\u5B50\u6811\u3002\u4E0D\u4F20\u5219\u4ECE\u6240\u6709\u6839\u4EFB\u52A1\uFF08forest\uFF09\u5F00\u59CB\u3002"),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:A.boolean().optional().default(!1).describe("\u662F\u5426\u5305\u542B\u5DF2\u5F52\u6863\u4EFB\u52A1\uFF08\u9ED8\u8BA4 false\uFF0C\u4E0E task_list \u4E00\u81F4\uFF09\u3002")});Dw();a();a();var PU=n("task-child-context"),ZU=["commit","token","secret","password","api_key"];function B$(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map(B$);if(typeof _!=="object")return _;let w={};for(let[$,X]of Object.entries(_)){let Y=$.toLowerCase();if(ZU.some((J)=>Y.includes(J)))continue;w[$]=B$(X)}return w}function CU(_){let{parent:w,overrides:$={}}=_,X=$.contextInherit!==!1,Y=$.inheritTags===!0,J=$.projectPath??w.projectPath??"unknown",D={};if(w.contextJson&&w.contextJson.trim().length>0)try{let q=JSON.parse(w.contextJson);if(q&&typeof q==="object"&&!Array.isArray(q))D=q}catch(q){PU.debug(`[task-child-context] parent #${w.taskId} context is malformed JSON; continuing with empty inherited context (${q instanceof Error?q.message:String(q)})`),D={}}let W={};if(X){if(D.worktree_path!==void 0&&$.worktreePath===void 0)W.worktree_path=D.worktree_path;if(D.branch!==void 0&&$.branch===void 0)W.branch=D.branch;if(D.parent_branch!==void 0)W.parent_branch=D.parent_branch;if(D.type!==void 0)W.type=D.type;if(D.prior_context&&typeof D.prior_context==="object"){let H=D.prior_context,B={};for(let[O,z]of Object.entries(H)){if(O.toLowerCase()==="commit")continue;B[O]=z}if(Object.keys(B).length>0)W.prior_context=B}let q=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[H,B]of Object.entries(D)){if(q.has(H))continue;W[H]=B}}if($.worktreePath!==void 0)W.worktree_path=$.worktreePath;if($.branch!==void 0)W.branch=$.branch;let G=$.createdAt??new Date().toISOString();W.created_at=G,W.child_of=w.taskId;let Q=B$(W);return{project_path:J,context:JSON.stringify(Q),inheritedTags:Y?w.tags??[]:[]}}var $6=n("task:tools:create");function TU(){try{let _=SU("git rev-parse --show-toplevel",{stdio:["ignore","pipe","ignore"]}).toString().trim(),w=process.cwd();if(!_)return null;if(w!==_)return w;if(w.includes(".worktrees/")||w.includes(".worktree/"))return w;return null}catch{return null}}function x0(_){return{name:"task_create",description:`
2245
2245
  Create a new task for tracking work.
2246
2246
 
2247
2247
  ## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
@@ -2381,20 +2381,20 @@ Parameters:
2381
2381
  env-injected value is 0 / negative / non-integer, it's treated as
2382
2382
  missing \u2014 only positive integers are honored.
2383
2383
 
2384
- `,parameters:p5,execute:async(w,$)=>{let X=p5.parse(w),Y=$.session_id||"unknown",J=CU(),W=X.context,Q=$1().parentTaskId,G=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:Q!==void 0&&Q!==null&&Number.isInteger(Q)&&Q>0?Q:void 0,q=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,H=q!==void 0&&q!==d5,B=H?q:void 0,D=X.tags,O;if(G!==void 0)try{let z=await _.getTask(G);if(z){let U=ZU({parent:{taskId:z.id,projectPath:z.project_path,contextJson:z.context??"",tags:z.tags},overrides:{projectPath:B,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(B===void 0)B=U.project_path;if(X.tags===void 0)D=U.inheritedTags;O=U.context}}catch(z){wX.debug(`[task_create] failed to pre-load parent #${G} for context inheritance: ${z instanceof Error?z.message:String(z)}`)}try{let z=X.context===NU?void 0:X.context,U=z?JSON.parse(z):{},V=typeof U==="object"&&U!==null&&!Array.isArray(U)?U:{};if(O)try{let M=JSON.parse(O);if(M&&typeof M==="object"&&!Array.isArray(M)){for(let[f,N]of Object.entries(M))if(V[f]===void 0)V[f]=N}}catch{}if(!V.created_at)V.created_at=new Date().toISOString();if(!V.worktree_path&&J)V.worktree_path=J;W=JSON.stringify(V)}catch{W=X.context}try{let z=await _.createTask({parent_task_id:G,title:X.title,description:X.description,priority:X.priority,type:X.type||"normal",goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:D,sessionId:Y,project_path:B??(H?q:d5),context:W});return v0(z.id),wX.info(`[createTask] Trace: Task #${z.id} created, currentTaskId=${z.id} set in EnvContext`),{success:!0,output:`Task created successfully: #${z.id} - ${z.title}`,metadata:{execution_time_ms:0,task_id:z.id,status:z.status,createdAt:z.createdAt}}}catch(z){return{success:!1,output:"",error:z instanceof Error?z.message:String(z),metadata:{execution_time_ms:0}}}}}}function m0(_){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:i5,execute:async(w,$)=>{let X=i5.parse(w);try{if(X.include_operations){let Y=await _.getTaskWithOperations(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let J=Y.task,W=J&&typeof J==="object"?{...J,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}else{let Y=await _.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function u0(_){return{name:"task_list",description:"List tasks with optional filters for status, priority, type, parent_task_id, and depth (hierarchy level). "+`depth: 0=\u53EA\u6839\u4EFB\u52A1\uFF08\u65E0\u7236\u4EFB\u52A1\uFF09\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8\u3002
2385
- `+"Returns { total, count, truncated, limit, offset, depth, tasks } where:\n - total: count of all matching tasks BEFORE pagination\n - count: count of tasks in the returned `tasks` array (after pagination)\n - truncated: true when total > count (data was truncated by pagination)\nNote: `total` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.",parameters:n5,execute:async(w,$)=>{let X=n5.parse(w);try{let Y=await _.listTasks({status:X.status,priority:X.priority,type:X.type,limit:X.limit,offset:X.offset,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({total:Y.total,count:Y.tasks.length,truncated:Y.total>Y.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:Y.tasks}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function l0(_){return{name:"task_search",description:"Search tasks by keywords across title, description, goals, tags, and operation records. Use this when you need to find tasks related to a "+"topic, feature, bug, or area of work \u2014 even when the keyword is only "+`in description / goals / tags / past operation logs.
2384
+ `,parameters:i5,execute:async(w,$)=>{let X=i5.parse(w),Y=$.session_id||"unknown",J=TU(),D=X.context,W=$2().parentTaskId,G=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:W!==void 0&&W!==null&&Number.isInteger(W)&&W>0?W:void 0,Q=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,q=Q!==void 0&&Q!==p5,H=q?Q:void 0,B=X.tags,O;if(G!==void 0)try{let z=await _.getTask(G);if(z){let U=CU({parent:{taskId:z.id,projectPath:z.project_path,contextJson:z.context??"",tags:z.tags},overrides:{projectPath:H,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(H===void 0)H=U.project_path;if(X.tags===void 0)B=U.inheritedTags;O=U.context}}catch(z){$6.debug(`[task_create] failed to pre-load parent #${G} for context inheritance: ${z instanceof Error?z.message:String(z)}`)}try{let z=X.context===bU?void 0:X.context,U=z?JSON.parse(z):{},V=typeof U==="object"&&U!==null&&!Array.isArray(U)?U:{};if(O)try{let M=JSON.parse(O);if(M&&typeof M==="object"&&!Array.isArray(M)){for(let[R,N]of Object.entries(M))if(V[R]===void 0)V[R]=N}}catch{}if(!V.created_at)V.created_at=new Date().toISOString();if(!V.worktree_path&&J)V.worktree_path=J;D=JSON.stringify(V)}catch{D=X.context}try{let z=await _.createTask({parent_task_id:G,title:X.title,description:X.description,priority:X.priority,type:X.type||"normal",goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:B,sessionId:Y,project_path:H??(q?Q:p5),context:D});return v0(z.id),$6.info(`[createTask] Trace: Task #${z.id} created, currentTaskId=${z.id} set in EnvContext`),{success:!0,output:`Task created successfully: #${z.id} - ${z.title}`,metadata:{execution_time_ms:0,task_id:z.id,status:z.status,createdAt:z.createdAt}}}catch(z){return{success:!1,output:"",error:z instanceof Error?z.message:String(z),metadata:{execution_time_ms:0}}}}}}function m0(_){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:n5,execute:async(w,$)=>{let X=n5.parse(w);try{if(X.include_operations){let Y=await _.getTaskWithOperations(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let J=Y.task,D=J&&typeof J==="object"?{...J,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(D,null,2),metadata:{execution_time_ms:0}}}else{let Y=await _.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function u0(_){return{name:"task_list",description:"List tasks with optional filters for status, priority, type, parent_task_id, and depth (hierarchy level). "+`depth: 0=\u53EA\u6839\u4EFB\u52A1\uFF08\u65E0\u7236\u4EFB\u52A1\uFF09\uFF0C1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1\uFF0C2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1\uFF0C-1 \u6216\u5FFD\u7565=\u5168\u90E8\u3002
2385
+ `+"Returns { total, count, truncated, limit, offset, depth, tasks } where:\n - total: count of all matching tasks BEFORE pagination\n - count: count of tasks in the returned `tasks` array (after pagination)\n - truncated: true when total > count (data was truncated by pagination)\nNote: `total` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.",parameters:r5,execute:async(w,$)=>{let X=r5.parse(w);try{let Y=await _.listTasks({status:X.status,priority:X.priority,type:X.type,limit:X.limit,offset:X.offset,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({total:Y.total,count:Y.tasks.length,truncated:Y.total>Y.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:Y.tasks}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function l0(_){return{name:"task_search",description:"Search tasks by keywords across title, description, goals, tags, and operation records. Use this when you need to find tasks related to a "+"topic, feature, bug, or area of work \u2014 even when the keyword is only "+`in description / goals / tags / past operation logs.
2386
2386
 
2387
2387
  Returns { tasks, total, limit, offset } so you can paginate large result sets.
2388
2388
 
2389
- If \`keywords\` is empty, returns no results.`,parameters:r5,execute:async(w,$)=>{let X=r5.parse(w);try{let Y=await _.searchTasksByKeywords(X.keywords,{limit:X.limit,offset:X.offset,excludeTaskId:X.exclude_task_id,status:X.status,priority:X.priority,type:X.type,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({tasks:Y.tasks,total:Y.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function z4(_){return{name:"task_batch_archive",description:`Batch archive multiple tasks at once. Sets all specified tasks to 'archived' status and creates operation records for each.
2389
+ If \`keywords\` is empty, returns no results.`,parameters:a5,execute:async(w,$)=>{let X=a5.parse(w);try{let Y=await _.searchTasksByKeywords(X.keywords,{limit:X.limit,offset:X.offset,excludeTaskId:X.exclude_task_id,status:X.status,priority:X.priority,type:X.type,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({tasks:Y.tasks,total:Y.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function z$(_){return{name:"task_batch_archive",description:`Batch archive multiple tasks at once. Sets all specified tasks to 'archived' status and creates operation records for each.
2390
2390
 
2391
2391
  Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
2392
2392
 
2393
- Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:t5,execute:async(w,$)=>{let X=t5.parse(w),Y=X.task_ids,J=$.session_id||"batch-archive";if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let W=[],Q=0;for(let q of Y)try{if(await _.updateTask(q,{status:"archived"}))await _.createOperation({taskId:q,sessionId:J,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),Q++,W.push({id:q,success:!0});else W.push({id:q,success:!1,error:"Task not found"})}catch(H){W.push({id:q,success:!1,error:H instanceof Error?H.message:String(H)})}return{success:!W.some((q)=>!q.success),output:JSON.stringify({archived_count:Q,total:Y.length,errors:W.filter((q)=>!q.success).map((q)=>({id:q.id,error:q.error})),results:W},null,2),metadata:{execution_time_ms:0}}}}}function V4(_){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
2393
+ Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:e5,execute:async(w,$)=>{let X=e5.parse(w),Y=X.task_ids,J=$.session_id||"batch-archive";if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let D=[],W=0;for(let Q of Y)try{if(await _.updateTask(Q,{status:"archived"}))await _.createOperation({taskId:Q,sessionId:J,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),W++,D.push({id:Q,success:!0});else D.push({id:Q,success:!1,error:"Task not found"})}catch(q){D.push({id:Q,success:!1,error:q instanceof Error?q.message:String(q)})}return{success:!D.some((Q)=>!Q.success),output:JSON.stringify({archived_count:W,total:Y.length,errors:D.filter((Q)=>!Q.success).map((Q)=>({id:Q.id,error:Q.error})),results:D},null,2),metadata:{execution_time_ms:0}}}}}function V$(_){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
2394
2394
 
2395
2395
  Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
2396
2396
 
2397
- Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:e5,execute:async(w,$)=>{let Y=e5.parse(w).task_ids;if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let J=[],W=0;for(let G of Y)try{if(await _.deleteTask(G))W++,J.push({id:G,success:!0});else J.push({id:G,success:!1,error:"Task not found"})}catch(q){J.push({id:G,success:!1,error:q instanceof Error?q.message:String(q)})}return{success:!J.some((G)=>!G.success),output:JSON.stringify({deleted_count:W,total:Y.length,errors:J.filter((G)=>!G.success).map((G)=>({id:G.id,error:G.error})),results:J},null,2),metadata:{execution_time_ms:0}}}}}Jw();a();var TU=n("tool:update-task");async function IU(_,w,$){let X=new Set,Y=$;while(Y!==null&&Y!==void 0){if(Y===w)return!0;if(X.has(Y))break;X.add(Y);let J=await _.getTask(Y);if(!J)break;Y=J.parent_task_id}return!1}function c0(_){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:a5,execute:async(w,$)=>{let X=a5.parse(w),Y=$.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await IU(_,X.task_id,X.parent_task_id))return{success:!1,output:"",error:`Circular reference detected: setting parent_task_id to ${X.parent_task_id} for task #${X.task_id} would create a cycle`,metadata:{execution_time_ms:0}}}let J=await _.updateTask(X.task_id,{title:X.title,description:X.description,status:X.status,priority:X.priority,type:X.type,progress:X.progress,current_status:X.current_status,goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:X.tags,project_path:X.project_path,context:X.context,parent_task_id:X.parent_task_id});if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await _.createOperation({taskId:X.task_id,sessionId:Y,actionType:"progress",actionTitle:X.current_status||`Updated: ${X.status||`${X.progress}%`}`,actionDescription:JSON.stringify({status:X.status,progress:X.progress,current_status:X.current_status})});return v0(J.id),TU.info(`[updateTask] Trace: Task #${J.id} updated, currentTaskId=${J.id} set in EnvContext`),{success:!0,output:`Task updated: #${J.id} - ${J.title}`,metadata:{execution_time_ms:0,task:J}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function O4(_){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:o5,execute:async(w,$)=>{let X=o5.parse(w);try{if(!await _.deleteTask(X.task_id))return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Task deleted: #${X.task_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}Jw();a();var kU=n("task:tools:complete"),gU=`
2397
+ Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:_6,execute:async(w,$)=>{let Y=_6.parse(w).task_ids;if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let J=[],D=0;for(let G of Y)try{if(await _.deleteTask(G))D++,J.push({id:G,success:!0});else J.push({id:G,success:!1,error:"Task not found"})}catch(Q){J.push({id:G,success:!1,error:Q instanceof Error?Q.message:String(Q)})}return{success:!J.some((G)=>!G.success),output:JSON.stringify({deleted_count:D,total:Y.length,errors:J.filter((G)=>!G.success).map((G)=>({id:G.id,error:G.error})),results:J},null,2),metadata:{execution_time_ms:0}}}}}Dw();a();var IU=n("tool:update-task");async function kU(_,w,$){let X=new Set,Y=$;while(Y!==null&&Y!==void 0){if(Y===w)return!0;if(X.has(Y))break;X.add(Y);let J=await _.getTask(Y);if(!J)break;Y=J.parent_task_id}return!1}function c0(_){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:o5,execute:async(w,$)=>{let X=o5.parse(w),Y=$.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await kU(_,X.task_id,X.parent_task_id))return{success:!1,output:"",error:`Circular reference detected: setting parent_task_id to ${X.parent_task_id} for task #${X.task_id} would create a cycle`,metadata:{execution_time_ms:0}}}let J=await _.updateTask(X.task_id,{title:X.title,description:X.description,status:X.status,priority:X.priority,type:X.type,progress:X.progress,current_status:X.current_status,goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:X.tags,project_path:X.project_path,context:X.context,parent_task_id:X.parent_task_id});if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await _.createOperation({taskId:X.task_id,sessionId:Y,actionType:"progress",actionTitle:X.current_status||`Updated: ${X.status||`${X.progress}%`}`,actionDescription:JSON.stringify({status:X.status,progress:X.progress,current_status:X.current_status})});return v0(J.id),IU.info(`[updateTask] Trace: Task #${J.id} updated, currentTaskId=${J.id} set in EnvContext`),{success:!0,output:`Task updated: #${J.id} - ${J.title}`,metadata:{execution_time_ms:0,task:J}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function O$(_){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:s5,execute:async(w,$)=>{let X=s5.parse(w);try{if(!await _.deleteTask(X.task_id))return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Task deleted: #${X.task_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}Dw();a();var gU=n("task:tools:complete"),hU=`
2398
2398
  Mark a task as completed (progress=100, status=completed). Creates an operation record.
2399
2399
 
2400
2400
  **Before calling this tool**, you MUST:
@@ -2418,23 +2418,23 @@ The \`deliverable_storage_path\` will be persisted to the task's \`context.deliv
2418
2418
  - Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
2419
2419
 
2420
2420
  **Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
2421
- `.trim();function d0(_){return{name:"task_complete",description:gU,parameters:s5,execute:async(w,$)=>{let X=s5.parse(w),Y=$.session_id||"unknown";try{let J=await _.getTask(X.task_id);if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(J.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let W=await _.completeTask(X.task_id,Y,X.deliverable_storage_path);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return v0(void 0),kU.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${W.id} - ${W.title}
2422
- Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${W.id} - ${W.title}
2423
- Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:W}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function $X(_,w){if(_.updatedAt<w.updatedAt)return 1;if(_.updatedAt>w.updatedAt)return-1;if(_.id<w.id)return 1;if(_.id>w.id)return-1;return 0}function XX(_,w){if(w<0)return _;if(w===0)return _.map(($)=>({...$,children:[]}));return _.map(($)=>({...$,children:XX($.children,w-1)}))}function YX(_){let w=0;for(let $ of _)w+=1+YX($.children);return w}function hU(_){let w=new Map,$=new Map,X=[];for(let Y of _)w.set(Y.id,{id:Y.id,title:Y.title,status:Y.status,type:Y.type,priority:Y.priority,progress:Y.progress,children:[]});for(let Y of _){let J=Y.parent_task_id;if(J!==void 0&&J!==null&&w.has(J)){let W=$.get(J)||[];W.push(Y),$.set(J,W)}else X.push(Y)}for(let[Y,J]of $.entries()){let W=w.get(Y);J.sort($X),W.children=J.map((Q)=>w.get(Q.id))}return X.sort($X),X.map((Y)=>w.get(Y.id))}function p0(_){return{name:"task_tree",description:"View the task tree (forest) with optional filters. Use this BEFORE task_create to decide whether to create a root task (omit parent_task_id) or attach to an existing parent. "+"depth: 0=\u53EA\u6839\u4EFB\u52A1, 1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1, 2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1 (default), "+"-1 or omitted as -1=\u65E0\u9650\u5C42\u7EA7. "+`Returns { total, truncated, depth, parent_task_id, nodes } where:
2421
+ `.trim();function d0(_){return{name:"task_complete",description:hU,parameters:t5,execute:async(w,$)=>{let X=t5.parse(w),Y=$.session_id||"unknown";try{let J=await _.getTask(X.task_id);if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(J.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let D=await _.completeTask(X.task_id,Y,X.deliverable_storage_path);if(!D)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return v0(void 0),gU.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${D.id} - ${D.title}
2422
+ Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${D.id} - ${D.title}
2423
+ Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:D}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function X6(_,w){if(_.updatedAt<w.updatedAt)return 1;if(_.updatedAt>w.updatedAt)return-1;if(_.id<w.id)return 1;if(_.id>w.id)return-1;return 0}function Y6(_,w){if(w<0)return _;if(w===0)return _.map(($)=>({...$,children:[]}));return _.map(($)=>({...$,children:Y6($.children,w-1)}))}function J6(_){let w=0;for(let $ of _)w+=1+J6($.children);return w}function yU(_){let w=new Map,$=new Map,X=[];for(let Y of _)w.set(Y.id,{id:Y.id,title:Y.title,status:Y.status,type:Y.type,priority:Y.priority,progress:Y.progress,children:[]});for(let Y of _){let J=Y.parent_task_id;if(J!==void 0&&J!==null&&w.has(J)){let D=$.get(J)||[];D.push(Y),$.set(J,D)}else X.push(Y)}for(let[Y,J]of $.entries()){let D=w.get(Y);J.sort(X6),D.children=J.map((W)=>w.get(W.id))}return X.sort(X6),X.map((Y)=>w.get(Y.id))}function p0(_){return{name:"task_tree",description:"View the task tree (forest) with optional filters. Use this BEFORE task_create to decide whether to create a root task (omit parent_task_id) or attach to an existing parent. "+"depth: 0=\u53EA\u6839\u4EFB\u52A1, 1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1, 2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1 (default), "+"-1 or omitted as -1=\u65E0\u9650\u5C42\u7EA7. "+`Returns { total, truncated, depth, parent_task_id, nodes } where:
2424
2424
  - total: count of ALL tasks in the returned tree (incl. descendants)
2425
2425
  - truncated: always false for now (no pagination cap on tree)
2426
2426
  - depth: the resolved depth value
2427
2427
  - parent_task_id: the root's id, or null for forest mode
2428
2428
  - nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
2429
- Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:_X,execute:async(w,$)=>{let X=_X.parse(w);try{let Y=[],J=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let G=await _.getTask(X.parent_task_id);if(!G)Y=[];else{let q=await _.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[G,...q]}}else Y=(await _.listTasks({status:X.status,priority:X.priority,type:X.type,include_archived:X.include_archived,limit:9999,offset:0})).tasks;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(X.status)Y=Y.filter((G)=>G.status===X.status);if(X.priority)Y=Y.filter((G)=>G.priority===X.priority);if(X.type)Y=Y.filter((G)=>G.type===X.type);if(!X.include_archived)Y=Y.filter((G)=>G.status!=="archived")}let W=hU(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)W=XX(W,X.depth);let Q=YX(W);return{success:!0,output:JSON.stringify({total:Q,truncated:!1,depth:X.depth,parent_task_id:J,nodes:W}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}var Q1=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),A4=100,M4=150,G1=5000,yU=1,q1=200,HX=A.string().min(A4,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${A4} \u5B57\u7B26\uFF09\uFF0C\u65E0\u6CD5\u8868\u8FBE\u8FC7\u7A0B\u6982\u8981\uFF1B\u5982\u65E0\u8FC7\u7A0B\u4FE1\u606F\u8BF7\u7701\u7565\u8BE5\u5B57\u6BB5\uFF0C\u7EC6\u8282\u8BF7\u56DE\u67E5 sessionId\u3002`}).max(M4,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${M4} \u5B57\u7B26\uFF09\uFF0C\u4F1A\u9000\u5316\u4E3A\u65E5\u5FD7\u7EC6\u8282\uFF1B\u64CD\u4F5C\u8BB0\u5F55\u53EA\u627F\u62C5 milestone \u6982\u8981\uFF0C\u5B8C\u6574\u7EC6\u8282\u8BF7\u901A\u8FC7 sessionId \u56DE\u67E5 session\u3002`}).describe("\u8FC7\u7A0B\u6982\u8981\uFF08process_description\uFF09\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981\uFF1B"+`\u4E25\u683C\u63A7\u5236 ${A4}-${M4} \u5B57\u7B26\u3002`+"\u64CD\u4F5C\u8BB0\u5F55\u662F\u8282\u70B9\u9636\u6BB5 milestone \u6458\u8981\uFF0C\u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session\uFF1B"+"milestone_description \u624D\u662F\u8FBE\u6210\u7684\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\u3002"),DX=A.string().min(yU,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(q1,{message:`milestone_title \u8D85\u8FC7 ${q1} \u5B57\u7B26\uFF0C\u5EFA\u8BAE\u7CBE\u7B80\uFF08\u4E00\u884C\u6807\u9898\u5373\u53EF\uFF09\u3002`}).describe("\u91CC\u7A0B\u7891\u6807\u9898\uFF08milestone_title\uFF09\uFF1A\u8FBE\u6210\u7684\u91CC\u7A0B\u7891/\u72B6\u6001\u7684\u4E00\u53E5\u8BDD\u6807\u9898\uFF1B"+"\u5FC5\u586B\uFF0C1-200 \u5B57\u7B26\u3002"),BX=A.string().max(G1,{message:`milestone_description \u8D85\u8FC7 ${G1} \u5B57\u7B26\uFF1B\u5982\u9700\u66F4\u8BE6\u7EC6\u7684\u8FC7\u7A0B\uFF0C\u8BF7\u6539\u7528 process_description\u3002`}).optional().describe("\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\uFF08milestone_description\uFF09\uFF1A\u8FBE\u6210\u7684\u72B6\u6001\u6216\u7ED3\u679C\u63CF\u8FF0\uFF1B"+"\u53EF\u957F\u53EF\u77ED\uFF1B\u8FC7\u7A0B\u6982\u8981\u5E94\u653E\u5728 process_description\uFF0C\u4E0D\u8981\u4E0E\u672C\u5B57\u6BB5\u91CD\u590D\u3002"),vU=A.object({task_id:A.number().describe("Task ID"),milestone_type:Q1.optional(),milestone_title:DX.optional(),milestone_description:BX,process_description:HX.optional(),action_type:Q1.optional(),action_title:A.string().min(1).max(q1).optional(),action_description:A.string().max(G1).optional(),md_path:A.string().optional().describe("Path to detailed markdown documentation")}),JX=vU.transform((_)=>{let w=[],$=_.milestone_type,X=_.milestone_title,Y=_.milestone_description;if(!$&&_.action_type)$=_.action_type,w.push("action_type");if(!X&&_.action_title)X=_.action_title,w.push("action_title");if(Y===void 0&&_.action_description!==void 0)Y=_.action_description,w.push("action_description");return{task_id:_.task_id,milestone_type:$,milestone_title:X,milestone_description:Y,process_description:_.process_description,md_path:_.md_path,_deprecated_fields_used:w}}),WX=A.object({operation_id:A.number().describe("Operation ID")}),QX=A.object({task_id:A.number().describe("Task ID"),milestone_type:Q1.optional(),action_type:Q1.optional(),limit:A.number().optional().default(20),offset:A.number().optional().default(0)}).transform((_)=>{let w=[],$=_.milestone_type;if(!$&&_.action_type)$=_.action_type,w.push("action_type");return{task_id:_.task_id,milestone_type:$,limit:_.limit,offset:_.offset,_deprecated_fields_used:w}}),xU=A.object({operation_id:A.number().describe("Operation ID"),milestone_title:DX.optional(),milestone_description:BX,process_description:HX.optional(),action_title:A.string().min(1).max(q1).optional(),action_description:A.string().max(G1).optional()}),GX=xU.transform((_)=>{let w=[],$=_.milestone_title,X=_.milestone_description;if(!$&&_.action_title)$=_.action_title,w.push("action_title");if(X===void 0&&_.action_description!==void 0)X=_.action_description,w.push("action_description");return{operation_id:_.operation_id,milestone_title:$,milestone_description:X,process_description:_.process_description,_deprecated_fields_used:w}}),qX=A.object({operation_id:A.number().describe("Operation ID")});function mU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function uU(_){if(!_.milestone_type)return{ok:!1,error:"milestone_type is required (or action_type for backward compatibility). Use one of: create, progress, milestone, problem, solution, decision, review, completed, workflow_extracted."};if(!_.milestone_title)return{ok:!1,error:"milestone_title is required (or action_title for backward compatibility)."};return{ok:!0,milestoneType:_.milestone_type,milestoneTitle:_.milestone_title}}function i0(_){return{name:"task_operation_create",description:"Create an operation record for a task. Tracks milestones (state/result) and process (strategy + tool steps). Dual-dimension schema: milestone_type/title/description captures WHAT milestone was reached; process_description (100-150 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:JX,execute:async(w,$)=>{let X;try{X=JX.parse(w)}catch(W){if(W instanceof W_)return{success:!1,output:"",error:mU(W),metadata:{execution_time_ms:0}};throw W}let Y=uU(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let J=$.session_id||"unknown";try{let W=await _.createOperation({taskId:X.task_id,sessionId:J,milestoneType:Y.milestoneType,milestoneTitle:Y.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),Q=`Operation created: #${W.id} for task #${W.taskId} [milestone=${W.milestoneType}] ${W.milestoneTitle}`,G=[];if(X._deprecated_fields_used.length>0)G.push(`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_type / milestone_title / milestone_description \u4E3B\u5B57\u6BB5\u3002");if(G.length>0)Q+=`
2429
+ Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:w6,execute:async(w,$)=>{let X=w6.parse(w);try{let Y=[],J=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let G=await _.getTask(X.parent_task_id);if(!G)Y=[];else{let Q=await _.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[G,...Q]}}else Y=(await _.listTasks({status:X.status,priority:X.priority,type:X.type,include_archived:X.include_archived,limit:9999,offset:0})).tasks;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(X.status)Y=Y.filter((G)=>G.status===X.status);if(X.priority)Y=Y.filter((G)=>G.priority===X.priority);if(X.type)Y=Y.filter((G)=>G.type===X.type);if(!X.include_archived)Y=Y.filter((G)=>G.status!=="archived")}let D=yU(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)D=Y6(D,X.depth);let W=J6(D);return{success:!0,output:JSON.stringify({total:W,truncated:!1,depth:X.depth,parent_task_id:J,nodes:D}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}var W2=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),A$=100,M$=150,G2=5000,vU=1,Q2=200,H6=A.string().min(A$,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${A$} \u5B57\u7B26\uFF09\uFF0C\u65E0\u6CD5\u8868\u8FBE\u8FC7\u7A0B\u6982\u8981\uFF1B\u5982\u65E0\u8FC7\u7A0B\u4FE1\u606F\u8BF7\u7701\u7565\u8BE5\u5B57\u6BB5\uFF0C\u7EC6\u8282\u8BF7\u56DE\u67E5 sessionId\u3002`}).max(M$,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${M$} \u5B57\u7B26\uFF09\uFF0C\u4F1A\u9000\u5316\u4E3A\u65E5\u5FD7\u7EC6\u8282\uFF1B\u64CD\u4F5C\u8BB0\u5F55\u53EA\u627F\u62C5 milestone \u6982\u8981\uFF0C\u5B8C\u6574\u7EC6\u8282\u8BF7\u901A\u8FC7 sessionId \u56DE\u67E5 session\u3002`}).describe("\u8FC7\u7A0B\u6982\u8981\uFF08process_description\uFF09\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981\uFF1B"+`\u4E25\u683C\u63A7\u5236 ${A$}-${M$} \u5B57\u7B26\u3002`+"\u64CD\u4F5C\u8BB0\u5F55\u662F\u8282\u70B9\u9636\u6BB5 milestone \u6458\u8981\uFF0C\u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session\uFF1B"+"milestone_description \u624D\u662F\u8FBE\u6210\u7684\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\u3002"),B6=A.string().min(vU,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(Q2,{message:`milestone_title \u8D85\u8FC7 ${Q2} \u5B57\u7B26\uFF0C\u5EFA\u8BAE\u7CBE\u7B80\uFF08\u4E00\u884C\u6807\u9898\u5373\u53EF\uFF09\u3002`}).describe("\u91CC\u7A0B\u7891\u6807\u9898\uFF08milestone_title\uFF09\uFF1A\u8FBE\u6210\u7684\u91CC\u7A0B\u7891/\u72B6\u6001\u7684\u4E00\u53E5\u8BDD\u6807\u9898\uFF1B"+"\u5FC5\u586B\uFF0C1-200 \u5B57\u7B26\u3002"),U6=A.string().max(G2,{message:`milestone_description \u8D85\u8FC7 ${G2} \u5B57\u7B26\uFF1B\u5982\u9700\u66F4\u8BE6\u7EC6\u7684\u8FC7\u7A0B\uFF0C\u8BF7\u6539\u7528 process_description\u3002`}).optional().describe("\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\uFF08milestone_description\uFF09\uFF1A\u8FBE\u6210\u7684\u72B6\u6001\u6216\u7ED3\u679C\u63CF\u8FF0\uFF1B"+"\u53EF\u957F\u53EF\u77ED\uFF1B\u8FC7\u7A0B\u6982\u8981\u5E94\u653E\u5728 process_description\uFF0C\u4E0D\u8981\u4E0E\u672C\u5B57\u6BB5\u91CD\u590D\u3002"),xU=A.object({task_id:A.number().describe("Task ID"),milestone_type:W2.optional(),milestone_title:B6.optional(),milestone_description:U6,process_description:H6.optional(),action_type:W2.optional(),action_title:A.string().min(1).max(Q2).optional(),action_description:A.string().max(G2).optional(),md_path:A.string().optional().describe("Path to detailed markdown documentation")}),D6=xU.transform((_)=>{let w=[],$=_.milestone_type,X=_.milestone_title,Y=_.milestone_description;if(!$&&_.action_type)$=_.action_type,w.push("action_type");if(!X&&_.action_title)X=_.action_title,w.push("action_title");if(Y===void 0&&_.action_description!==void 0)Y=_.action_description,w.push("action_description");return{task_id:_.task_id,milestone_type:$,milestone_title:X,milestone_description:Y,process_description:_.process_description,md_path:_.md_path,_deprecated_fields_used:w}}),W6=A.object({operation_id:A.number().describe("Operation ID")}),G6=A.object({task_id:A.number().describe("Task ID"),milestone_type:W2.optional(),action_type:W2.optional(),limit:A.number().optional().default(20),offset:A.number().optional().default(0)}).transform((_)=>{let w=[],$=_.milestone_type;if(!$&&_.action_type)$=_.action_type,w.push("action_type");return{task_id:_.task_id,milestone_type:$,limit:_.limit,offset:_.offset,_deprecated_fields_used:w}}),mU=A.object({operation_id:A.number().describe("Operation ID"),milestone_title:B6.optional(),milestone_description:U6,process_description:H6.optional(),action_title:A.string().min(1).max(Q2).optional(),action_description:A.string().max(G2).optional()}),Q6=mU.transform((_)=>{let w=[],$=_.milestone_title,X=_.milestone_description;if(!$&&_.action_title)$=_.action_title,w.push("action_title");if(X===void 0&&_.action_description!==void 0)X=_.action_description,w.push("action_description");return{operation_id:_.operation_id,milestone_title:$,milestone_description:X,process_description:_.process_description,_deprecated_fields_used:w}}),q6=A.object({operation_id:A.number().describe("Operation ID")});function uU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function lU(_){if(!_.milestone_type)return{ok:!1,error:"milestone_type is required (or action_type for backward compatibility). Use one of: create, progress, milestone, problem, solution, decision, review, completed, workflow_extracted."};if(!_.milestone_title)return{ok:!1,error:"milestone_title is required (or action_title for backward compatibility)."};return{ok:!0,milestoneType:_.milestone_type,milestoneTitle:_.milestone_title}}function i0(_){return{name:"task_operation_create",description:"Create an operation record for a task. Tracks milestones (state/result) and process (strategy + tool steps). Dual-dimension schema: milestone_type/title/description captures WHAT milestone was reached; process_description (100-150 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:D6,execute:async(w,$)=>{let X;try{X=D6.parse(w)}catch(D){if(D instanceof D_)return{success:!1,output:"",error:uU(D),metadata:{execution_time_ms:0}};throw D}let Y=lU(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let J=$.session_id||"unknown";try{let D=await _.createOperation({taskId:X.task_id,sessionId:J,milestoneType:Y.milestoneType,milestoneTitle:Y.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),W=`Operation created: #${D.id} for task #${D.taskId} [milestone=${D.milestoneType}] ${D.milestoneTitle}`,G=[];if(X._deprecated_fields_used.length>0)G.push(`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_type / milestone_title / milestone_description \u4E3B\u5B57\u6BB5\u3002");if(G.length>0)W+=`
2430
2430
 
2431
2431
  `+G.join(`
2432
- `);return{success:!0,output:Q,metadata:{execution_time_ms:0,operation_id:W.id,task_id:W.taskId,session_id:W.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function R4(_){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:WX,execute:async(w,$)=>{let X=WX.parse(w);try{let Y=await _.getOperation(X.operation_id);if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function n0(_){return{name:"task_operation_list",description:"List operation records for a task with optional filters. Use milestone_type (canonical) or action_type (deprecated, auto-mapped).",parameters:QX,execute:async(w,$)=>{let X=QX.parse(w);try{let Y=await _.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),J=JSON.stringify({operations:Y,count:Y.length});if(X._deprecated_fields_used.length>0)J=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
2432
+ `);return{success:!0,output:W,metadata:{execution_time_ms:0,operation_id:D.id,task_id:D.taskId,session_id:D.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(D){return{success:!1,output:"",error:D instanceof Error?D.message:String(D),metadata:{execution_time_ms:0}}}}}}function R$(_){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:W6,execute:async(w,$)=>{let X=W6.parse(w);try{let Y=await _.getOperation(X.operation_id);if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function n0(_){return{name:"task_operation_list",description:"List operation records for a task with optional filters. Use milestone_type (canonical) or action_type (deprecated, auto-mapped).",parameters:G6,execute:async(w,$)=>{let X=G6.parse(w);try{let Y=await _.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),J=JSON.stringify({operations:Y,count:Y.length});if(X._deprecated_fields_used.length>0)J=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
2433
2433
 
2434
- `+J;return{success:!0,output:J,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function lU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function f4(_){return{name:"task_operation_update",description:"Update an operation record. Use milestone_title / milestone_description (canonical) or action_title / action_description (deprecated, auto-mapped). process_description captures the process (100-150 chars).",parameters:GX,execute:async(w,$)=>{let X;try{X=GX.parse(w)}catch(Y){if(Y instanceof W_)return{success:!1,output:"",error:lU(Y),metadata:{execution_time_ms:0}};throw Y}try{let Y=await _.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let J=`Operation updated: #${Y.id}`;if(X._deprecated_fields_used.length>0)J+=`
2434
+ `+J;return{success:!0,output:J,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function cU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function f$(_){return{name:"task_operation_update",description:"Update an operation record. Use milestone_title / milestone_description (canonical) or action_title / action_description (deprecated, auto-mapped). process_description captures the process (100-150 chars).",parameters:Q6,execute:async(w,$)=>{let X;try{X=Q6.parse(w)}catch(Y){if(Y instanceof D_)return{success:!1,output:"",error:cU(Y),metadata:{execution_time_ms:0}};throw Y}try{let Y=await _.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let J=`Operation updated: #${Y.id}`;if(X._deprecated_fields_used.length>0)J+=`
2435
2435
 
2436
- \u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:J,metadata:{execution_time_ms:0,operation:Y,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function L4(_){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:qX,execute:async(w,$)=>{let X=qX.parse(w);try{if(!await _.deleteOperation(X.operation_id))return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Operation deleted: #${X.operation_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}import{join as RX}from"path";function o(_){process.stderr.write(`${_}
2437
- `)}var r0=()=>{},UX={};a_(UX,{runMigration:()=>cU});function cU(_){o(`[Migration 001] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw $}try{w.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw $}o("[Migration 001] Migration completed successfully")}finally{w.close()}}var dU=r(()=>{Ww(),r0()}),zX={};a_(zX,{runMigration:()=>pU});function pU(_){o(`[Migration 002] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw $}o("[Migration 002] Migration completed successfully")}finally{w.close()}}var iU=r(()=>{Ww(),r0()}),VX={};a_(VX,{runMigration:()=>nU});function nU(_){o(`[Migration 003] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw $}o("[Migration 003] Migration completed successfully")}finally{w.close()}}var rU=r(()=>{Ww(),r0()}),OX={};a_(OX,{runMigration:()=>aU});function aU(_){o(`[Migration 004] Starting migration for: ${_}`);let w=w0(_);try{let $=new Set,X=w.query("PRAGMA table_info(task_operation)").all();for(let Y of X)$.add(Y.name);for(let{oldName:Y,newName:J}of AX){let W=$.has(Y),Q=$.has(J);if(W&&!Q)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(Q)o(`[Migration 004] ${J} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${J}`)}o("[Migration 004] Migration completed successfully")}finally{w.close()}}var AX,oU=r(()=>{Ww(),r0(),AX=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),MX={};a_(MX,{runMigration:()=>sU});function sU(_){o(`[Migration 005] Starting migration for: ${_}`);let w=w0(_),$={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(w.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return o("[Migration 005] task table does not exist, skipping"),$;let Y=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if($.blobCountBefore=Y[0]?.cnt??0,$.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),$;w.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),$.ran=!0;let J=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();$.blobCountAfter=J[0]?.cnt??0,o(`[Migration 005] Converted ${$.blobCountBefore-$.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{w.close()}return $}var tU=r(()=>{Ww(),r0()});function eU(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}try{let{DatabaseSync:_}=w_("node:sqlite");if(typeof _==="function")return _}catch{}return w_("better-sqlite3")}function w0(_){let w=eU();return _z(new w(_))}function _z(_){if(typeof _.run!=="function")_.run=function(w,...$){if($.length>0)return this.prepare(w).run(...$);else return this.exec(w)};return _.query=function(w,...$){if($.length===0){let Y=this.prepare(w);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(w);return{all:(...Y)=>X.all(...$,...Y),get:(...Y)=>X.get(...$,...Y),run:(...Y)=>X.run(...$,...Y)}},_}function wz(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return RX(_,".local","share")}function H1(){return RX(wz(),"roy-agent","tasks.db")}var fw,Lw,Ww=r(()=>{a(),V_(),fw=n("task:store"),Lw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||H1()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=w_("fs"),X=w_("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=w0(this.dbPath),this.db.run(`
2436
+ \u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:J,metadata:{execution_time_ms:0,operation:Y,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function L$(_){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:q6,execute:async(w,$)=>{let X=q6.parse(w);try{if(!await _.deleteOperation(X.operation_id))return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Operation deleted: #${X.operation_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}import{join as f6}from"path";function o(_){process.stderr.write(`${_}
2437
+ `)}var r0=()=>{},z6={};o_(z6,{runMigration:()=>dU});function dU(_){o(`[Migration 001] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw $}try{w.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw $}o("[Migration 001] Migration completed successfully")}finally{w.close()}}var pU=r(()=>{Ww(),r0()}),V6={};o_(V6,{runMigration:()=>iU});function iU(_){o(`[Migration 002] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw $}o("[Migration 002] Migration completed successfully")}finally{w.close()}}var nU=r(()=>{Ww(),r0()}),O6={};o_(O6,{runMigration:()=>rU});function rU(_){o(`[Migration 003] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw $}o("[Migration 003] Migration completed successfully")}finally{w.close()}}var aU=r(()=>{Ww(),r0()}),A6={};o_(A6,{runMigration:()=>oU});function oU(_){o(`[Migration 004] Starting migration for: ${_}`);let w=w0(_);try{let $=new Set,X=w.query("PRAGMA table_info(task_operation)").all();for(let Y of X)$.add(Y.name);for(let{oldName:Y,newName:J}of M6){let D=$.has(Y),W=$.has(J);if(D&&!W)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(W)o(`[Migration 004] ${J} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${J}`)}o("[Migration 004] Migration completed successfully")}finally{w.close()}}var M6,sU=r(()=>{Ww(),r0(),M6=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),R6={};o_(R6,{runMigration:()=>tU});function tU(_){o(`[Migration 005] Starting migration for: ${_}`);let w=w0(_),$={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(w.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return o("[Migration 005] task table does not exist, skipping"),$;let Y=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if($.blobCountBefore=Y[0]?.cnt??0,$.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),$;w.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),$.ran=!0;let J=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();$.blobCountAfter=J[0]?.cnt??0,o(`[Migration 005] Converted ${$.blobCountBefore-$.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{w.close()}return $}var eU=r(()=>{Ww(),r0()});function _z(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function w0(_){let w=_z();return wz(new w(_))}function wz(_){if(typeof _.run!=="function")_.run=function(w,...$){if($.length>0)return this.prepare(w).run(...$);else return this.exec(w)};return _.query=function(w,...$){if($.length===0){let Y=this.prepare(w);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(w);return{all:(...Y)=>X.all(...$,...Y),get:(...Y)=>X.get(...$,...Y),run:(...Y)=>X.run(...$,...Y)}},_}function $z(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return f6(_,".local","share")}function q2(){return f6($z(),"roy-agent","tasks.db")}var Lw,Fw,Ww=r(()=>{a(),V_(),Lw=n("task:store"),Fw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||q2()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=e("fs"),X=e("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=w0(this.dbPath),this.db.run(`
2438
2438
  CREATE TABLE IF NOT EXISTS task (
2439
2439
  id INTEGER PRIMARY KEY AUTOINCREMENT,
2440
2440
  title TEXT NOT NULL,
@@ -2482,19 +2482,19 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
2482
2482
  FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
2483
2483
  FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
2484
2484
  )
2485
- `),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)"),this.dbPath!==":memory:"){try{let{runMigration:w}=(dU(),mw(UX));w(this.dbPath)}catch(w){fw.warn(`[Migration 001] Failed to run: ${w.message}`)}try{let{runMigration:w}=(iU(),mw(zX));w(this.dbPath)}catch(w){fw.warn(`[Migration 002] Failed to run: ${w.message}`)}try{let{runMigration:w}=(rU(),mw(VX));w(this.dbPath)}catch(w){fw.warn(`[Migration 003] Failed to run: ${w.message}`)}try{let{runMigration:w}=(oU(),mw(OX));w(this.dbPath)}catch(w){fw.warn(`[Migration 004] Failed to run: ${w.message}`)}try{let{runMigration:w}=(tU(),mw(MX));w(this.dbPath)}catch(w){fw.warn(`[Migration 005] Failed to run: ${w.message}`)}}this.initialized=!0,fw.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(w){await this.initialize();let $=Date.now(),Y=this.db.prepare(`
2485
+ `),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)"),this.dbPath!==":memory:"){try{let{runMigration:w}=(pU(),mw(z6));w(this.dbPath)}catch(w){Lw.warn(`[Migration 001] Failed to run: ${w.message}`)}try{let{runMigration:w}=(nU(),mw(V6));w(this.dbPath)}catch(w){Lw.warn(`[Migration 002] Failed to run: ${w.message}`)}try{let{runMigration:w}=(aU(),mw(O6));w(this.dbPath)}catch(w){Lw.warn(`[Migration 003] Failed to run: ${w.message}`)}try{let{runMigration:w}=(sU(),mw(A6));w(this.dbPath)}catch(w){Lw.warn(`[Migration 004] Failed to run: ${w.message}`)}try{let{runMigration:w}=(eU(),mw(R6));w(this.dbPath)}catch(w){Lw.warn(`[Migration 005] Failed to run: ${w.message}`)}}this.initialized=!0,Lw.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(w){await this.initialize();let $=Date.now(),Y=this.db.prepare(`
2486
2486
  INSERT INTO task (title, description, priority, type, parent_task_id,
2487
2487
  goals_and_expected_deliverables, due_date, tags, status,
2488
2488
  current_status, created_at, updated_at, project_path, context)
2489
2489
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
2490
- `).run(w.title,w.description||"",w.priority||"medium",w.type||"normal",w.parent_task_id||null,w.goals_and_expected_deliverables||"",w.due_date||null,w.tags?JSON.stringify(w.tags):null,$,$,w.project_path,w.context),J=await this.getTask(Y.lastInsertRowid);if(J)return this.tasksCache.set(J.id,J),J;throw Error("Failed to create task")}async getTask(w){if(await this.initialize(),this.tasksCache.has(w))return this.tasksCache.get(w);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(w);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(w,Y),Y}async updateTask(w,$){await this.initialize();let X=await this.getTask(w);if(!X)return;let Y=[],J=[];if($.title!==void 0)Y.push("title = ?"),J.push($.title);if($.description!==void 0)Y.push("description = ?"),J.push($.description);if($.status!==void 0)Y.push("status = ?"),J.push($.status);if($.priority!==void 0)Y.push("priority = ?"),J.push($.priority);if($.type!==void 0)Y.push("type = ?"),J.push($.type);if($.progress!==void 0)Y.push("progress = ?"),J.push($.progress);if($.current_status!==void 0)Y.push("current_status = ?"),J.push($.current_status);if($.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),J.push($.goals_and_expected_deliverables);if($.due_date!==void 0)Y.push("due_date = ?"),J.push($.due_date);if($.tags!==void 0)Y.push("tags = ?"),J.push(JSON.stringify($.tags));if($.project_path!==void 0)Y.push("project_path = ?"),J.push($.project_path);if($.context!==void 0)Y.push("context = ?"),J.push($.context);if($.parent_task_id!==void 0)Y.push("parent_task_id = ?"),J.push($.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),J.push(Date.now()),J.push(w),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...J),this.tasksCache.delete(w),this.getTask(w)}async deleteTask(w){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(w);if(X.changes>0)this.tasksCache.delete(w),this.operationsCache.delete(w);return X.changes>0}async listTasks(w){if(await this.initialize(),w?.depth!==void 0&&w.depth>=0&&w.parent_task_id===void 0)return this.listTasksByDepth(w);let $=["1=1"],X=[];if(w?.status)$.push("status = ?"),X.push(w.status);if(w?.priority)$.push("priority = ?"),X.push(w.priority);if(w?.type)$.push("type = ?"),X.push(w.type);if(w?.parent_task_id!==void 0)$.push("parent_task_id = ?"),X.push(w.parent_task_id);if(!w?.include_archived&&w?.status!=="archived")$.push("status != 'archived'");let Y=$.join(" AND "),J=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,Q=this.db.prepare(J).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${Y}`,q=[...X];if(G+=" ORDER BY updated_at DESC",w?.limit)G+=" LIMIT ?",q.push(w.limit);if(w?.offset)G+=" OFFSET ?",q.push(w.offset);return{tasks:this.db.prepare(G).all(...q).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z}),total:Q}}async listTasksByDepth(w){let $=w.depth??0,X=["1=1"],Y=[];if(w.status)X.push("status = ?"),Y.push(w.status);if(w.priority)X.push("priority = ?"),Y.push(w.priority);if(w.type)X.push("type = ?"),Y.push(w.type);if(!w?.include_archived&&w?.status!=="archived")X.push("status != 'archived'");let J=X.join(" AND "),W=[];if($===0){let B=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`,D=this.db.prepare(B).all(...Y);for(let O of D){let z=this.rowToTask(O);this.tasksCache.set(z.id,z),W.push(z)}}else{let D=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`).all(...Y).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z});W.push(...D);for(let O=1;O<=$;O++){if(D.length===0)break;let z=D.map((N)=>N.id),V=`SELECT * FROM task WHERE parent_task_id IN (${z.map(()=>"?").join(",")}) AND ${J} ORDER BY updated_at DESC`,f=this.db.prepare(V).all(...z,...Y).map((N)=>{let R=this.rowToTask(N);return this.tasksCache.set(R.id,R),R});W.push(...f),D=f}}let Q=W.length,G=w.offset??0,q=w.limit??Q;return{tasks:W.slice(G,G+q),total:Q}}async getTaskTree(w,$=-1){await this.initialize();let X=[],Y=[w],J=0;while(Y.length>0){if($!==-1&&J>=$)break;let W=Y.map(()=>"?").join(","),Q=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${W}) ORDER BY updated_at DESC`).all(...Y),G=[];for(let q of Q){let H=this.rowToTask(q);this.tasksCache.set(H.id,H),X.push(H),G.push(H.id)}Y=G,J++}return X}async getChildTasks(w,$={}){return this.listTasks({...$,parent_task_id:w})}async createOperation(w){await this.initialize();let $=w.milestoneType??w.actionType,X=w.milestoneTitle??w.actionTitle,Y=w.milestoneDescription??w.actionDescription;if(!$||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let J=Date.now(),Q=this.db.prepare(`
2490
+ `).run(w.title,w.description||"",w.priority||"medium",w.type||"normal",w.parent_task_id||null,w.goals_and_expected_deliverables||"",w.due_date||null,w.tags?JSON.stringify(w.tags):null,$,$,w.project_path,w.context),J=await this.getTask(Y.lastInsertRowid);if(J)return this.tasksCache.set(J.id,J),J;throw Error("Failed to create task")}async getTask(w){if(await this.initialize(),this.tasksCache.has(w))return this.tasksCache.get(w);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(w);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(w,Y),Y}async updateTask(w,$){await this.initialize();let X=await this.getTask(w);if(!X)return;let Y=[],J=[];if($.title!==void 0)Y.push("title = ?"),J.push($.title);if($.description!==void 0)Y.push("description = ?"),J.push($.description);if($.status!==void 0)Y.push("status = ?"),J.push($.status);if($.priority!==void 0)Y.push("priority = ?"),J.push($.priority);if($.type!==void 0)Y.push("type = ?"),J.push($.type);if($.progress!==void 0)Y.push("progress = ?"),J.push($.progress);if($.current_status!==void 0)Y.push("current_status = ?"),J.push($.current_status);if($.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),J.push($.goals_and_expected_deliverables);if($.due_date!==void 0)Y.push("due_date = ?"),J.push($.due_date);if($.tags!==void 0)Y.push("tags = ?"),J.push(JSON.stringify($.tags));if($.project_path!==void 0)Y.push("project_path = ?"),J.push($.project_path);if($.context!==void 0)Y.push("context = ?"),J.push($.context);if($.parent_task_id!==void 0)Y.push("parent_task_id = ?"),J.push($.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),J.push(Date.now()),J.push(w),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...J),this.tasksCache.delete(w),this.getTask(w)}async deleteTask(w){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(w);if(X.changes>0)this.tasksCache.delete(w),this.operationsCache.delete(w);return X.changes>0}async listTasks(w){if(await this.initialize(),w?.depth!==void 0&&w.depth>=0&&w.parent_task_id===void 0)return this.listTasksByDepth(w);let $=["1=1"],X=[];if(w?.status)$.push("status = ?"),X.push(w.status);if(w?.priority)$.push("priority = ?"),X.push(w.priority);if(w?.type)$.push("type = ?"),X.push(w.type);if(w?.parent_task_id!==void 0)$.push("parent_task_id = ?"),X.push(w.parent_task_id);if(!w?.include_archived&&w?.status!=="archived")$.push("status != 'archived'");let Y=$.join(" AND "),J=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,W=this.db.prepare(J).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${Y}`,Q=[...X];if(G+=" ORDER BY updated_at DESC",w?.limit)G+=" LIMIT ?",Q.push(w.limit);if(w?.offset)G+=" OFFSET ?",Q.push(w.offset);return{tasks:this.db.prepare(G).all(...Q).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z}),total:W}}async listTasksByDepth(w){let $=w.depth??0,X=["1=1"],Y=[];if(w.status)X.push("status = ?"),Y.push(w.status);if(w.priority)X.push("priority = ?"),Y.push(w.priority);if(w.type)X.push("type = ?"),Y.push(w.type);if(!w?.include_archived&&w?.status!=="archived")X.push("status != 'archived'");let J=X.join(" AND "),D=[];if($===0){let H=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`,B=this.db.prepare(H).all(...Y);for(let O of B){let z=this.rowToTask(O);this.tasksCache.set(z.id,z),D.push(z)}}else{let B=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`).all(...Y).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z});D.push(...B);for(let O=1;O<=$;O++){if(B.length===0)break;let z=B.map((N)=>N.id),V=`SELECT * FROM task WHERE parent_task_id IN (${z.map(()=>"?").join(",")}) AND ${J} ORDER BY updated_at DESC`,R=this.db.prepare(V).all(...z,...Y).map((N)=>{let b=this.rowToTask(N);return this.tasksCache.set(b.id,b),b});D.push(...R),B=R}}let W=D.length,G=w.offset??0,Q=w.limit??W;return{tasks:D.slice(G,G+Q),total:W}}async getTaskTree(w,$=-1){await this.initialize();let X=[],Y=[w],J=0;while(Y.length>0){if($!==-1&&J>=$)break;let D=Y.map(()=>"?").join(","),W=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${D}) ORDER BY updated_at DESC`).all(...Y),G=[];for(let Q of W){let q=this.rowToTask(Q);this.tasksCache.set(q.id,q),X.push(q),G.push(q.id)}Y=G,J++}return X}async getChildTasks(w,$={}){return this.listTasks({...$,parent_task_id:w})}async createOperation(w){await this.initialize();let $=w.milestoneType??w.actionType,X=w.milestoneTitle??w.actionTitle,Y=w.milestoneDescription??w.actionDescription;if(!$||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let J=Date.now(),W=this.db.prepare(`
2491
2491
  INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
2492
2492
  milestone_description, process_description, timestamp, md_path)
2493
2493
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
2494
- `).run(w.taskId,w.sessionId,$,X,Y||"",w.processDescription||"",J,w.mdPath||null);this.operationsCache.delete(w.taskId);let G=await this.getOperation(Q.lastInsertRowid);if(!G)throw Error("Failed to create operation");return G}async getOperation(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(w);if(!X)return;return this.rowToOperation(X)}async updateOperation(w,$){await this.initialize();let X=await this.getOperation(w);if(!X)return;let Y=$.milestoneTitle??$.actionTitle,J=$.milestoneDescription??$.actionDescription,W=[],Q=[];if(Y!==void 0)W.push("milestone_title = ?"),Q.push(Y);if(J!==void 0)W.push("milestone_description = ?"),Q.push(J);if($.processDescription!==void 0)W.push("process_description = ?"),Q.push($.processDescription);if(W.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${W.join(", ")} WHERE id = ?`).run(...Q,w),this.operationsCache.delete(X.taskId),this.getOperation(w)}async deleteOperation(w){await this.initialize();let $=await this.getOperation(w);if(!$)return!1;let Y=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(w);if(Y.changes>0)this.operationsCache.delete($.taskId);return Y.changes>0}async listOperations(w){await this.initialize();let $=w.taskId;if(!this.operationsCache.has($)){let G=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(w.taskId);this.operationsCache.set($,G.map((q)=>this.rowToOperation(q)))}let X=this.operationsCache.get($),Y=w.milestoneType??w.actionType;if(Y)X=X.filter((Q)=>Q.milestoneType===Y);let J=w.offset||0,W=w.limit||20;return X.slice(J,J+W)}async getTaskIdBySessionId(w){if(await this.initialize(),!w)return;let $=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(w);return typeof $?.task_id==="number"?$.task_id:void 0}rowToTask(w){return{id:w.id,title:String(w.title??""),description:String(w.description??""),status:String(w.status??"todo"),priority:String(w.priority??"medium"),type:String(w.type??"normal"),progress:w.progress,current_status:String(w.current_status??""),goals_and_expected_deliverables:String(w.goals_and_expected_deliverables??""),parent_task_id:w.parent_task_id||void 0,createdAt:new Date(w.created_at).toISOString(),updatedAt:new Date(w.updated_at).toISOString(),due_date:w.due_date?String(w.due_date):void 0,tags:_.parseTagsSafely(w.tags),project_path:String(w.project_path??"unknown"),context:w.context}}static parseTagsSafely(w){if(w===null||w===void 0||w==="")return;let $=typeof w==="string"?w:String(w);try{let X=JSON.parse($);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[$]}}rowToOperation(w){let $=w.milestone_type??w.action_type,X=w.milestone_title??w.action_title,Y=w.milestone_description??w.action_description??"";return{id:w.id,taskId:w.task_id,sessionId:w.session_id,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:w.process_description??"",timestamp:new Date(w.timestamp).toISOString(),mdPath:w.md_path||void 0,actionType:$,actionTitle:X,actionDescription:Y}}async createTag(w){await this.initialize();let $=Date.now(),X=await this.getTagByName(w);if(X)return X;return{id:this.db.prepare(`
2494
+ `).run(w.taskId,w.sessionId,$,X,Y||"",w.processDescription||"",J,w.mdPath||null);this.operationsCache.delete(w.taskId);let G=await this.getOperation(W.lastInsertRowid);if(!G)throw Error("Failed to create operation");return G}async getOperation(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(w);if(!X)return;return this.rowToOperation(X)}async updateOperation(w,$){await this.initialize();let X=await this.getOperation(w);if(!X)return;let Y=$.milestoneTitle??$.actionTitle,J=$.milestoneDescription??$.actionDescription,D=[],W=[];if(Y!==void 0)D.push("milestone_title = ?"),W.push(Y);if(J!==void 0)D.push("milestone_description = ?"),W.push(J);if($.processDescription!==void 0)D.push("process_description = ?"),W.push($.processDescription);if(D.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${D.join(", ")} WHERE id = ?`).run(...W,w),this.operationsCache.delete(X.taskId),this.getOperation(w)}async deleteOperation(w){await this.initialize();let $=await this.getOperation(w);if(!$)return!1;let Y=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(w);if(Y.changes>0)this.operationsCache.delete($.taskId);return Y.changes>0}async listOperations(w){await this.initialize();let $=w.taskId;if(!this.operationsCache.has($)){let G=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(w.taskId);this.operationsCache.set($,G.map((Q)=>this.rowToOperation(Q)))}let X=this.operationsCache.get($),Y=w.milestoneType??w.actionType;if(Y)X=X.filter((W)=>W.milestoneType===Y);let J=w.offset||0,D=w.limit||20;return X.slice(J,J+D)}async getTaskIdBySessionId(w){if(await this.initialize(),!w)return;let $=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(w);return typeof $?.task_id==="number"?$.task_id:void 0}rowToTask(w){return{id:w.id,title:String(w.title??""),description:String(w.description??""),status:String(w.status??"todo"),priority:String(w.priority??"medium"),type:String(w.type??"normal"),progress:w.progress,current_status:String(w.current_status??""),goals_and_expected_deliverables:String(w.goals_and_expected_deliverables??""),parent_task_id:w.parent_task_id||void 0,createdAt:new Date(w.created_at).toISOString(),updatedAt:new Date(w.updated_at).toISOString(),due_date:w.due_date?String(w.due_date):void 0,tags:_.parseTagsSafely(w.tags),project_path:String(w.project_path??"unknown"),context:w.context}}static parseTagsSafely(w){if(w===null||w===void 0||w==="")return;let $=typeof w==="string"?w:String(w);try{let X=JSON.parse($);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[$]}}rowToOperation(w){let $=w.milestone_type??w.action_type,X=w.milestone_title??w.action_title,Y=w.milestone_description??w.action_description??"";return{id:w.id,taskId:w.task_id,sessionId:w.session_id,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:w.process_description??"",timestamp:new Date(w.timestamp).toISOString(),mdPath:w.md_path||void 0,actionType:$,actionTitle:X,actionDescription:Y}}async createTag(w){await this.initialize();let $=Date.now(),X=await this.getTagByName(w);if(X)return X;return{id:this.db.prepare(`
2495
2495
  INSERT INTO task_tag (name, created_at, task_count)
2496
2496
  VALUES (?, ?, 0)
2497
- `).run(w,$).lastInsertRowid,name:w,createdAt:new Date($).toISOString(),taskCount:0}}async getTag(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(w);if(!X)return;return this.rowToTag(X)}async getTagByName(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(w);if(!X)return;return this.rowToTag(X)}async listTags(w){await this.initialize();let $="SELECT * FROM task_tag",X=[],Y=w?.orderBy||"count";if(Y==="count")$+=" ORDER BY task_count DESC";else if(Y==="name")$+=" ORDER BY name ASC";else $+=" ORDER BY created_at DESC";if(w?.limit)$+=" LIMIT ?",X.push(w.limit);if(w?.offset)$+=" OFFSET ?",X.push(w.offset);return this.db.prepare($).all(...X).map((Q)=>this.rowToTag(Q))}async searchTags(w){await this.initialize();let $=`
2497
+ `).run(w,$).lastInsertRowid,name:w,createdAt:new Date($).toISOString(),taskCount:0}}async getTag(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(w);if(!X)return;return this.rowToTag(X)}async getTagByName(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(w);if(!X)return;return this.rowToTag(X)}async listTags(w){await this.initialize();let $="SELECT * FROM task_tag",X=[],Y=w?.orderBy||"count";if(Y==="count")$+=" ORDER BY task_count DESC";else if(Y==="name")$+=" ORDER BY name ASC";else $+=" ORDER BY created_at DESC";if(w?.limit)$+=" LIMIT ?",X.push(w.limit);if(w?.offset)$+=" OFFSET ?",X.push(w.offset);return this.db.prepare($).all(...X).map((W)=>this.rowToTag(W))}async searchTags(w){await this.initialize();let $=`
2498
2498
  SELECT * FROM task_tag
2499
2499
  WHERE name LIKE ?
2500
2500
  ORDER BY task_count DESC
@@ -2515,12 +2515,12 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
2515
2515
  SELECT DISTINCT r.task_id FROM task_tag_relation r
2516
2516
  INNER JOIN task_tag t ON r.tag_id = t.id
2517
2517
  WHERE t.name IN (${w.map(()=>"?").join(", ")})
2518
- `;return this.db.prepare(X).all(...w).map((W)=>W.task_id)}async updateTaskTags(w,$){await this.initialize();let X=await this.getTagsForTask(w);if(X.length>0)await this.removeTagsFromTask(w,X.map((J)=>J.id));let Y=[];for(let J of $){let W=await this.getTagByName(J);if(!W)W=await this.createTag(J);Y.push(W.id)}if(Y.length>0)await this.addTagsToTask(w,Y)}async searchTasksByKeywords(w,$={}){if(await this.initialize(),!w||w.length===0)return{tasks:[],total:0};let{limit:X=20,offset:Y=0,excludeTaskId:J,status:W,priority:Q,type:G,depth:q}=$,H=null;if(q!==void 0&&q>=0)H=await this.collectTaskIdsByDepth(q);let B=new Map,D="SELECT * FROM task WHERE 1=1",O=[];if(J)D+=" AND id != ?",O.push(J);if(W)D+=" AND status = ?",O.push(W);if(Q)D+=" AND priority = ?",O.push(Q);if(G)D+=" AND type = ?",O.push(G);if(!$?.include_archived&&$?.status!=="archived")D+=" AND status != 'archived'";let z=Math.max(X*5,200);D+=" ORDER BY updated_at DESC LIMIT ?",O.push(z);let U=this.db.prepare(D).all(...O);for(let b of U){let F=this.rowToTask(b),T=new Set,j=0;if(typeof F.title==="string"&&F.title){let C=F.title.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(F.tags&&Array.isArray(F.tags))for(let C of w){let y=C.toLowerCase();if(F.tags.some((i)=>i.toLowerCase().includes(y)))j+=2,T.add(C)}if(typeof F.description==="string"&&F.description){let C=F.description.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(typeof F.goals_and_expected_deliverables==="string"&&F.goals_and_expected_deliverables){let C=F.goals_and_expected_deliverables.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(T.size===w.length)B.set(F.id,{task:F,matchCount:j})}let V=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let b of V){let T=new Set;for(let i of w){let v=`%${i}%`;if(this.db.prepare(`
2518
+ `;return this.db.prepare(X).all(...w).map((D)=>D.task_id)}async updateTaskTags(w,$){await this.initialize();let X=await this.getTagsForTask(w);if(X.length>0)await this.removeTagsFromTask(w,X.map((J)=>J.id));let Y=[];for(let J of $){let D=await this.getTagByName(J);if(!D)D=await this.createTag(J);Y.push(D.id)}if(Y.length>0)await this.addTagsToTask(w,Y)}async searchTasksByKeywords(w,$={}){if(await this.initialize(),!w||w.length===0)return{tasks:[],total:0};let{limit:X=20,offset:Y=0,excludeTaskId:J,status:D,priority:W,type:G,depth:Q}=$,q=null;if(Q!==void 0&&Q>=0)q=await this.collectTaskIdsByDepth(Q);let H=new Map,B="SELECT * FROM task WHERE 1=1",O=[];if(J)B+=" AND id != ?",O.push(J);if(D)B+=" AND status = ?",O.push(D);if(W)B+=" AND priority = ?",O.push(W);if(G)B+=" AND type = ?",O.push(G);if(!$?.include_archived&&$?.status!=="archived")B+=" AND status != 'archived'";let z=Math.max(X*5,200);B+=" ORDER BY updated_at DESC LIMIT ?",O.push(z);let U=this.db.prepare(B).all(...O);for(let E of U){let f=this.rowToTask(E),Z=new Set,L=0;if(typeof f.title==="string"&&f.title){let C=f.title.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))L++,Z.add(y)}if(f.tags&&Array.isArray(f.tags))for(let C of w){let y=C.toLowerCase();if(f.tags.some((i)=>i.toLowerCase().includes(y)))L+=2,Z.add(C)}if(typeof f.description==="string"&&f.description){let C=f.description.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))L++,Z.add(y)}if(typeof f.goals_and_expected_deliverables==="string"&&f.goals_and_expected_deliverables){let C=f.goals_and_expected_deliverables.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))L++,Z.add(y)}if(Z.size===w.length)H.set(f.id,{task:f,matchCount:L})}let V=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let E of V){let Z=new Set;for(let i of w){let v=`%${i}%`;if(this.db.prepare(`
2519
2519
  SELECT * FROM task_operation
2520
2520
  WHERE task_id = ?
2521
2521
  AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
2522
2522
  LIMIT 10
2523
- `).all(b.task_id,v,v,v).length>0)T.add(i)}if(T.size===0)continue;let j=this.db.prepare("SELECT * FROM task WHERE id = ?").get(b.task_id);if(!j)continue;let C=this.rowToTask(j);if(J&&C.id===J)continue;if(W&&C.status!==W)continue;if(Q&&C.priority!==Q)continue;if(G&&C.type!==G)continue;if(!$?.include_archived&&C.status==="archived")continue;let y=B.get(C.id);if(y)y.matchCount+=2;else{let i=new Set(T);if(typeof C.title==="string"&&C.title){let v=C.title.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.description==="string"&&C.description){let v=C.description.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.goals_and_expected_deliverables==="string"&&C.goals_and_expected_deliverables){let v=C.goals_and_expected_deliverables.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(C.tags&&Array.isArray(C.tags)){for(let v of w)if(C.tags.some((c)=>c.toLowerCase().includes(v.toLowerCase())))i.add(v)}if(i.size===w.length)B.set(C.id,{task:C,matchCount:2})}}let M=Array.from(B.values()).sort((b,F)=>F.matchCount-b.matchCount);if(H!==null)M=M.filter((b)=>H.has(b.task.id));let f=M.length;return{tasks:M.slice(Y,Y+X).map((b)=>b.task),total:f}}async collectTaskIdsByDepth(w){let $=new Set,Y=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((J)=>J.id);for(let J of Y)$.add(J);if(w===0)return $;for(let J=1;J<=w;J++){if(Y.length===0)break;let W=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${W})`).all(...Y).map((G)=>G.id);for(let G of Y)$.add(G)}return $}async findSimilarTasksByKeywords(w,$={}){let X={...$,limit:$.limit??5};return(await this.searchTasksByKeywords(w,X)).tasks}async findSimilarTasks(w,$=5){await this.initialize();let X=await this.getTagsForTask(w);if(X.length===0)return[];let Y=X.map((q)=>q.id),W=`
2523
+ `).all(E.task_id,v,v,v).length>0)Z.add(i)}if(Z.size===0)continue;let L=this.db.prepare("SELECT * FROM task WHERE id = ?").get(E.task_id);if(!L)continue;let C=this.rowToTask(L);if(J&&C.id===J)continue;if(D&&C.status!==D)continue;if(W&&C.priority!==W)continue;if(G&&C.type!==G)continue;if(!$?.include_archived&&C.status==="archived")continue;let y=H.get(C.id);if(y)y.matchCount+=2;else{let i=new Set(Z);if(typeof C.title==="string"&&C.title){let v=C.title.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.description==="string"&&C.description){let v=C.description.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.goals_and_expected_deliverables==="string"&&C.goals_and_expected_deliverables){let v=C.goals_and_expected_deliverables.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(C.tags&&Array.isArray(C.tags)){for(let v of w)if(C.tags.some((c)=>c.toLowerCase().includes(v.toLowerCase())))i.add(v)}if(i.size===w.length)H.set(C.id,{task:C,matchCount:2})}}let M=Array.from(H.values()).sort((E,f)=>f.matchCount-E.matchCount);if(q!==null)M=M.filter((E)=>q.has(E.task.id));let R=M.length;return{tasks:M.slice(Y,Y+X).map((E)=>E.task),total:R}}async collectTaskIdsByDepth(w){let $=new Set,Y=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((J)=>J.id);for(let J of Y)$.add(J);if(w===0)return $;for(let J=1;J<=w;J++){if(Y.length===0)break;let D=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${D})`).all(...Y).map((G)=>G.id);for(let G of Y)$.add(G)}return $}async findSimilarTasksByKeywords(w,$={}){let X={...$,limit:$.limit??5};return(await this.searchTasksByKeywords(w,X)).tasks}async findSimilarTasks(w,$=5){await this.initialize();let X=await this.getTagsForTask(w);if(X.length===0)return[];let Y=X.map((Q)=>Q.id),D=`
2524
2524
  SELECT t.*, COUNT(r2.tag_id) as match_count
2525
2525
  FROM task t
2526
2526
  INNER JOIN task_tag_relation r ON t.id = r.task_id
@@ -2530,21 +2530,21 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
2530
2530
  GROUP BY t.id
2531
2531
  ORDER BY match_count DESC, t.updated_at DESC
2532
2532
  LIMIT ?
2533
- `;return this.db.prepare(W).all(...Y,w,$).map((q)=>this.rowToTask(q))}async searchTasks(w,$=20){await this.initialize();let X=`
2533
+ `;return this.db.prepare(D).all(...Y,w,$).map((Q)=>this.rowToTask(Q))}async searchTasks(w,$=20){await this.initialize();let X=`
2534
2534
  SELECT * FROM task
2535
2535
  WHERE title LIKE ? OR description LIKE ?
2536
2536
  ORDER BY updated_at DESC
2537
2537
  LIMIT ?
2538
- `;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((W)=>this.rowToTask(W))}async findTasksByContextValue(w,$=50){if(await this.initialize(),!w)return[];let X=`
2538
+ `;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((D)=>this.rowToTask(D))}async findTasksByContextValue(w,$=50){if(await this.initialize(),!w)return[];let X=`
2539
2539
  SELECT * FROM task
2540
2540
  WHERE context LIKE ?
2541
2541
  ORDER BY updated_at DESC
2542
2542
  LIMIT ?
2543
- `;return this.db.prepare(X).all(`%${w}%`,$).map((J)=>this.rowToTask(J))}rowToTag(w){return{id:w.id,name:w.name,createdAt:new Date(w.created_at).toISOString(),taskCount:w.task_count}}async syncTaskTagsJson(w){let X=(await this.getTagsForTask(w)).map((J)=>J.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,w),this.tasksCache.delete(w)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Lw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Lw.prototype,"searchTasksByKeywords",null)});function fX(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let Y=$.replace(/-/g,"_").toUpperCase(),J=_.slice(X.length);if(J.startsWith("_"))J=J.slice(1);if(!J)return;let W=J.indexOf("_"),Q;if(W===-1)Q=J;else{let q=J.slice(0,W),H=J.slice(W+1);if(q===Y)Q=H;else Q=J}if(!Q)return;let G=Q.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function LX(_,w){return{..._,execute:w}}var $z=()=>{},FX=r(()=>{$z(),Q4(),_0()});FX();class F4{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new Y1}getStatus(){return this._status}getConfig(){return{name:this.name,version:this.version,enabled:this._enabled,env:this.env}}isEnvInitialized(){return this._status!=="created"}setStatus(_){this._status=_}getEnv(){return this.env}async init(_){if(_?.env)this.env=_.env;this.setStatus("initializing");try{if(_?.name)Object.defineProperty(this,"name",{value:_.name,writable:!1});if(_?.version)Object.defineProperty(this,"version",{value:_.version,writable:!1})}catch{}if(_?.enabled!==void 0)this._enabled=_.enabled;this.hookManager.setComponentInfo(this.name,this.version),await this.onInit(),this.setStatus("running")}async start(){if(this._started)return;this._started=!0,await this.onStart(),this.setStatus("running")}async stop(){this.setStatus("stopping"),this.hookManager.clear(),await this.onStop(),this.setStatus("stopped")}async onInit(){}async onStart(){}async onStop(){}registerHook(_,w){this.hookManager.register(_,w)}addHook(_,w,$,X){this.hookManager.register(_,LX({name:w,priority:X},$))}removeHook(_,w){return this.hookManager.unregister(_,w)}async executeHooks(_,w,$){await this.hookManager.execute(_,w,$)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig(_,w){let $=this.getConfigComponent();if($){let X=$.get(_);if(X!==void 0)return X}return w}}a();var Xz={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Yz={name:"task",sources:[{type:"env",envPrefix:"TASK",priority:20,watch:!1}],keys:[{key:"task.storage.type",sources:["env","file"]},{key:"task.storage.dbPath",sources:["env","file"]}]};_0();var Jz=["completed","failed","cancelled","timeout"];Jw();a();var a0=n("task:tag");class KX{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return a0.debug(`[TagService] Created tag: ${w.name} (id=${w.id})`),w}async getTag(_){return this.store.getTag(_)}async getTagByName(_){return this.store.getTagByName(_)}async listTags(_){return this.store.listTags(_)}async searchTags(_){return this.store.searchTags(_)}async deleteTag(_){let w=await this.store.deleteTag(_);if(w)a0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),a0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),a0.debug(`[TagService] Removed ${w.length} tags from task ${_}`)}async getTagsForTask(_){return this.store.getTagsForTask(_)}async getTaskIdsByTags(_){return this.store.getTaskIdsByTags(_)}async findSimilarTasks(_,w=5){return this.store.findSimilarTasks(_,w)}async searchTasks(_,w=20){return this.store.searchTasks(_,w)}async searchTasksByKeywords(_,w){return(await this.store.searchTasksByKeywords(_,w)).tasks}async findSimilarTasksByKeywords(_,w){return this.store.findSimilarTasksByKeywords(_,w)}async syncTagsToTask(_,w){let $=[];for(let G of w){let q=await this.store.getTagByName(G);if(!q)q=await this.store.createTag(G);$.push(q.id)}let X=await this.store.getTagsForTask(_),Y=new Set(X.map((G)=>G.id)),J=new Set($),W=$.filter((G)=>!Y.has(G)),Q=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(Q.length>0)await this.store.removeTagsFromTask(_,Q);if(W.length>0)await this.store.addTagsToTask(_,W);await this.store.updateTaskTags(_,w),a0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}V_();var J_=n("task"),Wz="Deliverable: ";function Qz(_){if(!_)return;return`${Wz}${_}`}class Fw extends F4{name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent(_,w,$){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.component",trigger_session_id:$}}),J_.info(`[TaskComponent] Event published: ${_}`)}constructor(){super()}async init(_){await super.init(_);let w=_?.options;if(!w?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=w.configComponent,await this.registerConfig(w),this.setStatus("running"),J_.info("[TaskComponent] Initialized")}async registerConfig(_){let w=this.configComponent;if(!w)return;let{configPath:$,envPrefix:X,config:Y}=_,J=X??"TASK";if(w.registerComponent(Yz),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:J,priority:20,watch:!1}),await w.load("task");for(let W of Object.keys(process.env)){let Q=fX(W,J,"task");if(!Q)continue;let G=process.env[W];if(G!==void 0)await w.set(Q,G)}for(let[W,Q]of Object.entries(Xz))if(w.get(W)===void 0)await w.set(W,Q);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",H1());if(Y){let W=this.flattenConfig(Y);for(let[Q,G]of Object.entries(W))await w.set(Q,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new KX(this.store)}async initStore(){let _=this.configComponent;if(!_)return;let w=_.get("task.storage.type")??"sqlite",$=_.get("task.storage.dbPath");if(w==="sqlite")this.store=new Lw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Lw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,Y]of Object.entries(_)){let J=`${w}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign($,this.flattenConfig(Y,J));else $[J]=Y}return $}registerConfigWatcher(_){if(typeof _.watch!=="function")return;this.configWatcher=_.watch("task.*",(w)=>{this.onConfigChange(w)})}onConfigChange(_){if(J_.info(`[TaskComponent] Config changed: ${_.key}`,{oldValue:_.oldValue,newValue:_.newValue}),_.key==="task.storage.type"||_.key==="task.storage.dbPath")this.initStore()}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new __(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(G2(this.backgroundTaskManager),"built-in"),J_.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else J_.warn("[TaskComponent] ToolComponent not found, skipping tool registration")}async stop(){if(this.configWatcher)this.configWatcher(),this.configWatcher=void 0;if(this.toolComponent)try{this.toolComponent.register(G2(null),"built-in"),J_.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch(_){J_.warn(`[TaskComponent] Failed to reset query_background_process tool: ${_.message}`)}if(this.backgroundTaskManager)this.backgroundTaskManager.dispose(),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let _=[x0(this),m0(this),u0(this),p0(this),l0(this),z4(this),V4(this),c0(this),O4(this),d0(this)],w=[i0(this),R4(this),n0(this),f4(this),L4(this)],$=[l5(this),c5(this.backgroundTaskManager)];for(let X of[..._,...w,...$])this.toolComponent.register(X),J_.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook(_,w,$={}){let X={component:{name:this.name,version:this.version},data:w,metadata:$,phase:_.includes("before")?"before":"after",hookPoint:_};await E_.execute(_,w,$)}async createTask(_){let w=_.sessionId;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){if(!await this.store.getTask(_.parent_task_id))throw Error(`Parent task #${_.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let $={options:{..._},sessionId:w,tagService:this.tagService};await this.executeHook($_.BEFORE_CREATE,$);let X=await this.store.createTask($.options);await this.store.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook($_.AFTER_CREATE,Y),this.publishEvent(Rw.CREATED,{task:X,sessionId:w},w),J_.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask(_){return this.store.getTask(_)}async getTaskIdBySessionId(_){return this.store.getTaskIdBySessionId(_)}async getTaskWithOperations(_){let w=await this.store.getTask(_);if(!w)return;let $=await this.store.listOperations({taskId:_});return{...w,operations:$}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook($_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let Y={task:X,changes:w,tagService:this.tagService};if(await this.executeHook($_.AFTER_UPDATE,Y),this.publishEvent(Rw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Jz.includes(w.status)){let J=$1(),W={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,W),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook($_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook($_.AFTER_DELETE,X),$)this.publishEvent(Rw.DELETED,{taskId:_,sessionId:""},""),J_.info(`[TaskComponent] Task deleted: ${_}`);return $}async listTasks(_){return this.store.listTasks(_)}async searchTasksByKeywords(_,w){return this.store.searchTasksByKeywords(_,w||{})}async getTaskTree(_,w=-1){return this.store.getTaskTree(_,w)}async getChildTasks(_,w){return this.store.getChildTasks(_,w)}async completeTask(_,w,$){let X=await this.store.getTask(_);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${_} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($){let W={};if(X?.context)try{let Q=JSON.parse(X.context);if(Q&&typeof Q==="object"&&!Array.isArray(Q))W=Q}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}W.deliverable_storage_path=$,Y.context=JSON.stringify(W)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Qz($)}),this.publishEvent(Rw.COMPLETED,{task:J,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return J}async createOperation(_){let w={options:{..._}};await this.executeHook($_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),Y={operation:$};return await this.executeHook($_.OPERATION_AFTER_CREATE,Y,{task:X,operation:$}),this.publishEvent(Rw.OPERATION_ADDED,{operation:$,taskId:$.taskId},$.sessionId),J_.info(`[TaskComponent] Operation created: ${$.id} for task ${$.taskId}`),$}async getOperation(_){return this.store.getOperation(_)}async updateOperation(_,w){return this.store.updateOperation(_,w)}async deleteOperation(_){return this.store.deleteOperation(_)}async listOperations(_){return this.store.listOperations(_)}getTagService(){return this.tagService}registerHook(_,w){E_.register(_,w),this.plugins.set(this.makePluginKey(_,w.name),w),J_.debug(`[TaskComponent] Registered hook: ${w.name} at ${_}`)}registerHooks(_){for(let{hookPoint:w,hook:$}of _)this.registerHook(w,$)}unregisterHook(_,w){let $=E_.unregister(_,w);if($)this.plugins.delete(this.makePluginKey(_,w)),J_.info(`[TaskComponent] Unregistered hook: ${w} from ${_}`);return $}listHooks(){return Array.from(this.plugins.values())}makePluginKey(_,w){return`${_}::${w}`}countHooks(_){return E_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],Fw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"createOperation",null);var K4=A.enum(["todo","active","completed","paused","cancelled","archived"]),N4=A.enum(["low","medium","high"]),b4=A.enum(["normal","cycle","longterm"]),j4=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Gz=A.object({storage:A.object({type:A.enum(["memory","sqlite"]).default("sqlite"),dbPath:A.string().optional()}).default({})}).default({});Ww();Ww();var qz="Deliverable: ";function Hz(_){if(!_)return;return`${qz}${_}`}var D1=1e6;class E4{port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=Dz(_);if(w!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(w);return(await this.scanAllTasks()).find(($)=>$.id===w)??null}return await this.port.getTask(String(_))}toTask(_){let{nativeId:w,...$}=_;return $}toOperation(_){let{nativeId:w,...$}=_;return $}async scanAllTasks(){return(await this.port.listTasks({limit:D1,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let Y=await this.resolve(_.parent_task_id);if(!Y)throw Error(`Parent task #${_.parent_task_id} not found.`);$=Y.id}let X=await this.port.createTask({title:_.title,description:_.description,priority:_.priority,type:_.type,goals_and_expected_deliverables:_.goals_and_expected_deliverables,...$!==void 0?{parent_task_id:$}:{},due_date:_.due_date,tags:_.tags,project_path:_.project_path,context:_.context,sessionId:w});return await this.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask(_){let w=await this.resolve(_);return w?this.toTask(w):null}async getTaskWithOperations(_){let w=await this.getTask(_);if(!w)return null;let $=await this.listOperations({taskId:w.id,limit:D1,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,_),{tasks:X.slice($,$+w),total:X.length}}async updateTask(_,w){let $=await this.resolve(_);if(!$)return null;let X;if(w.parent_task_id!==void 0)if(w.parent_task_id===null)X=null;else{let J=await this.resolve(w.parent_task_id);if(!J)throw Error(`Parent task #${w.parent_task_id} not found.`);X=J.id}let Y=await this.port.updateTask($.nativeId,{title:w.title,description:w.description,status:w.status,priority:w.priority,type:w.type,progress:w.progress,current_status:w.current_status,goals_and_expected_deliverables:w.goals_and_expected_deliverables,due_date:w.due_date,tags:w.tags,project_path:w.project_path,context:w.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask(_){let w=await this.resolve(_);if(!w)return!1;return await this.port.deleteTask(w.nativeId)}async completeTask(_,w,$){let X=await this.resolve(_);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($)Y.context=Uz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let W=Hz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:W??"Task completed",...$?{mdPath:$}:{}});let Q=await this.resolve(X.nativeId);return this.toTask(Q??J)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((q)=>this.toTask(q)),Y=new Map;for(let q of X){if(q.parent_task_id===void 0)continue;let H=Y.get(q.parent_task_id)??[];H.push(q),Y.set(q.parent_task_id,H)}let J=[],W=new Set([$.id]),Q=[$.id],G=0;while(Q.length>0){if(w!==-1&&G>=w)break;let q=[];for(let H of Q)for(let B of Y.get(H)??[]){if(W.has(B.id))continue;W.add(B.id),J.push(B),q.push(B.id)}Q=q,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((Q)=>this.toTask(Q));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((Q)=>Q.id!==w.excludeTaskId);let J=_.map((Q)=>Q.toLowerCase()).filter((Q)=>Q.length>0),W=J.length===0?Y:Y.filter((Q)=>{let G=[Q.title,Q.description,Q.goals_and_expected_deliverables,Q.current_status,(Q.tags??[]).join(" "),Q.project_path].join(" ").toLowerCase();return J.every((q)=>G.includes(q))});return{tasks:W.slice(X,X+$),total:W.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",Y=_.milestoneDescription??_.actionDescription??"",J=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(J)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let Y=await this.resolve(_.taskId);if(!Y)return[];let W=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?D1:w,offset:X?0:$})).operations.map((Q)=>this.toOperation(Q));if(X)W=W.filter((Q)=>Q.milestoneType===X),W=W.slice($,$+w);return W}async getOperation(_){if(typeof this.port.getOperationByNum==="function"){let $=await this.port.getOperationByNum(_);return $?this.toOperation($):null}let w=await this.scanAllTasks();for(let $ of w){let Y=(await this.port.listOperations({taskNativeId:$.nativeId,limit:D1})).operations.find((J)=>J.id===_);if(Y)return this.toOperation(Y)}return null}async updateOperation(_,w){let $=await this.getOperation(_);if(!$)return null;if(typeof this.port.updateOperationByNum!=="function")return $;let X=await this.port.updateOperationByNum(_,{sessionId:w.sessionId??$.sessionId,milestoneType:w.milestoneType??w.actionType??$.milestoneType,milestoneTitle:w.milestoneTitle??w.actionTitle??$.milestoneTitle,milestoneDescription:w.milestoneDescription??w.actionDescription??$.milestoneDescription,processDescription:w.processDescription??$.processDescription,...w.mdPath!==void 0?{mdPath:w.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation(_){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum(_)}applyFilters(_,w){let $=_;if(w.include_archived!==!0&&w.status!=="archived")$=$.filter((Y)=>Y.status!=="archived");if(w.status!==void 0)$=$.filter((Y)=>Y.status===w.status);if(w.priority!==void 0)$=$.filter((Y)=>Y.priority===w.priority);if(w.type!==void 0)$=$.filter((Y)=>Y.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((Y)=>Y.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let Y=Bz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function Dz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function Bz(_,w){if(w<0)return new Set(_.map((W)=>W.id));let $=new Set(_.map((W)=>W.id)),X=new Map;for(let W of _){let Q=W.parent_task_id;if(Q===void 0||!$.has(Q))continue;let G=X.get(Q)??[];G.push(W),X.set(Q,G)}let Y=new Set,J=_.filter((W)=>W.parent_task_id===void 0||!$.has(W.parent_task_id));for(let W of J)Y.add(W.id);for(let W=1;W<=w;W++){let Q=[];for(let G of J)for(let q of X.get(G.id)??[]){if(Y.has(q.id))continue;Y.add(q.id),Q.push(q)}if(Q.length===0)break;J=Q}return Y}function Uz(_,w){let $={};if(typeof _==="string"&&_.trim().length>0)try{let X=JSON.parse(_);if(X&&typeof X==="object"&&!Array.isArray(X))$=X}catch{}return $.deliverable_storage_path=w,JSON.stringify($)}var zz=1e6;function Vz(_){let w={};if(_.type!==void 0)w.type=_.type;if(_.progress!==void 0)w.progress=_.progress;if(_.current_status!==void 0)w.current_status=_.current_status;if(_.goals_and_expected_deliverables!==void 0)w.goals_and_expected_deliverables=_.goals_and_expected_deliverables;if(_.project_path!==void 0)w.project_path=_.project_path;if(_.context!==void 0)w.context=_.context;if(_.due_date!==void 0)w.due_date=_.due_date;return w}function o0(_,w,$){if(typeof _.num!=="number")throw Error(`store did not expose a numeric handle for task ${_.id}`);let X=_.roy??{};return{id:_.num,nativeId:_.id,title:_.title,description:_.description??"",status:w.toRoyStatus(_.status),priority:w.toRoyPriority(_.priority),type:X.type??"normal",progress:typeof X.progress==="number"?X.progress:_.status==="done"?100:0,current_status:X.current_status??"",goals_and_expected_deliverables:X.goals_and_expected_deliverables??"",...$!==void 0?{parent_task_id:$}:{},createdAt:_.created_at,updatedAt:_.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:w.toRoyTags(_.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function s0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),Y=String(w.milestoneDescription??w.actionDescription??""),J=w.taskId??_.task_id,W=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:W,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:Y}}function NX(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??zz;async function W(){let q=await _.listTasks({limit:J});return new Map(q.tasks.filter((H)=>typeof H.num==="number").map((H)=>[H.id,H.num]))}async function Q(q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(q);return(await _.listTasks({limit:J})).tasks.find((B)=>B.num===q)??null}async function G(q){let B=[...(await W()).entries()].find(([,D])=>D===q);if(!B)throw Error(`parent task not found: ${q}`);return B[0]}return{async createTask(q){let H=q.parent_task_id!==void 0?await G(q.parent_task_id):null,B={type:q.type??"normal",progress:q.progress??0,current_status:q.current_status??"",goals_and_expected_deliverables:q.goals_and_expected_deliverables??"",project_path:q.project_path,context:q.context,...q.due_date?{due_date:q.due_date}:{}},D=await _.createTask({title:q.title,description:q.description,priority:w.toStorePriority(q.priority),owner:Y,tags:w.toStoreTags(q.tags),parent_id:H,session_id:q.sessionId??"unknown",roy:B});return o0(D,w,q.parent_task_id)},async getTask(q){let H=await _.getTask(q);if(!H)return null;let B=await W();return o0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async getTaskByNum(q){let H=await Q(q);if(!H)return null;let B=await W();return o0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async listTasks(q){let H=await _.listTasks({limit:q?.limit??20,offset:q?.offset??0}),B=await W();return{tasks:H.tasks.map((D)=>o0(D,w,D.parent_id?B.get(D.parent_id):void 0)),total:H.total}},async updateTask(q,H){let B=Vz(H),D=await _.updateTask(q,{...H.title!==void 0?{title:H.title}:{},...H.description!==void 0?{description:H.description}:{},...H.status!==void 0?{status:w.toStoreStatus(H.status)}:{},...H.priority!==void 0?{priority:w.toStorePriority(H.priority)}:{},...H.tags!==void 0?{tags:w.toStoreTags(H.tags)}:{},...Object.keys(B).length>0?{roy:B}:{}});if(!D)return null;let O;if(H.parent_task_id!==void 0){let U=H.parent_task_id===null?null:await G(H.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(q,U);O=H.parent_task_id===null?void 0:H.parent_task_id}let z=await _.getTask(q)??D;if(O===void 0&&z.parent_id)O=(await W()).get(z.parent_id);return o0(z,w,O)},async deleteTask(q){return await _.deleteTask(q)},async createOperation(q){let H=await _.appendOperation({task_id:q.taskNativeId??String(q.taskId),type:X,data:{taskId:q.taskId,sessionId:q.sessionId,milestoneType:q.milestoneType,milestoneTitle:q.milestoneTitle,milestoneDescription:q.milestoneDescription,processDescription:q.processDescription,...q.mdPath?{mdPath:q.mdPath}:{}}});return s0(H)},async listOperations(q){let H=await _.listOperations({...q?.taskNativeId?{task_id:q.taskNativeId}:{},type:X,limit:q?.limit??J,offset:q?.offset??0});return{operations:H.operations.map(s0),total:H.total}},async getOperationByNum(q){if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(q);return H?s0(H):null},async updateOperationByNum(q,H){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let B=await _.getOperationByNum(q);if(!B)return null;let D=s0(B),O=await _.updateOperation(q,{data:{taskId:D.taskId,sessionId:H.sessionId??D.sessionId,milestoneType:H.milestoneType??D.milestoneType,milestoneTitle:H.milestoneTitle??D.milestoneTitle,milestoneDescription:H.milestoneDescription??D.milestoneDescription,processDescription:H.processDescription??D.processDescription,...H.mdPath??D.mdPath?{mdPath:H.mdPath??D.mdPath}:{}}});return O?s0(O):null},async deleteOperationByNum(q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(q)}}}var Oz="roy.milestone",Az={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Mz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function bX(_){return Az[_]??"pending"}function jX(_){return Mz[_]??"todo"}function EX(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function SX(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function PX(_){if(!_||_.length===0)return;return _.join(",")}function ZX(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var Rz={toRoyStatus:(_)=>jX(_),toStoreStatus:(_)=>bX(_),toRoyPriority:(_)=>SX(_),toStorePriority:(_)=>EX(_),toRoyTags:(_)=>ZX(_),toStoreTags:(_)=>PX(_)};function CX(_,w={}){return new E4(NX(_,Rz,{operationType:Oz,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var MR=K4.options,RR=N4.options,fR=b4.options,LR=j4.options;var IX=Symbol("Let zodToJsonSchema decide on which parser to use");var TX={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},kX=(_)=>typeof _==="string"?{...TX,name:_}:{...TX,..._};var gX=(_)=>{let w=kX(_),$=w.name!==void 0?[...w.basePath,w.definitionPath,w.name]:w.basePath;return{...w,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(w.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...w.basePath,w.definitionPath,X],jsonSchema:void 0}]))}};function S4(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,S4(_,w,X,Y)}var B1=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function s(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?B1(w,_.currentPath):w.join("/")}}function hX(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==K.ZodAny)$.items=k(_.type._def,{...w,currentPath:[...w.currentPath,"items"]});if(_.minLength)d($,"minItems",_.minLength.value,_.minLength.message,w);if(_.maxLength)d($,"maxItems",_.maxLength.value,_.maxLength.message,w);if(_.exactLength)d($,"minItems",_.exactLength.value,_.exactLength.message,w),d($,"maxItems",_.exactLength.value,_.exactLength.message,w);return $}function yX(_,w){let $={type:"integer",format:"int64"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function vX(){return{type:"boolean"}}function U1(_,w){return k(_.type._def,w)}var xX=(_,w)=>{return k(_.innerType._def,w)};function P4(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>P4(_,w,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return fz(_,w)}}var fz=(_,w)=>{let $={type:"integer",format:"unix-time"};if(w.target==="openApi3")return $;for(let X of _.checks)switch(X.kind){case"min":d($,"minimum",X.value,X.message,w);break;case"max":d($,"maximum",X.value,X.message,w);break}return $};function mX(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function uX(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function lX(_){return{type:"string",enum:Array.from(_.values)}}var Lz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function cX(_,w){let $=[k(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),k(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((J)=>!!J),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((J)=>{if(Lz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let W=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:Q,...G}=J;W=G}else X=void 0;Y.push(W)}}),Y.length?{allOf:Y,...X}:void 0}function dX(_,w){let $=typeof _.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(_.value)?"array":"object"};if(w.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[_.value]};return{type:$==="bigint"?"integer":$,const:_.value}}var Z4=void 0,S_={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Z4===void 0)Z4=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z4},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function z1(_,w){let $={type:"string"};if(_.checks)for(let X of _.checks)switch(X.kind){case"min":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w);break;case"max":d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"email":switch(w.emailStrategy){case"format:email":P_($,"email",X.message,w);break;case"format:idn-email":P_($,"idn-email",X.message,w);break;case"pattern:zod":q_($,S_.email,X.message,w);break}break;case"url":P_($,"uri",X.message,w);break;case"uuid":P_($,"uuid",X.message,w);break;case"regex":q_($,X.regex,X.message,w);break;case"cuid":q_($,S_.cuid,X.message,w);break;case"cuid2":q_($,S_.cuid2,X.message,w);break;case"startsWith":q_($,RegExp(`^${C4(X.value,w)}`),X.message,w);break;case"endsWith":q_($,RegExp(`${C4(X.value,w)}$`),X.message,w);break;case"datetime":P_($,"date-time",X.message,w);break;case"date":P_($,"date",X.message,w);break;case"time":P_($,"time",X.message,w);break;case"duration":P_($,"duration",X.message,w);break;case"length":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w),d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"includes":{q_($,RegExp(C4(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")P_($,"ipv4",X.message,w);if(X.version!=="v4")P_($,"ipv6",X.message,w);break}case"base64url":q_($,S_.base64url,X.message,w);break;case"jwt":q_($,S_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")q_($,S_.ipv4Cidr,X.message,w);if(X.version!=="v4")q_($,S_.ipv6Cidr,X.message,w);break}case"emoji":q_($,S_.emoji(),X.message,w);break;case"ulid":{q_($,S_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{P_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{q_($,S_.base64,X.message,w);break}}break}case"nanoid":q_($,S_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return $}function C4(_,w){return w.patternStrategy==="escape"?Kz(_):_}var Fz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kz(_){let w="";for(let $=0;$<_.length;$++){if(!Fz.has(_[$]))w+="\\";w+=_[$]}return w}function P_(_,w,$,X){if(_.format||_.anyOf?.some((Y)=>Y.format)){if(!_.anyOf)_.anyOf=[];if(_.format){if(_.anyOf.push({format:_.format,..._.errorMessage&&X.errorMessages&&{errorMessage:{format:_.errorMessage.format}}}),delete _.format,_.errorMessage){if(delete _.errorMessage.format,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.anyOf.push({format:w,...$&&X.errorMessages&&{errorMessage:{format:$}}})}else d(_,"format",w,$,X)}function q_(_,w,$,X){if(_.pattern||_.allOf?.some((Y)=>Y.pattern)){if(!_.allOf)_.allOf=[];if(_.pattern){if(_.allOf.push({pattern:_.pattern,..._.errorMessage&&X.errorMessages&&{errorMessage:{pattern:_.errorMessage.pattern}}}),delete _.pattern,_.errorMessage){if(delete _.errorMessage.pattern,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.allOf.push({pattern:pX(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",pX(w,X),$,X)}function pX(_,w){if(!w.applyRegexFlags||!_.flags)return _.source;let $={i:_.flags.includes("i"),m:_.flags.includes("m"),s:_.flags.includes("s")},X=$.i?_.source.toLowerCase():_.source,Y="",J=!1,W=!1,Q=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(W){if(X[G].match(/[a-z]/)){if(Q)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),Q=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],Q=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
2543
+ `;return this.db.prepare(X).all(`%${w}%`,$).map((J)=>this.rowToTask(J))}rowToTag(w){return{id:w.id,name:w.name,createdAt:new Date(w.created_at).toISOString(),taskCount:w.task_count}}async syncTaskTagsJson(w){let X=(await this.getTagsForTask(w)).map((J)=>J.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,w),this.tasksCache.delete(w)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"searchTasksByKeywords",null)});function L6(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let Y=$.replace(/-/g,"_").toUpperCase(),J=_.slice(X.length);if(J.startsWith("_"))J=J.slice(1);if(!J)return;let D=J.indexOf("_"),W;if(D===-1)W=J;else{let Q=J.slice(0,D),q=J.slice(D+1);if(Q===Y)W=q;else W=J}if(!W)return;let G=W.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function F6(_,w){return{..._,execute:w}}var Xz=()=>{},K6=r(()=>{Xz(),W$(),_0()});K6();class F${_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new Y2}getStatus(){return this._status}getConfig(){return{name:this.name,version:this.version,enabled:this._enabled,env:this.env}}isEnvInitialized(){return this._status!=="created"}setStatus(_){this._status=_}getEnv(){return this.env}async init(_){if(_?.env)this.env=_.env;this.setStatus("initializing");try{if(_?.name)Object.defineProperty(this,"name",{value:_.name,writable:!1});if(_?.version)Object.defineProperty(this,"version",{value:_.version,writable:!1})}catch{}if(_?.enabled!==void 0)this._enabled=_.enabled;this.hookManager.setComponentInfo(this.name,this.version),await this.onInit(),this.setStatus("running")}async start(){if(this._started)return;this._started=!0,await this.onStart(),this.setStatus("running")}async stop(){this.setStatus("stopping"),this.hookManager.clear(),await this.onStop(),this.setStatus("stopped")}async onInit(){}async onStart(){}async onStop(){}registerHook(_,w){this.hookManager.register(_,w)}addHook(_,w,$,X){this.hookManager.register(_,F6({name:w,priority:X},$))}removeHook(_,w){return this.hookManager.unregister(_,w)}async executeHooks(_,w,$){await this.hookManager.execute(_,w,$)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig(_,w){let $=this.getConfigComponent();if($){let X=$.get(_);if(X!==void 0)return X}return w}}a();var Yz={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Jz={name:"task",sources:[{type:"env",envPrefix:"TASK",priority:20,watch:!1}],keys:[{key:"task.storage.type",sources:["env","file"]},{key:"task.storage.dbPath",sources:["env","file"]}]};_0();var Dz=["completed","failed","cancelled","timeout"];Dw();a();var a0=n("task:tag");class N6{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return a0.debug(`[TagService] Created tag: ${w.name} (id=${w.id})`),w}async getTag(_){return this.store.getTag(_)}async getTagByName(_){return this.store.getTagByName(_)}async listTags(_){return this.store.listTags(_)}async searchTags(_){return this.store.searchTags(_)}async deleteTag(_){let w=await this.store.deleteTag(_);if(w)a0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),a0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),a0.debug(`[TagService] Removed ${w.length} tags from task ${_}`)}async getTagsForTask(_){return this.store.getTagsForTask(_)}async getTaskIdsByTags(_){return this.store.getTaskIdsByTags(_)}async findSimilarTasks(_,w=5){return this.store.findSimilarTasks(_,w)}async searchTasks(_,w=20){return this.store.searchTasks(_,w)}async searchTasksByKeywords(_,w){return(await this.store.searchTasksByKeywords(_,w)).tasks}async findSimilarTasksByKeywords(_,w){return this.store.findSimilarTasksByKeywords(_,w)}async syncTagsToTask(_,w){let $=[];for(let G of w){let Q=await this.store.getTagByName(G);if(!Q)Q=await this.store.createTag(G);$.push(Q.id)}let X=await this.store.getTagsForTask(_),Y=new Set(X.map((G)=>G.id)),J=new Set($),D=$.filter((G)=>!Y.has(G)),W=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(W.length>0)await this.store.removeTagsFromTask(_,W);if(D.length>0)await this.store.addTagsToTask(_,D);await this.store.updateTaskTags(_,w),a0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}V_();var J_=n("task"),Wz="Deliverable: ";function Gz(_){if(!_)return;return`${Wz}${_}`}class Kw extends F${name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent(_,w,$){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.component",trigger_session_id:$}}),J_.info(`[TaskComponent] Event published: ${_}`)}constructor(){super()}async init(_){await super.init(_);let w=_?.options;if(!w?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=w.configComponent,await this.registerConfig(w),this.setStatus("running"),J_.info("[TaskComponent] Initialized")}async registerConfig(_){let w=this.configComponent;if(!w)return;let{configPath:$,envPrefix:X,config:Y}=_,J=X??"TASK";if(w.registerComponent(Jz),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:J,priority:20,watch:!1}),await w.load("task");for(let D of Object.keys(process.env)){let W=L6(D,J,"task");if(!W)continue;let G=process.env[D];if(G!==void 0)await w.set(W,G)}for(let[D,W]of Object.entries(Yz))if(w.get(D)===void 0)await w.set(D,W);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",q2());if(Y){let D=this.flattenConfig(Y);for(let[W,G]of Object.entries(D))await w.set(W,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new N6(this.store)}async initStore(){let _=this.configComponent;if(!_)return;let w=_.get("task.storage.type")??"sqlite",$=_.get("task.storage.dbPath");if(w==="sqlite")this.store=new Fw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Fw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,Y]of Object.entries(_)){let J=`${w}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign($,this.flattenConfig(Y,J));else $[J]=Y}return $}registerConfigWatcher(_){if(typeof _.watch!=="function")return;this.configWatcher=_.watch("task.*",(w)=>{this.onConfigChange(w)})}onConfigChange(_){if(J_.info(`[TaskComponent] Config changed: ${_.key}`,{oldValue:_.oldValue,newValue:_.newValue}),_.key==="task.storage.type"||_.key==="task.storage.dbPath")this.initStore()}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new w_(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(G1(this.backgroundTaskManager),"built-in"),J_.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else J_.warn("[TaskComponent] ToolComponent not found, skipping tool registration")}async stop(){if(this.configWatcher)this.configWatcher(),this.configWatcher=void 0;if(this.toolComponent)try{this.toolComponent.register(G1(null),"built-in"),J_.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch(_){J_.warn(`[TaskComponent] Failed to reset query_background_process tool: ${_.message}`)}if(this.backgroundTaskManager)this.backgroundTaskManager.dispose(),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let _=[x0(this),m0(this),u0(this),p0(this),l0(this),z$(this),V$(this),c0(this),O$(this),d0(this)],w=[i0(this),R$(this),n0(this),f$(this),L$(this)],$=[d5(this),$4(this.backgroundTaskManager)];for(let X of[..._,...w,...$])this.toolComponent.register(X),J_.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook(_,w,$={}){let X={component:{name:this.name,version:this.version},data:w,metadata:$,phase:_.includes("before")?"before":"after",hookPoint:_};await E_.execute(_,w,$)}async createTask(_){let w=_.sessionId;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){if(!await this.store.getTask(_.parent_task_id))throw Error(`Parent task #${_.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let $={options:{..._},sessionId:w,tagService:this.tagService};await this.executeHook($_.BEFORE_CREATE,$);let X=await this.store.createTask($.options);await this.store.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook($_.AFTER_CREATE,Y),this.publishEvent(fw.CREATED,{task:X,sessionId:w},w),J_.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask(_){return this.store.getTask(_)}async getTaskIdBySessionId(_){return this.store.getTaskIdBySessionId(_)}async getTaskWithOperations(_){let w=await this.store.getTask(_);if(!w)return;let $=await this.store.listOperations({taskId:_});return{...w,operations:$,task:w}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook($_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let Y={task:X,changes:w,tagService:this.tagService};if(await this.executeHook($_.AFTER_UPDATE,Y),this.publishEvent(fw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Dz.includes(w.status)){let J=$2(),D={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,D),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook($_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook($_.AFTER_DELETE,X),$)this.publishEvent(fw.DELETED,{taskId:_,sessionId:""},""),J_.info(`[TaskComponent] Task deleted: ${_}`);return $}async listTasks(_){return this.store.listTasks(_)}async searchTasksByKeywords(_,w){return this.store.searchTasksByKeywords(_,w||{})}async getTaskTree(_,w=-1){return this.store.getTaskTree(_,w)}async getChildTasks(_,w){return this.store.getChildTasks(_,w)}async completeTask(_,w,$){let X=await this.store.getTask(_);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${_} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($){let D={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))D=W}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}D.deliverable_storage_path=$,Y.context=JSON.stringify(D)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Gz($)}),this.publishEvent(fw.COMPLETED,{task:J,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return J}async createOperation(_){let w={options:{..._}};await this.executeHook($_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),Y={operation:$};return await this.executeHook($_.OPERATION_AFTER_CREATE,Y,{task:X,operation:$}),this.publishEvent(fw.OPERATION_ADDED,{operation:$,taskId:$.taskId},$.sessionId),J_.info(`[TaskComponent] Operation created: ${$.id} for task ${$.taskId}`),$}async getOperation(_){return this.store.getOperation(_)}async updateOperation(_,w){return this.store.updateOperation(_,w)}async deleteOperation(_){return this.store.deleteOperation(_)}async listOperations(_){return this.store.listOperations(_)}getTagService(){return this.tagService}registerHook(_,w){E_.register(_,w),this.plugins.set(this.makePluginKey(_,w.name),w),J_.debug(`[TaskComponent] Registered hook: ${w.name} at ${_}`)}registerHooks(_){for(let{hookPoint:w,hook:$}of _)this.registerHook(w,$)}unregisterHook(_,w){let $=E_.unregister(_,w);if($)this.plugins.delete(this.makePluginKey(_,w)),J_.info(`[TaskComponent] Unregistered hook: ${w} from ${_}`);return $}listHooks(){return Array.from(this.plugins.values())}makePluginKey(_,w){return`${_}::${w}`}countHooks(_){return E_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],Kw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createOperation",null);var K$=A.enum(["todo","active","completed","paused","cancelled","archived"]),N$=A.enum(["low","medium","high"]),b$=A.enum(["normal","cycle","longterm"]),j$=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Qz=A.object({storage:A.object({type:A.enum(["memory","sqlite"]).default("sqlite"),dbPath:A.string().optional()}).default({})}).default({});Ww();Ww();var qz="Deliverable: ";function Hz(_){if(!_)return;return`${qz}${_}`}var H2=1e6;class E${port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=Bz(_);if(w!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(w);return(await this.scanAllTasks()).find(($)=>$.id===w)??null}return await this.port.getTask(String(_))}toTask(_){let{nativeId:w,...$}=_;return $}toOperation(_){let{nativeId:w,...$}=_;return $}async scanAllTasks(){return(await this.port.listTasks({limit:H2,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let Y=await this.resolve(_.parent_task_id);if(!Y)throw Error(`Parent task #${_.parent_task_id} not found.`);$=Y.id}let X=await this.port.createTask({title:_.title,description:_.description,priority:_.priority,type:_.type,goals_and_expected_deliverables:_.goals_and_expected_deliverables,...$!==void 0?{parent_task_id:$}:{},due_date:_.due_date,tags:_.tags,project_path:_.project_path,context:_.context,sessionId:w});return await this.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask(_){let w=await this.resolve(_);return w?this.toTask(w):null}async getTaskWithOperations(_){let w=await this.getTask(_);if(!w)return null;let $=await this.listOperations({taskId:w.id,limit:H2,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,_),{tasks:X.slice($,$+w),total:X.length}}async updateTask(_,w){let $=await this.resolve(_);if(!$)return null;let X;if(w.parent_task_id!==void 0)if(w.parent_task_id===null)X=null;else{let J=await this.resolve(w.parent_task_id);if(!J)throw Error(`Parent task #${w.parent_task_id} not found.`);X=J.id}let Y=await this.port.updateTask($.nativeId,{title:w.title,description:w.description,status:w.status,priority:w.priority,type:w.type,progress:w.progress,current_status:w.current_status,goals_and_expected_deliverables:w.goals_and_expected_deliverables,due_date:w.due_date,tags:w.tags,project_path:w.project_path,context:w.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask(_){let w=await this.resolve(_);if(!w)return!1;return await this.port.deleteTask(w.nativeId)}async completeTask(_,w,$){let X=await this.resolve(_);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($)Y.context=zz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let D=Hz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:D??"Task completed",...$?{mdPath:$}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??J)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((Q)=>this.toTask(Q)),Y=new Map;for(let Q of X){if(Q.parent_task_id===void 0)continue;let q=Y.get(Q.parent_task_id)??[];q.push(Q),Y.set(Q.parent_task_id,q)}let J=[],D=new Set([$.id]),W=[$.id],G=0;while(W.length>0){if(w!==-1&&G>=w)break;let Q=[];for(let q of W)for(let H of Y.get(q)??[]){if(D.has(H.id))continue;D.add(H.id),J.push(H),Q.push(H.id)}W=Q,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((W)=>W.id!==w.excludeTaskId);let J=_.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),D=J.length===0?Y:Y.filter((W)=>{let G=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return J.every((Q)=>G.includes(Q))});return{tasks:D.slice(X,X+$),total:D.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",Y=_.milestoneDescription??_.actionDescription??"",J=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(J)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let Y=await this.resolve(_.taskId);if(!Y)return[];let D=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?H2:w,offset:X?0:$})).operations.map((W)=>this.toOperation(W));if(X)D=D.filter((W)=>W.milestoneType===X),D=D.slice($,$+w);return D}async getOperation(_){if(typeof this.port.getOperationByNum==="function"){let $=await this.port.getOperationByNum(_);return $?this.toOperation($):null}let w=await this.scanAllTasks();for(let $ of w){let Y=(await this.port.listOperations({taskNativeId:$.nativeId,limit:H2})).operations.find((J)=>J.id===_);if(Y)return this.toOperation(Y)}return null}async updateOperation(_,w){let $=await this.getOperation(_);if(!$)return null;if(typeof this.port.updateOperationByNum!=="function")return $;let X=await this.port.updateOperationByNum(_,{sessionId:w.sessionId??$.sessionId,milestoneType:w.milestoneType??w.actionType??$.milestoneType,milestoneTitle:w.milestoneTitle??w.actionTitle??$.milestoneTitle,milestoneDescription:w.milestoneDescription??w.actionDescription??$.milestoneDescription,processDescription:w.processDescription??$.processDescription,...w.mdPath!==void 0?{mdPath:w.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation(_){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum(_)}applyFilters(_,w){let $=_;if(w.include_archived!==!0&&w.status!=="archived")$=$.filter((Y)=>Y.status!=="archived");if(w.status!==void 0)$=$.filter((Y)=>Y.status===w.status);if(w.priority!==void 0)$=$.filter((Y)=>Y.priority===w.priority);if(w.type!==void 0)$=$.filter((Y)=>Y.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((Y)=>Y.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let Y=Uz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function Bz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function Uz(_,w){if(w<0)return new Set(_.map((D)=>D.id));let $=new Set(_.map((D)=>D.id)),X=new Map;for(let D of _){let W=D.parent_task_id;if(W===void 0||!$.has(W))continue;let G=X.get(W)??[];G.push(D),X.set(W,G)}let Y=new Set,J=_.filter((D)=>D.parent_task_id===void 0||!$.has(D.parent_task_id));for(let D of J)Y.add(D.id);for(let D=1;D<=w;D++){let W=[];for(let G of J)for(let Q of X.get(G.id)??[]){if(Y.has(Q.id))continue;Y.add(Q.id),W.push(Q)}if(W.length===0)break;J=W}return Y}function zz(_,w){let $={};if(typeof _==="string"&&_.trim().length>0)try{let X=JSON.parse(_);if(X&&typeof X==="object"&&!Array.isArray(X))$=X}catch{}return $.deliverable_storage_path=w,JSON.stringify($)}var Vz=1e6;function Oz(_){let w={};if(_.type!==void 0)w.type=_.type;if(_.progress!==void 0)w.progress=_.progress;if(_.current_status!==void 0)w.current_status=_.current_status;if(_.goals_and_expected_deliverables!==void 0)w.goals_and_expected_deliverables=_.goals_and_expected_deliverables;if(_.project_path!==void 0)w.project_path=_.project_path;if(_.context!==void 0)w.context=_.context;if(_.due_date!==void 0)w.due_date=_.due_date;return w}function o0(_,w,$){if(typeof _.num!=="number")throw Error(`store did not expose a numeric handle for task ${_.id}`);let X=_.roy??{};return{id:_.num,nativeId:_.id,title:_.title,description:_.description??"",status:w.toRoyStatus(_.status),priority:w.toRoyPriority(_.priority),type:X.type??"normal",progress:typeof X.progress==="number"?X.progress:_.status==="done"?100:0,current_status:X.current_status??"",goals_and_expected_deliverables:X.goals_and_expected_deliverables??"",...$!==void 0?{parent_task_id:$}:{},createdAt:_.created_at,updatedAt:_.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:w.toRoyTags(_.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function s0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),Y=String(w.milestoneDescription??w.actionDescription??""),J=w.taskId??_.task_id,D=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:D,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:Y}}function b6(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??Vz;async function D(){let Q=await _.listTasks({limit:J});return new Map(Q.tasks.filter((q)=>typeof q.num==="number").map((q)=>[q.id,q.num]))}async function W(Q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(Q);return(await _.listTasks({limit:J})).tasks.find((H)=>H.num===Q)??null}async function G(Q){let H=[...(await D()).entries()].find(([,B])=>B===Q);if(!H)throw Error(`parent task not found: ${Q}`);return H[0]}return{async createTask(Q){let q=Q.parent_task_id!==void 0?await G(Q.parent_task_id):null,H={type:Q.type??"normal",progress:Q.progress??0,current_status:Q.current_status??"",goals_and_expected_deliverables:Q.goals_and_expected_deliverables??"",project_path:Q.project_path,context:Q.context,...Q.due_date?{due_date:Q.due_date}:{}},B=await _.createTask({title:Q.title,description:Q.description,priority:w.toStorePriority(Q.priority),owner:Y,tags:w.toStoreTags(Q.tags),parent_id:q,session_id:Q.sessionId??"unknown",roy:H});return o0(B,w,Q.parent_task_id)},async getTask(Q){let q=await _.getTask(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async getTaskByNum(Q){let q=await W(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async listTasks(Q){let q=await _.listTasks({limit:Q?.limit??20,offset:Q?.offset??0}),H=await D();return{tasks:q.tasks.map((B)=>o0(B,w,B.parent_id?H.get(B.parent_id):void 0)),total:q.total}},async updateTask(Q,q){let H=Oz(q),B=await _.updateTask(Q,{...q.title!==void 0?{title:q.title}:{},...q.description!==void 0?{description:q.description}:{},...q.status!==void 0?{status:w.toStoreStatus(q.status)}:{},...q.priority!==void 0?{priority:w.toStorePriority(q.priority)}:{},...q.tags!==void 0?{tags:w.toStoreTags(q.tags)}:{},...Object.keys(H).length>0?{roy:H}:{}});if(!B)return null;let O;if(q.parent_task_id!==void 0){let U=q.parent_task_id===null?null:await G(q.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(Q,U);O=q.parent_task_id===null?void 0:q.parent_task_id}let z=await _.getTask(Q)??B;if(O===void 0&&z.parent_id)O=(await D()).get(z.parent_id);return o0(z,w,O)},async deleteTask(Q){return await _.deleteTask(Q)},async createOperation(Q){let q=await _.appendOperation({task_id:Q.taskNativeId??String(Q.taskId),type:X,data:{taskId:Q.taskId,sessionId:Q.sessionId,milestoneType:Q.milestoneType,milestoneTitle:Q.milestoneTitle,milestoneDescription:Q.milestoneDescription,processDescription:Q.processDescription,...Q.mdPath?{mdPath:Q.mdPath}:{}}});return s0(q)},async listOperations(Q){let q=await _.listOperations({...Q?.taskNativeId?{task_id:Q.taskNativeId}:{},type:X,limit:Q?.limit??J,offset:Q?.offset??0});return{operations:q.operations.map(s0),total:q.total}},async getOperationByNum(Q){if(typeof _.getOperationByNum!=="function")return null;let q=await _.getOperationByNum(Q);return q?s0(q):null},async updateOperationByNum(Q,q){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(Q);if(!H)return null;let B=s0(H),O=await _.updateOperation(Q,{data:{taskId:B.taskId,sessionId:q.sessionId??B.sessionId,milestoneType:q.milestoneType??B.milestoneType,milestoneTitle:q.milestoneTitle??B.milestoneTitle,milestoneDescription:q.milestoneDescription??B.milestoneDescription,processDescription:q.processDescription??B.processDescription,...q.mdPath??B.mdPath?{mdPath:q.mdPath??B.mdPath}:{}}});return O?s0(O):null},async deleteOperationByNum(Q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(Q)}}}var Az="roy.milestone",Mz={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Rz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function j6(_){return Mz[_]??"pending"}function E6(_){return Rz[_]??"todo"}function S6(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function P6(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function Z6(_){if(!_||_.length===0)return;return _.join(",")}function C6(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var fz={toRoyStatus:(_)=>E6(_),toStoreStatus:(_)=>j6(_),toRoyPriority:(_)=>P6(_),toStorePriority:(_)=>S6(_),toRoyTags:(_)=>C6(_),toStoreTags:(_)=>Z6(_)};function T6(_,w={}){return new E$(b6(_,fz,{operationType:Az,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var FR=K$.options,KR=N$.options,NR=b$.options,bR=j$.options;var k6=Symbol("Let zodToJsonSchema decide on which parser to use");var I6={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},g6=(_)=>typeof _==="string"?{...I6,name:_}:{...I6,..._};var h6=(_)=>{let w=g6(_),$=w.name!==void 0?[...w.basePath,w.definitionPath,w.name]:w.basePath;return{...w,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(w.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...w.basePath,w.definitionPath,X],jsonSchema:void 0}]))}};function S$(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,S$(_,w,X,Y)}var B2=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function s(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?B2(w,_.currentPath):w.join("/")}}function y6(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==K.ZodAny)$.items=k(_.type._def,{...w,currentPath:[...w.currentPath,"items"]});if(_.minLength)d($,"minItems",_.minLength.value,_.minLength.message,w);if(_.maxLength)d($,"maxItems",_.maxLength.value,_.maxLength.message,w);if(_.exactLength)d($,"minItems",_.exactLength.value,_.exactLength.message,w),d($,"maxItems",_.exactLength.value,_.exactLength.message,w);return $}function v6(_,w){let $={type:"integer",format:"int64"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function x6(){return{type:"boolean"}}function U2(_,w){return k(_.type._def,w)}var m6=(_,w)=>{return k(_.innerType._def,w)};function P$(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>P$(_,w,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Lz(_,w)}}var Lz=(_,w)=>{let $={type:"integer",format:"unix-time"};if(w.target==="openApi3")return $;for(let X of _.checks)switch(X.kind){case"min":d($,"minimum",X.value,X.message,w);break;case"max":d($,"maximum",X.value,X.message,w);break}return $};function u6(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function l6(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function c6(_){return{type:"string",enum:Array.from(_.values)}}var Fz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function d6(_,w){let $=[k(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),k(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((J)=>!!J),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((J)=>{if(Fz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let D=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...G}=J;D=G}else X=void 0;Y.push(D)}}),Y.length?{allOf:Y,...X}:void 0}function p6(_,w){let $=typeof _.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(_.value)?"array":"object"};if(w.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[_.value]};return{type:$==="bigint"?"integer":$,const:_.value}}var Z$=void 0,S_={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Z$===void 0)Z$=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z$},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function z2(_,w){let $={type:"string"};if(_.checks)for(let X of _.checks)switch(X.kind){case"min":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w);break;case"max":d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"email":switch(w.emailStrategy){case"format:email":P_($,"email",X.message,w);break;case"format:idn-email":P_($,"idn-email",X.message,w);break;case"pattern:zod":q_($,S_.email,X.message,w);break}break;case"url":P_($,"uri",X.message,w);break;case"uuid":P_($,"uuid",X.message,w);break;case"regex":q_($,X.regex,X.message,w);break;case"cuid":q_($,S_.cuid,X.message,w);break;case"cuid2":q_($,S_.cuid2,X.message,w);break;case"startsWith":q_($,RegExp(`^${C$(X.value,w)}`),X.message,w);break;case"endsWith":q_($,RegExp(`${C$(X.value,w)}$`),X.message,w);break;case"datetime":P_($,"date-time",X.message,w);break;case"date":P_($,"date",X.message,w);break;case"time":P_($,"time",X.message,w);break;case"duration":P_($,"duration",X.message,w);break;case"length":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w),d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"includes":{q_($,RegExp(C$(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")P_($,"ipv4",X.message,w);if(X.version!=="v4")P_($,"ipv6",X.message,w);break}case"base64url":q_($,S_.base64url,X.message,w);break;case"jwt":q_($,S_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")q_($,S_.ipv4Cidr,X.message,w);if(X.version!=="v4")q_($,S_.ipv6Cidr,X.message,w);break}case"emoji":q_($,S_.emoji(),X.message,w);break;case"ulid":{q_($,S_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{P_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{q_($,S_.base64,X.message,w);break}}break}case"nanoid":q_($,S_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return $}function C$(_,w){return w.patternStrategy==="escape"?Nz(_):_}var Kz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nz(_){let w="";for(let $=0;$<_.length;$++){if(!Kz.has(_[$]))w+="\\";w+=_[$]}return w}function P_(_,w,$,X){if(_.format||_.anyOf?.some((Y)=>Y.format)){if(!_.anyOf)_.anyOf=[];if(_.format){if(_.anyOf.push({format:_.format,..._.errorMessage&&X.errorMessages&&{errorMessage:{format:_.errorMessage.format}}}),delete _.format,_.errorMessage){if(delete _.errorMessage.format,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.anyOf.push({format:w,...$&&X.errorMessages&&{errorMessage:{format:$}}})}else d(_,"format",w,$,X)}function q_(_,w,$,X){if(_.pattern||_.allOf?.some((Y)=>Y.pattern)){if(!_.allOf)_.allOf=[];if(_.pattern){if(_.allOf.push({pattern:_.pattern,..._.errorMessage&&X.errorMessages&&{errorMessage:{pattern:_.errorMessage.pattern}}}),delete _.pattern,_.errorMessage){if(delete _.errorMessage.pattern,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.allOf.push({pattern:i6(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",i6(w,X),$,X)}function i6(_,w){if(!w.applyRegexFlags||!_.flags)return _.source;let $={i:_.flags.includes("i"),m:_.flags.includes("m"),s:_.flags.includes("s")},X=$.i?_.source.toLowerCase():_.source,Y="",J=!1,D=!1,W=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(D){if(X[G].match(/[a-z]/)){if(W)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),W=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],W=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
2544
2544
  ]))`;continue}else if(X[G]==="$"){Y+=`($|(?=[\r
2545
- ]))`;continue}}if($.s&&X[G]==="."){Y+=W?`${X[G]}\r
2545
+ ]))`;continue}}if($.s&&X[G]==="."){Y+=D?`${X[G]}\r
2546
2546
  `:`[${X[G]}\r
2547
- ]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(W&&X[G]==="]")W=!1;else if(!W&&X[G]==="[")W=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${w.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),_.source}return Y}function V1(_,w){if(w.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(w.target==="openApi3"&&_.keyType?._def.typeName===K.ZodEnum)return{type:"object",required:_.keyType._def.values,properties:_.keyType._def.values.reduce((X,Y)=>({...X,[Y]:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",Y]})??s(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]})??w.allowedAdditionalProperties};if(w.target==="openApi3")return $;if(_.keyType?._def.typeName===K.ZodString&&_.keyType._def.checks?.length){let{type:X,...Y}=z1(_.keyType._def,w);return{...$,propertyNames:Y}}else if(_.keyType?._def.typeName===K.ZodEnum)return{...$,propertyNames:{enum:_.keyType._def.values}};else if(_.keyType?._def.typeName===K.ZodBranded&&_.keyType._def.type._def.typeName===K.ZodString&&_.keyType._def.type._def.checks?.length){let{type:X,...Y}=U1(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function iX(_,w){if(w.mapStrategy==="record")return V1(_,w);let $=k(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||s(w),X=k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||s(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function nX(_){let w=_.values,X=Object.keys(_.values).filter((J)=>{return typeof w[w[J]]!=="number"}).map((J)=>w[J]),Y=Array.from(new Set(X.map((J)=>typeof J)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function rX(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function aX(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sX(_,w){if(w.target==="openApi3")return oX(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in t0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((Y,J)=>{let W=t0[J._def.typeName];return W&&!Y.includes(W)?[...Y,W]:Y},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((Y,J)=>{let W=typeof J._def.value;switch(W){case"string":case"number":case"boolean":return[...Y,W];case"bigint":return[...Y,"integer"];case"object":if(J._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===$.length){let Y=X.filter((J,W,Q)=>Q.indexOf(J)===W);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,W)=>{return J.includes(W._def.value)?J:[...J,W._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,Y)=>[...X,...Y._def.values.filter((J)=>!X.includes(J))],[])};return oX(_,w)}var oX=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,Y)=>k(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function tX(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:t0[_.innerType._def.typeName],nullable:!0};return{type:[t0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=k(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function eX(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",S4($,"type",X.message,w);break;case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function _9(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let Q in J){let G=J[Q];if(G===void 0||G._def===void 0)continue;let q=bz(G);if(q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();q=!1}let H=k(G._def,{...w,currentPath:[...w.currentPath,"properties",Q],propertyPath:[...w.currentPath,"properties",Q]});if(H===void 0)continue;if(X.properties[Q]=H,!q)Y.push(Q)}if(Y.length)X.required=Y;let W=Nz(_,w);if(W!==void 0)X.additionalProperties=W;return X}function Nz(_,w){if(_.catchall._def.typeName!=="ZodNever")return k(_.catchall._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]});switch(_.unknownKeys){case"passthrough":return w.allowedAdditionalProperties;case"strict":return w.rejectedAdditionalProperties;case"strip":return w.removeAdditionalStrategy==="strict"?w.allowedAdditionalProperties:w.rejectedAdditionalProperties}}function bz(_){try{return _.isOptional()}catch{return!0}}var w9=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return k(_.innerType._def,w);let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:s(w)},$]}:s(w)};var $9=(_,w)=>{if(w.pipeStrategy==="input")return k(_.in._def,w);else if(w.pipeStrategy==="output")return k(_.out._def,w);let $=k(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=k(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((Y)=>Y!==void 0)}};function X9(_,w){return k(_.type._def,w)}function Y9(_,w){let X={type:"array",uniqueItems:!0,items:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items"]})};if(_.minSize)d(X,"minItems",_.minSize.value,_.minSize.message,w);if(_.maxSize)d(X,"maxItems",_.maxSize.value,_.maxSize.message,w);return X}function J9(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:k(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function W9(_){return{not:s(_)}}function Q9(_){return s(_)}var G9=(_,w)=>{return k(_.innerType._def,w)};var q9=(_,w,$)=>{switch(w){case K.ZodString:return z1(_,$);case K.ZodNumber:return eX(_,$);case K.ZodObject:return _9(_,$);case K.ZodBigInt:return yX(_,$);case K.ZodBoolean:return vX();case K.ZodDate:return P4(_,$);case K.ZodUndefined:return W9($);case K.ZodNull:return aX($);case K.ZodArray:return hX(_,$);case K.ZodUnion:case K.ZodDiscriminatedUnion:return sX(_,$);case K.ZodIntersection:return cX(_,$);case K.ZodTuple:return J9(_,$);case K.ZodRecord:return V1(_,$);case K.ZodLiteral:return dX(_,$);case K.ZodEnum:return lX(_);case K.ZodNativeEnum:return nX(_);case K.ZodNullable:return tX(_,$);case K.ZodOptional:return w9(_,$);case K.ZodMap:return iX(_,$);case K.ZodSet:return Y9(_,$);case K.ZodLazy:return()=>_.getter()._def;case K.ZodPromise:return X9(_,$);case K.ZodNaN:case K.ZodNever:return rX($);case K.ZodEffects:return uX(_,$);case K.ZodAny:return s($);case K.ZodUnknown:return Q9($);case K.ZodDefault:return mX(_,$);case K.ZodBranded:return U1(_,$);case K.ZodReadonly:return G9(_,$);case K.ZodCatch:return xX(_,$);case K.ZodPipeline:return $9(_,$);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return((X)=>{return})(w)}};function k(_,w,$=!1){let X=w.seen.get(_);if(w.override){let Q=w.override?.(_,w,X,$);if(Q!==IX)return Q}if(X&&!$){let Q=jz(X,w);if(Q!==void 0)return Q}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=q9(_,_.typeName,w),W=typeof J==="function"?k(J(),w):J;if(W)Ez(_,w,W);if(w.postProcess){let Q=w.postProcess(W,_,w);return Y.jsonSchema=W,Q}return Y.jsonSchema=W,W}var jz=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:B1(w.currentPath,_.path)};case"none":case"seen":{if(_.path.length<w.currentPath.length&&_.path.every(($,X)=>w.currentPath[X]===$))return console.warn(`Recursive reference detected at ${w.currentPath.join("/")}! Defaulting to any`),s(w);return w.$refStrategy==="seen"?s(w):void 0}}},Ez=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var T4=(_,w)=>{let $=gX(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[q,H])=>({...G,[q]:k(H._def,{...$,currentPath:[...$.basePath,$.definitionPath,q]},!0)??s($)}),{}):void 0,Y=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,J=k(_._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??s($),W=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(W!==void 0)J.title=W;if($.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[$.openAiAnyTypeName])X[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let Q=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")Q.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in Q)||("oneOf"in Q)||("allOf"in Q)||("type"in Q)&&Array.isArray(Q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return Q};var Sz=[x0,p0,m0,u0,l0,c0,d0,i0,n0];function Pz(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=T4($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function H9(_,w={}){let $=CX(_,w);return Sz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:Pz(Y.parameters),options:{codemode:!1},execute:async(J,W)=>{let Q={session_id:W?.sessionID??w.sessionId??"unknown",workdir:W?.directory};try{let G=await Y.execute(J??{},Q),q=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?q:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:Y.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function D9(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function B9(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let Y=_??{},J=w.agent??X0;if(typeof Y.agent?.transform==="function")try{let Q=await Y.agent.transform((G)=>{L1(G)});D9(Q,X.disposers),X.agentId=J}catch(Q){X.errors.push(`roy agent registration failed: ${I4(Q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let W=[];try{W=H9(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(Q){return X.errors.push(`roy tool construction failed: ${I4(Q)}`),X}if(typeof Y.tool?.transform==="function")try{let Q=await Y.tool.transform((G)=>{for(let q of W)G.add(q)});D9(Q,X.disposers),X.toolNames=W.map((G)=>G.name)}catch(Q){X.errors.push(`roy tool registration failed: ${I4(Q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function I4(_){return _ instanceof Error?_.message:String(_)}import{join as h4}from"path";import{homedir as yz}from"os";import{mkdirSync as vz}from"fs";import{Database as Zz}from"bun:sqlite";import{createHash as Cz,randomUUID as Tz}from"crypto";var Iz=`
2547
+ ]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(D&&X[G]==="]")D=!1;else if(!D&&X[G]==="[")D=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${w.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),_.source}return Y}function V2(_,w){if(w.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(w.target==="openApi3"&&_.keyType?._def.typeName===K.ZodEnum)return{type:"object",required:_.keyType._def.values,properties:_.keyType._def.values.reduce((X,Y)=>({...X,[Y]:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",Y]})??s(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]})??w.allowedAdditionalProperties};if(w.target==="openApi3")return $;if(_.keyType?._def.typeName===K.ZodString&&_.keyType._def.checks?.length){let{type:X,...Y}=z2(_.keyType._def,w);return{...$,propertyNames:Y}}else if(_.keyType?._def.typeName===K.ZodEnum)return{...$,propertyNames:{enum:_.keyType._def.values}};else if(_.keyType?._def.typeName===K.ZodBranded&&_.keyType._def.type._def.typeName===K.ZodString&&_.keyType._def.type._def.checks?.length){let{type:X,...Y}=U2(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function n6(_,w){if(w.mapStrategy==="record")return V2(_,w);let $=k(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||s(w),X=k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||s(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function r6(_){let w=_.values,X=Object.keys(_.values).filter((J)=>{return typeof w[w[J]]!=="number"}).map((J)=>w[J]),Y=Array.from(new Set(X.map((J)=>typeof J)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function a6(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function o6(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function t6(_,w){if(w.target==="openApi3")return s6(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in t0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((Y,J)=>{let D=t0[J._def.typeName];return D&&!Y.includes(D)?[...Y,D]:Y},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((Y,J)=>{let D=typeof J._def.value;switch(D){case"string":case"number":case"boolean":return[...Y,D];case"bigint":return[...Y,"integer"];case"object":if(J._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===$.length){let Y=X.filter((J,D,W)=>W.indexOf(J)===D);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,D)=>{return J.includes(D._def.value)?J:[...J,D._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,Y)=>[...X,...Y._def.values.filter((J)=>!X.includes(J))],[])};return s6(_,w)}var s6=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,Y)=>k(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function e6(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:t0[_.innerType._def.typeName],nullable:!0};return{type:[t0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=k(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function _X(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",S$($,"type",X.message,w);break;case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function wX(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let W in J){let G=J[W];if(G===void 0||G._def===void 0)continue;let Q=jz(G);if(Q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();Q=!1}let q=k(G._def,{...w,currentPath:[...w.currentPath,"properties",W],propertyPath:[...w.currentPath,"properties",W]});if(q===void 0)continue;if(X.properties[W]=q,!Q)Y.push(W)}if(Y.length)X.required=Y;let D=bz(_,w);if(D!==void 0)X.additionalProperties=D;return X}function bz(_,w){if(_.catchall._def.typeName!=="ZodNever")return k(_.catchall._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]});switch(_.unknownKeys){case"passthrough":return w.allowedAdditionalProperties;case"strict":return w.rejectedAdditionalProperties;case"strip":return w.removeAdditionalStrategy==="strict"?w.allowedAdditionalProperties:w.rejectedAdditionalProperties}}function jz(_){try{return _.isOptional()}catch{return!0}}var $X=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return k(_.innerType._def,w);let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:s(w)},$]}:s(w)};var XX=(_,w)=>{if(w.pipeStrategy==="input")return k(_.in._def,w);else if(w.pipeStrategy==="output")return k(_.out._def,w);let $=k(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=k(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((Y)=>Y!==void 0)}};function YX(_,w){return k(_.type._def,w)}function JX(_,w){let X={type:"array",uniqueItems:!0,items:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items"]})};if(_.minSize)d(X,"minItems",_.minSize.value,_.minSize.message,w);if(_.maxSize)d(X,"maxItems",_.maxSize.value,_.maxSize.message,w);return X}function DX(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:k(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function WX(_){return{not:s(_)}}function GX(_){return s(_)}var QX=(_,w)=>{return k(_.innerType._def,w)};var qX=(_,w,$)=>{switch(w){case K.ZodString:return z2(_,$);case K.ZodNumber:return _X(_,$);case K.ZodObject:return wX(_,$);case K.ZodBigInt:return v6(_,$);case K.ZodBoolean:return x6();case K.ZodDate:return P$(_,$);case K.ZodUndefined:return WX($);case K.ZodNull:return o6($);case K.ZodArray:return y6(_,$);case K.ZodUnion:case K.ZodDiscriminatedUnion:return t6(_,$);case K.ZodIntersection:return d6(_,$);case K.ZodTuple:return DX(_,$);case K.ZodRecord:return V2(_,$);case K.ZodLiteral:return p6(_,$);case K.ZodEnum:return c6(_);case K.ZodNativeEnum:return r6(_);case K.ZodNullable:return e6(_,$);case K.ZodOptional:return $X(_,$);case K.ZodMap:return n6(_,$);case K.ZodSet:return JX(_,$);case K.ZodLazy:return()=>_.getter()._def;case K.ZodPromise:return YX(_,$);case K.ZodNaN:case K.ZodNever:return a6($);case K.ZodEffects:return l6(_,$);case K.ZodAny:return s($);case K.ZodUnknown:return GX($);case K.ZodDefault:return u6(_,$);case K.ZodBranded:return U2(_,$);case K.ZodReadonly:return QX(_,$);case K.ZodCatch:return m6(_,$);case K.ZodPipeline:return XX(_,$);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return((X)=>{return})(w)}};function k(_,w,$=!1){let X=w.seen.get(_);if(w.override){let W=w.override?.(_,w,X,$);if(W!==k6)return W}if(X&&!$){let W=Ez(X,w);if(W!==void 0)return W}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=qX(_,_.typeName,w),D=typeof J==="function"?k(J(),w):J;if(D)Sz(_,w,D);if(w.postProcess){let W=w.postProcess(D,_,w);return Y.jsonSchema=D,W}return Y.jsonSchema=D,D}var Ez=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:B2(w.currentPath,_.path)};case"none":case"seen":{if(_.path.length<w.currentPath.length&&_.path.every(($,X)=>w.currentPath[X]===$))return console.warn(`Recursive reference detected at ${w.currentPath.join("/")}! Defaulting to any`),s(w);return w.$refStrategy==="seen"?s(w):void 0}}},Sz=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var T$=(_,w)=>{let $=h6(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[Q,q])=>({...G,[Q]:k(q._def,{...$,currentPath:[...$.basePath,$.definitionPath,Q]},!0)??s($)}),{}):void 0,Y=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,J=k(_._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??s($),D=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(D!==void 0)J.title=D;if($.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[$.openAiAnyTypeName])X[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let W=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in W)||("oneOf"in W)||("allOf"in W)||("type"in W)&&Array.isArray(W.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return W};var Pz=[x0,p0,m0,u0,l0,c0,d0,i0,n0];function Zz(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=T$($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function HX(_,w={}){let $=T6(_,w);return Pz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:Zz(Y.parameters),options:{codemode:!1},execute:async(J,D)=>{let W={session_id:D?.sessionID??w.sessionId??"unknown",workdir:D?.directory};try{let G=await Y.execute(J??{},W),Q=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?Q:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:Y.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function BX(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function UX(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let Y=_??{},J=w.agent??X0;if(typeof Y.agent?.transform==="function")try{let W=await Y.agent.transform((G)=>{L2(G)});BX(W,X.disposers),X.agentId=J}catch(W){X.errors.push(`roy agent registration failed: ${I$(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let D=[];try{D=HX(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${I$(W)}`),X}if(typeof Y.tool?.transform==="function")try{let W=await Y.tool.transform((G)=>{for(let Q of D)G.add(Q)});BX(W,X.disposers),X.toolNames=D.map((G)=>G.name)}catch(W){X.errors.push(`roy tool registration failed: ${I$(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function I$(_){return _ instanceof Error?_.message:String(_)}import{join as h$}from"path";import{homedir as vz}from"os";import{mkdirSync as xz}from"fs";import{Database as Cz}from"bun:sqlite";import{createHash as Tz,randomUUID as Iz}from"crypto";var kz=`
2548
2548
  CREATE TABLE IF NOT EXISTS tasks (
2549
2549
  id TEXT PRIMARY KEY,
2550
2550
  title TEXT NOT NULL,
@@ -2599,13 +2599,13 @@ CREATE TABLE IF NOT EXISTS bounties (
2599
2599
  done_at TEXT
2600
2600
  );
2601
2601
  CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
2602
- `;function Kw(){return new Date().toISOString()}function k4(){return Tz()}function kz(_){return Cz("sha256").update(_).digest("hex")}function U9(_){let w=JSON.stringify({id:_.id,type:_.type,data:_.data,prev_hash:_.prev_hash,created_at:_.created_at});return kz(w)}function g4(_){return{id:_.id,num:_.num,title:_.title,description:_.description??void 0,status:_.status,priority:_.priority,owner:_.owner??void 0,tags:_.tags??void 0,parent_id:_.parent_id,blocked_by:JSON.parse(_.blocked_by),retry_of:_.retry_of,retry_count:_.retry_count,session_id:_.session_id,roy:gz(_.roy),created_at:_.created_at,updated_at:_.updated_at}}function gz(_){if(_===null||_===void 0||_==="")return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}function hz(_){try{let w=_.query("PRAGMA table_info(tasks)").all();if(!new Set(w.map((X)=>X.name)).has("roy"))_.exec("ALTER TABLE tasks ADD COLUMN roy TEXT")}catch{}}function z9(_){return{id:_.id,num:_.num,task_id:_.task_id,type:_.type,data:JSON.parse(_.data),created_at:_.created_at,prev_hash:_.prev_hash,hash:_.hash}}function O1(_){return{id:_.id,subject:_.subject,body:_.body,from:_.from_,to:_.to_,status:_.status,claimed_by:_.claimed_by,task_id:_.task_id,created_at:_.created_at,claimed_at:_.claimed_at,done_at:_.done_at}}class A1{db;closedFlag=!1;constructor(_){this.db=_}static async create(_){let w=new Zz(_);return w.exec(Iz),hz(w),new A1(w)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask(_,w){if(this.closedFlag)throw Error("store closed");if(w){let W=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(w);if(W){let Q=await this.getTask(W.task_id);if(Q)return Q}}let $=k4(),X=Kw(),Y=_.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
2602
+ `;function Nw(){return new Date().toISOString()}function k$(){return Iz()}function gz(_){return Tz("sha256").update(_).digest("hex")}function zX(_){let w=JSON.stringify({id:_.id,type:_.type,data:_.data,prev_hash:_.prev_hash,created_at:_.created_at});return gz(w)}function g$(_){return{id:_.id,num:_.num,title:_.title,description:_.description??void 0,status:_.status,priority:_.priority,owner:_.owner??void 0,tags:_.tags??void 0,parent_id:_.parent_id,blocked_by:JSON.parse(_.blocked_by),retry_of:_.retry_of,retry_count:_.retry_count,session_id:_.session_id,roy:hz(_.roy),created_at:_.created_at,updated_at:_.updated_at}}function hz(_){if(_===null||_===void 0||_==="")return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}function yz(_){try{let w=_.query("PRAGMA table_info(tasks)").all();if(!new Set(w.map((X)=>X.name)).has("roy"))_.exec("ALTER TABLE tasks ADD COLUMN roy TEXT")}catch{}}function VX(_){return{id:_.id,num:_.num,task_id:_.task_id,type:_.type,data:JSON.parse(_.data),created_at:_.created_at,prev_hash:_.prev_hash,hash:_.hash}}function O2(_){return{id:_.id,subject:_.subject,body:_.body,from:_.from_,to:_.to_,status:_.status,claimed_by:_.claimed_by,task_id:_.task_id,created_at:_.created_at,claimed_at:_.claimed_at,done_at:_.done_at}}class A2{db;closedFlag=!1;constructor(_){this.db=_}static async create(_){let w=new Cz(_);return w.exec(kz),yz(w),new A2(w)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask(_,w){if(this.closedFlag)throw Error("store closed");if(w){let D=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(w);if(D){let W=await this.getTask(D.task_id);if(W)return W}}let $=k$(),X=Nw(),Y=_.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
2603
2603
  parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
2604
2604
  VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run($,_.title,_.description??null,Y,_.owner??null,_.tags??null,_.parent_id??null,JSON.stringify(_.blocked_by??[]),_.retry_of??null,_.session_id??null,_.roy===void 0?null:JSON.stringify(_.roy),X,X),w)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
2605
- VALUES (?, ?, ?)`).run(w,$,X);await this.appendOperation({task_id:$,type:"task.created",data:{title:_.title,parent_id:_.parent_id??null}});let J=await this.getTask($);if(!J)throw Error("internal: task vanished after insert");return J}async getTask(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get(_);return w?g4(w):null}async getTaskByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE rowid = ?").get(_);return w?g4(w):null}async updateTask(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getTask(_);if(!$)return null;let X=[],Y=[];if(w.title!==void 0)X.push("title = ?"),Y.push(w.title);if(w.description!==void 0)X.push("description = ?"),Y.push(w.description);if(w.status!==void 0)X.push("status = ?"),Y.push(w.status);if(w.priority!==void 0)X.push("priority = ?"),Y.push(w.priority);if(w.owner!==void 0)X.push("owner = ?"),Y.push(w.owner);if(w.tags!==void 0)X.push("tags = ?"),Y.push(w.tags);if(w.blocked_by!==void 0)X.push("blocked_by = ?"),Y.push(JSON.stringify(w.blocked_by));if(w.roy!==void 0){let J={...$.roy??{},...w.roy};X.push("roy = ?"),Y.push(JSON.stringify(J))}if(X.push("updated_at = ?"),Y.push(Kw()),Y.push(_),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...Y),w.status!==void 0&&w.status!==$.status)await this.appendOperation({task_id:_,type:"task.status_changed",data:{from:$.status,to:w.status}});else await this.appendOperation({task_id:_,type:"task.updated",data:{keys:Object.keys(w)}});return await this.getTask(_)}async listTasks(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)if(Array.isArray(_.status))w.push(`status IN (${_.status.map(()=>"?").join(",")})`),$.push(..._.status);else w.push("status = ?"),$.push(_.status);if(_.parent_id!==void 0)if(_.parent_id===null)w.push("parent_id IS NULL");else w.push("parent_id = ?"),$.push(_.parent_id);if(_.session_id!==void 0)w.push("session_id = ?"),$.push(_.session_id);if(_.owner!==void 0)w.push("owner = ?"),$.push(_.owner);if(_.tags!==void 0)w.push("tags LIKE ?"),$.push(`%${_.tags}%`);if(_.search!==void 0)w.push("(title LIKE ? OR description LIKE ?)"),$.push(`%${_.search}%`,`%${_.search}%`);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",W=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${J}`).get(...$).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${J} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...$,X,Y).map(g4),total:W}}async deleteTask(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run(_).changes>0}async setParentId(_,w){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(w,Kw(),_)}async appendOperation(_){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=k4(),Y=Kw(),J=U9({id:X,type:_.type,data:_.data,prev_hash:$,created_at:Y});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
2606
- VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),Y,$,J);let W=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:W,task_id:_.task_id,type:_.type,data:_.data,created_at:Y,prev_hash:$,hash:J}}async getOperationByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get(_);return w?z9(w):null}async updateOperation(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getOperationByNum(_);if(!$)return null;let X=[],Y=[];if(w.type!==void 0)X.push("type = ?"),Y.push(w.type);if(w.data!==void 0)X.push("data = ?"),Y.push(JSON.stringify(w.data));if(X.length===0)return $;return Y.push(_),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...Y),await this.getOperationByNum(_)}async deleteOperation(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM operations WHERE rowid = ?").run(_).changes>0}async listOperations(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.task_id!==void 0)w.push("task_id = ?"),$.push(_.task_id);if(_.type!==void 0)w.push("type = ?"),$.push(_.type);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",W=this.db.query(`SELECT COUNT(*) AS n FROM operations ${J}`).get(...$).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${J} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...$,X,Y).map(z9),total:W}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let _=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),w="0".repeat(64);for(let $ of _){let X=U9({id:$.id,type:$.type,data:JSON.parse($.data),prev_hash:w,created_at:$.created_at});if($.prev_hash!==w)return!1;if($.hash!==X)return!1;w=$.hash}return!0}async tamperOpForTest(_,w){this.db.query("UPDATE operations SET data = ? WHERE rowid = ?").run(JSON.stringify(w),_)}async sendBounty(_){if(this.closedFlag)throw Error("store closed");let w=k4(),$=Kw();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
2607
- VALUES (?, ?, ?, ?, 'open', ?)`).run(w,_.subject,_.body,_.from,$),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:w,subject:_.subject,from:_.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w);return O1(X)}async claimBounty(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!w)return null;let $=Kw();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run(_,$,w.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:w.id,by:_}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w.id);return O1(X)}async completeBounty(_,w){if(this.closedFlag)throw Error("store closed");let $=Kw();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
2608
- WHERE id = ? AND status = 'claimed'`).run(w,$,_).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:_,task_id:w}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get(_);return O1(Y)}async listBounties(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)w.push("status = ?"),$.push(_.status);if(_.to!==void 0)w.push("to_ = ?"),$.push(_.to);let X=w.length?`WHERE ${w.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...$).map(O1)}}var xz=h4(yz(),".roy-task-plugin"),mz=h4(xz,"tasks.db");class $0{inner;constructor(_){this.inner=_}static async create(_){let w=_??mz;if(w!==":memory:")vz(h4(w,".."),{recursive:!0});let $=await A1.create(w);return new $0($)}createTask(..._){return this.inner.createTask(..._)}getTask(..._){return this.inner.getTask(..._)}updateTask(..._){return this.inner.updateTask(..._)}deleteTask(..._){return this.inner.deleteTask(..._)}listTasks(..._){return this.inner.listTasks(..._)}appendOperation(..._){return this.inner.appendOperation(..._)}listOperations(..._){return this.inner.listOperations(..._)}verifyChain(){return this.inner.verifyChain()}sendBounty(..._){return this.inner.sendBounty(..._)}claimBounty(..._){return this.inner.claimBounty(..._)}completeBounty(..._){return this.inner.completeBounty(..._)}listBounties(..._){return this.inner.listBounties(..._)}async close(){await this.inner.close()}}class h_ extends Error{status;body;constructor(_,w,$){super(w);this.status=_,this.body=$}}class y4{baseUrl;headers;closedFlag=!1;constructor(_){this.baseUrl=_.baseUrl.replace(/\/+$/,""),this.headers={"content-type":"application/json",..._.authToken?{authorization:`Bearer ${_.authToken}`}:{},..._.headers??{}}}async close(){this.closedFlag=!0}async request(_,w,$){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if($?.idempotencyKey)X["idempotency-key"]=$.idempotencyKey;let Y=await fetch(`${this.baseUrl}${w}`,{method:_,headers:X,body:$?.body!==void 0?JSON.stringify($.body):void 0});if(Y.status===204)return null;let J=await Y.text(),W=null;try{W=J?JSON.parse(J):null}catch{W=J}if(!Y.ok)throw new h_(Y.status,`HTTP ${Y.status}`,W);return W}async createTask(_,w){let $=await this.request("POST","/tasks",{body:_,idempotencyKey:w});if(!$)throw new h_(500,"empty response from POST /tasks");return $}async getTask(_){try{return await this.request("GET",`/tasks/${encodeURIComponent(_)}`)}catch(w){if(w instanceof h_&&w.status===404)return null;throw w}}async updateTask(_,w){try{return await this.request("PATCH",`/tasks/${encodeURIComponent(_)}`,{body:w})}catch($){if($ instanceof h_&&$.status===404)return null;throw $}}async deleteTask(_){try{return await this.request("DELETE",`/tasks/${encodeURIComponent(_)}`),!0}catch(w){if(w instanceof h_&&w.status===404)return!1;throw w}}async listTasks(_={}){let w=new URLSearchParams;if(_.status!==void 0){let X=Array.isArray(_.status)?_.status.join(","):_.status;w.set("status",X)}if(_.parent_id!==void 0&&_.parent_id!==null)w.set("parent_id",_.parent_id);if(_.session_id!==void 0)w.set("session_id",_.session_id);if(_.owner!==void 0)w.set("owner",_.owner);if(_.tags!==void 0)w.set("tags",_.tags);if(_.search!==void 0)w.set("search",_.search);w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0));let $=await this.request("GET",`/tasks?${w}`);if(!$)throw new h_(500,"empty response");return $}async appendOperation(_){return await this.request("POST","/operations",{body:_})}async listOperations(_={}){let w=new URLSearchParams;if(_.task_id!==void 0)w.set("task_id",_.task_id);if(_.type!==void 0)w.set("type",_.type);return w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0)),await this.request("GET",`/operations?${w}`)}async verifyChain(){return(await this.request("GET","/verify"))?.valid===!0}async sendBounty(_){let w=await this.request("POST","/bounties",{body:_});if(!w)throw new h_(500,"empty bounty response");return w}async claimBounty(_){try{return await this.request("POST","/bounties/claim",{body:{agent:_}})}catch(w){if(w instanceof h_&&w.status===404)return null;throw w}}async completeBounty(_,w){try{return await this.request("POST",`/bounties/${encodeURIComponent(_)}/complete`,{body:{task_id:w}})}catch($){if($ instanceof h_&&$.status===404)return null;throw $}}async listBounties(_={}){let w=new URLSearchParams;if(_.status!==void 0)w.set("status",_.status);if(_.to!==void 0)w.set("to",_.to);return(await this.request("GET",`/bounties?${w}`))?.bounties??[]}}class e0{inner;constructor(_){this.inner=new y4(_)}createTask(..._){return this.inner.createTask(..._)}getTask(..._){return this.inner.getTask(..._)}updateTask(..._){return this.inner.updateTask(..._)}deleteTask(..._){return this.inner.deleteTask(..._)}listTasks(..._){return this.inner.listTasks(..._)}appendOperation(..._){return this.inner.appendOperation(..._)}listOperations(..._){return this.inner.listOperations(..._)}verifyChain(){return this.inner.verifyChain()}sendBounty(..._){return this.inner.sendBounty(..._)}claimBounty(..._){return this.inner.claimBounty(..._)}completeBounty(..._){return this.inner.completeBounty(..._)}listBounties(..._){return this.inner.listBounties(..._)}async close(){await this.inner.close()}}async function wK(_={}){let w=_.persistence??"local",$;if(w==="remote"){if(!_.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");$=new e0({baseUrl:_.remoteUrl,authToken:_.remoteAuthToken})}else $=await $0.create(_.localDbPath);let X={store:$,agent:_.agent??"opencode-default"};return{handlers:X2(X),store:$,async close(){await $.close()}}}var uz={id:"roy-task-plugin",async setup(_){let w=_.options??{},$=w.persistence??"local",X;if($==="remote"){if(!w.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");X=new e0({baseUrl:w.remoteUrl,authToken:w.remoteAuthToken})}else X=await $0.create(w.localDbPath);let Y={store:X,agent:w.agent??"opencode-default"},J=X2(Y),W=await B9(_,{store:X,enabled:w.royAgent!==!1,agent:"roy"}),Q=await _.agent.transform(async(q)=>{let B=q.get("build");if(!B)return;let D=String(B.system??""),O=`
2605
+ VALUES (?, ?, ?)`).run(w,$,X);await this.appendOperation({task_id:$,type:"task.created",data:{title:_.title,parent_id:_.parent_id??null}});let J=await this.getTask($);if(!J)throw Error("internal: task vanished after insert");return J}async getTask(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get(_);return w?g$(w):null}async getTaskByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE rowid = ?").get(_);return w?g$(w):null}async updateTask(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getTask(_);if(!$)return null;let X=[],Y=[];if(w.title!==void 0)X.push("title = ?"),Y.push(w.title);if(w.description!==void 0)X.push("description = ?"),Y.push(w.description);if(w.status!==void 0)X.push("status = ?"),Y.push(w.status);if(w.priority!==void 0)X.push("priority = ?"),Y.push(w.priority);if(w.owner!==void 0)X.push("owner = ?"),Y.push(w.owner);if(w.tags!==void 0)X.push("tags = ?"),Y.push(w.tags);if(w.blocked_by!==void 0)X.push("blocked_by = ?"),Y.push(JSON.stringify(w.blocked_by));if(w.roy!==void 0){let J={...$.roy??{},...w.roy};X.push("roy = ?"),Y.push(JSON.stringify(J))}if(X.push("updated_at = ?"),Y.push(Nw()),Y.push(_),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...Y),w.status!==void 0&&w.status!==$.status)await this.appendOperation({task_id:_,type:"task.status_changed",data:{from:$.status,to:w.status}});else await this.appendOperation({task_id:_,type:"task.updated",data:{keys:Object.keys(w)}});return await this.getTask(_)}async listTasks(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)if(Array.isArray(_.status))w.push(`status IN (${_.status.map(()=>"?").join(",")})`),$.push(..._.status);else w.push("status = ?"),$.push(_.status);if(_.parent_id!==void 0)if(_.parent_id===null)w.push("parent_id IS NULL");else w.push("parent_id = ?"),$.push(_.parent_id);if(_.session_id!==void 0)w.push("session_id = ?"),$.push(_.session_id);if(_.owner!==void 0)w.push("owner = ?"),$.push(_.owner);if(_.tags!==void 0)w.push("tags LIKE ?"),$.push(`%${_.tags}%`);if(_.search!==void 0)w.push("(title LIKE ? OR description LIKE ?)"),$.push(`%${_.search}%`,`%${_.search}%`);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",D=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${J}`).get(...$).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${J} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...$,X,Y).map(g$),total:D}}async deleteTask(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run(_).changes>0}async setParentId(_,w){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(w,Nw(),_)}async appendOperation(_){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=k$(),Y=Nw(),J=zX({id:X,type:_.type,data:_.data,prev_hash:$,created_at:Y});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
2606
+ VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),Y,$,J);let D=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:D,task_id:_.task_id,type:_.type,data:_.data,created_at:Y,prev_hash:$,hash:J}}async getOperationByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get(_);return w?VX(w):null}async updateOperation(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getOperationByNum(_);if(!$)return null;let X=[],Y=[];if(w.type!==void 0)X.push("type = ?"),Y.push(w.type);if(w.data!==void 0)X.push("data = ?"),Y.push(JSON.stringify(w.data));if(X.length===0)return $;return Y.push(_),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...Y),await this.getOperationByNum(_)}async deleteOperation(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM operations WHERE rowid = ?").run(_).changes>0}async listOperations(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.task_id!==void 0)w.push("task_id = ?"),$.push(_.task_id);if(_.type!==void 0)w.push("type = ?"),$.push(_.type);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",D=this.db.query(`SELECT COUNT(*) AS n FROM operations ${J}`).get(...$).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${J} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...$,X,Y).map(VX),total:D}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let _=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),w="0".repeat(64);for(let $ of _){let X=zX({id:$.id,type:$.type,data:JSON.parse($.data),prev_hash:w,created_at:$.created_at});if($.prev_hash!==w)return!1;if($.hash!==X)return!1;w=$.hash}return!0}async tamperOpForTest(_,w){this.db.query("UPDATE operations SET data = ? WHERE rowid = ?").run(JSON.stringify(w),_)}async sendBounty(_){if(this.closedFlag)throw Error("store closed");let w=k$(),$=Nw();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
2607
+ VALUES (?, ?, ?, ?, 'open', ?)`).run(w,_.subject,_.body,_.from,$),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:w,subject:_.subject,from:_.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w);return O2(X)}async claimBounty(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!w)return null;let $=Nw();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run(_,$,w.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:w.id,by:_}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w.id);return O2(X)}async completeBounty(_,w){if(this.closedFlag)throw Error("store closed");let $=Nw();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
2608
+ WHERE id = ? AND status = 'claimed'`).run(w,$,_).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:_,task_id:w}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get(_);return O2(Y)}async listBounties(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)w.push("status = ?"),$.push(_.status);if(_.to!==void 0)w.push("to_ = ?"),$.push(_.to);let X=w.length?`WHERE ${w.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...$).map(O2)}}var mz=h$(vz(),".roy-task-plugin"),uz=h$(mz,"tasks.db");class $0{inner;constructor(_){this.inner=_}static async create(_){let w=_??uz;if(w!==":memory:")xz(h$(w,".."),{recursive:!0});let $=await A2.create(w);return new $0($)}createTask(..._){return this.inner.createTask(..._)}getTask(..._){return this.inner.getTask(..._)}updateTask(..._){return this.inner.updateTask(..._)}deleteTask(..._){return this.inner.deleteTask(..._)}listTasks(..._){return this.inner.listTasks(..._)}appendOperation(..._){return this.inner.appendOperation(..._)}listOperations(..._){return this.inner.listOperations(..._)}verifyChain(){return this.inner.verifyChain()}sendBounty(..._){return this.inner.sendBounty(..._)}claimBounty(..._){return this.inner.claimBounty(..._)}completeBounty(..._){return this.inner.completeBounty(..._)}listBounties(..._){return this.inner.listBounties(..._)}async close(){await this.inner.close()}}class h_ extends Error{status;body;constructor(_,w,$){super(w);this.status=_,this.body=$}}class y${baseUrl;headers;closedFlag=!1;constructor(_){this.baseUrl=_.baseUrl.replace(/\/+$/,""),this.headers={"content-type":"application/json",..._.authToken?{authorization:`Bearer ${_.authToken}`}:{},..._.headers??{}}}async close(){this.closedFlag=!0}async request(_,w,$){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if($?.idempotencyKey)X["idempotency-key"]=$.idempotencyKey;let Y=await fetch(`${this.baseUrl}${w}`,{method:_,headers:X,body:$?.body!==void 0?JSON.stringify($.body):void 0});if(Y.status===204)return null;let J=await Y.text(),D=null;try{D=J?JSON.parse(J):null}catch{D=J}if(!Y.ok)throw new h_(Y.status,`HTTP ${Y.status}`,D);return D}async createTask(_,w){let $=await this.request("POST","/tasks",{body:_,idempotencyKey:w});if(!$)throw new h_(500,"empty response from POST /tasks");return $}async getTask(_){try{return await this.request("GET",`/tasks/${encodeURIComponent(_)}`)}catch(w){if(w instanceof h_&&w.status===404)return null;throw w}}async updateTask(_,w){try{return await this.request("PATCH",`/tasks/${encodeURIComponent(_)}`,{body:w})}catch($){if($ instanceof h_&&$.status===404)return null;throw $}}async deleteTask(_){try{return await this.request("DELETE",`/tasks/${encodeURIComponent(_)}`),!0}catch(w){if(w instanceof h_&&w.status===404)return!1;throw w}}async listTasks(_={}){let w=new URLSearchParams;if(_.status!==void 0){let X=Array.isArray(_.status)?_.status.join(","):_.status;w.set("status",X)}if(_.parent_id!==void 0&&_.parent_id!==null)w.set("parent_id",_.parent_id);if(_.session_id!==void 0)w.set("session_id",_.session_id);if(_.owner!==void 0)w.set("owner",_.owner);if(_.tags!==void 0)w.set("tags",_.tags);if(_.search!==void 0)w.set("search",_.search);w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0));let $=await this.request("GET",`/tasks?${w}`);if(!$)throw new h_(500,"empty response");return $}async appendOperation(_){return await this.request("POST","/operations",{body:_})}async listOperations(_={}){let w=new URLSearchParams;if(_.task_id!==void 0)w.set("task_id",_.task_id);if(_.type!==void 0)w.set("type",_.type);return w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0)),await this.request("GET",`/operations?${w}`)}async verifyChain(){return(await this.request("GET","/verify"))?.valid===!0}async sendBounty(_){let w=await this.request("POST","/bounties",{body:_});if(!w)throw new h_(500,"empty bounty response");return w}async claimBounty(_){try{return await this.request("POST","/bounties/claim",{body:{agent:_}})}catch(w){if(w instanceof h_&&w.status===404)return null;throw w}}async completeBounty(_,w){try{return await this.request("POST",`/bounties/${encodeURIComponent(_)}/complete`,{body:{task_id:w}})}catch($){if($ instanceof h_&&$.status===404)return null;throw $}}async listBounties(_={}){let w=new URLSearchParams;if(_.status!==void 0)w.set("status",_.status);if(_.to!==void 0)w.set("to",_.to);return(await this.request("GET",`/bounties?${w}`))?.bounties??[]}}class e0{inner;constructor(_){this.inner=new y$(_)}createTask(..._){return this.inner.createTask(..._)}getTask(..._){return this.inner.getTask(..._)}updateTask(..._){return this.inner.updateTask(..._)}deleteTask(..._){return this.inner.deleteTask(..._)}listTasks(..._){return this.inner.listTasks(..._)}appendOperation(..._){return this.inner.appendOperation(..._)}listOperations(..._){return this.inner.listOperations(..._)}verifyChain(){return this.inner.verifyChain()}sendBounty(..._){return this.inner.sendBounty(..._)}claimBounty(..._){return this.inner.claimBounty(..._)}completeBounty(..._){return this.inner.completeBounty(..._)}listBounties(..._){return this.inner.listBounties(..._)}async close(){await this.inner.close()}}async function JK(_={}){let w=_.persistence??"local",$;if(w==="remote"){if(!_.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");$=new e0({baseUrl:_.remoteUrl,authToken:_.remoteAuthToken})}else $=await $0.create(_.localDbPath);let X={store:$,agent:_.agent??"opencode-default"};return{handlers:X1(X),store:$,async close(){await $.close()}}}var lz={id:"roy-task-plugin",async setup(_){let w=_.options??{},$=w.persistence??"local",X;if($==="remote"){if(!w.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");X=new e0({baseUrl:w.remoteUrl,authToken:w.remoteAuthToken})}else X=await $0.create(w.localDbPath);let Y={store:X,agent:w.agent??"opencode-default"},J=X1(Y),D=await UX(_,{store:X,enabled:w.royAgent!==!1,agent:"roy"}),W=await _.agent.transform(async(Q)=>{let H=Q.get("build");if(!H)return;let B=String(H.system??""),O=`
2609
2609
 
2610
2610
  # Roy Task Plugin (auto-injected by roy-task-plugin v2)
2611
2611
 
@@ -2620,7 +2620,7 @@ Mark progress on long tasks via \`task-update <id> --status <status>\`.
2620
2620
  For task-first-class-citizen work (task tree, milestones, deliverables), switch
2621
2621
  to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
2622
2622
  lifecycle as native tools.
2623
- `;q.update("build",(z)=>{if(typeof z.system==="string"||z.system===void 0)z.system=D+O})}),G=await _.command.transform((q)=>{q.add({name:"task-create",description:"Create a tracked task in roy-task-plugin store. Persists to SQLite (~/.roy-task-plugin/tasks.db) or remote service. Args: <title> [body]",template:"task-create <title> [body]",execute:async(H)=>{let B=String(H?.prompt?.text??"").trim(),D=B.split(`
2624
- `)[0]?.trim()||`task-${Date.now()}`;await J.session({type:"session.created",payload:{id:H?.sessionID??`cmd-${Date.now()}`,title:D,body:B,source:"command:task-create"}})}}),q.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),q.add({name:"task-status",description:"Show full status of a single task. Args: <id>",template:"task-status <id>",execute:async()=>{}})});return{async dispose(){for(let q of W.disposers)try{await q()}catch{}await Q.dispose(),await G.dispose(),await X.close()}}}},XK=uz;export{XK as default,wK as createRoyTaskPlugin,X2 as createHandlers,e0 as RemoteTaskStore,$0 as LocalTaskStore};
2623
+ `;Q.update("build",(z)=>{if(typeof z.system==="string"||z.system===void 0)z.system=B+O})}),G=await _.command.transform((Q)=>{Q.add({name:"task-create",description:"Create a tracked task in roy-task-plugin store. Persists to SQLite (~/.roy-task-plugin/tasks.db) or remote service. Args: <title> [body]",template:"task-create <title> [body]",execute:async(q)=>{let H=String(q?.prompt?.text??"").trim(),B=H.split(`
2624
+ `)[0]?.trim()||`task-${Date.now()}`;await J.session({type:"session.created",payload:{id:q?.sessionID??`cmd-${Date.now()}`,title:B,body:H,source:"command:task-create"}})}}),Q.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),Q.add({name:"task-status",description:"Show full status of a single task. Args: <id>",template:"task-status <id>",execute:async()=>{}})});return{async dispose(){for(let Q of D.disposers)try{await Q()}catch{}await W.dispose(),await G.dispose(),await X.close()}}}},WK=lz;export{WK as default,JK as createRoyTaskPlugin,X1 as createHandlers,e0 as RemoteTaskStore,$0 as LocalTaskStore};
2625
2625
 
2626
- //# debugId=6EB360EE2D0AAB7664756E2164756E21
2626
+ //# debugId=CBD1B9583EE82A5664756E2164756E21