@ai-setting/roy-task-plugin 0.7.14 → 0.7.16

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,141 +1,141 @@
1
1
  // @bun
2
- var e1=Object.create;var{getPrototypeOf:$Q,defineProperty:T9,getOwnPropertyNames:JQ}=Object;var QQ=Object.prototype.hasOwnProperty;function XQ($){return this[$]}var YQ,GQ,qQ=($,J,Q)=>{var X=$!=null&&typeof $==="object";if(X){var Y=J?YQ??=new WeakMap:GQ??=new WeakMap,G=Y.get($);if(G)return G}Q=$!=null?e1($Q($)):{};let q=J||!$||!$.__esModule?T9(Q,"default",{value:$,enumerable:!0}):Q;for(let W of JQ($))if(!QQ.call(q,W))T9(q,W,{get:XQ.bind($,W),enumerable:!0});if(X)Y.set($,q);return q};var C=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var WQ=($)=>$;function zQ($,J){this[$]=WQ.bind(null,J)}var HQ=($,J)=>{for(var Q in J)T9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:zQ.bind(J,Q)})};var F6=import.meta.require;var d=C((dY)=>{var H4=Symbol.for("yaml.alias"),$5=Symbol.for("yaml.document"),P6=Symbol.for("yaml.map"),J5=Symbol.for("yaml.pair"),B4=Symbol.for("yaml.scalar"),b6=Symbol.for("yaml.seq"),d0=Symbol.for("yaml.node.type"),gY=($)=>!!$&&typeof $==="object"&&$[d0]===H4,kY=($)=>!!$&&typeof $==="object"&&$[d0]===$5,mY=($)=>!!$&&typeof $==="object"&&$[d0]===P6,uY=($)=>!!$&&typeof $==="object"&&$[d0]===J5,Q5=($)=>!!$&&typeof $==="object"&&$[d0]===B4,lY=($)=>!!$&&typeof $==="object"&&$[d0]===b6;function X5($){if($&&typeof $==="object")switch($[d0]){case P6:case b6:return!0}return!1}function cY($){if($&&typeof $==="object")switch($[d0]){case H4:case P6:case B4:case b6:return!0}return!1}var pY=($)=>(Q5($)||X5($))&&!!$.anchor;dY.ALIAS=H4;dY.DOC=$5;dY.MAP=P6;dY.NODE_TYPE=d0;dY.PAIR=J5;dY.SCALAR=B4;dY.SEQ=b6;dY.hasAnchor=pY;dY.isAlias=gY;dY.isCollection=X5;dY.isDocument=kY;dY.isMap=mY;dY.isNode=cY;dY.isPair=uY;dY.isScalar=Q5;dY.isSeq=lY});var A2=C((zG)=>{var G0=d(),D0=Symbol("break visit"),Y5=Symbol("skip children"),h0=Symbol("remove node");function E6($,J){let Q=G5(J);if(G0.isDocument($)){if(a$(null,$.contents,Q,Object.freeze([$]))===h0)$.contents=null}else a$(null,$,Q,Object.freeze([]))}E6.BREAK=D0;E6.SKIP=Y5;E6.REMOVE=h0;function a$($,J,Q,X){let Y=q5($,J,Q,X);if(G0.isNode(Y)||G0.isPair(Y))return W5($,X,Y),a$($,Y,Q,X);if(typeof Y!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let q=a$(G,J.items[G],Q,X);if(typeof q==="number")G=q-1;else if(q===D0)return D0;else if(q===h0)J.items.splice(G,1),G-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let G=a$("key",J.key,Q,X);if(G===D0)return D0;else if(G===h0)J.key=null;let q=a$("value",J.value,Q,X);if(q===D0)return D0;else if(q===h0)J.value=null}}return Y}async function S6($,J){let Q=G5(J);if(G0.isDocument($)){if(await s$(null,$.contents,Q,Object.freeze([$]))===h0)$.contents=null}else await s$(null,$,Q,Object.freeze([]))}S6.BREAK=D0;S6.SKIP=Y5;S6.REMOVE=h0;async function s$($,J,Q,X){let Y=await q5($,J,Q,X);if(G0.isNode(Y)||G0.isPair(Y))return W5($,X,Y),s$($,Y,Q,X);if(typeof Y!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let q=await s$(G,J.items[G],Q,X);if(typeof q==="number")G=q-1;else if(q===D0)return D0;else if(q===h0)J.items.splice(G,1),G-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let G=await s$("key",J.key,Q,X);if(G===D0)return D0;else if(G===h0)J.key=null;let q=await s$("value",J.value,Q,X);if(q===D0)return D0;else if(q===h0)J.value=null}}return Y}function G5($){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 q5($,J,Q,X){if(typeof Q==="function")return Q($,J,X);if(G0.isMap(J))return Q.Map?.($,J,X);if(G0.isSeq(J))return Q.Seq?.($,J,X);if(G0.isPair(J))return Q.Pair?.($,J,X);if(G0.isScalar(J))return Q.Scalar?.($,J,X);if(G0.isAlias(J))return Q.Alias?.($,J,X);return}function W5($,J,Q){let X=J[J.length-1];if(G0.isCollection(X))X.items[$]=Q;else if(G0.isPair(X))if($==="key")X.key=Q;else X.value=Q;else if(G0.isDocument(X))X.contents=Q;else{let Y=G0.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${Y} parent`)}}zG.visit=E6;zG.visitAsync=S6});var U4=C((FG)=>{var z5=d(),UG=A2(),VG={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},DG=($)=>$.replace(/[!,[\]{}]/g,(J)=>VG[J]);class K0{constructor($,J){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},K0.defaultYaml,$),this.tags=Object.assign({},K0.defaultTags,J)}clone(){let $=new K0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new K0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:K0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},K0.defaultTags);break}return $}add($,J){if(this.atNextDocument)this.yaml={explicit:K0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},K0.defaultTags),this.atNextDocument=!1;let Q=$.trim().split(/[ \t]+/),X=Q.shift();switch(X){case"%TAG":{if(Q.length!==2){if(J(0,"%TAG directive should contain exactly two parts"),Q.length<2)return!1}let[Y,G]=Q;return this.tags[Y]=G,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return J(0,"%YAML directive should contain exactly one part"),!1;let[Y]=Q;if(Y==="1.1"||Y==="1.2")return this.yaml.version=Y,!0;else{let G=/^\d+\.\d+$/.test(Y);return J(6,`Unsupported YAML version ${Y}`,G),!1}}default:return J(0,`Unknown directive ${X}`,!0),!1}}tagName($,J){if($==="!")return"!";if($[0]!=="!")return J(`Not a valid tag: ${$}`),null;if($[1]==="<"){let G=$.slice(2,-1);if(G==="!"||G==="!!")return J(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")J("Verbatim tags must end with a >");return G}let[,Q,X]=$.match(/^(.*!)([^!]*)$/s);if(!X)J(`The ${$} tag has no suffix`);let Y=this.tags[Q];if(Y)try{return Y+decodeURIComponent(X)}catch(G){return J(String(G)),null}if(Q==="!")return $;return J(`Could not resolve tag: ${$}`),null}tagString($){for(let[J,Q]of Object.entries(this.tags))if($.startsWith(Q))return J+DG($.substring(Q.length));return $[0]==="!"?$:`!<${$}>`}toString($){let J=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Q=Object.entries(this.tags),X;if($&&Q.length>0&&z5.isNode($.contents)){let Y={};UG.visit($.contents,(G,q)=>{if(z5.isNode(q)&&q.tag)Y[q.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,G]of Q){if(Y==="!!"&&G==="tag:yaml.org,2002:")continue;if(!$||X.some((q)=>q.startsWith(G)))J.push(`%TAG ${Y} ${G}`)}return J.join(`
3
- `)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};FG.Directives=K0});var C6=C((LG)=>{var H5=d(),OG=A2();function KG($){if(/[\x00-\x19\s,[\]{}]/.test($)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(Q)}return!0}function B5($){let J=new Set;return OG.visit($,{Value(Q,X){if(X.anchor)J.add(X.anchor)}}),J}function U5($,J){for(let Q=1;;++Q){let X=`${$}${Q}`;if(!J.has(X))return X}}function RG($,J){let Q=[],X=new Map,Y=null;return{onAnchor:(G)=>{Q.push(G),Y??(Y=B5($));let q=U5(J,Y);return Y.add(q),q},setAnchors:()=>{for(let G of Q){let q=X.get(G);if(typeof q==="object"&&q.anchor&&(H5.isScalar(q.node)||H5.isCollection(q.node)))q.node.anchor=q.anchor;else{let W=Error("Failed to resolve repeated object (this should not happen)");throw W.source=G,W}}},sourceObjects:X}}LG.anchorIsValid=KG;LG.anchorNames=B5;LG.createNodeAnchors=RG;LG.findNewAnchor=U5});var V4=C((ZG)=>{function Z2($,J,Q,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,G=X.length;Y<G;++Y){let q=X[Y],W=Z2($,X,String(Y),q);if(W===void 0)delete X[Y];else if(W!==q)X[Y]=W}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let G=X.get(Y),q=Z2($,X,Y,G);if(q===void 0)X.delete(Y);else if(q!==G)X.set(Y,q)}else if(X instanceof Set)for(let Y of Array.from(X)){let G=Z2($,X,Y,Y);if(G===void 0)X.delete(Y);else if(G!==Y)X.delete(Y),X.add(G)}else for(let[Y,G]of Object.entries(X)){let q=Z2($,X,Y,G);if(q===void 0)delete X[Y];else if(q!==G)X[Y]=q}return $.call(J,Q,X)}ZG.applyReviver=Z2});var J$=C((bG)=>{var PG=d();function V5($,J,Q){if(Array.isArray($))return $.map((X,Y)=>V5(X,String(Y),Q));if($&&typeof $.toJSON==="function"){if(!Q||!PG.hasAnchor($))return $.toJSON(J,Q);let X={aliasCount:0,count:1,res:void 0};Q.anchors.set($,X),Q.onCreate=(G)=>{X.res=G,delete Q.onCreate};let Y=$.toJSON(J,Q);if(Q.onCreate)Q.onCreate(Y);return Y}if(typeof $==="bigint"&&!Q?.keep)return Number($);return $}bG.toJS=V5});var f6=C((fG)=>{var SG=V4(),D5=d(),CG=J$();class F5{constructor($){Object.defineProperty(this,D5.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:J,maxAliasCount:Q,onAnchor:X,reviver:Y}={}){if(!D5.isDocument($))throw TypeError("A document argument is required");let G={anchors:new Map,doc:$,keep:!0,mapAsMap:J===!0,mapKeyWarned:!1,maxAliasCount:typeof Q==="number"?Q:100},q=CG.toJS(this,"",G);if(typeof X==="function")for(let{count:W,res:z}of G.anchors.values())X(z,W);return typeof Y==="function"?SG.applyReviver(Y,{"":q},"",q):q}}fG.NodeBase=F5});var w2=C((yG)=>{var TG=C6(),vG=A2(),o$=d(),xG=f6(),hG=J$();class M5 extends xG.NodeBase{constructor($){super(o$.ALIAS);this.source=$,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve($,J){if(J?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let Q;if(J?.aliasResolveCache)Q=J.aliasResolveCache;else if(Q=[],vG.visit($,{Node:(Y,G)=>{if(o$.isAlias(G)||o$.hasAnchor(G))Q.push(G)}}),J)J.aliasResolveCache=Q;let X=void 0;for(let Y of Q){if(Y===this)break;if(Y.anchor===this.source)X=Y}if(X&&J){let{anchors:Y,doc:G,maxAliasCount:q}=J,W=Y.get(X);if(!W)hG.toJS(X,null,J),W=Y.get(X);if(W?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(q>=0){if(W.count+=1,W.aliasCount===0)W.aliasCount=I6(G,X,Y);if(W.count*W.aliasCount>q)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON($,J){if(!J)return{source:this.source};let Q=this.resolve(J.doc,J);if(!Q){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return J.anchors.get(Q).res}toString($,J,Q){let X=`*${this.source}`;if($){if(TG.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 I6($,J,Q){if(o$.isAlias(J)){let X=J.resolve($),Y=Q&&X&&Q.get(X);return Y?Y.count*Y.aliasCount:0}else if(o$.isCollection(J)){let X=0;for(let Y of J.items){let G=I6($,Y,Q);if(G>X)X=G}return X}else if(o$.isPair(J)){let X=I6($,J.key,Q),Y=I6($,J.value,Q);return Math.max(X,Y)}return 1}yG.Alias=M5});var Y0=C((cG)=>{var kG=d(),mG=f6(),uG=J$(),lG=($)=>!$||typeof $!=="function"&&typeof $!=="object";class j$ extends mG.NodeBase{constructor($){super(kG.SCALAR);this.value=$}toJSON($,J){return J?.keep?this.value:uG.toJS(this.value,$,J)}toString(){return String(this.value)}}j$.BLOCK_FOLDED="BLOCK_FOLDED";j$.BLOCK_LITERAL="BLOCK_LITERAL";j$.PLAIN="PLAIN";j$.QUOTE_DOUBLE="QUOTE_DOUBLE";j$.QUOTE_SINGLE="QUOTE_SINGLE";cG.Scalar=j$;cG.isScalarValue=lG});var P2=C((sG)=>{var iG=w2(),N$=d(),O5=Y0(),nG="tag:yaml.org,2002:";function rG($,J,Q){if(J){let X=Q.filter((G)=>G.tag===J),Y=X.find((G)=>!G.format)??X[0];if(!Y)throw Error(`Tag ${J} not found`);return Y}return Q.find((X)=>X.identify?.($)&&!X.format)}function aG($,J,Q){if(N$.isDocument($))$=$.contents;if(N$.isNode($))return $;if(N$.isPair($)){let U=Q.schema[N$.MAP].createNode?.(Q.schema,null,Q);return U.items.push($),U}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:X,onAnchor:Y,onTagObj:G,schema:q,sourceObjects:W}=Q,z=void 0;if(X&&$&&typeof $==="object")if(z=W.get($),z)return z.anchor??(z.anchor=Y($)),new iG.Alias(z.anchor);else z={anchor:null,node:null},W.set($,z);if(J?.startsWith("!!"))J=nG+J.slice(2);let H=rG($,J,q.tags);if(!H){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let U=new O5.Scalar($);if(z)z.node=U;return U}H=$ instanceof Map?q[N$.MAP]:(Symbol.iterator in Object($))?q[N$.SEQ]:q[N$.MAP]}if(G)G(H),delete Q.onTagObj;let B=H?.createNode?H.createNode(Q.schema,$,Q):typeof H?.nodeClass?.from==="function"?H.nodeClass.from(Q.schema,$,Q):new O5.Scalar($);if(J)B.tag=J;else if(!H.default)B.tag=H.tag;if(z)z.node=B;return B}sG.createNode=aG});var T6=C(($q)=>{var tG=P2(),y0=d(),eG=f6();function D4($,J,Q){let X=Q;for(let Y=J.length-1;Y>=0;--Y){let G=J[Y];if(typeof G==="number"&&Number.isInteger(G)&&G>=0){let q=[];q[G]=X,X=q}else X=new Map([[G,X]])}return tG.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var K5=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class R5 extends eG.NodeBase{constructor($,J){super($);Object.defineProperty(this,"schema",{value:J,configurable:!0,enumerable:!1,writable:!0})}clone($){let J=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if($)J.schema=$;if(J.items=J.items.map((Q)=>y0.isNode(Q)||y0.isPair(Q)?Q.clone($):Q),this.range)J.range=this.range.slice();return J}addIn($,J){if(K5($))this.add(J);else{let[Q,...X]=$,Y=this.get(Q,!0);if(y0.isCollection(Y))Y.addIn(X,J);else if(Y===void 0&&this.schema)this.set(Q,D4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}deleteIn($){let[J,...Q]=$;if(Q.length===0)return this.delete(J);let X=this.get(J,!0);if(y0.isCollection(X))return X.deleteIn(Q);else throw Error(`Expected YAML collection at ${J}. Remaining path: ${Q}`)}getIn($,J){let[Q,...X]=$,Y=this.get(Q,!0);if(X.length===0)return!J&&y0.isScalar(Y)?Y.value:Y;else return y0.isCollection(Y)?Y.getIn(X,J):void 0}hasAllNullValues($){return this.items.every((J)=>{if(!y0.isPair(J))return!1;let Q=J.value;return Q==null||$&&y0.isScalar(Q)&&Q.value==null&&!Q.commentBefore&&!Q.comment&&!Q.tag})}hasIn($){let[J,...Q]=$;if(Q.length===0)return this.has(J);let X=this.get(J,!0);return y0.isCollection(X)?X.hasIn(Q):!1}setIn($,J){let[Q,...X]=$;if(X.length===0)this.set(Q,J);else{let Y=this.get(Q,!0);if(y0.isCollection(Y))Y.setIn(X,J);else if(Y===void 0&&this.schema)this.set(Q,D4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}}$q.Collection=R5;$q.collectionFromPath=D4;$q.isEmptyPath=K5});var b2=C((qq)=>{var Yq=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function F4($,J){if(/^\n+$/.test($))return $.substring(1);return J?$.replace(/^(?! *$)/gm,J):$}var Gq=($,J,Q)=>$.endsWith(`
4
- `)?F4(Q,J):Q.includes(`
2
+ var WQ=Object.create;var{getPrototypeOf:zQ,defineProperty:h9,getOwnPropertyNames:HQ}=Object;var BQ=Object.prototype.hasOwnProperty;function UQ($){return this[$]}var VQ,DQ,FQ=($,J,Q)=>{var X=$!=null&&typeof $==="object";if(X){var q=J?VQ??=new WeakMap:DQ??=new WeakMap,Y=q.get($);if(Y)return Y}Q=$!=null?WQ(zQ($)):{};let G=J||!$||!$.__esModule?h9(Q,"default",{value:$,enumerable:!0}):Q;for(let W of HQ($))if(!BQ.call(G,W))h9(G,W,{get:UQ.bind($,W),enumerable:!0});if(X)q.set($,G);return G};var S=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var MQ=($)=>$;function OQ($,J){this[$]=MQ.bind(null,J)}var KQ=($,J)=>{for(var Q in J)h9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:OQ.bind(J,Q)})};var j6=import.meta.require;var p=S((eq)=>{var D4=Symbol.for("yaml.alias"),W7=Symbol.for("yaml.document"),C6=Symbol.for("yaml.map"),z7=Symbol.for("yaml.pair"),F4=Symbol.for("yaml.scalar"),f6=Symbol.for("yaml.seq"),s0=Symbol.for("yaml.node.type"),iq=($)=>!!$&&typeof $==="object"&&$[s0]===D4,nq=($)=>!!$&&typeof $==="object"&&$[s0]===W7,rq=($)=>!!$&&typeof $==="object"&&$[s0]===C6,aq=($)=>!!$&&typeof $==="object"&&$[s0]===z7,H7=($)=>!!$&&typeof $==="object"&&$[s0]===F4,sq=($)=>!!$&&typeof $==="object"&&$[s0]===f6;function B7($){if($&&typeof $==="object")switch($[s0]){case C6:case f6:return!0}return!1}function oq($){if($&&typeof $==="object")switch($[s0]){case D4:case C6:case F4:case f6:return!0}return!1}var tq=($)=>(H7($)||B7($))&&!!$.anchor;eq.ALIAS=D4;eq.DOC=W7;eq.MAP=C6;eq.NODE_TYPE=s0;eq.PAIR=z7;eq.SCALAR=F4;eq.SEQ=f6;eq.hasAnchor=tq;eq.isAlias=iq;eq.isCollection=B7;eq.isDocument=nq;eq.isMap=rq;eq.isNode=oq;eq.isPair=aq;eq.isScalar=H7;eq.isSeq=sq});var S2=S((OY)=>{var G0=p(),F0=Symbol("break visit"),U7=Symbol("skip children"),l0=Symbol("remove node");function I6($,J){let Q=V7(J);if(G0.isDocument($)){if($2(null,$.contents,Q,Object.freeze([$]))===l0)$.contents=null}else $2(null,$,Q,Object.freeze([]))}I6.BREAK=F0;I6.SKIP=U7;I6.REMOVE=l0;function $2($,J,Q,X){let q=D7($,J,Q,X);if(G0.isNode(q)||G0.isPair(q))return F7($,X,q),$2($,q,Q,X);if(typeof q!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let Y=0;Y<J.items.length;++Y){let G=$2(Y,J.items[Y],Q,X);if(typeof G==="number")Y=G-1;else if(G===F0)return F0;else if(G===l0)J.items.splice(Y,1),Y-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let Y=$2("key",J.key,Q,X);if(Y===F0)return F0;else if(Y===l0)J.key=null;let G=$2("value",J.value,Q,X);if(G===F0)return F0;else if(G===l0)J.value=null}}return q}async function T6($,J){let Q=V7(J);if(G0.isDocument($)){if(await J2(null,$.contents,Q,Object.freeze([$]))===l0)$.contents=null}else await J2(null,$,Q,Object.freeze([]))}T6.BREAK=F0;T6.SKIP=U7;T6.REMOVE=l0;async function J2($,J,Q,X){let q=await D7($,J,Q,X);if(G0.isNode(q)||G0.isPair(q))return F7($,X,q),J2($,q,Q,X);if(typeof q!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let Y=0;Y<J.items.length;++Y){let G=await J2(Y,J.items[Y],Q,X);if(typeof G==="number")Y=G-1;else if(G===F0)return F0;else if(G===l0)J.items.splice(Y,1),Y-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let Y=await J2("key",J.key,Q,X);if(Y===F0)return F0;else if(Y===l0)J.key=null;let G=await J2("value",J.value,Q,X);if(G===F0)return F0;else if(G===l0)J.value=null}}return q}function V7($){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 D7($,J,Q,X){if(typeof Q==="function")return Q($,J,X);if(G0.isMap(J))return Q.Map?.($,J,X);if(G0.isSeq(J))return Q.Seq?.($,J,X);if(G0.isPair(J))return Q.Pair?.($,J,X);if(G0.isScalar(J))return Q.Scalar?.($,J,X);if(G0.isAlias(J))return Q.Alias?.($,J,X);return}function F7($,J,Q){let X=J[J.length-1];if(G0.isCollection(X))X.items[$]=Q;else if(G0.isPair(X))if($==="key")X.key=Q;else X.value=Q;else if(G0.isDocument(X))X.contents=Q;else{let q=G0.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${q} parent`)}}OY.visit=I6;OY.visitAsync=T6});var M4=S((_Y)=>{var M7=p(),LY=S2(),NY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},AY=($)=>$.replace(/[!,[\]{}]/g,(J)=>NY[J]);class A0{constructor($,J){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},A0.defaultYaml,$),this.tags=Object.assign({},A0.defaultTags,J)}clone(){let $=new A0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new A0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:A0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},A0.defaultTags);break}return $}add($,J){if(this.atNextDocument)this.yaml={explicit:A0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},A0.defaultTags),this.atNextDocument=!1;let Q=$.trim().split(/[ \t]+/),X=Q.shift();switch(X){case"%TAG":{if(Q.length!==2){if(J(0,"%TAG directive should contain exactly two parts"),Q.length<2)return!1}let[q,Y]=Q;return this.tags[q]=Y,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return J(0,"%YAML directive should contain exactly one part"),!1;let[q]=Q;if(q==="1.1"||q==="1.2")return this.yaml.version=q,!0;else{let Y=/^\d+\.\d+$/.test(q);return J(6,`Unsupported YAML version ${q}`,Y),!1}}default:return J(0,`Unknown directive ${X}`,!0),!1}}tagName($,J){if($==="!")return"!";if($[0]!=="!")return J(`Not a valid tag: ${$}`),null;if($[1]==="<"){let Y=$.slice(2,-1);if(Y==="!"||Y==="!!")return J(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")J("Verbatim tags must end with a >");return Y}let[,Q,X]=$.match(/^(.*!)([^!]*)$/s);if(!X)J(`The ${$} tag has no suffix`);let q=this.tags[Q];if(q)try{return q+decodeURIComponent(X)}catch(Y){return J(String(Y)),null}if(Q==="!")return $;return J(`Could not resolve tag: ${$}`),null}tagString($){for(let[J,Q]of Object.entries(this.tags))if($.startsWith(Q))return J+AY($.substring(Q.length));return $[0]==="!"?$:`!<${$}>`}toString($){let J=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],Q=Object.entries(this.tags),X;if($&&Q.length>0&&M7.isNode($.contents)){let q={};LY.visit($.contents,(Y,G)=>{if(M7.isNode(G)&&G.tag)q[G.tag]=!0}),X=Object.keys(q)}else X=[];for(let[q,Y]of Q){if(q==="!!"&&Y==="tag:yaml.org,2002:")continue;if(!$||X.some((G)=>G.startsWith(Y)))J.push(`%TAG ${q} ${Y}`)}return J.join(`
3
+ `)}}A0.defaultYaml={explicit:!1,version:"1.2"};A0.defaultTags={"!!":"tag:yaml.org,2002:"};_Y.Directives=A0});var v6=S((bY)=>{var O7=p(),ZY=S2();function wY($){if(/[\x00-\x19\s,[\]{}]/.test($)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(Q)}return!0}function K7($){let J=new Set;return ZY.visit($,{Value(Q,X){if(X.anchor)J.add(X.anchor)}}),J}function j7($,J){for(let Q=1;;++Q){let X=`${$}${Q}`;if(!J.has(X))return X}}function PY($,J){let Q=[],X=new Map,q=null;return{onAnchor:(Y)=>{Q.push(Y),q??(q=K7($));let G=j7(J,q);return q.add(G),G},setAnchors:()=>{for(let Y of Q){let G=X.get(Y);if(typeof G==="object"&&G.anchor&&(O7.isScalar(G.node)||O7.isCollection(G.node)))G.node.anchor=G.anchor;else{let W=Error("Failed to resolve repeated object (this should not happen)");throw W.source=Y,W}}},sourceObjects:X}}bY.anchorIsValid=wY;bY.anchorNames=K7;bY.createNodeAnchors=PY;bY.findNewAnchor=j7});var O4=S((IY)=>{function C2($,J,Q,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let q=0,Y=X.length;q<Y;++q){let G=X[q],W=C2($,X,String(q),G);if(W===void 0)delete X[q];else if(W!==G)X[q]=W}else if(X instanceof Map)for(let q of Array.from(X.keys())){let Y=X.get(q),G=C2($,X,q,Y);if(G===void 0)X.delete(q);else if(G!==Y)X.set(q,G)}else if(X instanceof Set)for(let q of Array.from(X)){let Y=C2($,X,q,q);if(Y===void 0)X.delete(q);else if(Y!==q)X.delete(q),X.add(Y)}else for(let[q,Y]of Object.entries(X)){let G=C2($,X,q,Y);if(G===void 0)delete X[q];else if(G!==Y)X[q]=G}return $.call(J,Q,X)}IY.applyReviver=C2});var Y$=S((xY)=>{var vY=p();function L7($,J,Q){if(Array.isArray($))return $.map((X,q)=>L7(X,String(q),Q));if($&&typeof $.toJSON==="function"){if(!Q||!vY.hasAnchor($))return $.toJSON(J,Q);let X={aliasCount:0,count:1,res:void 0};Q.anchors.set($,X),Q.onCreate=(Y)=>{X.res=Y,delete Q.onCreate};let q=$.toJSON(J,Q);if(Q.onCreate)Q.onCreate(q);return q}if(typeof $==="bigint"&&!Q?.keep)return Number($);return $}xY.toJS=L7});var x6=S((kY)=>{var hY=O4(),N7=p(),gY=Y$();class A7{constructor($){Object.defineProperty(this,N7.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:J,maxAliasCount:Q,onAnchor:X,reviver:q}={}){if(!N7.isDocument($))throw TypeError("A document argument is required");let Y={anchors:new Map,doc:$,keep:!0,mapAsMap:J===!0,mapKeyWarned:!1,maxAliasCount:typeof Q==="number"?Q:100},G=gY.toJS(this,"",Y);if(typeof X==="function")for(let{count:W,res:z}of Y.anchors.values())X(z,W);return typeof q==="function"?hY.applyReviver(q,{"":G},"",G):G}}kY.NodeBase=A7});var f2=S((pY)=>{var uY=v6(),lY=S2(),Q2=p(),cY=x6(),dY=Y$();class _7 extends cY.NodeBase{constructor($){super(Q2.ALIAS);this.source=$,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve($,J){if(J?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let Q;if(J?.aliasResolveCache)Q=J.aliasResolveCache;else if(Q=[],lY.visit($,{Node:(q,Y)=>{if(Q2.isAlias(Y)||Q2.hasAnchor(Y))Q.push(Y)}}),J)J.aliasResolveCache=Q;let X=void 0;for(let q of Q){if(q===this)break;if(q.anchor===this.source)X=q}if(X&&J){let{anchors:q,doc:Y,maxAliasCount:G}=J,W=q.get(X);if(!W)dY.toJS(X,null,J),W=q.get(X);if(W?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(G>=0){if(W.count+=1,W.aliasCount===0)W.aliasCount=y6(Y,X,q);if(W.count*W.aliasCount>G)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON($,J){if(!J)return{source:this.source};let Q=this.resolve(J.doc,J);if(!Q){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return J.anchors.get(Q).res}toString($,J,Q){let X=`*${this.source}`;if($){if(uY.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let q=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(q)}if($.implicitKey)return`${X} `}return X}}function y6($,J,Q){if(Q2.isAlias(J)){let X=J.resolve($),q=Q&&X&&Q.get(X);return q?q.count*q.aliasCount:0}else if(Q2.isCollection(J)){let X=0;for(let q of J.items){let Y=y6($,q,Q);if(Y>X)X=Y}return X}else if(Q2.isPair(J)){let X=y6($,J.key,Q),q=y6($,J.value,Q);return Math.max(X,q)}return 1}pY.Alias=_7});var Y0=S((oY)=>{var nY=p(),rY=x6(),aY=Y$(),sY=($)=>!$||typeof $!=="function"&&typeof $!=="object";class P$ extends rY.NodeBase{constructor($){super(nY.SCALAR);this.value=$}toJSON($,J){return J?.keep?this.value:aY.toJS(this.value,$,J)}toString(){return String(this.value)}}P$.BLOCK_FOLDED="BLOCK_FOLDED";P$.BLOCK_LITERAL="BLOCK_LITERAL";P$.PLAIN="PLAIN";P$.QUOTE_DOUBLE="QUOTE_DOUBLE";P$.QUOTE_SINGLE="QUOTE_SINGLE";oY.Scalar=P$;oY.isScalarValue=sY});var I2=S((qG)=>{var $G=f2(),b$=p(),R7=Y0(),JG="tag:yaml.org,2002:";function QG($,J,Q){if(J){let X=Q.filter((Y)=>Y.tag===J),q=X.find((Y)=>!Y.format)??X[0];if(!q)throw Error(`Tag ${J} not found`);return q}return Q.find((X)=>X.identify?.($)&&!X.format)}function XG($,J,Q){if(b$.isDocument($))$=$.contents;if(b$.isNode($))return $;if(b$.isPair($)){let U=Q.schema[b$.MAP].createNode?.(Q.schema,null,Q);return U.items.push($),U}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:X,onAnchor:q,onTagObj:Y,schema:G,sourceObjects:W}=Q,z=void 0;if(X&&$&&typeof $==="object")if(z=W.get($),z)return z.anchor??(z.anchor=q($)),new $G.Alias(z.anchor);else z={anchor:null,node:null},W.set($,z);if(J?.startsWith("!!"))J=JG+J.slice(2);let H=QG($,J,G.tags);if(!H){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let U=new R7.Scalar($);if(z)z.node=U;return U}H=$ instanceof Map?G[b$.MAP]:(Symbol.iterator in Object($))?G[b$.SEQ]:G[b$.MAP]}if(Y)Y(H),delete Q.onTagObj;let B=H?.createNode?H.createNode(Q.schema,$,Q):typeof H?.nodeClass?.from==="function"?H.nodeClass.from(Q.schema,$,Q):new R7.Scalar($);if(J)B.tag=J;else if(!H.default)B.tag=H.tag;if(z)z.node=B;return B}qG.createNode=XG});var h6=S((zG)=>{var GG=I2(),c0=p(),WG=x6();function K4($,J,Q){let X=Q;for(let q=J.length-1;q>=0;--q){let Y=J[q];if(typeof Y==="number"&&Number.isInteger(Y)&&Y>=0){let G=[];G[Y]=X,X=G}else X=new Map([[Y,X]])}return GG.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var Z7=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class w7 extends WG.NodeBase{constructor($,J){super($);Object.defineProperty(this,"schema",{value:J,configurable:!0,enumerable:!1,writable:!0})}clone($){let J=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if($)J.schema=$;if(J.items=J.items.map((Q)=>c0.isNode(Q)||c0.isPair(Q)?Q.clone($):Q),this.range)J.range=this.range.slice();return J}addIn($,J){if(Z7($))this.add(J);else{let[Q,...X]=$,q=this.get(Q,!0);if(c0.isCollection(q))q.addIn(X,J);else if(q===void 0&&this.schema)this.set(Q,K4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}deleteIn($){let[J,...Q]=$;if(Q.length===0)return this.delete(J);let X=this.get(J,!0);if(c0.isCollection(X))return X.deleteIn(Q);else throw Error(`Expected YAML collection at ${J}. Remaining path: ${Q}`)}getIn($,J){let[Q,...X]=$,q=this.get(Q,!0);if(X.length===0)return!J&&c0.isScalar(q)?q.value:q;else return c0.isCollection(q)?q.getIn(X,J):void 0}hasAllNullValues($){return this.items.every((J)=>{if(!c0.isPair(J))return!1;let Q=J.value;return Q==null||$&&c0.isScalar(Q)&&Q.value==null&&!Q.commentBefore&&!Q.comment&&!Q.tag})}hasIn($){let[J,...Q]=$;if(Q.length===0)return this.has(J);let X=this.get(J,!0);return c0.isCollection(X)?X.hasIn(Q):!1}setIn($,J){let[Q,...X]=$;if(X.length===0)this.set(Q,J);else{let q=this.get(Q,!0);if(c0.isCollection(q))q.setIn(X,J);else if(q===void 0&&this.schema)this.set(Q,K4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}}zG.Collection=w7;zG.collectionFromPath=K4;zG.isEmptyPath=Z7});var T2=S((FG)=>{var VG=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function j4($,J){if(/^\n+$/.test($))return $.substring(1);return J?$.replace(/^(?! *$)/gm,J):$}var DG=($,J,Q)=>$.endsWith(`
4
+ `)?j4(Q,J):Q.includes(`
5
5
  `)?`
6
- `+F4(Q,J):($.endsWith(" ")?"":" ")+Q;qq.indentComment=F4;qq.lineComment=Gq;qq.stringifyComment=Yq});var j5=C((Uq)=>{function Bq($,J,Q="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:G=20,onFold:q,onOverflow:W}={}){if(!Y||Y<0)return $;if(Y<G)G=0;let z=Math.max(1+G,1+Y-J.length);if($.length<=z)return $;let H=[],B={},U=Y-J.length;if(typeof X==="number")if(X>Y-Math.max(2,G))H.push(0);else U=Y-X;let V=void 0,O=void 0,F=!1,D=-1,M=-1,R=-1;if(Q==="block"){if(D=L5($,D,J.length),D!==-1)U=D+z}for(let N;N=$[D+=1];){if(Q==="quoted"&&N==="\\"){switch(M=D,$[D+1]){case"x":D+=3;break;case"u":D+=5;break;case"U":D+=9;break;default:D+=1}R=D}if(N===`
7
- `){if(Q==="block")D=L5($,D,J.length);U=D+J.length+z,V=void 0}else{if(N===" "&&O&&O!==" "&&O!==`
8
- `&&O!=="\t"){let Z=$[D+1];if(Z&&Z!==" "&&Z!==`
9
- `&&Z!=="\t")V=D}if(D>=U)if(V)H.push(V),U=V+z,V=void 0;else if(Q==="quoted"){while(O===" "||O==="\t")O=N,N=$[D+=1],F=!0;let Z=D>R+1?D-2:M-1;if(B[Z])return $;H.push(Z),B[Z]=!0,U=Z+z,V=void 0}else F=!0}O=N}if(F&&W)W();if(H.length===0)return $;if(q)q();let L=$.slice(0,H[0]);for(let N=0;N<H.length;++N){let Z=H[N],b=H[N+1]||$.length;if(Z===0)L=`
10
- ${J}${$.slice(0,b)}`;else{if(Q==="quoted"&&B[Z])L+=`${$[Z]}\\`;L+=`
11
- ${J}${$.slice(Z+1,b)}`}}return L}function L5($,J,Q){let X=J,Y=J+1,G=$[Y];while(G===" "||G==="\t")if(J<Y+Q)G=$[++J];else{do G=$[++J];while(G&&G!==`
12
- `);X=J,Y=J+1,G=$[Y]}return X}Uq.FOLD_BLOCK="block";Uq.FOLD_FLOW="flow";Uq.FOLD_QUOTED="quoted";Uq.foldFlowLines=Bq});var S2=C((Lq)=>{var b0=Y0(),Q$=j5(),x6=($,J)=>({indentAtStart:J?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),h6=($)=>/^(%|---|\.\.\.)/m.test($);function Oq($,J,Q){if(!J||J<0)return!1;let X=J-Q,Y=$.length;if(Y<=X)return!1;for(let G=0,q=0;G<Y;++G)if($[G]===`
13
- `){if(G-q>X)return!0;if(q=G+1,Y-q<=X)return!1}return!0}function E2($,J){let Q=JSON.stringify($);if(J.options.doubleQuotedAsJSON)return Q;let{implicitKey:X}=J,Y=J.options.doubleQuotedMinMultiLineLength,G=J.indent||(h6($)?" ":""),q="",W=0;for(let z=0,H=Q[z];H;H=Q[++z]){if(H===" "&&Q[z+1]==="\\"&&Q[z+2]==="n")q+=Q.slice(W,z)+"\\ ",z+=1,W=z,H="\\";if(H==="\\")switch(Q[z+1]){case"u":{q+=Q.slice(W,z);let B=Q.substr(z+2,4);switch(B){case"0000":q+="\\0";break;case"0007":q+="\\a";break;case"000b":q+="\\v";break;case"001b":q+="\\e";break;case"0085":q+="\\N";break;case"00a0":q+="\\_";break;case"2028":q+="\\L";break;case"2029":q+="\\P";break;default:if(B.substr(0,2)==="00")q+="\\x"+B.substr(2);else q+=Q.substr(z,6)}z+=5,W=z+1}break;case"n":if(X||Q[z+2]==='"'||Q.length<Y)z+=1;else{q+=Q.slice(W,z)+`
14
-
15
- `;while(Q[z+2]==="\\"&&Q[z+3]==="n"&&Q[z+4]!=='"')q+=`
16
- `,z+=2;if(q+=G,Q[z+2]===" ")q+="\\";z+=1,W=z+1}break;default:z+=1}}return q=W?q+Q.slice(W):Q,X?q:Q$.foldFlowLines(q,G,Q$.FOLD_QUOTED,x6(J,!1))}function M4($,J){if(J.options.singleQuote===!1||J.implicitKey&&$.includes(`
17
- `)||/[ \t]\n|\n[ \t]/.test($))return E2($,J);let Q=J.indent||(h6($)?" ":""),X="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
18
- ${Q}`)+"'";return J.implicitKey?X:Q$.foldFlowLines(X,Q,Q$.FOLD_FLOW,x6(J,!1))}function t$($,J){let{singleQuote:Q}=J.options,X;if(Q===!1)X=E2;else{let Y=$.includes('"'),G=$.includes("'");if(Y&&!G)X=M4;else if(G&&!Y)X=E2;else X=Q?M4:E2}return X($,J)}var O4;try{O4=new RegExp(`(^|(?<!
6
+ `+j4(Q,J):($.endsWith(" ")?"":" ")+Q;FG.indentComment=j4;FG.lineComment=DG;FG.stringifyComment=VG});var b7=S((LG)=>{function jG($,J,Q="flow",{indentAtStart:X,lineWidth:q=80,minContentWidth:Y=20,onFold:G,onOverflow:W}={}){if(!q||q<0)return $;if(q<Y)Y=0;let z=Math.max(1+Y,1+q-J.length);if($.length<=z)return $;let H=[],B={},U=q-J.length;if(typeof X==="number")if(X>q-Math.max(2,Y))H.push(0);else U=q-X;let V=void 0,O=void 0,F=!1,D=-1,M=-1,j=-1;if(Q==="block"){if(D=P7($,D,J.length),D!==-1)U=D+z}for(let A;A=$[D+=1];){if(Q==="quoted"&&A==="\\"){switch(M=D,$[D+1]){case"x":D+=3;break;case"u":D+=5;break;case"U":D+=9;break;default:D+=1}j=D}if(A===`
7
+ `){if(Q==="block")D=P7($,D,J.length);U=D+J.length+z,V=void 0}else{if(A===" "&&O&&O!==" "&&O!==`
8
+ `&&O!=="\t"){let R=$[D+1];if(R&&R!==" "&&R!==`
9
+ `&&R!=="\t")V=D}if(D>=U)if(V)H.push(V),U=V+z,V=void 0;else if(Q==="quoted"){while(O===" "||O==="\t")O=A,A=$[D+=1],F=!0;let R=D>j+1?D-2:M-1;if(B[R])return $;H.push(R),B[R]=!0,U=R+z,V=void 0}else F=!0}O=A}if(F&&W)W();if(H.length===0)return $;if(G)G();let L=$.slice(0,H[0]);for(let A=0;A<H.length;++A){let R=H[A],b=H[A+1]||$.length;if(R===0)L=`
10
+ ${J}${$.slice(0,b)}`;else{if(Q==="quoted"&&B[R])L+=`${$[R]}\\`;L+=`
11
+ ${J}${$.slice(R+1,b)}`}}return L}function P7($,J,Q){let X=J,q=J+1,Y=$[q];while(Y===" "||Y==="\t")if(J<q+Q)Y=$[++J];else{do Y=$[++J];while(Y&&Y!==`
12
+ `);X=J,q=J+1,Y=$[q]}return X}LG.FOLD_BLOCK="block";LG.FOLD_FLOW="flow";LG.FOLD_QUOTED="quoted";LG.foldFlowLines=jG});var x2=S((bG)=>{var f0=Y0(),G$=b7(),k6=($,J)=>({indentAtStart:J?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),m6=($)=>/^(%|---|\.\.\.)/m.test($);function ZG($,J,Q){if(!J||J<0)return!1;let X=J-Q,q=$.length;if(q<=X)return!1;for(let Y=0,G=0;Y<q;++Y)if($[Y]===`
13
+ `){if(Y-G>X)return!0;if(G=Y+1,q-G<=X)return!1}return!0}function v2($,J){let Q=JSON.stringify($);if(J.options.doubleQuotedAsJSON)return Q;let{implicitKey:X}=J,q=J.options.doubleQuotedMinMultiLineLength,Y=J.indent||(m6($)?" ":""),G="",W=0;for(let z=0,H=Q[z];H;H=Q[++z]){if(H===" "&&Q[z+1]==="\\"&&Q[z+2]==="n")G+=Q.slice(W,z)+"\\ ",z+=1,W=z,H="\\";if(H==="\\")switch(Q[z+1]){case"u":{G+=Q.slice(W,z);let B=Q.substr(z+2,4);switch(B){case"0000":G+="\\0";break;case"0007":G+="\\a";break;case"000b":G+="\\v";break;case"001b":G+="\\e";break;case"0085":G+="\\N";break;case"00a0":G+="\\_";break;case"2028":G+="\\L";break;case"2029":G+="\\P";break;default:if(B.substr(0,2)==="00")G+="\\x"+B.substr(2);else G+=Q.substr(z,6)}z+=5,W=z+1}break;case"n":if(X||Q[z+2]==='"'||Q.length<q)z+=1;else{G+=Q.slice(W,z)+`
14
+
15
+ `;while(Q[z+2]==="\\"&&Q[z+3]==="n"&&Q[z+4]!=='"')G+=`
16
+ `,z+=2;if(G+=Y,Q[z+2]===" ")G+="\\";z+=1,W=z+1}break;default:z+=1}}return G=W?G+Q.slice(W):Q,X?G:G$.foldFlowLines(G,Y,G$.FOLD_QUOTED,k6(J,!1))}function L4($,J){if(J.options.singleQuote===!1||J.implicitKey&&$.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test($))return v2($,J);let Q=J.indent||(m6($)?" ":""),X="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${Q}`)+"'";return J.implicitKey?X:G$.foldFlowLines(X,Q,G$.FOLD_FLOW,k6(J,!1))}function X2($,J){let{singleQuote:Q}=J.options,X;if(Q===!1)X=v2;else{let q=$.includes('"'),Y=$.includes("'");if(q&&!Y)X=L4;else if(Y&&!q)X=v2;else X=Q?L4:v2}return X($,J)}var N4;try{N4=new RegExp(`(^|(?<!
19
19
  ))
20
20
  +(?!
21
- |$)`,"g")}catch{O4=/\n+(?!\n|$)/g}function v6({comment:$,type:J,value:Q},X,Y,G){let{blockQuote:q,commentString:W,lineWidth:z}=X.options;if(!q||/\n[\t ]+$/.test(Q))return t$(Q,X);let H=X.indent||(X.forceBlockIndent||h6(Q)?" ":""),B=q==="literal"?!0:q==="folded"||J===b0.Scalar.BLOCK_FOLDED?!1:J===b0.Scalar.BLOCK_LITERAL?!0:!Oq(Q,z,H.length);if(!Q)return B?`|
21
+ |$)`,"g")}catch{N4=/\n+(?!\n|$)/g}function g6({comment:$,type:J,value:Q},X,q,Y){let{blockQuote:G,commentString:W,lineWidth:z}=X.options;if(!G||/\n[\t ]+$/.test(Q))return X2(Q,X);let H=X.indent||(X.forceBlockIndent||m6(Q)?" ":""),B=G==="literal"?!0:G==="folded"||J===f0.Scalar.BLOCK_FOLDED?!1:J===f0.Scalar.BLOCK_LITERAL?!0:!ZG(Q,z,H.length);if(!Q)return B?`|
22
22
  `:`>
23
23
  `;let U,V;for(V=Q.length;V>0;--V){let b=Q[V-1];if(b!==`
24
24
  `&&b!=="\t"&&b!==" ")break}let O=Q.substring(V),F=O.indexOf(`
25
- `);if(F===-1)U="-";else if(Q===O||F!==O.length-1){if(U="+",G)G()}else U="";if(O){if(Q=Q.slice(0,-O.length),O[O.length-1]===`
26
- `)O=O.slice(0,-1);O=O.replace(O4,`$&${H}`)}let D=!1,M,R=-1;for(M=0;M<Q.length;++M){let b=Q[M];if(b===" ")D=!0;else if(b===`
27
- `)R=M;else break}let L=Q.substring(0,R<M?R+1:M);if(L)Q=Q.substring(L.length),L=L.replace(/\n+/g,`$&${H}`);let Z=(D?H?"2":"1":"")+U;if($){if(Z+=" "+W($.replace(/ ?[\r\n]+/g," ")),Y)Y()}if(!B){let b=Q.replace(/\n+/g,`
28
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${H}`),w=!1,f=x6(X,!0);if(q!=="folded"&&J!==b0.Scalar.BLOCK_FOLDED)f.onOverflow=()=>{w=!0};let A=Q$.foldFlowLines(`${L}${b}${O}`,H,Q$.FOLD_BLOCK,f);if(!w)return`>${Z}
29
- ${H}${A}`}return Q=Q.replace(/\n+/g,`$&${H}`),`|${Z}
30
- ${H}${L}${Q}${O}`}function Kq($,J,Q,X){let{type:Y,value:G}=$,{actualString:q,implicitKey:W,indent:z,indentStep:H,inFlow:B}=J;if(W&&G.includes(`
31
- `)||B&&/[[\]{},]/.test(G))return t$(G,J);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(G))return W||B||!G.includes(`
32
- `)?t$(G,J):v6($,J,Q,X);if(!W&&!B&&Y!==b0.Scalar.PLAIN&&G.includes(`
33
- `))return v6($,J,Q,X);if(h6(G)){if(z==="")return J.forceBlockIndent=!0,v6($,J,Q,X);else if(W&&z===H)return t$(G,J)}let U=G.replace(/\n+/g,`$&
34
- ${z}`);if(q){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(U),{compat:O,tags:F}=J.doc.schema;if(F.some(V)||O?.some(V))return t$(G,J)}return W?U:Q$.foldFlowLines(U,z,Q$.FOLD_FLOW,x6(J,!1))}function Rq($,J,Q,X){let{implicitKey:Y,inFlow:G}=J,q=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:W}=$;if(W!==b0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(q.value))W=b0.Scalar.QUOTE_DOUBLE}let z=(B)=>{switch(B){case b0.Scalar.BLOCK_FOLDED:case b0.Scalar.BLOCK_LITERAL:return Y||G?t$(q.value,J):v6(q,J,Q,X);case b0.Scalar.QUOTE_DOUBLE:return E2(q.value,J);case b0.Scalar.QUOTE_SINGLE:return M4(q.value,J);case b0.Scalar.PLAIN:return Kq(q,J,Q,X);default:return null}},H=z(W);if(H===null){let{defaultKeyType:B,defaultStringType:U}=J.options,V=Y&&B||U;if(H=z(V),H===null)throw Error(`Unsupported default string type ${V}`)}return H}Lq.stringifyString=Rq});var C2=C((Eq)=>{var Nq=C6(),X$=d(),_q=b2(),Aq=S2();function Zq($,J){let Q=Object.assign({blockQuote:!0,commentString:_q.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,J),X;switch(Q.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:$,flowCollectionPadding:Q.flowCollectionPadding?" ":"",indent:"",indentStep:typeof Q.indent==="number"?" ".repeat(Q.indent):" ",inFlow:X,options:Q}}function wq($,J){if(J.tag){let Y=$.filter((G)=>G.tag===J.tag);if(Y.length>0)return Y.find((G)=>G.format===J.format)??Y[0]}let Q=void 0,X;if(X$.isScalar(J)){X=J.value;let Y=$.filter((G)=>G.identify?.(X));if(Y.length>1){let G=Y.filter((q)=>q.test);if(G.length>0)Y=G}Q=Y.find((G)=>G.format===J.format)??Y.find((G)=>!G.format)}else X=J,Q=$.find((Y)=>Y.nodeClass&&X instanceof Y.nodeClass);if(!Q){let Y=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${Y} value`)}return Q}function Pq($,J,{anchors:Q,doc:X}){if(!X.directives)return"";let Y=[],G=(X$.isScalar($)||X$.isCollection($))&&$.anchor;if(G&&Nq.anchorIsValid(G))Q.add(G),Y.push(`&${G}`);let q=$.tag??(J.default?null:J.tag);if(q)Y.push(X.directives.tagString(q));return Y.join(" ")}function bq($,J,Q,X){if(X$.isPair($))return $.toString(J,Q,X);if(X$.isAlias($)){if(J.doc.directives)return $.toString(J);if(J.resolvedAliases?.has($))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(J.resolvedAliases)J.resolvedAliases.add($);else J.resolvedAliases=new Set([$]);$=$.resolve(J.doc)}}let Y=void 0,G=X$.isNode($)?$:J.doc.createNode($,{onTagObj:(z)=>Y=z});Y??(Y=wq(J.doc.schema.tags,G));let q=Pq(G,Y,J);if(q.length>0)J.indentAtStart=(J.indentAtStart??0)+q.length+1;let W=typeof Y.stringify==="function"?Y.stringify(G,J,Q,X):X$.isScalar(G)?Aq.stringifyString(G,J,Q,X):G.toString(J,Q,X);if(!q)return W;return X$.isScalar(G)||W[0]==="{"||W[0]==="["?`${q} ${W}`:`${q}
35
- ${J.indent}${W}`}Eq.createStringifyContext=Zq;Eq.stringify=bq});var A5=C((Iq)=>{var i0=d(),N5=Y0(),_5=C2(),f2=b2();function fq({key:$,value:J},Q,X,Y){let{allNullValues:G,doc:q,indent:W,indentStep:z,options:{commentString:H,indentSeq:B,simpleKeys:U}}=Q,V=i0.isNode($)&&$.comment||null;if(U){if(V)throw Error("With simple keys, key nodes cannot have comments");if(i0.isCollection($)||!i0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!U&&(!$||V&&J==null&&!Q.inFlow||i0.isCollection($)||(i0.isScalar($)?$.type===N5.Scalar.BLOCK_FOLDED||$.type===N5.Scalar.BLOCK_LITERAL:typeof $==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!O&&(U||!G),indent:W+z});let F=!1,D=!1,M=_5.stringify($,Q,()=>F=!0,()=>D=!0);if(!O&&!Q.inFlow&&M.length>1024){if(U)throw Error("With simple keys, single line scalar must not span more than 1024 characters");O=!0}if(Q.inFlow){if(G||J==null){if(F&&X)X();return M===""?"?":O?`? ${M}`:M}}else if(G&&!U||J==null&&O){if(M=`? ${M}`,V&&!F)M+=f2.lineComment(M,Q.indent,H(V));else if(D&&Y)Y();return M}if(F)V=null;if(O){if(V)M+=f2.lineComment(M,Q.indent,H(V));M=`? ${M}
36
- ${W}:`}else if(M=`${M}:`,V)M+=f2.lineComment(M,Q.indent,H(V));let R,L,N;if(i0.isNode(J))R=!!J.spaceBefore,L=J.commentBefore,N=J.comment;else if(R=!1,L=null,N=null,J&&typeof J==="object")J=q.createNode(J);if(Q.implicitKey=!1,!O&&!V&&i0.isScalar(J))Q.indentAtStart=M.length+1;if(D=!1,!B&&z.length>=2&&!Q.inFlow&&!O&&i0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let Z=!1,b=_5.stringify(J,Q,()=>Z=!0,()=>D=!0),w=" ";if(V||R||L){if(w=R?`
37
- `:"",L){let f=H(L);w+=`
38
- ${f2.indentComment(f,Q.indent)}`}if(b===""&&!Q.inFlow){if(w===`
39
- `&&N)w=`
25
+ `);if(F===-1)U="-";else if(Q===O||F!==O.length-1){if(U="+",Y)Y()}else U="";if(O){if(Q=Q.slice(0,-O.length),O[O.length-1]===`
26
+ `)O=O.slice(0,-1);O=O.replace(N4,`$&${H}`)}let D=!1,M,j=-1;for(M=0;M<Q.length;++M){let b=Q[M];if(b===" ")D=!0;else if(b===`
27
+ `)j=M;else break}let L=Q.substring(0,j<M?j+1:M);if(L)Q=Q.substring(L.length),L=L.replace(/\n+/g,`$&${H}`);let R=(D?H?"2":"1":"")+U;if($){if(R+=" "+W($.replace(/ ?[\r\n]+/g," ")),q)q()}if(!B){let b=Q.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${H}`),w=!1,T=k6(X,!0);if(G!=="folded"&&J!==f0.Scalar.BLOCK_FOLDED)T.onOverflow=()=>{w=!0};let Z=G$.foldFlowLines(`${L}${b}${O}`,H,G$.FOLD_BLOCK,T);if(!w)return`>${R}
29
+ ${H}${Z}`}return Q=Q.replace(/\n+/g,`$&${H}`),`|${R}
30
+ ${H}${L}${Q}${O}`}function wG($,J,Q,X){let{type:q,value:Y}=$,{actualString:G,implicitKey:W,indent:z,indentStep:H,inFlow:B}=J;if(W&&Y.includes(`
31
+ `)||B&&/[[\]{},]/.test(Y))return X2(Y,J);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(Y))return W||B||!Y.includes(`
32
+ `)?X2(Y,J):g6($,J,Q,X);if(!W&&!B&&q!==f0.Scalar.PLAIN&&Y.includes(`
33
+ `))return g6($,J,Q,X);if(m6(Y)){if(z==="")return J.forceBlockIndent=!0,g6($,J,Q,X);else if(W&&z===H)return X2(Y,J)}let U=Y.replace(/\n+/g,`$&
34
+ ${z}`);if(G){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(U),{compat:O,tags:F}=J.doc.schema;if(F.some(V)||O?.some(V))return X2(Y,J)}return W?U:G$.foldFlowLines(U,z,G$.FOLD_FLOW,k6(J,!1))}function PG($,J,Q,X){let{implicitKey:q,inFlow:Y}=J,G=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:W}=$;if(W!==f0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(G.value))W=f0.Scalar.QUOTE_DOUBLE}let z=(B)=>{switch(B){case f0.Scalar.BLOCK_FOLDED:case f0.Scalar.BLOCK_LITERAL:return q||Y?X2(G.value,J):g6(G,J,Q,X);case f0.Scalar.QUOTE_DOUBLE:return v2(G.value,J);case f0.Scalar.QUOTE_SINGLE:return L4(G.value,J);case f0.Scalar.PLAIN:return wG(G,J,Q,X);default:return null}},H=z(W);if(H===null){let{defaultKeyType:B,defaultStringType:U}=J.options,V=q&&B||U;if(H=z(V),H===null)throw Error(`Unsupported default string type ${V}`)}return H}bG.stringifyString=PG});var y2=S((yG)=>{var SG=v6(),W$=p(),CG=T2(),fG=x2();function IG($,J){let Q=Object.assign({blockQuote:!0,commentString:CG.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,J),X;switch(Q.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:$,flowCollectionPadding:Q.flowCollectionPadding?" ":"",indent:"",indentStep:typeof Q.indent==="number"?" ".repeat(Q.indent):" ",inFlow:X,options:Q}}function TG($,J){if(J.tag){let q=$.filter((Y)=>Y.tag===J.tag);if(q.length>0)return q.find((Y)=>Y.format===J.format)??q[0]}let Q=void 0,X;if(W$.isScalar(J)){X=J.value;let q=$.filter((Y)=>Y.identify?.(X));if(q.length>1){let Y=q.filter((G)=>G.test);if(Y.length>0)q=Y}Q=q.find((Y)=>Y.format===J.format)??q.find((Y)=>!Y.format)}else X=J,Q=$.find((q)=>q.nodeClass&&X instanceof q.nodeClass);if(!Q){let q=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${q} value`)}return Q}function vG($,J,{anchors:Q,doc:X}){if(!X.directives)return"";let q=[],Y=(W$.isScalar($)||W$.isCollection($))&&$.anchor;if(Y&&SG.anchorIsValid(Y))Q.add(Y),q.push(`&${Y}`);let G=$.tag??(J.default?null:J.tag);if(G)q.push(X.directives.tagString(G));return q.join(" ")}function xG($,J,Q,X){if(W$.isPair($))return $.toString(J,Q,X);if(W$.isAlias($)){if(J.doc.directives)return $.toString(J);if(J.resolvedAliases?.has($))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(J.resolvedAliases)J.resolvedAliases.add($);else J.resolvedAliases=new Set([$]);$=$.resolve(J.doc)}}let q=void 0,Y=W$.isNode($)?$:J.doc.createNode($,{onTagObj:(z)=>q=z});q??(q=TG(J.doc.schema.tags,Y));let G=vG(Y,q,J);if(G.length>0)J.indentAtStart=(J.indentAtStart??0)+G.length+1;let W=typeof q.stringify==="function"?q.stringify(Y,J,Q,X):W$.isScalar(Y)?fG.stringifyString(Y,J,Q,X):Y.toString(J,Q,X);if(!G)return W;return W$.isScalar(Y)||W[0]==="{"||W[0]==="["?`${G} ${W}`:`${G}
35
+ ${J.indent}${W}`}yG.createStringifyContext=IG;yG.stringify=xG});var C7=S((mG)=>{var o0=p(),E7=Y0(),S7=y2(),h2=T2();function kG({key:$,value:J},Q,X,q){let{allNullValues:Y,doc:G,indent:W,indentStep:z,options:{commentString:H,indentSeq:B,simpleKeys:U}}=Q,V=o0.isNode($)&&$.comment||null;if(U){if(V)throw Error("With simple keys, key nodes cannot have comments");if(o0.isCollection($)||!o0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!U&&(!$||V&&J==null&&!Q.inFlow||o0.isCollection($)||(o0.isScalar($)?$.type===E7.Scalar.BLOCK_FOLDED||$.type===E7.Scalar.BLOCK_LITERAL:typeof $==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!O&&(U||!Y),indent:W+z});let F=!1,D=!1,M=S7.stringify($,Q,()=>F=!0,()=>D=!0);if(!O&&!Q.inFlow&&M.length>1024){if(U)throw Error("With simple keys, single line scalar must not span more than 1024 characters");O=!0}if(Q.inFlow){if(Y||J==null){if(F&&X)X();return M===""?"?":O?`? ${M}`:M}}else if(Y&&!U||J==null&&O){if(M=`? ${M}`,V&&!F)M+=h2.lineComment(M,Q.indent,H(V));else if(D&&q)q();return M}if(F)V=null;if(O){if(V)M+=h2.lineComment(M,Q.indent,H(V));M=`? ${M}
36
+ ${W}:`}else if(M=`${M}:`,V)M+=h2.lineComment(M,Q.indent,H(V));let j,L,A;if(o0.isNode(J))j=!!J.spaceBefore,L=J.commentBefore,A=J.comment;else if(j=!1,L=null,A=null,J&&typeof J==="object")J=G.createNode(J);if(Q.implicitKey=!1,!O&&!V&&o0.isScalar(J))Q.indentAtStart=M.length+1;if(D=!1,!B&&z.length>=2&&!Q.inFlow&&!O&&o0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let R=!1,b=S7.stringify(J,Q,()=>R=!0,()=>D=!0),w=" ";if(V||j||L){if(w=j?`
37
+ `:"",L){let T=H(L);w+=`
38
+ ${h2.indentComment(T,Q.indent)}`}if(b===""&&!Q.inFlow){if(w===`
39
+ `&&A)w=`
40
40
 
41
41
  `}else w+=`
42
- ${Q.indent}`}else if(!O&&i0.isCollection(J)){let f=b[0],A=b.indexOf(`
43
- `),S=A!==-1,x=Q.inFlow??J.flow??J.items.length===0;if(S||!x){let r=!1;if(S&&(f==="&"||f==="!")){let g=b.indexOf(" ");if(f==="&"&&g!==-1&&g<A&&b[g+1]==="!")g=b.indexOf(" ",g+1);if(g===-1||A<g)r=!0}if(!r)w=`
42
+ ${Q.indent}`}else if(!O&&o0.isCollection(J)){let T=b[0],Z=b.indexOf(`
43
+ `),I=Z!==-1,y=Q.inFlow??J.flow??J.items.length===0;if(I||!y){let n=!1;if(I&&(T==="&"||T==="!")){let C=b.indexOf(" ");if(T==="&"&&C!==-1&&C<Z&&b[C+1]==="!")C=b.indexOf(" ",C+1);if(C===-1||Z<C)n=!0}if(!n)w=`
44
44
  ${Q.indent}`}}else if(b===""||b[0]===`
45
- `)w="";if(M+=w+b,Q.inFlow){if(Z&&X)X()}else if(N&&!Z)M+=f2.lineComment(M,Q.indent,H(N));else if(D&&Y)Y();return M}Iq.stringifyPair=fq});var K4=C((hq)=>{var Z5=F6("process");function vq($,...J){if($==="debug")console.log(...J)}function xq($,J){if($==="debug"||$==="warn")if(typeof Z5.emitWarning==="function")Z5.emitWarning(J);else console.warn(J)}hq.debug=vq;hq.warn=xq});var m6=C((mq)=>{var k6=d(),w5=Y0(),y6="<<",g6={identify:($)=>$===y6||typeof $==="symbol"&&$.description===y6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new w5.Scalar(Symbol(y6)),{addToJSMap:P5}),stringify:()=>y6},kq=($,J)=>(g6.identify(J)||k6.isScalar(J)&&(!J.type||J.type===w5.Scalar.PLAIN)&&g6.identify(J.value))&&$?.doc.schema.tags.some((Q)=>Q.tag===g6.tag&&Q.default);function P5($,J,Q){let X=b5($,Q);if(k6.isSeq(X))for(let Y of X.items)R4($,J,Y);else if(Array.isArray(X))for(let Y of X)R4($,J,Y);else R4($,J,X)}function R4($,J,Q){let X=b5($,Q);if(!k6.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,$,Map);for(let[G,q]of Y)if(J instanceof Map){if(!J.has(G))J.set(G,q)}else if(J instanceof Set)J.add(G);else if(!Object.prototype.hasOwnProperty.call(J,G))Object.defineProperty(J,G,{value:q,writable:!0,enumerable:!0,configurable:!0});return J}function b5($,J){return $&&k6.isAlias(J)?J.resolve($.doc,$):J}mq.addMergeToJSMap=P5;mq.isMergeKey=kq;mq.merge=g6});var j4=C((rq)=>{var pq=K4(),E5=m6(),dq=C2(),S5=d(),L4=J$();function iq($,J,{key:Q,value:X}){if(S5.isNode(Q)&&Q.addToJSMap)Q.addToJSMap($,J,X);else if(E5.isMergeKey($,Q))E5.addMergeToJSMap($,J,X);else{let Y=L4.toJS(Q,"",$);if(J instanceof Map)J.set(Y,L4.toJS(X,Y,$));else if(J instanceof Set)J.add(Y);else{let G=nq(Q,Y,$),q=L4.toJS(X,G,$);if(G in J)Object.defineProperty(J,G,{value:q,writable:!0,enumerable:!0,configurable:!0});else J[G]=q}}return J}function nq($,J,Q){if(J===null)return"";if(typeof J!=="object")return String(J);if(S5.isNode($)&&Q?.doc){let X=dq.createStringifyContext(Q.doc,{});X.anchors=new Set;for(let G of Q.anchors.keys())X.anchors.add(G.anchor);X.inFlow=!0,X.inStringifyKey=!0;let Y=$.toString(X);if(!Q.mapKeyWarned){let G=JSON.stringify(Y);if(G.length>40)G=G.substring(0,36)+'..."';pq.warn(Q.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${G}. Set mapAsMap: true to use object keys.`),Q.mapKeyWarned=!0}return Y}return JSON.stringify(J)}rq.addPairToJSMap=iq});var Y$=C((eq)=>{var C5=P2(),sq=A5(),oq=j4(),u6=d();function tq($,J,Q){let X=C5.createNode($,void 0,Q),Y=C5.createNode(J,void 0,Q);return new l6(X,Y)}class l6{constructor($,J=null){Object.defineProperty(this,u6.NODE_TYPE,{value:u6.PAIR}),this.key=$,this.value=J}clone($){let{key:J,value:Q}=this;if(u6.isNode(J))J=J.clone($);if(u6.isNode(Q))Q=Q.clone($);return new l6(J,Q)}toJSON($,J){let Q=J?.mapAsMap?new Map:{};return oq.addPairToJSMap(J,Q,this)}toString($,J,Q){return $?.doc?sq.stringifyPair(this,$,J,Q):JSON.stringify(this)}}eq.Pair=l6;eq.createPair=tq});var N4=C((GW)=>{var _$=d(),f5=C2(),c6=b2();function QW($,J,Q){return(J.inFlow??$.flow?YW:XW)($,J,Q)}function XW({comment:$,items:J},Q,{blockItemPrefix:X,flowChars:Y,itemIndent:G,onChompKeep:q,onComment:W}){let{indent:z,options:{commentString:H}}=Q,B=Object.assign({},Q,{indent:G,type:null}),U=!1,V=[];for(let F=0;F<J.length;++F){let D=J[F],M=null;if(_$.isNode(D)){if(!U&&D.spaceBefore)V.push("");if(p6(Q,V,D.commentBefore,U),D.comment)M=D.comment}else if(_$.isPair(D)){let L=_$.isNode(D.key)?D.key:null;if(L){if(!U&&L.spaceBefore)V.push("");p6(Q,V,L.commentBefore,U)}}U=!1;let R=f5.stringify(D,B,()=>M=null,()=>U=!0);if(M)R+=c6.lineComment(R,G,H(M));if(U&&M)U=!1;V.push(X+R)}let O;if(V.length===0)O=Y.start+Y.end;else{O=V[0];for(let F=1;F<V.length;++F){let D=V[F];O+=D?`
45
+ `)w="";if(M+=w+b,Q.inFlow){if(R&&X)X()}else if(A&&!R)M+=h2.lineComment(M,Q.indent,H(A));else if(D&&q)q();return M}mG.stringifyPair=kG});var A4=S((dG)=>{var f7=j6("process");function lG($,...J){if($==="debug")console.log(...J)}function cG($,J){if($==="debug"||$==="warn")if(typeof f7.emitWarning==="function")f7.emitWarning(J);else console.warn(J)}dG.debug=lG;dG.warn=cG});var d6=S((rG)=>{var c6=p(),I7=Y0(),u6="<<",l6={identify:($)=>$===u6||typeof $==="symbol"&&$.description===u6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new I7.Scalar(Symbol(u6)),{addToJSMap:T7}),stringify:()=>u6},nG=($,J)=>(l6.identify(J)||c6.isScalar(J)&&(!J.type||J.type===I7.Scalar.PLAIN)&&l6.identify(J.value))&&$?.doc.schema.tags.some((Q)=>Q.tag===l6.tag&&Q.default);function T7($,J,Q){let X=v7($,Q);if(c6.isSeq(X))for(let q of X.items)_4($,J,q);else if(Array.isArray(X))for(let q of X)_4($,J,q);else _4($,J,X)}function _4($,J,Q){let X=v7($,Q);if(!c6.isMap(X))throw Error("Merge sources must be maps or map aliases");let q=X.toJSON(null,$,Map);for(let[Y,G]of q)if(J instanceof Map){if(!J.has(Y))J.set(Y,G)}else if(J instanceof Set)J.add(Y);else if(!Object.prototype.hasOwnProperty.call(J,Y))Object.defineProperty(J,Y,{value:G,writable:!0,enumerable:!0,configurable:!0});return J}function v7($,J){return $&&c6.isAlias(J)?J.resolve($.doc,$):J}rG.addMergeToJSMap=T7;rG.isMergeKey=nG;rG.merge=l6});var Z4=S((QW)=>{var tG=A4(),x7=d6(),eG=y2(),y7=p(),R4=Y$();function $W($,J,{key:Q,value:X}){if(y7.isNode(Q)&&Q.addToJSMap)Q.addToJSMap($,J,X);else if(x7.isMergeKey($,Q))x7.addMergeToJSMap($,J,X);else{let q=R4.toJS(Q,"",$);if(J instanceof Map)J.set(q,R4.toJS(X,q,$));else if(J instanceof Set)J.add(q);else{let Y=JW(Q,q,$),G=R4.toJS(X,Y,$);if(Y in J)Object.defineProperty(J,Y,{value:G,writable:!0,enumerable:!0,configurable:!0});else J[Y]=G}}return J}function JW($,J,Q){if(J===null)return"";if(typeof J!=="object")return String(J);if(y7.isNode($)&&Q?.doc){let X=eG.createStringifyContext(Q.doc,{});X.anchors=new Set;for(let Y of Q.anchors.keys())X.anchors.add(Y.anchor);X.inFlow=!0,X.inStringifyKey=!0;let q=$.toString(X);if(!Q.mapKeyWarned){let Y=JSON.stringify(q);if(Y.length>40)Y=Y.substring(0,36)+'..."';tG.warn(Q.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${Y}. Set mapAsMap: true to use object keys.`),Q.mapKeyWarned=!0}return q}return JSON.stringify(J)}QW.addPairToJSMap=$W});var z$=S((WW)=>{var h7=I2(),qW=C7(),YW=Z4(),p6=p();function GW($,J,Q){let X=h7.createNode($,void 0,Q),q=h7.createNode(J,void 0,Q);return new i6(X,q)}class i6{constructor($,J=null){Object.defineProperty(this,p6.NODE_TYPE,{value:p6.PAIR}),this.key=$,this.value=J}clone($){let{key:J,value:Q}=this;if(p6.isNode(J))J=J.clone($);if(p6.isNode(Q))Q=Q.clone($);return new i6(J,Q)}toJSON($,J){let Q=J?.mapAsMap?new Map:{};return YW.addPairToJSMap(J,Q,this)}toString($,J,Q){return $?.doc?qW.stringifyPair(this,$,J,Q):JSON.stringify(this)}}WW.Pair=i6;WW.createPair=GW});var w4=S((DW)=>{var E$=p(),g7=y2(),n6=T2();function BW($,J,Q){return(J.inFlow??$.flow?VW:UW)($,J,Q)}function UW({comment:$,items:J},Q,{blockItemPrefix:X,flowChars:q,itemIndent:Y,onChompKeep:G,onComment:W}){let{indent:z,options:{commentString:H}}=Q,B=Object.assign({},Q,{indent:Y,type:null}),U=!1,V=[];for(let F=0;F<J.length;++F){let D=J[F],M=null;if(E$.isNode(D)){if(!U&&D.spaceBefore)V.push("");if(r6(Q,V,D.commentBefore,U),D.comment)M=D.comment}else if(E$.isPair(D)){let L=E$.isNode(D.key)?D.key:null;if(L){if(!U&&L.spaceBefore)V.push("");r6(Q,V,L.commentBefore,U)}}U=!1;let j=g7.stringify(D,B,()=>M=null,()=>U=!0);if(M)j+=n6.lineComment(j,Y,H(M));if(U&&M)U=!1;V.push(X+j)}let O;if(V.length===0)O=q.start+q.end;else{O=V[0];for(let F=1;F<V.length;++F){let D=V[F];O+=D?`
46
46
  ${z}${D}`:`
47
47
  `}}if($){if(O+=`
48
- `+c6.indentComment(H($),z),W)W()}else if(U&&q)q();return O}function YW({items:$},J,{flowChars:Q,itemIndent:X}){let{indent:Y,indentStep:G,flowCollectionPadding:q,options:{commentString:W}}=J;X+=G;let z=Object.assign({},J,{indent:X,inFlow:!0,type:null}),H=!1,B=0,U=[];for(let F=0;F<$.length;++F){let D=$[F],M=null;if(_$.isNode(D)){if(D.spaceBefore)U.push("");if(p6(J,U,D.commentBefore,!1),D.comment)M=D.comment}else if(_$.isPair(D)){let L=_$.isNode(D.key)?D.key:null;if(L){if(L.spaceBefore)U.push("");if(p6(J,U,L.commentBefore,!1),L.comment)H=!0}let N=_$.isNode(D.value)?D.value:null;if(N){if(N.comment)M=N.comment;if(N.commentBefore)H=!0}else if(D.value==null&&L?.comment)M=L.comment}if(M)H=!0;let R=f5.stringify(D,z,()=>M=null);if(H||(H=U.length>B||R.includes(`
49
- `)),F<$.length-1)R+=",";else if(J.options.trailingComma){if(J.options.lineWidth>0)H||(H=U.reduce((L,N)=>L+N.length+2,2)+(R.length+2)>J.options.lineWidth);if(H)R+=","}if(M)R+=c6.lineComment(R,X,W(M));U.push(R),B=U.length}let{start:V,end:O}=Q;if(U.length===0)return V+O;else{if(!H){let F=U.reduce((D,M)=>D+M.length+2,2);H=J.options.lineWidth>0&&F>J.options.lineWidth}if(H){let F=V;for(let D of U)F+=D?`
50
- ${G}${Y}${D}`:`
48
+ `+n6.indentComment(H($),z),W)W()}else if(U&&G)G();return O}function VW({items:$},J,{flowChars:Q,itemIndent:X}){let{indent:q,indentStep:Y,flowCollectionPadding:G,options:{commentString:W}}=J;X+=Y;let z=Object.assign({},J,{indent:X,inFlow:!0,type:null}),H=!1,B=0,U=[];for(let F=0;F<$.length;++F){let D=$[F],M=null;if(E$.isNode(D)){if(D.spaceBefore)U.push("");if(r6(J,U,D.commentBefore,!1),D.comment)M=D.comment}else if(E$.isPair(D)){let L=E$.isNode(D.key)?D.key:null;if(L){if(L.spaceBefore)U.push("");if(r6(J,U,L.commentBefore,!1),L.comment)H=!0}let A=E$.isNode(D.value)?D.value:null;if(A){if(A.comment)M=A.comment;if(A.commentBefore)H=!0}else if(D.value==null&&L?.comment)M=L.comment}if(M)H=!0;let j=g7.stringify(D,z,()=>M=null);if(H||(H=U.length>B||j.includes(`
49
+ `)),F<$.length-1)j+=",";else if(J.options.trailingComma){if(J.options.lineWidth>0)H||(H=U.reduce((L,A)=>L+A.length+2,2)+(j.length+2)>J.options.lineWidth);if(H)j+=","}if(M)j+=n6.lineComment(j,X,W(M));U.push(j),B=U.length}let{start:V,end:O}=Q;if(U.length===0)return V+O;else{if(!H){let F=U.reduce((D,M)=>D+M.length+2,2);H=J.options.lineWidth>0&&F>J.options.lineWidth}if(H){let F=V;for(let D of U)F+=D?`
50
+ ${Y}${q}${D}`:`
51
51
  `;return`${F}
52
- ${Y}${O}`}else return`${V}${q}${U.join(" ")}${q}${O}`}}function p6({indent:$,options:{commentString:J}},Q,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let G=c6.indentComment(J(X),$);Q.push(G.trimStart())}}GW.stringifyCollection=QW});var q$=C((UW)=>{var WW=N4(),zW=j4(),HW=T6(),G$=d(),d6=Y$(),BW=Y0();function I2($,J){let Q=G$.isScalar(J)?J.value:J;for(let X of $)if(G$.isPair(X)){if(X.key===J||X.key===Q)return X;if(G$.isScalar(X.key)&&X.key.value===Q)return X}return}class I5 extends HW.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(G$.MAP,$);this.items=[]}static from($,J,Q){let{keepUndefined:X,replacer:Y}=Q,G=new this($),q=(W,z)=>{if(typeof Y==="function")z=Y.call(J,W,z);else if(Array.isArray(Y)&&!Y.includes(W))return;if(z!==void 0||X)G.items.push(d6.createPair(W,z,Q))};if(J instanceof Map)for(let[W,z]of J)q(W,z);else if(J&&typeof J==="object")for(let W of Object.keys(J))q(W,J[W]);if(typeof $.sortMapEntries==="function")G.items.sort($.sortMapEntries);return G}add($,J){let Q;if(G$.isPair($))Q=$;else if(!$||typeof $!=="object"||!("key"in $))Q=new d6.Pair($,$?.value);else Q=new d6.Pair($.key,$.value);let X=I2(this.items,Q.key),Y=this.schema?.sortMapEntries;if(X){if(!J)throw Error(`Key ${Q.key} already set`);if(G$.isScalar(X.value)&&BW.isScalarValue(Q.value))X.value.value=Q.value;else X.value=Q.value}else if(Y){let G=this.items.findIndex((q)=>Y(Q,q)<0);if(G===-1)this.items.push(Q);else this.items.splice(G,0,Q)}else this.items.push(Q)}delete($){let J=I2(this.items,$);if(!J)return!1;return this.items.splice(this.items.indexOf(J),1).length>0}get($,J){let X=I2(this.items,$)?.value;return(!J&&G$.isScalar(X)?X.value:X)??void 0}has($){return!!I2(this.items,$)}set($,J){this.add(new d6.Pair($,J),!0)}toJSON($,J,Q){let X=Q?new Q:J?.mapAsMap?new Map:{};if(J?.onCreate)J.onCreate(X);for(let Y of this.items)zW.addPairToJSMap(J,X,Y);return X}toString($,J,Q){if(!$)return JSON.stringify(this);for(let X of this.items)if(!G$.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 WW.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:Q,onComment:J})}}UW.YAMLMap=I5;UW.findPair=I2});var e$=C((OW)=>{var FW=d(),T5=q$(),MW={collection:"map",default:!0,nodeClass:T5.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,J){if(!FW.isMap($))J("Expected a mapping for this tag");return $},createNode:($,J,Q)=>T5.YAMLMap.from($,J,Q)};OW.map=MW});var W$=C((AW)=>{var RW=P2(),LW=N4(),jW=T6(),n6=d(),NW=Y0(),_W=J$();class v5 extends jW.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(n6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let J=i6($);if(typeof J!=="number")return!1;return this.items.splice(J,1).length>0}get($,J){let Q=i6($);if(typeof Q!=="number")return;let X=this.items[Q];return!J&&n6.isScalar(X)?X.value:X}has($){let J=i6($);return typeof J==="number"&&J<this.items.length}set($,J){let Q=i6($);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${$}.`);let X=this.items[Q];if(n6.isScalar(X)&&NW.isScalarValue(J))X.value=J;else this.items[Q]=J}toJSON($,J){let Q=[];if(J?.onCreate)J.onCreate(Q);let X=0;for(let Y of this.items)Q.push(_W.toJS(Y,String(X++),J));return Q}toString($,J,Q){if(!$)return JSON.stringify(this);return LW.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:Q,onComment:J})}static from($,J,Q){let{replacer:X}=Q,Y=new this($);if(J&&Symbol.iterator in Object(J)){let G=0;for(let q of J){if(typeof X==="function"){let W=J instanceof Set?q:String(G++);q=X.call(J,W,q)}Y.items.push(RW.createNode(q,void 0,Q))}}return Y}}function i6($){let J=n6.isScalar($)?$.value:$;if(J&&typeof J==="string")J=Number(J);return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:null}AW.YAMLSeq=v5});var $2=C((bW)=>{var wW=d(),x5=W$(),PW={collection:"seq",default:!0,nodeClass:x5.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,J){if(!wW.isSeq($))J("Expected a sequence for this tag");return $},createNode:($,J,Q)=>x5.YAMLSeq.from($,J,Q)};bW.seq=PW});var T2=C((fW)=>{var SW=S2(),CW={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,J,Q,X){return J=Object.assign({actualString:!0},J),SW.stringifyString($,J,Q,X)}};fW.string=CW});var r6=C((TW)=>{var h5=Y0(),y5={identify:($)=>$==null,createNode:()=>new h5.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new h5.Scalar(null),stringify:({source:$},J)=>typeof $==="string"&&y5.test.test($)?$:J.options.nullStr};TW.nullTag=y5});var _4=C((hW)=>{var xW=Y0(),g5={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new xW.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:J},Q){if($&&g5.test.test($)){let X=$[0]==="t"||$[0]==="T";if(J===X)return $}return J?Q.options.trueStr:Q.options.falseStr}};hW.boolTag=g5});var J2=C((kW)=>{function gW({format:$,minFractionDigits:J,tag:Q,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 G=Object.is(X,-0)?"-0":JSON.stringify(X);if(!$&&J&&(!Q||Q==="tag:yaml.org,2002:float")&&/^-?\d/.test(G)&&!G.includes("e")){let q=G.indexOf(".");if(q<0)q=G.length,G+=".";let W=J-(G.length-q-1);while(W-- >0)G+="0"}return G}kW.stringifyNumber=gW});var Z4=C((dW)=>{var uW=Y0(),A4=J2(),lW={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:A4.stringifyNumber},cW={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 J=Number($.value);return isFinite(J)?J.toExponential():A4.stringifyNumber($)}},pW={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let J=new uW.Scalar(parseFloat($)),Q=$.indexOf(".");if(Q!==-1&&$[$.length-1]==="0")J.minFractionDigits=$.length-Q-1;return J},stringify:A4.stringifyNumber};dW.float=pW;dW.floatExp=cW;dW.floatNaN=lW});var P4=C((tW)=>{var k5=J2(),a6=($)=>typeof $==="bigint"||Number.isInteger($),w4=($,J,Q,{intAsBigInt:X})=>X?BigInt($):parseInt($.substring(J),Q);function m5($,J,Q){let{value:X}=$;if(a6(X)&&X>=0)return Q+X.toString(J);return k5.stringifyNumber($)}var aW={identify:($)=>a6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,J,Q)=>w4($,2,8,Q),stringify:($)=>m5($,8,"0o")},sW={identify:a6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,J,Q)=>w4($,0,10,Q),stringify:k5.stringifyNumber},oW={identify:($)=>a6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,J,Q)=>w4($,2,16,Q),stringify:($)=>m5($,16,"0x")};tW.int=sW;tW.intHex=oW;tW.intOct=aW});var u5=C((zz)=>{var Qz=e$(),Xz=r6(),Yz=$2(),Gz=T2(),qz=_4(),b4=Z4(),E4=P4(),Wz=[Qz.map,Yz.seq,Gz.string,Xz.nullTag,qz.boolTag,E4.intOct,E4.int,E4.intHex,b4.floatNaN,b4.floatExp,b4.float];zz.schema=Wz});var c5=C((Oz)=>{var Bz=Y0(),Uz=e$(),Vz=$2();function l5($){return typeof $==="bigint"||Number.isInteger($)}var s6=({value:$})=>JSON.stringify($),Dz=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:s6},{identify:($)=>$==null,createNode:()=>new Bz.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:s6},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:s6},{identify:l5,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,J,{intAsBigInt:Q})=>Q?BigInt($):parseInt($,10),stringify:({value:$})=>l5($)?$.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:s6}],Fz={default:!0,tag:"",test:/^/,resolve($,J){return J(`Unresolved plain scalar ${JSON.stringify($)}`),$}},Mz=[Uz.map,Vz.seq].concat(Dz,Fz);Oz.schema=Mz});var C4=C((jz)=>{var v2=F6("buffer"),S4=Y0(),Rz=S2(),Lz={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,J){if(typeof v2.Buffer==="function")return v2.Buffer.from($,"base64");else if(typeof atob==="function"){let Q=atob($.replace(/[\n\r]/g,"")),X=new Uint8Array(Q.length);for(let Y=0;Y<Q.length;++Y)X[Y]=Q.charCodeAt(Y);return X}else return J("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:J,value:Q},X,Y,G){if(!Q)return"";let q=Q,W;if(typeof v2.Buffer==="function")W=q instanceof v2.Buffer?q.toString("base64"):v2.Buffer.from(q.buffer).toString("base64");else if(typeof btoa==="function"){let z="";for(let H=0;H<q.length;++H)z+=String.fromCharCode(q[H]);W=btoa(z)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(J??(J=S4.Scalar.BLOCK_LITERAL),J!==S4.Scalar.QUOTE_DOUBLE){let z=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),H=Math.ceil(W.length/z),B=Array(H);for(let U=0,V=0;U<H;++U,V+=z)B[U]=W.substr(V,z);W=B.join(J===S4.Scalar.BLOCK_LITERAL?`
53
- `:" ")}return Rz.stringifyString({comment:$,type:J,value:W},X,Y,G)}};jz.binary=Lz});var t6=C((wz)=>{var o6=d(),f4=Y$(),_z=Y0(),Az=W$();function p5($,J){if(o6.isSeq($))for(let Q=0;Q<$.items.length;++Q){let X=$.items[Q];if(o6.isPair(X))continue;else if(o6.isMap(X)){if(X.items.length>1)J("Each pair must have its own sequence indicator");let Y=X.items[0]||new f4.Pair(new _z.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
54
- ${Y.key.commentBefore}`:X.commentBefore;if(X.comment){let G=Y.value??Y.key;G.comment=G.comment?`${X.comment}
55
- ${G.comment}`:X.comment}X=Y}$.items[Q]=o6.isPair(X)?X:new f4.Pair(X)}else J("Expected a sequence for this tag");return $}function d5($,J,Q){let{replacer:X}=Q,Y=new Az.YAMLSeq($);Y.tag="tag:yaml.org,2002:pairs";let G=0;if(J&&Symbol.iterator in Object(J))for(let q of J){if(typeof X==="function")q=X.call(J,String(G++),q);let W,z;if(Array.isArray(q))if(q.length===2)W=q[0],z=q[1];else throw TypeError(`Expected [key, value] tuple: ${q}`);else if(q&&q instanceof Object){let H=Object.keys(q);if(H.length===1)W=H[0],z=q[W];else throw TypeError(`Expected tuple with one key, not ${H.length} keys`)}else W=q;Y.items.push(f4.createPair(W,z,Q))}return Y}var Zz={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:p5,createNode:d5};wz.createPairs=d5;wz.pairs=Zz;wz.resolvePairs=p5});var T4=C((fz)=>{var i5=d(),I4=J$(),x2=q$(),Sz=W$(),n5=t6();class A$ extends Sz.YAMLSeq{constructor(){super();this.add=x2.YAMLMap.prototype.add.bind(this),this.delete=x2.YAMLMap.prototype.delete.bind(this),this.get=x2.YAMLMap.prototype.get.bind(this),this.has=x2.YAMLMap.prototype.has.bind(this),this.set=x2.YAMLMap.prototype.set.bind(this),this.tag=A$.tag}toJSON($,J){if(!J)return super.toJSON($);let Q=new Map;if(J?.onCreate)J.onCreate(Q);for(let X of this.items){let Y,G;if(i5.isPair(X))Y=I4.toJS(X.key,"",J),G=I4.toJS(X.value,Y,J);else Y=I4.toJS(X,"",J);if(Q.has(Y))throw Error("Ordered maps must not include duplicate keys");Q.set(Y,G)}return Q}static from($,J,Q){let X=n5.createPairs($,J,Q),Y=new this;return Y.items=X.items,Y}}A$.tag="tag:yaml.org,2002:omap";var Cz={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:A$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=n5.resolvePairs($,J),X=[];for(let{key:Y}of Q.items)if(i5.isScalar(Y))if(X.includes(Y.value))J(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new A$,Q)},createNode:($,J,Q)=>A$.from($,J,Q)};fz.YAMLOMap=A$;fz.omap=Cz});var t5=C((vz)=>{var r5=Y0();function a5({value:$,source:J},Q){if(J&&($?s5:o5).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var s5={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new r5.Scalar(!0),stringify:a5},o5={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new r5.Scalar(!1),stringify:a5};vz.falseTag=o5;vz.trueTag=s5});var e5=C((uz)=>{var yz=Y0(),v4=J2(),gz={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:v4.stringifyNumber},kz={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 J=Number($.value);return isFinite(J)?J.toExponential():v4.stringifyNumber($)}},mz={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new yz.Scalar(parseFloat($.replace(/_/g,""))),Q=$.indexOf(".");if(Q!==-1){let X=$.substring(Q+1).replace(/_/g,"");if(X[X.length-1]==="0")J.minFractionDigits=X.length}return J},stringify:v4.stringifyNumber};uz.float=mz;uz.floatExp=kz;uz.floatNaN=gz});var JJ=C((az)=>{var $J=J2(),h2=($)=>typeof $==="bigint"||Number.isInteger($);function e6($,J,Q,{intAsBigInt:X}){let Y=$[0];if(Y==="-"||Y==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let q=BigInt($);return Y==="-"?BigInt(-1)*q:q}let G=parseInt($,Q);return Y==="-"?-1*G:G}function x4($,J,Q){let{value:X}=$;if(h2(X)){let Y=X.toString(J);return X<0?"-"+Q+Y.substr(1):Q+Y}return $J.stringifyNumber($)}var dz={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>e6($,2,2,Q),stringify:($)=>x4($,2,"0b")},iz={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>e6($,1,8,Q),stringify:($)=>x4($,8,"0")},nz={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>e6($,0,10,Q),stringify:$J.stringifyNumber},rz={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>e6($,2,16,Q),stringify:($)=>x4($,16,"0x")};az.int=nz;az.intBin=dz;az.intHex=rz;az.intOct=iz});var h4=C((JH)=>{var Q9=d(),$9=Y$(),J9=q$();class Z$ extends J9.YAMLMap{constructor($){super($);this.tag=Z$.tag}add($){let J;if(Q9.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new $9.Pair($.key,null);else J=new $9.Pair($,null);if(!J9.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=J9.findPair(this.items,$);return!J&&Q9.isPair(Q)?Q9.isScalar(Q.key)?Q.key.value:Q.key:Q}set($,J){if(typeof J!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof J}`);let Q=J9.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new $9.Pair($))}toJSON($,J){return super.toJSON($,J,Set)}toString($,J,Q){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),J,Q);else throw Error("Set items must all have null values")}static from($,J,Q){let{replacer:X}=Q,Y=new this($);if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,G,G);Y.items.push($9.createPair(G,null,Q))}return Y}}Z$.tag="tag:yaml.org,2002:set";var $H={collection:"map",identify:($)=>$ instanceof Set,nodeClass:Z$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>Z$.from($,J,Q),resolve($,J){if(Q9.isMap($))if($.hasAllNullValues(!0))return Object.assign(new Z$,$);else J("Set items must all have null values");else J("Expected a mapping for this tag");return $}};JH.YAMLSet=Z$;JH.set=$H});var g4=C((WH)=>{var YH=J2();function y4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,Y=(q)=>J?BigInt(q):Number(q),G=X.replace(/_/g,"").split(":").reduce((q,W)=>q*Y(60)+Y(W),Y(0));return Q==="-"?Y(-1)*G:G}function QJ($){let{value:J}=$,Q=(q)=>q;if(typeof J==="bigint")Q=(q)=>BigInt(q);else if(isNaN(J)||!isFinite(J))return YH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let Y=Q(60),G=[J%Y];if(J<60)G.unshift(0);else if(J=(J-G[0])/Y,G.unshift(J%Y),J>=60)J=(J-G[0])/Y,G.unshift(J);return X+G.map((q)=>String(q).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var GH={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:($,J,{intAsBigInt:Q})=>y4($,Q),stringify:QJ},qH={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:($)=>y4($,!1),stringify:QJ},XJ={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 J=$.match(XJ.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,Y,G,q,W]=J.map(Number),z=J[7]?Number((J[7]+"00").substr(1,3)):0,H=Date.UTC(Q,X-1,Y,G||0,q||0,W||0,z),B=J[8];if(B&&B!=="Z"){let U=y4(B,!1);if(Math.abs(U)<30)U*=60;H-=60000*U}return new Date(H)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};WH.floatTime=qH;WH.intTime=GH;WH.timestamp=XJ});var GJ=C((NH)=>{var UH=e$(),VH=r6(),DH=$2(),FH=T2(),MH=C4(),YJ=t5(),k4=e5(),X9=JJ(),OH=m6(),KH=T4(),RH=t6(),LH=h4(),m4=g4(),jH=[UH.map,DH.seq,FH.string,VH.nullTag,YJ.trueTag,YJ.falseTag,X9.intBin,X9.intOct,X9.int,X9.intHex,k4.floatNaN,k4.floatExp,k4.float,MH.binary,OH.merge,KH.omap,RH.pairs,LH.set,m4.intTime,m4.floatTime,m4.timestamp];NH.schema=jH});var MJ=C((CH)=>{var HJ=e$(),AH=r6(),BJ=$2(),ZH=T2(),wH=_4(),u4=Z4(),l4=P4(),PH=u5(),bH=c5(),UJ=C4(),y2=m6(),VJ=T4(),DJ=t6(),qJ=GJ(),FJ=h4(),Y9=g4(),WJ=new Map([["core",PH.schema],["failsafe",[HJ.map,BJ.seq,ZH.string]],["json",bH.schema],["yaml11",qJ.schema],["yaml-1.1",qJ.schema]]),zJ={binary:UJ.binary,bool:wH.boolTag,float:u4.float,floatExp:u4.floatExp,floatNaN:u4.floatNaN,floatTime:Y9.floatTime,int:l4.int,intHex:l4.intHex,intOct:l4.intOct,intTime:Y9.intTime,map:HJ.map,merge:y2.merge,null:AH.nullTag,omap:VJ.omap,pairs:DJ.pairs,seq:BJ.seq,set:FJ.set,timestamp:Y9.timestamp},EH={"tag:yaml.org,2002:binary":UJ.binary,"tag:yaml.org,2002:merge":y2.merge,"tag:yaml.org,2002:omap":VJ.omap,"tag:yaml.org,2002:pairs":DJ.pairs,"tag:yaml.org,2002:set":FJ.set,"tag:yaml.org,2002:timestamp":Y9.timestamp};function SH($,J,Q){let X=WJ.get(J);if(X&&!$)return Q&&!X.includes(y2.merge)?X.concat(y2.merge):X.slice();let Y=X;if(!Y)if(Array.isArray($))Y=[];else{let G=Array.from(WJ.keys()).filter((q)=>q!=="yaml11").map((q)=>JSON.stringify(q)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${G} or define customTags array`)}if(Array.isArray($))for(let G of $)Y=Y.concat(G);else if(typeof $==="function")Y=$(Y.slice());if(Q)Y=Y.concat(y2.merge);return Y.reduce((G,q)=>{let W=typeof q==="string"?zJ[q]:q;if(!W){let z=JSON.stringify(q),H=Object.keys(zJ).map((B)=>JSON.stringify(B)).join(", ");throw Error(`Unknown custom tag ${z}; use one of ${H}`)}if(!G.includes(W))G.push(W);return G},[])}CH.coreKnownTags=EH;CH.getTags=SH});var d4=C((yH)=>{var c4=d(),TH=e$(),vH=$2(),xH=T2(),G9=MJ(),hH=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class p4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:Y,sortMapEntries:G,toStringDefaults:q}){this.compat=Array.isArray($)?G9.getTags($,"compat"):$?G9.getTags(null,$):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?G9.coreKnownTags:{},this.tags=G9.getTags(J,this.name,Q),this.toStringOptions=q??null,Object.defineProperty(this,c4.MAP,{value:TH.map}),Object.defineProperty(this,c4.SCALAR,{value:xH.string}),Object.defineProperty(this,c4.SEQ,{value:vH.seq}),this.sortMapEntries=typeof G==="function"?G:G===!0?hH:null}clone(){let $=Object.create(p4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}yH.Schema=p4});var OJ=C((uH)=>{var kH=d(),i4=C2(),g2=b2();function mH($,J){let Q=[],X=J.directives===!0;if(J.directives!==!1&&$.directives){let z=$.directives.toString($);if(z)Q.push(z),X=!0;else if($.directives.docStart)X=!0}if(X)Q.push("---");let Y=i4.createStringifyContext($,J),{commentString:G}=Y.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let z=G($.commentBefore);Q.unshift(g2.indentComment(z,""))}let q=!1,W=null;if($.contents){if(kH.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let B=G($.contents.commentBefore);Q.push(g2.indentComment(B,""))}Y.forceBlockIndent=!!$.comment,W=$.contents.comment}let z=W?void 0:()=>q=!0,H=i4.stringify($.contents,Y,()=>W=null,z);if(W)H+=g2.lineComment(H,"",G(W));if((H[0]==="|"||H[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${H}`;else Q.push(H)}else Q.push(i4.stringify($.contents,Y));if($.directives?.docEnd)if($.comment){let z=G($.comment);if(z.includes(`
56
- `))Q.push("..."),Q.push(g2.indentComment(z,""));else Q.push(`... ${z}`)}else Q.push("...");else{let z=$.comment;if(z&&q)z=z.replace(/^\n+/,"");if(z){if((!q||W)&&Q[Q.length-1]!=="")Q.push("");Q.push(g2.indentComment(G(z),""))}}return Q.join(`
52
+ ${q}${O}`}else return`${V}${G}${U.join(" ")}${G}${O}`}}function r6({indent:$,options:{commentString:J}},Q,X,q){if(X&&q)X=X.replace(/^\n+/,"");if(X){let Y=n6.indentComment(J(X),$);Q.push(Y.trimStart())}}DW.stringifyCollection=BW});var B$=S((LW)=>{var MW=w4(),OW=Z4(),KW=h6(),H$=p(),a6=z$(),jW=Y0();function g2($,J){let Q=H$.isScalar(J)?J.value:J;for(let X of $)if(H$.isPair(X)){if(X.key===J||X.key===Q)return X;if(H$.isScalar(X.key)&&X.key.value===Q)return X}return}class k7 extends KW.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(H$.MAP,$);this.items=[]}static from($,J,Q){let{keepUndefined:X,replacer:q}=Q,Y=new this($),G=(W,z)=>{if(typeof q==="function")z=q.call(J,W,z);else if(Array.isArray(q)&&!q.includes(W))return;if(z!==void 0||X)Y.items.push(a6.createPair(W,z,Q))};if(J instanceof Map)for(let[W,z]of J)G(W,z);else if(J&&typeof J==="object")for(let W of Object.keys(J))G(W,J[W]);if(typeof $.sortMapEntries==="function")Y.items.sort($.sortMapEntries);return Y}add($,J){let Q;if(H$.isPair($))Q=$;else if(!$||typeof $!=="object"||!("key"in $))Q=new a6.Pair($,$?.value);else Q=new a6.Pair($.key,$.value);let X=g2(this.items,Q.key),q=this.schema?.sortMapEntries;if(X){if(!J)throw Error(`Key ${Q.key} already set`);if(H$.isScalar(X.value)&&jW.isScalarValue(Q.value))X.value.value=Q.value;else X.value=Q.value}else if(q){let Y=this.items.findIndex((G)=>q(Q,G)<0);if(Y===-1)this.items.push(Q);else this.items.splice(Y,0,Q)}else this.items.push(Q)}delete($){let J=g2(this.items,$);if(!J)return!1;return this.items.splice(this.items.indexOf(J),1).length>0}get($,J){let X=g2(this.items,$)?.value;return(!J&&H$.isScalar(X)?X.value:X)??void 0}has($){return!!g2(this.items,$)}set($,J){this.add(new a6.Pair($,J),!0)}toJSON($,J,Q){let X=Q?new Q:J?.mapAsMap?new Map:{};if(J?.onCreate)J.onCreate(X);for(let q of this.items)OW.addPairToJSMap(J,X,q);return X}toString($,J,Q){if(!$)return JSON.stringify(this);for(let X of this.items)if(!H$.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 MW.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:Q,onComment:J})}}LW.YAMLMap=k7;LW.findPair=g2});var q2=S((ZW)=>{var _W=p(),m7=B$(),RW={collection:"map",default:!0,nodeClass:m7.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,J){if(!_W.isMap($))J("Expected a mapping for this tag");return $},createNode:($,J,Q)=>m7.YAMLMap.from($,J,Q)};ZW.map=RW});var U$=S((fW)=>{var PW=I2(),bW=w4(),EW=h6(),o6=p(),SW=Y0(),CW=Y$();class u7 extends EW.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(o6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let J=s6($);if(typeof J!=="number")return!1;return this.items.splice(J,1).length>0}get($,J){let Q=s6($);if(typeof Q!=="number")return;let X=this.items[Q];return!J&&o6.isScalar(X)?X.value:X}has($){let J=s6($);return typeof J==="number"&&J<this.items.length}set($,J){let Q=s6($);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${$}.`);let X=this.items[Q];if(o6.isScalar(X)&&SW.isScalarValue(J))X.value=J;else this.items[Q]=J}toJSON($,J){let Q=[];if(J?.onCreate)J.onCreate(Q);let X=0;for(let q of this.items)Q.push(CW.toJS(q,String(X++),J));return Q}toString($,J,Q){if(!$)return JSON.stringify(this);return bW.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:Q,onComment:J})}static from($,J,Q){let{replacer:X}=Q,q=new this($);if(J&&Symbol.iterator in Object(J)){let Y=0;for(let G of J){if(typeof X==="function"){let W=J instanceof Set?G:String(Y++);G=X.call(J,W,G)}q.items.push(PW.createNode(G,void 0,Q))}}return q}}function s6($){let J=o6.isScalar($)?$.value:$;if(J&&typeof J==="string")J=Number(J);return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:null}fW.YAMLSeq=u7});var Y2=S((xW)=>{var TW=p(),l7=U$(),vW={collection:"seq",default:!0,nodeClass:l7.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,J){if(!TW.isSeq($))J("Expected a sequence for this tag");return $},createNode:($,J,Q)=>l7.YAMLSeq.from($,J,Q)};xW.seq=vW});var k2=S((kW)=>{var hW=x2(),gW={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,J,Q,X){return J=Object.assign({actualString:!0},J),hW.stringifyString($,J,Q,X)}};kW.string=gW});var t6=S((uW)=>{var c7=Y0(),d7={identify:($)=>$==null,createNode:()=>new c7.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new c7.Scalar(null),stringify:({source:$},J)=>typeof $==="string"&&d7.test.test($)?$:J.options.nullStr};uW.nullTag=d7});var P4=S((dW)=>{var cW=Y0(),p7={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new cW.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:J},Q){if($&&p7.test.test($)){let X=$[0]==="t"||$[0]==="T";if(J===X)return $}return J?Q.options.trueStr:Q.options.falseStr}};dW.boolTag=p7});var G2=S((nW)=>{function iW({format:$,minFractionDigits:J,tag:Q,value:X}){if(typeof X==="bigint")return String(X);let q=typeof X==="number"?X:Number(X);if(!isFinite(q))return isNaN(q)?".nan":q<0?"-.inf":".inf";let Y=Object.is(X,-0)?"-0":JSON.stringify(X);if(!$&&J&&(!Q||Q==="tag:yaml.org,2002:float")&&/^-?\d/.test(Y)&&!Y.includes("e")){let G=Y.indexOf(".");if(G<0)G=Y.length,Y+=".";let W=J-(Y.length-G-1);while(W-- >0)Y+="0"}return Y}nW.stringifyNumber=iW});var E4=S((eW)=>{var aW=Y0(),b4=G2(),sW={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:b4.stringifyNumber},oW={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 J=Number($.value);return isFinite(J)?J.toExponential():b4.stringifyNumber($)}},tW={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let J=new aW.Scalar(parseFloat($)),Q=$.indexOf(".");if(Q!==-1&&$[$.length-1]==="0")J.minFractionDigits=$.length-Q-1;return J},stringify:b4.stringifyNumber};eW.float=tW;eW.floatExp=oW;eW.floatNaN=sW});var C4=S((Gz)=>{var i7=G2(),e6=($)=>typeof $==="bigint"||Number.isInteger($),S4=($,J,Q,{intAsBigInt:X})=>X?BigInt($):parseInt($.substring(J),Q);function n7($,J,Q){let{value:X}=$;if(e6(X)&&X>=0)return Q+X.toString(J);return i7.stringifyNumber($)}var Xz={identify:($)=>e6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,J,Q)=>S4($,2,8,Q),stringify:($)=>n7($,8,"0o")},qz={identify:e6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,J,Q)=>S4($,0,10,Q),stringify:i7.stringifyNumber},Yz={identify:($)=>e6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,J,Q)=>S4($,2,16,Q),stringify:($)=>n7($,16,"0x")};Gz.int=qz;Gz.intHex=Yz;Gz.intOct=Xz});var r7=S((Oz)=>{var Bz=q2(),Uz=t6(),Vz=Y2(),Dz=k2(),Fz=P4(),f4=E4(),I4=C4(),Mz=[Bz.map,Vz.seq,Dz.string,Uz.nullTag,Fz.boolTag,I4.intOct,I4.int,I4.intHex,f4.floatNaN,f4.floatExp,f4.float];Oz.schema=Mz});var s7=S((Zz)=>{var jz=Y0(),Lz=q2(),Nz=Y2();function a7($){return typeof $==="bigint"||Number.isInteger($)}var $9=({value:$})=>JSON.stringify($),Az=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:$9},{identify:($)=>$==null,createNode:()=>new jz.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:$9},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:$9},{identify:a7,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,J,{intAsBigInt:Q})=>Q?BigInt($):parseInt($,10),stringify:({value:$})=>a7($)?$.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:$9}],_z={default:!0,tag:"",test:/^/,resolve($,J){return J(`Unresolved plain scalar ${JSON.stringify($)}`),$}},Rz=[Lz.map,Nz.seq].concat(Az,_z);Zz.schema=Rz});var v4=S((Ez)=>{var m2=j6("buffer"),T4=Y0(),Pz=x2(),bz={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,J){if(typeof m2.Buffer==="function")return m2.Buffer.from($,"base64");else if(typeof atob==="function"){let Q=atob($.replace(/[\n\r]/g,"")),X=new Uint8Array(Q.length);for(let q=0;q<Q.length;++q)X[q]=Q.charCodeAt(q);return X}else return J("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:J,value:Q},X,q,Y){if(!Q)return"";let G=Q,W;if(typeof m2.Buffer==="function")W=G instanceof m2.Buffer?G.toString("base64"):m2.Buffer.from(G.buffer).toString("base64");else if(typeof btoa==="function"){let z="";for(let H=0;H<G.length;++H)z+=String.fromCharCode(G[H]);W=btoa(z)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(J??(J=T4.Scalar.BLOCK_LITERAL),J!==T4.Scalar.QUOTE_DOUBLE){let z=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),H=Math.ceil(W.length/z),B=Array(H);for(let U=0,V=0;U<H;++U,V+=z)B[U]=W.substr(V,z);W=B.join(J===T4.Scalar.BLOCK_LITERAL?`
53
+ `:" ")}return Pz.stringifyString({comment:$,type:J,value:W},X,q,Y)}};Ez.binary=bz});var Q9=S((Tz)=>{var J9=p(),x4=z$(),Cz=Y0(),fz=U$();function o7($,J){if(J9.isSeq($))for(let Q=0;Q<$.items.length;++Q){let X=$.items[Q];if(J9.isPair(X))continue;else if(J9.isMap(X)){if(X.items.length>1)J("Each pair must have its own sequence indicator");let q=X.items[0]||new x4.Pair(new Cz.Scalar(null));if(X.commentBefore)q.key.commentBefore=q.key.commentBefore?`${X.commentBefore}
54
+ ${q.key.commentBefore}`:X.commentBefore;if(X.comment){let Y=q.value??q.key;Y.comment=Y.comment?`${X.comment}
55
+ ${Y.comment}`:X.comment}X=q}$.items[Q]=J9.isPair(X)?X:new x4.Pair(X)}else J("Expected a sequence for this tag");return $}function t7($,J,Q){let{replacer:X}=Q,q=new fz.YAMLSeq($);q.tag="tag:yaml.org,2002:pairs";let Y=0;if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,String(Y++),G);let W,z;if(Array.isArray(G))if(G.length===2)W=G[0],z=G[1];else throw TypeError(`Expected [key, value] tuple: ${G}`);else if(G&&G instanceof Object){let H=Object.keys(G);if(H.length===1)W=H[0],z=G[W];else throw TypeError(`Expected tuple with one key, not ${H.length} keys`)}else W=G;q.items.push(x4.createPair(W,z,Q))}return q}var Iz={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:o7,createNode:t7};Tz.createPairs=t7;Tz.pairs=Iz;Tz.resolvePairs=o7});var h4=S((kz)=>{var e7=p(),y4=Y$(),u2=B$(),hz=U$(),$3=Q9();class S$ extends hz.YAMLSeq{constructor(){super();this.add=u2.YAMLMap.prototype.add.bind(this),this.delete=u2.YAMLMap.prototype.delete.bind(this),this.get=u2.YAMLMap.prototype.get.bind(this),this.has=u2.YAMLMap.prototype.has.bind(this),this.set=u2.YAMLMap.prototype.set.bind(this),this.tag=S$.tag}toJSON($,J){if(!J)return super.toJSON($);let Q=new Map;if(J?.onCreate)J.onCreate(Q);for(let X of this.items){let q,Y;if(e7.isPair(X))q=y4.toJS(X.key,"",J),Y=y4.toJS(X.value,q,J);else q=y4.toJS(X,"",J);if(Q.has(q))throw Error("Ordered maps must not include duplicate keys");Q.set(q,Y)}return Q}static from($,J,Q){let X=$3.createPairs($,J,Q),q=new this;return q.items=X.items,q}}S$.tag="tag:yaml.org,2002:omap";var gz={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:S$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=$3.resolvePairs($,J),X=[];for(let{key:q}of Q.items)if(e7.isScalar(q))if(X.includes(q.value))J(`Ordered maps must not include duplicate keys: ${q.value}`);else X.push(q.value);return Object.assign(new S$,Q)},createNode:($,J,Q)=>S$.from($,J,Q)};kz.YAMLOMap=S$;kz.omap=gz});var Y3=S((lz)=>{var J3=Y0();function Q3({value:$,source:J},Q){if(J&&($?X3:q3).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var X3={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new J3.Scalar(!0),stringify:Q3},q3={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new J3.Scalar(!1),stringify:Q3};lz.falseTag=q3;lz.trueTag=X3});var G3=S((az)=>{var pz=Y0(),g4=G2(),iz={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:g4.stringifyNumber},nz={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 J=Number($.value);return isFinite(J)?J.toExponential():g4.stringifyNumber($)}},rz={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new pz.Scalar(parseFloat($.replace(/_/g,""))),Q=$.indexOf(".");if(Q!==-1){let X=$.substring(Q+1).replace(/_/g,"");if(X[X.length-1]==="0")J.minFractionDigits=X.length}return J},stringify:g4.stringifyNumber};az.float=rz;az.floatExp=nz;az.floatNaN=iz});var z3=S((XH)=>{var W3=G2(),l2=($)=>typeof $==="bigint"||Number.isInteger($);function X9($,J,Q,{intAsBigInt:X}){let q=$[0];if(q==="-"||q==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let G=BigInt($);return q==="-"?BigInt(-1)*G:G}let Y=parseInt($,Q);return q==="-"?-1*Y:Y}function k4($,J,Q){let{value:X}=$;if(l2(X)){let q=X.toString(J);return X<0?"-"+Q+q.substr(1):Q+q}return W3.stringifyNumber($)}var ez={identify:l2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>X9($,2,2,Q),stringify:($)=>k4($,2,"0b")},$H={identify:l2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>X9($,1,8,Q),stringify:($)=>k4($,8,"0")},JH={identify:l2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>X9($,0,10,Q),stringify:W3.stringifyNumber},QH={identify:l2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>X9($,2,16,Q),stringify:($)=>k4($,16,"0x")};XH.int=JH;XH.intBin=ez;XH.intHex=QH;XH.intOct=$H});var m4=S((HH)=>{var G9=p(),q9=z$(),Y9=B$();class C$ extends Y9.YAMLMap{constructor($){super($);this.tag=C$.tag}add($){let J;if(G9.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new q9.Pair($.key,null);else J=new q9.Pair($,null);if(!Y9.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=Y9.findPair(this.items,$);return!J&&G9.isPair(Q)?G9.isScalar(Q.key)?Q.key.value:Q.key:Q}set($,J){if(typeof J!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof J}`);let Q=Y9.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new q9.Pair($))}toJSON($,J){return super.toJSON($,J,Set)}toString($,J,Q){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),J,Q);else throw Error("Set items must all have null values")}static from($,J,Q){let{replacer:X}=Q,q=new this($);if(J&&Symbol.iterator in Object(J))for(let Y of J){if(typeof X==="function")Y=X.call(J,Y,Y);q.items.push(q9.createPair(Y,null,Q))}return q}}C$.tag="tag:yaml.org,2002:set";var zH={collection:"map",identify:($)=>$ instanceof Set,nodeClass:C$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>C$.from($,J,Q),resolve($,J){if(G9.isMap($))if($.hasAllNullValues(!0))return Object.assign(new C$,$);else J("Set items must all have null values");else J("Expected a mapping for this tag");return $}};HH.YAMLSet=C$;HH.set=zH});var l4=S((MH)=>{var VH=G2();function u4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,q=(G)=>J?BigInt(G):Number(G),Y=X.replace(/_/g,"").split(":").reduce((G,W)=>G*q(60)+q(W),q(0));return Q==="-"?q(-1)*Y:Y}function H3($){let{value:J}=$,Q=(G)=>G;if(typeof J==="bigint")Q=(G)=>BigInt(G);else if(isNaN(J)||!isFinite(J))return VH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let q=Q(60),Y=[J%q];if(J<60)Y.unshift(0);else if(J=(J-Y[0])/q,Y.unshift(J%q),J>=60)J=(J-Y[0])/q,Y.unshift(J);return X+Y.map((G)=>String(G).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var DH={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:($,J,{intAsBigInt:Q})=>u4($,Q),stringify:H3},FH={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:($)=>u4($,!1),stringify:H3},B3={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 J=$.match(B3.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,q,Y,G,W]=J.map(Number),z=J[7]?Number((J[7]+"00").substr(1,3)):0,H=Date.UTC(Q,X-1,q,Y||0,G||0,W||0,z),B=J[8];if(B&&B!=="Z"){let U=u4(B,!1);if(Math.abs(U)<30)U*=60;H-=60000*U}return new Date(H)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};MH.floatTime=FH;MH.intTime=DH;MH.timestamp=B3});var V3=S((SH)=>{var LH=q2(),NH=t6(),AH=Y2(),_H=k2(),RH=v4(),U3=Y3(),c4=G3(),W9=z3(),ZH=d6(),wH=h4(),PH=Q9(),bH=m4(),d4=l4(),EH=[LH.map,AH.seq,_H.string,NH.nullTag,U3.trueTag,U3.falseTag,W9.intBin,W9.intOct,W9.int,W9.intHex,c4.floatNaN,c4.floatExp,c4.float,RH.binary,ZH.merge,wH.omap,PH.pairs,bH.set,d4.intTime,d4.floatTime,d4.timestamp];SH.schema=EH});var _3=S((gH)=>{var O3=q2(),fH=t6(),K3=Y2(),IH=k2(),TH=P4(),p4=E4(),i4=C4(),vH=r7(),xH=s7(),j3=v4(),c2=d6(),L3=h4(),N3=Q9(),D3=V3(),A3=m4(),z9=l4(),F3=new Map([["core",vH.schema],["failsafe",[O3.map,K3.seq,IH.string]],["json",xH.schema],["yaml11",D3.schema],["yaml-1.1",D3.schema]]),M3={binary:j3.binary,bool:TH.boolTag,float:p4.float,floatExp:p4.floatExp,floatNaN:p4.floatNaN,floatTime:z9.floatTime,int:i4.int,intHex:i4.intHex,intOct:i4.intOct,intTime:z9.intTime,map:O3.map,merge:c2.merge,null:fH.nullTag,omap:L3.omap,pairs:N3.pairs,seq:K3.seq,set:A3.set,timestamp:z9.timestamp},yH={"tag:yaml.org,2002:binary":j3.binary,"tag:yaml.org,2002:merge":c2.merge,"tag:yaml.org,2002:omap":L3.omap,"tag:yaml.org,2002:pairs":N3.pairs,"tag:yaml.org,2002:set":A3.set,"tag:yaml.org,2002:timestamp":z9.timestamp};function hH($,J,Q){let X=F3.get(J);if(X&&!$)return Q&&!X.includes(c2.merge)?X.concat(c2.merge):X.slice();let q=X;if(!q)if(Array.isArray($))q=[];else{let Y=Array.from(F3.keys()).filter((G)=>G!=="yaml11").map((G)=>JSON.stringify(G)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${Y} or define customTags array`)}if(Array.isArray($))for(let Y of $)q=q.concat(Y);else if(typeof $==="function")q=$(q.slice());if(Q)q=q.concat(c2.merge);return q.reduce((Y,G)=>{let W=typeof G==="string"?M3[G]:G;if(!W){let z=JSON.stringify(G),H=Object.keys(M3).map((B)=>JSON.stringify(B)).join(", ");throw Error(`Unknown custom tag ${z}; use one of ${H}`)}if(!Y.includes(W))Y.push(W);return Y},[])}gH.coreKnownTags=yH;gH.getTags=hH});var a4=S((pH)=>{var n4=p(),uH=q2(),lH=Y2(),cH=k2(),H9=_3(),dH=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class r4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:q,sortMapEntries:Y,toStringDefaults:G}){this.compat=Array.isArray($)?H9.getTags($,"compat"):$?H9.getTags(null,$):null,this.name=typeof q==="string"&&q||"core",this.knownTags=X?H9.coreKnownTags:{},this.tags=H9.getTags(J,this.name,Q),this.toStringOptions=G??null,Object.defineProperty(this,n4.MAP,{value:uH.map}),Object.defineProperty(this,n4.SCALAR,{value:cH.string}),Object.defineProperty(this,n4.SEQ,{value:lH.seq}),this.sortMapEntries=typeof Y==="function"?Y:Y===!0?dH:null}clone(){let $=Object.create(r4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}pH.Schema=r4});var R3=S((aH)=>{var nH=p(),s4=y2(),d2=T2();function rH($,J){let Q=[],X=J.directives===!0;if(J.directives!==!1&&$.directives){let z=$.directives.toString($);if(z)Q.push(z),X=!0;else if($.directives.docStart)X=!0}if(X)Q.push("---");let q=s4.createStringifyContext($,J),{commentString:Y}=q.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let z=Y($.commentBefore);Q.unshift(d2.indentComment(z,""))}let G=!1,W=null;if($.contents){if(nH.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let B=Y($.contents.commentBefore);Q.push(d2.indentComment(B,""))}q.forceBlockIndent=!!$.comment,W=$.contents.comment}let z=W?void 0:()=>G=!0,H=s4.stringify($.contents,q,()=>W=null,z);if(W)H+=d2.lineComment(H,"",Y(W));if((H[0]==="|"||H[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${H}`;else Q.push(H)}else Q.push(s4.stringify($.contents,q));if($.directives?.docEnd)if($.comment){let z=Y($.comment);if(z.includes(`
56
+ `))Q.push("..."),Q.push(d2.indentComment(z,""));else Q.push(`... ${z}`)}else Q.push("...");else{let z=$.comment;if(z&&G)z=z.replace(/^\n+/,"");if(z){if((!G||W)&&Q[Q.length-1]!=="")Q.push("");Q.push(d2.indentComment(Y(z),""))}}return Q.join(`
57
57
  `)+`
58
- `}uH.stringifyDocument=mH});var k2=C((sH)=>{var cH=w2(),Q2=T6(),R0=d(),pH=Y$(),dH=J$(),iH=d4(),nH=OJ(),n4=C6(),rH=V4(),aH=P2(),r4=U4();class a4{constructor($,J,Q){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,R0.NODE_TYPE,{value:R0.DOC});let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J,J=void 0;let Y=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=Y;let{version:G}=Y;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)G=this.directives.yaml.version}else this.directives=new r4.Directives({version:G});this.setSchema(G,Q),this.contents=$===void 0?null:this.createNode($,X,Q)}clone(){let $=Object.create(a4.prototype,{[R0.NODE_TYPE]:{value:R0.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=R0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(X2(this.contents))this.contents.add($)}addIn($,J){if(X2(this.contents))this.contents.addIn($,J)}createAlias($,J){if(!$.anchor){let Q=n4.anchorNames(this);$.anchor=!J||Q.has(J)?n4.findNewAnchor(J||"a",Q):J}return new cH.Alias($.anchor)}createNode($,J,Q){let X=void 0;if(typeof J==="function")$=J.call({"":$},"",$),X=J;else if(Array.isArray(J)){let D=(R)=>typeof R==="number"||R instanceof String||R instanceof Number,M=J.filter(D).map(String);if(M.length>0)J=J.concat(M);X=J}else if(Q===void 0&&J)Q=J,J=void 0;let{aliasDuplicateObjects:Y,anchorPrefix:G,flow:q,keepUndefined:W,onTagObj:z,tag:H}=Q??{},{onAnchor:B,setAnchors:U,sourceObjects:V}=n4.createNodeAnchors(this,G||"a"),O={aliasDuplicateObjects:Y??!0,keepUndefined:W??!1,onAnchor:B,onTagObj:z,replacer:X,schema:this.schema,sourceObjects:V},F=aH.createNode($,H,O);if(q&&R0.isCollection(F))F.flow=!0;return U(),F}createPair($,J,Q={}){let X=this.createNode($,null,Q),Y=this.createNode(J,null,Q);return new pH.Pair(X,Y)}delete($){return X2(this.contents)?this.contents.delete($):!1}deleteIn($){if(Q2.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return X2(this.contents)?this.contents.deleteIn($):!1}get($,J){return R0.isCollection(this.contents)?this.contents.get($,J):void 0}getIn($,J){if(Q2.isEmptyPath($))return!J&&R0.isScalar(this.contents)?this.contents.value:this.contents;return R0.isCollection(this.contents)?this.contents.getIn($,J):void 0}has($){return R0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(Q2.isEmptyPath($))return this.contents!==void 0;return R0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,J){if(this.contents==null)this.contents=Q2.collectionFromPath(this.schema,[$],J);else if(X2(this.contents))this.contents.set($,J)}setIn($,J){if(Q2.isEmptyPath($))this.contents=J;else if(this.contents==null)this.contents=Q2.collectionFromPath(this.schema,Array.from($),J);else if(X2(this.contents))this.contents.setIn($,J)}setSchema($,J={}){if(typeof $==="number")$=String($);let Q;switch($){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new r4.Directives({version:"1.1"});Q={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=$;else this.directives=new r4.Directives({version:$});Q={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;Q=null;break;default:{let X=JSON.stringify($);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${X}`)}}if(J.schema instanceof Object)this.schema=J.schema;else if(Q)this.schema=new iH.Schema(Object.assign(Q,J));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:J,mapAsMap:Q,maxAliasCount:X,onAnchor:Y,reviver:G}={}){let q={anchors:new Map,doc:this,keep:!$,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},W=dH.toJS(this.contents,J??"",q);if(typeof Y==="function")for(let{count:z,res:H}of q.anchors.values())Y(H,z);return typeof G==="function"?rH.applyReviver(G,{"":W},"",W):W}toJSON($,J){return this.toJS({json:!0,jsonArg:$,mapAsMap:!1,onAnchor:J})}toString($={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in $&&(!Number.isInteger($.indent)||Number($.indent)<=0)){let J=JSON.stringify($.indent);throw Error(`"indent" option must be a positive integer, not ${J}`)}return nH.stringifyDocument(this,$)}}function X2($){if(R0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}sH.Document=a4});var m2=C((eH)=>{class q9 extends Error{constructor($,J,Q,X){super();this.name=$,this.code=Q,this.message=X,this.pos=J}}class KJ extends q9{constructor($,J,Q){super("YAMLParseError",$,J,Q)}}class RJ extends q9{constructor($,J,Q){super("YAMLWarning",$,J,Q)}}var tH=($,J)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((W)=>J.linePos(W));let{line:X,col:Y}=Q.linePos[0];Q.message+=` at line ${X}, column ${Y}`;let G=Y-1,q=$.substring(J.lineStarts[X-1],J.lineStarts[X]).replace(/[\n\r]+$/,"");if(G>=60&&q.length>80){let W=Math.min(G-39,q.length-79);q="\u2026"+q.substring(W),G-=W-1}if(q.length>80)q=q.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(q.substring(0,G))){let W=$.substring(J.lineStarts[X-2],J.lineStarts[X-1]);if(W.length>80)W=W.substring(0,79)+`\u2026
59
- `;q=W+q}if(/[^ ]/.test(q)){let W=1,z=Q.linePos[1];if(z?.line===X&&z.col>Y)W=Math.max(1,Math.min(z.col-Y,80-G));let H=" ".repeat(G)+"^".repeat(W);Q.message+=`:
58
+ `}aH.stringifyDocument=rH});var p2=S((qB)=>{var oH=f2(),W2=h6(),_0=p(),tH=z$(),eH=Y$(),$B=a4(),JB=R3(),o4=v6(),QB=O4(),XB=I2(),t4=M4();class e4{constructor($,J,Q){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,_0.NODE_TYPE,{value:_0.DOC});let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J,J=void 0;let q=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=q;let{version:Y}=q;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)Y=this.directives.yaml.version}else this.directives=new t4.Directives({version:Y});this.setSchema(Y,Q),this.contents=$===void 0?null:this.createNode($,X,Q)}clone(){let $=Object.create(e4.prototype,{[_0.NODE_TYPE]:{value:_0.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=_0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(z2(this.contents))this.contents.add($)}addIn($,J){if(z2(this.contents))this.contents.addIn($,J)}createAlias($,J){if(!$.anchor){let Q=o4.anchorNames(this);$.anchor=!J||Q.has(J)?o4.findNewAnchor(J||"a",Q):J}return new oH.Alias($.anchor)}createNode($,J,Q){let X=void 0;if(typeof J==="function")$=J.call({"":$},"",$),X=J;else if(Array.isArray(J)){let D=(j)=>typeof j==="number"||j instanceof String||j instanceof Number,M=J.filter(D).map(String);if(M.length>0)J=J.concat(M);X=J}else if(Q===void 0&&J)Q=J,J=void 0;let{aliasDuplicateObjects:q,anchorPrefix:Y,flow:G,keepUndefined:W,onTagObj:z,tag:H}=Q??{},{onAnchor:B,setAnchors:U,sourceObjects:V}=o4.createNodeAnchors(this,Y||"a"),O={aliasDuplicateObjects:q??!0,keepUndefined:W??!1,onAnchor:B,onTagObj:z,replacer:X,schema:this.schema,sourceObjects:V},F=XB.createNode($,H,O);if(G&&_0.isCollection(F))F.flow=!0;return U(),F}createPair($,J,Q={}){let X=this.createNode($,null,Q),q=this.createNode(J,null,Q);return new tH.Pair(X,q)}delete($){return z2(this.contents)?this.contents.delete($):!1}deleteIn($){if(W2.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return z2(this.contents)?this.contents.deleteIn($):!1}get($,J){return _0.isCollection(this.contents)?this.contents.get($,J):void 0}getIn($,J){if(W2.isEmptyPath($))return!J&&_0.isScalar(this.contents)?this.contents.value:this.contents;return _0.isCollection(this.contents)?this.contents.getIn($,J):void 0}has($){return _0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(W2.isEmptyPath($))return this.contents!==void 0;return _0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,J){if(this.contents==null)this.contents=W2.collectionFromPath(this.schema,[$],J);else if(z2(this.contents))this.contents.set($,J)}setIn($,J){if(W2.isEmptyPath($))this.contents=J;else if(this.contents==null)this.contents=W2.collectionFromPath(this.schema,Array.from($),J);else if(z2(this.contents))this.contents.setIn($,J)}setSchema($,J={}){if(typeof $==="number")$=String($);let Q;switch($){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new t4.Directives({version:"1.1"});Q={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=$;else this.directives=new t4.Directives({version:$});Q={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;Q=null;break;default:{let X=JSON.stringify($);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${X}`)}}if(J.schema instanceof Object)this.schema=J.schema;else if(Q)this.schema=new $B.Schema(Object.assign(Q,J));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:J,mapAsMap:Q,maxAliasCount:X,onAnchor:q,reviver:Y}={}){let G={anchors:new Map,doc:this,keep:!$,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},W=eH.toJS(this.contents,J??"",G);if(typeof q==="function")for(let{count:z,res:H}of G.anchors.values())q(H,z);return typeof Y==="function"?QB.applyReviver(Y,{"":W},"",W):W}toJSON($,J){return this.toJS({json:!0,jsonArg:$,mapAsMap:!1,onAnchor:J})}toString($={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in $&&(!Number.isInteger($.indent)||Number($.indent)<=0)){let J=JSON.stringify($.indent);throw Error(`"indent" option must be a positive integer, not ${J}`)}return JB.stringifyDocument(this,$)}}function z2($){if(_0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}qB.Document=e4});var i2=S((WB)=>{class B9 extends Error{constructor($,J,Q,X){super();this.name=$,this.code=Q,this.message=X,this.pos=J}}class Z3 extends B9{constructor($,J,Q){super("YAMLParseError",$,J,Q)}}class w3 extends B9{constructor($,J,Q){super("YAMLWarning",$,J,Q)}}var GB=($,J)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((W)=>J.linePos(W));let{line:X,col:q}=Q.linePos[0];Q.message+=` at line ${X}, column ${q}`;let Y=q-1,G=$.substring(J.lineStarts[X-1],J.lineStarts[X]).replace(/[\n\r]+$/,"");if(Y>=60&&G.length>80){let W=Math.min(Y-39,G.length-79);G="\u2026"+G.substring(W),Y-=W-1}if(G.length>80)G=G.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(G.substring(0,Y))){let W=$.substring(J.lineStarts[X-2],J.lineStarts[X-1]);if(W.length>80)W=W.substring(0,79)+`\u2026
59
+ `;G=W+G}if(/[^ ]/.test(G)){let W=1,z=Q.linePos[1];if(z?.line===X&&z.col>q)W=Math.max(1,Math.min(z.col-q,80-Y));let H=" ".repeat(Y)+"^".repeat(W);Q.message+=`:
60
60
 
61
- ${q}
61
+ ${G}
62
62
  ${H}
63
- `}};eH.YAMLError=q9;eH.YAMLParseError=KJ;eH.YAMLWarning=RJ;eH.prettifyError=tH});var u2=C((GB)=>{function YB($,{flow:J,indicator:Q,next:X,offset:Y,onError:G,parentIndent:q,startOnNewline:W}){let z=!1,H=W,B=W,U="",V="",O=!1,F=!1,D=null,M=null,R=null,L=null,N=null,Z=null,b=null;for(let A of $){if(F){if(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma")G(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");F=!1}if(D){if(H&&A.type!=="comment"&&A.type!=="newline")G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");D=null}switch(A.type){case"space":if(!J&&(Q!=="doc-start"||X?.type!=="flow-collection")&&A.source.includes("\t"))D=A;B=!0;break;case"comment":{if(!B)G(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=A.source.substring(1)||" ";if(!U)U=S;else U+=V+S;V="",H=!1;break}case"newline":if(H){if(U)U+=A.source;else if(!Z||Q!=="seq-item-ind")z=!0}else V+=A.source;if(H=!0,O=!0,M||R)L=A;B=!0;break;case"anchor":if(M)G(A,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(A.source.endsWith(":"))G(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);M=A,b??(b=A.offset),H=!1,B=!1,F=!0;break;case"tag":{if(R)G(A,"MULTIPLE_TAGS","A node can have at most one tag");R=A,b??(b=A.offset),H=!1,B=!1,F=!0;break}case Q:if(M||R)G(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`);if(Z)G(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${J??"collection"}`);Z=A,H=Q==="seq-item-ind"||Q==="explicit-key-ind",B=!1;break;case"comma":if(J){if(N)G(A,"UNEXPECTED_TOKEN",`Unexpected , in ${J}`);N=A,H=!1,B=!1;break}default:G(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),H=!1,B=!1}}let w=$[$.length-1],f=w?w.offset+w.source.length:Y;if(F&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))G(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(D&&(H&&D.indent<=q||X?.type==="block-map"||X?.type==="block-seq"))G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:N,found:Z,spaceBefore:z,comment:U,hasNewline:O,anchor:M,tag:R,newlineAfterProp:L,end:f,start:b??f}}GB.resolveProps=YB});var W9=C((WB)=>{function s4($){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 J of $.end)if(J.type==="newline")return!0}return!1;case"flow-collection":for(let J of $.items){for(let Q of J.start)if(Q.type==="newline")return!0;if(J.sep){for(let Q of J.sep)if(Q.type==="newline")return!0}if(s4(J.key)||s4(J.value))return!0}return!1;default:return!0}}WB.containsNewline=s4});var o4=C((UB)=>{var HB=W9();function BB($,J,Q){if(J?.type==="flow-collection"){let X=J.end[0];if(X.indent===$&&(X.source==="]"||X.source==="}")&&HB.containsNewline(J))Q(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}UB.flowIndentCheck=BB});var t4=C((FB)=>{var LJ=d();function DB($,J,Q){let{uniqueKeys:X}=$.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(G,q)=>G===q||LJ.isScalar(G)&&LJ.isScalar(q)&&G.value===q.value;return J.some((G)=>Y(G.key,Q))}FB.mapIncludes=DB});var ZJ=C((jB)=>{var jJ=Y$(),OB=q$(),NJ=u2(),KB=W9(),_J=o4(),RB=t4(),AJ="All mapping items must start at the same column";function LB({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let W=new(G?.nodeClass??OB.YAMLMap)(Q.schema);if(Q.atRoot)Q.atRoot=!1;let z=X.offset,H=null;for(let B of X.items){let{start:U,key:V,sep:O,value:F}=B,D=NJ.resolveProps(U,{indicator:"explicit-key-ind",next:V??O?.[0],offset:z,onError:Y,parentIndent:X.indent,startOnNewline:!0}),M=!D.found;if(M){if(V){if(V.type==="block-seq")Y(z,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in V&&V.indent!==X.indent)Y(z,"BAD_INDENT",AJ)}if(!D.anchor&&!D.tag&&!O){if(H=D.end,D.comment)if(W.comment)W.comment+=`
65
- `+D.comment;else W.comment=D.comment;continue}if(D.newlineAfterProp||KB.containsNewline(V))Y(V??U[U.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(D.found?.indent!==X.indent)Y(z,"BAD_INDENT",AJ);Q.atKey=!0;let R=D.end,L=V?$(Q,V,D,Y):J(Q,R,U,null,D,Y);if(Q.schema.compat)_J.flowIndentCheck(X.indent,V,Y);if(Q.atKey=!1,RB.mapIncludes(Q,W.items,L))Y(R,"DUPLICATE_KEY","Map keys must be unique");let N=NJ.resolveProps(O??[],{indicator:"map-value-ind",next:F,offset:L.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!V||V.type==="block-scalar"});if(z=N.end,N.found){if(M){if(F?.type==="block-map"&&!N.hasNewline)Y(z,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&D.start<N.found.offset-1024)Y(L.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let Z=F?$(Q,F,N,Y):J(Q,z,O,null,N,Y);if(Q.schema.compat)_J.flowIndentCheck(X.indent,F,Y);z=Z.range[2];let b=new jJ.Pair(L,Z);if(Q.options.keepSourceTokens)b.srcToken=B;W.items.push(b)}else{if(M)Y(L.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(N.comment)if(L.comment)L.comment+=`
66
- `+N.comment;else L.comment=N.comment;let Z=new jJ.Pair(L);if(Q.options.keepSourceTokens)Z.srcToken=B;W.items.push(Z)}}if(H&&H<z)Y(H,"IMPOSSIBLE","Map comment with trailing content");return W.range=[X.offset,z,H??z],W}jB.resolveBlockMap=LB});var wJ=C((PB)=>{var _B=W$(),AB=u2(),ZB=o4();function wB({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let W=new(G?.nodeClass??_B.YAMLSeq)(Q.schema);if(Q.atRoot)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let z=X.offset,H=null;for(let{start:B,value:U}of X.items){let V=AB.resolveProps(B,{indicator:"seq-item-ind",next:U,offset:z,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!V.found)if(V.anchor||V.tag||U)if(U?.type==="block-seq")Y(V.end,"BAD_INDENT","All sequence items must start at the same column");else Y(z,"MISSING_CHAR","Sequence item without - indicator");else{if(H=V.end,V.comment)W.comment=V.comment;continue}let O=U?$(Q,U,V,Y):J(Q,V.end,B,null,V,Y);if(Q.schema.compat)ZB.flowIndentCheck(X.indent,U,Y);z=O.range[2],W.items.push(O)}return W.range=[X.offset,z,H??z],W}PB.resolveBlockSeq=wB});var Y2=C((SB)=>{function EB($,J,Q,X){let Y="";if($){let G=!1,q="";for(let W of $){let{source:z,type:H}=W;switch(H){case"space":G=!0;break;case"comment":{if(Q&&!G)X(W,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let B=z.substring(1)||" ";if(!Y)Y=B;else Y+=q+B;q="";break}case"newline":if(Y)q+=z;G=!0;break;default:X(W,"UNEXPECTED_TOKEN",`Unexpected ${H} at node end`)}J+=z.length}}return{comment:Y,offset:J}}SB.resolveEnd=EB});var EJ=C((gB)=>{var fB=d(),IB=Y$(),PJ=q$(),TB=W$(),vB=Y2(),bJ=u2(),xB=W9(),hB=t4(),e4="Block collections are not allowed within flow collections",$8=($)=>$&&($.type==="block-map"||$.type==="block-seq");function yB({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let q=X.start.source==="{",W=q?"flow map":"flow sequence",H=new(G?.nodeClass??(q?PJ.YAMLMap:TB.YAMLSeq))(Q.schema);H.flow=!0;let B=Q.atRoot;if(B)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let U=X.offset+X.start.source.length;for(let M=0;M<X.items.length;++M){let R=X.items[M],{start:L,key:N,sep:Z,value:b}=R,w=bJ.resolveProps(L,{flow:W,indicator:"explicit-key-ind",next:N??Z?.[0],offset:U,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!Z&&!b){if(M===0&&w.comma)Y(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`);else if(M<X.items.length-1)Y(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${W}`);if(w.comment)if(H.comment)H.comment+=`
67
- `+w.comment;else H.comment=w.comment;U=w.end;continue}if(!q&&Q.options.strict&&xB.containsNewline(N))Y(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(M===0){if(w.comma)Y(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`)}else{if(!w.comma)Y(w.start,"MISSING_CHAR",`Missing , between ${W} items`);if(w.comment){let f="";$:for(let A of L)switch(A.type){case"comma":case"space":break;case"comment":f=A.source.substring(1);break $;default:break $}if(f){let A=H.items[H.items.length-1];if(fB.isPair(A))A=A.value??A.key;if(A.comment)A.comment+=`
68
- `+f;else A.comment=f;w.comment=w.comment.substring(f.length+1)}}}if(!q&&!Z&&!w.found){let f=b?$(Q,b,w,Y):J(Q,w.end,Z,null,w,Y);if(H.items.push(f),U=f.range[2],$8(b))Y(f.range,"BLOCK_IN_FLOW",e4)}else{Q.atKey=!0;let f=w.end,A=N?$(Q,N,w,Y):J(Q,f,L,null,w,Y);if($8(N))Y(A.range,"BLOCK_IN_FLOW",e4);Q.atKey=!1;let S=bJ.resolveProps(Z??[],{flow:W,indicator:"map-value-ind",next:b,offset:A.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(S.found){if(!q&&!w.found&&Q.options.strict){if(Z)for(let g of Z){if(g===S.found)break;if(g.type==="newline"){Y(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(w.start<S.found.offset-1024)Y(S.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 ${W}`);else Y(S.start,"MISSING_CHAR",`Missing , or : between ${W} items`);let x=b?$(Q,b,S,Y):S.found?J(Q,S.end,Z,null,S,Y):null;if(x){if($8(b))Y(x.range,"BLOCK_IN_FLOW",e4)}else if(S.comment)if(A.comment)A.comment+=`
69
- `+S.comment;else A.comment=S.comment;let r=new IB.Pair(A,x);if(Q.options.keepSourceTokens)r.srcToken=R;if(q){let g=H;if(hB.mapIncludes(Q,g.items,A))Y(f,"DUPLICATE_KEY","Map keys must be unique");g.items.push(r)}else{let g=new PJ.YAMLMap(Q.schema);g.flow=!0,g.items.push(r);let c=(x??A).range;g.range=[A.range[0],c[1],c[2]],H.items.push(g)}U=x?x.range[2]:S.end}}let V=q?"}":"]",[O,...F]=X.end,D=U;if(O?.source===V)D=O.offset+O.source.length;else{let M=W[0].toUpperCase()+W.substring(1),R=B?`${M} must end with a ${V}`:`${M} in block collection must be sufficiently indented and end with a ${V}`;if(Y(U,B?"MISSING_CHAR":"BAD_INDENT",R),O&&O.source.length!==1)F.unshift(O)}if(F.length>0){let M=vB.resolveEnd(F,D,Q.options.strict,Y);if(M.comment)if(H.comment)H.comment+=`
70
- `+M.comment;else H.comment=M.comment;H.range=[X.offset,D,M.offset]}else H.range=[X.offset,D,D];return H}gB.resolveFlowCollection=yB});var SJ=C((rB)=>{var mB=d(),uB=Y0(),lB=q$(),cB=W$(),pB=ZJ(),dB=wJ(),iB=EJ();function J8($,J,Q,X,Y,G){let q=Q.type==="block-map"?pB.resolveBlockMap($,J,Q,X,G):Q.type==="block-seq"?dB.resolveBlockSeq($,J,Q,X,G):iB.resolveFlowCollection($,J,Q,X,G),W=q.constructor;if(Y==="!"||Y===W.tagName)return q.tag=W.tagName,q;if(Y)q.tag=Y;return q}function nB($,J,Q,X,Y){let G=X.tag,q=!G?null:J.directives.tagName(G.source,(V)=>Y(G,"TAG_RESOLVE_FAILED",V));if(Q.type==="block-seq"){let{anchor:V,newlineAfterProp:O}=X,F=V&&G?V.offset>G.offset?V:G:V??G;if(F&&(!O||O.offset<F.offset))Y(F,"MISSING_CHAR","Missing newline after block sequence props")}let W=Q.type==="block-map"?"map":Q.type==="block-seq"?"seq":Q.start.source==="{"?"map":"seq";if(!G||!q||q==="!"||q===lB.YAMLMap.tagName&&W==="map"||q===cB.YAMLSeq.tagName&&W==="seq")return J8($,J,Q,Y,q);let z=J.schema.tags.find((V)=>V.tag===q&&V.collection===W);if(!z){let V=J.schema.knownTags[q];if(V?.collection===W)J.schema.tags.push(Object.assign({},V,{default:!1})),z=V;else{if(V)Y(G,"BAD_COLLECTION_TYPE",`${V.tag} used for ${W} collection, but expects ${V.collection??"scalar"}`,!0);else Y(G,"TAG_RESOLVE_FAILED",`Unresolved tag: ${q}`,!0);return J8($,J,Q,Y,q)}}let H=J8($,J,Q,Y,q,z),B=z.resolve?.(H,(V)=>Y(G,"TAG_RESOLVE_FAILED",V),J.options)??H,U=mB.isNode(B)?B:new uB.Scalar(B);if(U.range=H.range,U.tag=q,z?.format)U.format=z.format;return U}rB.composeCollection=nB});var X8=C((eB)=>{var Q8=Y0();function sB($,J,Q){let X=J.offset,Y=oB(J,$.options.strict,Q);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let G=Y.mode===">"?Q8.Scalar.BLOCK_FOLDED:Q8.Scalar.BLOCK_LITERAL,q=J.source?tB(J.source):[],W=q.length;for(let D=q.length-1;D>=0;--D){let M=q[D][1];if(M===""||M==="\r")W=D;else break}if(W===0){let D=Y.chomp==="+"&&q.length>0?`
71
- `.repeat(Math.max(1,q.length-1)):"",M=X+Y.length;if(J.source)M+=J.source.length;return{value:D,type:G,comment:Y.comment,range:[X,M,M]}}let z=J.indent+Y.indent,H=J.offset+Y.length,B=0;for(let D=0;D<W;++D){let[M,R]=q[D];if(R===""||R==="\r"){if(Y.indent===0&&M.length>z)z=M.length}else{if(M.length<z)Q(H+M.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(Y.indent===0)z=M.length;if(B=D,z===0&&!$.atRoot)Q(H,"BAD_INDENT","Block scalar values in collections must be indented");break}H+=M.length+R.length+1}for(let D=q.length-1;D>=W;--D)if(q[D][0].length>z)W=D+1;let U="",V="",O=!1;for(let D=0;D<B;++D)U+=q[D][0].slice(z)+`
72
- `;for(let D=B;D<W;++D){let[M,R]=q[D];H+=M.length+R.length+1;let L=R[R.length-1]==="\r";if(L)R=R.slice(0,-1);if(R&&M.length<z){let Z=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;Q(H-R.length-(L?2:1),"BAD_INDENT",Z),M=""}if(G===Q8.Scalar.BLOCK_LITERAL)U+=V+M.slice(z)+R,V=`
73
- `;else if(M.length>z||R[0]==="\t"){if(V===" ")V=`
63
+ `}};WB.YAMLError=B9;WB.YAMLParseError=Z3;WB.YAMLWarning=w3;WB.prettifyError=GB});var n2=S((DB)=>{function VB($,{flow:J,indicator:Q,next:X,offset:q,onError:Y,parentIndent:G,startOnNewline:W}){let z=!1,H=W,B=W,U="",V="",O=!1,F=!1,D=null,M=null,j=null,L=null,A=null,R=null,b=null;for(let Z of $){if(F){if(Z.type!=="space"&&Z.type!=="newline"&&Z.type!=="comma")Y(Z.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");F=!1}if(D){if(H&&Z.type!=="comment"&&Z.type!=="newline")Y(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");D=null}switch(Z.type){case"space":if(!J&&(Q!=="doc-start"||X?.type!=="flow-collection")&&Z.source.includes("\t"))D=Z;B=!0;break;case"comment":{if(!B)Y(Z,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let I=Z.source.substring(1)||" ";if(!U)U=I;else U+=V+I;V="",H=!1;break}case"newline":if(H){if(U)U+=Z.source;else if(!R||Q!=="seq-item-ind")z=!0}else V+=Z.source;if(H=!0,O=!0,M||j)L=Z;B=!0;break;case"anchor":if(M)Y(Z,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(Z.source.endsWith(":"))Y(Z.offset+Z.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);M=Z,b??(b=Z.offset),H=!1,B=!1,F=!0;break;case"tag":{if(j)Y(Z,"MULTIPLE_TAGS","A node can have at most one tag");j=Z,b??(b=Z.offset),H=!1,B=!1,F=!0;break}case Q:if(M||j)Y(Z,"BAD_PROP_ORDER",`Anchors and tags must be after the ${Z.source} indicator`);if(R)Y(Z,"UNEXPECTED_TOKEN",`Unexpected ${Z.source} in ${J??"collection"}`);R=Z,H=Q==="seq-item-ind"||Q==="explicit-key-ind",B=!1;break;case"comma":if(J){if(A)Y(Z,"UNEXPECTED_TOKEN",`Unexpected , in ${J}`);A=Z,H=!1,B=!1;break}default:Y(Z,"UNEXPECTED_TOKEN",`Unexpected ${Z.type} token`),H=!1,B=!1}}let w=$[$.length-1],T=w?w.offset+w.source.length:q;if(F&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))Y(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(D&&(H&&D.indent<=G||X?.type==="block-map"||X?.type==="block-seq"))Y(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:A,found:R,spaceBefore:z,comment:U,hasNewline:O,anchor:M,tag:j,newlineAfterProp:L,end:T,start:b??T}}DB.resolveProps=VB});var U9=S((MB)=>{function $8($){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 J of $.end)if(J.type==="newline")return!0}return!1;case"flow-collection":for(let J of $.items){for(let Q of J.start)if(Q.type==="newline")return!0;if(J.sep){for(let Q of J.sep)if(Q.type==="newline")return!0}if($8(J.key)||$8(J.value))return!0}return!1;default:return!0}}MB.containsNewline=$8});var J8=S((LB)=>{var KB=U9();function jB($,J,Q){if(J?.type==="flow-collection"){let X=J.end[0];if(X.indent===$&&(X.source==="]"||X.source==="}")&&KB.containsNewline(J))Q(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}LB.flowIndentCheck=jB});var Q8=S((_B)=>{var P3=p();function AB($,J,Q){let{uniqueKeys:X}=$.options;if(X===!1)return!1;let q=typeof X==="function"?X:(Y,G)=>Y===G||P3.isScalar(Y)&&P3.isScalar(G)&&Y.value===G.value;return J.some((Y)=>q(Y.key,Q))}_B.mapIncludes=AB});var f3=S((EB)=>{var b3=z$(),ZB=B$(),E3=n2(),wB=U9(),S3=J8(),PB=Q8(),C3="All mapping items must start at the same column";function bB({composeNode:$,composeEmptyNode:J},Q,X,q,Y){let W=new(Y?.nodeClass??ZB.YAMLMap)(Q.schema);if(Q.atRoot)Q.atRoot=!1;let z=X.offset,H=null;for(let B of X.items){let{start:U,key:V,sep:O,value:F}=B,D=E3.resolveProps(U,{indicator:"explicit-key-ind",next:V??O?.[0],offset:z,onError:q,parentIndent:X.indent,startOnNewline:!0}),M=!D.found;if(M){if(V){if(V.type==="block-seq")q(z,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in V&&V.indent!==X.indent)q(z,"BAD_INDENT",C3)}if(!D.anchor&&!D.tag&&!O){if(H=D.end,D.comment)if(W.comment)W.comment+=`
65
+ `+D.comment;else W.comment=D.comment;continue}if(D.newlineAfterProp||wB.containsNewline(V))q(V??U[U.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(D.found?.indent!==X.indent)q(z,"BAD_INDENT",C3);Q.atKey=!0;let j=D.end,L=V?$(Q,V,D,q):J(Q,j,U,null,D,q);if(Q.schema.compat)S3.flowIndentCheck(X.indent,V,q);if(Q.atKey=!1,PB.mapIncludes(Q,W.items,L))q(j,"DUPLICATE_KEY","Map keys must be unique");let A=E3.resolveProps(O??[],{indicator:"map-value-ind",next:F,offset:L.range[2],onError:q,parentIndent:X.indent,startOnNewline:!V||V.type==="block-scalar"});if(z=A.end,A.found){if(M){if(F?.type==="block-map"&&!A.hasNewline)q(z,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&D.start<A.found.offset-1024)q(L.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let R=F?$(Q,F,A,q):J(Q,z,O,null,A,q);if(Q.schema.compat)S3.flowIndentCheck(X.indent,F,q);z=R.range[2];let b=new b3.Pair(L,R);if(Q.options.keepSourceTokens)b.srcToken=B;W.items.push(b)}else{if(M)q(L.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(A.comment)if(L.comment)L.comment+=`
66
+ `+A.comment;else L.comment=A.comment;let R=new b3.Pair(L);if(Q.options.keepSourceTokens)R.srcToken=B;W.items.push(R)}}if(H&&H<z)q(H,"IMPOSSIBLE","Map comment with trailing content");return W.range=[X.offset,z,H??z],W}EB.resolveBlockMap=bB});var I3=S((vB)=>{var CB=U$(),fB=n2(),IB=J8();function TB({composeNode:$,composeEmptyNode:J},Q,X,q,Y){let W=new(Y?.nodeClass??CB.YAMLSeq)(Q.schema);if(Q.atRoot)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let z=X.offset,H=null;for(let{start:B,value:U}of X.items){let V=fB.resolveProps(B,{indicator:"seq-item-ind",next:U,offset:z,onError:q,parentIndent:X.indent,startOnNewline:!0});if(!V.found)if(V.anchor||V.tag||U)if(U?.type==="block-seq")q(V.end,"BAD_INDENT","All sequence items must start at the same column");else q(z,"MISSING_CHAR","Sequence item without - indicator");else{if(H=V.end,V.comment)W.comment=V.comment;continue}let O=U?$(Q,U,V,q):J(Q,V.end,B,null,V,q);if(Q.schema.compat)IB.flowIndentCheck(X.indent,U,q);z=O.range[2],W.items.push(O)}return W.range=[X.offset,z,H??z],W}vB.resolveBlockSeq=TB});var H2=S((hB)=>{function yB($,J,Q,X){let q="";if($){let Y=!1,G="";for(let W of $){let{source:z,type:H}=W;switch(H){case"space":Y=!0;break;case"comment":{if(Q&&!Y)X(W,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let B=z.substring(1)||" ";if(!q)q=B;else q+=G+B;G="";break}case"newline":if(q)G+=z;Y=!0;break;default:X(W,"UNEXPECTED_TOKEN",`Unexpected ${H} at node end`)}J+=z.length}}return{comment:q,offset:J}}hB.resolveEnd=yB});var x3=S((iB)=>{var kB=p(),mB=z$(),T3=B$(),uB=U$(),lB=H2(),v3=n2(),cB=U9(),dB=Q8(),X8="Block collections are not allowed within flow collections",q8=($)=>$&&($.type==="block-map"||$.type==="block-seq");function pB({composeNode:$,composeEmptyNode:J},Q,X,q,Y){let G=X.start.source==="{",W=G?"flow map":"flow sequence",H=new(Y?.nodeClass??(G?T3.YAMLMap:uB.YAMLSeq))(Q.schema);H.flow=!0;let B=Q.atRoot;if(B)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let U=X.offset+X.start.source.length;for(let M=0;M<X.items.length;++M){let j=X.items[M],{start:L,key:A,sep:R,value:b}=j,w=v3.resolveProps(L,{flow:W,indicator:"explicit-key-ind",next:A??R?.[0],offset:U,onError:q,parentIndent:X.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!R&&!b){if(M===0&&w.comma)q(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`);else if(M<X.items.length-1)q(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${W}`);if(w.comment)if(H.comment)H.comment+=`
67
+ `+w.comment;else H.comment=w.comment;U=w.end;continue}if(!G&&Q.options.strict&&cB.containsNewline(A))q(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(M===0){if(w.comma)q(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`)}else{if(!w.comma)q(w.start,"MISSING_CHAR",`Missing , between ${W} items`);if(w.comment){let T="";$:for(let Z of L)switch(Z.type){case"comma":case"space":break;case"comment":T=Z.source.substring(1);break $;default:break $}if(T){let Z=H.items[H.items.length-1];if(kB.isPair(Z))Z=Z.value??Z.key;if(Z.comment)Z.comment+=`
68
+ `+T;else Z.comment=T;w.comment=w.comment.substring(T.length+1)}}}if(!G&&!R&&!w.found){let T=b?$(Q,b,w,q):J(Q,w.end,R,null,w,q);if(H.items.push(T),U=T.range[2],q8(b))q(T.range,"BLOCK_IN_FLOW",X8)}else{Q.atKey=!0;let T=w.end,Z=A?$(Q,A,w,q):J(Q,T,L,null,w,q);if(q8(A))q(Z.range,"BLOCK_IN_FLOW",X8);Q.atKey=!1;let I=v3.resolveProps(R??[],{flow:W,indicator:"map-value-ind",next:b,offset:Z.range[2],onError:q,parentIndent:X.indent,startOnNewline:!1});if(I.found){if(!G&&!w.found&&Q.options.strict){if(R)for(let C of R){if(C===I.found)break;if(C.type==="newline"){q(C,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(w.start<I.found.offset-1024)q(I.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]===":")q(b,"MISSING_CHAR",`Missing space after : in ${W}`);else q(I.start,"MISSING_CHAR",`Missing , or : between ${W} items`);let y=b?$(Q,b,I,q):I.found?J(Q,I.end,R,null,I,q):null;if(y){if(q8(b))q(y.range,"BLOCK_IN_FLOW",X8)}else if(I.comment)if(Z.comment)Z.comment+=`
69
+ `+I.comment;else Z.comment=I.comment;let n=new mB.Pair(Z,y);if(Q.options.keepSourceTokens)n.srcToken=j;if(G){let C=H;if(dB.mapIncludes(Q,C.items,Z))q(T,"DUPLICATE_KEY","Map keys must be unique");C.items.push(n)}else{let C=new T3.YAMLMap(Q.schema);C.flow=!0,C.items.push(n);let r=(y??Z).range;C.range=[Z.range[0],r[1],r[2]],H.items.push(C)}U=y?y.range[2]:I.end}}let V=G?"}":"]",[O,...F]=X.end,D=U;if(O?.source===V)D=O.offset+O.source.length;else{let M=W[0].toUpperCase()+W.substring(1),j=B?`${M} must end with a ${V}`:`${M} in block collection must be sufficiently indented and end with a ${V}`;if(q(U,B?"MISSING_CHAR":"BAD_INDENT",j),O&&O.source.length!==1)F.unshift(O)}if(F.length>0){let M=lB.resolveEnd(F,D,Q.options.strict,q);if(M.comment)if(H.comment)H.comment+=`
70
+ `+M.comment;else H.comment=M.comment;H.range=[X.offset,D,M.offset]}else H.range=[X.offset,D,D];return H}iB.resolveFlowCollection=pB});var y3=S((QU)=>{var rB=p(),aB=Y0(),sB=B$(),oB=U$(),tB=f3(),eB=I3(),$U=x3();function Y8($,J,Q,X,q,Y){let G=Q.type==="block-map"?tB.resolveBlockMap($,J,Q,X,Y):Q.type==="block-seq"?eB.resolveBlockSeq($,J,Q,X,Y):$U.resolveFlowCollection($,J,Q,X,Y),W=G.constructor;if(q==="!"||q===W.tagName)return G.tag=W.tagName,G;if(q)G.tag=q;return G}function JU($,J,Q,X,q){let Y=X.tag,G=!Y?null:J.directives.tagName(Y.source,(V)=>q(Y,"TAG_RESOLVE_FAILED",V));if(Q.type==="block-seq"){let{anchor:V,newlineAfterProp:O}=X,F=V&&Y?V.offset>Y.offset?V:Y:V??Y;if(F&&(!O||O.offset<F.offset))q(F,"MISSING_CHAR","Missing newline after block sequence props")}let W=Q.type==="block-map"?"map":Q.type==="block-seq"?"seq":Q.start.source==="{"?"map":"seq";if(!Y||!G||G==="!"||G===sB.YAMLMap.tagName&&W==="map"||G===oB.YAMLSeq.tagName&&W==="seq")return Y8($,J,Q,q,G);let z=J.schema.tags.find((V)=>V.tag===G&&V.collection===W);if(!z){let V=J.schema.knownTags[G];if(V?.collection===W)J.schema.tags.push(Object.assign({},V,{default:!1})),z=V;else{if(V)q(Y,"BAD_COLLECTION_TYPE",`${V.tag} used for ${W} collection, but expects ${V.collection??"scalar"}`,!0);else q(Y,"TAG_RESOLVE_FAILED",`Unresolved tag: ${G}`,!0);return Y8($,J,Q,q,G)}}let H=Y8($,J,Q,q,G,z),B=z.resolve?.(H,(V)=>q(Y,"TAG_RESOLVE_FAILED",V),J.options)??H,U=rB.isNode(B)?B:new aB.Scalar(B);if(U.range=H.range,U.tag=G,z?.format)U.format=z.format;return U}QU.composeCollection=JU});var W8=S((WU)=>{var G8=Y0();function qU($,J,Q){let X=J.offset,q=YU(J,$.options.strict,Q);if(!q)return{value:"",type:null,comment:"",range:[X,X,X]};let Y=q.mode===">"?G8.Scalar.BLOCK_FOLDED:G8.Scalar.BLOCK_LITERAL,G=J.source?GU(J.source):[],W=G.length;for(let D=G.length-1;D>=0;--D){let M=G[D][1];if(M===""||M==="\r")W=D;else break}if(W===0){let D=q.chomp==="+"&&G.length>0?`
71
+ `.repeat(Math.max(1,G.length-1)):"",M=X+q.length;if(J.source)M+=J.source.length;return{value:D,type:Y,comment:q.comment,range:[X,M,M]}}let z=J.indent+q.indent,H=J.offset+q.length,B=0;for(let D=0;D<W;++D){let[M,j]=G[D];if(j===""||j==="\r"){if(q.indent===0&&M.length>z)z=M.length}else{if(M.length<z)Q(H+M.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(q.indent===0)z=M.length;if(B=D,z===0&&!$.atRoot)Q(H,"BAD_INDENT","Block scalar values in collections must be indented");break}H+=M.length+j.length+1}for(let D=G.length-1;D>=W;--D)if(G[D][0].length>z)W=D+1;let U="",V="",O=!1;for(let D=0;D<B;++D)U+=G[D][0].slice(z)+`
72
+ `;for(let D=B;D<W;++D){let[M,j]=G[D];H+=M.length+j.length+1;let L=j[j.length-1]==="\r";if(L)j=j.slice(0,-1);if(j&&M.length<z){let R=`Block scalar lines must not be less indented than their ${q.indent?"explicit indentation indicator":"first line"}`;Q(H-j.length-(L?2:1),"BAD_INDENT",R),M=""}if(Y===G8.Scalar.BLOCK_LITERAL)U+=V+M.slice(z)+j,V=`
73
+ `;else if(M.length>z||j[0]==="\t"){if(V===" ")V=`
74
74
  `;else if(!O&&V===`
75
75
  `)V=`
76
76
 
77
- `;U+=V+M.slice(z)+R,V=`
78
- `,O=!0}else if(R==="")if(V===`
77
+ `;U+=V+M.slice(z)+j,V=`
78
+ `,O=!0}else if(j==="")if(V===`
79
79
  `)U+=`
80
80
  `;else V=`
81
- `;else U+=V+R,V=" ",O=!1}switch(Y.chomp){case"-":break;case"+":for(let D=W;D<q.length;++D)U+=`
82
- `+q[D][0].slice(z);if(U[U.length-1]!==`
81
+ `;else U+=V+j,V=" ",O=!1}switch(q.chomp){case"-":break;case"+":for(let D=W;D<G.length;++D)U+=`
82
+ `+G[D][0].slice(z);if(U[U.length-1]!==`
83
83
  `)U+=`
84
84
  `;break;default:U+=`
85
- `}let F=X+Y.length+J.source.length;return{value:U,type:G,comment:Y.comment,range:[X,F,F]}}function oB({offset:$,props:J},Q,X){if(J[0].type!=="block-scalar-header")return X(J[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:Y}=J[0],G=Y[0],q=0,W="",z=-1;for(let V=1;V<Y.length;++V){let O=Y[V];if(!W&&(O==="-"||O==="+"))W=O;else{let F=Number(O);if(!q&&F)q=F;else if(z===-1)z=$+V}}if(z!==-1)X(z,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let H=!1,B="",U=Y.length;for(let V=1;V<J.length;++V){let O=J[V];switch(O.type){case"space":H=!0;case"newline":U+=O.source.length;break;case"comment":if(Q&&!H)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");U+=O.source.length,B=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),U+=O.source.length;break;default:{let F=`Unexpected token in block scalar header: ${O.type}`;X(O,"UNEXPECTED_TOKEN",F);let D=O.source;if(D&&typeof D==="string")U+=D.length}}}return{mode:G,indent:q,chomp:W,comment:B,length:U}}function tB($){let J=$.split(/\n( *)/),Q=J[0],X=Q.match(/^( *)/),G=[X?.[1]?[X[1],Q.slice(X[1].length)]:["",Q]];for(let q=1;q<J.length;q+=2)G.push([J[q],J[q+1]]);return G}eB.resolveBlockScalar=sB});var G8=C((HU)=>{var Y8=Y0(),JU=Y2();function QU($,J,Q){let{offset:X,type:Y,source:G,end:q}=$,W,z,H=(V,O,F)=>Q(X+V,O,F);switch(Y){case"scalar":W=Y8.Scalar.PLAIN,z=XU(G,H);break;case"single-quoted-scalar":W=Y8.Scalar.QUOTE_SINGLE,z=YU(G,H);break;case"double-quoted-scalar":W=Y8.Scalar.QUOTE_DOUBLE,z=GU(G,H);break;default:return Q($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${Y}`),{value:"",type:null,comment:"",range:[X,X+G.length,X+G.length]}}let B=X+G.length,U=JU.resolveEnd(q,B,J,Q);return{value:z,type:W,comment:U.comment,range:[X,B,U.offset]}}function XU($,J){let Q="";switch($[0]){case"\t":Q="a tab character";break;case",":Q="flow indicator character ,";break;case"%":Q="directive indicator character %";break;case"|":case">":{Q=`block scalar indicator ${$[0]}`;break}case"@":case"`":{Q=`reserved character ${$[0]}`;break}}if(Q)J(0,"BAD_SCALAR_START",`Plain value cannot start with ${Q}`);return CJ($)}function YU($,J){if($[$.length-1]!=="'"||$.length===1)J($.length,"MISSING_CHAR","Missing closing 'quote");return CJ($.slice(1,-1)).replace(/''/g,"'")}function CJ($){let J=/(.*?)\r?\n/sy,Q=J.exec($);if(!Q)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 G=Q[1].replace(X,""),q=" ",W=J.lastIndex;while(Q=J.exec($)){let H=Q[1].replace(Y,"");if(H==="")if(q===`
86
- `)G+=q;else q=`
87
- `;else G+=q+H,q=" ";W=J.lastIndex}let z=/[ \t]*(.*)/sy;return z.lastIndex=W,Q=z.exec($),G+q+(Q?.[1]??"")}function GU($,J){let Q="";for(let X=1;X<$.length-1;++X){let Y=$[X];if(Y==="\r"&&$[X+1]===`
88
- `)continue;if(Y===`
89
- `){let{fold:G,offset:q}=qU($,X);Q+=G,X=q}else if(Y==="\\"){let G=$[++X],q=WU[G];if(q)Q+=q;else if(G===`
90
- `){G=$[X+1];while(G===" "||G==="\t")G=$[++X+1]}else if(G==="\r"&&$[X+1]===`
91
- `){G=$[++X+1];while(G===" "||G==="\t")G=$[++X+1]}else if(G==="x"||G==="u"||G==="U"){let W=G==="x"?2:G==="u"?4:8;Q+=zU($,X+1,W,J),X+=W}else{let W=$.substr(X-1,2);J(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),Q+=W}}else if(Y===" "||Y==="\t"){let G=X,q=$[X+1];while(q===" "||q==="\t")q=$[++X+1];if(q!==`
92
- `&&!(q==="\r"&&$[X+2]===`
93
- `))Q+=X>G?$.slice(G,X+1):Y}else Q+=Y}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function qU($,J){let Q="",X=$[J+1];while(X===" "||X==="\t"||X===`
85
+ `}let F=X+q.length+J.source.length;return{value:U,type:Y,comment:q.comment,range:[X,F,F]}}function YU({offset:$,props:J},Q,X){if(J[0].type!=="block-scalar-header")return X(J[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:q}=J[0],Y=q[0],G=0,W="",z=-1;for(let V=1;V<q.length;++V){let O=q[V];if(!W&&(O==="-"||O==="+"))W=O;else{let F=Number(O);if(!G&&F)G=F;else if(z===-1)z=$+V}}if(z!==-1)X(z,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${q}`);let H=!1,B="",U=q.length;for(let V=1;V<J.length;++V){let O=J[V];switch(O.type){case"space":H=!0;case"newline":U+=O.source.length;break;case"comment":if(Q&&!H)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");U+=O.source.length,B=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),U+=O.source.length;break;default:{let F=`Unexpected token in block scalar header: ${O.type}`;X(O,"UNEXPECTED_TOKEN",F);let D=O.source;if(D&&typeof D==="string")U+=D.length}}}return{mode:Y,indent:G,chomp:W,comment:B,length:U}}function GU($){let J=$.split(/\n( *)/),Q=J[0],X=Q.match(/^( *)/),Y=[X?.[1]?[X[1],Q.slice(X[1].length)]:["",Q]];for(let G=1;G<J.length;G+=2)Y.push([J[G],J[G+1]]);return Y}WU.resolveBlockScalar=qU});var H8=S((KU)=>{var z8=Y0(),HU=H2();function BU($,J,Q){let{offset:X,type:q,source:Y,end:G}=$,W,z,H=(V,O,F)=>Q(X+V,O,F);switch(q){case"scalar":W=z8.Scalar.PLAIN,z=UU(Y,H);break;case"single-quoted-scalar":W=z8.Scalar.QUOTE_SINGLE,z=VU(Y,H);break;case"double-quoted-scalar":W=z8.Scalar.QUOTE_DOUBLE,z=DU(Y,H);break;default:return Q($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${q}`),{value:"",type:null,comment:"",range:[X,X+Y.length,X+Y.length]}}let B=X+Y.length,U=HU.resolveEnd(G,B,J,Q);return{value:z,type:W,comment:U.comment,range:[X,B,U.offset]}}function UU($,J){let Q="";switch($[0]){case"\t":Q="a tab character";break;case",":Q="flow indicator character ,";break;case"%":Q="directive indicator character %";break;case"|":case">":{Q=`block scalar indicator ${$[0]}`;break}case"@":case"`":{Q=`reserved character ${$[0]}`;break}}if(Q)J(0,"BAD_SCALAR_START",`Plain value cannot start with ${Q}`);return h3($)}function VU($,J){if($[$.length-1]!=="'"||$.length===1)J($.length,"MISSING_CHAR","Missing closing 'quote");return h3($.slice(1,-1)).replace(/''/g,"'")}function h3($){let J=/(.*?)\r?\n/sy,Q=J.exec($);if(!Q)return $;let X,q;try{X=new RegExp("(?<![ \t])[ \t]+$"),q=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,q=/^[ \t]+|[ \t]+$/g}let Y=Q[1].replace(X,""),G=" ",W=J.lastIndex;while(Q=J.exec($)){let H=Q[1].replace(q,"");if(H==="")if(G===`
86
+ `)Y+=G;else G=`
87
+ `;else Y+=G+H,G=" ";W=J.lastIndex}let z=/[ \t]*(.*)/sy;return z.lastIndex=W,Q=z.exec($),Y+G+(Q?.[1]??"")}function DU($,J){let Q="";for(let X=1;X<$.length-1;++X){let q=$[X];if(q==="\r"&&$[X+1]===`
88
+ `)continue;if(q===`
89
+ `){let{fold:Y,offset:G}=FU($,X);Q+=Y,X=G}else if(q==="\\"){let Y=$[++X],G=MU[Y];if(G)Q+=G;else if(Y===`
90
+ `){Y=$[X+1];while(Y===" "||Y==="\t")Y=$[++X+1]}else if(Y==="\r"&&$[X+1]===`
91
+ `){Y=$[++X+1];while(Y===" "||Y==="\t")Y=$[++X+1]}else if(Y==="x"||Y==="u"||Y==="U"){let W=Y==="x"?2:Y==="u"?4:8;Q+=OU($,X+1,W,J),X+=W}else{let W=$.substr(X-1,2);J(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),Q+=W}}else if(q===" "||q==="\t"){let Y=X,G=$[X+1];while(G===" "||G==="\t")G=$[++X+1];if(G!==`
92
+ `&&!(G==="\r"&&$[X+2]===`
93
+ `))Q+=X>Y?$.slice(Y,X+1):q}else Q+=q}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function FU($,J){let Q="",X=$[J+1];while(X===" "||X==="\t"||X===`
94
94
  `||X==="\r"){if(X==="\r"&&$[J+2]!==`
95
95
  `)break;if(X===`
96
96
  `)Q+=`
97
- `;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var WU={"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 zU($,J,Q,X){let Y=$.substr(J,Q),q=Y.length===Q&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(q)}catch{let W=$.substr(J-2,Q+2);return X(J-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),W}}HU.resolveFlowScalar=QU});var IJ=C((OU)=>{var w$=d(),fJ=Y0(),UU=X8(),VU=G8();function DU($,J,Q,X){let{value:Y,type:G,comment:q,range:W}=J.type==="block-scalar"?UU.resolveBlockScalar($,J,X):VU.resolveFlowScalar(J,$.options.strict,X),z=Q?$.directives.tagName(Q.source,(U)=>X(Q,"TAG_RESOLVE_FAILED",U)):null,H;if($.options.stringKeys&&$.atKey)H=$.schema[w$.SCALAR];else if(z)H=FU($.schema,Y,z,Q,X);else if(J.type==="scalar")H=MU($,Y,J,X);else H=$.schema[w$.SCALAR];let B;try{let U=H.resolve(Y,(V)=>X(Q??J,"TAG_RESOLVE_FAILED",V),$.options);B=w$.isScalar(U)?U:new fJ.Scalar(U)}catch(U){let V=U instanceof Error?U.message:String(U);X(Q??J,"TAG_RESOLVE_FAILED",V),B=new fJ.Scalar(Y)}if(B.range=W,B.source=Y,G)B.type=G;if(z)B.tag=z;if(H.format)B.format=H.format;if(q)B.comment=q;return B}function FU($,J,Q,X,Y){if(Q==="!")return $[w$.SCALAR];let G=[];for(let W of $.tags)if(!W.collection&&W.tag===Q)if(W.default&&W.test)G.push(W);else return W;for(let W of G)if(W.test?.test(J))return W;let q=$.knownTags[Q];if(q&&!q.collection)return $.tags.push(Object.assign({},q,{default:!1,test:void 0})),q;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),$[w$.SCALAR]}function MU({atKey:$,directives:J,schema:Q},X,Y,G){let q=Q.tags.find((W)=>(W.default===!0||$&&W.default==="key")&&W.test?.test(X))||Q[w$.SCALAR];if(Q.compat){let W=Q.compat.find((z)=>z.default&&z.test?.test(X))??Q[w$.SCALAR];if(q.tag!==W.tag){let z=J.tagString(q.tag),H=J.tagString(W.tag),B=`Value may be parsed as either ${z} or ${H}`;G(Y,"TAG_RESOLVE_FAILED",B,!0)}}return q}OU.composeScalar=DU});var TJ=C((LU)=>{function RU($,J,Q){if(J){Q??(Q=J.length);for(let X=Q-1;X>=0;--X){let Y=J[X];switch(Y.type){case"space":case"comment":case"newline":$-=Y.source.length;continue}Y=J[++X];while(Y?.type==="space")$+=Y.source.length,Y=J[++X];break}}return $}LU.emptyScalarPosition=RU});var hJ=C((EU)=>{var NU=w2(),_U=d(),AU=SJ(),vJ=IJ(),ZU=Y2(),wU=TJ(),PU={composeNode:xJ,composeEmptyNode:q8};function xJ($,J,Q,X){let Y=$.atKey,{spaceBefore:G,comment:q,anchor:W,tag:z}=Q,H,B=!0;switch(J.type){case"alias":if(H=bU($,J,X),W||z)X(J,"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(H=vJ.composeScalar($,J,z,X),W)H.anchor=W.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(H=AU.composeCollection(PU,$,J,Q,X),W)H.anchor=W.source.substring(1)}catch(U){let V=U instanceof Error?U.message:String(U);X(J,"RESOURCE_EXHAUSTION",V)}break;default:{let U=J.type==="error"?J.message:`Unsupported token (type: ${J.type})`;X(J,"UNEXPECTED_TOKEN",U),B=!1}}if(H??(H=q8($,J.offset,void 0,null,Q,X)),W&&H.anchor==="")X(W,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&$.options.stringKeys&&(!_U.isScalar(H)||typeof H.value!=="string"||H.tag&&H.tag!=="tag:yaml.org,2002:str"))X(z??J,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(G)H.spaceBefore=!0;if(q)if(J.type==="scalar"&&J.source==="")H.comment=q;else H.commentBefore=q;if($.options.keepSourceTokens&&B)H.srcToken=J;return H}function q8($,J,Q,X,{spaceBefore:Y,comment:G,anchor:q,tag:W,end:z},H){let B={type:"scalar",offset:wU.emptyScalarPosition(J,Q,X),indent:-1,source:""},U=vJ.composeScalar($,B,W,H);if(q){if(U.anchor=q.source.substring(1),U.anchor==="")H(q,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)U.spaceBefore=!0;if(G)U.comment=G,U.range[2]=z;return U}function bU({options:$},{offset:J,source:Q,end:X},Y){let G=new NU.Alias(Q.substring(1));if(G.source==="")Y(J,"BAD_ALIAS","Alias cannot be an empty string");if(G.source.endsWith(":"))Y(J+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let q=J+Q.length,W=ZU.resolveEnd(X,q,$.strict,Y);if(G.range=[J,q,W.offset],W.comment)G.comment=W.comment;return G}EU.composeEmptyNode=q8;EU.composeNode=xJ});var gJ=C((xU)=>{var fU=k2(),yJ=hJ(),IU=Y2(),TU=u2();function vU($,J,{offset:Q,start:X,value:Y,end:G},q){let W=Object.assign({_directives:J},$),z=new fU.Document(void 0,W),H={atKey:!1,atRoot:!0,directives:z.directives,options:z.options,schema:z.schema},B=TU.resolveProps(X,{indicator:"doc-start",next:Y??G?.[0],offset:Q,onError:q,parentIndent:0,startOnNewline:!0});if(B.found){if(z.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!B.hasNewline)q(B.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}z.contents=Y?yJ.composeNode(H,Y,B,q):yJ.composeEmptyNode(H,B.end,X,null,B,q);let U=z.contents.range[2],V=IU.resolveEnd(G,U,!1,q);if(V.comment)z.comment=V.comment;return z.range=[Q,U,V.offset],z}xU.composeDoc=vU});var W8=C((lU)=>{var yU=F6("process"),gU=U4(),kU=k2(),l2=m2(),kJ=d(),mU=gJ(),uU=Y2();function c2($){if(typeof $==="number")return[$,$+1];if(Array.isArray($))return $.length===2?$:[$[0],$[1]];let{offset:J,source:Q}=$;return[J,J+(typeof Q==="string"?Q.length:1)]}function mJ($){let J="",Q=!1,X=!1;for(let Y=0;Y<$.length;++Y){let G=$[Y];switch(G[0]){case"#":J+=(J===""?"":X?`
97
+ `;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var MU={"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 OU($,J,Q,X){let q=$.substr(J,Q),G=q.length===Q&&/^[0-9a-fA-F]+$/.test(q)?parseInt(q,16):NaN;try{return String.fromCodePoint(G)}catch{let W=$.substr(J-2,Q+2);return X(J-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),W}}KU.resolveFlowScalar=BU});var k3=S((ZU)=>{var f$=p(),g3=Y0(),LU=W8(),NU=H8();function AU($,J,Q,X){let{value:q,type:Y,comment:G,range:W}=J.type==="block-scalar"?LU.resolveBlockScalar($,J,X):NU.resolveFlowScalar(J,$.options.strict,X),z=Q?$.directives.tagName(Q.source,(U)=>X(Q,"TAG_RESOLVE_FAILED",U)):null,H;if($.options.stringKeys&&$.atKey)H=$.schema[f$.SCALAR];else if(z)H=_U($.schema,q,z,Q,X);else if(J.type==="scalar")H=RU($,q,J,X);else H=$.schema[f$.SCALAR];let B;try{let U=H.resolve(q,(V)=>X(Q??J,"TAG_RESOLVE_FAILED",V),$.options);B=f$.isScalar(U)?U:new g3.Scalar(U)}catch(U){let V=U instanceof Error?U.message:String(U);X(Q??J,"TAG_RESOLVE_FAILED",V),B=new g3.Scalar(q)}if(B.range=W,B.source=q,Y)B.type=Y;if(z)B.tag=z;if(H.format)B.format=H.format;if(G)B.comment=G;return B}function _U($,J,Q,X,q){if(Q==="!")return $[f$.SCALAR];let Y=[];for(let W of $.tags)if(!W.collection&&W.tag===Q)if(W.default&&W.test)Y.push(W);else return W;for(let W of Y)if(W.test?.test(J))return W;let G=$.knownTags[Q];if(G&&!G.collection)return $.tags.push(Object.assign({},G,{default:!1,test:void 0})),G;return q(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),$[f$.SCALAR]}function RU({atKey:$,directives:J,schema:Q},X,q,Y){let G=Q.tags.find((W)=>(W.default===!0||$&&W.default==="key")&&W.test?.test(X))||Q[f$.SCALAR];if(Q.compat){let W=Q.compat.find((z)=>z.default&&z.test?.test(X))??Q[f$.SCALAR];if(G.tag!==W.tag){let z=J.tagString(G.tag),H=J.tagString(W.tag),B=`Value may be parsed as either ${z} or ${H}`;Y(q,"TAG_RESOLVE_FAILED",B,!0)}}return G}ZU.composeScalar=AU});var m3=S((bU)=>{function PU($,J,Q){if(J){Q??(Q=J.length);for(let X=Q-1;X>=0;--X){let q=J[X];switch(q.type){case"space":case"comment":case"newline":$-=q.source.length;continue}q=J[++X];while(q?.type==="space")$+=q.source.length,q=J[++X];break}}return $}bU.emptyScalarPosition=PU});var c3=S((yU)=>{var SU=f2(),CU=p(),fU=y3(),u3=k3(),IU=H2(),TU=m3(),vU={composeNode:l3,composeEmptyNode:B8};function l3($,J,Q,X){let q=$.atKey,{spaceBefore:Y,comment:G,anchor:W,tag:z}=Q,H,B=!0;switch(J.type){case"alias":if(H=xU($,J,X),W||z)X(J,"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(H=u3.composeScalar($,J,z,X),W)H.anchor=W.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(H=fU.composeCollection(vU,$,J,Q,X),W)H.anchor=W.source.substring(1)}catch(U){let V=U instanceof Error?U.message:String(U);X(J,"RESOURCE_EXHAUSTION",V)}break;default:{let U=J.type==="error"?J.message:`Unsupported token (type: ${J.type})`;X(J,"UNEXPECTED_TOKEN",U),B=!1}}if(H??(H=B8($,J.offset,void 0,null,Q,X)),W&&H.anchor==="")X(W,"BAD_ALIAS","Anchor cannot be an empty string");if(q&&$.options.stringKeys&&(!CU.isScalar(H)||typeof H.value!=="string"||H.tag&&H.tag!=="tag:yaml.org,2002:str"))X(z??J,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(Y)H.spaceBefore=!0;if(G)if(J.type==="scalar"&&J.source==="")H.comment=G;else H.commentBefore=G;if($.options.keepSourceTokens&&B)H.srcToken=J;return H}function B8($,J,Q,X,{spaceBefore:q,comment:Y,anchor:G,tag:W,end:z},H){let B={type:"scalar",offset:TU.emptyScalarPosition(J,Q,X),indent:-1,source:""},U=u3.composeScalar($,B,W,H);if(G){if(U.anchor=G.source.substring(1),U.anchor==="")H(G,"BAD_ALIAS","Anchor cannot be an empty string")}if(q)U.spaceBefore=!0;if(Y)U.comment=Y,U.range[2]=z;return U}function xU({options:$},{offset:J,source:Q,end:X},q){let Y=new SU.Alias(Q.substring(1));if(Y.source==="")q(J,"BAD_ALIAS","Alias cannot be an empty string");if(Y.source.endsWith(":"))q(J+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let G=J+Q.length,W=IU.resolveEnd(X,G,$.strict,q);if(Y.range=[J,G,W.offset],W.comment)Y.comment=W.comment;return Y}yU.composeEmptyNode=B8;yU.composeNode=l3});var p3=S((cU)=>{var kU=p2(),d3=c3(),mU=H2(),uU=n2();function lU($,J,{offset:Q,start:X,value:q,end:Y},G){let W=Object.assign({_directives:J},$),z=new kU.Document(void 0,W),H={atKey:!1,atRoot:!0,directives:z.directives,options:z.options,schema:z.schema},B=uU.resolveProps(X,{indicator:"doc-start",next:q??Y?.[0],offset:Q,onError:G,parentIndent:0,startOnNewline:!0});if(B.found){if(z.directives.docStart=!0,q&&(q.type==="block-map"||q.type==="block-seq")&&!B.hasNewline)G(B.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}z.contents=q?d3.composeNode(H,q,B,G):d3.composeEmptyNode(H,B.end,X,null,B,G);let U=z.contents.range[2],V=mU.resolveEnd(Y,U,!1,G);if(V.comment)z.comment=V.comment;return z.range=[Q,U,V.offset],z}cU.composeDoc=lU});var U8=S((sU)=>{var pU=j6("process"),iU=M4(),nU=p2(),r2=i2(),i3=p(),rU=p3(),aU=H2();function a2($){if(typeof $==="number")return[$,$+1];if(Array.isArray($))return $.length===2?$:[$[0],$[1]];let{offset:J,source:Q}=$;return[J,J+(typeof Q==="string"?Q.length:1)]}function n3($){let J="",Q=!1,X=!1;for(let q=0;q<$.length;++q){let Y=$[q];switch(Y[0]){case"#":J+=(J===""?"":X?`
99
99
 
100
100
  `:`
101
- `)+(G.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[Y+1]?.[0]!=="#")Y+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class uJ{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(J,Q,X,Y)=>{let G=c2(J);if(Y)this.warnings.push(new l2.YAMLWarning(G,Q,X));else this.errors.push(new l2.YAMLParseError(G,Q,X))},this.directives=new gU.Directives({version:$.version||"1.2"}),this.options=$}decorate($,J){let{comment:Q,afterEmptyLine:X}=mJ(this.prelude);if(Q){let Y=$.contents;if(J)$.comment=$.comment?`${$.comment}
102
- ${Q}`:Q;else if(X||$.directives.docStart||!Y)$.commentBefore=Q;else if(kJ.isCollection(Y)&&!Y.flow&&Y.items.length>0){let G=Y.items[0];if(kJ.isPair(G))G=G.key;let q=G.commentBefore;G.commentBefore=q?`${Q}
103
- ${q}`:Q}else{let G=Y.commentBefore;Y.commentBefore=G?`${Q}
104
- ${G}`:Q}}if(J){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:mJ(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose($,J=!1,Q=-1){for(let X of $)yield*this.next(X);yield*this.end(J,Q)}*next($){if(yU.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(J,Q,X)=>{let Y=c2($);Y[0]+=J,this.onError(Y,"BAD_DIRECTIVE",Q,X)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let J=mU.composeDoc(this.options,this.directives,$,this.onError);if(this.atDirectives&&!J.directives.docStart)this.onError($,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(J,!1),this.doc)yield this.doc;this.doc=J,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push($.source);break;case"error":{let J=$.source?`${$.message}: ${JSON.stringify($.source)}`:$.message,Q=new l2.YAMLParseError(c2($),"UNEXPECTED_TOKEN",J);if(this.atDirectives||!this.doc)this.errors.push(Q);else this.doc.errors.push(Q);break}case"doc-end":{if(!this.doc){this.errors.push(new l2.YAMLParseError(c2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let J=uU.resolveEnd($.end,$.offset+$.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),J.comment){let Q=this.doc.comment;this.doc.comment=Q?`${Q}
105
- ${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.push(new l2.YAMLParseError(c2($),"UNEXPECTED_TOKEN",`Unsupported token ${$.type}`))}}*end($=!1,J=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if($){let Q=Object.assign({_directives:this.directives},this.options),X=new kU.Document(void 0,Q);if(this.atDirectives)this.onError(J,"MISSING_CHAR","Missing directives-end indicator line");X.range=[0,J,J],this.decorate(X,!1),yield X}}}lU.Composer=uJ});var pJ=C((oU)=>{var pU=X8(),dU=G8(),iU=m2(),lJ=S2();function nU($,J=!0,Q){if($){let X=(Y,G,q)=>{let W=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if(Q)Q(W,G,q);else throw new iU.YAMLParseError([W,W+1],G,q)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return dU.resolveFlowScalar($,J,X);case"block-scalar":return pU.resolveBlockScalar({options:{strict:J}},$,X)}}return null}function rU($,J){let{implicitKey:Q=!1,indent:X,inFlow:Y=!1,offset:G=-1,type:q="PLAIN"}=J,W=lJ.stringifyString({type:q,value:$},{implicitKey:Q,indent:X>0?" ".repeat(X):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}}),z=J.end??[{type:"newline",offset:-1,indent:X,source:`
101
+ `)+(Y.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[q+1]?.[0]!=="#")q+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class r3{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(J,Q,X,q)=>{let Y=a2(J);if(q)this.warnings.push(new r2.YAMLWarning(Y,Q,X));else this.errors.push(new r2.YAMLParseError(Y,Q,X))},this.directives=new iU.Directives({version:$.version||"1.2"}),this.options=$}decorate($,J){let{comment:Q,afterEmptyLine:X}=n3(this.prelude);if(Q){let q=$.contents;if(J)$.comment=$.comment?`${$.comment}
102
+ ${Q}`:Q;else if(X||$.directives.docStart||!q)$.commentBefore=Q;else if(i3.isCollection(q)&&!q.flow&&q.items.length>0){let Y=q.items[0];if(i3.isPair(Y))Y=Y.key;let G=Y.commentBefore;Y.commentBefore=G?`${Q}
103
+ ${G}`:Q}else{let Y=q.commentBefore;q.commentBefore=Y?`${Q}
104
+ ${Y}`:Q}}if(J){for(let q=0;q<this.errors.length;++q)$.errors.push(this.errors[q]);for(let q=0;q<this.warnings.length;++q)$.warnings.push(this.warnings[q])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:n3(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose($,J=!1,Q=-1){for(let X of $)yield*this.next(X);yield*this.end(J,Q)}*next($){if(pU.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(J,Q,X)=>{let q=a2($);q[0]+=J,this.onError(q,"BAD_DIRECTIVE",Q,X)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let J=rU.composeDoc(this.options,this.directives,$,this.onError);if(this.atDirectives&&!J.directives.docStart)this.onError($,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(J,!1),this.doc)yield this.doc;this.doc=J,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push($.source);break;case"error":{let J=$.source?`${$.message}: ${JSON.stringify($.source)}`:$.message,Q=new r2.YAMLParseError(a2($),"UNEXPECTED_TOKEN",J);if(this.atDirectives||!this.doc)this.errors.push(Q);else this.doc.errors.push(Q);break}case"doc-end":{if(!this.doc){this.errors.push(new r2.YAMLParseError(a2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let J=aU.resolveEnd($.end,$.offset+$.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),J.comment){let Q=this.doc.comment;this.doc.comment=Q?`${Q}
105
+ ${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.push(new r2.YAMLParseError(a2($),"UNEXPECTED_TOKEN",`Unsupported token ${$.type}`))}}*end($=!1,J=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if($){let Q=Object.assign({_directives:this.directives},this.options),X=new nU.Document(void 0,Q);if(this.atDirectives)this.onError(J,"MISSING_CHAR","Missing directives-end indicator line");X.range=[0,J,J],this.decorate(X,!1),yield X}}}sU.Composer=r3});var o3=S((YV)=>{var tU=W8(),eU=H8(),$V=i2(),a3=x2();function JV($,J=!0,Q){if($){let X=(q,Y,G)=>{let W=typeof q==="number"?q:Array.isArray(q)?q[0]:q.offset;if(Q)Q(W,Y,G);else throw new $V.YAMLParseError([W,W+1],Y,G)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return eU.resolveFlowScalar($,J,X);case"block-scalar":return tU.resolveBlockScalar({options:{strict:J}},$,X)}}return null}function QV($,J){let{implicitKey:Q=!1,indent:X,inFlow:q=!1,offset:Y=-1,type:G="PLAIN"}=J,W=a3.stringifyString({type:G,value:$},{implicitKey:Q,indent:X>0?" ".repeat(X):"",inFlow:q,options:{blockQuote:!0,lineWidth:-1}}),z=J.end??[{type:"newline",offset:-1,indent:X,source:`
106
106
  `}];switch(W[0]){case"|":case">":{let H=W.indexOf(`
107
107
  `),B=W.substring(0,H),U=W.substring(H+1)+`
108
- `,V=[{type:"block-scalar-header",offset:G,indent:X,source:B}];if(!cJ(V,z))V.push({type:"newline",offset:-1,indent:X,source:`
109
- `});return{type:"block-scalar",offset:G,indent:X,props:V,source:U}}case'"':return{type:"double-quoted-scalar",offset:G,indent:X,source:W,end:z};case"'":return{type:"single-quoted-scalar",offset:G,indent:X,source:W,end:z};default:return{type:"scalar",offset:G,indent:X,source:W,end:z}}}function aU($,J,Q={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:G=!1,type:q}=Q,W="indent"in $?$.indent:null;if(X&&typeof W==="number")W+=2;if(!q)switch($.type){case"single-quoted-scalar":q="QUOTE_SINGLE";break;case"double-quoted-scalar":q="QUOTE_DOUBLE";break;case"block-scalar":{let H=$.props[0];if(H.type!=="block-scalar-header")throw Error("Invalid block scalar header");q=H.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:q="PLAIN"}let z=lJ.stringifyString({type:q,value:J},{implicitKey:Y||W===null,indent:W!==null&&W>0?" ".repeat(W):"",inFlow:G,options:{blockQuote:!0,lineWidth:-1}});switch(z[0]){case"|":case">":sU($,z);break;case'"':z8($,z,"double-quoted-scalar");break;case"'":z8($,z,"single-quoted-scalar");break;default:z8($,z,"scalar")}}function sU($,J){let Q=J.indexOf(`
110
- `),X=J.substring(0,Q),Y=J.substring(Q+1)+`
111
- `;if($.type==="block-scalar"){let G=$.props[0];if(G.type!=="block-scalar-header")throw Error("Invalid block scalar header");G.source=X,$.source=Y}else{let{offset:G}=$,q="indent"in $?$.indent:-1,W=[{type:"block-scalar-header",offset:G,indent:q,source:X}];if(!cJ(W,"end"in $?$.end:void 0))W.push({type:"newline",offset:-1,indent:q,source:`
112
- `});for(let z of Object.keys($))if(z!=="type"&&z!=="offset")delete $[z];Object.assign($,{type:"block-scalar",indent:q,props:W,source:Y})}}function cJ($,J){if(J)for(let Q of J)switch(Q.type){case"space":case"comment":$.push(Q);break;case"newline":return $.push(Q),!0}return!1}function z8($,J,Q){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=Q,$.source=J;break;case"block-scalar":{let X=$.props.slice(1),Y=J.length;if($.props[0].type==="block-scalar-header")Y-=$.props[0].source.length;for(let G of X)G.offset+=Y;delete $.props,Object.assign($,{type:Q,source:J,end:X});break}case"block-map":case"block-seq":{let Y={type:"newline",offset:$.offset+J.length,indent:$.indent,source:`
113
- `};delete $.items,Object.assign($,{type:Q,source:J,end:[Y]});break}default:{let X="indent"in $?$.indent:-1,Y="end"in $&&Array.isArray($.end)?$.end.filter((G)=>G.type==="space"||G.type==="comment"||G.type==="newline"):[];for(let G of Object.keys($))if(G!=="type"&&G!=="offset")delete $[G];Object.assign($,{type:Q,indent:X,source:J,end:Y})}}}oU.createScalarToken=rU;oU.resolveAsScalar=nU;oU.setScalarValue=aU});var dJ=C((QV)=>{var JV=($)=>("type"in $)?H9($):z9($);function H9($){switch($.type){case"block-scalar":{let J="";for(let Q of $.props)J+=H9(Q);return J+$.source}case"block-map":case"block-seq":{let J="";for(let Q of $.items)J+=z9(Q);return J}case"flow-collection":{let J=$.start.source;for(let Q of $.items)J+=z9(Q);for(let Q of $.end)J+=Q.source;return J}case"document":{let J=z9($);if($.end)for(let Q of $.end)J+=Q.source;return J}default:{let J=$.source;if("end"in $&&$.end)for(let Q of $.end)J+=Q.source;return J}}}function z9({start:$,key:J,sep:Q,value:X}){let Y="";for(let G of $)Y+=G.source;if(J)Y+=H9(J);if(Q)for(let G of Q)Y+=G.source;if(X)Y+=H9(X);return Y}QV.stringify=JV});var rJ=C((GV)=>{var H8=Symbol("break visit"),YV=Symbol("skip children"),iJ=Symbol("remove item");function P$($,J){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};nJ(Object.freeze([]),$,J)}P$.BREAK=H8;P$.SKIP=YV;P$.REMOVE=iJ;P$.itemAtPath=($,J)=>{let Q=$;for(let[X,Y]of J){let G=Q?.[X];if(G&&"items"in G)Q=G.items[Y];else return}return Q};P$.parentCollection=($,J)=>{let Q=P$.itemAtPath($,J.slice(0,-1)),X=J[J.length-1][0],Y=Q?.[X];if(Y&&"items"in Y)return Y;throw Error("Parent collection not found")};function nJ($,J,Q){let X=Q(J,$);if(typeof X==="symbol")return X;for(let Y of["key","value"]){let G=J[Y];if(G&&"items"in G){for(let q=0;q<G.items.length;++q){let W=nJ(Object.freeze($.concat([[Y,q]])),G.items[q],Q);if(typeof W==="number")q=W-1;else if(W===H8)return H8;else if(W===iJ)G.items.splice(q,1),q-=1}if(typeof X==="function"&&Y==="key")X=X(J,$)}}return typeof X==="function"?X(J,$):X}GV.visit=P$});var B9=C((DV)=>{var B8=pJ(),WV=dJ(),zV=rJ(),U8="\uFEFF",V8="\x02",D8="\x18",F8="\x1F",HV=($)=>!!$&&("items"in $),BV=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function UV($){switch($){case U8:return"<BOM>";case V8:return"<DOC>";case D8:return"<FLOW_END>";case F8:return"<SCALAR>";default:return JSON.stringify($)}}function VV($){switch($){case U8:return"byte-order-mark";case V8:return"doc-mode";case D8:return"flow-error-end";case F8:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
108
+ `,V=[{type:"block-scalar-header",offset:Y,indent:X,source:B}];if(!s3(V,z))V.push({type:"newline",offset:-1,indent:X,source:`
109
+ `});return{type:"block-scalar",offset:Y,indent:X,props:V,source:U}}case'"':return{type:"double-quoted-scalar",offset:Y,indent:X,source:W,end:z};case"'":return{type:"single-quoted-scalar",offset:Y,indent:X,source:W,end:z};default:return{type:"scalar",offset:Y,indent:X,source:W,end:z}}}function XV($,J,Q={}){let{afterKey:X=!1,implicitKey:q=!1,inFlow:Y=!1,type:G}=Q,W="indent"in $?$.indent:null;if(X&&typeof W==="number")W+=2;if(!G)switch($.type){case"single-quoted-scalar":G="QUOTE_SINGLE";break;case"double-quoted-scalar":G="QUOTE_DOUBLE";break;case"block-scalar":{let H=$.props[0];if(H.type!=="block-scalar-header")throw Error("Invalid block scalar header");G=H.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:G="PLAIN"}let z=a3.stringifyString({type:G,value:J},{implicitKey:q||W===null,indent:W!==null&&W>0?" ".repeat(W):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}});switch(z[0]){case"|":case">":qV($,z);break;case'"':V8($,z,"double-quoted-scalar");break;case"'":V8($,z,"single-quoted-scalar");break;default:V8($,z,"scalar")}}function qV($,J){let Q=J.indexOf(`
110
+ `),X=J.substring(0,Q),q=J.substring(Q+1)+`
111
+ `;if($.type==="block-scalar"){let Y=$.props[0];if(Y.type!=="block-scalar-header")throw Error("Invalid block scalar header");Y.source=X,$.source=q}else{let{offset:Y}=$,G="indent"in $?$.indent:-1,W=[{type:"block-scalar-header",offset:Y,indent:G,source:X}];if(!s3(W,"end"in $?$.end:void 0))W.push({type:"newline",offset:-1,indent:G,source:`
112
+ `});for(let z of Object.keys($))if(z!=="type"&&z!=="offset")delete $[z];Object.assign($,{type:"block-scalar",indent:G,props:W,source:q})}}function s3($,J){if(J)for(let Q of J)switch(Q.type){case"space":case"comment":$.push(Q);break;case"newline":return $.push(Q),!0}return!1}function V8($,J,Q){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=Q,$.source=J;break;case"block-scalar":{let X=$.props.slice(1),q=J.length;if($.props[0].type==="block-scalar-header")q-=$.props[0].source.length;for(let Y of X)Y.offset+=q;delete $.props,Object.assign($,{type:Q,source:J,end:X});break}case"block-map":case"block-seq":{let q={type:"newline",offset:$.offset+J.length,indent:$.indent,source:`
113
+ `};delete $.items,Object.assign($,{type:Q,source:J,end:[q]});break}default:{let X="indent"in $?$.indent:-1,q="end"in $&&Array.isArray($.end)?$.end.filter((Y)=>Y.type==="space"||Y.type==="comment"||Y.type==="newline"):[];for(let Y of Object.keys($))if(Y!=="type"&&Y!=="offset")delete $[Y];Object.assign($,{type:Q,indent:X,source:J,end:q})}}}YV.createScalarToken=QV;YV.resolveAsScalar=JV;YV.setScalarValue=XV});var t3=S((BV)=>{var HV=($)=>("type"in $)?D9($):V9($);function D9($){switch($.type){case"block-scalar":{let J="";for(let Q of $.props)J+=D9(Q);return J+$.source}case"block-map":case"block-seq":{let J="";for(let Q of $.items)J+=V9(Q);return J}case"flow-collection":{let J=$.start.source;for(let Q of $.items)J+=V9(Q);for(let Q of $.end)J+=Q.source;return J}case"document":{let J=V9($);if($.end)for(let Q of $.end)J+=Q.source;return J}default:{let J=$.source;if("end"in $&&$.end)for(let Q of $.end)J+=Q.source;return J}}}function V9({start:$,key:J,sep:Q,value:X}){let q="";for(let Y of $)q+=Y.source;if(J)q+=D9(J);if(Q)for(let Y of Q)q+=Y.source;if(X)q+=D9(X);return q}BV.stringify=HV});var JJ=S((DV)=>{var D8=Symbol("break visit"),VV=Symbol("skip children"),e3=Symbol("remove item");function I$($,J){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};$J(Object.freeze([]),$,J)}I$.BREAK=D8;I$.SKIP=VV;I$.REMOVE=e3;I$.itemAtPath=($,J)=>{let Q=$;for(let[X,q]of J){let Y=Q?.[X];if(Y&&"items"in Y)Q=Y.items[q];else return}return Q};I$.parentCollection=($,J)=>{let Q=I$.itemAtPath($,J.slice(0,-1)),X=J[J.length-1][0],q=Q?.[X];if(q&&"items"in q)return q;throw Error("Parent collection not found")};function $J($,J,Q){let X=Q(J,$);if(typeof X==="symbol")return X;for(let q of["key","value"]){let Y=J[q];if(Y&&"items"in Y){for(let G=0;G<Y.items.length;++G){let W=$J(Object.freeze($.concat([[q,G]])),Y.items[G],Q);if(typeof W==="number")G=W-1;else if(W===D8)return D8;else if(W===e3)Y.items.splice(G,1),G-=1}if(typeof X==="function"&&q==="key")X=X(J,$)}}return typeof X==="function"?X(J,$):X}DV.visit=I$});var F9=S((AV)=>{var F8=o3(),MV=t3(),OV=JJ(),M8="\uFEFF",O8="\x02",K8="\x18",j8="\x1F",KV=($)=>!!$&&("items"in $),jV=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function LV($){switch($){case M8:return"<BOM>";case O8:return"<DOC>";case K8:return"<FLOW_END>";case j8:return"<SCALAR>";default:return JSON.stringify($)}}function NV($){switch($){case M8:return"byte-order-mark";case O8:return"doc-mode";case K8:return"flow-error-end";case j8: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}DV.createScalarToken=B8.createScalarToken;DV.resolveAsScalar=B8.resolveAsScalar;DV.setScalarValue=B8.setScalarValue;DV.stringify=WV.stringify;DV.visit=zV.visit;DV.BOM=U8;DV.DOCUMENT=V8;DV.FLOW_END=D8;DV.SCALAR=F8;DV.isCollection=HV;DV.isScalar=BV;DV.prettyToken=UV;DV.tokenType=VV});var O8=C((SV)=>{var p2=B9();function E0($){switch($){case void 0:case" ":case`
116
- `:case"\r":case"\t":return!0;default:return!1}}var aJ=new Set("0123456789ABCDEFabcdef"),bV=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),U9=new Set(",[]{}"),EV=new Set(` ,[]{}
117
- \r `),M8=($)=>!$||EV.has($);class sJ{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($,J=!1){if($){if(typeof $!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+$:$,this.lineEndPos=null}this.atEnd=!J;let Q=this.next??"stream";while(Q&&(J||this.hasChars(1)))Q=yield*this.parseNext(Q)}atLineEnd(){let $=this.pos,J=this.buffer[$];while(J===" "||J==="\t")J=this.buffer[++$];if(!J||J==="#"||J===`
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}AV.createScalarToken=F8.createScalarToken;AV.resolveAsScalar=F8.resolveAsScalar;AV.setScalarValue=F8.setScalarValue;AV.stringify=MV.stringify;AV.visit=OV.visit;AV.BOM=M8;AV.DOCUMENT=O8;AV.FLOW_END=K8;AV.SCALAR=j8;AV.isCollection=KV;AV.isScalar=jV;AV.prettyToken=LV;AV.tokenType=NV});var N8=S((hV)=>{var s2=F9();function I0($){switch($){case void 0:case" ":case`
116
+ `:case"\r":case"\t":return!0;default:return!1}}var QJ=new Set("0123456789ABCDEFabcdef"),xV=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),M9=new Set(",[]{}"),yV=new Set(` ,[]{}
117
+ \r `),L8=($)=>!$||yV.has($);class XJ{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($,J=!1){if($){if(typeof $!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+$:$,this.lineEndPos=null}this.atEnd=!J;let Q=this.next??"stream";while(Q&&(J||this.hasChars(1)))Q=yield*this.parseNext(Q)}atLineEnd(){let $=this.pos,J=this.buffer[$];while(J===" "||J==="\t")J=this.buffer[++$];if(!J||J==="#"||J===`
118
118
  `)return!0;if(J==="\r")return this.buffer[$+1]===`
119
119
  `;return!1}charAt($){return this.buffer[this.pos+$]}continueScalar($){let J=this.buffer[$];if(this.indentNext>0){let Q=0;while(J===" ")J=this.buffer[++Q+$];if(J==="\r"){let X=this.buffer[Q+$+1];if(X===`
120
120
  `||!X&&!this.atEnd)return $+Q+1}return J===`
121
- `||Q>=this.indentNext||!J&&!this.atEnd?$+Q:-1}if(J==="-"||J==="."){let Q=this.buffer.substr($,3);if((Q==="---"||Q==="...")&&E0(this.buffer[$+3]))return-1}return $}getLine(){let $=this.lineEndPos;if(typeof $!=="number"||$!==-1&&$<this.pos)$=this.buffer.indexOf(`
122
- `,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===p2.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let J=$.length,Q=$.indexOf("#");while(Q!==-1){let Y=$[Q-1];if(Y===" "||Y==="\t"){J=Q-1;break}else Q=$.indexOf("#",Q+1)}while(!0){let Y=$[J-1];if(Y===" "||Y==="\t")J-=1;else break}let X=(yield*this.pushCount(J))+(yield*this.pushSpaces(!0));return yield*this.pushCount($.length-X),this.pushNewline(),"stream"}if(this.atLineEnd()){let J=yield*this.pushSpaces(!0);return yield*this.pushCount($.length-J),yield*this.pushNewline(),"stream"}return yield p2.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let $=this.charAt(0);if(!$&&!this.atEnd)return this.setNext("line-start");if($==="-"||$==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let J=this.peek(3);if((J==="---"||J==="...")&&E0(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,J==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!E0(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[$,J]=this.peek(2);if(!J&&!this.atEnd)return this.setNext("block-start");if(($==="-"||$==="?"||$===":")&&E0(J)){let Q=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=Q,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let $=this.getLine();if($===null)return this.setNext("doc");let J=yield*this.pushIndicators();switch($[J]){case"#":yield*this.pushCount($.length-J);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(M8),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return J+=yield*this.parseBlockScalarHeader(),J+=yield*this.pushSpaces(!0),yield*this.pushCount($.length-J),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let $,J,Q=-1;do{if($=yield*this.pushNewline(),$>0)J=yield*this.pushSpaces(!1),this.indentValue=Q=J;else J=0;J+=yield*this.pushSpaces(!0)}while($+J>0);let X=this.getLine();if(X===null)return this.setNext("flow");if(Q!==-1&&Q<this.indentNext&&X[0]!=="#"||Q===0&&(X.startsWith("---")||X.startsWith("..."))&&E0(X[3])){if(!(Q===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield p2.FLOW_END,yield*this.parseLineStart()}let Y=0;while(X[Y]===",")Y+=yield*this.pushCount(1),Y+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(Y+=yield*this.pushIndicators(),X[Y]){case void 0:return"flow";case"#":return yield*this.pushCount(X.length-Y),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(M8),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let G=this.charAt(1);if(this.flowKey||E0(G)||G===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),J=this.buffer.indexOf($,this.pos+1);if($==="'")while(J!==-1&&this.buffer[J+1]==="'")J=this.buffer.indexOf("'",J+2);else while(J!==-1){let Y=0;while(this.buffer[J-1-Y]==="\\")Y+=1;if(Y%2===0)break;J=this.buffer.indexOf('"',J+1)}let Q=this.buffer.substring(0,J),X=Q.indexOf(`
123
- `,this.pos);if(X!==-1){while(X!==-1){let Y=this.continueScalar(X+1);if(Y===-1)break;X=Q.indexOf(`
124
- `,Y)}if(X!==-1)J=X-(Q[X-1]==="\r"?2:1)}if(J===-1){if(!this.atEnd)return this.setNext("quoted-scalar");J=this.buffer.length}return yield*this.pushToIndex(J+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let J=this.buffer[++$];if(J==="+")this.blockScalarKeep=!0;else if(J>"0"&&J<="9")this.blockScalarIndent=Number(J)-1;else if(J!=="-")break}return yield*this.pushUntil((J)=>E0(J)||J==="#")}*parseBlockScalar(){let $=this.pos-1,J=0,Q;$:for(let Y=this.pos;Q=this.buffer[Y];++Y)switch(Q){case" ":J+=1;break;case`
125
- `:$=Y,J=0;break;case"\r":{let G=this.buffer[Y+1];if(!G&&!this.atEnd)return this.setNext("block-scalar");if(G===`
126
- `)break}default:break $}if(!Q&&!this.atEnd)return this.setNext("block-scalar");if(J>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=J;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
- `,Y)}while($!==-1);if($===-1){if(!this.atEnd)return this.setNext("block-scalar");$=this.buffer.length}}let X=$+1;Q=this.buffer[X];while(Q===" ")Q=this.buffer[++X];if(Q==="\t"){while(Q==="\t"||Q===" "||Q==="\r"||Q===`
128
- `)Q=this.buffer[++X];$=X-1}else if(!this.blockScalarKeep)do{let Y=$-1,G=this.buffer[Y];if(G==="\r")G=this.buffer[--Y];let q=Y;while(G===" ")G=this.buffer[--Y];if(G===`
129
- `&&Y>=this.pos&&Y+1+J>q)$=Y;else break}while(!0);return yield p2.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,J=this.pos-1,Q=this.pos-1,X;while(X=this.buffer[++Q])if(X===":"){let Y=this.buffer[Q+1];if(E0(Y)||$&&U9.has(Y))break;J=Q}else if(E0(X)){let Y=this.buffer[Q+1];if(X==="\r")if(Y===`
121
+ `||Q>=this.indentNext||!J&&!this.atEnd?$+Q:-1}if(J==="-"||J==="."){let Q=this.buffer.substr($,3);if((Q==="---"||Q==="...")&&I0(this.buffer[$+3]))return-1}return $}getLine(){let $=this.lineEndPos;if(typeof $!=="number"||$!==-1&&$<this.pos)$=this.buffer.indexOf(`
122
+ `,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===s2.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let J=$.length,Q=$.indexOf("#");while(Q!==-1){let q=$[Q-1];if(q===" "||q==="\t"){J=Q-1;break}else Q=$.indexOf("#",Q+1)}while(!0){let q=$[J-1];if(q===" "||q==="\t")J-=1;else break}let X=(yield*this.pushCount(J))+(yield*this.pushSpaces(!0));return yield*this.pushCount($.length-X),this.pushNewline(),"stream"}if(this.atLineEnd()){let J=yield*this.pushSpaces(!0);return yield*this.pushCount($.length-J),yield*this.pushNewline(),"stream"}return yield s2.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let $=this.charAt(0);if(!$&&!this.atEnd)return this.setNext("line-start");if($==="-"||$==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let J=this.peek(3);if((J==="---"||J==="...")&&I0(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,J==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!I0(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[$,J]=this.peek(2);if(!J&&!this.atEnd)return this.setNext("block-start");if(($==="-"||$==="?"||$===":")&&I0(J)){let Q=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=Q,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let $=this.getLine();if($===null)return this.setNext("doc");let J=yield*this.pushIndicators();switch($[J]){case"#":yield*this.pushCount($.length-J);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(L8),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return J+=yield*this.parseBlockScalarHeader(),J+=yield*this.pushSpaces(!0),yield*this.pushCount($.length-J),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let $,J,Q=-1;do{if($=yield*this.pushNewline(),$>0)J=yield*this.pushSpaces(!1),this.indentValue=Q=J;else J=0;J+=yield*this.pushSpaces(!0)}while($+J>0);let X=this.getLine();if(X===null)return this.setNext("flow");if(Q!==-1&&Q<this.indentNext&&X[0]!=="#"||Q===0&&(X.startsWith("---")||X.startsWith("..."))&&I0(X[3])){if(!(Q===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield s2.FLOW_END,yield*this.parseLineStart()}let q=0;while(X[q]===",")q+=yield*this.pushCount(1),q+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(q+=yield*this.pushIndicators(),X[q]){case void 0:return"flow";case"#":return yield*this.pushCount(X.length-q),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(L8),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let Y=this.charAt(1);if(this.flowKey||I0(Y)||Y===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),J=this.buffer.indexOf($,this.pos+1);if($==="'")while(J!==-1&&this.buffer[J+1]==="'")J=this.buffer.indexOf("'",J+2);else while(J!==-1){let q=0;while(this.buffer[J-1-q]==="\\")q+=1;if(q%2===0)break;J=this.buffer.indexOf('"',J+1)}let Q=this.buffer.substring(0,J),X=Q.indexOf(`
123
+ `,this.pos);if(X!==-1){while(X!==-1){let q=this.continueScalar(X+1);if(q===-1)break;X=Q.indexOf(`
124
+ `,q)}if(X!==-1)J=X-(Q[X-1]==="\r"?2:1)}if(J===-1){if(!this.atEnd)return this.setNext("quoted-scalar");J=this.buffer.length}return yield*this.pushToIndex(J+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let J=this.buffer[++$];if(J==="+")this.blockScalarKeep=!0;else if(J>"0"&&J<="9")this.blockScalarIndent=Number(J)-1;else if(J!=="-")break}return yield*this.pushUntil((J)=>I0(J)||J==="#")}*parseBlockScalar(){let $=this.pos-1,J=0,Q;$:for(let q=this.pos;Q=this.buffer[q];++q)switch(Q){case" ":J+=1;break;case`
125
+ `:$=q,J=0;break;case"\r":{let Y=this.buffer[q+1];if(!Y&&!this.atEnd)return this.setNext("block-scalar");if(Y===`
126
+ `)break}default:break $}if(!Q&&!this.atEnd)return this.setNext("block-scalar");if(J>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=J;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let q=this.continueScalar($+1);if(q===-1)break;$=this.buffer.indexOf(`
127
+ `,q)}while($!==-1);if($===-1){if(!this.atEnd)return this.setNext("block-scalar");$=this.buffer.length}}let X=$+1;Q=this.buffer[X];while(Q===" ")Q=this.buffer[++X];if(Q==="\t"){while(Q==="\t"||Q===" "||Q==="\r"||Q===`
128
+ `)Q=this.buffer[++X];$=X-1}else if(!this.blockScalarKeep)do{let q=$-1,Y=this.buffer[q];if(Y==="\r")Y=this.buffer[--q];let G=q;while(Y===" ")Y=this.buffer[--q];if(Y===`
129
+ `&&q>=this.pos&&q+1+J>G)$=q;else break}while(!0);return yield s2.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,J=this.pos-1,Q=this.pos-1,X;while(X=this.buffer[++Q])if(X===":"){let q=this.buffer[Q+1];if(I0(q)||$&&M9.has(q))break;J=Q}else if(I0(X)){let q=this.buffer[Q+1];if(X==="\r")if(q===`
130
130
  `)Q+=1,X=`
131
- `,Y=this.buffer[Q+1];else J=Q;if(Y==="#"||$&&U9.has(Y))break;if(X===`
132
- `){let G=this.continueScalar(Q+1);if(G===-1)break;Q=Math.max(Q,G-2)}}else{if($&&U9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield p2.SCALAR,yield*this.pushToIndex(J+1,!0),$?"flow":"doc"}*pushCount($){if($>0)return yield this.buffer.substr(this.pos,$),this.pos+=$,$;return 0}*pushToIndex($,J){let Q=this.buffer.slice(this.pos,$);if(Q)return yield Q,this.pos+=Q.length,Q.length;else if(J)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(M8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(E0(Q)||J&&U9.has(Q)){if(!J)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,J=this.buffer[$];while(!E0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(bV.has(J))J=this.buffer[++$];else if(J==="%"&&aJ.has(this.buffer[$+1])&&aJ.has(this.buffer[$+2]))J=this.buffer[$+=3];else break;return yield*this.pushToIndex($,!1)}}*pushNewline(){let $=this.buffer[this.pos];if($===`
131
+ `,q=this.buffer[Q+1];else J=Q;if(q==="#"||$&&M9.has(q))break;if(X===`
132
+ `){let Y=this.continueScalar(Q+1);if(Y===-1)break;Q=Math.max(Q,Y-2)}}else{if($&&M9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield s2.SCALAR,yield*this.pushToIndex(J+1,!0),$?"flow":"doc"}*pushCount($){if($>0)return yield this.buffer.substr(this.pos,$),this.pos+=$,$;return 0}*pushToIndex($,J){let Q=this.buffer.slice(this.pos,$);if(Q)return yield Q,this.pos+=Q.length,Q.length;else if(J)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(L8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(I0(Q)||J&&M9.has(Q)){if(!J)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,J=this.buffer[$];while(!I0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(xV.has(J))J=this.buffer[++$];else if(J==="%"&&QJ.has(this.buffer[$+1])&&QJ.has(this.buffer[$+2]))J=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 J=this.pos-1,Q;do Q=this.buffer[++J];while(Q===" "||$&&Q==="\t");let X=J-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=J;return X}*pushUntil($){let J=this.pos,Q=this.buffer[J];while(!$(Q))Q=this.buffer[++J];return yield*this.pushToIndex(J,!1)}}SV.Lexer=sJ});var K8=C((fV)=>{class oJ{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let J=0,Q=this.lineStarts.length;while(J<Q){let Y=J+Q>>1;if(this.lineStarts[Y]<$)J=Y+1;else Q=Y}if(this.lineStarts[J]===$)return{line:J+1,col:1};if(J===0)return{line:0,col:$};let X=this.lineStarts[J-1];return{line:J,col:$-X+1}}}}fV.LineCounter=oJ});var R8=C((xV)=>{var TV=F6("process"),tJ=B9(),vV=O8();function z$($,J){for(let Q=0;Q<$.length;++Q)if($[Q].type===J)return!0;return!1}function eJ($){for(let J=0;J<$.length;++J)switch($[J].type){case"space":case"comment":case"newline":break;default:return J}return-1}function J3($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function V9($){switch($.type){case"document":return $.start;case"block-map":{let J=$.items[$.items.length-1];return J.sep??J.start}case"block-seq":return $.items[$.items.length-1].start;default:return[]}}function G2($){if($.length===0)return[];let J=$.length;$:while(--J>=0)switch($[J].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break $}while($[++J]?.type==="space");return $.splice(J,$.length)}function D9($,J){if(J.length<1e5)Array.prototype.push.apply($,J);else for(let Q=0;Q<J.length;++Q)$.push(J[Q])}function $3($){if($.start.type==="flow-seq-start"){for(let J of $.items)if(J.sep&&!J.value&&!z$(J.start,"explicit-key-ind")&&!z$(J.sep,"map-value-ind")){if(J.key)J.value=J.key;if(delete J.key,J3(J.value))if(J.value.end)D9(J.value.end,J.sep);else J.value.end=J.sep;else D9(J.start,J.sep);delete J.sep}}}class Q3{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 vV.Lexer,this.onNewLine=$}*parse($,J=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let Q of this.lexer.lex($,J))yield*this.next(Q);if(!J)yield*this.end()}*next($){if(this.source=$,TV.env.LOG_TOKENS)console.log("|",tJ.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let J=tJ.tokenType($);if(!J){let Q=`Not a YAML token: ${$}`;yield*this.pop({type:"error",offset:this.offset,message:Q,source:$}),this.offset+=$.length}else if(J==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=J,yield*this.step(),J){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 J=$??this.stack.pop();if(!J)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield J;else{let Q=this.peek(1);if(J.type==="block-scalar")J.indent="indent"in Q?Q.indent:0;else if(J.type==="flow-collection"&&Q.type==="document")J.indent=0;if(J.type==="flow-collection")$3(J);switch(Q.type){case"document":Q.value=J;break;case"block-scalar":Q.props.push(J);break;case"block-map":{let X=Q.items[Q.items.length-1];if(X.value){Q.items.push({start:[],key:J,sep:[]}),this.onKeyLine=!0;return}else if(X.sep)X.value=J;else{Object.assign(X,{key:J,sep:[]}),this.onKeyLine=!X.explicitKey;return}break}case"block-seq":{let X=Q.items[Q.items.length-1];if(X.value)Q.items.push({start:[],value:J});else X.value=J;break}case"flow-collection":{let X=Q.items[Q.items.length-1];if(!X||X.value)Q.items.push({start:[],key:J,sep:[]});else if(X.sep)X.value=J;else Object.assign(X,{key:J,sep:[]});return}default:yield*this.pop(),yield*this.pop(J)}if((Q.type==="document"||Q.type==="block-map"||Q.type==="block-seq")&&(J.type==="block-map"||J.type==="block-seq")){let X=J.items[J.items.length-1];if(X&&!X.sep&&!X.value&&X.start.length>0&&eJ(X.start)===-1&&(J.indent===0||X.start.every((Y)=>Y.type!=="comment"||Y.indent<J.indent))){if(Q.type==="document")Q.end=X.start;else Q.items.push({start:X.start});J.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(eJ($.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 J=this.startBlockValue($);if(J)this.stack.push(J);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 J=V9(this.peek(2)),Q=G2(J),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:Q,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 J=this.source.indexOf(`
134
+ `)return yield*this.pushCount(2);else return 0}*pushSpaces($){let J=this.pos-1,Q;do Q=this.buffer[++J];while(Q===" "||$&&Q==="\t");let X=J-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=J;return X}*pushUntil($){let J=this.pos,Q=this.buffer[J];while(!$(Q))Q=this.buffer[++J];return yield*this.pushToIndex(J,!1)}}hV.Lexer=XJ});var A8=S((kV)=>{class qJ{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let J=0,Q=this.lineStarts.length;while(J<Q){let q=J+Q>>1;if(this.lineStarts[q]<$)J=q+1;else Q=q}if(this.lineStarts[J]===$)return{line:J+1,col:1};if(J===0)return{line:0,col:$};let X=this.lineStarts[J-1];return{line:J,col:$-X+1}}}}kV.LineCounter=qJ});var _8=S((cV)=>{var uV=j6("process"),YJ=F9(),lV=N8();function V$($,J){for(let Q=0;Q<$.length;++Q)if($[Q].type===J)return!0;return!1}function GJ($){for(let J=0;J<$.length;++J)switch($[J].type){case"space":case"comment":case"newline":break;default:return J}return-1}function zJ($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function O9($){switch($.type){case"document":return $.start;case"block-map":{let J=$.items[$.items.length-1];return J.sep??J.start}case"block-seq":return $.items[$.items.length-1].start;default:return[]}}function B2($){if($.length===0)return[];let J=$.length;$:while(--J>=0)switch($[J].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break $}while($[++J]?.type==="space");return $.splice(J,$.length)}function K9($,J){if(J.length<1e5)Array.prototype.push.apply($,J);else for(let Q=0;Q<J.length;++Q)$.push(J[Q])}function WJ($){if($.start.type==="flow-seq-start"){for(let J of $.items)if(J.sep&&!J.value&&!V$(J.start,"explicit-key-ind")&&!V$(J.sep,"map-value-ind")){if(J.key)J.value=J.key;if(delete J.key,zJ(J.value))if(J.value.end)K9(J.value.end,J.sep);else J.value.end=J.sep;else K9(J.start,J.sep);delete J.sep}}}class HJ{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 lV.Lexer,this.onNewLine=$}*parse($,J=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let Q of this.lexer.lex($,J))yield*this.next(Q);if(!J)yield*this.end()}*next($){if(this.source=$,uV.env.LOG_TOKENS)console.log("|",YJ.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let J=YJ.tokenType($);if(!J){let Q=`Not a YAML token: ${$}`;yield*this.pop({type:"error",offset:this.offset,message:Q,source:$}),this.offset+=$.length}else if(J==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=J,yield*this.step(),J){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 J=$??this.stack.pop();if(!J)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield J;else{let Q=this.peek(1);if(J.type==="block-scalar")J.indent="indent"in Q?Q.indent:0;else if(J.type==="flow-collection"&&Q.type==="document")J.indent=0;if(J.type==="flow-collection")WJ(J);switch(Q.type){case"document":Q.value=J;break;case"block-scalar":Q.props.push(J);break;case"block-map":{let X=Q.items[Q.items.length-1];if(X.value){Q.items.push({start:[],key:J,sep:[]}),this.onKeyLine=!0;return}else if(X.sep)X.value=J;else{Object.assign(X,{key:J,sep:[]}),this.onKeyLine=!X.explicitKey;return}break}case"block-seq":{let X=Q.items[Q.items.length-1];if(X.value)Q.items.push({start:[],value:J});else X.value=J;break}case"flow-collection":{let X=Q.items[Q.items.length-1];if(!X||X.value)Q.items.push({start:[],key:J,sep:[]});else if(X.sep)X.value=J;else Object.assign(X,{key:J,sep:[]});return}default:yield*this.pop(),yield*this.pop(J)}if((Q.type==="document"||Q.type==="block-map"||Q.type==="block-seq")&&(J.type==="block-map"||J.type==="block-seq")){let X=J.items[J.items.length-1];if(X&&!X.sep&&!X.value&&X.start.length>0&&GJ(X.start)===-1&&(J.indent===0||X.start.every((q)=>q.type!=="comment"||q.indent<J.indent))){if(Q.type==="document")Q.end=X.start;else Q.items.push({start:X.start});J.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(GJ($.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 J=this.startBlockValue($);if(J)this.stack.push(J);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 J=O9(this.peek(2)),Q=B2(J),X;if($.end)X=$.end,X.push(this.sourceToken),delete $.end;else X=[this.sourceToken];let q={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Q,key:$,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=q}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 J=this.source.indexOf(`
135
135
  `)+1;while(J!==0)this.onNewLine(this.offset+J),J=this.source.indexOf(`
136
- `,J)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){D9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let Q=!this.onKeyLine&&this.indent===$.indent,X=Q&&(J.sep||J.explicitKey)&&this.type!=="seq-item-ind",Y=[];if(X&&J.sep&&!J.value){let G=[];for(let q=0;q<J.sep.length;++q){let W=J.sep[q];switch(W.type){case"newline":G.push(q);break;case"space":break;case"comment":if(W.indent>$.indent)G.length=0;break;default:G.length=0}}if(G.length>=2)Y=J.sep.splice(G[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)Y.push(this.sourceToken),$.items.push({start:Y}),this.onKeyLine=!0;else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"explicit-key-ind":if(!J.sep&&!J.explicitKey)J.start.push(this.sourceToken),J.explicitKey=!0;else if(X||J.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(J.explicitKey)if(!J.sep)if(z$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let G=G2(J.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:null,sep:[this.sourceToken]}]})}else if(J.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(z$(J.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(J3(J.key)&&!z$(J.sep,"newline")){let G=G2(J.start),q=J.key,W=J.sep;W.push(this.sourceToken),delete J.key,delete J.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:G,key:q,sep:W}]})}else if(Y.length>0)J.sep=J.sep.concat(Y,this.sourceToken);else J.sep.push(this.sourceToken);else if(!J.sep)Object.assign(J,{key:null,sep:[this.sourceToken]});else if(J.value||X)$.items.push({start:Y,key:null,sep:[this.sourceToken]});else if(z$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else J.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let G=this.flowScalar(this.type);if(X||J.value)$.items.push({start:Y,key:G,sep:[]}),this.onKeyLine=!0;else if(J.sep)this.stack.push(G);else Object.assign(J,{key:G,sep:[]}),this.onKeyLine=!0;return}default:{let G=this.startBlockValue($);if(G){if(G.type==="block-seq"){if(!J.explicitKey&&J.sep&&!z$(J.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(Q)$.items.push({start:Y});this.stack.push(G);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){D9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return;case"anchor":case"tag":if(J.value||this.indent<=$.indent)break;J.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==$.indent)break;if(J.value||z$(J.start,"seq-item-ind"))$.items.push({start:[this.sourceToken]});else J.start.push(this.sourceToken);return}if(this.indent>$.indent){let Q=this.startBlockValue($);if(Q){this.stack.push(Q);return}}yield*this.pop(),yield*this.step()}*flowCollection($){let J=$.items[$.items.length-1];if(this.type==="flow-error-end"){let Q;do yield*this.pop(),Q=this.peek(1);while(Q?.type==="flow-collection")}else if($.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!J||J.sep)$.items.push({start:[this.sourceToken]});else J.start.push(this.sourceToken);return;case"map-value-ind":if(!J||J.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else Object.assign(J,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!J||J.value)$.items.push({start:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!J||J.value)$.items.push({start:[],key:X,sep:[]});else if(J.sep)this.stack.push(X);else Object.assign(J,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":$.end.push(this.sourceToken);return}let Q=this.startBlockValue($);if(Q)this.stack.push(Q);else yield*this.pop(),yield*this.step()}else{let Q=this.peek(2);if(Q.type==="block-map"&&(this.type==="map-value-ind"&&Q.indent===$.indent||this.type==="newline"&&!Q.items[Q.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Q.type!=="flow-collection"){let X=V9(Q),Y=G2(X);$3($);let G=$.end.splice(1,$.end.length);G.push(this.sourceToken);let q={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Y,key:$,sep:G}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=q}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let J=this.source.indexOf(`
136
+ `,J)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){K9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let Q=!this.onKeyLine&&this.indent===$.indent,X=Q&&(J.sep||J.explicitKey)&&this.type!=="seq-item-ind",q=[];if(X&&J.sep&&!J.value){let Y=[];for(let G=0;G<J.sep.length;++G){let W=J.sep[G];switch(W.type){case"newline":Y.push(G);break;case"space":break;case"comment":if(W.indent>$.indent)Y.length=0;break;default:Y.length=0}}if(Y.length>=2)q=J.sep.splice(Y[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)q.push(this.sourceToken),$.items.push({start:q}),this.onKeyLine=!0;else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"explicit-key-ind":if(!J.sep&&!J.explicitKey)J.start.push(this.sourceToken),J.explicitKey=!0;else if(X||J.value)q.push(this.sourceToken),$.items.push({start:q,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(J.explicitKey)if(!J.sep)if(V$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let Y=B2(J.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]})}else if(J.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(V$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:q,key:null,sep:[this.sourceToken]}]});else if(zJ(J.key)&&!V$(J.sep,"newline")){let Y=B2(J.start),G=J.key,W=J.sep;W.push(this.sourceToken),delete J.key,delete J.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:G,sep:W}]})}else if(q.length>0)J.sep=J.sep.concat(q,this.sourceToken);else J.sep.push(this.sourceToken);else if(!J.sep)Object.assign(J,{key:null,sep:[this.sourceToken]});else if(J.value||X)$.items.push({start:q,key:null,sep:[this.sourceToken]});else if(V$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else J.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Y=this.flowScalar(this.type);if(X||J.value)$.items.push({start:q,key:Y,sep:[]}),this.onKeyLine=!0;else if(J.sep)this.stack.push(Y);else Object.assign(J,{key:Y,sep:[]}),this.onKeyLine=!0;return}default:{let Y=this.startBlockValue($);if(Y){if(Y.type==="block-seq"){if(!J.explicitKey&&J.sep&&!V$(J.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(Q)$.items.push({start:q});this.stack.push(Y);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){K9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return;case"anchor":case"tag":if(J.value||this.indent<=$.indent)break;J.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==$.indent)break;if(J.value||V$(J.start,"seq-item-ind"))$.items.push({start:[this.sourceToken]});else J.start.push(this.sourceToken);return}if(this.indent>$.indent){let Q=this.startBlockValue($);if(Q){this.stack.push(Q);return}}yield*this.pop(),yield*this.step()}*flowCollection($){let J=$.items[$.items.length-1];if(this.type==="flow-error-end"){let Q;do yield*this.pop(),Q=this.peek(1);while(Q?.type==="flow-collection")}else if($.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!J||J.sep)$.items.push({start:[this.sourceToken]});else J.start.push(this.sourceToken);return;case"map-value-ind":if(!J||J.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else Object.assign(J,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!J||J.value)$.items.push({start:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!J||J.value)$.items.push({start:[],key:X,sep:[]});else if(J.sep)this.stack.push(X);else Object.assign(J,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":$.end.push(this.sourceToken);return}let Q=this.startBlockValue($);if(Q)this.stack.push(Q);else yield*this.pop(),yield*this.step()}else{let Q=this.peek(2);if(Q.type==="block-map"&&(this.type==="map-value-ind"&&Q.indent===$.indent||this.type==="newline"&&!Q.items[Q.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&Q.type!=="flow-collection"){let X=O9(Q),q=B2(X);WJ($);let Y=$.end.splice(1,$.end.length);Y.push(this.sourceToken);let G={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:q,key:$,sep:Y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=G}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let J=this.source.indexOf(`
137
137
  `)+1;while(J!==0)this.onNewLine(this.offset+J),J=this.source.indexOf(`
138
- `,J)+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 J=V9($),Q=G2(J);return Q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let J=V9($),Q=G2(J);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,J){if(this.type!=="comment")return!1;if(this.indent<=J)return!1;return $.every((Q)=>Q.type==="newline"||Q.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()}}}xV.Parser=Q3});var W3=C((pV)=>{var X3=W8(),yV=k2(),d2=m2(),gV=K4(),kV=d(),mV=K8(),Y3=R8();function G3($){let J=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||J&&new mV.LineCounter||null,prettyErrors:J}}function uV($,J={}){let{lineCounter:Q,prettyErrors:X}=G3(J),Y=new Y3.Parser(Q?.addNewLine),G=new X3.Composer(J),q=Array.from(G.compose(Y.parse($)));if(X&&Q)for(let W of q)W.errors.forEach(d2.prettifyError($,Q)),W.warnings.forEach(d2.prettifyError($,Q));if(q.length>0)return q;return Object.assign([],{empty:!0},G.streamInfo())}function q3($,J={}){let{lineCounter:Q,prettyErrors:X}=G3(J),Y=new Y3.Parser(Q?.addNewLine),G=new X3.Composer(J),q=null;for(let W of G.compose(Y.parse($),!0,$.length))if(!q)q=W;else if(q.options.logLevel!=="silent"){q.errors.push(new d2.YAMLParseError(W.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Q)q.errors.forEach(d2.prettifyError($,Q)),q.warnings.forEach(d2.prettifyError($,Q));return q}function lV($,J,Q){let X=void 0;if(typeof J==="function")X=J;else if(Q===void 0&&J&&typeof J==="object")Q=J;let Y=q3($,Q);if(!Y)return null;if(Y.warnings.forEach((G)=>gV.warn(Y.options.logLevel,G)),Y.errors.length>0)if(Y.options.logLevel!=="silent")throw Y.errors[0];else Y.errors=[];return Y.toJS(Object.assign({reviver:X},Q))}function cV($,J,Q){let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J;if(typeof Q==="string")Q=Q.length;if(typeof Q==="number"){let Y=Math.round(Q);Q=Y<1?void 0:Y>8?{indent:8}:{indent:Y}}if($===void 0){let{keepUndefined:Y}=Q??J??{};if(!Y)return}if(kV.isDocument($)&&!X)return $.toString(Q);return new yV.Document($,X,Q).toString(Q)}pV.parse=lV;pV.parseAllDocuments=uV;pV.parseDocument=q3;pV.stringify=cV});var H3=C((WD)=>{var aV=W8(),sV=k2(),oV=d4(),L8=m2(),tV=w2(),H$=d(),eV=Y$(),$D=Y0(),JD=q$(),QD=W$(),XD=B9(),YD=O8(),GD=K8(),qD=R8(),F9=W3(),z3=A2();WD.Composer=aV.Composer;WD.Document=sV.Document;WD.Schema=oV.Schema;WD.YAMLError=L8.YAMLError;WD.YAMLParseError=L8.YAMLParseError;WD.YAMLWarning=L8.YAMLWarning;WD.Alias=tV.Alias;WD.isAlias=H$.isAlias;WD.isCollection=H$.isCollection;WD.isDocument=H$.isDocument;WD.isMap=H$.isMap;WD.isNode=H$.isNode;WD.isPair=H$.isPair;WD.isScalar=H$.isScalar;WD.isSeq=H$.isSeq;WD.Pair=eV.Pair;WD.Scalar=$D.Scalar;WD.YAMLMap=JD.YAMLMap;WD.YAMLSeq=QD.YAMLSeq;WD.CST=XD;WD.Lexer=YD.Lexer;WD.LineCounter=GD.LineCounter;WD.Parser=qD.Parser;WD.parse=F9.parse;WD.parseAllDocuments=F9.parseAllDocuments;WD.parseDocument=F9.parseDocument;WD.stringify=F9.stringify;WD.visit=z3.visit;WD.visitAsync=z3.visitAsync});var BQ=($)=>$.payload.title?.trim()||`session:${$.payload.id}`;function M6($){let{store:J,agent:Q}=$;return{async session(X){let Y=X.payload.id,G=await z7(J,Y);switch(X.type){case"session.created":{if(G)return{task_id:G.id};let q=BQ(X);return{task_id:(await J.createTask({title:q,session_id:Y,owner:Q,priority:3})).id}}case"session.idle":{if(!G)return null;if(G.status==="pending"){let q=await J.updateTask(G.id,{status:"in_progress"});return q?{task_id:q.id}:null}return null}case"session.deleted":{if(!G)return null;return await J.updateTask(G.id,{status:"cancelled"}),{task_id:G.id}}case"session.error":case"session.compacted":return await J.appendOperation({task_id:G?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:Y,agent:Q}}),null;default:return null}},async tool(X){let Y=X.payload.sessionID,G=await z7(J,Y);if(!G)return await J.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:Y,tool:X.payload.tool}}),{task_id:(await J.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:Q,priority:3})).id};let q=UQ(X),z=(await J.listTasks({parent_id:G.id,limit:20})).tasks.find((B)=>B.title===q&&Date.now()-new Date(B.created_at).getTime()<60000);if(z)return{task_id:z.id};let H=await J.createTask({title:q,parent_id:G.id,session_id:Y,owner:Q,priority:3});return await J.updateTask(H.id,{status:"in_progress"}),{task_id:H.id}},async catchAll(X){try{await J.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:Q}})}catch{}}}}async function z7($,J){return(await $.listTasks({session_id:J,limit:1})).tasks[0]??null}function UQ($){let J=$.payload.tool,Q=$.payload.args??{};switch(J){case"write":case"edit":return`${J} ${Q.filePath??"?"}`;case"bash":case"shell":{let X=String(Q.command??Q.cmd??"");return`${J} ${X.slice(0,40)}`}case"read":return`read ${Q.filePath??"?"}`;default:return`${J} ${JSON.stringify(Q).slice(0,40)}`}}var H7=`### Task Lifecycle \u2014 the plugin's contract
138
+ `,J)+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 J=O9($),Q=B2(J);return Q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let J=O9($),Q=B2(J);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,J){if(this.type!=="comment")return!1;if(this.indent<=J)return!1;return $.every((Q)=>Q.type==="newline"||Q.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()}}}cV.Parser=HJ});var FJ=S((tV)=>{var BJ=U8(),pV=p2(),o2=i2(),iV=A4(),nV=p(),rV=A8(),UJ=_8();function VJ($){let J=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||J&&new rV.LineCounter||null,prettyErrors:J}}function aV($,J={}){let{lineCounter:Q,prettyErrors:X}=VJ(J),q=new UJ.Parser(Q?.addNewLine),Y=new BJ.Composer(J),G=Array.from(Y.compose(q.parse($)));if(X&&Q)for(let W of G)W.errors.forEach(o2.prettifyError($,Q)),W.warnings.forEach(o2.prettifyError($,Q));if(G.length>0)return G;return Object.assign([],{empty:!0},Y.streamInfo())}function DJ($,J={}){let{lineCounter:Q,prettyErrors:X}=VJ(J),q=new UJ.Parser(Q?.addNewLine),Y=new BJ.Composer(J),G=null;for(let W of Y.compose(q.parse($),!0,$.length))if(!G)G=W;else if(G.options.logLevel!=="silent"){G.errors.push(new o2.YAMLParseError(W.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Q)G.errors.forEach(o2.prettifyError($,Q)),G.warnings.forEach(o2.prettifyError($,Q));return G}function sV($,J,Q){let X=void 0;if(typeof J==="function")X=J;else if(Q===void 0&&J&&typeof J==="object")Q=J;let q=DJ($,Q);if(!q)return null;if(q.warnings.forEach((Y)=>iV.warn(q.options.logLevel,Y)),q.errors.length>0)if(q.options.logLevel!=="silent")throw q.errors[0];else q.errors=[];return q.toJS(Object.assign({reviver:X},Q))}function oV($,J,Q){let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J;if(typeof Q==="string")Q=Q.length;if(typeof Q==="number"){let q=Math.round(Q);Q=q<1?void 0:q>8?{indent:8}:{indent:q}}if($===void 0){let{keepUndefined:q}=Q??J??{};if(!q)return}if(nV.isDocument($)&&!X)return $.toString(Q);return new pV.Document($,X,Q).toString(Q)}tV.parse=sV;tV.parseAllDocuments=aV;tV.parseDocument=DJ;tV.stringify=oV});var OJ=S((MD)=>{var XD=U8(),qD=p2(),YD=a4(),R8=i2(),GD=f2(),D$=p(),WD=z$(),zD=Y0(),HD=B$(),BD=U$(),UD=F9(),VD=N8(),DD=A8(),FD=_8(),j9=FJ(),MJ=S2();MD.Composer=XD.Composer;MD.Document=qD.Document;MD.Schema=YD.Schema;MD.YAMLError=R8.YAMLError;MD.YAMLParseError=R8.YAMLParseError;MD.YAMLWarning=R8.YAMLWarning;MD.Alias=GD.Alias;MD.isAlias=D$.isAlias;MD.isCollection=D$.isCollection;MD.isDocument=D$.isDocument;MD.isMap=D$.isMap;MD.isNode=D$.isNode;MD.isPair=D$.isPair;MD.isScalar=D$.isScalar;MD.isSeq=D$.isSeq;MD.Pair=WD.Pair;MD.Scalar=zD.Scalar;MD.YAMLMap=HD.YAMLMap;MD.YAMLSeq=BD.YAMLSeq;MD.CST=UD;MD.Lexer=VD.Lexer;MD.LineCounter=DD.LineCounter;MD.Parser=FD.Parser;MD.parse=j9.parse;MD.parseAllDocuments=j9.parseAllDocuments;MD.parseDocument=j9.parseDocument;MD.stringify=j9.stringify;MD.visit=MJ.visit;MD.visitAsync=MJ.visitAsync});var jQ=($)=>$.payload.title?.trim()||`session:${$.payload.id}`;function L6($){let{store:J,agent:Q}=$;return{async session(X){let q=X.payload.id,Y=await M5(J,q);switch(X.type){case"session.created":{if(Y)return{task_id:Y.id};let G=jQ(X);return{task_id:(await J.createTask({title:G,session_id:q,owner:Q,priority:3})).id}}case"session.idle":{if(!Y)return null;if(Y.status==="pending"){let G=await J.updateTask(Y.id,{status:"in_progress"});return G?{task_id:G.id}:null}return null}case"session.deleted":{if(!Y)return null;return await J.updateTask(Y.id,{status:"cancelled"}),{task_id:Y.id}}case"session.error":case"session.compacted":return await J.appendOperation({task_id:Y?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:q,agent:Q}}),null;default:return null}},async tool(X){let q=X.payload.sessionID,Y=await M5(J,q);if(!Y)return await J.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:q,tool:X.payload.tool}}),{task_id:(await J.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:Q,priority:3})).id};let G=LQ(X),z=(await J.listTasks({parent_id:Y.id,limit:20})).tasks.find((B)=>B.title===G&&Date.now()-new Date(B.created_at).getTime()<60000);if(z)return{task_id:z.id};let H=await J.createTask({title:G,parent_id:Y.id,session_id:q,owner:Q,priority:3});return await J.updateTask(H.id,{status:"in_progress"}),{task_id:H.id}},async catchAll(X){try{await J.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:Q}})}catch{}}}}async function M5($,J){return(await $.listTasks({session_id:J,limit:1})).tasks[0]??null}function LQ($){let J=$.payload.tool,Q=$.payload.args??{};switch(J){case"write":case"edit":return`${J} ${Q.filePath??"?"}`;case"bash":case"shell":{let X=String(Q.command??Q.cmd??"");return`${J} ${X.slice(0,40)}`}case"read":return`read ${Q.filePath??"?"}`;default:return`${J} ${JSON.stringify(Q).slice(0,40)}`}}var O5=`### Task Lifecycle \u2014 the plugin's contract
139
139
 
140
140
  > **Task is the first-class citizen.** No task, no work.
141
141
 
@@ -275,7 +275,7 @@ not tracked.
275
275
  - Report the task id and its state whenever you finish a step.
276
276
  - If a task is blocked, mark it (\`task_update(status="paused")\`) and
277
277
  record a \`problem\` milestone explaining the blocker instead of going
278
- silent.`,$O=Object.freeze(["opencode","claude"]);var v9=`# Roy \u2014 task-first-class-citizen agent
278
+ silent.`,RO=Object.freeze(["opencode","claude"]);var g9=`# Roy \u2014 task-first-class-citizen agent
279
279
 
280
280
  You are **Roy**, an agent whose defining rule is simple:
281
281
 
@@ -284,7 +284,7 @@ You are **Roy**, an agent whose defining rule is simple:
284
284
  You are a worker agent: you act through the tools, and your output is what
285
285
  the user sees.
286
286
 
287
- ${H7}
287
+ ${O5}
288
288
 
289
289
  ## Other tools
290
290
 
@@ -301,7 +301,7 @@ ${H7}
301
301
  - Be direct and concrete; the user is reading task titles and milestones.
302
302
  - Report the task id and its state whenever you finish a step.
303
303
  - If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
304
- \`problem\` milestone explaining the blocker instead of going silent.`,VQ=`
304
+ \`problem\` milestone explaining the blocker instead of going silent.`,NQ=`
305
305
  ## Milestone discipline (Claude runtime)
306
306
 
307
307
  The task card renders **your** milestones. A run that calls tools but
@@ -370,8 +370,8 @@ continue.
370
370
  For a task with 3\u20134 stages you should end up with **3\u20134 hand-written
371
371
  milestones** in the card \u2014 not 2 automatic hooks and nothing else. The
372
372
  automatic \`\u6536\u5230\u6D88\u606F\` / \`Task \u5B8C\u6210\` hooks are not a substitute for yours.
373
- `,DQ=`
374
- ${VQ}
373
+ `,AQ=`
374
+ ${NQ}
375
375
  ## Tool surface on Claude Code
376
376
 
377
377
  The \`task_*\` tools are served by the **\`roy-task\` MCP server** this runtime
@@ -396,7 +396,7 @@ progress card renders the task these tools create.
396
396
  Measured: it has no way to write a milestone (its \`operations <id>\` subcommand
397
397
  is a *reader*), and it targets a different database than this server. Use the
398
398
  MCP tools above; if they are genuinely unavailable, say so in your answer
399
- instead of silently skipping the lifecycle.`;var x9="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_pre_complete \u2192 task_complete) "+"so every piece of work is tracked in the local task store.",h9=v9;var U2="roy",B7={action:"execute",resource:"*",effect:"deny"};function U7(){return{id:U2,mode:"primary",description:x9,system:h9,permissions:[{...B7}]}}function FQ($,J){if(!Array.isArray($.permissions))$.permissions=[];for(let Q of J)if(!$.permissions.some((Y)=>Y.action===Q.action&&Y.resource===Q.resource&&Y.effect===Q.effect))$.permissions.push({...Q})}function y9($){let J=U7();return $.update(U2,(Q)=>{if(Q.mode=J.mode,Q.description=J.description,Q.system=J.system,Q.hidden===void 0)Q.hidden=!1;FQ(Q,J.permissions)}),J}import{createRequire as MQ}from"module";var{defineProperty:g9,getOwnPropertyNames:OQ,getOwnPropertyDescriptor:KQ}=Object,RQ=Object.prototype.hasOwnProperty;function LQ($){return this[$]}var f$=($)=>{var J=(V7??=new WeakMap).get($),Q;if(J)return J;if(J=g9({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of OQ($))if(!RQ.call(J,X))g9(J,X,{get:LQ.bind($,X),enumerable:!(Q=KQ($,X))||Q.enumerable})}return V7.set($,J),J},V7,jQ=($)=>$;function NQ($,J){this[$]=jQ.bind(null,J)}var r0=($,J)=>{for(var Q in J)g9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:NQ.bind(J,Q)})},k=function($,J,Q,X){var Y=arguments.length,G=Y<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,Q):X,q;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")G=Reflect.decorate($,J,Q,X);else for(var W=$.length-1;W>=0;W--)if(q=$[W])G=(Y<3?q(G):Y>3?q(J,Q,G):q(J,Q))||G;return Y>3&&G&&Object.defineProperty(J,Q,G),G},a=($,J)=>()=>($&&(J=$($=0)),J),e=MQ(import.meta.url);function k9(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function D7($){let J=new WeakSet;try{return JSON.stringify($,(Q,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(J.has(X))return"[Circular]";J.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch(Q){return`[Unserializable: ${Q instanceof Error?Q.message:String(Q)}]`}}function _Q(){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 AQ($){let Q=new(_Q())($);if(typeof Q.run!=="function")Q.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return Q}class m9{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"),Q=e("path").dirname(this.dbPath);if(!$.existsSync(Q))$.mkdirSync(Q,{recursive:!0});this.db=AQ(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(`
399
+ instead of silently skipping the lifecycle.`;var k9="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_pre_complete \u2192 task_complete) "+"so every piece of work is tracked in the local task store.",m9=g9;var K2="roy",K5={action:"execute",resource:"*",effect:"deny"};function j5(){return{id:K2,mode:"primary",description:k9,system:m9,permissions:[{...K5}]}}function _Q($,J){if(!Array.isArray($.permissions))$.permissions=[];for(let Q of J)if(!$.permissions.some((q)=>q.action===Q.action&&q.resource===Q.resource&&q.effect===Q.effect))$.permissions.push({...Q})}function u9($){let J=j5();return $.update(K2,(Q)=>{if(Q.mode=J.mode,Q.description=J.description,Q.system=J.system,Q.hidden===void 0)Q.hidden=!1;_Q(Q,J.permissions)}),J}import{createRequire as RQ}from"module";var{defineProperty:l9,getOwnPropertyNames:ZQ,getOwnPropertyDescriptor:wQ}=Object,PQ=Object.prototype.hasOwnProperty;function bQ($){return this[$]}var j$=($)=>{var J=(L5??=new WeakMap).get($),Q;if(J)return J;if(J=l9({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of ZQ($))if(!PQ.call(J,X))l9(J,X,{get:bQ.bind($,X),enumerable:!(Q=wQ($,X))||Q.enumerable})}return L5.set($,J),J},L5,EQ=($)=>$;function SQ($,J){this[$]=EQ.bind(null,J)}var d0=($,J)=>{for(var Q in J)l9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:SQ.bind(J,Q)})},k=function($,J,Q,X){var q=arguments.length,Y=q<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,Q):X,G;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")Y=Reflect.decorate($,J,Q,X);else for(var W=$.length-1;W>=0;W--)if(G=$[W])Y=(q<3?G(Y):q>3?G(J,Q,Y):G(J,Q))||Y;return q>3&&Y&&Object.defineProperty(J,Q,Y),Y},s=($,J)=>()=>($&&(J=$($=0)),J),$0=RQ(import.meta.url);function c9(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function N5($){let J=new WeakSet;try{return JSON.stringify($,(Q,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(J.has(X))return"[Circular]";J.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch(Q){return`[Unserializable: ${Q instanceof Error?Q.message:String(Q)}]`}}function CQ(){if(typeof Bun<"u"){let{Database:$}=$0("bun:sqlite");return $}try{let{DatabaseSync:$}=$0("node:sqlite");if(typeof $==="function")return $}catch{}return $0("better-sqlite3")}function fQ($){let Q=new(CQ())($);if(typeof Q.run!=="function")Q.run=function(X,...q){if(q.length>0)return this.prepare(X).run(...q);else return this.exec(X)};return Q}class d9{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 $=$0("fs"),Q=$0("path").dirname(this.dbPath);if(!$.existsSync(Q))$.mkdirSync(Q,{recursive:!0});this.db=fQ(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(`
400
400
  CREATE TABLE IF NOT EXISTS span (
401
401
  span_id TEXT PRIMARY KEY,
402
402
  trace_id TEXT NOT NULL,
@@ -411,11 +411,11 @@ instead of silently skipping the lifecycle.`;var x9="Roy \u2014 task-as-first-cl
411
411
  error TEXT,
412
412
  time_created INTEGER NOT NULL
413
413
  )
414
- `),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(k9())console.log(`[SpanStorage] save() skipped: db not initialized for span "${$.name}" traceId=${$.traceId}`);return}let J=this.db.prepare(`
414
+ `),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(c9())console.log(`[SpanStorage] save() skipped: db not initialized for span "${$.name}" traceId=${$.traceId}`);return}let J=this.db.prepare(`
415
415
  INSERT OR REPLACE INTO span
416
416
  (span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
417
417
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
418
- `),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:D7($.result):null;if(k9())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${$.name}" traceId=${$.traceId} spanId=${$.spanId} status=${$.status}`);try{let X=J.run($.spanId,$.traceId,$.parentSpanId||null,$.name,$.kind,$.status,$.startTime,$.endTime||null,D7($.attributes),Q,$.error||null,Date.now());if(k9())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch($){for(let J of $)this.save(J)}findByTraceId($){if(!this.db)return[];let J=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all($);return this.buildTree(J.map(this.rowToSpan))}findBySpanId($){if(!this.db)return;let J=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get($);return J?this.rowToSpan(J):void 0}listTraces($=10){if(!this.db)return[];return this.db.prepare(`
418
+ `),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:N5($.result):null;if(c9())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${$.name}" traceId=${$.traceId} spanId=${$.spanId} status=${$.status}`);try{let X=J.run($.spanId,$.traceId,$.parentSpanId||null,$.name,$.kind,$.status,$.startTime,$.endTime||null,N5($.attributes),Q,$.error||null,Date.now());if(c9())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch($){for(let J of $)this.save(J)}findByTraceId($){if(!this.db)return[];let J=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all($);return this.buildTree(J.map(this.rowToSpan))}findBySpanId($){if(!this.db)return;let J=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get($);return J?this.rowToSpan(J):void 0}listTraces($=10){if(!this.db)return[];return this.db.prepare(`
419
419
  SELECT trace_id,
420
420
  MIN(start_time) as start_time,
421
421
  MAX(end_time) as end_time,
@@ -430,9 +430,9 @@ instead of silently skipping the lifecycle.`;var x9="Roy \u2014 task-as-first-cl
430
430
  GROUP BY trace_id
431
431
  ORDER BY start_time DESC
432
432
  LIMIT ?
433
- `).all($).map((Q)=>{let X=Number(Q.span_count)||0,Y=Number(Q.error_count)||0,G=Q.end_time??void 0,q=Y===0?"ok":Y>=X?"error":"mixed";return{traceId:Q.trace_id,rootSpanName:Q.root_name??"unknown",startTime:Q.start_time,endTime:G,duration:G!==void 0?G-Q.start_time:void 0,spanCount:X,status:q}})}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 J=new Map,Q=[];for(let X of $)J.set(X.spanId,{...X,children:[]});for(let X of J.values())if(X.parentSpanId){let Y=J.get(X.parentSpanId);if(Y)Y.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var F7=()=>{};import{appendFileSync as IQ,existsSync as TQ,mkdirSync as vQ}from"fs";import{join as V2}from"path";import{AsyncLocalStorage as O7}from"async_hooks";function M7($,J){return $.padStart(J,"0")}function u9($){return/^[0-9a-f]+$/i.test($)}function ZQ($){let J=M7($.traceId.toLowerCase(),j7),Q=M7($.spanId.toLowerCase(),N7);return[p9,J,Q,PQ].join("-")}function wQ($){if(!$||typeof $!=="string")return;let Q=$.trim().split("-");if(Q.length!==4)return;let[X,Y,G,q]=Q;if(X!==p9){if(X>p9)return}if(Y.length!==j7||!u9(Y))return;if(G.length!==N7||!u9(G))return;if(q.length!==bQ||!u9(q))return;return{traceId:Y.toLowerCase(),spanId:G.toLowerCase()}}var p9="00",PQ="01",l9="TRACEPARENT",j7=32,N7=16,bQ=2,n9,EQ=a(()=>{n9={inject($,J){$[l9]=ZQ(J)},extract($){let J=$[l9];if(!J)return;return wQ(J)},getTraceparentHeader(){return l9}}}),SQ,CQ,fQ=a(()=>{(($)=>{$.CLIENT="client",$.SERVER="server",$.INTERNAL="internal"})(SQ||={}),(($)=>{$.OK="ok",$.ERROR="error"})(CQ||={})});function r9($){let J=$.replace(/\\/g,"/"),Q=J.match(/\/\$bunfs\/root\/(.+)$/);if(Q){let q=Q[1],W=q.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];return q}let X=J.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let q=X[1].replace(/\+/g,"/"),W=X[2],z=q,H=W.startsWith("src/")?W:`src/${W}`;return`${z}/${H}`}let Y=J.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let G=["packages/core/src","packages/core","packages"];for(let q of G){let W=J.indexOf(q);if(W!==-1)return J.substring(W)}return J}function xQ(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let J=e("xdg-basedir");if(J.xdgData)return V2(J.xdgData,"roy-agent","logs")}catch{}return V2($,".local","share","roy-agent","logs")}function hQ(){return cQ}function yQ(){if(N0){let J=N0.get("log_trace.logging.level");if(J&&["debug","info","warn","error"].includes(J))return J}let $=process.env.LOG_LEVEL;if($&&["debug","info","warn","error"].includes($))return $;return"info"}function gQ($){if(N0){let X=N0.get("log_trace.logging.levels");if(X&&typeof X==="object"){let G=X[$];if(G&&["debug","info","warn","error"].includes(G))return G}let Y=N0.get(`log_trace.logging.levels.${$}`);if(Y&&["debug","info","warn","error"].includes(Y))return Y}let J=`LOG_LEVEL_${$.toUpperCase().replace(/:/g,"_")}`,Q=process.env[J];if(Q&&["debug","info","warn","error"].includes(Q))return Q;return yQ()}function kQ($){if($.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test($))return!0;return!1}function mQ($){if($.startsWith("~")){let J=process.env.HOME||process.env.USERPROFILE||"/tmp";return V2(J,$.slice(1))}return $}function uQ(){if(N0){let $=N0.get("log-trace.logging.file");if($)return $}return"app.log"}function lQ(){if(N0){let $=N0.get("log-trace.logging.dir");if($)return $}return xQ()}function a9(){if(N0){let $=N0.get("log-trace.logging.maxOutput");if(typeof $==="number")return $}return}class _7{prefix;constructor($){this.prefix=$}shouldLog($){let J=gQ(this.prefix);return d9[$]>=d9[J]}ensureLogDirectory($){if(!TQ($))try{vQ($,{recursive:!0})}catch(J){console.error("[Logger] Failed to create log directory:",$,J)}}getCallerLocation(){let $=Error.stackTraceLimit;Error.stackTraceLimit=10;let J=Error();Error.captureStackTrace(J,this.formatMessage);let Q=J.stack?.split(`
434
- `)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let Y=Q[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let G=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(G){let q=G[1];return{file:this.getRelativePath(q),line:parseInt(G[2],10)}}}}return null}getRelativePath($){return r9($)}formatMessage($,J,Q){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"),G=this.prefix?`[${this.prefix}]`:"",q="";try{let V=D2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)q=`[traceId=${V.traceId}]`}catch{}let W="";if(Q&&typeof Q==="object"&&"callerLocation"in Q){let B=Q;W=B.callerLocation?` [${B.callerLocation}]`:"";let{callerLocation:U,...V}=B;Q=Object.keys(V).length>0?V:void 0}else{let B=this.getCallerLocation();if(B)W=` [${B.file}:${B.line}]`}let z=`${Y} [${$.toUpperCase()}]${q}${W}${G} ${J}`;if(Q!==void 0)if(typeof Q==="object")z+=" "+JSON.stringify(Q).replace(/\n/g,"");else z+=" "+String(Q);let H=a9();if(H&&H>0&&z.length>H)z=z.substring(0,H)+" [TRUNCATED]";return z}writeToFile($){try{let J=lQ(),Q=uQ(),X=mQ(J),Y=kQ(X)?X:V2(process.cwd(),X);this.ensureLogDirectory(Y);let G=V2(Y,Q);IQ(G,$+`
435
- `,"utf-8")}catch(J){console.error("[Logger] Failed to write to log file:",J)}}log($,J,Q){if(!this.shouldLog($))return;let X=this.formatMessage($,J,Q);if(this.writeToFile(X),!hQ())if(pQ)console.error(X);else($==="error"?console.error:$==="warn"?console.warn:$==="info"?console.log:console.debug)(X)}debug($,J){this.log("debug",$,J)}info($,J){this.log("info",$,J)}warn($,J){this.log("warn",$,J)}error($,J){this.log("error",$,J)}}function i($){if(!O6.has($))O6.set($,new _7($));return O6.get($)}var N0=null,cQ=!1,pQ=!1;var d9,O6,n=a(()=>{t9(),d9={debug:0,info:1,warn:2,error:3},O6=new Map}),dQ={};r0(dQ,{setTracerProvider:()=>nQ,resetTracerProvider:()=>iQ,getTracerProvider:()=>D2,OTelTracerProvider:()=>o9});function s9(){if(!c9)c9=i("otel-tracer");return c9}function A7(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function Z7($,...J){s9().info($,...J)}function K7($,...J){s9().warn($,...J)}function R7($,...J){s9().error($,...J)}class i9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,Y){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=Y}setAttribute($,J){this.attributes[$]=J}addEvent($,J){let Q=this.attributes._events||[];Q.push({name:$,attributes:J}),this.attributes._events=Q}end($,J){if(this.endTime=Date.now(),J)this.error=J.message;let Q=this.endTime-(this.startTime||0);if(A7())Z7(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${Q}ms status=${J?"ERROR":"OK"}`);let X=this.storage;if(!X)K7(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=D2().getStorage();if(X){if(!(X.db||X.initialized))K7(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((G)=>{R7("[OTelSpan] Failed to initialize storage:",G)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:J?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:$,error:this.error})}else R7(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class w7{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($,J,Q,X){this.name=$,this.version=J,this.storage=Q,this.provider=X,this.instanceId=`${$}@${X.instanceId}`}setOnSpanEndCallback($){this.onSpanEndCallback=$}getActiveSpanCount(){return this.activeSpans.size}startSpan($,J){let Q=J?.parent,X=J&&"parent"in J,Y=J&&"context"in J,G=this.provider.getGlobalContext(),q,W,z,H,B;if(Y&&J?.context){let V=J.context;W=V.traceId,z=this.generateSpanId(),H=V.spanId,B={traceId:W,spanId:z,parentSpanId:H},this.currentContext={traceId:W,spanId:z,parentSpanId:H};let O=new i9($,B,this.storage,V,()=>this.handleSpanEnd(B.spanId,V.spanId));if(J?.attributes)for(let[F,D]of Object.entries(J.attributes))O.setAttribute(F,D);return this.activeSpans.set(z,O),O}if(X)q=Q;else if(this.currentContext)q=this.currentContext;else if(G)q=G;if(W=q?.traceId||this.generateTraceId(),z=this.generateSpanId(),X&&Q)H=Q.parentSpanId||Q.spanId;else if(this.currentContext)H=this.currentContext.spanId;else if(G)H=G.spanId;B={traceId:W,spanId:z,parentSpanId:H},this.currentContext={traceId:W,spanId:z,parentSpanId:H};let U=new i9($,B,this.storage,q,()=>this.handleSpanEnd(B.spanId,q?.spanId));if(J?.attributes)for(let[V,O]of Object.entries(J.attributes))U.setAttribute(V,O);if(this.activeSpans.set(z,U),A7())Z7(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${W} spanId=${z} parentSpanId=${H||"-"}`);return U}injectToEnv($){if(this.currentContext)n9.inject($,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}findStackParentSpan($){for(let[,J]of this.activeSpans)if(J.spanContext.parentSpanId===$)return J;return}endSpan($){let J=$.spanContext;this.activeSpans.delete(J.spanId);let Q=this.currentContext?.traceId;if(J.parentSpanId){let Y=this.activeSpans.get(J.parentSpanId);if(Y){let G={traceId:J.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=G,G}if(Q){let G={traceId:Q,spanId:J.parentSpanId,parentSpanId:void 0};return this.currentContext=G,G}}let X=this.findStackParentSpan(J.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"),J=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return($+J).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd($,J){if(this.activeSpans.delete($),J){let X=this.activeSpans.get(J);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:J,parentSpanId:void 0};return}}let Q=this.findStackParentSpan($);if(Q){this.currentContext={traceId:Q.spanContext.traceId,spanId:Q.spanContext.spanId,parentSpanId:Q.spanContext.parentSpanId};return}this.currentContext=void 0}}class o9{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new O7;tracerContexts=new Map;tracerContextScope=new O7;instanceId;constructor($,J){L7++,this.instanceId=`Provider#${L7}`,this.storage=$||new m9(J||rQ())}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($,J){let Q=new Map(this.tracerContexts);return this.globalContextScope.run({value:$},()=>this.tracerContextScope.run({contexts:Q},J))}runInGlobalContextSync($,J){let Q=new Map(this.tracerContexts);return this.globalContextScope.run({value:$},()=>this.tracerContextScope.run({contexts:Q},J))}getTracerCurrentContext($){let J=this.tracerContextScope.getStore();if(J)return J.contexts.get($);return this.tracerContexts.get($)}setTracerCurrentContext($,J){let Q=this.tracerContextScope.getStore();if(Q){Q.contexts.set($,J);return}this.tracerContexts.set($,J)}clearAllTracerCurrentContexts(){let $=this.tracerContextScope.getStore();if($){$.contexts.clear();return}this.tracerContexts.clear()}getTracer($,J){let Q=`${$}@${J||"0.0.0"}`,X=this.tracers.get(Q);if(!X){if(X=new w7($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=n9.extract(process.env);if(J)$.setCurrentContext({traceId:J.traceId,spanId:J.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 D2(){if(!m0)m0=new o9;return m0}function iQ(){if(m0)m0.shutdown(),m0=null}function nQ($){if(m0)m0.shutdown();m0=$}function rQ(){let $=e("os"),J=e("path"),Q=$.homedir(),X=process.env.XDG_DATA_HOME||J.join(Q,".local","share");return J.join(X,"roy-agent","traces.db")}var c9=null,m0=null,L7=0,t9=a(()=>{F7(),EQ(),fQ(),n()});var K={};HQ(K,{void:()=>IX,util:()=>l,unknown:()=>CX,union:()=>hX,undefined:()=>bX,tuple:()=>kX,transformer:()=>aX,symbol:()=>PX,string:()=>v7,strictObject:()=>xX,setErrorMap:()=>oQ,set:()=>lX,record:()=>mX,quotelessJson:()=>aQ,promise:()=>rX,preprocess:()=>tX,pipeline:()=>eX,ostring:()=>$Y,optional:()=>sX,onumber:()=>JY,oboolean:()=>QY,objectUtil:()=>e9,object:()=>vX,number:()=>x7,nullable:()=>oX,null:()=>EX,never:()=>fX,nativeEnum:()=>nX,nan:()=>AX,map:()=>uX,makeIssue:()=>F2,literal:()=>dX,lazy:()=>pX,late:()=>NX,isValid:()=>a0,isDirty:()=>R6,isAsync:()=>T$,isAborted:()=>K6,intersection:()=>gX,instanceof:()=>_X,getParsedType:()=>I0,getErrorMap:()=>I$,function:()=>cX,enum:()=>iX,effect:()=>aX,discriminatedUnion:()=>yX,defaultErrorMap:()=>u0,datetimeRegex:()=>f7,date:()=>wX,custom:()=>T7,coerce:()=>XY,boolean:()=>h7,bigint:()=>ZX,array:()=>TX,any:()=>SX,addIssueToContext:()=>E,ZodVoid:()=>O2,ZodUnknown:()=>s0,ZodUnion:()=>k$,ZodUndefined:()=>y$,ZodType:()=>m,ZodTuple:()=>v0,ZodTransformer:()=>P0,ZodSymbol:()=>M2,ZodString:()=>_0,ZodSet:()=>O$,ZodSchema:()=>m,ZodRecord:()=>K2,ZodReadonly:()=>i$,ZodPromise:()=>K$,ZodPipeline:()=>j2,ZodParsedType:()=>P,ZodOptional:()=>Z0,ZodObject:()=>$0,ZodNumber:()=>o0,ZodNullable:()=>c0,ZodNull:()=>g$,ZodNever:()=>T0,ZodNativeEnum:()=>c$,ZodNaN:()=>L2,ZodMap:()=>R2,ZodLiteral:()=>l$,ZodLazy:()=>u$,ZodIssueCode:()=>j,ZodIntersection:()=>m$,ZodFunction:()=>x$,ZodFirstPartyTypeKind:()=>_,ZodError:()=>q0,ZodEnum:()=>e0,ZodEffects:()=>P0,ZodDiscriminatedUnion:()=>L6,ZodDefault:()=>p$,ZodDate:()=>F$,ZodCatch:()=>d$,ZodBranded:()=>j6,ZodBoolean:()=>h$,ZodBigInt:()=>t0,ZodArray:()=>A0,ZodAny:()=>M$,Schema:()=>m,ParseStatus:()=>W0,OK:()=>H0,NEVER:()=>YY,INVALID:()=>T,EMPTY_PATH:()=>tQ,DIRTY:()=>D$,BRAND:()=>jX});var l;(function($){$.assertEqual=(Y)=>{};function J(Y){}$.assertIs=J;function Q(Y){throw Error()}$.assertNever=Q,$.arrayToEnum=(Y)=>{let G={};for(let q of Y)G[q]=q;return G},$.getValidEnumValues=(Y)=>{let G=$.objectKeys(Y).filter((W)=>typeof Y[Y[W]]!=="number"),q={};for(let W of G)q[W]=Y[W];return $.objectValues(q)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(G){return Y[G]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let G=[];for(let q in Y)if(Object.prototype.hasOwnProperty.call(Y,q))G.push(q);return G},$.find=(Y,G)=>{for(let q of Y)if(G(q))return q;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,G=" | "){return Y.map((q)=>typeof q==="string"?`'${q}'`:q).join(G)}$.joinValues=X,$.jsonStringifyReplacer=(Y,G)=>{if(typeof G==="bigint")return G.toString();return G}})(l||(l={}));var e9;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(e9||(e9={}));var P=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I0=($)=>{switch(typeof $){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN($)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":if(Array.isArray($))return P.array;if($===null)return P.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return P.promise;if(typeof Map<"u"&&$ instanceof Map)return P.map;if(typeof Set<"u"&&$ instanceof Set)return P.set;if(typeof Date<"u"&&$ instanceof Date)return P.date;return P.object;default:return P.unknown}};var j=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"]),aQ=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class q0 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(Y){return Y.message},Q={_errors:[]},X=(Y)=>{for(let G of Y.issues)if(G.code==="invalid_union")G.unionErrors.map(X);else if(G.code==="invalid_return_type")X(G.returnTypeError);else if(G.code==="invalid_arguments")X(G.argumentsError);else if(G.path.length===0)Q._errors.push(J(G));else{let q=Q,W=0;while(W<G.path.length){let z=G.path[W];if(W!==G.path.length-1)q[z]=q[z]||{_errors:[]};else q[z]=q[z]||{_errors:[]},q[z]._errors.push(J(G));q=q[z],W++}}};return X(this),Q}static assert($){if(!($ instanceof q0))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($=(J)=>J.message){let J={},Q=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];J[Y]=J[Y]||[],J[Y].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}q0.create=($)=>{return new q0($)};var sQ=($,J)=>{let Q;switch($.code){case j.invalid_type:if($.received===P.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case j.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case j.invalid_union:Q="Invalid input";break;case j.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case j.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case j.invalid_arguments:Q="Invalid function arguments";break;case j.invalid_return_type:Q="Invalid function return type";break;case j.invalid_date:Q="Invalid date";break;case j.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(Q=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")Q=`${Q} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)Q=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)Q=`Invalid input: must end with "${$.validation.endsWith}"`;else l.assertNever($.validation);else if($.validation!=="regex")Q=`Invalid ${$.validation}`;else Q="Invalid";break;case j.too_small:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else Q="Invalid input";break;case j.too_big:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")Q=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else Q="Invalid input";break;case j.custom:Q="Invalid input";break;case j.invalid_intersection_types:Q="Intersection results could not be merged";break;case j.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case j.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},u0=sQ;var P7=u0;function oQ($){P7=$}function I$(){return P7}var F2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:Y}=$,G=[...Q,...Y.path||[]],q={...Y,path:G};if(Y.message!==void 0)return{...Y,path:G,message:Y.message};let W="",z=X.filter((H)=>!!H).slice().reverse();for(let H of z)W=H(q,{data:J,defaultError:W}).message;return{...Y,path:G,message:W}},tQ=[];function E($,J){let Q=I$(),X=F2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===u0?void 0:u0].filter((Y)=>!!Y)});$.common.issues.push(X)}class W0{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,J){let Q=[];for(let X of J){if(X.status==="aborted")return T;if(X.status==="dirty")$.dirty();Q.push(X.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,J){let Q=[];for(let X of J){let Y=await X.key,G=await X.value;Q.push({key:Y,value:G})}return W0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:Y,value:G}=X;if(Y.status==="aborted")return T;if(G.status==="aborted")return T;if(Y.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof G.value<"u"||X.alwaysSet))Q[Y.value]=G.value}return{status:$.value,value:Q}}}var T=Object.freeze({status:"aborted"}),D$=($)=>({status:"dirty",value:$}),H0=($)=>({status:"valid",value:$}),K6=($)=>$.status==="aborted",R6=($)=>$.status==="dirty",a0=($)=>$.status==="valid",T$=($)=>typeof Promise<"u"&&$ instanceof Promise;var I;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(I||(I={}));class w0{constructor($,J,Q,X){this._cachedPath=[],this.parent=$,this.data=J,this._path=Q,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 b7=($,J)=>{if(a0(J))return{success:!0,data:J.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 Q=new q0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:Y}=$;if(J&&(Q||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:Y};return{errorMap:(q,W)=>{let{message:z}=$;if(q.code==="invalid_enum_value")return{message:z??W.defaultError};if(typeof W.data>"u")return{message:z??X??W.defaultError};if(q.code!=="invalid_type")return{message:W.defaultError};return{message:z??Q??W.defaultError}},description:Y}}class m{get description(){return this._def.description}_getType($){return I0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new W0,ctx:{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(T$(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let Q=this.safeParse($,J);if(Q.success)return Q.data;throw Q.error}safeParse($,J){let Q={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return b7(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return a0(Q)?{value:Q.value}:{issues:J.common.issues}}catch(Q){if(Q?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Q)=>a0(Q)?{value:Q.value}:{issues:J.common.issues})}async parseAsync($,J){let Q=await this.safeParseAsync($,J);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,J){let Q={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},X=this._parse({data:$,path:Q.path,parent:Q}),Y=await(T$(X)?X:Promise.resolve(X));return b7(Q,Y)}refine($,J){let Q=(X)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(X);else return J};return this._refinement((X,Y)=>{let G=$(X),q=()=>Y.addIssue({code:j.custom,...Q(X)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((W)=>{if(!W)return q(),!1;else return!0});if(!G)return q(),!1;else return!0})}refinement($,J){return this._refinement((Q,X)=>{if(!$(Q))return X.addIssue(typeof J==="function"?J(Q,X):J),!1;else return!0})}_refinement($){return new P0({schema:this,typeName:_.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:(J)=>this["~validate"](J)}}optional(){return Z0.create(this,this._def)}nullable(){return c0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return A0.create(this)}promise(){return K$.create(this,this._def)}or($){return k$.create([this,$],this._def)}and($){return m$.create(this,$,this._def)}transform($){return new P0({...h(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new p$({...h(this._def),innerType:this,defaultValue:J,typeName:_.ZodDefault})}brand(){return new j6({typeName:_.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new d$({...h(this._def),innerType:this,catchValue:J,typeName:_.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return j2.create(this,$)}readonly(){return i$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var eQ=/^c[^\s-]{8,}$/i,$X=/^[0-9a-z]+$/,JX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,QX=/^[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,XX=/^[a-z0-9_-]{21}$/i,YX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,GX=/^[-+]?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)?)??$/,qX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,WX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",$4,zX=/^(?:(?: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])$/,HX=/^(?:(?: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])$/,BX=/^(([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]))$/,UX=/^(([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])$/,VX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,DX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,S7="((\\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])))",FX=new RegExp(`^${S7}$`);function C7($){let J="[0-5]\\d";if($.precision)J=`${J}\\.\\d{${$.precision}}`;else if($.precision==null)J=`${J}(\\.\\d+)?`;let Q=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${J})${Q}`}function MX($){return new RegExp(`^${C7($)}$`)}function f7($){let J=`${S7}T${C7($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function OX($,J){if((J==="v4"||!J)&&zX.test($))return!0;if((J==="v6"||!J)&&BX.test($))return!0;return!1}function KX($,J){if(!YX.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let X=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.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(J&&Y.alg!==J)return!1;return!0}catch{return!1}}function RX($,J){if((J==="v4"||!J)&&HX.test($))return!0;if((J==="v6"||!J)&&UX.test($))return!0;return!1}class _0 extends m{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==P.string){let Y=this._getOrReturnCtx($);return E(Y,{code:j.invalid_type,expected:P.string,received:Y.parsedType}),T}let Q=new W0,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)X=this._getOrReturnCtx($,X),E(X,{code:j.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)X=this._getOrReturnCtx($,X),E(X,{code:j.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="length"){let G=$.data.length>Y.value,q=$.data.length<Y.value;if(G||q){if(X=this._getOrReturnCtx($,X),G)E(X,{code:j.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(q)E(X,{code:j.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});Q.dirty()}}else if(Y.kind==="email"){if(!qX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"email",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="emoji"){if(!$4)$4=new RegExp(WX,"u");if(!$4.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"emoji",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="uuid"){if(!QX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"uuid",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="nanoid"){if(!XX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"nanoid",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cuid"){if(!eQ.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cuid2"){if(!$X.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid2",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="ulid"){if(!JX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"ulid",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),E(X,{validation:"url",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"regex",code:j.invalid_string,message:Y.message}),Q.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),E(X,{code:j.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),Q.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),E(X,{code:j.invalid_string,validation:{startsWith:Y.value},message:Y.message}),Q.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))X=this._getOrReturnCtx($,X),E(X,{code:j.invalid_string,validation:{endsWith:Y.value},message:Y.message}),Q.dirty()}else if(Y.kind==="datetime"){if(!f7(Y).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:j.invalid_string,validation:"datetime",message:Y.message}),Q.dirty()}else if(Y.kind==="date"){if(!FX.test($.data))X=this._getOrReturnCtx($,X),E(X,{code:j.invalid_string,validation:"date",message:Y.message}),Q.dirty()}else if(Y.kind==="time"){if(!MX(Y).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:j.invalid_string,validation:"time",message:Y.message}),Q.dirty()}else if(Y.kind==="duration"){if(!GX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"duration",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="ip"){if(!OX($.data,Y.version))X=this._getOrReturnCtx($,X),E(X,{validation:"ip",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="jwt"){if(!KX($.data,Y.alg))X=this._getOrReturnCtx($,X),E(X,{validation:"jwt",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cidr"){if(!RX($.data,Y.version))X=this._getOrReturnCtx($,X),E(X,{validation:"cidr",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="base64"){if(!VX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64",code:j.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="base64url"){if(!DX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64url",code:j.invalid_string,message:Y.message}),Q.dirty()}else l.assertNever(Y);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:j.invalid_string,...I.errToObj(Q)})}_addCheck($){return new _0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...I.errToObj($)})}url($){return this._addCheck({kind:"url",...I.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...I.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...I.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...I.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...I.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...I.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...I.errToObj($)})}base64($){return this._addCheck({kind:"base64",...I.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...I.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...I.errToObj($)})}ip($){return this._addCheck({kind:"ip",...I.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...I.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,...I.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,...I.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...I.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...I.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...I.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...I.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...I.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...I.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...I.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...I.errToObj(J)})}nonempty($){return this.min(1,I.errToObj($))}trim(){return new _0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new _0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new _0({...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 J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxLength(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}_0.create=($)=>{return new _0({checks:[],typeName:_.ZodString,coerce:$?.coerce??!1,...h($)})};function LX($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,Y=Q>X?Q:X,G=Number.parseInt($.toFixed(Y).replace(".","")),q=Number.parseInt(J.toFixed(Y).replace(".",""));return G%q/10**Y}class o0 extends m{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($)!==P.number){let Y=this._getOrReturnCtx($);return E(Y,{code:j.invalid_type,expected:P.number,received:Y.parsedType}),T}let Q=void 0,X=new W0;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:j.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)Q=this._getOrReturnCtx($,Q),E(Q,{code:j.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)Q=this._getOrReturnCtx($,Q),E(Q,{code:j.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(LX($.data,Y.value)!==0)Q=this._getOrReturnCtx($,Q),E(Q,{code:j.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:j.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,I.toString(J))}gt($,J){return this.setLimit("min",$,!1,I.toString(J))}lte($,J){return this.setLimit("max",$,!0,I.toString(J))}lt($,J){return this.setLimit("max",$,!1,I.toString(J))}setLimit($,J,Q,X){return new o0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:I.toString(X)}]})}_addCheck($){return new o0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:I.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:I.toString(J)})}finite($){return this._addCheck({kind:"finite",message:I.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&l.isInteger($.value))}get isFinite(){let $=null,J=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(J===null||Q.value>J)J=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(J)&&Number.isFinite($)}}o0.create=($)=>{return new o0({checks:[],typeName:_.ZodNumber,coerce:$?.coerce||!1,...h($)})};class t0 extends m{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($)!==P.bigint)return this._getInvalidInput($);let Q=void 0,X=new W0;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:j.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)Q=this._getOrReturnCtx($,Q),E(Q,{code:j.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))Q=this._getOrReturnCtx($,Q),E(Q,{code:j.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return E(J,{code:j.invalid_type,expected:P.bigint,received:J.parsedType}),T}gte($,J){return this.setLimit("min",$,!0,I.toString(J))}gt($,J){return this.setLimit("min",$,!1,I.toString(J))}lte($,J){return this.setLimit("max",$,!0,I.toString(J))}lt($,J){return this.setLimit("max",$,!1,I.toString(J))}setLimit($,J,Q,X){return new t0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:I.toString(X)}]})}_addCheck($){return new t0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:I.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}t0.create=($)=>{return new t0({checks:[],typeName:_.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class h$ extends m{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==P.boolean){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.boolean,received:Q.parsedType}),T}return H0($.data)}}h$.create=($)=>{return new h$({typeName:_.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class F$ extends m{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==P.date){let Y=this._getOrReturnCtx($);return E(Y,{code:j.invalid_type,expected:P.date,received:Y.parsedType}),T}if(Number.isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return E(Y,{code:j.invalid_date}),T}let Q=new W0,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)X=this._getOrReturnCtx($,X),E(X,{code:j.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),Q.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)X=this._getOrReturnCtx($,X),E(X,{code:j.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),Q.dirty()}else l.assertNever(Y);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new F$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:I.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:I.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}F$.create=($)=>{return new F$({checks:[],coerce:$?.coerce||!1,typeName:_.ZodDate,...h($)})};class M2 extends m{_parse($){if(this._getType($)!==P.symbol){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.symbol,received:Q.parsedType}),T}return H0($.data)}}M2.create=($)=>{return new M2({typeName:_.ZodSymbol,...h($)})};class y$ extends m{_parse($){if(this._getType($)!==P.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.undefined,received:Q.parsedType}),T}return H0($.data)}}y$.create=($)=>{return new y$({typeName:_.ZodUndefined,...h($)})};class g$ extends m{_parse($){if(this._getType($)!==P.null){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.null,received:Q.parsedType}),T}return H0($.data)}}g$.create=($)=>{return new g$({typeName:_.ZodNull,...h($)})};class M$ extends m{constructor(){super(...arguments);this._any=!0}_parse($){return H0($.data)}}M$.create=($)=>{return new M$({typeName:_.ZodAny,...h($)})};class s0 extends m{constructor(){super(...arguments);this._unknown=!0}_parse($){return H0($.data)}}s0.create=($)=>{return new s0({typeName:_.ZodUnknown,...h($)})};class T0 extends m{_parse($){let J=this._getOrReturnCtx($);return E(J,{code:j.invalid_type,expected:P.never,received:J.parsedType}),T}}T0.create=($)=>{return new T0({typeName:_.ZodNever,...h($)})};class O2 extends m{_parse($){if(this._getType($)!==P.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.void,received:Q.parsedType}),T}return H0($.data)}}O2.create=($)=>{return new O2({typeName:_.ZodVoid,...h($)})};class A0 extends m{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==P.array)return E(J,{code:j.invalid_type,expected:P.array,received:J.parsedType}),T;if(X.exactLength!==null){let G=J.data.length>X.exactLength.value,q=J.data.length<X.exactLength.value;if(G||q)E(J,{code:G?j.too_big:j.too_small,minimum:q?X.exactLength.value:void 0,maximum:G?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),Q.dirty()}if(X.minLength!==null){if(J.data.length<X.minLength.value)E(J,{code:j.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),Q.dirty()}if(X.maxLength!==null){if(J.data.length>X.maxLength.value)E(J,{code:j.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),Q.dirty()}if(J.common.async)return Promise.all([...J.data].map((G,q)=>{return X.type._parseAsync(new w0(J,G,J.path,q))})).then((G)=>{return W0.mergeArray(Q,G)});let Y=[...J.data].map((G,q)=>{return X.type._parseSync(new w0(J,G,J.path,q))});return W0.mergeArray(Q,Y)}get element(){return this._def.type}min($,J){return new A0({...this._def,minLength:{value:$,message:I.toString(J)}})}max($,J){return new A0({...this._def,maxLength:{value:$,message:I.toString(J)}})}length($,J){return new A0({...this._def,exactLength:{value:$,message:I.toString(J)}})}nonempty($){return this.min(1,$)}}A0.create=($,J)=>{return new A0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...h(J)})};function v$($){if($ instanceof $0){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=Z0.create(v$(X))}return new $0({...$._def,shape:()=>J})}else if($ instanceof A0)return new A0({...$._def,type:v$($.element)});else if($ instanceof Z0)return Z0.create(v$($.unwrap()));else if($ instanceof c0)return c0.create(v$($.unwrap()));else if($ instanceof v0)return v0.create($.items.map((J)=>v$(J)));else return $}class $0 extends m{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(),J=l.objectKeys($);return this._cached={shape:$,keys:J},this._cached}_parse($){if(this._getType($)!==P.object){let z=this._getOrReturnCtx($);return E(z,{code:j.invalid_type,expected:P.object,received:z.parsedType}),T}let{status:Q,ctx:X}=this._processInputParams($),{shape:Y,keys:G}=this._getCached(),q=[];if(!(this._def.catchall instanceof T0&&this._def.unknownKeys==="strip")){for(let z in X.data)if(!G.includes(z))q.push(z)}let W=[];for(let z of G){let H=Y[z],B=X.data[z];W.push({key:{status:"valid",value:z},value:H._parse(new w0(X,B,X.path,z)),alwaysSet:z in X.data})}if(this._def.catchall instanceof T0){let z=this._def.unknownKeys;if(z==="passthrough")for(let H of q)W.push({key:{status:"valid",value:H},value:{status:"valid",value:X.data[H]}});else if(z==="strict"){if(q.length>0)E(X,{code:j.unrecognized_keys,keys:q}),Q.dirty()}else if(z==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let z=this._def.catchall;for(let H of q){let B=X.data[H];W.push({key:{status:"valid",value:H},value:z._parse(new w0(X,B,X.path,H)),alwaysSet:H in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let z=[];for(let H of W){let B=await H.key,U=await H.value;z.push({key:B,value:U,alwaysSet:H.alwaysSet})}return z}).then((z)=>{return W0.mergeObjectSync(Q,z)});else return W0.mergeObjectSync(Q,W)}get shape(){return this._def.shape()}strict($){return I.errToObj,new $0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,Q)=>{let X=this._def.errorMap?.(J,Q).message??Q.defaultError;if(J.code==="unrecognized_keys")return{message:I.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new $0({...this._def,unknownKeys:"strip"})}passthrough(){return new $0({...this._def,unknownKeys:"passthrough"})}extend($){return new $0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new $0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:_.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new $0({...this._def,catchall:$})}pick($){let J={};for(let Q of l.objectKeys($))if($[Q]&&this.shape[Q])J[Q]=this.shape[Q];return new $0({...this._def,shape:()=>J})}omit($){let J={};for(let Q of l.objectKeys(this.shape))if(!$[Q])J[Q]=this.shape[Q];return new $0({...this._def,shape:()=>J})}deepPartial(){return v$(this)}partial($){let J={};for(let Q of l.objectKeys(this.shape)){let X=this.shape[Q];if($&&!$[Q])J[Q]=X;else J[Q]=X.optional()}return new $0({...this._def,shape:()=>J})}required($){let J={};for(let Q of l.objectKeys(this.shape))if($&&!$[Q])J[Q]=this.shape[Q];else{let Y=this.shape[Q];while(Y instanceof Z0)Y=Y._def.innerType;J[Q]=Y}return new $0({...this._def,shape:()=>J})}keyof(){return I7(l.objectKeys(this.shape))}}$0.create=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strip",catchall:T0.create(),typeName:_.ZodObject,...h(J)})};$0.strictCreate=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strict",catchall:T0.create(),typeName:_.ZodObject,...h(J)})};$0.lazycreate=($,J)=>{return new $0({shape:$,unknownKeys:"strip",catchall:T0.create(),typeName:_.ZodObject,...h(J)})};class k$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(Y){for(let q of Y)if(q.result.status==="valid")return q.result;for(let q of Y)if(q.result.status==="dirty")return J.common.issues.push(...q.ctx.common.issues),q.result;let G=Y.map((q)=>new q0(q.ctx.common.issues));return E(J,{code:j.invalid_union,unionErrors:G}),T}if(J.common.async)return Promise.all(Q.map(async(Y)=>{let G={...J,common:{...J.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:J.data,path:J.path,parent:G}),ctx:G}})).then(X);else{let Y=void 0,G=[];for(let W of Q){let z={...J,common:{...J.common,issues:[]},parent:null},H=W._parseSync({data:J.data,path:J.path,parent:z});if(H.status==="valid")return H;else if(H.status==="dirty"&&!Y)Y={result:H,ctx:z};if(z.common.issues.length)G.push(z.common.issues)}if(Y)return J.common.issues.push(...Y.ctx.common.issues),Y.result;let q=G.map((W)=>new q0(W));return E(J,{code:j.invalid_union,unionErrors:q}),T}}get options(){return this._def.options}}k$.create=($,J)=>{return new k$({options:$,typeName:_.ZodUnion,...h(J)})};var l0=($)=>{if($ instanceof u$)return l0($.schema);else if($ instanceof P0)return l0($.innerType());else if($ instanceof l$)return[$.value];else if($ instanceof e0)return $.options;else if($ instanceof c$)return l.objectValues($.enum);else if($ instanceof p$)return l0($._def.innerType);else if($ instanceof y$)return[void 0];else if($ instanceof g$)return[null];else if($ instanceof Z0)return[void 0,...l0($.unwrap())];else if($ instanceof c0)return[null,...l0($.unwrap())];else if($ instanceof j6)return l0($.unwrap());else if($ instanceof i$)return l0($.unwrap());else if($ instanceof d$)return l0($._def.innerType);else return[]};class L6 extends m{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.object)return E(J,{code:j.invalid_type,expected:P.object,received:J.parsedType}),T;let Q=this.discriminator,X=J.data[Q],Y=this.optionsMap.get(X);if(!Y)return E(J,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),T;if(J.common.async)return Y._parseAsync({data:J.data,path:J.path,parent:J});else return Y._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,Q){let X=new Map;for(let Y of J){let G=l0(Y.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let q of G){if(X.has(q))throw Error(`Discriminator property ${String($)} has duplicate value ${String(q)}`);X.set(q,Y)}}return new L6({typeName:_.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function J4($,J){let Q=I0($),X=I0(J);if($===J)return{valid:!0,data:$};else if(Q===P.object&&X===P.object){let Y=l.objectKeys(J),G=l.objectKeys($).filter((W)=>Y.indexOf(W)!==-1),q={...$,...J};for(let W of G){let z=J4($[W],J[W]);if(!z.valid)return{valid:!1};q[W]=z.data}return{valid:!0,data:q}}else if(Q===P.array&&X===P.array){if($.length!==J.length)return{valid:!1};let Y=[];for(let G=0;G<$.length;G++){let q=$[G],W=J[G],z=J4(q,W);if(!z.valid)return{valid:!1};Y.push(z.data)}return{valid:!0,data:Y}}else if(Q===P.date&&X===P.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class m$ extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(Y,G)=>{if(K6(Y)||K6(G))return T;let q=J4(Y.value,G.value);if(!q.valid)return E(Q,{code:j.invalid_intersection_types}),T;if(R6(Y)||R6(G))J.dirty();return{status:J.value,value:q.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([Y,G])=>X(Y,G));else return X(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}m$.create=($,J,Q)=>{return new m$({left:$,right:J,typeName:_.ZodIntersection,...h(Q)})};class v0 extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.array)return E(Q,{code:j.invalid_type,expected:P.array,received:Q.parsedType}),T;if(Q.data.length<this._def.items.length)return E(Q,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;if(!this._def.rest&&Q.data.length>this._def.items.length)E(Q,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let Y=[...Q.data].map((G,q)=>{let W=this._def.items[q]||this._def.rest;if(!W)return null;return W._parse(new w0(Q,G,Q.path,q))}).filter((G)=>!!G);if(Q.common.async)return Promise.all(Y).then((G)=>{return W0.mergeArray(J,G)});else return W0.mergeArray(J,Y)}get items(){return this._def.items}rest($){return new v0({...this._def,rest:$})}}v0.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new v0({items:$,typeName:_.ZodTuple,rest:null,...h(J)})};class K2 extends m{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.object)return E(Q,{code:j.invalid_type,expected:P.object,received:Q.parsedType}),T;let X=[],Y=this._def.keyType,G=this._def.valueType;for(let q in Q.data)X.push({key:Y._parse(new w0(Q,q,Q.path,q)),value:G._parse(new w0(Q,Q.data[q],Q.path,q)),alwaysSet:q in Q.data});if(Q.common.async)return W0.mergeObjectAsync(J,X);else return W0.mergeObjectSync(J,X)}get element(){return this._def.valueType}static create($,J,Q){if(J instanceof m)return new K2({keyType:$,valueType:J,typeName:_.ZodRecord,...h(Q)});return new K2({keyType:_0.create(),valueType:$,typeName:_.ZodRecord,...h(J)})}}class R2 extends m{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.map)return E(Q,{code:j.invalid_type,expected:P.map,received:Q.parsedType}),T;let X=this._def.keyType,Y=this._def.valueType,G=[...Q.data.entries()].map(([q,W],z)=>{return{key:X._parse(new w0(Q,q,Q.path,[z,"key"])),value:Y._parse(new w0(Q,W,Q.path,[z,"value"]))}});if(Q.common.async){let q=new Map;return Promise.resolve().then(async()=>{for(let W of G){let z=await W.key,H=await W.value;if(z.status==="aborted"||H.status==="aborted")return T;if(z.status==="dirty"||H.status==="dirty")J.dirty();q.set(z.value,H.value)}return{status:J.value,value:q}})}else{let q=new Map;for(let W of G){let{key:z,value:H}=W;if(z.status==="aborted"||H.status==="aborted")return T;if(z.status==="dirty"||H.status==="dirty")J.dirty();q.set(z.value,H.value)}return{status:J.value,value:q}}}}R2.create=($,J,Q)=>{return new R2({valueType:J,keyType:$,typeName:_.ZodMap,...h(Q)})};class O$ extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.set)return E(Q,{code:j.invalid_type,expected:P.set,received:Q.parsedType}),T;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)E(Q,{code:j.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),J.dirty()}if(X.maxSize!==null){if(Q.data.size>X.maxSize.value)E(Q,{code:j.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let Y=this._def.valueType;function G(W){let z=new Set;for(let H of W){if(H.status==="aborted")return T;if(H.status==="dirty")J.dirty();z.add(H.value)}return{status:J.value,value:z}}let q=[...Q.data.values()].map((W,z)=>Y._parse(new w0(Q,W,Q.path,z)));if(Q.common.async)return Promise.all(q).then((W)=>G(W));else return G(q)}min($,J){return new O$({...this._def,minSize:{value:$,message:I.toString(J)}})}max($,J){return new O$({...this._def,maxSize:{value:$,message:I.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}O$.create=($,J)=>{return new O$({valueType:$,minSize:null,maxSize:null,typeName:_.ZodSet,...h(J)})};class x$ extends m{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.function)return E(J,{code:j.invalid_type,expected:P.function,received:J.parsedType}),T;function Q(q,W){return F2({data:q,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,I$(),u0].filter((z)=>!!z),issueData:{code:j.invalid_arguments,argumentsError:W}})}function X(q,W){return F2({data:q,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,I$(),u0].filter((z)=>!!z),issueData:{code:j.invalid_return_type,returnTypeError:W}})}let Y={errorMap:J.common.contextualErrorMap},G=J.data;if(this._def.returns instanceof K$){let q=this;return H0(async function(...W){let z=new q0([]),H=await q._def.args.parseAsync(W,Y).catch((V)=>{throw z.addIssue(Q(W,V)),z}),B=await Reflect.apply(G,this,H);return await q._def.returns._def.type.parseAsync(B,Y).catch((V)=>{throw z.addIssue(X(B,V)),z})})}else{let q=this;return H0(function(...W){let z=q._def.args.safeParse(W,Y);if(!z.success)throw new q0([Q(W,z.error)]);let H=Reflect.apply(G,this,z.data),B=q._def.returns.safeParse(H,Y);if(!B.success)throw new q0([X(H,B.error)]);return B.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new x$({...this._def,args:v0.create($).rest(s0.create())})}returns($){return new x$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new x$({args:$?$:v0.create([]).rest(s0.create()),returns:J||s0.create(),typeName:_.ZodFunction,...h(Q)})}}class u$ extends m{get schema(){return this._def.getter()}_parse($){let{ctx:J}=this._processInputParams($);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}u$.create=($,J)=>{return new u$({getter:$,typeName:_.ZodLazy,...h(J)})};class l$ extends m{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return E(J,{received:J.data,code:j.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:$.data}}get value(){return this._def.value}}l$.create=($,J)=>{return new l$({value:$,typeName:_.ZodLiteral,...h(J)})};function I7($,J){return new e0({values:$,typeName:_.ZodEnum,...h(J)})}class e0 extends m{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{expected:l.joinValues(Q),received:J.parsedType,code:j.invalid_type}),T}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{received:J.data,code:j.invalid_enum_value,options:Q}),T}return H0($.data)}get options(){return this._def.values}get enum(){let $={};for(let J of this._def.values)$[J]=J;return $}get Values(){let $={};for(let J of this._def.values)$[J]=J;return $}get Enum(){let $={};for(let J of this._def.values)$[J]=J;return $}extract($,J=this._def){return e0.create($,{...this._def,...J})}exclude($,J=this._def){return e0.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}e0.create=I7;class c$ extends m{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==P.string&&Q.parsedType!==P.number){let X=l.objectValues(J);return E(Q,{expected:l.joinValues(X),received:Q.parsedType,code:j.invalid_type}),T}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return E(Q,{received:Q.data,code:j.invalid_enum_value,options:X}),T}return H0($.data)}get enum(){return this._def.values}}c$.create=($,J)=>{return new c$({values:$,typeName:_.ZodNativeEnum,...h(J)})};class K$ extends m{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.promise&&J.common.async===!1)return E(J,{code:j.invalid_type,expected:P.promise,received:J.parsedType}),T;let Q=J.parsedType===P.promise?J.data:Promise.resolve(J.data);return H0(Q.then((X)=>{return this._def.type.parseAsync(X,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}K$.create=($,J)=>{return new K$({type:$,typeName:_.ZodPromise,...h(J)})};class P0 extends m{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,Y={addIssue:(G)=>{if(E(Q,G),G.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let G=X.transform(Q.data,Y);if(Q.common.async)return Promise.resolve(G).then(async(q)=>{if(J.value==="aborted")return T;let W=await this._def.schema._parseAsync({data:q,path:Q.path,parent:Q});if(W.status==="aborted")return T;if(W.status==="dirty")return D$(W.value);if(J.value==="dirty")return D$(W.value);return W});else{if(J.value==="aborted")return T;let q=this._def.schema._parseSync({data:G,path:Q.path,parent:Q});if(q.status==="aborted")return T;if(q.status==="dirty")return D$(q.value);if(J.value==="dirty")return D$(q.value);return q}}if(X.type==="refinement"){let G=(q)=>{let W=X.refinement(q,Y);if(Q.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return q};if(Q.common.async===!1){let q=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(q.status==="aborted")return T;if(q.status==="dirty")J.dirty();return G(q.value),{status:J.value,value:q.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((q)=>{if(q.status==="aborted")return T;if(q.status==="dirty")J.dirty();return G(q.value).then(()=>{return{status:J.value,value:q.value}})})}if(X.type==="transform")if(Q.common.async===!1){let G=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!a0(G))return T;let q=X.transform(G.value,Y);if(q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:q}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(!a0(G))return T;return Promise.resolve(X.transform(G.value,Y)).then((q)=>({status:J.value,value:q}))});l.assertNever(X)}}P0.create=($,J,Q)=>{return new P0({schema:$,typeName:_.ZodEffects,effect:J,...h(Q)})};P0.createWithPreprocess=($,J,Q)=>{return new P0({schema:J,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...h(Q)})};class Z0 extends m{_parse($){if(this._getType($)===P.undefined)return H0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z0.create=($,J)=>{return new Z0({innerType:$,typeName:_.ZodOptional,...h(J)})};class c0 extends m{_parse($){if(this._getType($)===P.null)return H0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}c0.create=($,J)=>{return new c0({innerType:$,typeName:_.ZodNullable,...h(J)})};class p$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===P.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}p$.create=($,J)=>{return new p$({innerType:$,typeName:_.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class d$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q={...J,common:{...J.common,issues:[]}},X=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(T$(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new q0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new q0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}d$.create=($,J)=>{return new d$({innerType:$,typeName:_.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class L2 extends m{_parse($){if(this._getType($)!==P.nan){let Q=this._getOrReturnCtx($);return E(Q,{code:j.invalid_type,expected:P.nan,received:Q.parsedType}),T}return{status:"valid",value:$.data}}}L2.create=($)=>{return new L2({typeName:_.ZodNaN,...h($)})};var jX=Symbol("zod_brand");class j6 extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;return this._def.type._parse({data:Q,path:J.path,parent:J})}unwrap(){return this._def.type}}class j2 extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return T;if(Y.status==="dirty")return J.dirty(),D$(Y.value);else return this._def.out._parseAsync({data:Y.value,path:Q.path,parent:Q})})();else{let X=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(X.status==="aborted")return T;if(X.status==="dirty")return J.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:Q.path,parent:Q})}}static create($,J){return new j2({in:$,out:J,typeName:_.ZodPipeline})}}class i$ extends m{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(a0(X))X.value=Object.freeze(X.value);return X};return T$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}i$.create=($,J)=>{return new i$({innerType:$,typeName:_.ZodReadonly,...h(J)})};function E7($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function T7($,J={},Q){if($)return M$.create().superRefine((X,Y)=>{let G=$(X);if(G instanceof Promise)return G.then((q)=>{if(!q){let W=E7(J,X),z=W.fatal??Q??!0;Y.addIssue({code:"custom",...W,fatal:z})}});if(!G){let q=E7(J,X),W=q.fatal??Q??!0;Y.addIssue({code:"custom",...q,fatal:W})}return});return M$.create()}var NX={object:$0.lazycreate},_;(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"})(_||(_={}));var _X=($,J={message:`Input not instance of ${$.name}`})=>T7((Q)=>Q instanceof $,J),v7=_0.create,x7=o0.create,AX=L2.create,ZX=t0.create,h7=h$.create,wX=F$.create,PX=M2.create,bX=y$.create,EX=g$.create,SX=M$.create,CX=s0.create,fX=T0.create,IX=O2.create,TX=A0.create,vX=$0.create,xX=$0.strictCreate,hX=k$.create,yX=L6.create,gX=m$.create,kX=v0.create,mX=K2.create,uX=R2.create,lX=O$.create,cX=x$.create,pX=u$.create,dX=l$.create,iX=e0.create,nX=c$.create,rX=K$.create,aX=P0.create,sX=Z0.create,oX=c0.create,tX=P0.createWithPreprocess,eX=j2.create,$Y=()=>v7().optional(),JY=()=>x7().optional(),QY=()=>h7().optional(),XY={string:($)=>_0.create({...$,coerce:!0}),number:($)=>o0.create({...$,coerce:!0}),boolean:($)=>h$.create({...$,coerce:!0}),bigint:($)=>t0.create({...$,coerce:!0}),date:($)=>F$.create({...$,coerce:!0})};var YY=T;var Q4=K.object({bgProcessId:K.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function GY($){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 y7($){let J=Date.now();return{alive:!1,status:"not_found",createdAt:J,lastUpdatedAt:J,description:`No background process found with id '${$}'.`}}var tO={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
433
+ `).all($).map((Q)=>{let X=Number(Q.span_count)||0,q=Number(Q.error_count)||0,Y=Q.end_time??void 0,G=q===0?"ok":q>=X?"error":"mixed";return{traceId:Q.trace_id,rootSpanName:Q.root_name??"unknown",startTime:Q.start_time,endTime:Y,duration:Y!==void 0?Y-Q.start_time:void 0,spanCount:X,status:G}})}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 J=new Map,Q=[];for(let X of $)J.set(X.spanId,{...X,children:[]});for(let X of J.values())if(X.parentSpanId){let q=J.get(X.parentSpanId);if(q)q.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var A5=()=>{};import{appendFileSync as mQ,existsSync as uQ,mkdirSync as lQ}from"fs";import{join as j2}from"path";import{AsyncLocalStorage as R5}from"async_hooks";function _5($,J){return $.padStart(J,"0")}function p9($){return/^[0-9a-f]+$/i.test($)}function IQ($){let J=_5($.traceId.toLowerCase(),b5),Q=_5($.spanId.toLowerCase(),E5);return[r9,J,Q,vQ].join("-")}function TQ($){if(!$||typeof $!=="string")return;let Q=$.trim().split("-");if(Q.length!==4)return;let[X,q,Y,G]=Q;if(X!==r9){if(X>r9)return}if(q.length!==b5||!p9(q))return;if(Y.length!==E5||!p9(Y))return;if(G.length!==xQ||!p9(G))return;return{traceId:q.toLowerCase(),spanId:Y.toLowerCase()}}var r9="00",vQ="01",i9="TRACEPARENT",b5=32,E5=16,xQ=2,o9,yQ=s(()=>{o9={inject($,J){$[i9]=IQ(J)},extract($){let J=$[i9];if(!J)return;return TQ(J)},getTraceparentHeader(){return i9}}}),hQ,gQ,kQ=s(()=>{(($)=>{$.CLIENT="client",$.SERVER="server",$.INTERNAL="internal"})(hQ||={}),(($)=>{$.OK="ok",$.ERROR="error"})(gQ||={})});function t9($){let J=$.replace(/\\/g,"/"),Q=J.match(/\/\$bunfs\/root\/(.+)$/);if(Q){let G=Q[1],W=G.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];return G}let X=J.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let G=X[1].replace(/\+/g,"/"),W=X[2],z=G,H=W.startsWith("src/")?W:`src/${W}`;return`${z}/${H}`}let q=J.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(q)return q[1];let Y=["packages/core/src","packages/core","packages"];for(let G of Y){let W=J.indexOf(G);if(W!==-1)return J.substring(W)}return J}function cQ(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let J=$0("xdg-basedir");if(J.xdgData)return j2(J.xdgData,"roy-agent","logs")}catch{}return j2($,".local","share","roy-agent","logs")}function dQ(){return oQ}function pQ(){if(w0){let J=w0.get("log_trace.logging.level");if(J&&["debug","info","warn","error"].includes(J))return J}let $=process.env.LOG_LEVEL;if($&&["debug","info","warn","error"].includes($))return $;return"info"}function iQ($){if(w0){let X=w0.get("log_trace.logging.levels");if(X&&typeof X==="object"){let Y=X[$];if(Y&&["debug","info","warn","error"].includes(Y))return Y}let q=w0.get(`log_trace.logging.levels.${$}`);if(q&&["debug","info","warn","error"].includes(q))return q}let J=`LOG_LEVEL_${$.toUpperCase().replace(/:/g,"_")}`,Q=process.env[J];if(Q&&["debug","info","warn","error"].includes(Q))return Q;return pQ()}function nQ($){if($.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test($))return!0;return!1}function rQ($){if($.startsWith("~")){let J=process.env.HOME||process.env.USERPROFILE||"/tmp";return j2(J,$.slice(1))}return $}function aQ(){if(w0){let $=w0.get("log-trace.logging.file");if($)return $}return"app.log"}function sQ(){if(w0){let $=w0.get("log-trace.logging.dir");if($)return $}return cQ()}function e9(){if(w0){let $=w0.get("log-trace.logging.maxOutput");if(typeof $==="number")return $}return}class S5{prefix;constructor($){this.prefix=$}shouldLog($){let J=iQ(this.prefix);return a9[$]>=a9[J]}ensureLogDirectory($){if(!uQ($))try{lQ($,{recursive:!0})}catch(J){console.error("[Logger] Failed to create log directory:",$,J)}}getCallerLocation(){let $=Error.stackTraceLimit;Error.stackTraceLimit=10;let J=Error();Error.captureStackTrace(J,this.formatMessage);let Q=J.stack?.split(`
434
+ `)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let q=Q[X];if(q.includes("at ")&&!q.includes("logger.ts")&&!q.includes("formatMessage")){let Y=q.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||q.match(/at\s+(.+):(\d+):\d+/);if(Y){let G=Y[1];return{file:this.getRelativePath(G),line:parseInt(Y[2],10)}}}}return null}getRelativePath($){return t9($)}formatMessage($,J,Q){let X=new Date,q=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"),Y=this.prefix?`[${this.prefix}]`:"",G="";try{let V=L2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)G=`[traceId=${V.traceId}]`}catch{}let W="";if(Q&&typeof Q==="object"&&"callerLocation"in Q){let B=Q;W=B.callerLocation?` [${B.callerLocation}]`:"";let{callerLocation:U,...V}=B;Q=Object.keys(V).length>0?V:void 0}else{let B=this.getCallerLocation();if(B)W=` [${B.file}:${B.line}]`}let z=`${q} [${$.toUpperCase()}]${G}${W}${Y} ${J}`;if(Q!==void 0)if(typeof Q==="object")z+=" "+JSON.stringify(Q).replace(/\n/g,"");else z+=" "+String(Q);let H=e9();if(H&&H>0&&z.length>H)z=z.substring(0,H)+" [TRUNCATED]";return z}writeToFile($){try{let J=sQ(),Q=aQ(),X=rQ(J),q=nQ(X)?X:j2(process.cwd(),X);this.ensureLogDirectory(q);let Y=j2(q,Q);mQ(Y,$+`
435
+ `,"utf-8")}catch(J){console.error("[Logger] Failed to write to log file:",J)}}log($,J,Q){if(!this.shouldLog($))return;let X=this.formatMessage($,J,Q);if(this.writeToFile(X),!dQ())if(tQ)console.error(X);else($==="error"?console.error:$==="warn"?console.warn:$==="info"?console.log:console.debug)(X)}debug($,J){this.log("debug",$,J)}info($,J){this.log("info",$,J)}warn($,J){this.log("warn",$,J)}error($,J){this.log("error",$,J)}}function d($){if(!N6.has($))N6.set($,new S5($));return N6.get($)}var w0=null,oQ=!1,tQ=!1;var a9,N6,i=s(()=>{Q4(),a9={debug:0,info:1,warn:2,error:3},N6=new Map}),eQ={};d0(eQ,{setTracerProvider:()=>JX,resetTracerProvider:()=>$X,getTracerProvider:()=>L2,OTelTracerProvider:()=>J4});function $4(){if(!n9)n9=d("otel-tracer");return n9}function C5(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function f5($,...J){$4().info($,...J)}function Z5($,...J){$4().warn($,...J)}function w5($,...J){$4().error($,...J)}class s9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,q){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=q}setAttribute($,J){this.attributes[$]=J}addEvent($,J){let Q=this.attributes._events||[];Q.push({name:$,attributes:J}),this.attributes._events=Q}end($,J){if(this.endTime=Date.now(),J)this.error=J.message;let Q=this.endTime-(this.startTime||0);if(C5())f5(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${Q}ms status=${J?"ERROR":"OK"}`);let X=this.storage;if(!X)Z5(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=L2().getStorage();if(X){if(!(X.db||X.initialized))Z5(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((Y)=>{w5("[OTelSpan] Failed to initialize storage:",Y)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:J?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:$,error:this.error})}else w5(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class I5{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($,J,Q,X){this.name=$,this.version=J,this.storage=Q,this.provider=X,this.instanceId=`${$}@${X.instanceId}`}setOnSpanEndCallback($){this.onSpanEndCallback=$}getActiveSpanCount(){return this.activeSpans.size}startSpan($,J){let Q=J?.parent,X=J&&"parent"in J,q=J&&"context"in J,Y=this.provider.getGlobalContext(),G,W,z,H,B;if(q&&J?.context){let V=J.context;W=V.traceId,z=this.generateSpanId(),H=V.spanId,B={traceId:W,spanId:z,parentSpanId:H},this.currentContext={traceId:W,spanId:z,parentSpanId:H};let O=new s9($,B,this.storage,V,()=>this.handleSpanEnd(B.spanId,V.spanId));if(J?.attributes)for(let[F,D]of Object.entries(J.attributes))O.setAttribute(F,D);return this.activeSpans.set(z,O),O}if(X)G=Q;else if(this.currentContext)G=this.currentContext;else if(Y)G=Y;if(W=G?.traceId||this.generateTraceId(),z=this.generateSpanId(),X&&Q)H=Q.parentSpanId||Q.spanId;else if(this.currentContext)H=this.currentContext.spanId;else if(Y)H=Y.spanId;B={traceId:W,spanId:z,parentSpanId:H},this.currentContext={traceId:W,spanId:z,parentSpanId:H};let U=new s9($,B,this.storage,G,()=>this.handleSpanEnd(B.spanId,G?.spanId));if(J?.attributes)for(let[V,O]of Object.entries(J.attributes))U.setAttribute(V,O);if(this.activeSpans.set(z,U),C5())f5(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${W} spanId=${z} parentSpanId=${H||"-"}`);return U}injectToEnv($){if(this.currentContext)o9.inject($,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}findStackParentSpan($){for(let[,J]of this.activeSpans)if(J.spanContext.parentSpanId===$)return J;return}endSpan($){let J=$.spanContext;this.activeSpans.delete(J.spanId);let Q=this.currentContext?.traceId;if(J.parentSpanId){let q=this.activeSpans.get(J.parentSpanId);if(q){let Y={traceId:J.traceId,spanId:q.spanContext.spanId,parentSpanId:q.spanContext.parentSpanId};return this.currentContext=Y,Y}if(Q){let Y={traceId:Q,spanId:J.parentSpanId,parentSpanId:void 0};return this.currentContext=Y,Y}}let X=this.findStackParentSpan(J.spanId);if(X){let q={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=q,q}this.currentContext=void 0;return}generateTraceId(){let $=Date.now().toString(16).padStart(12,"0"),J=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return($+J).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd($,J){if(this.activeSpans.delete($),J){let X=this.activeSpans.get(J);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:J,parentSpanId:void 0};return}}let Q=this.findStackParentSpan($);if(Q){this.currentContext={traceId:Q.spanContext.traceId,spanId:Q.spanContext.spanId,parentSpanId:Q.spanContext.parentSpanId};return}this.currentContext=void 0}}class J4{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new R5;tracerContexts=new Map;tracerContextScope=new R5;instanceId;constructor($,J){P5++,this.instanceId=`Provider#${P5}`,this.storage=$||new d9(J||QX())}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($,J){let Q=new Map(this.tracerContexts);return this.globalContextScope.run({value:$},()=>this.tracerContextScope.run({contexts:Q},J))}runInGlobalContextSync($,J){let Q=new Map(this.tracerContexts);return this.globalContextScope.run({value:$},()=>this.tracerContextScope.run({contexts:Q},J))}getTracerCurrentContext($){let J=this.tracerContextScope.getStore();if(J)return J.contexts.get($);return this.tracerContexts.get($)}setTracerCurrentContext($,J){let Q=this.tracerContextScope.getStore();if(Q){Q.contexts.set($,J);return}this.tracerContexts.set($,J)}clearAllTracerCurrentContexts(){let $=this.tracerContextScope.getStore();if($){$.contexts.clear();return}this.tracerContexts.clear()}getTracer($,J){let Q=`${$}@${J||"0.0.0"}`,X=this.tracers.get(Q);if(!X){if(X=new I5($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=o9.extract(process.env);if(J)$.setCurrentContext({traceId:J.traceId,spanId:J.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 L2(){if(!p0)p0=new J4;return p0}function $X(){if(p0)p0.shutdown(),p0=null}function JX($){if(p0)p0.shutdown();p0=$}function QX(){let $=$0("os"),J=$0("path"),Q=$.homedir(),X=process.env.XDG_DATA_HOME||J.join(Q,".local","share");return J.join(X,"roy-agent","traces.db")}var n9=null,p0=null,P5=0,Q4=s(()=>{A5(),yQ(),kQ(),i()});var K={};KQ(K,{void:()=>mX,util:()=>l,unknown:()=>gX,union:()=>dX,undefined:()=>xX,tuple:()=>nX,transformer:()=>Xq,symbol:()=>vX,string:()=>u5,strictObject:()=>cX,setErrorMap:()=>YX,set:()=>sX,record:()=>rX,quotelessJson:()=>XX,promise:()=>Qq,preprocess:()=>Gq,pipeline:()=>Wq,ostring:()=>zq,optional:()=>qq,onumber:()=>Hq,oboolean:()=>Bq,objectUtil:()=>X4,object:()=>lX,number:()=>l5,nullable:()=>Yq,null:()=>yX,never:()=>kX,nativeEnum:()=>Jq,nan:()=>fX,map:()=>aX,makeIssue:()=>N2,literal:()=>eX,lazy:()=>tX,late:()=>SX,isValid:()=>e0,isDirty:()=>_6,isAsync:()=>g$,isAborted:()=>A6,intersection:()=>iX,instanceof:()=>CX,getParsedType:()=>g0,getErrorMap:()=>h$,function:()=>oX,enum:()=>$q,effect:()=>Xq,discriminatedUnion:()=>pX,defaultErrorMap:()=>i0,datetimeRegex:()=>g5,date:()=>TX,custom:()=>m5,coerce:()=>Uq,boolean:()=>c5,bigint:()=>IX,array:()=>uX,any:()=>hX,addIssueToContext:()=>E,ZodVoid:()=>_2,ZodUnknown:()=>$$,ZodUnion:()=>d$,ZodUndefined:()=>l$,ZodType:()=>m,ZodTuple:()=>m0,ZodTransformer:()=>C0,ZodSymbol:()=>A2,ZodString:()=>P0,ZodSet:()=>_$,ZodSchema:()=>m,ZodRecord:()=>R2,ZodReadonly:()=>o$,ZodPromise:()=>R$,ZodPipeline:()=>P2,ZodParsedType:()=>P,ZodOptional:()=>E0,ZodObject:()=>J0,ZodNumber:()=>J$,ZodNullable:()=>r0,ZodNull:()=>c$,ZodNever:()=>k0,ZodNativeEnum:()=>r$,ZodNaN:()=>w2,ZodMap:()=>Z2,ZodLiteral:()=>n$,ZodLazy:()=>i$,ZodIssueCode:()=>N,ZodIntersection:()=>p$,ZodFunction:()=>m$,ZodFirstPartyTypeKind:()=>_,ZodError:()=>W0,ZodEnum:()=>X$,ZodEffects:()=>C0,ZodDiscriminatedUnion:()=>R6,ZodDefault:()=>a$,ZodDate:()=>N$,ZodCatch:()=>s$,ZodBranded:()=>Z6,ZodBoolean:()=>u$,ZodBigInt:()=>Q$,ZodArray:()=>b0,ZodAny:()=>A$,Schema:()=>m,ParseStatus:()=>z0,OK:()=>U0,NEVER:()=>Vq,INVALID:()=>v,EMPTY_PATH:()=>GX,DIRTY:()=>L$,BRAND:()=>EX});var l;(function($){$.assertEqual=(q)=>{};function J(q){}$.assertIs=J;function Q(q){throw Error()}$.assertNever=Q,$.arrayToEnum=(q)=>{let Y={};for(let G of q)Y[G]=G;return Y},$.getValidEnumValues=(q)=>{let Y=$.objectKeys(q).filter((W)=>typeof q[q[W]]!=="number"),G={};for(let W of Y)G[W]=q[W];return $.objectValues(G)},$.objectValues=(q)=>{return $.objectKeys(q).map(function(Y){return q[Y]})},$.objectKeys=typeof Object.keys==="function"?(q)=>Object.keys(q):(q)=>{let Y=[];for(let G in q)if(Object.prototype.hasOwnProperty.call(q,G))Y.push(G);return Y},$.find=(q,Y)=>{for(let G of q)if(Y(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(q)=>Number.isInteger(q):(q)=>typeof q==="number"&&Number.isFinite(q)&&Math.floor(q)===q;function X(q,Y=" | "){return q.map((G)=>typeof G==="string"?`'${G}'`:G).join(Y)}$.joinValues=X,$.jsonStringifyReplacer=(q,Y)=>{if(typeof Y==="bigint")return Y.toString();return Y}})(l||(l={}));var X4;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(X4||(X4={}));var P=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),g0=($)=>{switch(typeof $){case"undefined":return P.undefined;case"string":return P.string;case"number":return Number.isNaN($)?P.nan:P.number;case"boolean":return P.boolean;case"function":return P.function;case"bigint":return P.bigint;case"symbol":return P.symbol;case"object":if(Array.isArray($))return P.array;if($===null)return P.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return P.promise;if(typeof Map<"u"&&$ instanceof Map)return P.map;if(typeof Set<"u"&&$ instanceof Set)return P.set;if(typeof Date<"u"&&$ instanceof Date)return P.date;return P.object;default:return P.unknown}};var N=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"]),XX=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class W0 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(q){return q.message},Q={_errors:[]},X=(q)=>{for(let Y of q.issues)if(Y.code==="invalid_union")Y.unionErrors.map(X);else if(Y.code==="invalid_return_type")X(Y.returnTypeError);else if(Y.code==="invalid_arguments")X(Y.argumentsError);else if(Y.path.length===0)Q._errors.push(J(Y));else{let G=Q,W=0;while(W<Y.path.length){let z=Y.path[W];if(W!==Y.path.length-1)G[z]=G[z]||{_errors:[]};else G[z]=G[z]||{_errors:[]},G[z]._errors.push(J(Y));G=G[z],W++}}};return X(this),Q}static assert($){if(!($ instanceof W0))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($=(J)=>J.message){let J={},Q=[];for(let X of this.issues)if(X.path.length>0){let q=X.path[0];J[q]=J[q]||[],J[q].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}W0.create=($)=>{return new W0($)};var qX=($,J)=>{let Q;switch($.code){case N.invalid_type:if($.received===P.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case N.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case N.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case N.invalid_union:Q="Invalid input";break;case N.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case N.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case N.invalid_arguments:Q="Invalid function arguments";break;case N.invalid_return_type:Q="Invalid function return type";break;case N.invalid_date:Q="Invalid date";break;case N.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(Q=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")Q=`${Q} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)Q=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)Q=`Invalid input: must end with "${$.validation.endsWith}"`;else l.assertNever($.validation);else if($.validation!=="regex")Q=`Invalid ${$.validation}`;else Q="Invalid";break;case N.too_small:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")Q=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else Q="Invalid input";break;case N.too_big:if($.type==="array")Q=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")Q=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")Q=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")Q=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")Q=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else Q="Invalid input";break;case N.custom:Q="Invalid input";break;case N.invalid_intersection_types:Q="Intersection results could not be merged";break;case N.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case N.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},i0=qX;var T5=i0;function YX($){T5=$}function h$(){return T5}var N2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:q}=$,Y=[...Q,...q.path||[]],G={...q,path:Y};if(q.message!==void 0)return{...q,path:Y,message:q.message};let W="",z=X.filter((H)=>!!H).slice().reverse();for(let H of z)W=H(G,{data:J,defaultError:W}).message;return{...q,path:Y,message:W}},GX=[];function E($,J){let Q=h$(),X=N2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===i0?void 0:i0].filter((q)=>!!q)});$.common.issues.push(X)}class z0{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,J){let Q=[];for(let X of J){if(X.status==="aborted")return v;if(X.status==="dirty")$.dirty();Q.push(X.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,J){let Q=[];for(let X of J){let q=await X.key,Y=await X.value;Q.push({key:q,value:Y})}return z0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:q,value:Y}=X;if(q.status==="aborted")return v;if(Y.status==="aborted")return v;if(q.status==="dirty")$.dirty();if(Y.status==="dirty")$.dirty();if(q.value!=="__proto__"&&(typeof Y.value<"u"||X.alwaysSet))Q[q.value]=Y.value}return{status:$.value,value:Q}}}var v=Object.freeze({status:"aborted"}),L$=($)=>({status:"dirty",value:$}),U0=($)=>({status:"valid",value:$}),A6=($)=>$.status==="aborted",_6=($)=>$.status==="dirty",e0=($)=>$.status==="valid",g$=($)=>typeof Promise<"u"&&$ instanceof Promise;var f;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(f||(f={}));class S0{constructor($,J,Q,X){this._cachedPath=[],this.parent=$,this.data=J,this._path=Q,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 v5=($,J)=>{if(e0(J))return{success:!0,data:J.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 Q=new W0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:q}=$;if(J&&(Q||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:q};return{errorMap:(G,W)=>{let{message:z}=$;if(G.code==="invalid_enum_value")return{message:z??W.defaultError};if(typeof W.data>"u")return{message:z??X??W.defaultError};if(G.code!=="invalid_type")return{message:W.defaultError};return{message:z??Q??W.defaultError}},description:q}}class m{get description(){return this._def.description}_getType($){return g0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:g0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new z0,ctx:{common:$.parent.common,data:$.data,parsedType:g0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(g$(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let Q=this.safeParse($,J);if(Q.success)return Q.data;throw Q.error}safeParse($,J){let Q={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return v5(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return e0(Q)?{value:Q.value}:{issues:J.common.issues}}catch(Q){if(Q?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Q)=>e0(Q)?{value:Q.value}:{issues:J.common.issues})}async parseAsync($,J){let Q=await this.safeParseAsync($,J);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,J){let Q={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:g0($)},X=this._parse({data:$,path:Q.path,parent:Q}),q=await(g$(X)?X:Promise.resolve(X));return v5(Q,q)}refine($,J){let Q=(X)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(X);else return J};return this._refinement((X,q)=>{let Y=$(X),G=()=>q.addIssue({code:N.custom,...Q(X)});if(typeof Promise<"u"&&Y instanceof Promise)return Y.then((W)=>{if(!W)return G(),!1;else return!0});if(!Y)return G(),!1;else return!0})}refinement($,J){return this._refinement((Q,X)=>{if(!$(Q))return X.addIssue(typeof J==="function"?J(Q,X):J),!1;else return!0})}_refinement($){return new C0({schema:this,typeName:_.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:(J)=>this["~validate"](J)}}optional(){return E0.create(this,this._def)}nullable(){return r0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return b0.create(this)}promise(){return R$.create(this,this._def)}or($){return d$.create([this,$],this._def)}and($){return p$.create(this,$,this._def)}transform($){return new C0({...h(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new a$({...h(this._def),innerType:this,defaultValue:J,typeName:_.ZodDefault})}brand(){return new Z6({typeName:_.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new s$({...h(this._def),innerType:this,catchValue:J,typeName:_.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return P2.create(this,$)}readonly(){return o$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var WX=/^c[^\s-]{8,}$/i,zX=/^[0-9a-z]+$/,HX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,BX=/^[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,UX=/^[a-z0-9_-]{21}$/i,VX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,DX=/^[-+]?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)?)??$/,FX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,MX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",q4,OX=/^(?:(?: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])$/,KX=/^(?:(?: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])$/,jX=/^(([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]))$/,LX=/^(([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}=))?$/,AX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,y5="((\\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])))",_X=new RegExp(`^${y5}$`);function h5($){let J="[0-5]\\d";if($.precision)J=`${J}\\.\\d{${$.precision}}`;else if($.precision==null)J=`${J}(\\.\\d+)?`;let Q=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${J})${Q}`}function RX($){return new RegExp(`^${h5($)}$`)}function g5($){let J=`${y5}T${h5($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function ZX($,J){if((J==="v4"||!J)&&OX.test($))return!0;if((J==="v6"||!J)&&jX.test($))return!0;return!1}function wX($,J){if(!VX.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let X=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),q=JSON.parse(atob(X));if(typeof q!=="object"||q===null)return!1;if("typ"in q&&q?.typ!=="JWT")return!1;if(!q.alg)return!1;if(J&&q.alg!==J)return!1;return!0}catch{return!1}}function PX($,J){if((J==="v4"||!J)&&KX.test($))return!0;if((J==="v6"||!J)&&LX.test($))return!0;return!1}class P0 extends m{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==P.string){let q=this._getOrReturnCtx($);return E(q,{code:N.invalid_type,expected:P.string,received:q.parsedType}),v}let Q=new z0,X=void 0;for(let q of this._def.checks)if(q.kind==="min"){if($.data.length<q.value)X=this._getOrReturnCtx($,X),E(X,{code:N.too_small,minimum:q.value,type:"string",inclusive:!0,exact:!1,message:q.message}),Q.dirty()}else if(q.kind==="max"){if($.data.length>q.value)X=this._getOrReturnCtx($,X),E(X,{code:N.too_big,maximum:q.value,type:"string",inclusive:!0,exact:!1,message:q.message}),Q.dirty()}else if(q.kind==="length"){let Y=$.data.length>q.value,G=$.data.length<q.value;if(Y||G){if(X=this._getOrReturnCtx($,X),Y)E(X,{code:N.too_big,maximum:q.value,type:"string",inclusive:!0,exact:!0,message:q.message});else if(G)E(X,{code:N.too_small,minimum:q.value,type:"string",inclusive:!0,exact:!0,message:q.message});Q.dirty()}}else if(q.kind==="email"){if(!FX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"email",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="emoji"){if(!q4)q4=new RegExp(MX,"u");if(!q4.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"emoji",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="uuid"){if(!BX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"uuid",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="nanoid"){if(!UX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"nanoid",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="cuid"){if(!WX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="cuid2"){if(!zX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid2",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="ulid"){if(!HX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"ulid",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),E(X,{validation:"url",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="regex"){if(q.regex.lastIndex=0,!q.regex.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"regex",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="trim")$.data=$.data.trim();else if(q.kind==="includes"){if(!$.data.includes(q.value,q.position))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:{includes:q.value,position:q.position},message:q.message}),Q.dirty()}else if(q.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(q.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(q.kind==="startsWith"){if(!$.data.startsWith(q.value))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:{startsWith:q.value},message:q.message}),Q.dirty()}else if(q.kind==="endsWith"){if(!$.data.endsWith(q.value))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:{endsWith:q.value},message:q.message}),Q.dirty()}else if(q.kind==="datetime"){if(!g5(q).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:"datetime",message:q.message}),Q.dirty()}else if(q.kind==="date"){if(!_X.test($.data))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:"date",message:q.message}),Q.dirty()}else if(q.kind==="time"){if(!RX(q).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:N.invalid_string,validation:"time",message:q.message}),Q.dirty()}else if(q.kind==="duration"){if(!DX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"duration",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="ip"){if(!ZX($.data,q.version))X=this._getOrReturnCtx($,X),E(X,{validation:"ip",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="jwt"){if(!wX($.data,q.alg))X=this._getOrReturnCtx($,X),E(X,{validation:"jwt",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="cidr"){if(!PX($.data,q.version))X=this._getOrReturnCtx($,X),E(X,{validation:"cidr",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="base64"){if(!NX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64",code:N.invalid_string,message:q.message}),Q.dirty()}else if(q.kind==="base64url"){if(!AX.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64url",code:N.invalid_string,message:q.message}),Q.dirty()}else l.assertNever(q);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:N.invalid_string,...f.errToObj(Q)})}_addCheck($){return new P0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...f.errToObj($)})}url($){return this._addCheck({kind:"url",...f.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...f.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...f.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...f.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...f.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...f.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...f.errToObj($)})}base64($){return this._addCheck({kind:"base64",...f.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...f.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...f.errToObj($)})}ip($){return this._addCheck({kind:"ip",...f.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...f.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,...f.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,...f.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...f.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...f.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...f.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...f.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...f.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...f.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...f.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...f.errToObj(J)})}nonempty($){return this.min(1,f.errToObj($))}trim(){return new P0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new P0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new P0({...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 J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxLength(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}P0.create=($)=>{return new P0({checks:[],typeName:_.ZodString,coerce:$?.coerce??!1,...h($)})};function bX($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,q=Q>X?Q:X,Y=Number.parseInt($.toFixed(q).replace(".","")),G=Number.parseInt(J.toFixed(q).replace(".",""));return Y%G/10**q}class J$ extends m{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($)!==P.number){let q=this._getOrReturnCtx($);return E(q,{code:N.invalid_type,expected:P.number,received:q.parsedType}),v}let Q=void 0,X=new z0;for(let q of this._def.checks)if(q.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:N.invalid_type,expected:"integer",received:"float",message:q.message}),X.dirty()}else if(q.kind==="min"){if(q.inclusive?$.data<q.value:$.data<=q.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:N.too_small,minimum:q.value,type:"number",inclusive:q.inclusive,exact:!1,message:q.message}),X.dirty()}else if(q.kind==="max"){if(q.inclusive?$.data>q.value:$.data>=q.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:N.too_big,maximum:q.value,type:"number",inclusive:q.inclusive,exact:!1,message:q.message}),X.dirty()}else if(q.kind==="multipleOf"){if(bX($.data,q.value)!==0)Q=this._getOrReturnCtx($,Q),E(Q,{code:N.not_multiple_of,multipleOf:q.value,message:q.message}),X.dirty()}else if(q.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:N.not_finite,message:q.message}),X.dirty()}else l.assertNever(q);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,f.toString(J))}gt($,J){return this.setLimit("min",$,!1,f.toString(J))}lte($,J){return this.setLimit("max",$,!0,f.toString(J))}lt($,J){return this.setLimit("max",$,!1,f.toString(J))}setLimit($,J,Q,X){return new J$({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:f.toString(X)}]})}_addCheck($){return new J$({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:f.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:f.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:f.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:f.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:f.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:f.toString(J)})}finite($){return this._addCheck({kind:"finite",message:f.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:f.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:f.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&l.isInteger($.value))}get isFinite(){let $=null,J=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(J===null||Q.value>J)J=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(J)&&Number.isFinite($)}}J$.create=($)=>{return new J$({checks:[],typeName:_.ZodNumber,coerce:$?.coerce||!1,...h($)})};class Q$ extends m{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($)!==P.bigint)return this._getInvalidInput($);let Q=void 0,X=new z0;for(let q of this._def.checks)if(q.kind==="min"){if(q.inclusive?$.data<q.value:$.data<=q.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:N.too_small,type:"bigint",minimum:q.value,inclusive:q.inclusive,message:q.message}),X.dirty()}else if(q.kind==="max"){if(q.inclusive?$.data>q.value:$.data>=q.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:N.too_big,type:"bigint",maximum:q.value,inclusive:q.inclusive,message:q.message}),X.dirty()}else if(q.kind==="multipleOf"){if($.data%q.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),E(Q,{code:N.not_multiple_of,multipleOf:q.value,message:q.message}),X.dirty()}else l.assertNever(q);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return E(J,{code:N.invalid_type,expected:P.bigint,received:J.parsedType}),v}gte($,J){return this.setLimit("min",$,!0,f.toString(J))}gt($,J){return this.setLimit("min",$,!1,f.toString(J))}lte($,J){return this.setLimit("max",$,!0,f.toString(J))}lt($,J){return this.setLimit("max",$,!1,f.toString(J))}setLimit($,J,Q,X){return new Q$({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:f.toString(X)}]})}_addCheck($){return new Q$({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:f.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:f.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:f.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:f.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:f.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}Q$.create=($)=>{return new Q$({checks:[],typeName:_.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class u$ extends m{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==P.boolean){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.boolean,received:Q.parsedType}),v}return U0($.data)}}u$.create=($)=>{return new u$({typeName:_.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class N$ extends m{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==P.date){let q=this._getOrReturnCtx($);return E(q,{code:N.invalid_type,expected:P.date,received:q.parsedType}),v}if(Number.isNaN($.data.getTime())){let q=this._getOrReturnCtx($);return E(q,{code:N.invalid_date}),v}let Q=new z0,X=void 0;for(let q of this._def.checks)if(q.kind==="min"){if($.data.getTime()<q.value)X=this._getOrReturnCtx($,X),E(X,{code:N.too_small,message:q.message,inclusive:!0,exact:!1,minimum:q.value,type:"date"}),Q.dirty()}else if(q.kind==="max"){if($.data.getTime()>q.value)X=this._getOrReturnCtx($,X),E(X,{code:N.too_big,message:q.message,inclusive:!0,exact:!1,maximum:q.value,type:"date"}),Q.dirty()}else l.assertNever(q);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new N$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:f.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:f.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}N$.create=($)=>{return new N$({checks:[],coerce:$?.coerce||!1,typeName:_.ZodDate,...h($)})};class A2 extends m{_parse($){if(this._getType($)!==P.symbol){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.symbol,received:Q.parsedType}),v}return U0($.data)}}A2.create=($)=>{return new A2({typeName:_.ZodSymbol,...h($)})};class l$ extends m{_parse($){if(this._getType($)!==P.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.undefined,received:Q.parsedType}),v}return U0($.data)}}l$.create=($)=>{return new l$({typeName:_.ZodUndefined,...h($)})};class c$ extends m{_parse($){if(this._getType($)!==P.null){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.null,received:Q.parsedType}),v}return U0($.data)}}c$.create=($)=>{return new c$({typeName:_.ZodNull,...h($)})};class A$ extends m{constructor(){super(...arguments);this._any=!0}_parse($){return U0($.data)}}A$.create=($)=>{return new A$({typeName:_.ZodAny,...h($)})};class $$ extends m{constructor(){super(...arguments);this._unknown=!0}_parse($){return U0($.data)}}$$.create=($)=>{return new $$({typeName:_.ZodUnknown,...h($)})};class k0 extends m{_parse($){let J=this._getOrReturnCtx($);return E(J,{code:N.invalid_type,expected:P.never,received:J.parsedType}),v}}k0.create=($)=>{return new k0({typeName:_.ZodNever,...h($)})};class _2 extends m{_parse($){if(this._getType($)!==P.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.void,received:Q.parsedType}),v}return U0($.data)}}_2.create=($)=>{return new _2({typeName:_.ZodVoid,...h($)})};class b0 extends m{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==P.array)return E(J,{code:N.invalid_type,expected:P.array,received:J.parsedType}),v;if(X.exactLength!==null){let Y=J.data.length>X.exactLength.value,G=J.data.length<X.exactLength.value;if(Y||G)E(J,{code:Y?N.too_big:N.too_small,minimum:G?X.exactLength.value:void 0,maximum:Y?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),Q.dirty()}if(X.minLength!==null){if(J.data.length<X.minLength.value)E(J,{code:N.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),Q.dirty()}if(X.maxLength!==null){if(J.data.length>X.maxLength.value)E(J,{code:N.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),Q.dirty()}if(J.common.async)return Promise.all([...J.data].map((Y,G)=>{return X.type._parseAsync(new S0(J,Y,J.path,G))})).then((Y)=>{return z0.mergeArray(Q,Y)});let q=[...J.data].map((Y,G)=>{return X.type._parseSync(new S0(J,Y,J.path,G))});return z0.mergeArray(Q,q)}get element(){return this._def.type}min($,J){return new b0({...this._def,minLength:{value:$,message:f.toString(J)}})}max($,J){return new b0({...this._def,maxLength:{value:$,message:f.toString(J)}})}length($,J){return new b0({...this._def,exactLength:{value:$,message:f.toString(J)}})}nonempty($){return this.min(1,$)}}b0.create=($,J)=>{return new b0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...h(J)})};function k$($){if($ instanceof J0){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=E0.create(k$(X))}return new J0({...$._def,shape:()=>J})}else if($ instanceof b0)return new b0({...$._def,type:k$($.element)});else if($ instanceof E0)return E0.create(k$($.unwrap()));else if($ instanceof r0)return r0.create(k$($.unwrap()));else if($ instanceof m0)return m0.create($.items.map((J)=>k$(J)));else return $}class J0 extends m{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(),J=l.objectKeys($);return this._cached={shape:$,keys:J},this._cached}_parse($){if(this._getType($)!==P.object){let z=this._getOrReturnCtx($);return E(z,{code:N.invalid_type,expected:P.object,received:z.parsedType}),v}let{status:Q,ctx:X}=this._processInputParams($),{shape:q,keys:Y}=this._getCached(),G=[];if(!(this._def.catchall instanceof k0&&this._def.unknownKeys==="strip")){for(let z in X.data)if(!Y.includes(z))G.push(z)}let W=[];for(let z of Y){let H=q[z],B=X.data[z];W.push({key:{status:"valid",value:z},value:H._parse(new S0(X,B,X.path,z)),alwaysSet:z in X.data})}if(this._def.catchall instanceof k0){let z=this._def.unknownKeys;if(z==="passthrough")for(let H of G)W.push({key:{status:"valid",value:H},value:{status:"valid",value:X.data[H]}});else if(z==="strict"){if(G.length>0)E(X,{code:N.unrecognized_keys,keys:G}),Q.dirty()}else if(z==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let z=this._def.catchall;for(let H of G){let B=X.data[H];W.push({key:{status:"valid",value:H},value:z._parse(new S0(X,B,X.path,H)),alwaysSet:H in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let z=[];for(let H of W){let B=await H.key,U=await H.value;z.push({key:B,value:U,alwaysSet:H.alwaysSet})}return z}).then((z)=>{return z0.mergeObjectSync(Q,z)});else return z0.mergeObjectSync(Q,W)}get shape(){return this._def.shape()}strict($){return f.errToObj,new J0({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,Q)=>{let X=this._def.errorMap?.(J,Q).message??Q.defaultError;if(J.code==="unrecognized_keys")return{message:f.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new J0({...this._def,unknownKeys:"strip"})}passthrough(){return new J0({...this._def,unknownKeys:"passthrough"})}extend($){return new J0({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new J0({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:_.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new J0({...this._def,catchall:$})}pick($){let J={};for(let Q of l.objectKeys($))if($[Q]&&this.shape[Q])J[Q]=this.shape[Q];return new J0({...this._def,shape:()=>J})}omit($){let J={};for(let Q of l.objectKeys(this.shape))if(!$[Q])J[Q]=this.shape[Q];return new J0({...this._def,shape:()=>J})}deepPartial(){return k$(this)}partial($){let J={};for(let Q of l.objectKeys(this.shape)){let X=this.shape[Q];if($&&!$[Q])J[Q]=X;else J[Q]=X.optional()}return new J0({...this._def,shape:()=>J})}required($){let J={};for(let Q of l.objectKeys(this.shape))if($&&!$[Q])J[Q]=this.shape[Q];else{let q=this.shape[Q];while(q instanceof E0)q=q._def.innerType;J[Q]=q}return new J0({...this._def,shape:()=>J})}keyof(){return k5(l.objectKeys(this.shape))}}J0.create=($,J)=>{return new J0({shape:()=>$,unknownKeys:"strip",catchall:k0.create(),typeName:_.ZodObject,...h(J)})};J0.strictCreate=($,J)=>{return new J0({shape:()=>$,unknownKeys:"strict",catchall:k0.create(),typeName:_.ZodObject,...h(J)})};J0.lazycreate=($,J)=>{return new J0({shape:$,unknownKeys:"strip",catchall:k0.create(),typeName:_.ZodObject,...h(J)})};class d$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(q){for(let G of q)if(G.result.status==="valid")return G.result;for(let G of q)if(G.result.status==="dirty")return J.common.issues.push(...G.ctx.common.issues),G.result;let Y=q.map((G)=>new W0(G.ctx.common.issues));return E(J,{code:N.invalid_union,unionErrors:Y}),v}if(J.common.async)return Promise.all(Q.map(async(q)=>{let Y={...J,common:{...J.common,issues:[]},parent:null};return{result:await q._parseAsync({data:J.data,path:J.path,parent:Y}),ctx:Y}})).then(X);else{let q=void 0,Y=[];for(let W of Q){let z={...J,common:{...J.common,issues:[]},parent:null},H=W._parseSync({data:J.data,path:J.path,parent:z});if(H.status==="valid")return H;else if(H.status==="dirty"&&!q)q={result:H,ctx:z};if(z.common.issues.length)Y.push(z.common.issues)}if(q)return J.common.issues.push(...q.ctx.common.issues),q.result;let G=Y.map((W)=>new W0(W));return E(J,{code:N.invalid_union,unionErrors:G}),v}}get options(){return this._def.options}}d$.create=($,J)=>{return new d$({options:$,typeName:_.ZodUnion,...h(J)})};var n0=($)=>{if($ instanceof i$)return n0($.schema);else if($ instanceof C0)return n0($.innerType());else if($ instanceof n$)return[$.value];else if($ instanceof X$)return $.options;else if($ instanceof r$)return l.objectValues($.enum);else if($ instanceof a$)return n0($._def.innerType);else if($ instanceof l$)return[void 0];else if($ instanceof c$)return[null];else if($ instanceof E0)return[void 0,...n0($.unwrap())];else if($ instanceof r0)return[null,...n0($.unwrap())];else if($ instanceof Z6)return n0($.unwrap());else if($ instanceof o$)return n0($.unwrap());else if($ instanceof s$)return n0($._def.innerType);else return[]};class R6 extends m{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.object)return E(J,{code:N.invalid_type,expected:P.object,received:J.parsedType}),v;let Q=this.discriminator,X=J.data[Q],q=this.optionsMap.get(X);if(!q)return E(J,{code:N.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),v;if(J.common.async)return q._parseAsync({data:J.data,path:J.path,parent:J});else return q._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,Q){let X=new Map;for(let q of J){let Y=n0(q.shape[$]);if(!Y.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of Y){if(X.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);X.set(G,q)}}return new R6({typeName:_.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function Y4($,J){let Q=g0($),X=g0(J);if($===J)return{valid:!0,data:$};else if(Q===P.object&&X===P.object){let q=l.objectKeys(J),Y=l.objectKeys($).filter((W)=>q.indexOf(W)!==-1),G={...$,...J};for(let W of Y){let z=Y4($[W],J[W]);if(!z.valid)return{valid:!1};G[W]=z.data}return{valid:!0,data:G}}else if(Q===P.array&&X===P.array){if($.length!==J.length)return{valid:!1};let q=[];for(let Y=0;Y<$.length;Y++){let G=$[Y],W=J[Y],z=Y4(G,W);if(!z.valid)return{valid:!1};q.push(z.data)}return{valid:!0,data:q}}else if(Q===P.date&&X===P.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class p$ extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(q,Y)=>{if(A6(q)||A6(Y))return v;let G=Y4(q.value,Y.value);if(!G.valid)return E(Q,{code:N.invalid_intersection_types}),v;if(_6(q)||_6(Y))J.dirty();return{status:J.value,value:G.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([q,Y])=>X(q,Y));else return X(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}p$.create=($,J,Q)=>{return new p$({left:$,right:J,typeName:_.ZodIntersection,...h(Q)})};class m0 extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.array)return E(Q,{code:N.invalid_type,expected:P.array,received:Q.parsedType}),v;if(Q.data.length<this._def.items.length)return E(Q,{code:N.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),v;if(!this._def.rest&&Q.data.length>this._def.items.length)E(Q,{code:N.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let q=[...Q.data].map((Y,G)=>{let W=this._def.items[G]||this._def.rest;if(!W)return null;return W._parse(new S0(Q,Y,Q.path,G))}).filter((Y)=>!!Y);if(Q.common.async)return Promise.all(q).then((Y)=>{return z0.mergeArray(J,Y)});else return z0.mergeArray(J,q)}get items(){return this._def.items}rest($){return new m0({...this._def,rest:$})}}m0.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new m0({items:$,typeName:_.ZodTuple,rest:null,...h(J)})};class R2 extends m{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.object)return E(Q,{code:N.invalid_type,expected:P.object,received:Q.parsedType}),v;let X=[],q=this._def.keyType,Y=this._def.valueType;for(let G in Q.data)X.push({key:q._parse(new S0(Q,G,Q.path,G)),value:Y._parse(new S0(Q,Q.data[G],Q.path,G)),alwaysSet:G in Q.data});if(Q.common.async)return z0.mergeObjectAsync(J,X);else return z0.mergeObjectSync(J,X)}get element(){return this._def.valueType}static create($,J,Q){if(J instanceof m)return new R2({keyType:$,valueType:J,typeName:_.ZodRecord,...h(Q)});return new R2({keyType:P0.create(),valueType:$,typeName:_.ZodRecord,...h(J)})}}class Z2 extends m{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.map)return E(Q,{code:N.invalid_type,expected:P.map,received:Q.parsedType}),v;let X=this._def.keyType,q=this._def.valueType,Y=[...Q.data.entries()].map(([G,W],z)=>{return{key:X._parse(new S0(Q,G,Q.path,[z,"key"])),value:q._parse(new S0(Q,W,Q.path,[z,"value"]))}});if(Q.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let W of Y){let z=await W.key,H=await W.value;if(z.status==="aborted"||H.status==="aborted")return v;if(z.status==="dirty"||H.status==="dirty")J.dirty();G.set(z.value,H.value)}return{status:J.value,value:G}})}else{let G=new Map;for(let W of Y){let{key:z,value:H}=W;if(z.status==="aborted"||H.status==="aborted")return v;if(z.status==="dirty"||H.status==="dirty")J.dirty();G.set(z.value,H.value)}return{status:J.value,value:G}}}}Z2.create=($,J,Q)=>{return new Z2({valueType:J,keyType:$,typeName:_.ZodMap,...h(Q)})};class _$ extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==P.set)return E(Q,{code:N.invalid_type,expected:P.set,received:Q.parsedType}),v;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)E(Q,{code:N.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),J.dirty()}if(X.maxSize!==null){if(Q.data.size>X.maxSize.value)E(Q,{code:N.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let q=this._def.valueType;function Y(W){let z=new Set;for(let H of W){if(H.status==="aborted")return v;if(H.status==="dirty")J.dirty();z.add(H.value)}return{status:J.value,value:z}}let G=[...Q.data.values()].map((W,z)=>q._parse(new S0(Q,W,Q.path,z)));if(Q.common.async)return Promise.all(G).then((W)=>Y(W));else return Y(G)}min($,J){return new _$({...this._def,minSize:{value:$,message:f.toString(J)}})}max($,J){return new _$({...this._def,maxSize:{value:$,message:f.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}_$.create=($,J)=>{return new _$({valueType:$,minSize:null,maxSize:null,typeName:_.ZodSet,...h(J)})};class m$ extends m{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.function)return E(J,{code:N.invalid_type,expected:P.function,received:J.parsedType}),v;function Q(G,W){return N2({data:G,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,h$(),i0].filter((z)=>!!z),issueData:{code:N.invalid_arguments,argumentsError:W}})}function X(G,W){return N2({data:G,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,h$(),i0].filter((z)=>!!z),issueData:{code:N.invalid_return_type,returnTypeError:W}})}let q={errorMap:J.common.contextualErrorMap},Y=J.data;if(this._def.returns instanceof R$){let G=this;return U0(async function(...W){let z=new W0([]),H=await G._def.args.parseAsync(W,q).catch((V)=>{throw z.addIssue(Q(W,V)),z}),B=await Reflect.apply(Y,this,H);return await G._def.returns._def.type.parseAsync(B,q).catch((V)=>{throw z.addIssue(X(B,V)),z})})}else{let G=this;return U0(function(...W){let z=G._def.args.safeParse(W,q);if(!z.success)throw new W0([Q(W,z.error)]);let H=Reflect.apply(Y,this,z.data),B=G._def.returns.safeParse(H,q);if(!B.success)throw new W0([X(H,B.error)]);return B.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new m$({...this._def,args:m0.create($).rest($$.create())})}returns($){return new m$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new m$({args:$?$:m0.create([]).rest($$.create()),returns:J||$$.create(),typeName:_.ZodFunction,...h(Q)})}}class i$ extends m{get schema(){return this._def.getter()}_parse($){let{ctx:J}=this._processInputParams($);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}i$.create=($,J)=>{return new i$({getter:$,typeName:_.ZodLazy,...h(J)})};class n$ extends m{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return E(J,{received:J.data,code:N.invalid_literal,expected:this._def.value}),v}return{status:"valid",value:$.data}}get value(){return this._def.value}}n$.create=($,J)=>{return new n$({value:$,typeName:_.ZodLiteral,...h(J)})};function k5($,J){return new X$({values:$,typeName:_.ZodEnum,...h(J)})}class X$ extends m{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{expected:l.joinValues(Q),received:J.parsedType,code:N.invalid_type}),v}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{received:J.data,code:N.invalid_enum_value,options:Q}),v}return U0($.data)}get options(){return this._def.values}get enum(){let $={};for(let J of this._def.values)$[J]=J;return $}get Values(){let $={};for(let J of this._def.values)$[J]=J;return $}get Enum(){let $={};for(let J of this._def.values)$[J]=J;return $}extract($,J=this._def){return X$.create($,{...this._def,...J})}exclude($,J=this._def){return X$.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}X$.create=k5;class r$ extends m{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==P.string&&Q.parsedType!==P.number){let X=l.objectValues(J);return E(Q,{expected:l.joinValues(X),received:Q.parsedType,code:N.invalid_type}),v}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return E(Q,{received:Q.data,code:N.invalid_enum_value,options:X}),v}return U0($.data)}get enum(){return this._def.values}}r$.create=($,J)=>{return new r$({values:$,typeName:_.ZodNativeEnum,...h(J)})};class R$ extends m{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==P.promise&&J.common.async===!1)return E(J,{code:N.invalid_type,expected:P.promise,received:J.parsedType}),v;let Q=J.parsedType===P.promise?J.data:Promise.resolve(J.data);return U0(Q.then((X)=>{return this._def.type.parseAsync(X,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}R$.create=($,J)=>{return new R$({type:$,typeName:_.ZodPromise,...h(J)})};class C0 extends m{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,q={addIssue:(Y)=>{if(E(Q,Y),Y.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(q.addIssue=q.addIssue.bind(q),X.type==="preprocess"){let Y=X.transform(Q.data,q);if(Q.common.async)return Promise.resolve(Y).then(async(G)=>{if(J.value==="aborted")return v;let W=await this._def.schema._parseAsync({data:G,path:Q.path,parent:Q});if(W.status==="aborted")return v;if(W.status==="dirty")return L$(W.value);if(J.value==="dirty")return L$(W.value);return W});else{if(J.value==="aborted")return v;let G=this._def.schema._parseSync({data:Y,path:Q.path,parent:Q});if(G.status==="aborted")return v;if(G.status==="dirty")return L$(G.value);if(J.value==="dirty")return L$(G.value);return G}}if(X.type==="refinement"){let Y=(G)=>{let W=X.refinement(G,q);if(Q.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(Q.common.async===!1){let G=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(G.status==="aborted")return v;if(G.status==="dirty")J.dirty();return Y(G.value),{status:J.value,value:G.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(G.status==="aborted")return v;if(G.status==="dirty")J.dirty();return Y(G.value).then(()=>{return{status:J.value,value:G.value}})})}if(X.type==="transform")if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!e0(Y))return v;let G=X.transform(Y.value,q);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:G}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(!e0(Y))return v;return Promise.resolve(X.transform(Y.value,q)).then((G)=>({status:J.value,value:G}))});l.assertNever(X)}}C0.create=($,J,Q)=>{return new C0({schema:$,typeName:_.ZodEffects,effect:J,...h(Q)})};C0.createWithPreprocess=($,J,Q)=>{return new C0({schema:J,effect:{type:"preprocess",transform:$},typeName:_.ZodEffects,...h(Q)})};class E0 extends m{_parse($){if(this._getType($)===P.undefined)return U0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}E0.create=($,J)=>{return new E0({innerType:$,typeName:_.ZodOptional,...h(J)})};class r0 extends m{_parse($){if(this._getType($)===P.null)return U0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}r0.create=($,J)=>{return new r0({innerType:$,typeName:_.ZodNullable,...h(J)})};class a$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===P.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}a$.create=($,J)=>{return new a$({innerType:$,typeName:_.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class s$ extends m{_parse($){let{ctx:J}=this._processInputParams($),Q={...J,common:{...J.common,issues:[]}},X=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(g$(X))return X.then((q)=>{return{status:"valid",value:q.status==="valid"?q.value:this._def.catchValue({get error(){return new W0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new W0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}s$.create=($,J)=>{return new s$({innerType:$,typeName:_.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class w2 extends m{_parse($){if(this._getType($)!==P.nan){let Q=this._getOrReturnCtx($);return E(Q,{code:N.invalid_type,expected:P.nan,received:Q.parsedType}),v}return{status:"valid",value:$.data}}}w2.create=($)=>{return new w2({typeName:_.ZodNaN,...h($)})};var EX=Symbol("zod_brand");class Z6 extends m{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;return this._def.type._parse({data:Q,path:J.path,parent:J})}unwrap(){return this._def.type}}class P2 extends m{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let q=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(q.status==="aborted")return v;if(q.status==="dirty")return J.dirty(),L$(q.value);else return this._def.out._parseAsync({data:q.value,path:Q.path,parent:Q})})();else{let X=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(X.status==="aborted")return v;if(X.status==="dirty")return J.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:Q.path,parent:Q})}}static create($,J){return new P2({in:$,out:J,typeName:_.ZodPipeline})}}class o$ extends m{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(e0(X))X.value=Object.freeze(X.value);return X};return g$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}o$.create=($,J)=>{return new o$({innerType:$,typeName:_.ZodReadonly,...h(J)})};function x5($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function m5($,J={},Q){if($)return A$.create().superRefine((X,q)=>{let Y=$(X);if(Y instanceof Promise)return Y.then((G)=>{if(!G){let W=x5(J,X),z=W.fatal??Q??!0;q.addIssue({code:"custom",...W,fatal:z})}});if(!Y){let G=x5(J,X),W=G.fatal??Q??!0;q.addIssue({code:"custom",...G,fatal:W})}return});return A$.create()}var SX={object:J0.lazycreate},_;(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"})(_||(_={}));var CX=($,J={message:`Input not instance of ${$.name}`})=>m5((Q)=>Q instanceof $,J),u5=P0.create,l5=J$.create,fX=w2.create,IX=Q$.create,c5=u$.create,TX=N$.create,vX=A2.create,xX=l$.create,yX=c$.create,hX=A$.create,gX=$$.create,kX=k0.create,mX=_2.create,uX=b0.create,lX=J0.create,cX=J0.strictCreate,dX=d$.create,pX=R6.create,iX=p$.create,nX=m0.create,rX=R2.create,aX=Z2.create,sX=_$.create,oX=m$.create,tX=i$.create,eX=n$.create,$q=X$.create,Jq=r$.create,Qq=R$.create,Xq=C0.create,qq=E0.create,Yq=r0.create,Gq=C0.createWithPreprocess,Wq=P2.create,zq=()=>u5().optional(),Hq=()=>l5().optional(),Bq=()=>c5().optional(),Uq={string:($)=>P0.create({...$,coerce:!0}),number:($)=>J$.create({...$,coerce:!0}),boolean:($)=>u$.create({...$,coerce:!0}),bigint:($)=>Q$.create({...$,coerce:!0}),date:($)=>N$.create({...$,coerce:!0})};var Vq=v;var G4=K.object({bgProcessId:K.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function Dq($){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 d5($){let J=Date.now();return{alive:!1,status:"not_found",createdAt:J,lastUpdatedAt:J,description:`No background process found with id '${$}'.`}}var AK={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
436
436
 
437
437
  Use this tool when:
438
438
  - 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.
@@ -449,7 +449,7 @@ Use this tool when:
449
449
  - result: present when status is 'completed'
450
450
  - error: present when status is 'failed'
451
451
 
452
- 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:Q4,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async($,J)=>N6(null).execute($,J)};function N6($=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
452
+ 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:G4,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async($,J)=>w6(null).execute($,J)};function w6($=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
453
453
 
454
454
  Use this tool when:
455
455
  - 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.
@@ -466,7 +466,7 @@ Use this tool when:
466
466
  - result: present when status is 'completed'
467
467
  - error: present when status is 'failed'
468
468
 
469
- 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:Q4,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(J,Q)=>{let X=Date.now(),Y=Q4.parse(J),{bgProcessId:G}=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 q;try{q=$.getTask(G)}catch(z){return{success:!1,output:"",error:`failed to query background task: ${z.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(q){let z=Q.session_id;if(!z||q.parentSessionId!==z)return{success:!0,output:JSON.stringify(y7(G),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:G,status:"not_found",alive:!1}}}let W=q?GY(q):y7(G);if(W.alive)try{let z=await $.getSubSessionActivity?.(G);if(z)W.lastUpdatedAt=Math.max(W.lastUpdatedAt,z.updatedAt),W.messageCount=z.messageCount,W.subSessionUpdatedAt=z.updatedAt}catch{}return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:G,status:W.status,alive:W.alive}}}}}n();var N2=i("compact-session-tool"),g7=K.object({session_id:K.string().min(1,"session_id must not be empty").describe("The sub-session ID to compact (format: session_xxx or oc_xxx). Must be a sub-session previously created via delegate_task (the bgProcess notification reports its subSessionId).")});function qY($){return{status:"not_found",sessionId:$}}function WY($,J){let X=($.listTasks()??[]).find((Y)=>Y.subSessionId===J);if(X)return X;return $.getTask(J)}function zY($,J){if(!$||!J)return!1;return $.parentSessionId===J}function HY($){return $?.status==="running"||$?.status==="pending"}function X4($=null,J=null){return{name:"compact_session",description:`Compact (compress) a sub-agent session by summarizing its history into a checkpoint and archiving the old messages, so the session can be REUSED with delegate_task(sub_session_id=...) without exceeding the context threshold.
469
+ 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:G4,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(J,Q)=>{let X=Date.now(),q=G4.parse(J),{bgProcessId:Y}=q;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 G;try{G=$.getTask(Y)}catch(z){return{success:!1,output:"",error:`failed to query background task: ${z.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(G){let z=Q.session_id;if(!z||G.parentSessionId!==z)return{success:!0,output:JSON.stringify(d5(Y),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:Y,status:"not_found",alive:!1}}}let W=G?Dq(G):d5(Y);if(W.alive)try{let z=await $.getSubSessionActivity?.(Y);if(z)W.lastUpdatedAt=Math.max(W.lastUpdatedAt,z.updatedAt),W.messageCount=z.messageCount,W.subSessionUpdatedAt=z.updatedAt}catch{}return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:Y,status:W.status,alive:W.alive}}}}}i();var b2=d("compact-session-tool"),p5=K.object({session_id:K.string().min(1,"session_id must not be empty").describe("The sub-session ID to compact (format: session_xxx or oc_xxx). Must be a sub-session previously created via delegate_task (the bgProcess notification reports its subSessionId).")});function Fq($){return{status:"not_found",sessionId:$}}function Mq($,J){let X=($.listTasks()??[]).find((q)=>q.subSessionId===J);if(X)return X;return $.getTask(J)}function Oq($,J){if(!$||!J)return!1;return $.parentSessionId===J}function Kq($){return $?.status==="running"||$?.status==="pending"}function W4($=null,J=null){return{name:"compact_session",description:`Compact (compress) a sub-agent session by summarizing its history into a checkpoint and archiving the old messages, so the session can be REUSED with delegate_task(sub_session_id=...) without exceeding the context threshold.
470
470
 
471
471
  Use this tool when:
472
472
  - A delegated sub-agent returned 'Context threshold exceeded' (e.g. 125575/120000 tokens) and you want to continue the SAME sub-session instead of losing all its progress.
@@ -485,7 +485,7 @@ Guards:
485
485
  - You can only compact sub-sessions YOU delegated (ownership check).
486
486
  - A session whose background task is still running/pending cannot be compacted (stop_task it first to avoid corrupting live state).
487
487
 
488
- Only the default receptionist agent has this tool.`,parameters:g7,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["compact","session","delegate","checkpoint","context"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(Q,X)=>{let Y=Date.now(),q=g7.parse(Q).session_id;if(!$||!J)return{success:!1,output:"",error:"compact_session is not initialized: no BackgroundTaskManager or SessionComponent has been bound. TaskComponent should call createCompactSessionTool(manager, sessionComponent) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-Y}};let W=X.session_id;if(W&&q===W)return{success:!1,output:"",error:`Refusing to compact session '${q}': it is your OWN current session. Compacting it would destroy your own active context. Only sub-sessions you delegated can be compacted.`,metadata:{execution_time_ms:Date.now()-Y}};if(!W)return{success:!1,output:"",error:"compact_session requires a current session context (ctx.session_id) to verify ownership, but none was provided.",metadata:{execution_time_ms:Date.now()-Y}};let z=WY($,q);if(!z||!zY(z,W))return N2.warn("[compact_session] not_found (unknown or foreign sub-session)",{sessionId:q,currentSessionId:W}),{success:!0,output:JSON.stringify(qY(q),null,2),metadata:{execution_time_ms:Date.now()-Y,sessionId:q,status:"not_found"}};if(HY(z))return{success:!1,output:"",error:`Cannot compact session '${q}': its background task '${z.id}' is still ${z.status}. The sub-agent writes to this session every ReAct iteration; archiving messages now would corrupt live state. Run stop_task(task_id="${z.id}") first, then compact the session.`,metadata:{execution_time_ms:Date.now()-Y,sessionId:q,bgProcessId:z.id,taskStatus:z.status}};let H;try{H=await J.previewCompact(q)}catch(O){return{success:!1,output:"",error:`failed to preview compaction for session '${q}': ${O.message}`,metadata:{execution_time_ms:Date.now()-Y}}}if(!H||H.messageCountToCompact<3)return{success:!1,output:"",error:`Cannot compact session '${q}': minimum 3 compactable messages required (found ${H?.messageCountToCompact??0}).`,metadata:{execution_time_ms:Date.now()-Y,sessionId:q,messageCountToCompact:H?.messageCountToCompact??0}};let B="";try{B=await J.generateCompactHint(q)}catch(O){N2.warn("[compact_session] hint generation failed, continuing with empty hint",{sessionId:q,error:O.message}),B=""}let U;try{U=await J.compact(q,{scenarioHint:B})}catch(O){let F=O.message;return N2.error(`[compact_session] compact failed: ${F}`,{sessionId:q}),{success:!1,output:"",error:`compaction failed for session '${q}': ${F}`,metadata:{execution_time_ms:Date.now()-Y,sessionId:q}}}try{$.env?.pushEnvEvent?.({type:"context.compacted",metadata:{sessionId:q},payload:{checkpointId:U.checkpoint.id,messagesCompacted:U.deletedMessageCount,scenarioHintUsed:B.length>0,source:"compact_session_tool"}})}catch(O){N2.warn("[compact_session] failed to push context.compacted event",{sessionId:q,error:O.message})}let V={status:"compacted",sessionId:q,checkpointId:U.checkpoint.id,checkpointTitle:U.checkpoint.title,contentLength:U.checkpoint.content?.length??0,originalMessages:H.messageCountToCompact,deletedMessages:U.deletedMessageCount,remainingMessages:U.remainingMessageCount,hintUsed:B.length>0};return N2.info("[compact_session] session compacted",{sessionId:q,checkpointId:V.checkpointId,deletedMessages:V.deletedMessages,remainingMessages:V.remainingMessages}),{success:!0,output:JSON.stringify(V,null,2),metadata:{execution_time_ms:Date.now()-Y,sessionId:q,status:"compacted",checkpointId:V.checkpointId}}}}}var k7=X4(null,null);var m7=K.object({task_id:K.string().describe("The ID of the background task to stop")}),BY=`Stop a running background task.
488
+ Only the default receptionist agent has this tool.`,parameters:p5,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["compact","session","delegate","checkpoint","context"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(Q,X)=>{let q=Date.now(),G=p5.parse(Q).session_id;if(!$||!J)return{success:!1,output:"",error:"compact_session is not initialized: no BackgroundTaskManager or SessionComponent has been bound. TaskComponent should call createCompactSessionTool(manager, sessionComponent) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-q}};let W=X.session_id;if(W&&G===W)return{success:!1,output:"",error:`Refusing to compact session '${G}': it is your OWN current session. Compacting it would destroy your own active context. Only sub-sessions you delegated can be compacted.`,metadata:{execution_time_ms:Date.now()-q}};if(!W)return{success:!1,output:"",error:"compact_session requires a current session context (ctx.session_id) to verify ownership, but none was provided.",metadata:{execution_time_ms:Date.now()-q}};let z=Mq($,G);if(!z||!Oq(z,W))return b2.warn("[compact_session] not_found (unknown or foreign sub-session)",{sessionId:G,currentSessionId:W}),{success:!0,output:JSON.stringify(Fq(G),null,2),metadata:{execution_time_ms:Date.now()-q,sessionId:G,status:"not_found"}};if(Kq(z))return{success:!1,output:"",error:`Cannot compact session '${G}': its background task '${z.id}' is still ${z.status}. The sub-agent writes to this session every ReAct iteration; archiving messages now would corrupt live state. Run stop_task(task_id="${z.id}") first, then compact the session.`,metadata:{execution_time_ms:Date.now()-q,sessionId:G,bgProcessId:z.id,taskStatus:z.status}};let H;try{H=await J.previewCompact(G)}catch(O){return{success:!1,output:"",error:`failed to preview compaction for session '${G}': ${O.message}`,metadata:{execution_time_ms:Date.now()-q}}}if(!H||H.messageCountToCompact<3)return{success:!1,output:"",error:`Cannot compact session '${G}': minimum 3 compactable messages required (found ${H?.messageCountToCompact??0}).`,metadata:{execution_time_ms:Date.now()-q,sessionId:G,messageCountToCompact:H?.messageCountToCompact??0}};let B="";try{B=await J.generateCompactHint(G)}catch(O){b2.warn("[compact_session] hint generation failed, continuing with empty hint",{sessionId:G,error:O.message}),B=""}let U;try{U=await J.compact(G,{scenarioHint:B})}catch(O){let F=O.message;return b2.error(`[compact_session] compact failed: ${F}`,{sessionId:G}),{success:!1,output:"",error:`compaction failed for session '${G}': ${F}`,metadata:{execution_time_ms:Date.now()-q,sessionId:G}}}try{$.env?.pushEnvEvent?.({type:"context.compacted",metadata:{sessionId:G},payload:{checkpointId:U.checkpoint.id,messagesCompacted:U.deletedMessageCount,scenarioHintUsed:B.length>0,source:"compact_session_tool"}})}catch(O){b2.warn("[compact_session] failed to push context.compacted event",{sessionId:G,error:O.message})}let V={status:"compacted",sessionId:G,checkpointId:U.checkpoint.id,checkpointTitle:U.checkpoint.title,contentLength:U.checkpoint.content?.length??0,originalMessages:H.messageCountToCompact,deletedMessages:U.deletedMessageCount,remainingMessages:U.remainingMessageCount,hintUsed:B.length>0};return b2.info("[compact_session] session compacted",{sessionId:G,checkpointId:V.checkpointId,deletedMessages:V.deletedMessages,remainingMessages:V.remainingMessages}),{success:!0,output:JSON.stringify(V,null,2),metadata:{execution_time_ms:Date.now()-q,sessionId:G,status:"compacted",checkpointId:V.checkpointId}}}}}var i5=W4(null,null);var n5=K.object({task_id:K.string().describe("The ID of the background task to stop")}),jq=`Stop a running background task.
489
489
 
490
490
  Use this tool to stop a background task that is currently running. This is useful when:
491
491
  - The user wants to cancel a long-running task
@@ -495,11 +495,11 @@ Use this tool to stop a background task that is currently running. This is usefu
495
495
  When stopped, the task will be terminated immediately and you will receive a confirmation.
496
496
 
497
497
  Parameters:
498
- - task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function UY($){let J=Math.floor($/1000),Q=Math.floor(J/60),X=Math.floor(Q/60);if(X>0)return`${X}h ${Q%60}m ${J%60}s`;else if(Q>0)return`${Q}m ${J%60}s`;else return`${J}s`}function u7($){return{name:"stop_task",description:BY,parameters:m7,execute:async(J,Q)=>{let X=Date.now(),Y=m7.parse(J),{task_id:G}=Y,q=await $.stopTask(G);if(q.success){let W=q.task,z=W.startedAt?Date.now()-W.startedAt:Date.now()-W.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${G}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Status: ${W.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${UY(z)}`,"",q.message].join(`
499
- `),metadata:{execution_time_ms:Date.now()-X,task_id:G,previous_status:W.status}}}else{let W=q.task,z;if(W)z=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${G}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Current Status: ${W.status}`,"",q.message].join(`
500
- `);else z=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${G}`,"",q.message].join(`
501
- `);return{success:!1,output:z,error:q.message,metadata:{execution_time_ms:Date.now()-X,task_id:G}}}}}}import{AsyncLocalStorage as VY}from"async_hooks";n();var _6=i("process-tree-killer");function p7(){return e("child_process")}var l7;function DY($,J,Q){if(l7)return l7($,J,Q);return p7().spawn($,J,Q)}var c7;function FY($,J,Q){if(c7)return c7($,J,Q);let X=p7();if(typeof X.spawnSync!=="function")return;return X.spawnSync($,J,Q)}var MY;function OY(){return MY??process.platform}function KY($){try{return process.kill($,0),!0}catch(J){if(J.code==="ESRCH")return!1;return!0}}function RY($){try{let J=FY("tasklist",["/fi",`PID eq ${$}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!J)return!0;return J.stdout.toString().includes(String($))}catch{return!0}}function LY($){return new Promise((J)=>setTimeout(J,$))}async function jY($,J){if(!Number.isInteger($)||$<=0)throw Error(`Invalid PID: ${$} (must be a positive integer)`);let Q=OY(),X=J?.signal??"SIGKILL",Y=J?.retry??3,G=J?.retryDelayMs??500;_6.info(`[bg-process:kill-begin] pid=${$} signal=${X} retry=${Y} delayMs=${G}`);for(let q=1;q<=Y;q++){let W=Q==="win32"?NY($):_Y($,X,Q);if(await LY(G),!(Q==="win32"?RY($):KY($)))return _6.info(`[bg-process:kill-done] pid=${$} attempts=${q} stillAlive=false`),{pid:$,platform:Q,signal:W.signal,success:!0,attempts:q,stillAlive:!1};if(q<Y)_6.warn(`[bg-process:kill-retry] pid=${$} attempt=${q}/${Y}`)}return _6.error(`[bg-process:kill-failed] pid=${$} attempts=${Y} stillAlive=true`),{pid:$,platform:Q,signal:Q==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function NY($){try{return DY("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 _Y($,J,Q){try{return process.kill(-$,J),{pid:$,platform:Q,signal:J,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:$,platform:Q,signal:J,success:!0};return{pid:$,platform:Q,signal:J,success:!1}}}n();var Y4=i("task:process-registry");class G4{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);Y4.info(`[bg-process:killAll-begin] count=${$.length} pids=[${$.join(",")}]`);for(let J of $)try{let Q=await jY(J,{retry:3,retryDelayMs:500});if(Q.stillAlive)Y4.error(`\u8FDB\u7A0B PID ${J} \u7ECF\u8FC7 ${Q.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(J)}catch{}Y4.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var AY=new VY;function d7($,J){return AY.run($,J)}function ZY(){if(A6!==void 0)return A6;let $=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return A6=$==="1"||$==="true"||$==="yes",A6}var A6;var wY=()=>{};function PY($){let J=()=>({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(Q,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let W=Y.value,z=$?.name||String(X);return Y.value=B0(W,z,J()),Y}let G=Q,q=X||{};if(typeof G==="function"){let W=$?.name||(q?.name?String(q.name):"anonymous");return B0(G,W,J())}return G}}function u($,J){return PY({name:$,...J})}function B0($,J,Q){let X={recordParams:Q?.recordParams??!0,recordResult:Q?.recordResult??!0,recordResultToDb:Q?.recordResultToDb??!1,logResult:Q?.logResult,recordError:Q?.recordError??!0,log:Q?.log??!1,maxLogSize:Q?.maxLogSize,paramFilter:Q?.paramFilter,resultFilter:Q?.resultFilter,flattenParamFilter:Q?.flattenParamFilter??!1,errorIf:Q?.errorIf},Y=X.log,G=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let F=a9();return F!==void 0?F:500},q=(F)=>{if(F===void 0)return;if(F===null)return null;let D=G(),M;try{M=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(R){M=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}if(D>0&&M.length>D)return M.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(M)}catch{return M}},W=(F)=>{if(F===void 0)return"undefined";if(F===null)return"null";let D=G(),M;try{M=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(R){M=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}return D>0&&M.length>D?M.slice(0,D)+" [TRUNCATED]":M},z=(F)=>{if(F===void 0)return;if(F===null)return null;if(typeof F==="string")return F;try{return JSON.parse(JSON.stringify(F))}catch(D){return`[Object with circular reference: ${D instanceof Error?D.message:String(D)}]`}},H="[TRACE]",B=(F)=>{try{return F()}catch(D){try{i("traced:"+J).warn(`[trace] filter threw, ignoring: ${D instanceof Error?D.message:String(D)}`)}catch{}return}},U=(F,D)=>{if(X.recordResultToDb===!0)return{value:F,store:!0};if(ZY())return{value:F,store:!0};if(X.resultFilter){let M=D?.ran?D.value:B(()=>X.resultFilter(F));if(M&&typeof M==="object"&&!Array.isArray(M))return{value:M,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:F,store:!0}},V=()=>{let F=Error.stackTraceLimit;Error.stackTraceLimit=15;let D=Error();Error.captureStackTrace(D,V);let M=D.stack?.split(`
502
- `)||[];Error.stackTraceLimit=F;for(let R=1;R<M.length;R++){let L=M[R];if(L.includes("decorator.ts")||L.includes("decorator.js")||L.includes("logFn")||L.includes("getCallerLocation"))continue;let N=L.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||L.match(/at\s+(.+):(\d+):\d+/);if(N){let Z=N[1];if(!Z||Z==="native")continue;return`${r9(Z)}:${N[2]}`}}return""},O=(F,D,M)=>{if(!Y)return;let R=i("traced:"+J),N=`[TRACE] ${F==="enter"?">>>":F==="quit"?"<<<":"!!!"} ${J}`,Z=M||V(),b=(w,f)=>{if(f!==void 0)R.info(`${N} ${w}: ${W(f)}`,{callerLocation:Z});else R.info(`${N} ${w}`,{callerLocation:Z})};if(F==="enter")b("enter",D);else if(F==="quit")b("quit",X.logResult??X.recordResult?D:void 0);else b("error",D)};return function(...F){let D=D2().getTracer("roy-tracer"),M={};if(X.recordParams!==!1)if(X.paramFilter){let N=B(()=>X.paramFilter(F));if(M.params=z(N),X.flattenParamFilter&&N&&typeof N==="object"&&!Array.isArray(N)){for(let[Z,b]of Object.entries(N))if(!(Z in M))M[Z]=z(b)}}else M.params=z(F);let R=V(),L;try{L=D.startSpan(J,{attributes:M})}catch{}O("enter",F,R);try{let N=$.call(this,...F);if(N&&typeof N==="object"&&typeof N.then==="function")return N.then((Z)=>{if(L){let b=X.resultFilter!==void 0,w=X.resultFilter?B(()=>X.resultFilter(Z)):void 0;if(w&&typeof w==="object"&&!Array.isArray(w))for(let[S,x]of Object.entries(w))L.setAttribute(S,z(x));let f=U(Z,{ran:b,value:w});if(f.store)L.setAttribute("result",JSON.stringify(z(f.value)));let A=X.errorIf?B(()=>X.errorIf(Z)):void 0;if(A){let S=A instanceof Error?A:Error(String(A));L.setAttribute("error",S.message),L.end(void 0,S)}else L.end(f.store?f.value:void 0)}return O("quit",X.logResult??X.recordResult?Z:void 0,R),Z},(Z)=>{if(L)L.setAttribute("error",String(Z)),L.end(void 0,Z instanceof Error?Z:Error(String(Z)));throw O("error",Z.message,R),Z});if(L){let Z=X.resultFilter!==void 0,b=X.resultFilter?B(()=>X.resultFilter(N)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[A,S]of Object.entries(b))L.setAttribute(A,z(S));let w=U(N,{ran:Z,value:b});if(w.store)L.setAttribute("result",JSON.stringify(z(w.value)));let f=X.errorIf?B(()=>X.errorIf(N)):void 0;if(f){let A=f instanceof Error?f:Error(String(f));L.setAttribute("error",A.message),L.end(void 0,A)}else L.end(w.store?w.value:void 0)}return O("quit",X.logResult??X.recordResult?N:void 0,R),N}catch(N){if(L)L.setAttribute("error",String(N)),L.end(void 0,N instanceof Error?N:Error(String(N)));throw O("error",N.message,R),N}}}var V0=a(()=>{t9(),n(),wY()});import{randomUUID as bY}from"crypto";V0();function EY(){if(typeof Bun<"u"){let{Database:$}=e("bun:sqlite");return $}else return e("better-sqlite3")}function SY($){let Q=new(EY())($);if(typeof Q.run!=="function")Q.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return Q}class q4{db;insertStmt;getByIdStmt;recentStmt;constructor($){this.db=SY($.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 (
498
+ - task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function Lq($){let J=Math.floor($/1000),Q=Math.floor(J/60),X=Math.floor(Q/60);if(X>0)return`${X}h ${Q%60}m ${J%60}s`;else if(Q>0)return`${Q}m ${J%60}s`;else return`${J}s`}function r5($){return{name:"stop_task",description:jq,parameters:n5,execute:async(J,Q)=>{let X=Date.now(),q=n5.parse(J),{task_id:Y}=q,G=await $.stopTask(Y);if(G.success){let W=G.task,z=W.startedAt?Date.now()-W.startedAt:Date.now()-W.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${Y}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Status: ${W.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${Lq(z)}`,"",G.message].join(`
499
+ `),metadata:{execution_time_ms:Date.now()-X,task_id:Y,previous_status:W.status}}}else{let W=G.task,z;if(W)z=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${Y}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Current Status: ${W.status}`,"",G.message].join(`
500
+ `);else z=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${Y}`,"",G.message].join(`
501
+ `);return{success:!1,output:z,error:G.message,metadata:{execution_time_ms:Date.now()-X,task_id:Y}}}}}}import{AsyncLocalStorage as Nq}from"async_hooks";i();var P6=d("process-tree-killer");function o5(){return $0("child_process")}var a5;function Aq($,J,Q){if(a5)return a5($,J,Q);return o5().spawn($,J,Q)}var s5;function _q($,J,Q){if(s5)return s5($,J,Q);let X=o5();if(typeof X.spawnSync!=="function")return;return X.spawnSync($,J,Q)}var Rq;function Zq(){return Rq??process.platform}function wq($){try{return process.kill($,0),!0}catch(J){if(J.code==="ESRCH")return!1;return!0}}function Pq($){try{let J=_q("tasklist",["/fi",`PID eq ${$}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!J)return!0;return J.stdout.toString().includes(String($))}catch{return!0}}function bq($){return new Promise((J)=>setTimeout(J,$))}async function Eq($,J){if(!Number.isInteger($)||$<=0)throw Error(`Invalid PID: ${$} (must be a positive integer)`);let Q=Zq(),X=J?.signal??"SIGKILL",q=J?.retry??3,Y=J?.retryDelayMs??500;P6.info(`[bg-process:kill-begin] pid=${$} signal=${X} retry=${q} delayMs=${Y}`);for(let G=1;G<=q;G++){let W=Q==="win32"?Sq($):Cq($,X,Q);if(await bq(Y),!(Q==="win32"?Pq($):wq($)))return P6.info(`[bg-process:kill-done] pid=${$} attempts=${G} stillAlive=false`),{pid:$,platform:Q,signal:W.signal,success:!0,attempts:G,stillAlive:!1};if(G<q)P6.warn(`[bg-process:kill-retry] pid=${$} attempt=${G}/${q}`)}return P6.error(`[bg-process:kill-failed] pid=${$} attempts=${q} stillAlive=true`),{pid:$,platform:Q,signal:Q==="win32"?"taskkill /f /t":X,success:!1,attempts:q,stillAlive:!0}}function Sq($){try{return Aq("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 Cq($,J,Q){try{return process.kill(-$,J),{pid:$,platform:Q,signal:J,success:!0}}catch(X){let q=X.code;if(q==="ESRCH"||q==="EPERM")return{pid:$,platform:Q,signal:J,success:!0};return{pid:$,platform:Q,signal:J,success:!1}}}i();var z4=d("task:process-registry");class H4{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);z4.info(`[bg-process:killAll-begin] count=${$.length} pids=[${$.join(",")}]`);for(let J of $)try{let Q=await Eq(J,{retry:3,retryDelayMs:500});if(Q.stillAlive)z4.error(`\u8FDB\u7A0B PID ${J} \u7ECF\u8FC7 ${Q.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(J)}catch{}z4.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var fq=new Nq;function t5($,J){return fq.run($,J)}function Iq(){if(b6!==void 0)return b6;let $=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return b6=$==="1"||$==="true"||$==="yes",b6}var b6;var Tq=()=>{};function vq($){let J=()=>({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(Q,X,q){if(q!==void 0&&q!==null&&typeof q==="object"&&"value"in q){let W=q.value,z=$?.name||String(X);return q.value=H0(W,z,J()),q}let Y=Q,G=X||{};if(typeof Y==="function"){let W=$?.name||(G?.name?String(G.name):"anonymous");return H0(Y,W,J())}return Y}}function u($,J){return vq({name:$,...J})}function H0($,J,Q){let X={recordParams:Q?.recordParams??!0,recordResult:Q?.recordResult??!0,recordResultToDb:Q?.recordResultToDb??!1,logResult:Q?.logResult,recordError:Q?.recordError??!0,log:Q?.log??!1,maxLogSize:Q?.maxLogSize,paramFilter:Q?.paramFilter,resultFilter:Q?.resultFilter,flattenParamFilter:Q?.flattenParamFilter??!1,errorIf:Q?.errorIf},q=X.log,Y=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let F=e9();return F!==void 0?F:500},G=(F)=>{if(F===void 0)return;if(F===null)return null;let D=Y(),M;try{M=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(j){M=`[Object with circular reference: ${j instanceof Error?j.message:String(j)}]`}if(D>0&&M.length>D)return M.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(M)}catch{return M}},W=(F)=>{if(F===void 0)return"undefined";if(F===null)return"null";let D=Y(),M;try{M=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(j){M=`[Object with circular reference: ${j instanceof Error?j.message:String(j)}]`}return D>0&&M.length>D?M.slice(0,D)+" [TRUNCATED]":M},z=(F)=>{if(F===void 0)return;if(F===null)return null;if(typeof F==="string")return F;try{return JSON.parse(JSON.stringify(F))}catch(D){return`[Object with circular reference: ${D instanceof Error?D.message:String(D)}]`}},H="[TRACE]",B=(F)=>{try{return F()}catch(D){try{d("traced:"+J).warn(`[trace] filter threw, ignoring: ${D instanceof Error?D.message:String(D)}`)}catch{}return}},U=(F,D)=>{if(X.recordResultToDb===!0)return{value:F,store:!0};if(Iq())return{value:F,store:!0};if(X.resultFilter){let M=D?.ran?D.value:B(()=>X.resultFilter(F));if(M&&typeof M==="object"&&!Array.isArray(M))return{value:M,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:F,store:!0}},V=()=>{let F=Error.stackTraceLimit;Error.stackTraceLimit=15;let D=Error();Error.captureStackTrace(D,V);let M=D.stack?.split(`
502
+ `)||[];Error.stackTraceLimit=F;for(let j=1;j<M.length;j++){let L=M[j];if(L.includes("decorator.ts")||L.includes("decorator.js")||L.includes("logFn")||L.includes("getCallerLocation"))continue;let A=L.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||L.match(/at\s+(.+):(\d+):\d+/);if(A){let R=A[1];if(!R||R==="native")continue;return`${t9(R)}:${A[2]}`}}return""},O=(F,D,M)=>{if(!q)return;let j=d("traced:"+J),A=`[TRACE] ${F==="enter"?">>>":F==="quit"?"<<<":"!!!"} ${J}`,R=M||V(),b=(w,T)=>{if(T!==void 0)j.info(`${A} ${w}: ${W(T)}`,{callerLocation:R});else j.info(`${A} ${w}`,{callerLocation:R})};if(F==="enter")b("enter",D);else if(F==="quit")b("quit",X.logResult??X.recordResult?D:void 0);else b("error",D)};return function(...F){let D=L2().getTracer("roy-tracer"),M={};if(X.recordParams!==!1)if(X.paramFilter){let A=B(()=>X.paramFilter(F));if(M.params=z(A),X.flattenParamFilter&&A&&typeof A==="object"&&!Array.isArray(A)){for(let[R,b]of Object.entries(A))if(!(R in M))M[R]=z(b)}}else M.params=z(F);let j=V(),L;try{L=D.startSpan(J,{attributes:M})}catch{}O("enter",F,j);try{let A=$.call(this,...F);if(A&&typeof A==="object"&&typeof A.then==="function")return A.then((R)=>{if(L){let b=X.resultFilter!==void 0,w=X.resultFilter?B(()=>X.resultFilter(R)):void 0;if(w&&typeof w==="object"&&!Array.isArray(w))for(let[I,y]of Object.entries(w))L.setAttribute(I,z(y));let T=U(R,{ran:b,value:w});if(T.store)L.setAttribute("result",JSON.stringify(z(T.value)));let Z=X.errorIf?B(()=>X.errorIf(R)):void 0;if(Z){let I=Z instanceof Error?Z:Error(String(Z));L.setAttribute("error",I.message),L.end(void 0,I)}else L.end(T.store?T.value:void 0)}return O("quit",X.logResult??X.recordResult?R:void 0,j),R},(R)=>{if(L)L.setAttribute("error",String(R)),L.end(void 0,R instanceof Error?R:Error(String(R)));throw O("error",R.message,j),R});if(L){let R=X.resultFilter!==void 0,b=X.resultFilter?B(()=>X.resultFilter(A)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[Z,I]of Object.entries(b))L.setAttribute(Z,z(I));let w=U(A,{ran:R,value:b});if(w.store)L.setAttribute("result",JSON.stringify(z(w.value)));let T=X.errorIf?B(()=>X.errorIf(A)):void 0;if(T){let Z=T instanceof Error?T:Error(String(T));L.setAttribute("error",Z.message),L.end(void 0,Z)}else L.end(w.store?w.value:void 0)}return O("quit",X.logResult??X.recordResult?A:void 0,j),A}catch(A){if(L)L.setAttribute("error",String(A)),L.end(void 0,A instanceof Error?A:Error(String(A)));throw O("error",A.message,j),A}}}var D0=s(()=>{Q4(),i(),Tq()});import{randomUUID as xq}from"crypto";D0();function yq(){if(typeof Bun<"u"){let{Database:$}=$0("bun:sqlite");return $}else return $0("better-sqlite3")}function hq($){let Q=new(yq())($);if(typeof Q.run!=="function")Q.run=function(X,...q){if(q.length>0)return this.prepare(X).run(...q);else return this.exec(X)};return Q}class B4{db;insertStmt;getByIdStmt;recentStmt;constructor($){this.db=hq($.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 (
503
503
  event_id TEXT PRIMARY KEY,
504
504
  es_type TEXT NOT NULL,
505
505
  sender_id TEXT NOT NULL,
@@ -514,7 +514,7 @@ Parameters:
514
514
  FROM event_store
515
515
  WHERE es_type = ? AND sender_id = ?
516
516
  ORDER BY created_at DESC
517
- LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${bY()}`,X=Date.now(),Y=JSON.stringify($.metadata??{}),G=$.rawEvent===void 0?null:CY($.rawEvent);return this.insertStmt.run(Q,J,$.senderId,$.text??null,Y,G,X),Q}async getEventById($){let J=this.getByIdStmt.get($);if(!J)return null;return i7(J)}async getRecentEvents($,J,Q){return this.recentStmt.all($,J,Q).map((Y)=>i7(Y))}close(){this.db.close()}}k([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],q4.prototype,"insertTriggerEvent",null);k([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],q4.prototype,"getEventById",null);function i7($){let J;try{J=$.metadata?JSON.parse($.metadata):{}}catch{J={}}let Q;if($.raw_event)try{Q=JSON.parse($.raw_event)}catch{Q=null}else Q=null;return{eventId:$.event_id,esType:$.es_type,senderId:$.sender_id,text:$.text??null,metadata:J,rawEvent:Q,createdAt:typeof $.created_at==="bigint"?Number($.created_at):$.created_at}}function CY($){let J=new WeakSet;try{return JSON.stringify($,(Q,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(J.has(X))return"[Circular]";J.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch{return"{}"}}var fY=null;function n7(){return fY}var n$="\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536",$$="TASK_COMPLETION_HINT",r$="\u6838\u5B9E\u4E49\u52A1";var p0="\u5DF2\u5B8C\u6210",R$="\u5DF2\u53D6\u6D88",_2="\u4EA4\u4ED8\u7269\u5DF2\u8BB0\u5F55",L$="\u5DF2\u5F52\u6863",r7="\u5DF2\u91CD\u65B0\u6253\u5F00",x0="\u5F85\u9A8C\u8BC1",a7=[p0,R$,L$],Z6=["cancelled","archived"];var IY="### Task Lifecycle (7 steps, 0-6)\n\n> Tasks are the **first-class citizen**. Follow this lifecycle for every task:\n\n0. CHECK TASK CONTEXT OR SEARCH\n - If `[\u5F53\u524D Task #N]` is in the context \u2192 use `task_get #N` directly, skip searching.\n - Otherwise use `task_list` / `task_search` to find related tasks.\n - If found \u2192 reuse, extend, and update (see the reuse rules in step 1).\n If not found \u2192 proceed to step 1.\n - **Orient before creating**: read the existing tree with\n `task_tree(depth=1)` (`depth=2` for bigger trees) and decide whether the\n work belongs to an existing root (attach via `parent_task_id`) or is\n genuinely new. Keep **root tasks \u2264 10**; prefer attaching to an existing\n thematic root over spawning a new root. Never hardcode ids \u2014 read them\n from `task_tree`.\n\n1. CREATE or REUSE\n - No existing task \u2192 create a new one with title, description, goals.\n - Existing task \u2192 reuse via `task_get`, then `task_update`:\n * Append new context to description and goals (preserve the old content)\n * Add / extend `goals_and_expected_deliverables`\n * Create an operation record documenting the continuation\n * Set priority and due date if any\n * If the original task was completed \u2192 reset status to `active`\n and reset progress to a reasonable value\n\n2. GATHER CONTEXT (never skip)\n - Read description, goals, current_status\n - Check `parent_task_id` for sub-tasks\n - Read the operation history: `task_operation_list` (~20 recent records)\n - Review recent operations for history and decisions\n - Working without context risks: outdated goals, missed decisions,\n duplicated work, misalignment with the parent task\n\n3. EXECUTE\n - Use the available tools, skills and workflows to satisfy the task\n description and goals.\n - Long-running work: for work longer than 5 minutes, record a milestone\n with `task_operation_create` as you go, so the user can see progress.\n - Several independent sub-tasks may run in parallel (background `bash &`\n or parallel ReAct steps).\n - **\u8FB9\u5E72\u8FB9\u8BB0** \u2014 milestones are recorded **while working**;\n **\u7981\u6B62\u4E8B\u540E\u6279\u91CF\u8865**\uFF08do not defer them to one batch at the end\uFF09.\n - Note: `task_create` / `task_update` already create operation records\n automatically \u2014 do not create duplicates by hand.\n\n4. TRACK\n - Update progress (0-100%) as the work advances\n - Update status: todo \u2192 active\n - Record `current_status` with human-readable progress\n - \u26A0\uFE0F **\u4E0D\u8981**\u628A status \u76F4\u63A5\u7F6E\u4E3A `completed` \u6216 `to_validate` \u2014\u2014\n \u7EC8\u6001\u7531\u9A8C\u6536\u65B9\u843D\u3001\u5F85\u9A8C\u8BC1\u7531 `task_pre_complete` \u63D0\u4EA4\uFF08\u89C1\u6B65\u9AA4 6\uFF09\n\n5. RECORD \u2014 operation records (see Operation Discipline below)\n\n6. COMPLETE \u2014 \u6536\u5C3E\u5206\u4E24\u79CD\u89D2\u8272\uFF08Task #5007/#5073\uFF0C\u9A8C\u6536\u6743\u5206\u79BB\uFF09\n - **\u6267\u884C\u65B9\uFF08roy sub-agent\uFF09**\uFF1A\u8FDB\u5EA6\u8FBE\u5230\u4F60\u5224\u65AD\u7684 100% \u21D2\n `task_pre_complete` **\u63D0\u4EA4\u5F85\u9A8C\u8BC1**\uFF08`deliverable_storage_path`\n \u4F20\u4EA4\u4ED8\u7269\u5730\u5740\uFF1Bstatus \u2192 to_validate\uFF0C\u5E76\u89E6\u53D1\u4E00\u6B21 goal \u68C0\u67E5\u81EA\u67E5\uFF09\n + \u6700\u540E\u4E00\u6761 `task_operation_create` \u21D2 **\u7ED3\u675F\u5E76\u8FD4\u56DE\u7ED3\u679C**\u3002\n \u274C **\u4E0D\u8981\u8C03\u7528 `task_complete`**\uFF08\u4F60\u65E0\u6B64\u6743\u9650\uFF09\u3002\n - **\u9A8C\u6536\u65B9\uFF08default agent / \u63A5\u5F85\u5458\uFF09**\uFF1A`task_complete` after item-by-item verification\n (see Complete Discipline below)".trim(),TY=`### Operation Record \u2014 \u53CC\u7EF4\u5EA6\u5206\u5DE5\u89C4\u8303
517
+ LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${xq()}`,X=Date.now(),q=JSON.stringify($.metadata??{}),Y=$.rawEvent===void 0?null:gq($.rawEvent);return this.insertStmt.run(Q,J,$.senderId,$.text??null,q,Y,X),Q}async getEventById($){let J=this.getByIdStmt.get($);if(!J)return null;return e5(J)}async getRecentEvents($,J,Q){return this.recentStmt.all($,J,Q).map((q)=>e5(q))}close(){this.db.close()}}k([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],B4.prototype,"insertTriggerEvent",null);k([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],B4.prototype,"getEventById",null);function e5($){let J;try{J=$.metadata?JSON.parse($.metadata):{}}catch{J={}}let Q;if($.raw_event)try{Q=JSON.parse($.raw_event)}catch{Q=null}else Q=null;return{eventId:$.event_id,esType:$.es_type,senderId:$.sender_id,text:$.text??null,metadata:J,rawEvent:Q,createdAt:typeof $.created_at==="bigint"?Number($.created_at):$.created_at}}function gq($){let J=new WeakSet;try{return JSON.stringify($,(Q,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(J.has(X))return"[Circular]";J.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch{return"{}"}}var kq=null;function $7(){return kq}var t$="\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536",q$="TASK_COMPLETION_HINT",e$="\u6838\u5B9E\u4E49\u52A1";var a0="\u5DF2\u5B8C\u6210",Z$="\u5DF2\u53D6\u6D88",E2="\u4EA4\u4ED8\u7269\u5DF2\u8BB0\u5F55",w$="\u5DF2\u5F52\u6863",J7="\u5DF2\u91CD\u65B0\u6253\u5F00",u0="\u5F85\u9A8C\u8BC1",Q7=[a0,Z$,w$],E6=["cancelled","archived"];var mq="### Task Lifecycle (7 steps, 0-6)\n\n> Tasks are the **first-class citizen**. Follow this lifecycle for every task:\n\n0. CHECK TASK CONTEXT OR SEARCH\n - If `[\u5F53\u524D Task #N]` is in the context \u2192 use `task_get #N` directly, skip searching.\n - Otherwise use `task_list` / `task_search` to find related tasks.\n - If found \u2192 reuse, extend, and update (see the reuse rules in step 1).\n If not found \u2192 proceed to step 1.\n - **Orient before creating**: read the existing tree with\n `task_tree(depth=1)` (`depth=2` for bigger trees) and decide whether the\n work belongs to an existing root (attach via `parent_task_id`) or is\n genuinely new. Keep **root tasks \u2264 10**; prefer attaching to an existing\n thematic root over spawning a new root. Never hardcode ids \u2014 read them\n from `task_tree`.\n\n1. CREATE or REUSE\n - No existing task \u2192 create a new one with title, description, goals.\n - Existing task \u2192 reuse via `task_get`, then `task_update`:\n * Append new context to description and goals (preserve the old content)\n * Add / extend `goals_and_expected_deliverables`\n * Create an operation record documenting the continuation\n * Set priority and due date if any\n * If the original task was completed \u2192 reset status to `active`\n and reset progress to a reasonable value\n\n2. GATHER CONTEXT (never skip)\n - Read description, goals, current_status\n - Check `parent_task_id` for sub-tasks\n - Read the operation history: `task_operation_list` (~20 recent records)\n - Review recent operations for history and decisions\n - Working without context risks: outdated goals, missed decisions,\n duplicated work, misalignment with the parent task\n\n3. EXECUTE\n - Use the available tools, skills and workflows to satisfy the task\n description and goals.\n - Long-running work: for work longer than 5 minutes, record a milestone\n with `task_operation_create` as you go, so the user can see progress.\n - Several independent sub-tasks may run in parallel (background `bash &`\n or parallel ReAct steps).\n - **\u8FB9\u5E72\u8FB9\u8BB0** \u2014 milestones are recorded **while working**;\n **\u7981\u6B62\u4E8B\u540E\u6279\u91CF\u8865**\uFF08do not defer them to one batch at the end\uFF09.\n - Note: `task_create` / `task_update` already create operation records\n automatically \u2014 do not create duplicates by hand.\n\n4. TRACK\n - Update progress (0-100%) as the work advances\n - Update status: todo \u2192 active\n - Record `current_status` with human-readable progress\n - \u26A0\uFE0F **\u4E0D\u8981**\u628A status \u76F4\u63A5\u7F6E\u4E3A `completed` \u6216 `to_validate` \u2014\u2014\n \u7EC8\u6001\u7531\u9A8C\u6536\u65B9\u843D\u3001\u5F85\u9A8C\u8BC1\u7531 `task_pre_complete` \u63D0\u4EA4\uFF08\u89C1\u6B65\u9AA4 6\uFF09\n\n5. RECORD \u2014 operation records (see Operation Discipline below)\n\n6. COMPLETE \u2014 \u6536\u5C3E\u5206\u4E24\u79CD\u89D2\u8272\uFF08Task #5007/#5073\uFF0C\u9A8C\u6536\u6743\u5206\u79BB\uFF09\n - **\u6267\u884C\u65B9\uFF08roy sub-agent\uFF09**\uFF1A\u8FDB\u5EA6\u8FBE\u5230\u4F60\u5224\u65AD\u7684 100% \u21D2\n `task_pre_complete` **\u63D0\u4EA4\u5F85\u9A8C\u8BC1**\uFF08`deliverable_storage_path`\n \u4F20\u4EA4\u4ED8\u7269\u5730\u5740\uFF1Bstatus \u2192 to_validate\uFF0C\u5E76\u89E6\u53D1\u4E00\u6B21 goal \u68C0\u67E5\u81EA\u67E5\uFF09\n + \u6700\u540E\u4E00\u6761 `task_operation_create` \u21D2 **\u7ED3\u675F\u5E76\u8FD4\u56DE\u7ED3\u679C**\u3002\n \u274C **\u4E0D\u8981\u8C03\u7528 `task_complete`**\uFF08\u4F60\u65E0\u6B64\u6743\u9650\uFF09\u3002\n - **\u9A8C\u6536\u65B9\uFF08default agent / \u63A5\u5F85\u5458\uFF09**\uFF1A`task_complete` after item-by-item verification\n (see Complete Discipline below)".trim(),uq=`### Operation Record \u2014 \u53CC\u7EF4\u5EA6\u5206\u5DE5\u89C4\u8303
518
518
 
519
519
  **Record milestones as you work** \u2014 call \`task_operation_create\` the moment a
520
520
  stage is reached, **not after the fact** (not in a batch at the end).
@@ -548,7 +548,7 @@ stage is reached, **not after the fact** (not in a batch at the end).
548
548
  "milestone_description": "21/21 \u6D4B\u8BD5\u901A\u8FC7\uFF0C\u5305\u542B 4 \u4E2A action_* alias \u517C\u5BB9\u6D4B\u8BD5",
549
549
  "process_description": "TDD RED \u5199 4 \u4E2A\u5931\u8D25\u6D4B\u8BD5\u8986\u76D6 storage/tool\uFF1B\u8FC1\u79FB 004 rename \u5217\uFF1BrowToOperation \u540C\u65F6\u8F93\u51FA\u53CC\u5B57\u6BB5\u517C\u5BB9\uFF1Btool zod preprocess \u81EA\u52A8\u6620\u5C04 action_*"
550
550
  }
551
- \`\`\``,W4=`### Goals \u5B50\u9879\u62C6\u5206\u89C4\u5219
551
+ \`\`\``,U4=`### Goals \u5B50\u9879\u62C6\u5206\u89C4\u5219
552
552
 
553
553
  \`goals_and_expected_deliverables\` **MUST** be written as
554
554
  **numbered sub-items** (\u7F16\u53F7\u5B50\u9879) that can each be verified
@@ -577,7 +577,7 @@ Reference the four atomic assertion forms (Task #4768
577
577
  - \u6587\u4EF6\u65AD\u8A00 (file assertion): file exists / size / content grep
578
578
  - \u8FDB\u7A0B\u65AD\u8A00 (process assertion): command exit code / stdout match
579
579
  - \u6D4B\u8BD5\u65AD\u8A00 (test assertion): pass/fail counts, no NEW fail
580
- - \u72B6\u6001\u65AD\u8A00 (state assertion): version number / HTTP 200 / status field`,vY=`### Task Complete \u2014 \u6838\u5B9E\u4E49\u52A1\uFF08**\u4EC5\u9A8C\u6536\u65B9\u9002\u7528**\uFF09
580
+ - \u72B6\u6001\u65AD\u8A00 (state assertion): version number / HTTP 200 / status field`,lq=`### Task Complete \u2014 \u6838\u5B9E\u4E49\u52A1\uFF08**\u4EC5\u9A8C\u6536\u65B9\u9002\u7528**\uFF09
581
581
 
582
582
  > \u26A0\uFE0F **\u89D2\u8272\u4F5C\u7528\u57DF\uFF08Task #5007\uFF09**\uFF1A\u672C\u8282\u662F**\u9A8C\u6536\u65B9**\uFF08default agent / \u63A5\u5F85\u5458\uFF09\u7684\u52A8\u4F5C\u3002
583
583
  > \u82E5\u4F60\u662F**\u6267\u884C\u65B9**\uFF08roy sub-agent\uFF09\uFF0C\u4F60\u6CA1\u6709 \`task_complete\` \u6743\u9650 \u2014\u2014
@@ -588,7 +588,7 @@ Before calling \`task_complete\`, you MUST:
588
588
  1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
589
589
  - Use \`task_get(task_id=<id>)\` to fetch the full task record.
590
590
  2. **Validate whether each goal sub-item was achieved** \u2014 accept the goal
591
- **item-by-item** (${n$}).
591
+ **item-by-item** (${t$}).
592
592
  - Goals should be numbered sub-items (\u7F16\u53F7\u5B50\u9879). Check
593
593
  each sub-item against the operation-record chain (\u64CD\u4F5C\u8BB0\u5F55\u94FE) and the
594
594
  deliverable evidence (context.deliverable_storage_path).
@@ -596,9 +596,9 @@ Before calling \`task_complete\`, you MUST:
596
596
  deliverables; numbered sub-items give it finer-grained evidence to
597
597
  reason with (\u9010\u6761\u5BF9\u7167\u7684\u8BC1\u636E\u7C92\u5EA6). If it detects that the goal or
598
598
  deliverables appear unmet, the task context will carry a
599
- \`[${$$}]\`.
600
- - **If you receive a [${$$}]**, you MUST verify it
601
- (${r$}): re-read the task via \`task_get\`, then do exactly one of:
599
+ \`[${q$}]\`.
600
+ - **If you receive a [${q$}]**, you MUST verify it
601
+ (${e$}): re-read the task via \`task_get\`, then do exactly one of:
602
602
  (a) \u786E\u8BA4\u672A\u5B8C\u6210 \u2192 **\u91CD\u65B0\u59D4\u6258**\uFF08\u7528\u4F60\u7684\u59D4\u6258\u5DE5\u5177 + \u540C\u4E00 sub-session \u7EED\u8DD1\uFF0C
603
603
  \u5728\u6307\u4EE4\u91CC\u5199\u660E"\u76EE\u6807\u5C1A\u672A\u8FBE\u6210\uFF0C\u9700\u8981\u8865 X/Y/Z"\uFF09\uFF0C\u7531 sub-agent \u7528
604
604
  \`task_update(status=active)\` \u91CD\u5F00\u5E76\u7EE7\u7EED\u63A8\u8FDB\uFF1B\u82E5\u4F60**\u81EA\u5DF1\u5C31\u662F\u6267\u884C\u65B9**
@@ -624,9 +624,9 @@ Before calling \`task_complete\`, you MUST:
624
624
  (\`Deliverable: <path>\` lines). Cross-check them in step 2.
625
625
  \`task_complete\` takes **no** deliverable parameter \u2014 if the
626
626
  deliverables are missing from the record, re-delegate instead of
627
- asking for a path here.`,s7=[IY,TY,W4,vY].join(`
627
+ asking for a path here.`,X7=[mq,uq,U4,lq].join(`
628
628
 
629
- `);var z4={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
629
+ `);var V4={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
630
630
 
631
631
  ## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
632
632
 
@@ -778,7 +778,7 @@ delegate_task({
778
778
  - \u2705 \u529F\u80FD\u5F00\u53D1\u3001bug \u4FEE\u590D\u3001\u91CD\u6784\u3001\u6587\u6863\u751F\u6210
779
779
  - \u2705 \u7F51\u7EDC\u641C\u7D22\u548C\u7814\u7A76
780
780
 
781
- **roy** \u7684\u63D0\u793A\u8BCD\u4E2D\u5185\u7F6E\u4E86\u4EFB\u52A1\u751F\u547D\u5468\u671F\u2014\u2014\u5B83\u77E5\u9053\u5982\u4F55\u4F7F\u7528 \`task_create\`\u3001\`task_update\`\u3001\`task_operation_create\` \u6765\u8DDF\u8E2A\u6BCF\u9879\u5DE5\u4F5C\u5E76\u7559\u4E0B\u64CD\u4F5C\u8BB0\u5F55\u3002\u26A0\uFE0F **Task #5007/#5073**\uFF1Aroy **\u6CA1\u6709** \`task_complete\` \u6743\u9650 \u2014\u2014 \u5B83\u5E72\u5B8C\u6D3B\u4F1A\u8C03 \`task_pre_complete\` \u63D0\u4EA4\u5F85\u9A8C\u8BC1\uFF08\u4EFB\u52A1\u8FDB\u5165 to_validate\uFF09\uFF0C**\u6700\u7EC8\u9A8C\u6536\uFF08${n$}\uFF09\u7531\u4F60\uFF08default agent\uFF09\u7528 \`task_complete\` \u843D\u5B9A**\u3002\u82E5\u9A8C\u6536\u65F6\u6536\u5230 [${$$}]\uFF0C\u6309\u5DE5\u5177\u63CF\u8FF0\u91CC\u7684${r$}\u4E8C\u9009\u4E00\uFF08\u91CD\u5F00 / \u843D decision \u8BF4\u660E\u7406\u7531\uFF09\u3002
781
+ **roy** \u7684\u63D0\u793A\u8BCD\u4E2D\u5185\u7F6E\u4E86\u4EFB\u52A1\u751F\u547D\u5468\u671F\u2014\u2014\u5B83\u77E5\u9053\u5982\u4F55\u4F7F\u7528 \`task_create\`\u3001\`task_update\`\u3001\`task_operation_create\` \u6765\u8DDF\u8E2A\u6BCF\u9879\u5DE5\u4F5C\u5E76\u7559\u4E0B\u64CD\u4F5C\u8BB0\u5F55\u3002\u26A0\uFE0F **Task #5007/#5073**\uFF1Aroy **\u6CA1\u6709** \`task_complete\` \u6743\u9650 \u2014\u2014 \u5B83\u5E72\u5B8C\u6D3B\u4F1A\u8C03 \`task_pre_complete\` \u63D0\u4EA4\u5F85\u9A8C\u8BC1\uFF08\u4EFB\u52A1\u8FDB\u5165 to_validate\uFF09\uFF0C**\u6700\u7EC8\u9A8C\u6536\uFF08${t$}\uFF09\u7531\u4F60\uFF08default agent\uFF09\u7528 \`task_complete\` \u843D\u5B9A**\u3002\u82E5\u9A8C\u6536\u65F6\u6536\u5230 [${q$}]\uFF0C\u6309\u5DE5\u5177\u63CF\u8FF0\u91CC\u7684${e$}\u4E8C\u9009\u4E00\uFF08\u91CD\u5F00 / \u843D decision \u8BF4\u660E\u7406\u7531\uFF09\u3002
782
782
 
783
783
  \u63A8\u8350\u4F7F\u7528\uFF1A
784
784
  \`\`\`
@@ -1056,7 +1056,7 @@ subSessionId: sub-session-xyz
1056
1056
  | session \u89C4\u6A21 | \u5EFA\u8BAE\u5904\u7F6E |
1057
1057
  |---|---|
1058
1058
  | **\u5C0F**\uFF08\u8D85\u9650\u6BD4\u4F8B < 30%\uFF0C\u6D88\u606F\u6570\u4E0D\u591A\uFF09 | \u76F4\u63A5 \`compact_session\` \u2192 \u538B\u7F29\u6210\u529F\u540E\u7528 \`sub_session_id\` \u7EED\u8DD1 |
1059
- | **\u5927**\uFF08\u8D85\u9650\u6BD4\u4F8B\u5F88\u9AD8 / \u6D88\u606F\u6570\u5F88\u591A\uFF09 | \`compact_session\` **\u53EF\u80FD\u8981\u8DD1\u5F88\u4E45\u751A\u81F3\u649E 120s \u5DE5\u5177\u8D85\u65F6** \u2192 **\u4E0D\u8981\u5728\u540C\u4E00\u4E2A session \u4E0A\u6B7B\u78D5**\uFF0C\u76F4\u63A5**\u5F00\u65B0 session** + \u660E\u786E\u5217\u51FA\u300C\u5DF2\u5B8C\u6210\u9879 / \u65AD\u70B9 / \u5C0F\u76EE\u6807\u300D |
1059
+ | **\u5927**\uFF08\u8D85\u9650\u6BD4\u4F8B\u5F88\u9AD8 / \u6D88\u606F\u6570\u5F88\u591A\uFF09 | \`compact_session\` **\u53EF\u80FD\u8981\u8DD1\u5F88\u4E45\u751A\u81F3\u649E 120s \u5DE5\u5177\u8D85\u65F6** \u2192 **\u4E0D\u8981\u5728\u540C\u4E00\u4E2A session \u4E0A\u6B7B\u78D5**\uFF0C\u8D70\u4E0B\u9762\u7684**\u515C\u5E95\u8DEF\u5F84**\uFF08\u538B\u7F29\u590D\u67E5 \u2192 \u4ECD\u65E0\u6548\u624D\u5F00\u65B0 session\uFF09+ \u660E\u786E\u5217\u51FA\u300C\u5DF2\u5B8C\u6210\u9879 / \u65AD\u70B9 / \u5C0F\u76EE\u6807\u300D |
1060
1060
 
1061
1061
  **\u4E3A\u4EC0\u4E48\u5FC5\u987B\u5148\u8BC4\u4F30**\uFF08\u5B9E\u6D4B\u6570\u636E\uFF09\uFF1A
1062
1062
 
@@ -1091,7 +1091,7 @@ const r = await compact_session({ session_id: "sub-session-xyz" });
1091
1091
  2. **\u518D\u68C0\u67E5\u4E00\u6B21**\u8BE5 session \u7684**\u6D88\u606F\u6570 / checkpoint** \u2014\u2014 \`compact_session\` \u6210\u529F\u4F1A\u8FD4\u56DE \`checkpointId\`\uFF0C\u4E5F\u53EF\u4EE5\u7528 session \u76F8\u5173\u5DE5\u5177\u786E\u8BA4\u6D88\u606F\u662F\u5426\u5DF2\u88AB archived
1092
1092
  3. \u518D\u51B3\u5B9A\u8D70\u54EA\u6761\u8DEF\uFF1A
1093
1093
  - **\u538B\u7F29\u5176\u5B9E\u6210\u529F\u4E86** \u2192 \u7528 \`sub_session_id\` \u7EED\u8DD1\uFF08\u4E0A\u4E0B\u6587\u5DF2\u7ECF\u53D8\u5C0F\uFF0C\u5B89\u5168\uFF09
1094
- - **\u538B\u7F29\u786E\u5B9E\u6CA1\u751F\u6548** \u2192 \u624D\u8D70\u4E0B\u9762\u7684\u300C\u5F00\u65B0 session\u300D\u8DEF\u5F84
1094
+ - **\u538B\u7F29\u786E\u5B9E\u6CA1\u751F\u6548** \u2192 \u624D\u8D70\u4E0B\u9762\u7684\u515C\u5E95\u8DEF\u5F84\uFF08\u6362\u65B0 session\uFF09
1095
1095
 
1096
1096
  **\u7B2C 3 \u6B65\uFF1A\u5E26\u540C\u4E00\u4E2A \`sub_session_id\` \u7EED\u8DD1**
1097
1097
 
@@ -1119,9 +1119,9 @@ delegate_task({
1119
1119
 
1120
1120
  \`\`\`typescript
1121
1121
  delegate_task({
1122
- description: "\u63A5\u7EED\u5DE5\u4F5C\uFF08\u4E0A\u4E0B\u6587\u5DF2\u8D85\u9650\uFF0C\u6539\u7528\u65B0 session\uFF09",
1122
+ description: "\u63A5\u7EED\u5DE5\u4F5C\uFF08\u4E0A\u4E0B\u6587\u5DF2\u8D85\u9650\uFF0C\u538B\u7F29\u590D\u67E5\u540E\u4ECD\u4E0D\u53EF\u6551\uFF0C\u6362\u65B0 session\uFF09",
1123
1123
  prompt: "\u3010\u5DF2\u5B8C\u6210\u3011... \\n\u3010\u65AD\u70B9\u3011... \\n\u3010\u5C0F\u76EE\u6807\u3011... \\n\u3010\u76F8\u5173\u6587\u4EF6\u8DEF\u5F84\u3011... \\n\u3010\u5DF2\u77E5\u7ED3\u8BBA\u3011...",
1124
- // \u4E0D\u4F20 sub_session_id \u2014\u2014 \u5F00\u65B0 session
1124
+ sub_session_id: "sub-session-xyz", // \u26A0\uFE0F \u515C\u5E95\u8DEF\u5F84\uFF1A\u4EC5\u5728 compact_session \u4E5F\u65E0\u6548\u65F6\u624D\u7701\u7565
1125
1125
  });
1126
1126
  \`\`\`
1127
1127
 
@@ -1129,9 +1129,9 @@ delegate_task({
1129
1129
 
1130
1130
  #### \u274C \u53CD\u6A21\u5F0F\u8B66\u793A
1131
1131
 
1132
- - \u274C **\u4E0D\u8981\u4ECE\u5934\u91CD\u65B0\u59D4\u6258**\uFF08\u4E0D\u4F20 \`sub_session_id\` \u76F4\u63A5 \`delegate_task\`\uFF09\u2014\u2014 \u4E22\u6389\u5168\u90E8\u4E0A\u4E0B\u6587\uFF0C\u524D\u9762\u7684\u8C03\u7814\u548C\u4EE3\u7801\u5168\u767D\u505A\uFF0C\u8FD8\u53EF\u80FD\u91CD\u590D\u8E29\u5DF2\u89E3\u51B3\u8FC7\u7684\u5751\u3002
1133
- - \u274C **\u4E0D\u8981\u5728\u538B\u7F29\u5931\u8D25\u65F6\u53CD\u590D\u7528\u540C\u4E00\u4E2A session \u7EED\u8DD1** \u2014\u2014 \u540C\u6837\u7684\u8D85\u9650\u4F1A\u518D\u53D1\u751F\u4E00\u6B21\uFF0C\u5F92\u589E token \u6D88\u8017\u3002\u538B\u7F29\u5931\u8D25\u5C31\u8D70"\u5F00\u65B0 session + \u660E\u786E\u5217\u51FA\u5DF2\u5B8C\u6210\u9879/\u65AD\u70B9/\u5C0F\u76EE\u6807"\u7684\u515C\u5E95\u8DEF\u5F84\u3002
1134
- - \u274C **\u4E0D\u8981\u5728 session \u89C4\u6A21\u5F88\u5927\u65F6\u6B7B\u78D5 \`compact_session\`** \u2014\u2014 \u5148\u6309\u7B2C 0 \u6B65\u8BC4\u4F30\uFF0Cmessage \u6570\u5F88\u591A\u5C31\u76F4\u63A5\u5F00\u65B0 session\u3002
1132
+ - \u274C **\u4E0D\u8981\u4ECE\u5934\u91CD\u65B0\u59D4\u6258** \u2014\u2014 \u4E0D\u4F20 \`sub_session_id\` \u76F4\u63A5 \`delegate_task\` \u662F**\u6700\u540E\u624B\u6BB5**\uFF0C\u53EA\u5728\u65E7 session \u4E0A\u4E0B\u6587\u5DF2\u786E\u8BA4\u4E0D\u53EF\u6551\uFF08compact_session \u540E\u4ECD\u8D85\u9650 / \u8FED\u4EE3\u4E0A\u9650\u4E14\u65E0\u53EF\u590D\u7528\u65AD\u70B9\uFF09\u65F6\u624D\u5141\u8BB8\u3002\u5176\u4F59\u60C5\u51B5\u4E00\u5F8B\u5E26 \`sub_session_id\` \u7EED\u8DD1\uFF08\u4E0D\u4F20\u624D\u4F1A\u4E22\u6389\u5168\u90E8\u4E0A\u4E0B\u6587\uFF0C\u524D\u9762\u7684\u8C03\u7814\u548C\u4EE3\u7801\u5168\u767D\u505A\uFF0C\u8FD8\u53EF\u80FD\u91CD\u590D\u8E29\u5DF2\u89E3\u51B3\u8FC7\u7684\u5751\uFF09\u3002
1133
+ - \u274C **\u4E0D\u8981\u5728\u538B\u7F29\u5931\u8D25\u65F6\u53CD\u590D\u7528\u540C\u4E00\u4E2A session \u7EED\u8DD1** \u2014\u2014 \u540C\u6837\u7684\u8D85\u9650\u4F1A\u518D\u53D1\u751F\u4E00\u6B21\uFF0C\u5F92\u589E token \u6D88\u8017\u3002\u538B\u7F29\u5931\u8D25\u5C31\u8D70"\u6362\u65B0 session\uFF08\u4E0D\u4F20 \`sub_session_id\`\uFF09+ \u660E\u786E\u5217\u51FA\u5DF2\u5B8C\u6210\u9879/\u65AD\u70B9/\u5C0F\u76EE\u6807"\u7684\u515C\u5E95\u8DEF\u5F84\u3002
1134
+ - \u274C **\u4E0D\u8981\u5728 session \u89C4\u6A21\u5F88\u5927\u65F6\u6B7B\u78D5 \`compact_session\`** \u2014\u2014 \u5148\u6309\u7B2C 0 \u6B65\u8BC4\u4F30\uFF0Cmessage \u6570\u5F88\u591A\u5C31\u8D70\u515C\u5E95\u8DEF\u5F84\uFF08\u538B\u7F29\u590D\u67E5 \u2192 \u4ECD\u65E0\u6548\u624D\u6362\u65B0 session\uFF09\u3002
1135
1135
  - \u274C **\u4E0D\u8981\u7528 \`compact_session\` \u538B\u7F29\u5F53\u524D\u4F1A\u8BDD\u81EA\u5DF1** \u2014\u2014 \u5DE5\u5177\u4F1A\u76F4\u63A5\u62D2\u7EDD\uFF08\u81EA\u6BC1\uFF09\u3002
1136
1136
  - \u274C **\u4E0D\u8981\u538B\u7F29\u8FD8\u5728 running/pending \u7684\u540E\u53F0\u4EFB\u52A1** \u2014\u2014 \u5148 \`stop_task\`\u3002
1137
1137
 
@@ -1666,7 +1666,7 @@ roy-agent <command> <subcmd> --help
1666
1666
  > \u26A0\uFE0F \u5982\u679C\u4F60\u56E0\u4E3A\u8D85\u65F6 / \u5D29\u6E83\u6CA1\u80FD\u628A\u72B6\u6001\u66F4\u65B0\u5230\u4F4D\uFF0C\u4E3B\u667A\u80FD\u4F53**\u4E5F\u4F1A**\u6765\u515C\u5E95\u9A8C\u6536 \u2014\u2014
1667
1667
  > \u4F46\u4F60**\u4E3B\u52A8**\u628A\u8FDB\u5EA6\u548C\u64CD\u4F5C\u8BB0\u5F55\u5199\u5168\uFF0C\u80FD\u8BA9\u9A8C\u6536\u66F4\u5FEB\u66F4\u51C6\u3002
1668
1668
 
1669
- ${s7}
1669
+ ${X7}
1670
1670
  ### {{memory}}`,coding:`You are an expert coding assistant.
1671
1671
 
1672
1672
  ## Your Approach
@@ -2447,8 +2447,8 @@ task_operation_create({
2447
2447
  \u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
2448
2448
 
2449
2449
  > \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
2450
- `},LK=z4["workflow-extract"];var X0={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"};import o7 from"os";import O0 from"path";var w6="roy-agent";function xY(){let $=o7.homedir();try{let J=e("xdg-basedir");return{config:J.xdgConfig||O0.join($,".config"),state:J.xdgState||O0.join($,".local","state"),data:J.xdgData||O0.join($,".local","share"),cache:J.xdgCache||O0.join($,".cache")}}catch{return{config:O0.join($,".config"),state:O0.join($,".local","state"),data:O0.join($,".local","share"),cache:O0.join($,".cache")}}}function hY(){let $=o7.homedir(),J=xY();return{home:$,config:O0.join(J.config,w6),state:O0.join(J.state,w6),data:O0.join(J.data,w6),cache:O0.join(J.cache,w6)}}class t7{_paths;get paths(){if(!this._paths)this._paths=hY();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return O0.join(this.paths[$],J)}reset(){this._paths=void 0}}var yY=new t7;function e7($){return yY.getPath($)}import*as yD from"fs/promises";import*as gD from"fs";import{join as q2}from"path";var N8=qQ(H3(),1);n();V0();var s=i("agent:registry"),j8=K.object({name:K.string(),type:K.enum(["primary","sub","workflow"]),workflow:K.string().optional(),entryAgent:K.string().optional(),description:K.string().optional(),systemPromptRef:K.string().optional(),systemPrompt:K.string().optional(),model:K.string().optional(),maxIterations:K.number().optional(),maxErrorRetries:K.number().optional(),allowedTools:K.array(K.string()).optional(),deniedTools:K.array(K.string()).optional(),toolTimeout:K.number().optional(),toolRetries:K.number().optional(),doomLoopThreshold:K.number().optional(),filterHistory:K.boolean().optional()}).refine(($)=>$.type!=="workflow"||$.workflow&&$.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class L0{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor($){this.configComponent=$.configComponent,this.promptComponent=$.promptComponent??null,this.resolvePromptComponent=$.resolvePromptComponent,this.fs=$.fs||gD,this.fsPromises=$.fsPromises||yD;let J=this.configComponent?.get?.("agent.configDir");if(J&&typeof J==="string"&&J.length>0)this.configDir=J;else if($.baseDir)this.configDir=q2($.baseDir,"agents");else this.configDir=q2(e7("data"),"agents");s.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((J)=>J.type===$)}register($){if(!$.name)throw Error("Agent name is required");let J=j8.safeParse($);if(!J.success)throw Error(`Invalid agent config for "${$.name}": ${J.error.issues.map((Q)=>Q.message).join("; ")}`);this.agents.set($.name,{...$}),s.info(`[AgentRegistry] Registered agent: ${$.name}`,{type:$.type})}unregister($){let J=this.agents.delete($);if(J)s.info(`[AgentRegistry] Unregistered agent: ${$}`);return J}clear(){this.agents.clear(),s.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt($){let J=this.agents.get($);if(!J)return;let Q=this.getActivePromptComponent();if(J.systemPromptRef)try{if(Q?.getPrompt){let Y=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(Y)return s.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),Y}let X=Q?.get?.(J.systemPromptRef);if(X)return s.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${J.systemPromptRef}`),X;if(J.systemPrompt)return s.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),J.systemPrompt;return}catch(X){return s.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${J.systemPromptRef}`,{error:X}),J.systemPrompt}return J.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt($){let J=this.agents.get($);if(!J)return;return J.systemPrompt}getWorkflowName($){let J=this.agents.get($);if(!J||J.type!=="workflow")return;return J.workflow}getEntryAgent($){let J=this.agents.get($);if(!J||J.type!=="workflow")return;return J.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let J={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",J)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let J={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",J)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let J={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",J)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let J={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",J)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let J={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",J)}registerCompactAgent(){let J={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:[],deniedTools:[],maxIterations:3,filterHistory:!1},Q=this.agents.get("compact");if(Q){this.agents.set("compact",{...J,description:Q.description??J.description}),s.info("[AgentRegistry] Built-in compact agent overrode user-level definition (tool whitelist enforced: allowedTools=[])");return}this.agents.set("compact",J)}registerCompactHintAgent(){let J={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:[],deniedTools:[],maxIterations:3,filterHistory:!1},Q=this.agents.get("compact-hint");if(Q){this.agents.set("compact-hint",{...J,description:Q.description??J.description}),s.info("[AgentRegistry] Built-in compact-hint agent overrode user-level definition (tool whitelist enforced: allowedTools=[])");return}this.agents.set("compact-hint",J)}registerRoyAgent(){if(this.agents.has("roy"))return;let J={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","task_complete","task_cancel"]};this.agents.set("roy",J)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch($){return s.warn(`[AgentRegistry] Failed to load agents: ${$}`),0}}async loadFromDirectory($){let J=0;try{if(!this.fs.existsSync($))return s.debug(`[AgentRegistry] Config directory does not exist: ${$}`),0;let Q=await this.fsPromises.readdir($,{withFileTypes:!0});for(let X of Q){let Y=q2($,X.name);if(X.isDirectory())continue;if(!kD(X.name))continue;try{let G=await this.fsPromises.readFile(Y,"utf-8"),q=this.parseAgentConfig(G,Y);if(q)this.agents.set(q.name,q),s.info(`[AgentRegistry] Loaded agent: ${q.name} from ${X.name}`),J++}catch(G){s.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${G}`)}}s.info(`[AgentRegistry] Loaded ${J} agents from ${$}`)}catch(Q){s.warn(`[AgentRegistry] Error reading config directory: ${Q}`)}return J}parseAgentConfig($,J){try{let Q=N8.default.parse($),X=j8.safeParse(Q);if(!X.success)return s.warn(`[AgentRegistry] Invalid agent config: ${J}`,{errors:X.error.errors}),null;return X.data}catch(Q){return s.error(`[AgentRegistry] Failed to parse agent config: ${J}`,{error:Q}),null}}async saveAgent($){try{let J=j8.safeParse($);if(!J.success)return s.error(`[AgentRegistry] Invalid agent config for "${$.name}": ${J.error.message}`),!1;await this.ensureConfigDir();let Q=this.agentToYaml($),X=q2(this.configDir,`${$.name}.yaml`);return await this.fsPromises.writeFile(X,Q,"utf-8"),this.agents.set($.name,$),s.info(`[AgentRegistry] Saved agent: ${$.name} to ${X}`),!0}catch(J){return s.error(`[AgentRegistry] Failed to save agent: ${$.name}`,{error:J}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),s.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml($){let J={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 N8.default.stringify(J).trimEnd()+`
2451
- `}async deleteAgent($){if(!this.agents.get($))return s.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=q2(this.configDir,`${$}.yaml`);if(this.fs.existsSync(Q))await this.fsPromises.unlink(Q),s.info(`[AgentRegistry] Deleted agent file: ${Q}`);return this.agents.delete($),!0}catch(Q){return s.error(`[AgentRegistry] Failed to delete agent: ${$}`,{error:Q}),!1}}exportAgents($={}){let J=this.list();if($.format==="json")return J;return J}exportAgentsAsJson(){return JSON.stringify(this.list(),null,2)}size(){return this.agents.size}configDirExists(){return this.fs.existsSync(this.configDir)}getAgentFilePath($){return q2(this.configDir,`${$}.yaml`)}}k([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"register",null);k([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"unregister",null);k([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"clear",null);k([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],L0.prototype,"getSystemPrompt",null);k([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],L0.prototype,"getWorkflowName",null);k([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],L0.prototype,"getEntryAgent",null);k([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowRunner",null);k([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerTaskOrganizer",null);k([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowCreator",null);k([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"load",null);k([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"loadFromDirectory",null);function kD($){return $.endsWith(".yaml")||$.endsWith(".yml")}var _8=`You are a subagent created by the main agent to handle a specific task.
2450
+ `},lK=V4["workflow-extract"];var q0={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"};import q7 from"os";import N0 from"path";var S6="roy-agent";function cq(){let $=q7.homedir();try{let J=$0("xdg-basedir");return{config:J.xdgConfig||N0.join($,".config"),state:J.xdgState||N0.join($,".local","state"),data:J.xdgData||N0.join($,".local","share"),cache:J.xdgCache||N0.join($,".cache")}}catch{return{config:N0.join($,".config"),state:N0.join($,".local","state"),data:N0.join($,".local","share"),cache:N0.join($,".cache")}}}function dq(){let $=q7.homedir(),J=cq();return{home:$,config:N0.join(J.config,S6),state:N0.join(J.state,S6),data:N0.join(J.data,S6),cache:N0.join(J.cache,S6)}}class Y7{_paths;get paths(){if(!this._paths)this._paths=dq();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return N0.join(this.paths[$],J)}reset(){this._paths=void 0}}var pq=new Y7;function G7($){return pq.getPath($)}import*as pD from"fs/promises";import*as iD from"fs";import{join as U2}from"path";var w8=FQ(OJ(),1);i();D0();var t=d("agent:registry"),Z8=K.object({name:K.string(),type:K.enum(["primary","sub","workflow"]),workflow:K.string().optional(),entryAgent:K.string().optional(),description:K.string().optional(),systemPromptRef:K.string().optional(),systemPrompt:K.string().optional(),model:K.string().optional(),maxIterations:K.number().optional(),maxErrorRetries:K.number().optional(),allowedTools:K.array(K.string()).optional(),deniedTools:K.array(K.string()).optional(),toolTimeout:K.number().optional(),toolRetries:K.number().optional(),doomLoopThreshold:K.number().optional(),filterHistory:K.boolean().optional()}).refine(($)=>$.type!=="workflow"||$.workflow&&$.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class R0{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor($){this.configComponent=$.configComponent,this.promptComponent=$.promptComponent??null,this.resolvePromptComponent=$.resolvePromptComponent,this.fs=$.fs||iD,this.fsPromises=$.fsPromises||pD;let J=this.configComponent?.get?.("agent.configDir");if(J&&typeof J==="string"&&J.length>0)this.configDir=J;else if($.baseDir)this.configDir=U2($.baseDir,"agents");else this.configDir=U2(G7("data"),"agents");t.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((J)=>J.type===$)}register($){if(!$.name)throw Error("Agent name is required");let J=Z8.safeParse($);if(!J.success)throw Error(`Invalid agent config for "${$.name}": ${J.error.issues.map((Q)=>Q.message).join("; ")}`);this.agents.set($.name,{...$}),t.info(`[AgentRegistry] Registered agent: ${$.name}`,{type:$.type})}unregister($){let J=this.agents.delete($);if(J)t.info(`[AgentRegistry] Unregistered agent: ${$}`);return J}clear(){this.agents.clear(),t.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt($){let J=this.agents.get($);if(!J)return;let Q=this.getActivePromptComponent();if(J.systemPromptRef)try{if(Q?.getPrompt){let q=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(q)return t.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),q}let X=Q?.get?.(J.systemPromptRef);if(X)return t.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${J.systemPromptRef}`),X;if(J.systemPrompt)return t.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),J.systemPrompt;return}catch(X){return t.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${J.systemPromptRef}`,{error:X}),J.systemPrompt}return J.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt($){let J=this.agents.get($);if(!J)return;return J.systemPrompt}getWorkflowName($){let J=this.agents.get($);if(!J||J.type!=="workflow")return;return J.workflow}getEntryAgent($){let J=this.agents.get($);if(!J||J.type!=="workflow")return;return J.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let J={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",J)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let J={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",J)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let J={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",J)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let J={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",J)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let J={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",J)}registerCompactAgent(){let J={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:[],deniedTools:[],maxIterations:3,filterHistory:!1},Q=this.agents.get("compact");if(Q){this.agents.set("compact",{...J,description:Q.description??J.description}),t.info("[AgentRegistry] Built-in compact agent overrode user-level definition (tool whitelist enforced: allowedTools=[])");return}this.agents.set("compact",J)}registerCompactHintAgent(){let J={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:[],deniedTools:[],maxIterations:3,filterHistory:!1},Q=this.agents.get("compact-hint");if(Q){this.agents.set("compact-hint",{...J,description:Q.description??J.description}),t.info("[AgentRegistry] Built-in compact-hint agent overrode user-level definition (tool whitelist enforced: allowedTools=[])");return}this.agents.set("compact-hint",J)}registerRoyAgent(){if(this.agents.has("roy"))return;let J={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","task_complete","task_cancel"]};this.agents.set("roy",J)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch($){return t.warn(`[AgentRegistry] Failed to load agents: ${$}`),0}}async loadFromDirectory($){let J=0;try{if(!this.fs.existsSync($))return t.debug(`[AgentRegistry] Config directory does not exist: ${$}`),0;let Q=await this.fsPromises.readdir($,{withFileTypes:!0});for(let X of Q){let q=U2($,X.name);if(X.isDirectory())continue;if(!nD(X.name))continue;try{let Y=await this.fsPromises.readFile(q,"utf-8"),G=this.parseAgentConfig(Y,q);if(G)this.agents.set(G.name,G),t.info(`[AgentRegistry] Loaded agent: ${G.name} from ${X.name}`),J++}catch(Y){t.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${Y}`)}}t.info(`[AgentRegistry] Loaded ${J} agents from ${$}`)}catch(Q){t.warn(`[AgentRegistry] Error reading config directory: ${Q}`)}return J}parseAgentConfig($,J){try{let Q=w8.default.parse($),X=Z8.safeParse(Q);if(!X.success)return t.warn(`[AgentRegistry] Invalid agent config: ${J}`,{errors:X.error.errors}),null;return X.data}catch(Q){return t.error(`[AgentRegistry] Failed to parse agent config: ${J}`,{error:Q}),null}}async saveAgent($){try{let J=Z8.safeParse($);if(!J.success)return t.error(`[AgentRegistry] Invalid agent config for "${$.name}": ${J.error.message}`),!1;await this.ensureConfigDir();let Q=this.agentToYaml($),X=U2(this.configDir,`${$.name}.yaml`);return await this.fsPromises.writeFile(X,Q,"utf-8"),this.agents.set($.name,$),t.info(`[AgentRegistry] Saved agent: ${$.name} to ${X}`),!0}catch(J){return t.error(`[AgentRegistry] Failed to save agent: ${$.name}`,{error:J}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),t.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml($){let J={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 w8.default.stringify(J).trimEnd()+`
2451
+ `}async deleteAgent($){if(!this.agents.get($))return t.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=U2(this.configDir,`${$}.yaml`);if(this.fs.existsSync(Q))await this.fsPromises.unlink(Q),t.info(`[AgentRegistry] Deleted agent file: ${Q}`);return this.agents.delete($),!0}catch(Q){return t.error(`[AgentRegistry] Failed to delete agent: ${$}`,{error:Q}),!1}}exportAgents($={}){let J=this.list();if($.format==="json")return J;return J}exportAgentsAsJson(){return JSON.stringify(this.list(),null,2)}size(){return this.agents.size}configDirExists(){return this.fs.existsSync(this.configDir)}getAgentFilePath($){return U2(this.configDir,`${$}.yaml`)}}k([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],R0.prototype,"register",null);k([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],R0.prototype,"unregister",null);k([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],R0.prototype,"clear",null);k([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],R0.prototype,"getSystemPrompt",null);k([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],R0.prototype,"getWorkflowName",null);k([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],R0.prototype,"getEntryAgent",null);k([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],R0.prototype,"registerWorkflowRunner",null);k([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],R0.prototype,"registerTaskOrganizer",null);k([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],R0.prototype,"registerWorkflowCreator",null);k([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],R0.prototype,"load",null);k([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],R0.prototype,"loadFromDirectory",null);function nD($){return $.endsWith(".yaml")||$.endsWith(".yml")}var P8=`You are a subagent created by the main agent to handle a specific task.
2452
2452
 
2453
2453
  ## Your Role
2454
2454
  - You were created to handle: {task_description}
@@ -2465,14 +2465,17 @@ task_operation_create({
2465
2465
  ## Execution
2466
2466
  - Use the available tools to complete the task
2467
2467
  - If you need more information, ask the main agent through the result
2468
- - Return a clear summary of what you did and the results`;import{AsyncLocalStorage as mD}from"async_hooks";var uD=new mD;function A8($,J){return uD.run($,J)}import{AsyncLocalStorage as lD}from"async_hooks";var Z8=()=>{};function W2(){return i2.getStore()}function M9(){return i2.getStore()||{}}function n2(){return i2.getStore()?.agentContext?.currentTaskId}function B3($){return typeof $==="number"&&Number.isInteger($)&&$>0?$:void 0}var U3,i2,cD,r2,B$=a(()=>{n(),V0(),Z8(),U3=i("env:context:env-context"),i2=new lD,cD=B0(function(J,Q){return B3(J?.metadata?.parentTaskId)??B3(Q?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:($)=>({parentTaskId:$??null})}),r2=B0(function(J){let Q=n2(),X=i2.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=J}U3.info(`[setCurrentTaskId] taskId=${J??"undefined"} (was: ${Q??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var O9=a(()=>{B$(),Z8()});class K9{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor($={}){this.componentName=$.componentName??"unknown",this.componentVersion=$.componentVersion??"0.0.0",this.defaultPriority=$.defaultPriority??0}register($,J){this.getOrCreateHooks($).push(J)}registerMany($,J){this.getOrCreateHooks($).push(...J)}unregister($,J){let Q=this._hooks.get($);if(!Q)return!1;let X=Q.findIndex((Y)=>Y.name===J);if(X===-1)return!1;return Q.splice(X,1),!0}unregisterAll($){this._hooks.delete($)}async execute($,J,Q={}){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 G=W2();if(Y){if(console.error(`[DEBUG hook-manager.execute] envContext=${G?"present":"absent"}`),G)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(G.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${G.sourceId}`)}if(G){if(Q.envContext=G,!Q.pluginEnabled&&G.pluginEnabled)Q.pluginEnabled=G.pluginEnabled}let q=this.sortHooks(X),W=this.createContext($,J,Q,"before"),z=Q.pluginEnabled||{};if(Y){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(z)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${q.length}:`);for(let H of q)console.error(`[DEBUG hook-manager.execute] - name=${H.name} pluginName=${H.pluginName} sourceId=${H.sourceId}`)}for(let H of q){if(H.pluginName&&H.sourceId){let B=`${H.sourceId}:${H.pluginName}`,U=z[B];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${H.name} (${B}) enabled=${U}`);if(U!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${B}] !== true, got ${JSON.stringify(U)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${H.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${H.name}`);await this.safeExecute(H,W)}}async executeAndCollect($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return[];let Y=this.sortHooks(X),G=this.createContext($,J,Q,"before"),q=[];for(let W of Y){let z=await this.safeExecuteAndReturn(W,G);if(z!==void 0)q.push(z)}return q}count($){return this._hooks.get($)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks($){return this.count($)>0}setComponentInfo($,J){this.componentName=$,this.componentVersion=J}get hooks(){return this._hooks}async executeWithIntervention($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return{stopped:!1,results:[]};let Y=this.sortHooks(X),G=this.createContext($,J,Q,"before"),q=[],W=!1,z;for(let H of Y){if(W)break;let B=await this.safeExecuteAndReturn(H,G);if(q.push(B),B&&typeof B==="object"&&"stopped"in B){let U=B;if(U.stopped)W=!0,z=U.action}}return{stopped:W,action:z,results:q}}getOrCreateHooks($){let J=this._hooks.get($);if(!J)J=[],this._hooks.set($,J);return J}sortHooks($){return[...$].sort((J,Q)=>{let X=J.priority??this.defaultPriority,Y=Q.priority??this.defaultPriority;return X-Y})}createContext($,J,Q,X){return{component:{name:this.componentName,version:this.componentVersion},data:J,metadata:Q,phase:X,hookPoint:$}}async safeExecute($,J){try{let Q=$.execute(J);if(Q&&typeof Q==="object"&&typeof Q.then==="function")await Q}catch(Q){console.error(`Hook "${$.name}" failed:`,Q)}}async safeExecuteAndReturn($,J){try{return await $.execute(J)}catch(Q){console.error(`Hook "${$.name}" failed:`,Q);return}}}var w8=a(()=>{O9()});function pD(){let $=S0.register.bind(S0);S0.register=function(J,Q){$(J,Q);let X=V3[J];if(X)$(X,Q)}}var S0,dD,iD,nD,V3,z2=a(()=>{w8(),S0=new K9,dD={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"},iD={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},nD={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"},V3={"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"},pD()});n();V0();O9();function rD($,J){if(S8($))return!0;return J?.hasAgent($)??!1}async function aD($,J={}){let X=(J.getBuiltIn??S8)($),Y=J.registry?.get($);if(!X&&!Y)return;if(Y)return sD($,Y,X,J.registry);return{subagentType:$,description:X.description,basePrompt:X.promptOverride||_8,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function sD($,J,Q,X){let Y=X?await X.getSystemPrompt($):J.systemPrompt;return{subagentType:$,description:J.description||Q?.description||"Custom agent",basePrompt:Y||Q?.promptOverride||_8,allowedTools:J.allowedTools??Q?.allowedTools,deniedTools:J.deniedTools??Q?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function oD($){return`
2468
+ - Return a clear summary of what you did and the results`;import{AsyncLocalStorage as rD}from"async_hooks";var aD=new rD;function b8($,J){return aD.run($,J)}import{AsyncLocalStorage as sD}from"async_hooks";var E8=()=>{};function F$(){return t2.getStore()}function L9(){return t2.getStore()||{}}function e2(){return t2.getStore()?.agentContext?.currentTaskId}function KJ($){return typeof $==="number"&&Number.isInteger($)&&$>0?$:void 0}var jJ,t2,oD,$6,M$=s(()=>{i(),D0(),E8(),jJ=d("env:context:env-context"),t2=new sD,oD=H0(function(J,Q){return KJ(J?.metadata?.parentTaskId)??KJ(Q?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:($)=>({parentTaskId:$??null})}),$6=H0(function(J){let Q=e2(),X=t2.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=J}jJ.info(`[setCurrentTaskId] taskId=${J??"undefined"} (was: ${Q??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var N9=s(()=>{M$(),E8()});class A9{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor($={}){this.componentName=$.componentName??"unknown",this.componentVersion=$.componentVersion??"0.0.0",this.defaultPriority=$.defaultPriority??0}register($,J){this.getOrCreateHooks($).push(J)}registerMany($,J){this.getOrCreateHooks($).push(...J)}unregister($,J){let Q=this._hooks.get($);if(!Q)return!1;let X=Q.findIndex((q)=>q.name===J);if(X===-1)return!1;return Q.splice(X,1),!0}unregisterAll($){this._hooks.delete($)}async execute($,J,Q={}){let X=this._hooks.get($),q=process.env.ROY_HOOK_DEBUG==="1";if(q)console.error(`[DEBUG hook-manager.execute] hookPoint=${$}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(q)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${$})`);return}let Y=F$();if(q){if(console.error(`[DEBUG hook-manager.execute] envContext=${Y?"present":"absent"}`),Y)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(Y.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${Y.sourceId}`)}if(Y){if(Q.envContext=Y,!Q.pluginEnabled&&Y.pluginEnabled)Q.pluginEnabled=Y.pluginEnabled}let G=this.sortHooks(X),W=this.createContext($,J,Q,"before"),z=Q.pluginEnabled||{};if(q){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(z)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${G.length}:`);for(let H of G)console.error(`[DEBUG hook-manager.execute] - name=${H.name} pluginName=${H.pluginName} sourceId=${H.sourceId}`)}for(let H of G){if(H.pluginName&&H.sourceId){let B=`${H.sourceId}:${H.pluginName}`,U=z[B];if(q)console.error(`[DEBUG hook-manager.execute] hook ${H.name} (${B}) enabled=${U}`);if(U!==!0){if(q)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${B}] !== true, got ${JSON.stringify(U)})`);continue}}else if(q)console.error(`[DEBUG hook-manager.execute] hook ${H.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(q)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${H.name}`);await this.safeExecute(H,W)}}async executeAndCollect($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return[];let q=this.sortHooks(X),Y=this.createContext($,J,Q,"before"),G=[];for(let W of q){let z=await this.safeExecuteAndReturn(W,Y);if(z!==void 0)G.push(z)}return G}count($){return this._hooks.get($)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks($){return this.count($)>0}setComponentInfo($,J){this.componentName=$,this.componentVersion=J}get hooks(){return this._hooks}async executeWithIntervention($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return{stopped:!1,results:[]};let q=this.sortHooks(X),Y=this.createContext($,J,Q,"before"),G=[],W=!1,z;for(let H of q){if(W)break;let B=await this.safeExecuteAndReturn(H,Y);if(G.push(B),B&&typeof B==="object"&&"stopped"in B){let U=B;if(U.stopped)W=!0,z=U.action}}return{stopped:W,action:z,results:G}}getOrCreateHooks($){let J=this._hooks.get($);if(!J)J=[],this._hooks.set($,J);return J}sortHooks($){return[...$].sort((J,Q)=>{let X=J.priority??this.defaultPriority,q=Q.priority??this.defaultPriority;return X-q})}createContext($,J,Q,X){return{component:{name:this.componentName,version:this.componentVersion},data:J,metadata:Q,phase:X,hookPoint:$}}async safeExecute($,J){try{let Q=$.execute(J);if(Q&&typeof Q==="object"&&typeof Q.then==="function")await Q}catch(Q){console.error(`Hook "${$.name}" failed:`,Q)}}async safeExecuteAndReturn($,J){try{return await $.execute(J)}catch(Q){console.error(`Hook "${$.name}" failed:`,Q);return}}}var S8=s(()=>{N9()});function tD(){let $=T0.register.bind(T0);T0.register=function(J,Q){$(J,Q);let X=LJ[J];if(X)$(X,Q)}}var T0,eD,$F,JF,LJ,V2=s(()=>{S8(),T0=new A9,eD={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"},$F={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},JF={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"},LJ={"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"},tD()});i();D0();N9();var QF="## \u6E20\u9053\u4EA4\u4ED8\u63D0\u793A\uFF08\u5F53\u524D\u4F1A\u8BDD\u6765\u81EA\u5916\u90E8\u6E20\u9053\uFF09";function XF($){if(!$)return;let J;if($==="lark-cli"||$.startsWith("lark"))J=["- \u89E6\u53D1\u6E20\u9053\u662F**\u98DE\u4E66**\u3002\u6587\u6863\u7C7B\u4EA7\u51FA\uFF08\u8C03\u7814\u6587\u6863 / \u62A5\u544A / PPT / doc \u7B49\uFF09"," \u5FC5\u987B\u7528**\u98DE\u4E66\u4E91\u76D8**\u5B58\u50A8\uFF1A`lark-cli docs +create --title <\u6807\u9898> --markdown @<\u672C\u5730md>`\uFF0C\u7528\u5B8C\u5373\u5F03\u3002","- \u4EA4\u4ED8\u65F6\u53EA\u7ED9**\u4E91\u76D8\u94FE\u63A5**\uFF08https://my.feishu.cn/...\uFF09\uFF0C**\u4E0D\u843D\u672C\u5730\u8DEF\u5F84**\u4EA4\u4ED8\u3002"," \u672C\u5730\u8DEF\u5F84\u53EA\u4F5C\u4E2D\u8F6C\uFF08\u751F\u6210 md \u2192 \u4E0A\u4F20\u4E91\u76D8 \u2192 \u56DE\u590D\u91CC\u8D34\u4E91\u76D8\u94FE\u63A5\uFF09\uFF0C\u4E0D\u4F5C\u4E3A\u4EA4\u4ED8\u7269\u3002"].join(`
2469
+ `);else if($==="wecom-cli"||$.startsWith("wecom"))J=["- \u89E6\u53D1\u6E20\u9053\u662F**\u4F01\u4E1A\u5FAE\u4FE1**\u3002\u6587\u6863\u7C7B\u4EA7\u51FA\uFF08\u8C03\u7814\u6587\u6863 / docs / ppt \u7B49\uFF09"," \u5FC5\u987B\u4E0A\u4F20\u5230**\u4F01\u5FAE\u6587\u6863**\uFF0C\u94FE\u63A5\u4F5C\u4E3A\u4EA4\u4ED8\u7269\uFF1A"," - \u5728\u7EBF\u6587\u6863\uFF1A`wecom-cli doc create --doc-name <\u6807\u9898> --doc-type doc --content-type text --file-path <\u672C\u5730md>`"," - \u5FAE\u76D8\u6587\u4EF6\uFF1A`wecom-cli disk files upload --file-path <\u672C\u5730\u6587\u4EF6>`\uFF08\u9ED8\u8BA4\u4F20\u5230\u6211\u7684\u7A7A\u95F4\uFF09","- \u672C\u5730\u8DEF\u5F84\u53EA\u4F5C\u4E2D\u8F6C\uFF08\u751F\u6210 \u2192 \u4E0A\u4F20\u4F01\u5FAE\u6587\u6863 \u2192 \u56DE\u590D\u91CC\u8D34\u94FE\u63A5\uFF09\uFF0C**\u4E0D\u843D\u672C\u5730\u8DEF\u5F84**\u4EA4\u4ED8\u3002"].join(`
2470
+ `);if(!J)return;return[QF,"","\u901A\u7528\u63AA\u8F9E\uFF1A\u5F53\u524D\u4F1A\u8BDD\u6765\u81EA\u5916\u90E8\u6E20\u9053\uFF0C\u4EA4\u4ED8\u7C7B\u4EA7\u51FA\u4F18\u5148\u7528\u8BE5\u6E20\u9053\u7684\u539F\u751F\u5B58\u50A8/\u5C55\u793A\u65B9\u5F0F\uFF0C","\u4E0D\u8981\u628A\u672C\u5730\u6587\u4EF6\u8DEF\u5F84\u5F53\u4F5C\u4EA4\u4ED8\u7269\uFF08\u6E20\u9053\u7528\u6237\u65E0\u6CD5\u8BBF\u95EE\u672C\u673A\u6587\u4EF6\u7CFB\u7EDF\uFF09\u3002","",J].join(`
2471
+ `)}function qF($,J){if(T8($))return!0;return J?.hasAgent($)??!1}async function YF($,J={}){let X=(J.getBuiltIn??T8)($),q=J.registry?.get($);if(!X&&!q)return;if(q)return GF($,q,X,J.registry);return{subagentType:$,description:X.description,basePrompt:X.promptOverride||P8,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function GF($,J,Q,X){let q=X?await X.getSystemPrompt($):J.systemPrompt;return{subagentType:$,description:J.description||Q?.description||"Custom agent",basePrompt:q||Q?.promptOverride||P8,allowedTools:J.allowedTools??Q?.allowedTools,deniedTools:J.deniedTools??Q?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function WF($){return`
2469
2472
  ## Agent Selection Guide
2470
2473
 
2471
2474
  - Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
2472
2475
  ${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
2473
- - For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function tD($){let J=b8.map((q)=>`- ${q.id}: ${q.description}`),X=($?.list()??[]).filter((q)=>!b8.some((W)=>W.id===q.name)).map((q)=>{if(q.type==="workflow"){let W=q.workflow?` (workflow: ${q.workflow})`:"";return`- ${q.name}: ${q.description||"Workflow agent"}${W}`}return`- ${q.name}: ${q.description||"Custom agent"}`}),Y=[...J,...X],G=oD({hasCustomAgents:X.length>0});return Y.join(`
2474
- `)+G}z2();var eD=[/\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 $F($){let J=$;for(let Q of eD)J=J.replace(Q,"<redacted>");return J}function JF($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function D3($,J){return JF($F($),J)}class E8{maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor($={}){this.maxEntries=$.maxEntries??500,this.ttlMs=$.ttlMs??86400000,this.maxDescriptionChars=$.maxDescriptionChars??240}record($,J={}){let Q=new Date().toISOString(),X=this.toRecord($,J,Q);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update($,J){let Q=this.records.get($.id);if(!Q)return;let X=new Date().toISOString();this.records.delete($.id);let Y={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove($){let J=this.records.get($);if(!J)return!1;if(this.records.delete($),J.parentTaskId!==void 0){let Q=this.childrenIndex.get(J.parentTaskId);if(Q?.delete($),Q&&Q.size===0)this.childrenIndex.delete(J.parentTaskId)}return!0}getById($){let J=this.records.get($);if(!J)return;if(Date.now()-Date.parse(J.updatedAt)>this.ttlMs){this.remove($);return}return J}peekById($){return this.records.get($)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent($={}){let J=$.limit??10,Q=$.statuses,X=new Set($.excludeIds??[]),Y=$.excludeAncestorOf??$.excludeSelfOrDescendant,G=Y?this.collectSubtree(Y):new Set,q=$.sinceHours?Date.now()-$.sinceHours*60*60*1000:0,W=Date.now(),z=new Set([...X,...G]),H=[];for(let B of this.records.values()){if(W-Date.parse(B.updatedAt)>this.ttlMs)continue;if(q>0&&Date.parse(B.updatedAt)<q)continue;if(z.has(B.taskId))continue;if($.scope){if($.scope.sessionId!==void 0&&B.source.sessionId!==$.scope.sessionId)continue;if($.scope.parentSessionId!==void 0&&B.source.parentSessionId!==$.scope.parentSessionId)continue;if($.scope.subagentType!==void 0&&B.source.subagentType!==$.scope.subagentType)continue}if(Q){if(!Q.includes(B.status))continue}else if(B.status==="archived")continue;H.push(B)}if($.activeChildFirst){let B=new Map;for(let U of H)B.set(U.taskId,this.hasActiveChild(U.taskId));H.sort((U,V)=>{let O=B.get(U.taskId)?1:0,F=B.get(V.taskId)?1:0;if(O!==F)return F-O;let D=Date.parse(V.updatedAt)-Date.parse(U.updatedAt);if(D!==0)return D;return V.taskId-U.taskId})}else H.sort((B,U)=>{let V=Date.parse(U.updatedAt)-Date.parse(B.updatedAt);if(V!==0)return V;return U.taskId-B.taskId});return H.slice(0,J)}getSubtreeSummary($,J={}){let Q=J.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($),G=Y?Array.from(Y):[],q=G.length>0?1:0;X.maxDepth=q;let W=G;while(W.length>0){let z=[];for(let H of W){let B=this.records.get(H);if(!B)continue;if(!Q&&B.status==="archived")continue;if(X.descendantCount++,B.status==="active")X.activeCount++;else if(B.status==="completed")X.completedCount++;let U=this.childrenIndex.get(H);if(U&&U.size>0)for(let V of U)z.push(V)}if(z.length>0)q++,X.maxDepth=q;W=z}return X}hasActiveChild($){let J=this.childrenIndex.get($);if(!J)return!1;for(let Q of J){let X=this.records.get(Q);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord($,J,Q){let X=this.safeParseContext($.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:D3($.description||"",this.maxDescriptionChars),goals:D3($.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:$.tags??[],status:$.status,priority:$.priority,type:$.type,parentTaskId:$.parent_task_id,source:J,createdAt:$.createdAt||Q,updatedAt:$.updatedAt||Q,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 J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}pickString($,J){if(!$)return;let Q=$[J];return typeof Q==="string"?Q: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 J={},Q=E8.STRIPPED_KEYS;for(let[X,Y]of Object.entries($)){let G=X.toLowerCase();if(Q.some((q)=>G.includes(q)))continue;J[X]=this.stripSensitiveKeys(Y)}return J}upsert($){this.records.set($.taskId,$)}indexParentChild($){if($.parentTaskId===void 0||$.parentTaskId===null)return;let J=$.parentTaskId,Q=this.childrenIndex.get(J);if(!Q)Q=new Set,this.childrenIndex.set(J,Q);Q.add($.taskId)}collectSubtree($){let J=new Set([$]),Q=[$];while(Q.length>0){let X=Q.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let G of Y)if(!J.has(G))J.add(G),Q.push(G)}return J}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let $=this.records.size-this.maxEntries,J=Array.from(this.records.keys()).slice(0,$);for(let Q of J)this.remove(Q)}}n();var R9=i("registry-hook-installer");function QF($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,G=Q.priority??100,q=!1,W=(D,M)=>{try{J.record(D,M)}catch(R){R9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},z=(D,M)=>{try{J.update(D,M)}catch(R){R9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},H=(D)=>{try{J.remove(D)}catch(M){R9.warn(`[registry-hook-installer] remove failed for task #${D}: ${M instanceof Error?M.message:String(M)}`)}},B=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),U={name:`${Y}:after-create`,priority:G,execute:async(D)=>{let M=D.data;if(M?.task)W(M.task,B())}},V={name:`${Y}:after-update`,priority:G,execute:async(D)=>{let M=D.data;if(!M?.task)return;if(J.peekById(M.task.id))z(M.task,B());else W(M.task,B())}},O={name:`${Y}:after-complete`,priority:G,execute:async(D)=>{let M=D.data;if(M?.task)z(M.task,B())}},F={name:`${Y}:after-delete`,priority:G,execute:async(D)=>{let M=D.data;if(typeof M?.id==="number")H(M.id)}};return $.registerHook(X0.AFTER_CREATE,U),$.registerHook(X0.AFTER_UPDATE,V),$.registerHook(X0.AFTER_COMPLETE,O),$.registerHook(X0.AFTER_DELETE,F),{uninstall(){if(q)return;q=!0,$.unregisterHook(X0.AFTER_CREATE,U.name),$.unregisterHook(X0.AFTER_UPDATE,V.name),$.unregisterHook(X0.AFTER_COMPLETE,O.name),$.unregisterHook(X0.AFTER_DELETE,F.name),R9.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}n();var P8=i("task-reuse-registry"),XF={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},F3=new WeakMap;function YF($){let J=F3.get($);if(J)return J.registry;let Q=new E8(XF),X={uninstall:()=>{}};try{let G=$.getComponent?.("task");if(G?.registerHook)X=QF(G,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),P8.debug("[task-reuse-registry] hook installed");else P8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(G){P8.warn(`[task-reuse-registry] hook install failed: ${G instanceof Error?G.message:String(G)}`)}let Y={registry:Q,installHandle:X};return F3.set($,Y),Q}var GF=[/\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 qF($){let J=$;for(let Q of GF)J=J.replace(Q,"<redacted>");return J}function M3($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function WF($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,Y=$.heading??"Recent task context (reuse candidates)",G=$.registry.recent({scope:$.scope,limit:J,statuses:$.statuses,excludeIds:$.similarTaskIds??[],excludeAncestorOf:$.excludeAncestorOf});if(G.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let q=[];q.push(`## ${Y}`),q.push(""),q.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."),q.push("");for(let z of G){if(q.push(`### Task #${z.taskId}: ${z.title}`),q.push(`- Status: ${z.status}`),z.parentTaskId!==void 0&&z.parentTaskId!==null)q.push(`- Parent: #${z.parentTaskId}`);if(z.source.subagentType)q.push(`- Created by: ${z.source.subagentType}`);if(q.push(`- Updated: ${z.updatedAt}`),z.project_path)q.push(`- Project: ${z.project_path}`);if(z.worktree_path)q.push(`- Worktree: ${z.worktree_path}`);if(z.branch)q.push(`- Branch: ${z.branch}`);if(z.parentBranch)q.push(`- Parent branch: ${z.parentBranch}`);let H;try{H=$.registry.getSubtreeSummary(z.taskId)}catch{H=void 0}if(H&&H.descendantCount>0)q.push(`- Children: ${H.descendantCount} (active: ${H.activeCount}, completed: ${H.completedCount}, max depth: ${H.maxDepth})`);let B=H!==void 0&&H.activeCount>0;if(z.status==="completed"&&B)q.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let U=qF(M3(z.description,X));if(U)q.push(`- Description: ${U}`);if(z.tags&&z.tags.length>0)q.push(`- Tags: ${z.tags.join(", ")}`);q.push("")}q.push("---"),q.push(""),q.push("### Reuse instructions"),q.push(""),q.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),q.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),q.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),q.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),q.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),q.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),q.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),q.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),q.push(""),q.push("### Decision matrix \u2014 three legal paths"),q.push(""),q.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),q.push("remains the default, but the matrix adds two new paths for independent work."),q.push(""),q.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),q.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),q.push("append description/goals. Do **not** create a new task id."),q.push(""),q.push("```"),q.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),q.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),q.push(' milestone_title: "Reopened for <new-scope>",'),q.push(' milestone_description: "<why this is the same work>" })'),q.push("```"),q.push(""),q.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),q.push("distinct: an independent bug fix, optimization, parallel delivery or"),q.push("independent acceptance item under the same feature. Create a child task so"),q.push("the audit trail is preserved. Always pair with an audit operation."),q.push(""),q.push("```");for(let z of G){let H=z.project_path??"<project_path>";q.push(`task_create(parent_task_id=${z.taskId}, title="<distinguishing title>", project_path="${H}", context=<inherit or override>)`);break}q.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),q.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),q.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),q.push("```"),q.push(""),q.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),q.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),q.push("should stay \u2264 ~10 to keep the tree readable."),q.push(""),q.push("```"),q.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),q.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),q.push(' milestone_title: "New root: <topic>",'),q.push(' milestone_description: "<why this is not a child of any existing task>" })'),q.push("```"),q.push(""),q.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),q.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),q.push("chosen. Use the appropriate `milestone_type`:"),q.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),q.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),q.push(" - new root \u2192 `create` (then `progress` per phase)"),q.push(""),q.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),q.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),q.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),q.push("tokens, secrets) are stripped automatically. Use the helper:"),q.push(""),q.push("```"),q.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),q.push("```"),q.push("");let W=q.join(`
2475
- `);if(W.length>Q)W=M3(W,Q);return{markdown:W,candidateIds:G.map((z)=>z.taskId),isEmpty:!1}}var y=i("task:delegate"),n0={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"},b8=[{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.
2476
+ - For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function zF($){let J=f8.map((G)=>`- ${G.id}: ${G.description}`),X=($?.list()??[]).filter((G)=>!f8.some((W)=>W.id===G.name)).map((G)=>{if(G.type==="workflow"){let W=G.workflow?` (workflow: ${G.workflow})`:"";return`- ${G.name}: ${G.description||"Workflow agent"}${W}`}return`- ${G.name}: ${G.description||"Custom agent"}`}),q=[...J,...X],Y=WF({hasCustomAgents:X.length>0});return q.join(`
2477
+ `)+Y}V2();var HF=[/\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 BF($){let J=$;for(let Q of HF)J=J.replace(Q,"<redacted>");return J}function UF($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function NJ($,J){return UF(BF($),J)}class I8{maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor($={}){this.maxEntries=$.maxEntries??500,this.ttlMs=$.ttlMs??86400000,this.maxDescriptionChars=$.maxDescriptionChars??240}record($,J={}){let Q=new Date().toISOString(),X=this.toRecord($,J,Q);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update($,J){let Q=this.records.get($.id);if(!Q)return;let X=new Date().toISOString();this.records.delete($.id);let q={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,q),this.childrenIndex.delete(q.taskId),this.indexParentChild(q),this.evictIfNeeded(),q}remove($){let J=this.records.get($);if(!J)return!1;if(this.records.delete($),J.parentTaskId!==void 0){let Q=this.childrenIndex.get(J.parentTaskId);if(Q?.delete($),Q&&Q.size===0)this.childrenIndex.delete(J.parentTaskId)}return!0}getById($){let J=this.records.get($);if(!J)return;if(Date.now()-Date.parse(J.updatedAt)>this.ttlMs){this.remove($);return}return J}peekById($){return this.records.get($)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent($={}){let J=$.limit??10,Q=$.statuses,X=new Set($.excludeIds??[]),q=$.excludeAncestorOf??$.excludeSelfOrDescendant,Y=q?this.collectSubtree(q):new Set,G=$.sinceHours?Date.now()-$.sinceHours*60*60*1000:0,W=Date.now(),z=new Set([...X,...Y]),H=[];for(let B of this.records.values()){if(W-Date.parse(B.updatedAt)>this.ttlMs)continue;if(G>0&&Date.parse(B.updatedAt)<G)continue;if(z.has(B.taskId))continue;if($.scope){if($.scope.sessionId!==void 0&&B.source.sessionId!==$.scope.sessionId)continue;if($.scope.parentSessionId!==void 0&&B.source.parentSessionId!==$.scope.parentSessionId)continue;if($.scope.subagentType!==void 0&&B.source.subagentType!==$.scope.subagentType)continue}if(Q){if(!Q.includes(B.status))continue}else if(B.status==="archived")continue;H.push(B)}if($.activeChildFirst){let B=new Map;for(let U of H)B.set(U.taskId,this.hasActiveChild(U.taskId));H.sort((U,V)=>{let O=B.get(U.taskId)?1:0,F=B.get(V.taskId)?1:0;if(O!==F)return F-O;let D=Date.parse(V.updatedAt)-Date.parse(U.updatedAt);if(D!==0)return D;return V.taskId-U.taskId})}else H.sort((B,U)=>{let V=Date.parse(U.updatedAt)-Date.parse(B.updatedAt);if(V!==0)return V;return U.taskId-B.taskId});return H.slice(0,J)}getSubtreeSummary($,J={}){let Q=J.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has($)&&!this.childrenIndex.has($))return X;let q=this.childrenIndex.get($),Y=q?Array.from(q):[],G=Y.length>0?1:0;X.maxDepth=G;let W=Y;while(W.length>0){let z=[];for(let H of W){let B=this.records.get(H);if(!B)continue;if(!Q&&B.status==="archived")continue;if(X.descendantCount++,B.status==="active")X.activeCount++;else if(B.status==="completed")X.completedCount++;let U=this.childrenIndex.get(H);if(U&&U.size>0)for(let V of U)z.push(V)}if(z.length>0)G++,X.maxDepth=G;W=z}return X}hasActiveChild($){let J=this.childrenIndex.get($);if(!J)return!1;for(let Q of J){let X=this.records.get(Q);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord($,J,Q){let X=this.safeParseContext($.context),q=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:NJ($.description||"",this.maxDescriptionChars),goals:NJ($.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:$.tags??[],status:$.status,priority:$.priority,type:$.type,parentTaskId:$.parent_task_id,source:J,createdAt:$.createdAt||Q,updatedAt:$.updatedAt||Q,operationCount:0,project_path:$.project_path,branch:this.pickString(q,"branch"),worktree_path:this.pickString(q,"worktree_path"),parentBranch:this.pickString(q,"parent_branch"),context:q}}safeParseContext($){if(!$||!$.trim())return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}pickString($,J){if(!$)return;let Q=$[J];return typeof Q==="string"?Q: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 J={},Q=I8.STRIPPED_KEYS;for(let[X,q]of Object.entries($)){let Y=X.toLowerCase();if(Q.some((G)=>Y.includes(G)))continue;J[X]=this.stripSensitiveKeys(q)}return J}upsert($){this.records.set($.taskId,$)}indexParentChild($){if($.parentTaskId===void 0||$.parentTaskId===null)return;let J=$.parentTaskId,Q=this.childrenIndex.get(J);if(!Q)Q=new Set,this.childrenIndex.set(J,Q);Q.add($.taskId)}collectSubtree($){let J=new Set([$]),Q=[$];while(Q.length>0){let X=Q.shift(),q=this.childrenIndex.get(X);if(!q)continue;for(let Y of q)if(!J.has(Y))J.add(Y),Q.push(Y)}return J}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let $=this.records.size-this.maxEntries,J=Array.from(this.records.keys()).slice(0,$);for(let Q of J)this.remove(Q)}}i();var _9=d("registry-hook-installer");function VF($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,q=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,Y=Q.priority??100,G=!1,W=(D,M)=>{try{J.record(D,M)}catch(j){_9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${j instanceof Error?j.message:String(j)}`)}},z=(D,M)=>{try{J.update(D,M)}catch(j){_9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${j instanceof Error?j.message:String(j)}`)}},H=(D)=>{try{J.remove(D)}catch(M){_9.warn(`[registry-hook-installer] remove failed for task #${D}: ${M instanceof Error?M.message:String(M)}`)}},B=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),U={name:`${q}:after-create`,priority:Y,execute:async(D)=>{let M=D.data;if(M?.task)W(M.task,B())}},V={name:`${q}:after-update`,priority:Y,execute:async(D)=>{let M=D.data;if(!M?.task)return;if(J.peekById(M.task.id))z(M.task,B());else W(M.task,B())}},O={name:`${q}:after-complete`,priority:Y,execute:async(D)=>{let M=D.data;if(M?.task)z(M.task,B())}},F={name:`${q}:after-delete`,priority:Y,execute:async(D)=>{let M=D.data;if(typeof M?.id==="number")H(M.id)}};return $.registerHook(q0.AFTER_CREATE,U),$.registerHook(q0.AFTER_UPDATE,V),$.registerHook(q0.AFTER_COMPLETE,O),$.registerHook(q0.AFTER_DELETE,F),{uninstall(){if(G)return;G=!0,$.unregisterHook(q0.AFTER_CREATE,U.name),$.unregisterHook(q0.AFTER_UPDATE,V.name),$.unregisterHook(q0.AFTER_COMPLETE,O.name),$.unregisterHook(q0.AFTER_DELETE,F.name),_9.debug(`[registry-hook-installer] uninstalled hooks (name=${q})`)}}}i();var C8=d("task-reuse-registry"),DF={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},AJ=new WeakMap;function FF($){let J=AJ.get($);if(J)return J.registry;let Q=new I8(DF),X={uninstall:()=>{}};try{let Y=$.getComponent?.("task");if(Y?.registerHook)X=VF(Y,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),C8.debug("[task-reuse-registry] hook installed");else C8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(Y){C8.warn(`[task-reuse-registry] hook install failed: ${Y instanceof Error?Y.message:String(Y)}`)}let q={registry:Q,installHandle:X};return AJ.set($,q),Q}var MF=[/\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 OF($){let J=$;for(let Q of MF)J=J.replace(Q,"<redacted>");return J}function _J($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function KF($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,q=$.heading??"Recent task context (reuse candidates)",Y=$.registry.recent({scope:$.scope,limit:J,statuses:$.statuses,excludeIds:$.similarTaskIds??[],excludeAncestorOf:$.excludeAncestorOf});if(Y.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let G=[];G.push(`## ${q}`),G.push(""),G.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."),G.push("");for(let z of Y){if(G.push(`### Task #${z.taskId}: ${z.title}`),G.push(`- Status: ${z.status}`),z.parentTaskId!==void 0&&z.parentTaskId!==null)G.push(`- Parent: #${z.parentTaskId}`);if(z.source.subagentType)G.push(`- Created by: ${z.source.subagentType}`);if(G.push(`- Updated: ${z.updatedAt}`),z.project_path)G.push(`- Project: ${z.project_path}`);if(z.worktree_path)G.push(`- Worktree: ${z.worktree_path}`);if(z.branch)G.push(`- Branch: ${z.branch}`);if(z.parentBranch)G.push(`- Parent branch: ${z.parentBranch}`);let H;try{H=$.registry.getSubtreeSummary(z.taskId)}catch{H=void 0}if(H&&H.descendantCount>0)G.push(`- Children: ${H.descendantCount} (active: ${H.activeCount}, completed: ${H.completedCount}, max depth: ${H.maxDepth})`);let B=H!==void 0&&H.activeCount>0;if(z.status==="completed"&&B)G.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let U=OF(_J(z.description,X));if(U)G.push(`- Description: ${U}`);if(z.tags&&z.tags.length>0)G.push(`- Tags: ${z.tags.join(", ")}`);G.push("")}G.push("---"),G.push(""),G.push("### Reuse instructions"),G.push(""),G.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),G.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),G.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),G.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),G.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),G.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),G.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),G.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),G.push(""),G.push("### Decision matrix \u2014 three legal paths"),G.push(""),G.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),G.push("remains the default, but the matrix adds two new paths for independent work."),G.push(""),G.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),G.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),G.push("append description/goals. Do **not** create a new task id."),G.push(""),G.push("```"),G.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),G.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),G.push(' milestone_title: "Reopened for <new-scope>",'),G.push(' milestone_description: "<why this is the same work>" })'),G.push("```"),G.push(""),G.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),G.push("distinct: an independent bug fix, optimization, parallel delivery or"),G.push("independent acceptance item under the same feature. Create a child task so"),G.push("the audit trail is preserved. Always pair with an audit operation."),G.push(""),G.push("```");for(let z of Y){let H=z.project_path??"<project_path>";G.push(`task_create(parent_task_id=${z.taskId}, title="<distinguishing title>", project_path="${H}", context=<inherit or override>)`);break}G.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),G.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),G.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),G.push("```"),G.push(""),G.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),G.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),G.push("should stay \u2264 ~10 to keep the tree readable."),G.push(""),G.push("```"),G.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),G.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),G.push(' milestone_title: "New root: <topic>",'),G.push(' milestone_description: "<why this is not a child of any existing task>" })'),G.push("```"),G.push(""),G.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),G.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),G.push("chosen. Use the appropriate `milestone_type`:"),G.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),G.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),G.push(" - new root \u2192 `create` (then `progress` per phase)"),G.push(""),G.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),G.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),G.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),G.push("tokens, secrets) are stripped automatically. Use the helper:"),G.push(""),G.push("```"),G.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),G.push("```"),G.push("");let W=G.join(`
2478
+ `);if(W.length>Q)W=_J(W,Q);return{markdown:W,candidateIds:Y.map((z)=>z.taskId),isEmpty:!1}}var g=d("task:delegate"),M0={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",SESSION_STARTED:"task.background.session_started"},f8=[{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.
2476
2479
 
2477
2480
  ## Your Role
2478
2481
  - You were created to handle: {task_description}
@@ -2523,7 +2526,7 @@ ${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
2523
2526
  ## Execution
2524
2527
  - Use the available tools to complete the task
2525
2528
  - If you need more information, ask the main agent through the result
2526
- - 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:z4.roy,deniedTools:["delegate_task","stop_task","task_complete","task_cancel"]}];function S8($){return b8.find((J)=>J.id===$)}function zF($,J,Q,X,Y){let G=$.getRegistry?.();if(G){if(G.get(J)?.type==="workflow")return y.debug(`[delegate] Skipping registration for workflow agent: ${J}`),null}let q=$.getAgent(J);if(!q){let W={type:"sub",systemPrompt:Q};if(X?.allowedTools&&X.allowedTools.length>0)W.allowedTools=X.allowedTools;if(Y.length>0)W.deniedTools=Y;q=$.registerAgent(J,W),y.debug(`[delegate] Registered subagent: ${J}`)}return q}var O3=K.object({description:K.string().describe("A short (3-5 words) description of the task"),prompt:K.string().describe("The task for the agent to perform"),subagent_type:K.string().describe("The type of specialized agent to use for this task").default("general"),timeout:K.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:K.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:K.array(K.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:K.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:K.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 HF($){let{workflowName:J,originalPrompt:Q,description:X}=$;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
2529
+ - 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:V4.roy,deniedTools:["delegate_task","stop_task","task_complete","task_cancel"]}];function T8($){return f8.find((J)=>J.id===$)}function jF($){if(!Array.isArray($))return;let J=[];for(let Q of $){if(typeof Q!=="string")continue;let X=Q.trim();if(X.length===0)continue;if(!J.includes(X))J.push(X)}return J.length>0?J:void 0}function LF($,J,Q,X,q){let Y=$.getRegistry?.();if(Y){if(Y.get(J)?.type==="workflow")return g.debug(`[delegate] Skipping registration for workflow agent: ${J}`),null}let G=$.getAgent(J);if(!G){let W={type:"sub",systemPrompt:Q};if(X?.allowedTools&&X.allowedTools.length>0)W.allowedTools=X.allowedTools;if(q.length>0)W.deniedTools=q;G=$.registerAgent(J,W),g.debug(`[delegate] Registered subagent: ${J}`)}return G}var RJ=K.object({description:K.string().describe("A short (3-5 words) description of the task"),prompt:K.string().describe("The task for the agent to perform"),subagent_type:K.string().describe("The type of specialized agent to use for this task").default("general"),timeout:K.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:K.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:K.array(K.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:K.string().describe("\u26A0\uFE0F \u786C\u7EA6\u675F\uFF1A\u540C\u4E00\u4EFB\u52A1\u94FE\u7684\u7EED\u8DD1\u5FC5\u987B\u4F20\u6B64\u53C2\u6570\uFF08\u4ECE\u7EC8\u6001 notify \u7684\u300C\u5B50 session:\u300D\u884C"+"\u6216 delegate \u8FD4\u56DE\u7684\u300C\uD83D\uDD17 Sub-session:\u300D\u884C\u590D\u5236\uFF09\u3002"+"\u4EC5\u5F53\u65E7 session \u4E0A\u4E0B\u6587\u5DF2\u786E\u8BA4\u4E0D\u53EF\u6551\uFF08compact_session \u540E\u4ECD\u8D85\u9650 / \u8FED\u4EE3\u4E0A\u9650\u4E14\u65E0\u53EF\u590D\u7528\u65AD\u70B9\uFF09\u65F6\u624D\u7559\u7A7A\uFF1B"+"\u7559\u7A7A\u7B49\u4E8E\u4E22\u5F03\u5168\u90E8\u4E0A\u4E0B\u6587\uFF0C\u4ECE\u96F6\u5F00\u59CB\u3002").optional(),triggerEventId:K.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 NF($){let{workflowName:J,originalPrompt:Q,description:X}=$;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
2527
2530
 
2528
2531
  \u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${J}**\u3002
2529
2532
  \u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
@@ -2547,13 +2550,10 @@ ${Q}
2547
2550
  4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
2548
2551
 
2549
2552
  \u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
2550
- `}var BF=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),L9=1800000,UF=1200000;class J0{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($,J){if(!$||!J)return;let Q=this.workflowRunRegistries.get($);if(!Q)Q=new Set,this.workflowRunRegistries.set($,Q);Q.add(J)}detachWorkflowRun($,J){this.workflowRunRegistries.get($)?.delete(J)}replaceWorkflowRun($,J,Q){if(!$)return;let X=this.workflowRunRegistries.get($);if(!X)return;if(J)X.delete(J);if(Q)X.add(Q)}async propagateStopToWorkflowRuns($,J){let Q=this.workflowRunRegistries.get($);if(!Q||Q.size===0)return{runIds:[],stopResults:[]};let X=Array.from(Q);y.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${$}`);let Y=[];for(let G of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${G}`),Y.push({runId:G,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(G,J),Y.push({runId:G,success:!0})}catch(q){let W=q instanceof Error?q.message:String(q);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${G}) failed (likely already terminal): ${W}`),Y.push({runId:G,success:!1,error:W})}}return Q.clear(),{runIds:X,stopResults:Y}}finalizeTask($,J){if(!$)return;this.stopProgressReporter($),this.progressTimers.delete($);let Q=this.tasks.get($);if(Q){if(this.tasks.delete($),this.terminalTasks.size>=this.maxTerminalTasks){let G=this.terminalTasks.keys().next().value;if(G!==void 0)this.terminalTasks.delete(G)}this.terminalTasks.set($,Q)}let X=this.abortControllers.get($);if(X&&J!=="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)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${Y.size()}, reason=${J})`);y.debug(`[BackgroundTaskManager] finalizeTask taskId=${$} reason=${J}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let $=0;for(let[J,Q]of this.processRegistries)if(Q.size()===0)this.processRegistries.delete(J),$++;return $}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent($){try{if(J0.detectWorkflowShortcutCompat($))return y.info(`[BackgroundTaskManager] Compat rewrite: '${$}' \u2192 '${J0.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),J0.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.($);if(!X||X.type!=="workflow")return;return X.entryAgent??J0.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(J){y.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${$}: ${J}`);return}}static _detectWorkflowShortcutWrapped=B0(($)=>BF.has($),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat($){return J0._detectWorkflowShortcutWrapped($)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession($){if(!$)return;try{let Q=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.($);return typeof Q==="number"&&Q>0?Q:void 0}catch(J){y.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${$}: ${J instanceof Error?J.message:String(J)}`);return}}publishBackgroundEvent($,J,Q,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,Y){this.publishBackgroundEvent($,J,Q,X,Y)}static parseAskUserErrorFromMessage($){let J=$ 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,delivered:X.delivered===!0,rawErrorMessage:J}}let Q="__ASK_USER_ERROR__:";if(J.includes(Q))try{let X=J.substring(J.indexOf(Q)+Q.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,delivered:Y.delivered===!0,rawErrorMessage:J}}catch(X){return y.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask($){let{parentSessionId:J,description:Q,prompt:X,subagentType:Y,timeout:G,similarTaskIds:q,existingSubSessionId:W,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U}=$,V=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,O=this.getSessionComponent();if(!O)throw Error("SessionComponent not found");if(!await O.get(J))throw Error(`Parent session not found: ${J}`);let D;if(W){let f=await O.get(W);if(!f)throw Error(`Sub session not found for resume: ${W}`);let A=f?.metadata?.created_by;if(A&&A!=="subagent")y.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${A}); reusing anyway`);D=f;try{let S=f?.metadata??{};await O.update(W,{metadata:{...S,reused_sub_session:!0,reused_at:Date.now()}})}catch(S){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:S instanceof Error?S.message:String(S)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${V}`)}else{let f={subagent_type:Y,created_by:"subagent",task_description:Q},A=W2();if(A){if(A.messageId)f.messageId=A.messageId;let S=A.replyChannel;if(S?.messageId)f.larkMessageId=S.messageId;if(S?.chatId)f.chatId=S.chatId;if(S?.userId)f.larkUserId=S.userId;let x=S?.profile;if(x)f.larkProfile=x}if(z)f.triggerEventId=z;if(D=await O.create({title:`${Q} (@${Y} subagent)`,parentSessionId:J,metadata:f}),!D)throw Error("Failed to create sub-session")}let M=MF(),R=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=${V}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let L=new G4;this.processRegistries.set(V,L);let N=Date.now(),Z=`${Y}:bg_${V}`,b={id:V,runId:Z,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:Y,status:"pending",createdAt:N,lastUpdatedAt:N,timeoutMs:G||L9,abortController:R,similarTaskIds:q,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U,replyChannel:M};this.tasks.set(V,b),this.abortControllers.set(V,R);let w={backgroundTaskId:V,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:Y,startedAt:N,timeoutMs:G||L9};return this.publishBackgroundEvent(n0.STARTED,w,J,z,M),this.executeTask(V,X,G,J).catch((f)=>{y.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:V,error:f instanceof Error?f.message:String(f)})}),{taskId:V,subSessionId:D.id}}async executeTask($,J,Q,X){let Y=this.tasks.get($);if(!Y){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let G=Date.now();Y.status="running",Y.startedAt=G,Y.lastUpdatedAt=G;let q=Q||L9,W=this.abortControllers.get($);this.startProgressReporter($,X||Y.parentSessionId);try{let H=await this.getSessionComponent().get(Y.subSessionId);if(!H)throw Error(`Sub session not found: ${Y.subSessionId}`);let B=this.processRegistries.get($),U=await this.executeWithAbort(H,J,q,$,W?.signal,Y.similarTaskIds,B,()=>W?.abort(),Y.subagentType);if(W?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();Y.status="completed",Y.completedAt=V,Y.lastUpdatedAt=V,Y.result=U;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId),Y.associatedTaskId===void 0)Y.associatedTaskId=n2();let F={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(n0.COMPLETED,F,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:O})}catch(z){let H=z instanceof Error?z.message:String(z),B=J0.parseAskUserErrorFromMessage(z),U=H.toLowerCase().includes("stopped")||H.toLowerCase().includes("aborted"),V=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId),Y.associatedTaskId===void 0)Y.associatedTaskId=n2();if(B){Y.status="awaiting-user",Y.error=B.rawErrorMessage,Y.pendingAskUserQuery=B.query;let F={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:B.query,sessionId:B.sessionId,nodeId:B.nodeId,nodeType:B.nodeType,agentSessionId:B.agentSessionId,delivered:B.delivered===!0,error:B.rawErrorMessage,executionTimeMs:V,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(n0.ASK_USER,F,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:Y.subSessionId,nodeId:B.nodeId,queryPreview:B.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(U){Y.status="stopped";let F={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:H,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(n0.STOPPED,F,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(H.startsWith("Task execution timeout after")){Y.status="timeout";let F={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:H,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(n0.TIMEOUT,F,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let F={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:H,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(n0.FAILED,F,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=H,y.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:Y.status,error:H})}finally{this.finalizeTask($,Y.status);let z=Y?._preserveSubSessionOnExit===!0,H=this.getSessionComponent();if(!z&&H?.endSessionCleanup&&Y?.subSessionId)try{await H.endSessionCleanup(Y.subSessionId)}catch(B){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:B instanceof Error?B.message:String(B)})}else if(z)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let Y=n2();if(Y!==void 0&&X.associatedTaskId===void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let G={backgroundTaskId:$,subSessionId:X.subSessionId,parentSessionId:J,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(n0.PROGRESS,G,J,X.triggerEventId,X.replyChannel)},UF);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,Y,G,q,W,z){let H=$?.metadata??{},B=H.task_id,U=H.task_description||"",V=$.id,O=H.subagent_type,F=O||z||"general";if(!O&&!z)y.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${V}`);let D=this.env?.getComponent?.("agent"),M=D?.getRegistry?.(),R=await aD(F,{registry:M}),L=S8(F),N=R?.basePrompt||L?.promptOverride||"You are a subagent. Complete this task: {task_description}",Z=R?.deniedTools||L?.deniedTools||[],b=R?.allowedTools||L?.allowedTools,w=N.replace(/{task_description}/g,U||"N/A");if(w+=`
2551
-
2552
- ---
2553
-
2554
- # Session Info
2553
+ `}var AF=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),R9=1800000,_F=1200000;class Q0{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($,J){if(!$||!J)return;let Q=this.workflowRunRegistries.get($);if(!Q)Q=new Set,this.workflowRunRegistries.set($,Q);Q.add(J)}detachWorkflowRun($,J){this.workflowRunRegistries.get($)?.delete(J)}replaceWorkflowRun($,J,Q){if(!$)return;let X=this.workflowRunRegistries.get($);if(!X)return;if(J)X.delete(J);if(Q)X.add(Q)}async propagateStopToWorkflowRuns($,J){let Q=this.workflowRunRegistries.get($);if(!Q||Q.size===0)return{runIds:[],stopResults:[]};let X=Array.from(Q);g.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${$}`);let q=[];for(let Y of X){if(typeof this.workflowService?.stopRun!=="function"){g.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${Y}`),q.push({runId:Y,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(Y,J),q.push({runId:Y,success:!0})}catch(G){let W=G instanceof Error?G.message:String(G);g.warn(`[BackgroundTaskManager] workflowService.stopRun(${Y}) failed (likely already terminal): ${W}`),q.push({runId:Y,success:!1,error:W})}}return Q.clear(),{runIds:X,stopResults:q}}finalizeTask($,J){if(!$)return;this.stopProgressReporter($),this.progressTimers.delete($);let Q=this.tasks.get($);if(Q){if(this.tasks.delete($),this.terminalTasks.size>=this.maxTerminalTasks){let Y=this.terminalTasks.keys().next().value;if(Y!==void 0)this.terminalTasks.delete(Y)}this.terminalTasks.set($,Q)}let X=this.abortControllers.get($);if(X&&J!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete($),this.workflowRunRegistries.delete($);let q=this.processRegistries.get($);if(q&&q.size()>0)g.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${q.size()}, reason=${J})`);g.debug(`[BackgroundTaskManager] finalizeTask taskId=${$} reason=${J}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let $=0;for(let[J,Q]of this.processRegistries)if(Q.size()===0)this.processRegistries.delete(J),$++;return $}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent($){try{if(Q0.detectWorkflowShortcutCompat($))return g.info(`[BackgroundTaskManager] Compat rewrite: '${$}' \u2192 '${Q0.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),Q0.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.($);if(!X||X.type!=="workflow")return;return X.entryAgent??Q0.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(J){g.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${$}: ${J}`);return}}static _detectWorkflowShortcutWrapped=H0(($)=>AF.has($),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat($){return Q0._detectWorkflowShortcutWrapped($)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession($){if(!$)return;try{let Q=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.($);return typeof Q==="number"&&Q>0?Q:void 0}catch(J){g.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${$}: ${J instanceof Error?J.message:String(J)}`);return}}publishBackgroundEvent($,J,Q,X,q,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...q?{replyChannel:q}:{},...Y?{pluginEnabled:Y}:{}}}),g.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:q?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,q,Y){this.publishBackgroundEvent($,J,Q,X,q,Y)}static parseAskUserErrorFromMessage($){let J=$ 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,delivered:X.delivered===!0,rawErrorMessage:J}}let Q="__ASK_USER_ERROR__:";if(J.includes(Q))try{let X=J.substring(J.indexOf(Q)+Q.length),q=JSON.parse(X);return{query:q.query,sessionId:q.sessionId,nodeId:q.nodeId,nodeType:q.nodeType||"agent",agentSessionId:q.agentSessionId,delivered:q.delivered===!0,rawErrorMessage:J}}catch(X){return g.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask($){let{parentSessionId:J,description:Q,prompt:X,subagentType:q,timeout:Y,similarTaskIds:G,existingSubSessionId:W,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U,systemPrompt:V,extendTools:O}=$,F=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,D=this.getSessionComponent();if(!D)throw Error("SessionComponent not found");if(!await D.get(J))throw Error(`Parent session not found: ${J}`);let j;if(W){let y=await D.get(W);if(!y)throw Error(`Sub session not found for resume: ${W}`);let n=y?.metadata?.created_by;if(n&&n!=="subagent")g.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${n}); reusing anyway`);j=y;try{let C=y?.metadata??{};await D.update(W,{metadata:{...C,reused_sub_session:!0,reused_at:Date.now()}})}catch(C){g.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:C instanceof Error?C.message:String(C)})}g.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${F}`)}else{let y={subagent_type:q,created_by:"subagent",task_description:Q},n=F$();if(n){if(n.messageId)y.messageId=n.messageId;let C=n.replyChannel;if(C?.messageId)y.larkMessageId=C.messageId;if(C?.chatId)y.chatId=C.chatId;if(C?.userId)y.larkUserId=C.userId;let r=C?.profile;if(r)y.larkProfile=r;let h0=C?.type;if(h0)y.channelType=h0}if(z)y.triggerEventId=z;if(j=await D.create({title:`${Q} (@${q} subagent)`,parentSessionId:J,metadata:y}),!j)throw Error("Failed to create sub-session")}let L=PF(),A=EF(),R=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=${F}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let b=new H4;this.processRegistries.set(F,b);let w=Date.now(),T=`${q}:bg_${F}`,Z={id:F,runId:T,subSessionId:j.id,parentSessionId:J,description:Q,subagentType:q,status:"pending",createdAt:w,lastUpdatedAt:w,timeoutMs:Y||R9,abortController:R,similarTaskIds:G,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U,systemPrompt:V,extendTools:O,replyChannel:L,pluginEnabledSnapshot:A};this.tasks.set(F,Z),this.abortControllers.set(F,R);let I={backgroundTaskId:F,subSessionId:j.id,parentSessionId:J,description:Q,subagentType:q,startedAt:w,timeoutMs:Y||R9};return this.publishBackgroundEvent(M0.STARTED,I,J,z,L,Z.pluginEnabledSnapshot),this.publishBackgroundEvent(M0.SESSION_STARTED,{backgroundTaskId:F,subSessionId:j.id,parentSessionId:J,description:Q,subagentType:q,associatedTaskId:void 0,lifecycle:"running",startedAt:w},J,z,L,Z.pluginEnabledSnapshot),this.executeTask(F,X,Y,J).catch((y)=>{g.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:F,error:y instanceof Error?y.message:String(y)})}),{taskId:F,subSessionId:j.id}}async executeTask($,J,Q,X){let q=this.tasks.get($);if(!q){g.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let Y=Date.now();q.status="running",q.startedAt=Y,q.lastUpdatedAt=Y;let G=Q||R9,W=this.abortControllers.get($);this.startProgressReporter($,X||q.parentSessionId);try{let H=await this.getSessionComponent().get(q.subSessionId);if(!H)throw Error(`Sub session not found: ${q.subSessionId}`);let B=this.processRegistries.get($),U=await this.executeWithAbort(H,J,G,$,W?.signal,q.similarTaskIds,B,()=>W?.abort(),q.subagentType);if(W?.signal.aborted){g.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();q.status="completed",q.completedAt=V,q.lastUpdatedAt=V,q.result=U;let O=q.completedAt-q.startedAt;if(q.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(q.subSessionId),q.associatedTaskId===void 0)q.associatedTaskId=e2();this.publishBackgroundEvent(M0.SESSION_STARTED,{backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,description:q.description,subagentType:q.subagentType,associatedTaskId:q.associatedTaskId,lifecycle:"completed",executionTimeMs:O},X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot);let F={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,status:"completed",result:q.result,description:q.description,executionTimeMs:O,associatedTaskId:q.associatedTaskId};this.publishBackgroundEvent(M0.COMPLETED,F,X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot),g.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:O})}catch(z){let H=z instanceof Error?z.message:String(z),B=Q0.parseAskUserErrorFromMessage(z),U=H.toLowerCase().includes("stopped")||H.toLowerCase().includes("aborted"),V=q.startedAt?Date.now()-q.startedAt:0,O=Date.now();if(q.completedAt=O,q.lastUpdatedAt=O,q.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(q.subSessionId),q.associatedTaskId===void 0)q.associatedTaskId=e2();if(B){q.status="awaiting-user",q.error=B.rawErrorMessage,q.pendingAskUserQuery=B.query;let F={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,subagentType:q.subagentType,description:q.description,query:B.query,sessionId:B.sessionId,nodeId:B.nodeId,nodeType:B.nodeType,agentSessionId:B.agentSessionId,delivered:B.delivered===!0,error:B.rawErrorMessage,executionTimeMs:V,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(subagent_type="${q.subagentType}", sub_session_id="${q.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:q.associatedTaskId};this.publishBackgroundEvent(M0.ASK_USER,F,X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot),g.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:q.subSessionId,nodeId:B.nodeId,queryPreview:B.query.substring(0,80)}),q._preserveSubSessionOnExit=!0;return}if(U){q.status="stopped";let F={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,status:"stopped",description:q.description,error:H,executionTimeMs:V,associatedTaskId:q.associatedTaskId};this.publishBackgroundEvent(M0.STOPPED,F,X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot),this.publishBackgroundEvent(M0.SESSION_STARTED,{backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,description:q.description,subagentType:q.subagentType,associatedTaskId:q.associatedTaskId,lifecycle:"stopped",executionTimeMs:V},X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot)}else if(H.startsWith("Task execution timeout after")){q.status="timeout";let F={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,status:"timeout",description:q.description,error:H,executionTimeMs:V,associatedTaskId:q.associatedTaskId};this.publishBackgroundEvent(M0.TIMEOUT,F,X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot),this.publishBackgroundEvent(M0.SESSION_STARTED,{backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,description:q.description,subagentType:q.subagentType,associatedTaskId:q.associatedTaskId,lifecycle:"timeout",executionTimeMs:V},X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot)}else{q.status="failed";let F={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,status:"failed",error:H,executionTimeMs:V,associatedTaskId:q.associatedTaskId};this.publishBackgroundEvent(M0.FAILED,F,X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot),this.publishBackgroundEvent(M0.SESSION_STARTED,{backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:X||q.parentSessionId,description:q.description,subagentType:q.subagentType,associatedTaskId:q.associatedTaskId,lifecycle:"failed",executionTimeMs:V},X||q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot)}q.error=H,g.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:q.status,error:H})}finally{this.finalizeTask($,q.status);let z=q?._preserveSubSessionOnExit===!0,H=this.getSessionComponent();if(!z&&H?.endSessionCleanup&&q?.subSessionId)try{await H.endSessionCleanup(q.subSessionId)}catch(B){g.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${q.subSessionId}`,{error:B instanceof Error?B.message:String(B)})}else if(z)g.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${q.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let q=e2();if(q!==void 0&&X.associatedTaskId===void 0)X.associatedTaskId=q;X.lastUpdatedAt=Date.now();let Y={backgroundTaskId:$,subSessionId:X.subSessionId,parentSessionId:J,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(M0.PROGRESS,Y,J,X.triggerEventId,X.replyChannel,X.pluginEnabledSnapshot)},_F);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,q,Y,G,W,z){let H=$?.metadata??{},B=H.task_id,U=H.task_description||"",V=$.id,O=H.subagent_type,F=O||z||"general";if(!O&&!z)g.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${V}`);let D=this.env?.getComponent?.("agent"),M=D?.getRegistry?.(),j=await YF(F,{registry:M}),L=T8(F),A=j?.basePrompt||L?.promptOverride||"You are a subagent. Complete this task: {task_description}",R=j?.deniedTools||L?.deniedTools||[],b=j?.allowedTools||L?.allowedTools,w=`# Session Info
2555
2554
  - task_id: ${B||"N/A"}
2556
2555
  - session_id: ${V}
2556
+ - task_description: ${U||"N/A"}
2557
2557
 
2558
2558
  ---
2559
2559
 
@@ -2566,13 +2566,13 @@ ${J}
2566
2566
  - \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
2567
2567
  - \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
2568
2568
  - \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
2569
- - \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`,G&&G.length>0)try{let x=this.env?.getComponent?.("task");if(x){let r=[];for(let g of G)try{let c=await x.getTask(g);if(!c){y.warn(`[delegate] Similar task #${g} not found, skipping`);continue}let F0=await x.listOperations({taskId:g,limit:10}),M0=`### Task #${c.id}: ${c.title}
2570
- `;if(M0+=`- Status: ${c.status}
2571
- `,c.description)M0+=`- Description: ${c.description}
2572
- `;if(c.goals_and_expected_deliverables)M0+=`- Goals: ${c.goals_and_expected_deliverables}
2573
- `;if(F0&&F0.length>0){M0+=`- Recent Operations:
2574
- `;for(let k0 of F0)M0+=` - [${k0.actionType}] ${k0.actionTitle}: ${k0.actionDescription||""}
2575
- `}r.push(M0)}catch(c){y.warn(`[delegate] Failed to fetch similar task #${g}`,{error:c instanceof Error?c.message:String(c)})}if(r.length>0)w+=`
2569
+ - \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`;if(Y&&Y.length>0)try{let C=this.env?.getComponent?.("task");if(C){let r=[];for(let h0 of Y)try{let X0=await C.getTask(h0);if(!X0){g.warn(`[delegate] Similar task #${h0} not found, skipping`);continue}let K0=await C.listOperations({taskId:h0,limit:10}),j0=`### Task #${X0.id}: ${X0.title}
2570
+ `;if(j0+=`- Status: ${X0.status}
2571
+ `,X0.description)j0+=`- Description: ${X0.description}
2572
+ `;if(X0.goals_and_expected_deliverables)j0+=`- Goals: ${X0.goals_and_expected_deliverables}
2573
+ `;if(K0&&K0.length>0){j0+=`- Recent Operations:
2574
+ `;for(let L0 of K0)j0+=` - [${L0.actionType}] ${L0.actionTitle}: ${L0.actionDescription||""}
2575
+ `}r.push(j0)}catch(X0){g.warn(`[delegate] Failed to fetch similar task #${h0}`,{error:X0 instanceof Error?X0.message:String(X0)})}if(r.length>0)w+=`
2576
2576
 
2577
2577
  ---
2578
2578
 
@@ -2585,14 +2585,18 @@ The following similar tasks and their operation records can serve as reference:
2585
2585
 
2586
2586
  ---
2587
2587
 
2588
- Use these as guidance to improve task execution efficiency.`}}catch(x){y.warn("[delegate] Failed to inject similar tasks reference",{error:x instanceof Error?x.message:String(x)})}if(!D)throw Error("AgentComponent not found");try{if(this.env){let x=YF(this.env),r=WF({registry:x,similarTaskIds:G??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!r.isEmpty)w+=`
2588
+ Use these as guidance to improve task execution efficiency.`}}catch(C){g.warn("[delegate] Failed to inject similar tasks reference",{error:C instanceof Error?C.message:String(C)})}if(!D)throw Error("AgentComponent not found");try{if(this.env){let C=FF(this.env),r=KF({registry:C,similarTaskIds:Y??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!r.isEmpty)w+=`
2589
+
2590
+ ---
2591
+
2592
+ ${r.markdown}`}}catch(C){g.warn("[delegate] Failed to inject reuse candidate section",{error:C instanceof Error?C.message:String(C)})}let T=H.channelType??F$()?.replyChannel?.type,Z=XF(T);if(Z)w+=`
2589
2593
 
2590
2594
  ---
2591
2595
 
2592
- ${r.markdown}`}}catch(x){y.warn("[delegate] Failed to inject reuse candidate section",{error:x instanceof Error?x.message:String(x)})}let f=L?{...L,allowedTools:b}:b?{id:F,name:F,mode:"subagent",description:R?.description||"Custom agent",allowedTools:b,deniedTools:Z}:void 0;zF(D,F,N,f,Z);let S=M?.get(F)?.type==="workflow"?J:w;return new Promise((x,r)=>{let g=async()=>{try{await q?.killAll()}catch(z0){y.warn("[delegate] ProcessRegistry.killAll failed",{error:z0 instanceof Error?z0.message:String(z0)})}},c=!1,F0,M0,k0=this.tasks.get(X);if(k0?.runId)M0=k0.runId;let V6=()=>{if(Y&&D6)try{Y.removeEventListener("abort",D6)}catch{}},D6;if(D6=()=>{if(c)return;if(c=!0,F0)clearTimeout(F0);V6();try{let z0=this.env?.getComponent?.("agent");if(z0?.abortRun&&M0)z0.abortRun(M0,"task_signal_abort")}catch{}g().catch(()=>{}).then(()=>{r(Error("Task execution stopped"))})},F0=setTimeout(()=>{if(c)return;if(c=!0,F0)clearTimeout(F0);V6();try{W?.()}catch{}try{let z0=this.env?.getComponent?.("agent");if(z0?.abortRun&&M0)z0.abortRun(M0,"task_timeout")}catch{}g().catch(()=>{}).then(()=>{r(Error(`Task execution timeout after ${Q}ms`))})},Q),Y)Y.addEventListener("abort",D6);let G7=()=>{let z0=k0?.model,q7=k0?.fallbackModel,W7=k0?.fallbackModels;return this.env.handle_query?.(S,{sessionId:V,deniedTools:Z.length>0?Z:void 0,agentType:F,abort:Y,runId:M0,...z0?{model:z0}:{},...q7?{fallbackModel:q7}:{},...Array.isArray(W7)?{fallbackModels:W7}:{}})};(q?d7(q,()=>A8(X,()=>G7())):A8(X,()=>G7()))?.then((z0)=>{if(c)return;if(c=!0,F0)clearTimeout(F0);V6(),x(z0)}).catch((z0)=>{if(c)return;if(c=!0,F0)clearTimeout(F0);V6(),r(z0)})})}async stopTask($){let J=this.tasks.get($)??this.terminalTasks.get($);if(!J)return{success:!1,message:"Task not found"};if(this.terminalTasks.has($))return{success:!1,task:J,message:`Cannot stop task with status: ${J.status}`};if(J.status==="completed"||J.status==="failed"||J.status==="stopped"||J.status==="timeout")return{success:!1,task:J,message:`Cannot stop task with status: ${J.status}`};let Q=Date.now();if(J.status="stopped",J.abortController?.abort(),J.runId)try{this.env?.getComponent?.("agent")?.abortRun?.(J.runId,"stop_task")}catch(q){y.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:$,runId:J.runId,error:q instanceof Error?q.message:String(q)})}J.completedAt=Q,J.lastUpdatedAt=Q;try{await this.processRegistries.get($)?.killAll()}catch(q){y.warn("[delegate] stopTask killAll failed",{taskId:$,error:q instanceof Error?q.message:String(q)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns($,"Task stopped by user"),G={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:J.parentSessionId,status:"stopped",description:J.description,error:"Task stopped by user",executionTimeMs:J.startedAt?J.completedAt-J.startedAt:0,associatedTaskId:J.associatedTaskId};return this.publishBackgroundEvent(n0.STOPPED,G,J.parentSessionId,J.triggerEventId,J.replyChannel),this.finalizeTask($,"stopped"),{success:!0,task:J,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:Y}}getTask($){return this.tasks.get($)??this.terminalTasks.get($)}async getSubSessionActivity($){let J=this.getTask($);if(!J)return;let Q=this.getSessionComponent();if(!Q?.get)return;try{let X=await Q.get(J.subSessionId);if(!X)return;return{messageCount:X.messageCount??0,updatedAt:X.updatedAt??J.lastUpdatedAt??J.createdAt}}catch{return}}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent($){if(!$)return!1;for(let J of this.tasks.values())if(J.parentSessionId===$&&(J.status==="pending"||J.status==="running"))return!0;return!1}async stopAllForParent($){if(!$)return{stoppedTaskIds:[]};let J=[];for(let[Q,X]of this.tasks)if(X.parentSessionId===$&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask(Q))?.success)J.push(Q)}catch(Y){y.warn(`[BackgroundTaskManager] stopAllForParent failed for ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}return{stoppedTaskIds:J}}async forceStopAllAcrossParents(){let $=new Set,J=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let Q of J){if($.has(Q))continue;$.add(Q);let Y=this.tasks.get(Q)??this.terminalTasks.get(Q);try{await this.processRegistries.get(Q)?.killAll()}catch(q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${Q}: ${q instanceof Error?q.message:String(q)}`)}try{await this.propagateStopToWorkflowRuns(Q,"force stop all")}catch(q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${Q}: ${q instanceof Error?q.message:String(q)}`)}let G=!1;if(Y&&(Y.status==="running"||Y.status==="pending"))try{Y.status="stopped",Y.completedAt=Date.now(),Y.lastUpdatedAt=Y.completedAt,Y.abortController?.abort(),G=!0}catch(q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${Q}: ${q instanceof Error?q.message:String(q)}`)}if(G&&Y){let q={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(n0.STOPPED,q,Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose($){for(let[,X]of this.progressTimers)try{clearInterval(X)}catch{}this.progressTimers.clear();let J=$?.skipAbortRunningTasks===!0;if($?.waitForRunningTasks===!0&&J){let X=Date.now(),Y=600000;while(Date.now()-X<600000){let G=0;for(let[,q]of this.tasks)if(q.status==="running"||q.status==="pending")G++;if(G===0)break;y.info(`[BackgroundTaskManager] dispose waiting for ${G} running task(s)`),await new Promise((q)=>setTimeout(q,200))}}for(let[,X]of this.abortControllers){if(J)break;try{X.abort()}catch{}}this.abortControllers.clear();for(let[,X]of this.processRegistries)try{await X.killAll()}catch(Y){y.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:Y instanceof Error?Y.message:String(Y)})}this.processRegistries.clear();for(let X of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(X,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),y.info("[BackgroundTaskManager] Disposed")}}k([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"attachWorkflowRun",null);k([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"detachWorkflowRun",null);k([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"replaceWorkflowRun",null);k([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"propagateStopToWorkflowRuns",null);k([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"finalizeTask",null);k([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],J0.prototype,"resolveEntryAgent",null);k([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"createTask",null);k([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"executeTask",null);k([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"startProgressReporter",null);k([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"stopProgressReporter",null);k([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"executeWithAbort",null);k([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"stopAllForParent",null);k([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"forceStopAllAcrossParents",null);function K3($){return $.env?.getComponent?.("agent")?.getRegistry?.()}function R3($){let J=$.env,X=$.backgroundTaskManager??new J0(J),Y=K3($);$._backgroundTaskManager=X;let G={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
2596
+ ${Z}`;let I=L?{...L,allowedTools:b}:b?{id:F,name:F,mode:"subagent",description:j?.description||"Custom agent",allowedTools:b,deniedTools:R}:void 0;LF(D,F,A,I,R);let n=M?.get(F)?.type==="workflow"?J:w;return new Promise((C,r)=>{let h0=async()=>{try{await G?.killAll()}catch(B0){g.warn("[delegate] ProcessRegistry.killAll failed",{error:B0 instanceof Error?B0.message:String(B0)})}},X0=!1,K0,j0,L0=this.tasks.get(X);if(L0?.runId)j0=L0.runId;let O6=()=>{if(q&&K6)try{q.removeEventListener("abort",K6)}catch{}},K6;if(K6=()=>{if(X0)return;if(X0=!0,K0)clearTimeout(K0);O6();try{let B0=this.env?.getComponent?.("agent");if(B0?.abortRun&&j0)B0.abortRun(j0,"task_signal_abort")}catch{}h0().catch(()=>{}).then(()=>{r(Error("Task execution stopped"))})},K0=setTimeout(()=>{if(X0)return;if(X0=!0,K0)clearTimeout(K0);O6();try{W?.()}catch{}try{let B0=this.env?.getComponent?.("agent");if(B0?.abortRun&&j0)B0.abortRun(j0,"task_timeout")}catch{}h0().catch(()=>{}).then(()=>{r(Error(`Task execution timeout after ${Q}ms`))})},Q),q)q.addEventListener("abort",K6);let V5=()=>{let B0=L0?.model,D5=L0?.fallbackModel,F5=L0?.fallbackModels;return this.env.handle_query?.(n,{sessionId:V,deniedTools:R.length>0?R:void 0,agentType:F,abort:q,runId:j0,...B0?{model:B0}:{},...D5?{fallbackModel:D5}:{},...Array.isArray(F5)?{fallbackModels:F5}:{},...L0?.systemPrompt?{metadata:{systemPrompt:L0.systemPrompt}}:{},...L0?.extendTools?.length?{extendTools:L0.extendTools}:{}})};(G?t5(G,()=>b8(X,()=>V5())):b8(X,()=>V5()))?.then((B0)=>{if(X0)return;if(X0=!0,K0)clearTimeout(K0);O6(),C(B0)}).catch((B0)=>{if(X0)return;if(X0=!0,K0)clearTimeout(K0);O6(),r(B0)})})}async stopTask($){let J=this.tasks.get($)??this.terminalTasks.get($);if(!J)return{success:!1,message:"Task not found"};if(this.terminalTasks.has($))return{success:!1,task:J,message:`Cannot stop task with status: ${J.status}`};if(J.status==="completed"||J.status==="failed"||J.status==="stopped"||J.status==="timeout")return{success:!1,task:J,message:`Cannot stop task with status: ${J.status}`};let Q=Date.now();if(J.status="stopped",J.abortController?.abort(),J.runId)try{this.env?.getComponent?.("agent")?.abortRun?.(J.runId,"stop_task")}catch(G){g.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:$,runId:J.runId,error:G instanceof Error?G.message:String(G)})}J.completedAt=Q,J.lastUpdatedAt=Q;try{await this.processRegistries.get($)?.killAll()}catch(G){g.warn("[delegate] stopTask killAll failed",{taskId:$,error:G instanceof Error?G.message:String(G)})}let{runIds:X,stopResults:q}=await this.propagateStopToWorkflowRuns($,"Task stopped by user"),Y={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:J.parentSessionId,status:"stopped",description:J.description,error:"Task stopped by user",executionTimeMs:J.startedAt?J.completedAt-J.startedAt:0,associatedTaskId:J.associatedTaskId};return this.publishBackgroundEvent(M0.STOPPED,Y,J.parentSessionId,J.triggerEventId,J.replyChannel,J.pluginEnabledSnapshot),this.finalizeTask($,"stopped"),{success:!0,task:J,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:q}}getTask($){return this.tasks.get($)??this.terminalTasks.get($)}async getSubSessionActivity($){let J=this.getTask($);if(!J)return;let Q=this.getSessionComponent();if(!Q?.get)return;try{let X=await Q.get(J.subSessionId);if(!X)return;return{messageCount:X.messageCount??0,updatedAt:X.updatedAt??J.lastUpdatedAt??J.createdAt}}catch{return}}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent($){if(!$)return!1;for(let J of this.tasks.values())if(J.parentSessionId===$&&(J.status==="pending"||J.status==="running"))return!0;return!1}async stopAllForParent($){if(!$)return{stoppedTaskIds:[]};let J=[];for(let[Q,X]of this.tasks)if(X.parentSessionId===$&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask(Q))?.success)J.push(Q)}catch(q){g.warn(`[BackgroundTaskManager] stopAllForParent failed for ${Q}: ${q instanceof Error?q.message:String(q)}`)}return{stoppedTaskIds:J}}async forceStopAllAcrossParents(){let $=new Set,J=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let Q of J){if($.has(Q))continue;$.add(Q);let q=this.tasks.get(Q)??this.terminalTasks.get(Q);try{await this.processRegistries.get(Q)?.killAll()}catch(G){g.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}try{await this.propagateStopToWorkflowRuns(Q,"force stop all")}catch(G){g.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}let Y=!1;if(q&&(q.status==="running"||q.status==="pending"))try{q.status="stopped",q.completedAt=Date.now(),q.lastUpdatedAt=q.completedAt,q.abortController?.abort(),Y=!0}catch(G){g.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}if(Y&&q){let G={backgroundTaskId:q.id,subSessionId:q.subSessionId,parentSessionId:q.parentSessionId,status:"stopped",description:q.description,error:"force stop all",executionTimeMs:q.startedAt&&q.completedAt?q.completedAt-q.startedAt:0,associatedTaskId:q.associatedTaskId};this.publishBackgroundEvent(M0.STOPPED,G,q.parentSessionId,q.triggerEventId,q.replyChannel,q.pluginEnabledSnapshot)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose($){for(let[,X]of this.progressTimers)try{clearInterval(X)}catch{}this.progressTimers.clear();let J=$?.skipAbortRunningTasks===!0;if($?.waitForRunningTasks===!0&&J){let X=Date.now(),q=600000;while(Date.now()-X<600000){let Y=0;for(let[,G]of this.tasks)if(G.status==="running"||G.status==="pending")Y++;if(Y===0)break;g.info(`[BackgroundTaskManager] dispose waiting for ${Y} running task(s)`),await new Promise((G)=>setTimeout(G,200))}}for(let[,X]of this.abortControllers){if(J)break;try{X.abort()}catch{}}this.abortControllers.clear();for(let[,X]of this.processRegistries)try{await X.killAll()}catch(q){g.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:q instanceof Error?q.message:String(q)})}this.processRegistries.clear();for(let X of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(X,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),g.info("[BackgroundTaskManager] Disposed")}}k([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],Q0.prototype,"attachWorkflowRun",null);k([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],Q0.prototype,"detachWorkflowRun",null);k([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],Q0.prototype,"replaceWorkflowRun",null);k([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],Q0.prototype,"propagateStopToWorkflowRuns",null);k([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],Q0.prototype,"finalizeTask",null);k([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],Q0.prototype,"resolveEntryAgent",null);k([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],Q0.prototype,"createTask",null);k([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],Q0.prototype,"executeTask",null);k([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],Q0.prototype,"startProgressReporter",null);k([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],Q0.prototype,"stopProgressReporter",null);k([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],Q0.prototype,"executeWithAbort",null);k([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],Q0.prototype,"stopAllForParent",null);k([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],Q0.prototype,"forceStopAllAcrossParents",null);function ZJ($){return $.env?.getComponent?.("agent")?.getRegistry?.()}function wJ($){let J=$.env,X=$.backgroundTaskManager??new Q0(J),q=ZJ($);$._backgroundTaskManager=X;let Y={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
2593
2597
 
2594
2598
  Available agent types:
2595
- ${tD(Y)}
2599
+ ${zF(q)}
2596
2600
 
2597
2601
  When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
2598
2602
 
@@ -2621,14 +2625,14 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
2621
2625
  - **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
2622
2626
  - **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
2623
2627
  - **reason**: Brief reason for calling this tool (optional)
2624
- - **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:O3,execute:async(q,W)=>{let z=Date.now(),H=O3.parse(q),{description:B,prompt:U,subagent_type:V="general",timeout:O,reason:F,similar_task_ids:D}=H,M=W.session_id||"default",R=H.triggerEventId??DF();if(R&&R!==H.triggerEventId)y.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${R}`);if(y.info(`[delegate_task] Called: description=${B}, subagent_type=${V}, triggerEventId=${R??"(none)"}`),R){let f=n7();if(f)try{if(!await f.getEventById(R))return{success:!1,output:"",error:`Unknown triggerEventId: ${R} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-z}}}catch(A){return{success:!1,output:"",error:`Failed to verify triggerEventId ${R}: ${A instanceof Error?A.message:String(A)}`,metadata:{execution_time_ms:Date.now()-z}}}else y.warn(`[delegate_task] triggerEventId=${R} supplied but no shared EventStore registered; skipping verification`)}let L=K3($);if(!rD(V,L))return{success:!1,output:"",error:`Unknown subagent type: ${V}`,metadata:{execution_time_ms:Date.now()-z}};let N=$.getTagService(),Z=U,b={prompt:Z,subagentType:V,timeout:O,reason:F,tagService:N},w={component:{name:"task",version:"1.0.0"},data:b,metadata:{sessionId:M},phase:"before",hookPoint:X0.DELEGATE_BEFORE};return await S0.execute(X0.DELEGATE_BEFORE,b,{sessionId:M}),Z=b.prompt,await OF(X,M,B,Z,b.subagentType,b.timeout,D,H.sub_session_id,R,W.model,W.fallbackModel,W.fallbackModels)}};return G.execute=B0(G.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),G}function VF(){let $=W2();if(!$)return;let J=$.envEvent,Q=J?.metadata?.triggerEventId;if(typeof Q==="string"&&Q.length>0)return Q;let X=J?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var DF=B0(VF,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function FF(){let $=W2()?.replyChannel;if(!$)return;if(!$.chatId&&!$.messageId)return;let J={...$.params??{}};if($.userId&&J.userId===void 0)J.userId=$.userId;return{type:$.type,appId:$.appId,chatId:$.chatId,messageId:$.messageId,profile:$.profile,params:Object.keys(J).length>0?J:void 0}}var MF=B0(FF,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function OF($,J,Q,X,Y,G,q,W,z,H,B,U){let V=Date.now();try{let O=Y,F=X,D,M=$.resolveEntryAgent(Y);if(M)D=Y,O=M,F=HF({workflowName:D,originalPrompt:X,description:Q}),y.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${M}'`);let{taskId:R,subSessionId:L}=await $.createTask({parentSessionId:J,description:Q,prompt:F,subagentType:O,timeout:G,similarTaskIds:q,originalWorkflowName:D,existingSubSessionId:W,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${R}`,`\uD83D\uDCDD Description: ${Q}`,`\uD83E\uDD16 Sub-agent: ${O}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(G||L9)/1000}s`,"",`Use stop_task with task_id="${R}" to cancel this task.`].join(`
2625
- `),metadata:{execution_time_ms:Date.now()-V,sessionId:L,background:!0,status:"accepted",bgProcessId:R}}}catch(O){return{success:!1,output:"",error:O instanceof Error?O.message:String(O),metadata:{execution_time_ms:Date.now()-V}}}}var b$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};V0();var KF=20;var RF=["expected_decision","expected_root","expected_","case_id","category","suggested_","recommended_","best_match","answer","answer_key","label","should_","target","gold","ground_truth","hint","solution","duplicate_of","similar_task_ids","candidate_order","verdict","decision"];function LF($){if(!$)return[];let J;try{J=JSON.parse($)}catch{return[]}if(!J||typeof J!=="object"||Array.isArray(J))return[];let Q=J.similar_task_ids;if(!Array.isArray(Q))return[];let X=[],Y=new Set;for(let G of Q){if(typeof G!=="number")continue;if(!Number.isInteger(G)||G<=0)continue;if(Y.has(G))continue;if(Y.add(G),X.push(G),X.length>=KF)break}return X}function jF($){switch($){case"completed":case"cancelled":case"paused":case"archived":return"reopen";case"todo":case"active":default:return"enhance"}}function L3($){return $==="paused"?"active":"todo"}var f8="__NEW_TASK_ID__",I8="#__NEW_TASK_ID__";function NF($){switch($.scenario){case"reuse":return _F($);case"reopen":return AF($);case"reopen_enhance":return ZF($);case"remount":return wF($);case"soft_reuse":return PF($)}}function C8($){return $.newTaskId>0?String($.newTaskId):f8}function j0($){return $.newTaskId>0?`#${$.newTaskId}`:I8}function N9($){let J=$.targetTask;if(!J)return"";return`#${$.targetTaskId} [${J.type}] ${J.title}
2626
- \u72B6\u6001\uFF1A${J.status}`}function _F($){let J=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u4E0E\u5DF2\u6709\u4EFB\u52A1\u9AD8\u5EA6\u76F8\u4F3C\uFF0C\u5EFA\u8BAE\u590D\u7528\u800C\u975E\u65B0\u5EFA\u3002","",N9($),"\u72B6\u6001\uFF1A"+($.targetTask?.status??"")+" \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Aenhance\uFF08\u8865\u5145\u76EE\u6807/\u63CF\u8FF0\uFF09","",`\u5982\u9700\u5408\u5E76\u5230 #${$.targetTaskId}\uFF0C\u53EF\u6267\u884C\uFF1A`,` task_update(task_id=${$.targetTaskId}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${J})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${j0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${j0($)}\u3002`,"","\u6838\u5B9E\u8981\u70B9\uFF1A\u672C\u6B21\u8BF7\u6C42\u662F\u5426\u5C31\u662F #"+$.targetTaskId+" \u7684\u300C\u540C\u4E00\u4EF6\u4E8B\u300D\uFF0C\u800C\u4E0D\u662F\u540C\u4E3B\u9898\u4E0B\u65B0\u7684\u4E00\u6B65\uFF1F"," - \u82E5\u53EA\u662F\u540C\u4E3B\u9898\u7684\u65B0\u4E00\u6B65\uFF08\u9700\u8981\u72EC\u7ACB\u8DDF\u8E2A\u7684\u65B0\u5B50\u4EFB\u52A1\uFF09\uFF0C\u5EFA\u5B50\u4EFB\u52A1\u4E0D\u7B97\u4E0D\u91C7\u7EB3\uFF0C\u4F46\u9700\u5728\u56DE\u590D\u4E2D\u8BF4\u660E\u4E3A\u4F55\u4E0D\u76F4\u63A5\u5408\u5E76\u3002"," - \u82E5\u786E\u5B9E\u662F\u540C\u4E00\u4EF6\u4E8B\uFF0C\u5E94\u91C7\u7EB3 (a) \u6267\u884C\u590D\u7528\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, ...) \u6267\u884C\u590D\u7528\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${j0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2627
- `)}function AF($){let J=$.targetTask?.status??"completed",Q=L3(J),X=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u4E0E\u5DF2\u6709\u4EFB\u52A1\u5B9E\u8D28\u76F8\u540C\uFF0C\u5EFA\u8BAE\u91CD\u5F00\u8BE5\u4EFB\u52A1\u800C\u4E0D\u662F\u65B0\u5EFA\u3002","",N9($),`\u72B6\u6001\uFF1A${J} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen\uFF08\u6062\u590D\u4E3A ${Q}\uFF09`,"","\u5982\u9700\u91CD\u5F00\u5E76\u627F\u63A5\u672C\u6B21\u8BF7\u6C42\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, status=${Q}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${X})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${j0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${j0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A#${$.targetTaskId} \u662F\u5426\u771F\u7684\u5DF2\u5B8C\u7ED3\uFF08completed / cancelled\uFF09\uFF0C\u4F46\u5176\u8BED\u4E49\u4E0E\u672C\u6B21\u8BF7\u6C42\u4ECD\u7136\u76F8\u540C\uFF1F`," - \u82E5\u5DF2\u5B8C\u7ED3\u4F46\u8BED\u4E49\u4ECD\u76F8\u540C\uFF08\u672C\u6B21\u8BF7\u6C42\u662F\u8BE5\u4EFB\u52A1\u7684\u5EF6\u7EED\uFF09\u2192 \u5E94\u91C7\u7EB3 (a) \u91CD\u5F00\u3002"," - \u82E5\u76EE\u6807\u5DF2\u5B8C\u7ED3\u4E14\u8BED\u4E49\u4E0D\u540C\uFF08\u53EA\u662F\u4E3B\u9898\u76F8\u8FD1\uFF09\u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, status=${Q}, ...) \u6267\u884C\u91CD\u5F00\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${j0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2628
- `)}function ZF($){let J=$.targetTask?.status??"completed",Q=L3(J);return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u4E0E\u5DF2\u6709\u4EFB\u52A1\u5B9E\u8D28\u76F8\u540C\uFF0C\u4E14\u672C\u6B21\u65B0\u589E\u4E86\u76EE\u6807\uFF0C\u5EFA\u8BAE\u91CD\u5F00\u5E76\u589E\u5F3A\u8BE5\u4EFB\u52A1\u3002","",N9($),`\u72B6\u6001\uFF1A${J} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen + enhance\uFF08\u6062\u590D\u4E3A ${Q} \u5E76\u8FFD\u52A0\u76EE\u6807\uFF09`,"","\u5982\u9700\u91CD\u5F00\u5E76\u627F\u63A5\u672C\u6B21\u8BF7\u6C42\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, status=${Q}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>, goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>)`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${j0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${j0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A\u2460 #${$.targetTaskId} \u662F\u5426\u771F\u7684\u5DF2\u5B8C\u7ED3\uFF08completed / cancelled\uFF09\u4F46\u8BED\u4E49\u4ECD\u4E0E\u672C\u6B21\u8BF7\u6C42\u76F8\u540C\uFF1B\u2461 \u672C\u6B21\u65B0\u589E\u7684\u76EE\u6807\u662F\u5426\u786E\u5B9E\u5C5E\u4E8E\u8BE5\u4EFB\u52A1\u7684\u8303\u56F4\u5185\uFF1F`," - \u4E24\u70B9\u90FD\u6210\u7ACB \u2192 \u5E94\u91C7\u7EB3 (a) \u91CD\u5F00\u5E76\u589E\u5F3A\u3002"," - \u65B0\u589E\u76EE\u6807\u8D85\u51FA\u539F\u4EFB\u52A1\u8303\u56F4\uFF08\u662F\u72EC\u7ACB\u7684\u65B0\u5DE5\u4F5C\uFF09\u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, status=${Q}, ..., goals_and_expected_deliverables=...) \u6267\u884C\u91CD\u5F00\u5E76\u589E\u5F3A\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${j0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2629
- `)}function wF($){return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u4EFB\u52A1\u7684\u6302\u8F7D\u4F4D\u7F6E\u53EF\u80FD\u4E0D\u5408\u7406\u3002","",`\u5F53\u524D\u6302\u8F7D\uFF1Aparent #${$.currentParentId} \u2192 root \u7956\u5148 #${$.currentRootAncestorId}`,`\u5EFA\u8BAE\u5F52\u5C5E\uFF1Aroot #${$.recommendedRootId} ${$.recommendedRootTitle??""}`.trimEnd(),"","\u5982\u9700\u6539\u6302\u5230\u5EFA\u8BAE\u7684 root \u4E0B\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${C8($)}, parent_task_id=${$.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${j0($)}\uFF0Cparent \u672A\u88AB\u81EA\u52A8\u4FEE\u6539\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A\u5F53\u524D parent #${$.currentParentId} \u7684 root \u7956\u5148 #${$.currentRootAncestorId} \u4E0E\u5EFA\u8BAE\u7684 root #${$.recommendedRootId}\uFF0C\u54EA\u4E00\u6761\u624D\u662F\u672C\u6B21\u4EFB\u52A1\u7684\u6B63\u786E\u5F52\u5C5E\u7EBF\uFF1F\uFF08\u53EF\u53C2\u8003\u5144\u5F1F\u4EFB\u52A1\u7684\u4E3B\u9898\u5206\u5E03\uFF09`," - \u5EFA\u8BAE\u7684 root \u66F4\u8D34\u5408\u672C\u6B21\u4EFB\u52A1\u4E3B\u9898 \u2192 \u5E94\u91C7\u7EB3 (a) \u6267\u884C\u6539\u6302\u3002"," - \u5F53\u524D\u5F52\u5C5E\u7EBF\u5DF2\u6B63\u786E \u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${C8($)}) \u786E\u8BA4\u672C\u6B21\u65B0\u5EFA\u4EFB\u52A1\u7684\u5B9E\u9645 parent\uFF0C\u5E76\u7528 task_get(${$.recommendedRootId})\uFF08\u5FC5\u8981\u65F6 task_tree\uFF09\u786E\u8BA4\u5F52\u5C5E\u7EBF\u662F\u5426\u771F\u7684\u4E0D\u5BF9\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u6302\u8F7D\u4E0D\u5408\u7406 \u2192 \u6267\u884C\u6539\u6302 task_update(task_id=${C8($)}, parent_task_id=${$.recommendedRootId})\uFF1B`,"(b) \u786E\u8BA4\u5F53\u524D\u6302\u8F7D\u5408\u7406 \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2630
- `)}function PF($){let J=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u53EF\u80FD\u4E0E\u5DF2\u6709\u4EFB\u52A1\u6709\u5173\u8054\uFF08\u7F6E\u4FE1\u5EA6\u504F\u4F4E\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF09\u3002","",N9($),"","\u82E5\u786E\u8BA4\u662F\u540C\u4E00\u4EF6\u4E8B\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${J})`,"",`\u8BF4\u660E\uFF1A\u672C\u63D0\u793A\u57FA\u4E8E\u8F83\u4F4E\u7F6E\u4FE1\u5EA6\uFF0C\u53EF\u80FD\u8BEF\u5224\u3002\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${j0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A#${$.targetTaskId} \u4E0E\u672C\u6B21\u8BF7\u6C42\u662F\u5426\u786E\u4E3A\u540C\u4E00\u4EF6\u4E8B\uFF1F\uFF08\u672C\u63D0\u793A\u7F6E\u4FE1\u5EA6\u4F4E\uFF0C\u6838\u5B9E\u6743\u91CD\u76F8\u5E94\u964D\u4F4E\uFF0C\u4F46\u4E0D\u5F97\u8DF3\u8FC7\u8868\u6001\uFF09`,"",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, ...) \u6267\u884C\u590D\u7528\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${j0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2631
- `)}function bF($){let J=$.toLowerCase();return RF.some((Q)=>Q.endsWith("_")||Q.endsWith("*")?J.startsWith(Q.slice(0,-1)):J===Q)}function EF($,J){let Q=(X,Y)=>{if(Array.isArray(X)){X.forEach((G,q)=>Q(G,`${Y}[${q}]`));return}if(!X||typeof X!=="object")return;for(let[G,q]of Object.entries(X)){let W=Y?`${Y}.${G}`:G;if(bF(G))throw Error(`[assertNoLeakage] leakage key detected at ${W}: "${G}"`);Q(q,W)}};Q($,"state"),Q(J,"questions")}function SF($,J){let Q;try{Q=JSON.parse($.context)}catch{return!1}if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;return Q.decision_hint=J,$.context=JSON.stringify(Q),!0}var bL=B0(LF,"task.decision.parseSimilarTaskIds",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0],Q=typeof J==="string"?J:"";return{contextLen:Q.length,contextPreview:Q.length>80?Q.slice(0,80)+"\u2026":Q}},resultFilter:($)=>({count:$.length,ids:$.join(",")})}),EL=B0(jF,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),SL=B0(NF,"task.decision.buildHintText",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0]??{};return{scenario:J.scenario,newTaskId:J.newTaskId,targetTaskId:J.targetTaskId??null,recommendedRootId:J.recommendedRootId??null,currentParentId:J.currentParentId??null,confidence:J.confidence??null}},resultFilter:($)=>({hintLen:$.length,hintPreview:$.slice(0,240),hasTaskUpdate:/task_update\s*\(/.test($),hasTaskId:/"task_id"\s*:/.test($),hasParentTaskId:/"parent_task_id"\s*:/.test($)})}),CL=B0(EF,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:($)=>({stateKeys:j9($[0]),questionKeys:j9($[1])})}),fL=B0(SF,"task.decision.writeDecisionHint",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0]??{},Q=typeof $[1]==="string"?$[1]:"";return{contextLen:typeof J.context==="string"?J.context.length:0,hintLen:Q.length,hintScenario:/task_update\s*\(/.test(Q)?"actionable":"plain"}},resultFilter:($)=>({written:$}),errorIf:($)=>$===!1?Error("writeDecisionHint returned false (context not a JSON object)"):void 0});function j9($,J=[],Q=0){if(J.length>=40||Q>4)return J;if(Array.isArray($)){for(let X of $.slice(0,3))j9(X,J,Q+1);return J}if(!$||typeof $!=="object")return J;for(let X of Object.keys($)){if(J.length>=40)break;if(!J.includes(X))J.push(X);j9($[X],J,Q+1)}return J}import{execSync as TF}from"child_process";var j3="unknown",CF='{"type":"unknown"}';function fF(){return{task_id:K.number().describe("Task ID")}}function IF($){if(typeof $!=="object"||$===null||Array.isArray($))return $;let J=$;if(J.task_id===void 0&&J.id!==void 0)return{...J,task_id:J.id};return J}function a2($){return K.preprocess(IF,K.object({...fF(),...$}))}var N3=K.object({title:K.string().describe("Task title"),description:K.string().optional().describe("Task description"),priority:K.enum(["low","medium","high"]).optional().describe("Task priority"),type:K.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:K.string().optional().describe("Goals and expected deliverables. "+"\u26A0\uFE0F \u5199\u6210\u53EF\u9010\u6761\u9A8C\u6536\u7684\u7F16\u53F7\u5B50\u9879\uFF081. \u2026 2. \u2026 3. \u2026\uFF09\uFF0C\u6BCF\u6761\u662F\u4E00\u4E2A\u53EF\u5224\u5B9A\u7684\u4EA4\u4ED8/\u52A8\u4F5C"+"\uFF08\u6587\u4EF6\u65AD\u8A00\uFF1A\u6587\u4EF6\u5B58\u5728/\u5927\u5C0F/\u5185\u5BB9\uFF1B\u8FDB\u7A0B\u65AD\u8A00\uFF1A\u547D\u4EE4 exit code/stdout\uFF1B"+"\u6D4B\u8BD5\u65AD\u8A00\uFF1Apass/fail \u8BA1\u6570\uFF1B\u72B6\u6001\u65AD\u8A00\uFF1A\u7248\u672C\u53F7/HTTP 200/\u72B6\u6001\u5B57\u6BB5\uFF09\u3002"+"\u907F\u514D\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF08\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D\uFF09\u2014\u2014"+"\u4EFB\u52A1\u5B8C\u6210\u65F6 completion hook \u4F1A\u6309\u8FD9\u4E9B\u5B50\u9879\u9010\u6761\u5BF9\u7167\u64CD\u4F5C\u8BB0\u5F55\u9A8C\u6536\u3002"),due_date:K.string().optional().describe("Due date (ISO format)"),tags:K.array(K.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:K.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:K.union([K.number(),K.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
2628
+ - **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:RJ,execute:async(G,W)=>{let z=Date.now(),H=RJ.parse(G),{description:B,prompt:U,subagent_type:V="general",timeout:O,reason:F,similar_task_ids:D}=H,M=W.session_id||"default",j=H.triggerEventId??ZF();if(j&&j!==H.triggerEventId)g.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${j}`);if(g.info(`[delegate_task] Called: description=${B}, subagent_type=${V}, triggerEventId=${j??"(none)"}`),j){let T=$7();if(T)try{if(!await T.getEventById(j))return{success:!1,output:"",error:`Unknown triggerEventId: ${j} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-z}}}catch(Z){return{success:!1,output:"",error:`Failed to verify triggerEventId ${j}: ${Z instanceof Error?Z.message:String(Z)}`,metadata:{execution_time_ms:Date.now()-z}}}else g.warn(`[delegate_task] triggerEventId=${j} supplied but no shared EventStore registered; skipping verification`)}let L=ZJ($);if(!qF(V,L))return{success:!1,output:"",error:`Unknown subagent type: ${V}`,metadata:{execution_time_ms:Date.now()-z}};let A=$.getTagService(),R=U,b={prompt:R,subagentType:V,timeout:O,reason:F,tagService:A},w={component:{name:"task",version:"1.0.0"},data:b,metadata:{sessionId:M},phase:"before",hookPoint:q0.DELEGATE_BEFORE};return await T0.execute(q0.DELEGATE_BEFORE,b,{sessionId:M}),R=b.prompt,await SF(X,M,B,R,b.subagentType,b.timeout,D,H.sub_session_id,j,W.model,W.fallbackModel,W.fallbackModels,W.metadata?.systemPrompt,jF(W.metadata?.extendTools))}};return Y.execute=H0(Y.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),Y}function RF(){let $=F$();if(!$)return;let J=$.envEvent,Q=J?.metadata?.triggerEventId;if(typeof Q==="string"&&Q.length>0)return Q;let X=J?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var ZF=H0(RF,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function wF(){let $=F$()?.replyChannel;if(!$)return;if(!$.chatId&&!$.messageId)return;let J={...$.params??{}};if($.userId&&J.userId===void 0)J.userId=$.userId;return{type:$.type,appId:$.appId,chatId:$.chatId,messageId:$.messageId,profile:$.profile,params:Object.keys(J).length>0?J:void 0}}var PF=H0(wF,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});function bF(){let $=F$()?.pluginEnabled;if(!$)return;if(typeof $!=="object")return;if(Object.keys($).length===0)return;return{...$}}var EF=H0(bF,"delegate.capturePluginEnabled",{recordParams:!1,recordResult:!0,recordError:!0});async function SF($,J,Q,X,q,Y,G,W,z,H,B,U,V,O){let F=Date.now();try{let D=q,M=X,j,L=$.resolveEntryAgent(q);if(L)j=q,D=L,M=NF({workflowName:j,originalPrompt:X,description:Q}),g.info(`[delegate_task] Routing workflow subagent '${q}' \u2192 entry-agent '${L}'`);let{taskId:A,subSessionId:R}=await $.createTask({parentSessionId:J,description:Q,prompt:M,subagentType:D,timeout:Y,similarTaskIds:G,originalWorkflowName:j,existingSubSessionId:W,triggerEventId:z,model:H,fallbackModel:B,fallbackModels:U,systemPrompt:V,extendTools:O});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${A}`,`\uD83D\uDCDD Description: ${Q}`,`\uD83E\uDD16 Sub-agent: ${D}${j?` (workflow: ${j})`:""}`,`\u23F1\uFE0F Timeout: ${(Y||R9)/1000}s`,"",`\uD83D\uDD17 Sub-session: ${R} \uFF08\u7EED\u8DD1\u672C\u4EFB\u52A1\uFF1Adelegate_task(sub_session_id="${R}", prompt="...")\uFF09`,"",`Use stop_task with task_id="${A}" to cancel this task.`].join(`
2629
+ `),metadata:{execution_time_ms:Date.now()-F,sessionId:R,background:!0,status:"accepted",bgProcessId:A}}}catch(D){return{success:!1,output:"",error:D instanceof Error?D.message:String(D),metadata:{execution_time_ms:Date.now()-F}}}}i();class O0 extends Error{endpoint;cause;constructor($,J,Q){super($);this.endpoint=J,this.cause=Q,this.name=new.target.name}}class v8 extends O0{}class x8 extends O0{}class y8 extends O0{}class D2 extends O0{}var CF=new Set(["createTask","updateTask","deleteTask","createOperation","updateOperation","deleteOperation","createTag","deleteTag","addTagsToTask","removeTagsFromTask","updateTaskTags"]);var PJ=1;function fF($){let J=$.length;while(J>0){let Q=$[J-1];if(Q===null||Q===void 0)J-=1;else break}return J===$.length?$:$.slice(0,J)}var IF=d("task-remote");class T${endpoint;authToken;timeoutMs;maxRetries;retryBaseDelayMs;fetchImpl;log;stats={handshakes:0,requests:0,retries:0};handshake;closed=!1;constructor($){if(!$?.endpoint)throw Error("[RemoteTaskStore] endpoint is required (task.storage.endpoint)");this.endpoint=$.endpoint.replace(/\/+$/,""),this.authToken=$.authToken,this.timeoutMs=$.timeoutMs??5000,this.maxRetries=$.maxRetries??3,this.retryBaseDelayMs=$.retryBaseDelayMs??200,this.fetchImpl=$.fetchImpl??globalThis.fetch,this.log=$.log??IF}getStats(){return{...this.stats}}ensureOpen(){if(this.closed)throw new O0(`RemoteTaskStore is closed (endpoint=${this.endpoint})`,this.endpoint)}async ensureHandshake(){if(!this.handshake)this.handshake=this.doHandshake().catch(($)=>{throw this.handshake=void 0,$});return this.handshake}async doHandshake(){this.ensureOpen();let $;try{$=await this.fetchWithTimeout(`${this.endpoint}/version`,{method:"GET"})}catch(X){throw new O0(`Cannot reach task-service at ${this.endpoint} (/version): ${X instanceof Error?X.message:String(X)}. Start it (systemctl --user start roy-task-service) or set task.storage.endpoint correctly. No local fallback is performed by design.`,this.endpoint,X)}if(!$.ok)throw new D2(`task-service /version returned HTTP ${$.status} (endpoint=${this.endpoint})`,this.endpoint);let Q=(await $.json().catch(()=>({})))?.protocol?.major;if(typeof Q!=="number")throw new D2(`task-service /version response has no protocol.major (endpoint=${this.endpoint})`,this.endpoint);if(Q!==PJ)throw new D2(`Protocol mismatch: client speaks store-major ${PJ}, task-service speaks ${Q} (endpoint=${this.endpoint}). Upgrade one side.`,this.endpoint);this.stats.handshakes+=1}async fetchWithTimeout($,J){let Q=new AbortController,X=setTimeout(()=>Q.abort(),this.timeoutMs);try{return await this.fetchImpl($,{...J,signal:Q.signal})}finally{clearTimeout(X)}}isRetryableStatus($){return $===503||$===502||$===504||$>=500}async call($,J){this.ensureOpen(),await this.ensureHandshake();let Q=fF(J),X=CF.has($)?`${$}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`:void 0,q;for(let Y=0;Y<=this.maxRetries;Y++){if(Y>0){this.stats.retries+=1;let U=this.retryBaseDelayMs*2**(Y-1);this.log.debug?.(`[RemoteTaskStore] retry ${Y}/${this.maxRetries} ${$} in ${U}ms`),await new Promise((V)=>setTimeout(V,U))}let G={"content-type":"application/json"};if(this.authToken)G.authorization=`Bearer ${this.authToken}`;if(X)G["idempotency-key"]=X;this.stats.requests+=1;let W;try{W=await this.fetchWithTimeout(`${this.endpoint}/store/${$}`,{method:"POST",headers:G,body:JSON.stringify({args:Q})})}catch(U){if(q=U,Y===this.maxRetries)throw new O0(`task-service request failed: ${$} (endpoint=${this.endpoint}) after ${Y+1} attempts: ${U instanceof Error?U.message:String(U)}. No local fallback is performed by design.`,this.endpoint,U);continue}if(W.ok){let U=await W.text();if(!U)return;try{return JSON.parse(U)}catch(V){throw new O0(`task-service returned non-JSON for ${$} (endpoint=${this.endpoint})`,this.endpoint,V)}}let z=await W.json().catch(()=>null),H=z?.error?.code??"",B=z?.error?.message??`HTTP ${W.status}`;if(W.status===401)throw new v8(`task-service rejected the request (401 ${H}): ${B}. Check task.storage.authToken against the service's TASK_AUTH_TOKEN (endpoint=${this.endpoint}).`,this.endpoint);if(W.status===409&&H==="IDEMPOTENCY_CONFLICT")throw new x8(`task-service idempotency conflict for ${$}: ${B} (endpoint=${this.endpoint})`,this.endpoint);if(W.status===404&&H==="METHOD_NOT_FOUND")throw new D2(`task-service does not implement ${$}() \u2014 service is older than this client `+`(endpoint=${this.endpoint}). deploy a newer task-service.`,this.endpoint);if(W.status===400)throw new O0(`task-service rejected ${$} payload (400 ${H}): ${B} (endpoint=${this.endpoint})`,this.endpoint);if(W.status===503&&H==="BUSY"){if(q=new y8(`sqlite backend busy for ${$}: a batch transaction holds the single shared connection; retried ${this.maxRetries} times without success (endpoint=${this.endpoint}). Retry after the batch completes.`,this.endpoint),Y===this.maxRetries)throw q;continue}if(this.isRetryableStatus(W.status)){if(q=new O0(`task-service error for ${$} (HTTP ${W.status} ${H}): ${B} (endpoint=${this.endpoint})`,this.endpoint),Y===this.maxRetries)throw q;continue}throw new O0(`task-service rejected ${$} (HTTP ${W.status} ${H}): ${B} (endpoint=${this.endpoint})`,this.endpoint)}throw new O0(`task-service call ${$} exhausted retries (endpoint=${this.endpoint}): ${q instanceof Error?q.message:String(q)}`,this.endpoint,q)}createTask($){return this.call("createTask",[$])}async getTask($){return await this.call("getTask",[$])??void 0}async updateTask($,J){return await this.call("updateTask",[$,J])??void 0}deleteTask($){return this.call("deleteTask",[$])}listTasks($){return this.call("listTasks",[$])}async getTaskIdBySessionId($){return await this.call("getTaskIdBySessionId",[$])??void 0}getTaskIdsBySessionId($){return this.call("getTaskIdsBySessionId",[$])}createOperation($){return this.call("createOperation",[$])}async getOperation($){return await this.call("getOperation",[$])??void 0}async updateOperation($,J){return await this.call("updateOperation",[$,J])??void 0}deleteOperation($){return this.call("deleteOperation",[$])}listOperations($){return this.call("listOperations",[$])}listOperationsFresh($){return this.call("listOperationsFresh",[$])}invalidateOperationsCache($){this.call("invalidateOperationsCache",[$]).catch((J)=>{this.log.warn?.(`[RemoteTaskStore] invalidateOperationsCache(${$}) failed: ${J instanceof Error?J.message:String(J)}`)})}createTag($){return this.call("createTag",[$])}async getTag($){return await this.call("getTag",[$])??void 0}async getTagByName($){return await this.call("getTagByName",[$])??void 0}listTags($){return this.call("listTags",[$])}searchTags($){return this.call("searchTags",[$])}deleteTag($){return this.call("deleteTag",[$])}async addTagsToTask($,J){await this.call("addTagsToTask",[$,J])}async removeTagsFromTask($,J){await this.call("removeTagsFromTask",[$,J])}getTagsForTask($){return this.call("getTagsForTask",[$])}getTaskIdsByTags($){return this.call("getTaskIdsByTags",[$])}async updateTaskTags($,J){await this.call("updateTaskTags",[$,J])}searchTasksByKeywords($,J){return this.call("searchTasksByKeywords",[$,J])}findSimilarTasksByKeywords($,J){return this.call("findSimilarTasksByKeywords",[$,J])}getTaskTree($,J){return this.call("getTaskTree",[$,J])}getChildTasks($,J){return this.call("getChildTasks",[$,J])}findSimilarTasks($,J){return this.call("findSimilarTasks",[$,J])}searchTasks($,J){return this.call("searchTasks",[$,J])}findTasksByContextValue($,J){return this.call("findTasksByContextValue",[$,J])}close(){this.closed=!0}}var v$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};D0();var TF=20;var vF=["expected_decision","expected_root","expected_","case_id","category","suggested_","recommended_","best_match","answer","answer_key","label","should_","target","gold","ground_truth","hint","solution","duplicate_of","similar_task_ids","candidate_order","verdict","decision"];function xF($){if(!$)return[];let J;try{J=JSON.parse($)}catch{return[]}if(!J||typeof J!=="object"||Array.isArray(J))return[];let Q=J.similar_task_ids;if(!Array.isArray(Q))return[];let X=[],q=new Set;for(let Y of Q){if(typeof Y!=="number")continue;if(!Number.isInteger(Y)||Y<=0)continue;if(q.has(Y))continue;if(q.add(Y),X.push(Y),X.length>=TF)break}return X}function yF($){switch($){case"completed":case"cancelled":case"paused":case"archived":return"reopen";case"todo":case"active":default:return"enhance"}}function bJ($){return $==="paused"?"active":"todo"}var g8="__NEW_TASK_ID__",k8="#__NEW_TASK_ID__";function hF($){switch($.scenario){case"reuse":return gF($);case"reopen":return kF($);case"reopen_enhance":return mF($);case"remount":return uF($);case"soft_reuse":return lF($)}}function h8($){return $.newTaskId>0?String($.newTaskId):g8}function Z0($){return $.newTaskId>0?`#${$.newTaskId}`:k8}function w9($){let J=$.targetTask;if(!J)return"";return`#${$.targetTaskId} [${J.type}] ${J.title}
2630
+ \u72B6\u6001\uFF1A${J.status}`}function gF($){let J=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u4E0E\u5DF2\u6709\u4EFB\u52A1\u9AD8\u5EA6\u76F8\u4F3C\uFF0C\u5EFA\u8BAE\u590D\u7528\u800C\u975E\u65B0\u5EFA\u3002","",w9($),"\u72B6\u6001\uFF1A"+($.targetTask?.status??"")+" \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Aenhance\uFF08\u8865\u5145\u76EE\u6807/\u63CF\u8FF0\uFF09","",`\u5982\u9700\u5408\u5E76\u5230 #${$.targetTaskId}\uFF0C\u53EF\u6267\u884C\uFF1A`,` task_update(task_id=${$.targetTaskId}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${J})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${Z0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${Z0($)}\u3002`,"","\u6838\u5B9E\u8981\u70B9\uFF1A\u672C\u6B21\u8BF7\u6C42\u662F\u5426\u5C31\u662F #"+$.targetTaskId+" \u7684\u300C\u540C\u4E00\u4EF6\u4E8B\u300D\uFF0C\u800C\u4E0D\u662F\u540C\u4E3B\u9898\u4E0B\u65B0\u7684\u4E00\u6B65\uFF1F"," - \u82E5\u53EA\u662F\u540C\u4E3B\u9898\u7684\u65B0\u4E00\u6B65\uFF08\u9700\u8981\u72EC\u7ACB\u8DDF\u8E2A\u7684\u65B0\u5B50\u4EFB\u52A1\uFF09\uFF0C\u5EFA\u5B50\u4EFB\u52A1\u4E0D\u7B97\u4E0D\u91C7\u7EB3\uFF0C\u4F46\u9700\u5728\u56DE\u590D\u4E2D\u8BF4\u660E\u4E3A\u4F55\u4E0D\u76F4\u63A5\u5408\u5E76\u3002"," - \u82E5\u786E\u5B9E\u662F\u540C\u4E00\u4EF6\u4E8B\uFF0C\u5E94\u91C7\u7EB3 (a) \u6267\u884C\u590D\u7528\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, ...) \u6267\u884C\u590D\u7528\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${Z0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2631
+ `)}function kF($){let J=$.targetTask?.status??"completed",Q=bJ(J),X=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u4E0E\u5DF2\u6709\u4EFB\u52A1\u5B9E\u8D28\u76F8\u540C\uFF0C\u5EFA\u8BAE\u91CD\u5F00\u8BE5\u4EFB\u52A1\u800C\u4E0D\u662F\u65B0\u5EFA\u3002","",w9($),`\u72B6\u6001\uFF1A${J} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen\uFF08\u6062\u590D\u4E3A ${Q}\uFF09`,"","\u5982\u9700\u91CD\u5F00\u5E76\u627F\u63A5\u672C\u6B21\u8BF7\u6C42\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, status=${Q}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${X})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${Z0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${Z0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A#${$.targetTaskId} \u662F\u5426\u771F\u7684\u5DF2\u5B8C\u7ED3\uFF08completed / cancelled\uFF09\uFF0C\u4F46\u5176\u8BED\u4E49\u4E0E\u672C\u6B21\u8BF7\u6C42\u4ECD\u7136\u76F8\u540C\uFF1F`," - \u82E5\u5DF2\u5B8C\u7ED3\u4F46\u8BED\u4E49\u4ECD\u76F8\u540C\uFF08\u672C\u6B21\u8BF7\u6C42\u662F\u8BE5\u4EFB\u52A1\u7684\u5EF6\u7EED\uFF09\u2192 \u5E94\u91C7\u7EB3 (a) \u91CD\u5F00\u3002"," - \u82E5\u76EE\u6807\u5DF2\u5B8C\u7ED3\u4E14\u8BED\u4E49\u4E0D\u540C\uFF08\u53EA\u662F\u4E3B\u9898\u76F8\u8FD1\uFF09\u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, status=${Q}, ...) \u6267\u884C\u91CD\u5F00\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${Z0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2632
+ `)}function mF($){let J=$.targetTask?.status??"completed",Q=bJ(J);return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u4E0E\u5DF2\u6709\u4EFB\u52A1\u5B9E\u8D28\u76F8\u540C\uFF0C\u4E14\u672C\u6B21\u65B0\u589E\u4E86\u76EE\u6807\uFF0C\u5EFA\u8BAE\u91CD\u5F00\u5E76\u589E\u5F3A\u8BE5\u4EFB\u52A1\u3002","",w9($),`\u72B6\u6001\uFF1A${J} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen + enhance\uFF08\u6062\u590D\u4E3A ${Q} \u5E76\u8FFD\u52A0\u76EE\u6807\uFF09`,"","\u5982\u9700\u91CD\u5F00\u5E76\u627F\u63A5\u672C\u6B21\u8BF7\u6C42\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, status=${Q}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>, goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>)`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${Z0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${Z0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A\u2460 #${$.targetTaskId} \u662F\u5426\u771F\u7684\u5DF2\u5B8C\u7ED3\uFF08completed / cancelled\uFF09\u4F46\u8BED\u4E49\u4ECD\u4E0E\u672C\u6B21\u8BF7\u6C42\u76F8\u540C\uFF1B\u2461 \u672C\u6B21\u65B0\u589E\u7684\u76EE\u6807\u662F\u5426\u786E\u5B9E\u5C5E\u4E8E\u8BE5\u4EFB\u52A1\u7684\u8303\u56F4\u5185\uFF1F`," - \u4E24\u70B9\u90FD\u6210\u7ACB \u2192 \u5E94\u91C7\u7EB3 (a) \u91CD\u5F00\u5E76\u589E\u5F3A\u3002"," - \u65B0\u589E\u76EE\u6807\u8D85\u51FA\u539F\u4EFB\u52A1\u8303\u56F4\uFF08\u662F\u72EC\u7ACB\u7684\u65B0\u5DE5\u4F5C\uFF09\u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, status=${Q}, ..., goals_and_expected_deliverables=...) \u6267\u884C\u91CD\u5F00\u5E76\u589E\u5F3A\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${Z0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2633
+ `)}function uF($){return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u4EFB\u52A1\u7684\u6302\u8F7D\u4F4D\u7F6E\u53EF\u80FD\u4E0D\u5408\u7406\u3002","",`\u5F53\u524D\u6302\u8F7D\uFF1Aparent #${$.currentParentId} \u2192 root \u7956\u5148 #${$.currentRootAncestorId}`,`\u5EFA\u8BAE\u5F52\u5C5E\uFF1Aroot #${$.recommendedRootId} ${$.recommendedRootTitle??""}`.trimEnd(),"","\u5982\u9700\u6539\u6302\u5230\u5EFA\u8BAE\u7684 root \u4E0B\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${h8($)}, parent_task_id=${$.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${Z0($)}\uFF0Cparent \u672A\u88AB\u81EA\u52A8\u4FEE\u6539\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A\u5F53\u524D parent #${$.currentParentId} \u7684 root \u7956\u5148 #${$.currentRootAncestorId} \u4E0E\u5EFA\u8BAE\u7684 root #${$.recommendedRootId}\uFF0C\u54EA\u4E00\u6761\u624D\u662F\u672C\u6B21\u4EFB\u52A1\u7684\u6B63\u786E\u5F52\u5C5E\u7EBF\uFF1F\uFF08\u53EF\u53C2\u8003\u5144\u5F1F\u4EFB\u52A1\u7684\u4E3B\u9898\u5206\u5E03\uFF09`," - \u5EFA\u8BAE\u7684 root \u66F4\u8D34\u5408\u672C\u6B21\u4EFB\u52A1\u4E3B\u9898 \u2192 \u5E94\u91C7\u7EB3 (a) \u6267\u884C\u6539\u6302\u3002"," - \u5F53\u524D\u5F52\u5C5E\u7EBF\u5DF2\u6B63\u786E \u2192 \u5E94\u91C7\u7EB3 (b) \u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${h8($)}) \u786E\u8BA4\u672C\u6B21\u65B0\u5EFA\u4EFB\u52A1\u7684\u5B9E\u9645 parent\uFF0C\u5E76\u7528 task_get(${$.recommendedRootId})\uFF08\u5FC5\u8981\u65F6 task_tree\uFF09\u786E\u8BA4\u5F52\u5C5E\u7EBF\u662F\u5426\u771F\u7684\u4E0D\u5BF9\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u6302\u8F7D\u4E0D\u5408\u7406 \u2192 \u6267\u884C\u6539\u6302 task_update(task_id=${h8($)}, parent_task_id=${$.recommendedRootId})\uFF1B`,"(b) \u786E\u8BA4\u5F53\u524D\u6302\u8F7D\u5408\u7406 \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2634
+ `)}function lF($){let J=$.includeGoals?", goals_and_expected_deliverables=<\u8FFD\u52A0\u672C\u6B21\u76EE\u6807>":"";return["[TASK_CREATE_HINT] \u68C0\u6D4B\u5230\u672C\u6B21\u8BF7\u6C42\u53EF\u80FD\u4E0E\u5DF2\u6709\u4EFB\u52A1\u6709\u5173\u8054\uFF08\u7F6E\u4FE1\u5EA6\u504F\u4F4E\uFF0C\u4EC5\u4F9B\u53C2\u8003\uFF09\u3002","",w9($),"","\u82E5\u786E\u8BA4\u662F\u540C\u4E00\u4EF6\u4E8B\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${$.targetTaskId}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${J})`,"",`\u8BF4\u660E\uFF1A\u672C\u63D0\u793A\u57FA\u4E8E\u8F83\u4F4E\u7F6E\u4FE1\u5EA6\uFF0C\u53EF\u80FD\u8BEF\u5224\u3002\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${Z0($)}\u3002`,"",`\u6838\u5B9E\u8981\u70B9\uFF1A#${$.targetTaskId} \u4E0E\u672C\u6B21\u8BF7\u6C42\u662F\u5426\u786E\u4E3A\u540C\u4E00\u4EF6\u4E8B\uFF1F\uFF08\u672C\u63D0\u793A\u7F6E\u4FE1\u5EA6\u4F4E\uFF0C\u6838\u5B9E\u6743\u91CD\u76F8\u5E94\u964D\u4F4E\uFF0C\u4F46\u4E0D\u5F97\u8DF3\u8FC7\u8868\u6001\uFF09`,"",`\u26A0\uFE0F \u4F60\u5FC5\u987B\u6838\u5B9E\u672C\u63D0\u793A\uFF1A\u5148\u7528 task_get(${$.targetTaskId}) \u786E\u8BA4\u76EE\u6807\u4EFB\u52A1\u7684\u5F53\u524D\u72B6\u6001\u4E0E\u5185\u5BB9\u662F\u5426\u4E0E\u672C\u6B21\u8BF7\u6C42\u5B9E\u8D28\u76F8\u540C\u3002`,"\u6838\u5B9E\u540E\u4E8C\u9009\u4E00\u6267\u884C\uFF1A",`(a) \u786E\u8BA4\u5B9E\u8D28\u76F8\u540C \u2192 \u6309\u4E0A\u9762\u7684 task_update(task_id=${$.targetTaskId}, ...) \u6267\u884C\u590D\u7528\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${Z0($)}\uFF1B`,"(b) \u786E\u8BA4\u4E0D\u76F8\u4F3C \u2192 \u5728\u672C\u6B21\u56DE\u590D\u4E2D\u660E\u786E\u8BF4\u660E\u4E0D\u91C7\u7EB3\u7684\u7406\u7531\u3002","\u4E0D\u5141\u8BB8\u65E0\u89C6\u672C\u63D0\u793A\u3002"].join(`
2635
+ `)}function cF($){let J=$.toLowerCase();return vF.some((Q)=>Q.endsWith("_")||Q.endsWith("*")?J.startsWith(Q.slice(0,-1)):J===Q)}function dF($,J){let Q=(X,q)=>{if(Array.isArray(X)){X.forEach((Y,G)=>Q(Y,`${q}[${G}]`));return}if(!X||typeof X!=="object")return;for(let[Y,G]of Object.entries(X)){let W=q?`${q}.${Y}`:Y;if(cF(Y))throw Error(`[assertNoLeakage] leakage key detected at ${W}: "${Y}"`);Q(G,W)}};Q($,"state"),Q(J,"questions")}function pF($,J){let Q;try{Q=JSON.parse($.context)}catch{return!1}if(!Q||typeof Q!=="object"||Array.isArray(Q))return!1;return Q.decision_hint=J,$.context=JSON.stringify(Q),!0}var tL=H0(xF,"task.decision.parseSimilarTaskIds",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0],Q=typeof J==="string"?J:"";return{contextLen:Q.length,contextPreview:Q.length>80?Q.slice(0,80)+"\u2026":Q}},resultFilter:($)=>({count:$.length,ids:$.join(",")})}),eL=H0(yF,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),$N=H0(hF,"task.decision.buildHintText",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0]??{};return{scenario:J.scenario,newTaskId:J.newTaskId,targetTaskId:J.targetTaskId??null,recommendedRootId:J.recommendedRootId??null,currentParentId:J.currentParentId??null,confidence:J.confidence??null}},resultFilter:($)=>({hintLen:$.length,hintPreview:$.slice(0,240),hasTaskUpdate:/task_update\s*\(/.test($),hasTaskId:/"task_id"\s*:/.test($),hasParentTaskId:/"parent_task_id"\s*:/.test($)})}),JN=H0(dF,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:($)=>({stateKeys:Z9($[0]),questionKeys:Z9($[1])})}),QN=H0(pF,"task.decision.writeDecisionHint",{recordParams:!0,recordResult:!0,log:!1,paramFilter:($)=>{let J=$[0]??{},Q=typeof $[1]==="string"?$[1]:"";return{contextLen:typeof J.context==="string"?J.context.length:0,hintLen:Q.length,hintScenario:/task_update\s*\(/.test(Q)?"actionable":"plain"}},resultFilter:($)=>({written:$}),errorIf:($)=>$===!1?Error("writeDecisionHint returned false (context not a JSON object)"):void 0});function Z9($,J=[],Q=0){if(J.length>=40||Q>4)return J;if(Array.isArray($)){for(let X of $.slice(0,3))Z9(X,J,Q+1);return J}if(!$||typeof $!=="object")return J;for(let X of Object.keys($)){if(J.length>=40)break;if(!J.includes(X))J.push(X);Z9($[X],J,Q+1)}return J}import{execSync as aF}from"child_process";var EJ="unknown",iF='{"type":"unknown"}';function nF(){return{task_id:K.number().describe("Task ID")}}function rF($){if(typeof $!=="object"||$===null||Array.isArray($))return $;let J=$;if(J.task_id===void 0&&J.id!==void 0)return{...J,task_id:J.id};return J}function J6($){return K.preprocess(rF,K.object({...nF(),...$}))}var SJ=K.object({title:K.string().describe("Task title"),description:K.string().optional().describe("Task description"),priority:K.enum(["low","medium","high"]).optional().describe("Task priority"),type:K.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:K.string().optional().describe("Goals and expected deliverables. "+"\u26A0\uFE0F \u5199\u6210\u53EF\u9010\u6761\u9A8C\u6536\u7684\u7F16\u53F7\u5B50\u9879\uFF081. \u2026 2. \u2026 3. \u2026\uFF09\uFF0C\u6BCF\u6761\u662F\u4E00\u4E2A\u53EF\u5224\u5B9A\u7684\u4EA4\u4ED8/\u52A8\u4F5C"+"\uFF08\u6587\u4EF6\u65AD\u8A00\uFF1A\u6587\u4EF6\u5B58\u5728/\u5927\u5C0F/\u5185\u5BB9\uFF1B\u8FDB\u7A0B\u65AD\u8A00\uFF1A\u547D\u4EE4 exit code/stdout\uFF1B"+"\u6D4B\u8BD5\u65AD\u8A00\uFF1Apass/fail \u8BA1\u6570\uFF1B\u72B6\u6001\u65AD\u8A00\uFF1A\u7248\u672C\u53F7/HTTP 200/\u72B6\u6001\u5B57\u6BB5\uFF09\u3002"+"\u907F\u514D\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF08\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D\uFF09\u2014\u2014"+"\u4EFB\u52A1\u5B8C\u6210\u65F6 completion hook \u4F1A\u6309\u8FD9\u4E9B\u5B50\u9879\u9010\u6761\u5BF9\u7167\u64CD\u4F5C\u8BB0\u5F55\u9A8C\u6536\u3002"),due_date:K.string().optional().describe("Due date (ISO format)"),tags:K.array(K.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:K.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:K.union([K.number(),K.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
2632
2636
  `+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
2633
2637
  `+`**\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
2634
2638
  `+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
@@ -2636,9 +2640,9 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
2636
2640
  `+` 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
2637
2641
  `+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
2638
2642
  `+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
2639
- `+"\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:K.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! `+"**Task #4467 \u2014 similar_task_ids (REQUIRED)**: array of existing task ids that "+"cover the same ground as this request, used by the task:before.create decision check to suggest reusing/reopening instead of creating a duplicate. Search first (task_search / task_get), then pass the ids. "+"It may be an empty array [] if you searched and found nothing related \u2014 "+'but the field itself must be present. Example: {"type":"feature", "similar_task_ids": [4433, 4445]}')}),_3=a2({include_operations:K.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.")}),A3=K.object({status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional(),priority:K.enum(["low","medium","high"]).optional(),type:K.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:K.number().optional().default(20),offset:K.number().optional().default(0),depth:K.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:K.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")}),Z3=K.object({keywords:K.array(K.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:K.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:K.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:K.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:K.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:K.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:K.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:K.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")}),w3=a2({title:K.string().optional(),description:K.string().optional(),status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional(),priority:K.enum(["low","medium","high"]).optional(),type:K.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:K.number().min(0).max(100).optional(),current_status:K.string().optional(),goals_and_expected_deliverables:K.string().optional().describe("Goals and expected deliverables. "+"\u26A0\uFE0F \u8FFD\u52A0/\u4FEE\u6539\u65F6\u540C\u6837\u5199\u6210\u53EF\u9010\u6761\u9A8C\u6536\u7684\u7F16\u53F7\u5B50\u9879\uFF081. \u2026 2. \u2026 3. \u2026\uFF09\uFF0C"+"\u6BCF\u6761\u662F\u4E00\u4E2A\u53EF\u5224\u5B9A\u7684\u4EA4\u4ED8/\u52A8\u4F5C\uFF08\u6587\u4EF6\u65AD\u8A00\uFF1A\u6587\u4EF6\u5B58\u5728/\u5927\u5C0F/\u5185\u5BB9\uFF1B"+"\u8FDB\u7A0B\u65AD\u8A00\uFF1A\u547D\u4EE4 exit code/stdout\uFF1B\u6D4B\u8BD5\u65AD\u8A00\uFF1Apass/fail \u8BA1\u6570\uFF1B"+"\u72B6\u6001\u65AD\u8A00\uFF1A\u7248\u672C\u53F7/HTTP 200/\u72B6\u6001\u5B57\u6BB5\uFF09\u3002"+"\u907F\u514D\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF08\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D\uFF09\u2014\u2014"+"\u4EFB\u52A1\u5B8C\u6210\u65F6 completion hook \u4F1A\u6309\u8FD9\u4E9B\u5B50\u9879\u9010\u6761\u5BF9\u7167\u64CD\u4F5C\u8BB0\u5F55\u9A8C\u6536\u3002"+"\uFF08Task #4833 \u2014 \u4E0E task_create \u7684 goals \u89C4\u5219\u540C\u6E90\uFF09"),due_date:K.string().optional(),tags:K.array(K.string()).optional(),project_path:K.string().optional().describe("Project path, identifies which project this task belongs to"),context:K.string().optional().describe("Task context information for storing additional context"),parent_task_id:K.union([K.number(),K.null()]).optional().describe("Parent task ID (set to null to make it a root task)")}),P3=K.object({task_id:K.number().describe("Task ID")}),b3=a2({}),E3=a2({deliverable_storage_path:K.string().optional().describe("\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\uFF08\u8DEF\u5F84 / URL / \u5206\u652F\u540D\u7B49\uFF09\u3002"+"\u4F1A\u6301\u4E45\u5316\u5230 task.context.deliverable_storage_path\uFF0C"+"\u5E76\u5199\u5165 operation \u8BB0\u5F55\uFF08Deliverable \u884C\uFF09\uFF0C\u4F9B\u9A8C\u6536\u65B9 task_complete \u65F6\u9010\u6761\u5BF9\u7167\u3002"),current_status:K.string().optional().describe("\u672C\u6B21\u4EA4\u4ED8\u7684\u8FDB\u5C55\u6458\u8981\uFF08\u53EF\u9009\uFF09\u3002"+"\u4F1A\u62FC\u8FDB\u300C\u5F85\u9A8C\u8BC1\uFF1A\u300D\u6587\u6848\uFF0C\u4F5C\u4E3A\u4EFB\u52A1\u5F53\u524D\u72B6\u6001\u5C55\u793A\u7ED9\u9A8C\u6536\u65B9\uFF08default agent\uFF09\u3002")}),S3=a2({reason:K.string().optional().describe("\u53D6\u6D88\u539F\u56E0\uFF08\u53EF\u9009\uFF09\u3002\u4F1A\u5199\u5165\u8BE5\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF0C\u4FBF\u4E8E\u4E8B\u540E\u8FFD\u6EAF\u9A8C\u6536\u7ED3\u8BBA\u3002")}),C3=K.object({task_ids:K.array(K.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:K.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),f3=K.object({task_ids:K.array(K.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),I3=K.object({depth:K.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:K.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:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:K.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:K.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:K.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")});B$();n();n();var vF=i("task-child-context"),xF=["commit","token","secret","password","api_key"];function T8($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map(T8);if(typeof $!=="object")return $;let J={};for(let[Q,X]of Object.entries($)){let Y=Q.toLowerCase();if(xF.some((G)=>Y.includes(G)))continue;J[Q]=T8(X)}return J}function hF($){let{parent:J,overrides:Q={}}=$,X=Q.contextInherit!==!1,Y=Q.inheritTags===!0,G=Q.projectPath??J.projectPath??"unknown",q={};if(J.contextJson&&J.contextJson.trim().length>0)try{let B=JSON.parse(J.contextJson);if(B&&typeof B==="object"&&!Array.isArray(B))q=B}catch(B){vF.debug(`[task-child-context] parent #${J.taskId} context is malformed JSON; continuing with empty inherited context (${B instanceof Error?B.message:String(B)})`),q={}}let W={};if(X){if(q.worktree_path!==void 0&&Q.worktreePath===void 0)W.worktree_path=q.worktree_path;if(q.branch!==void 0&&Q.branch===void 0)W.branch=q.branch;if(q.parent_branch!==void 0)W.parent_branch=q.parent_branch;if(q.type!==void 0)W.type=q.type;if(q.prior_context&&typeof q.prior_context==="object"){let U=q.prior_context,V={};for(let[O,F]of Object.entries(U)){if(O.toLowerCase()==="commit")continue;V[O]=F}if(Object.keys(V).length>0)W.prior_context=V}let B=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[U,V]of Object.entries(q)){if(B.has(U))continue;W[U]=V}}if(Q.worktreePath!==void 0)W.worktree_path=Q.worktreePath;if(Q.branch!==void 0)W.branch=Q.branch;let z=Q.createdAt??new Date().toISOString();W.created_at=z,W.child_of=J.taskId;let H=T8(W);return{project_path:G,context:JSON.stringify(H),inheritedTags:Y?J.tags??[]:[]}}var T3=i("task:tools:create"),yF=W4.split(`
2643
+ `+"\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:K.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! `+"**Task #4467 \u2014 similar_task_ids (REQUIRED)**: array of existing task ids that "+"cover the same ground as this request, used by the task:before.create decision check to suggest reusing/reopening instead of creating a duplicate. Search first (task_search / task_get), then pass the ids. "+"It may be an empty array [] if you searched and found nothing related \u2014 "+'but the field itself must be present. Example: {"type":"feature", "similar_task_ids": [4433, 4445]}'),owner:K.union([K.string(),K.null()]).optional().describe("\u8D1F\u8D23\u4EBA\uFF08owner\uFF09\uFF1A\u8FD9\u4E2A\u4EFB\u52A1\u7531**\u8C01**\u8D1F\u8D23\u63A8\u8FDB\uFF0C\u53EF\u7A7A\uFF08\u4E0D\u4F20 / \u4F20 null \u5373\u672A\u6307\u6D3E\uFF09\u3002"+"\u53D6\u503C\u4E3A\u81EA\u7531\u5B57\u7B26\u4E32\uFF08open_id / \u7528\u6237\u540D / \u90AE\u7BB1\u5747\u53EF\uFF0Ccore \u4E0D\u89E3\u91CA\u683C\u5F0F\uFF09\uFF1B"+"\u591A\u4EBA\u534F\u4F5C\u573A\u666F\u4E0B\u7528\u5B83\u533A\u5206\u8D1F\u8D23\u4EBA\uFF0C\u4E0E sessionId\uFF08\u8C01\u5728\u64CD\u4F5C\uFF09\u3001project_path\uFF08\u54EA\u4E2A\u9879\u76EE\uFF09\u6B63\u4EA4\u3002"+"\u5411\u540E\u517C\u5BB9\uFF1A\u7701\u7565\u8BE5\u5B57\u6BB5\u65F6\u4EFB\u52A1\u4EE5 owner=null \u521B\u5EFA\u3002")}),CJ=J6({include_operations:K.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.")}),fJ=K.object({status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional(),priority:K.enum(["low","medium","high"]).optional(),type:K.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:K.number().optional().default(20),offset:K.number().optional().default(0),depth:K.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:K.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")}),IJ=K.object({keywords:K.array(K.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:K.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:K.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:K.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:K.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:K.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:K.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:K.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")}),TJ=J6({title:K.string().optional(),description:K.string().optional(),status:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional(),priority:K.enum(["low","medium","high"]).optional(),type:K.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:K.number().min(0).max(100).optional(),current_status:K.string().optional(),goals_and_expected_deliverables:K.string().optional().describe("Goals and expected deliverables. "+"\u26A0\uFE0F \u8FFD\u52A0/\u4FEE\u6539\u65F6\u540C\u6837\u5199\u6210\u53EF\u9010\u6761\u9A8C\u6536\u7684\u7F16\u53F7\u5B50\u9879\uFF081. \u2026 2. \u2026 3. \u2026\uFF09\uFF0C"+"\u6BCF\u6761\u662F\u4E00\u4E2A\u53EF\u5224\u5B9A\u7684\u4EA4\u4ED8/\u52A8\u4F5C\uFF08\u6587\u4EF6\u65AD\u8A00\uFF1A\u6587\u4EF6\u5B58\u5728/\u5927\u5C0F/\u5185\u5BB9\uFF1B"+"\u8FDB\u7A0B\u65AD\u8A00\uFF1A\u547D\u4EE4 exit code/stdout\uFF1B\u6D4B\u8BD5\u65AD\u8A00\uFF1Apass/fail \u8BA1\u6570\uFF1B"+"\u72B6\u6001\u65AD\u8A00\uFF1A\u7248\u672C\u53F7/HTTP 200/\u72B6\u6001\u5B57\u6BB5\uFF09\u3002"+"\u907F\u514D\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF08\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D\uFF09\u2014\u2014"+"\u4EFB\u52A1\u5B8C\u6210\u65F6 completion hook \u4F1A\u6309\u8FD9\u4E9B\u5B50\u9879\u9010\u6761\u5BF9\u7167\u64CD\u4F5C\u8BB0\u5F55\u9A8C\u6536\u3002"+"\uFF08Task #4833 \u2014 \u4E0E task_create \u7684 goals \u89C4\u5219\u540C\u6E90\uFF09"),due_date:K.string().optional(),tags:K.array(K.string()).optional(),project_path:K.string().optional().describe("Project path, identifies which project this task belongs to"),context:K.string().optional().describe("Task context information for storing additional context"),parent_task_id:K.union([K.number(),K.null()]).optional().describe("Parent task ID (set to null to make it a root task)"),owner:K.union([K.string(),K.null()]).optional().describe("\u8D1F\u8D23\u4EBA\uFF08owner\uFF09\uFF1A\u53EF\u7A7A\u3002\u4F20\u5B57\u7B26\u4E32 = \u6307\u6D3E/\u6539\u6D3E\u8BE5\u8D1F\u8D23\u4EBA\uFF1B\u4F20 null \u6216\u7A7A\u5B57\u7B26\u4E32 = \u6E05\u7A7A\uFF08\u672A\u6307\u6D3E\uFF09\uFF1B"+"**\u7701\u7565\u8BE5\u5B57\u6BB5** = \u4E0D\u6539\u52A8\uFF08\u4E0E status / progress \u7B49\u5B57\u6BB5\u8BED\u4E49\u4E00\u81F4\uFF09\u3002"+"\u7528\u4E8E\u591A\u4EBA\u534F\u4F5C\u573A\u666F\u6807\u6CE8\u4EFB\u52A1\u8D1F\u8D23\u4EBA\u3002")}),vJ=K.object({task_id:K.number().describe("Task ID")}),xJ=J6({}),yJ=J6({deliverable_storage_path:K.string().optional().describe("\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\uFF08\u8DEF\u5F84 / URL / \u5206\u652F\u540D\u7B49\uFF09\u3002"+"\u4F1A\u6301\u4E45\u5316\u5230 task.context.deliverable_storage_path\uFF0C"+"\u5E76\u5199\u5165 operation \u8BB0\u5F55\uFF08Deliverable \u884C\uFF09\uFF0C\u4F9B\u9A8C\u6536\u65B9 task_complete \u65F6\u9010\u6761\u5BF9\u7167\u3002"),current_status:K.string().optional().describe("\u672C\u6B21\u4EA4\u4ED8\u7684\u8FDB\u5C55\u6458\u8981\uFF08\u53EF\u9009\uFF09\u3002"+"\u4F1A\u62FC\u8FDB\u300C\u5F85\u9A8C\u8BC1\uFF1A\u300D\u6587\u6848\uFF0C\u4F5C\u4E3A\u4EFB\u52A1\u5F53\u524D\u72B6\u6001\u5C55\u793A\u7ED9\u9A8C\u6536\u65B9\uFF08default agent\uFF09\u3002")}),hJ=J6({reason:K.string().optional().describe("\u53D6\u6D88\u539F\u56E0\uFF08\u53EF\u9009\uFF09\u3002\u4F1A\u5199\u5165\u8BE5\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF0C\u4FBF\u4E8E\u4E8B\u540E\u8FFD\u6EAF\u9A8C\u6536\u7ED3\u8BBA\u3002")}),gJ=K.object({task_ids:K.array(K.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:K.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),kJ=K.object({task_ids:K.array(K.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),mJ=K.object({depth:K.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:K.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:K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:K.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:K.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:K.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")});M$();i();i();var sF=d("task-child-context"),oF=["commit","token","secret","password","api_key"],tF=["decision_hint","decision_hint_delivered_at","decision_hint_digest","completion_hint"];function m8($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map(m8);if(typeof $!=="object")return $;let J={};for(let[Q,X]of Object.entries($)){let q=Q.toLowerCase();if(oF.some((Y)=>q.includes(Y)))continue;J[Q]=m8(X)}return J}function eF($){let{parent:J,overrides:Q={}}=$,X=Q.contextInherit!==!1,q=Q.inheritTags===!0,Y=Q.projectPath??J.projectPath??"unknown",G={};if(J.contextJson&&J.contextJson.trim().length>0)try{let B=JSON.parse(J.contextJson);if(B&&typeof B==="object"&&!Array.isArray(B))G=B}catch(B){sF.debug(`[task-child-context] parent #${J.taskId} context is malformed JSON; continuing with empty inherited context (${B instanceof Error?B.message:String(B)})`),G={}}let W={};if(X){if(G.worktree_path!==void 0&&Q.worktreePath===void 0)W.worktree_path=G.worktree_path;if(G.branch!==void 0&&Q.branch===void 0)W.branch=G.branch;if(G.parent_branch!==void 0)W.parent_branch=G.parent_branch;if(G.type!==void 0)W.type=G.type;if(G.prior_context&&typeof G.prior_context==="object"){let U=G.prior_context,V={};for(let[O,F]of Object.entries(U)){if(O.toLowerCase()==="commit")continue;V[O]=F}if(Object.keys(V).length>0)W.prior_context=V}let B=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at",...tF]);for(let[U,V]of Object.entries(G)){if(B.has(U))continue;W[U]=V}}if(Q.worktreePath!==void 0)W.worktree_path=Q.worktreePath;if(Q.branch!==void 0)W.branch=Q.branch;let z=Q.createdAt??new Date().toISOString();W.created_at=z,W.child_of=J.taskId;let H=m8(W);return{project_path:Y,context:JSON.stringify(H),inheritedTags:q?J.tags??[]:[]}}var uJ=d("task:tools:create"),$M=U4.split(`
2640
2644
  `).map(($)=>$.trim()?" "+$:$).join(`
2641
- `);function gF($){if(!$)return;try{let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J.decision_hint;return typeof Q==="string"&&Q.length>0?Q:void 0}catch{return}}function kF(){try{let $=TF("git rev-parse --show-toplevel",{stdio:["ignore","pipe","ignore"]}).toString().trim(),J=process.cwd();if(!$)return null;if(J!==$)return J;if(J.includes(".worktrees/")||J.includes(".worktree/"))return J;return null}catch{return null}}function s2($){return{name:"task_create",description:`
2645
+ `);function JM($){if(!$)return;try{let J=JSON.parse($);if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J.decision_hint;return typeof Q==="string"&&Q.length>0?Q:void 0}catch{return}}function QM(){try{let $=aF("git rev-parse --show-toplevel",{stdio:["ignore","pipe","ignore"]}).toString().trim(),J=process.cwd();if(!$)return null;if(J!==$)return J;if(J.includes(".worktrees/")||J.includes(".worktree/"))return J;return null}catch{return null}}function Q6($){return{name:"task_create",description:`
2642
2646
  Create a new task for tracking work.
2643
2647
 
2644
2648
  ## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
@@ -2707,7 +2711,7 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
2707
2711
  - Depth \u2264 5 (avoid deep nesting)
2708
2712
  - Same-theme tasks cluster under one parent
2709
2713
  - Long-tail/stranded tasks should be archived or merged
2710
- ${yF}
2714
+ ${$M}
2711
2715
 
2712
2716
  ## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
2713
2717
 
@@ -2803,22 +2807,22 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
2803
2807
  env-injected value is 0 / negative / non-integer, it's treated as
2804
2808
  missing \u2014 only positive integers are honored.
2805
2809
 
2806
- `,parameters:N3,execute:async(J,Q)=>{let X=N3.parse(J),Y=Q.session_id||"unknown",G=kF(),q=X.context,W=M9().parentTaskId,z=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,H=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,B=H!==void 0&&H!==j3,U=B?H:void 0,V=X.tags,O;if(z!==void 0)try{let F=await $.getTask(z);if(F){let D=hF({parent:{taskId:F.id,projectPath:F.project_path,contextJson:F.context??"",tags:F.tags},overrides:{projectPath:U,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(U===void 0)U=D.project_path;if(X.tags===void 0)V=D.inheritedTags;O=D.context}}catch(F){T3.debug(`[task_create] failed to pre-load parent #${z} for context inheritance: ${F instanceof Error?F.message:String(F)}`)}try{let F=X.context===CF?void 0:X.context,D=F?JSON.parse(F):{},M=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(O)try{let R=JSON.parse(O);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[L,N]of Object.entries(R))if(M[L]===void 0)M[L]=N}}catch{}if(!M.created_at)M.created_at=new Date().toISOString();if(!M.worktree_path&&G)M.worktree_path=G;q=JSON.stringify(M)}catch{q=X.context}try{let F=await $.createTask({parent_task_id:z,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:V,sessionId:Y,project_path:U??(B?H:j3),context:q});r2(F.id),T3.info(`[createTask] Trace: Task #${F.id} created, currentTaskId=${F.id} set in EnvContext`);let D=gF(F.context),M=D?D.replaceAll(I8,`#${F.id}`).replaceAll(f8,String(F.id)):"";return{success:!0,output:`Task created successfully: #${F.id} - ${F.title}`+(M?`
2810
+ `,parameters:SJ,execute:async(J,Q)=>{let X=SJ.parse(J),q=Q.session_id||"unknown",Y=QM(),G=X.context,W=L9().parentTaskId,z=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,H=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,B=H!==void 0&&H!==EJ,U=B?H:void 0,V=X.tags,O;if(z!==void 0)try{let F=await $.getTask(z);if(F){let D=eF({parent:{taskId:F.id,projectPath:F.project_path,contextJson:F.context??"",tags:F.tags},overrides:{projectPath:U,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(U===void 0)U=D.project_path;if(X.tags===void 0)V=D.inheritedTags;O=D.context}}catch(F){uJ.debug(`[task_create] failed to pre-load parent #${z} for context inheritance: ${F instanceof Error?F.message:String(F)}`)}try{let F=X.context===iF?void 0:X.context,D=F?JSON.parse(F):{},M=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(O)try{let j=JSON.parse(O);if(j&&typeof j==="object"&&!Array.isArray(j)){for(let[L,A]of Object.entries(j))if(M[L]===void 0)M[L]=A}}catch{}if(!M.created_at)M.created_at=new Date().toISOString();if(!M.worktree_path&&Y)M.worktree_path=Y;G=JSON.stringify(M)}catch{G=X.context}try{let F=await $.createTask({parent_task_id:z,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:V,sessionId:q,project_path:U??(B?H:EJ),context:G,owner:X.owner??null});$6(F.id),uJ.info(`[createTask] Trace: Task #${F.id} created, currentTaskId=${F.id} set in EnvContext`);let D=JM(F.context),M=D?D.replaceAll(k8,`#${F.id}`).replaceAll(g8,String(F.id)):"";return{success:!0,output:`Task created successfully: #${F.id} - ${F.title}`+(M?`
2807
2811
 
2808
- ${M}`:""),metadata:{execution_time_ms:0,task_id:F.id,status:F.status,createdAt:F.createdAt}}}catch(F){return{success:!1,output:"",error:F instanceof Error?F.message:String(F),metadata:{execution_time_ms:0}}}}}}function o2($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:_3,execute:async(J,Q)=>{let X=_3.parse(J);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 G=Y.task,q=G&&typeof G==="object"?{...G,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(q,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 t2($){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
2809
- `+"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:A3,execute:async(J,Q)=>{let X=A3.parse(J);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 e2($){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.
2812
+ ${M}`:""),metadata:{execution_time_ms:0,task_id:F.id,status:F.status,createdAt:F.createdAt}}}catch(F){return{success:!1,output:"",error:F instanceof Error?F.message:String(F),metadata:{execution_time_ms:0}}}}}}function X6($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:CJ,execute:async(J,Q)=>{let X=CJ.parse(J);try{if(X.include_operations){let q=await $.getTaskWithOperations(X.task_id);if(!q)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let Y=q.task,G=Y&&typeof Y==="object"?{...Y,operations:q.operations}:q;return{success:!0,output:JSON.stringify(G,null,2),metadata:{execution_time_ms:0}}}else{let q=await $.getTask(X.task_id);if(!q)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(q,null,2),metadata:{execution_time_ms:0}}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function q6($){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
2813
+ `+"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:fJ,execute:async(J,Q)=>{let X=fJ.parse(J);try{let q=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:q.total,count:q.tasks.length,truncated:q.total>q.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:q.tasks}),metadata:{execution_time_ms:0}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function Y6($){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.
2810
2814
 
2811
2815
  Returns { tasks, total, limit, offset } so you can paginate large result sets.
2812
2816
 
2813
- If \`keywords\` is empty, returns no results.`,parameters:Z3,execute:async(J,Q)=>{let X=Z3.parse(J);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 v8($){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.
2817
+ If \`keywords\` is empty, returns no results.`,parameters:IJ,execute:async(J,Q)=>{let X=IJ.parse(J);try{let q=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:q.tasks,total:q.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function u8($){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.
2814
2818
 
2815
2819
  Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
2816
2820
 
2817
- Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:C3,execute:async(J,Q)=>{let X=C3.parse(J),Y=X.task_ids,G=Q.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 q=[],W=0;for(let H of Y)try{if(await $.updateTask(H,{status:"archived",current_status:X.reason?`${L$}\uFF1A${X.reason}`:L$}))await $.createOperation({taskId:H,sessionId:G,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),W++,q.push({id:H,success:!0});else q.push({id:H,success:!1,error:"Task not found"})}catch(B){q.push({id:H,success:!1,error:B instanceof Error?B.message:String(B)})}return{success:!q.some((H)=>!H.success),output:JSON.stringify({archived_count:W,total:Y.length,errors:q.filter((H)=>!H.success).map((H)=>({id:H.id,error:H.error})),results:q},null,2),metadata:{execution_time_ms:0}}}}}function x8($){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
2821
+ Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:gJ,execute:async(J,Q)=>{let X=gJ.parse(J),q=X.task_ids,Y=Q.session_id||"batch-archive";if(!q||q.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let G=[],W=0;for(let H of q)try{if(await $.updateTask(H,{status:"archived",current_status:X.reason?`${w$}\uFF1A${X.reason}`:w$}))await $.createOperation({taskId:H,sessionId:Y,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),W++,G.push({id:H,success:!0});else G.push({id:H,success:!1,error:"Task not found"})}catch(B){G.push({id:H,success:!1,error:B instanceof Error?B.message:String(B)})}return{success:!G.some((H)=>!H.success),output:JSON.stringify({archived_count:W,total:q.length,errors:G.filter((H)=>!H.success).map((H)=>({id:H.id,error:H.error})),results:G},null,2),metadata:{execution_time_ms:0}}}}}function l8($){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
2818
2822
 
2819
2823
  Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
2820
2824
 
2821
- Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:f3,execute:async(J,Q)=>{let Y=f3.parse(J).task_ids;if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let G=[],q=0;for(let z of Y)try{if(await $.deleteTask(z))q++,G.push({id:z,success:!0});else G.push({id:z,success:!1,error:"Task not found"})}catch(H){G.push({id:z,success:!1,error:H instanceof Error?H.message:String(H)})}return{success:!G.some((z)=>!z.success),output:JSON.stringify({deleted_count:q,total:Y.length,errors:G.filter((z)=>!z.success).map((z)=>({id:z.id,error:z.error})),results:G},null,2),metadata:{execution_time_ms:0}}}}}B$();n();var mF=i("tool:update-task");async function uF($,J,Q){let X=new Set,Y=Q;while(Y!==null&&Y!==void 0){if(Y===J)return!0;if(X.has(Y))break;X.add(Y);let G=await $.getTask(Y);if(!G)break;Y=G.parent_task_id}return!1}function $6($){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:w3,execute:async(J,Q)=>{let X=w3.parse(J),Y=Q.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await uF($,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 G=Q.metadata?.agentType??void 0,q=Q.metadata?.agentName??void 0;if(X.status==="completed"&&G==="sub"){let z=$.env?.getComponent?.("agent"),B=(q&&z?.getAgent?z.getAgent(q):void 0)?.config;if(!(B?Array.isArray(B.allowedTools)&&B.allowedTools.includes("task_complete")||!Array.isArray(B.allowedTools)&&!(Array.isArray(B.deniedTools)&&B.deniedTools.includes("task_complete")):!1))return{success:!1,output:"",error:'Cannot set status="completed" without acceptance permission (Task #5007 \u2014 \u9A8C\u6536\u6743\u5206\u79BB). '+'\u6267\u884C\u65B9\u53EA\u80FD\u63A8\u8FDB\u8FDB\u5EA6\uFF1A\u7528 task_update(progress=100) \u8868\u793A"\u6211\u8FD9\u8FB9\u5E72\u5B8C\u4E86"\uFF0C'+"\u518D task_operation_create \u8BB0\u5F55\u7ED3\u8BBA\uFF0C\u7136\u540E\u7ED3\u675F\u8FD4\u56DE\uFF1B"+"\u4EFB\u52A1\u7EC8\u6001\u5FC5\u987B\u7531\u9A8C\u6536\u65B9\uFF08default agent / \u4E3B\u667A\u80FD\u4F53\uFF09\u8C03\u7528 task_complete \u843D\u5B9A\u3002",metadata:{execution_time_ms:0}}}let W=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(!W)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 r2(W.id),mF.info(`[updateTask] Trace: Task #${W.id} updated, currentTaskId=${W.id} set in EnvContext`),{success:!0,output:`Task updated: #${W.id} - ${W.title}`,metadata:{execution_time_ms:0,task:W}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function h8($){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:P3,execute:async(J,Q)=>{let X=P3.parse(J);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}}}}}}B$();n();var lF=i("task:tools:complete"),cF=`
2825
+ Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:kJ,execute:async(J,Q)=>{let q=kJ.parse(J).task_ids;if(!q||q.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let Y=[],G=0;for(let z of q)try{if(await $.deleteTask(z))G++,Y.push({id:z,success:!0});else Y.push({id:z,success:!1,error:"Task not found"})}catch(H){Y.push({id:z,success:!1,error:H instanceof Error?H.message:String(H)})}return{success:!Y.some((z)=>!z.success),output:JSON.stringify({deleted_count:G,total:q.length,errors:Y.filter((z)=>!z.success).map((z)=>({id:z.id,error:z.error})),results:Y},null,2),metadata:{execution_time_ms:0}}}}}M$();i();var XM=d("tool:update-task");async function qM($,J,Q){let X=new Set,q=Q;while(q!==null&&q!==void 0){if(q===J)return!0;if(X.has(q))break;X.add(q);let Y=await $.getTask(q);if(!Y)break;q=Y.parent_task_id}return!1}function G6($){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:TJ,execute:async(J,Q)=>{let X=TJ.parse(J),q=Q.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await qM($,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 Y=Q.metadata?.agentType??void 0,G=Q.metadata?.agentName??void 0;if(X.status==="completed"&&Y==="sub"){let z=$.env?.getComponent?.("agent"),B=(G&&z?.getAgent?z.getAgent(G):void 0)?.config;if(!(B?Array.isArray(B.allowedTools)&&B.allowedTools.includes("task_complete")||!Array.isArray(B.allowedTools)&&!(Array.isArray(B.deniedTools)&&B.deniedTools.includes("task_complete")):!1))return{success:!1,output:"",error:'Cannot set status="completed" without acceptance permission (Task #5007 \u2014 \u9A8C\u6536\u6743\u5206\u79BB). '+'\u6267\u884C\u65B9\u53EA\u80FD\u63A8\u8FDB\u8FDB\u5EA6\uFF1A\u7528 task_update(progress=100) \u8868\u793A"\u6211\u8FD9\u8FB9\u5E72\u5B8C\u4E86"\uFF0C'+"\u518D task_operation_create \u8BB0\u5F55\u7ED3\u8BBA\uFF0C\u7136\u540E\u7ED3\u675F\u8FD4\u56DE\uFF1B"+"\u4EFB\u52A1\u7EC8\u6001\u5FC5\u987B\u7531\u9A8C\u6536\u65B9\uFF08default agent / \u4E3B\u667A\u80FD\u4F53\uFF09\u8C03\u7528 task_complete \u843D\u5B9A\u3002",metadata:{execution_time_ms:0}}}let W=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,owner:X.owner});if(!W)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:q,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 $6(W.id),XM.info(`[updateTask] Trace: Task #${W.id} updated, currentTaskId=${W.id} set in EnvContext`),{success:!0,output:`Task updated: #${W.id} - ${W.title}`,metadata:{execution_time_ms:0,task:W}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function c8($){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:vJ,execute:async(J,Q)=>{let X=vJ.parse(J);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(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}M$();i();var YM=d("task:tools:complete"),GM=`
2822
2826
  Final acceptance of a submitted task: set status=completed, progress=100
2823
2827
  (two-phase acceptance, Task #5073).
2824
2828
 
@@ -2829,7 +2833,7 @@ executor (sub-agent) has NO permission to call it (deniedTools, Task #5007).
2829
2833
 
2830
2834
  1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
2831
2835
  - Use \`task_get(task_id=<id>)\` to fetch the full task record.
2832
- 2. **Validate whether each goal sub-item was achieved** (${n$}).
2836
+ 2. **Validate whether each goal sub-item was achieved** (${t$}).
2833
2837
  - Goals should be numbered sub-items (\u7F16\u53F7\u5B50\u9879, see task_create rules). Check
2834
2838
  each sub-item against the operation-record chain (\u64CD\u4F5C\u8BB0\u5F55\u94FE) and the
2835
2839
  deliverable evidence (context.deliverable_storage_path).
@@ -2837,9 +2841,9 @@ executor (sub-agent) has NO permission to call it (deniedTools, Task #5007).
2837
2841
  deliverables; numbered sub-items give it finer-grained evidence to
2838
2842
  reason with (\u9010\u6761\u5BF9\u7167\u7684\u8BC1\u636E\u7C92\u5EA6). If it detects that the goal or
2839
2843
  deliverables appear unmet, the task context will carry a
2840
- \`[${$$}]\`.
2841
- - **If you receive a [${$$}]**, you MUST verify it
2842
- (${r$}): re-read the task via \`task_get\`, then do exactly one of:
2844
+ \`[${q$}]\`.
2845
+ - **If you receive a [${q$}]**, you MUST verify it
2846
+ (${e$}): re-read the task via \`task_get\`, then do exactly one of:
2843
2847
  (a) \u786E\u8BA4\u672A\u5B8C\u6210 \u2192 \`task_update(task_id=<id>, status=todo)\` reopen and continue; or
2844
2848
  (b) \u786E\u8BA4\u5DF2\u5B8C\u6210 \u2192 \`task_operation_create\` (milestone_type=decision,
2845
2849
  milestone_title=<\u4E00\u884C\u7ED3\u8BBA>) state why the sub-items are actually
@@ -2872,7 +2876,7 @@ executor (sub-agent) has NO permission to call it (deniedTools, Task #5007).
2872
2876
  state commit by the acceptance side.
2873
2877
  - Cannot complete a task that is already in a terminal state (cancelled /
2874
2878
  archived) \u2014 reopen it first via \`task_update(status="active")\`.
2875
- `.trim();function J6($){return{name:"task_complete",description:cF,parameters:b3,execute:async(J,Q)=>{let X=b3.parse(J),Y=Q.session_id||"unknown";try{let G=await $.getTask(X.task_id);if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(G.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}};if(new Set([...Z6]).has(G.status))return{success:!1,output:"",error:`Cannot complete task #${X.task_id}: it is already in terminal status "${G.status}". Reopen it first via task_update(status="active") if acceptance should proceed.`,metadata:{execution_time_ms:0}};let W=await $.completeTask(X.task_id,Y);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return r2(void 0),lF.info(`[completeTask] Trace: Task #${X.task_id} completed (acceptance committed), currentTaskId cleared from EnvContext`),{success:!0,output:`Task completed: #${W.id} - ${W.title}`,metadata:{execution_time_ms:0,task:W}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}n();var pF=i("tool:cancel-task"),dF=new Set(["completed","cancelled","archived"]),iF=`
2879
+ `.trim();function W6($){return{name:"task_complete",description:GM,parameters:xJ,execute:async(J,Q)=>{let X=xJ.parse(J),q=Q.session_id||"unknown";try{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}};if(Y.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}};if(new Set([...E6]).has(Y.status))return{success:!1,output:"",error:`Cannot complete task #${X.task_id}: it is already in terminal status "${Y.status}". Reopen it first via task_update(status="active") if acceptance should proceed.`,metadata:{execution_time_ms:0}};let W=await $.completeTask(X.task_id,q);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return $6(void 0),YM.info(`[completeTask] Trace: Task #${X.task_id} completed (acceptance committed), currentTaskId cleared from EnvContext`),{success:!0,output:`Task completed: #${W.id} - ${W.title}`,metadata:{execution_time_ms:0,task:W}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}i();var WM=d("tool:cancel-task"),zM=new Set(["completed","cancelled","archived"]),HM=`
2876
2880
  Cancel a task (task.status = "cancelled"). This is the **acceptance-side** cancel.
2877
2881
 
2878
2882
  **When to use** \u2014 ONLY when the user explicitly asks (\u7528\u6237\u660E\u4EE4):
@@ -2902,7 +2906,7 @@ Cancel a task (task.status = "cancelled"). This is the **acceptance-side** cance
2902
2906
  **Parameters**:
2903
2907
  - \`task_id\` (required): the task to cancel
2904
2908
  - \`reason\` (optional): why it is being cancelled \u2014 recorded in the operation trail
2905
- `.trim();function y8($){return{name:"task_cancel",description:iF,parameters:S3,execute:async(J,Q)=>{let X=S3.parse(J),Y=Q.session_id||"unknown";try{let G=await $.getTask(X.task_id);if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(dF.has(G.status))return{success:!1,output:"",error:`Cannot cancel task #${X.task_id}: it is already in terminal status "${G.status}".`,metadata:{execution_time_ms:0,task_id:X.task_id}};let q=await $.updateTask(X.task_id,{status:"cancelled",current_status:X.reason?`${R$}\uFF1A${X.reason}`:R$});if(!q)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return await $.createOperation({taskId:X.task_id,sessionId:Y,milestoneType:"decision",milestoneTitle:`Task cancelled: #${X.task_id}`,milestoneDescription:X.reason?`Cancelled by acceptance side. Reason: ${X.reason}`:"Cancelled by acceptance side (no reason given)."}),pF.info(`[cancelTask] Task #${X.task_id} cancelled (previous status: ${G.status})`),{success:!0,output:`Task cancelled: #${X.task_id} - ${q.title}`,metadata:{execution_time_ms:0,task:q}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}n();var mL=i("task:tools:pre-complete"),nF=`
2909
+ `.trim();function d8($){return{name:"task_cancel",description:HM,parameters:hJ,execute:async(J,Q)=>{let X=hJ.parse(J),q=Q.session_id||"unknown";try{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}};if(zM.has(Y.status))return{success:!1,output:"",error:`Cannot cancel task #${X.task_id}: it is already in terminal status "${Y.status}".`,metadata:{execution_time_ms:0,task_id:X.task_id}};let G=await $.updateTask(X.task_id,{status:"cancelled",current_status:X.reason?`${Z$}\uFF1A${X.reason}`:Z$});if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return await $.createOperation({taskId:X.task_id,sessionId:q,milestoneType:"decision",milestoneTitle:`Task cancelled: #${X.task_id}`,milestoneDescription:X.reason?`Cancelled by acceptance side. Reason: ${X.reason}`:"Cancelled by acceptance side (no reason given)."}),WM.info(`[cancelTask] Task #${X.task_id} cancelled (previous status: ${Y.status})`),{success:!0,output:`Task cancelled: #${X.task_id} - ${G.title}`,metadata:{execution_time_ms:0,task:G}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}i();var UN=d("task:tools:pre-complete"),BM=`
2906
2910
  Submit a task for acceptance (two-phase acceptance, Task #5073).
2907
2911
 
2908
2912
  **Who should call this** \u2014 the **executor** (sub-agent) when it believes
@@ -2944,22 +2948,22 @@ the work is done and deliverables are ready.
2944
2948
 
2945
2949
  **Restrictions**:
2946
2950
  - Cannot pre-complete cycle-type tasks (they are periodic).
2947
- `.trim();function Q6($){return{name:"task_pre_complete",description:nF,parameters:E3,execute:async(J,Q)=>{let X=E3.parse(J),Y=Q.session_id||"unknown";try{let G=await $.preCompleteTask(X.task_id,Y,X.deliverable_storage_path,X.current_status);if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:X.deliverable_storage_path?`Task submitted for acceptance (to_validate): #${G.id} - ${G.title}
2948
- Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task submitted for acceptance (to_validate): #${G.id} - ${G.title}
2949
- Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:G}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function v3($,J){if($.updatedAt<J.updatedAt)return 1;if($.updatedAt>J.updatedAt)return-1;if($.id<J.id)return 1;if($.id>J.id)return-1;return 0}function x3($,J){if(J<0)return $;if(J===0)return $.map((Q)=>({...Q,children:[]}));return $.map((Q)=>({...Q,children:x3(Q.children,J-1)}))}function h3($){let J=0;for(let Q of $)J+=1+h3(Q.children);return J}function rF($){let J=new Map,Q=new Map,X=[];for(let Y of $)J.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 G=Y.parent_task_id;if(G!==void 0&&G!==null&&J.has(G)){let q=Q.get(G)||[];q.push(Y),Q.set(G,q)}else X.push(Y)}for(let[Y,G]of Q.entries()){let q=J.get(Y);G.sort(v3),q.children=G.map((W)=>J.get(W.id))}return X.sort(v3),X.map((Y)=>J.get(Y.id))}function X6($){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:
2951
+ `.trim();function z6($){return{name:"task_pre_complete",description:BM,parameters:yJ,execute:async(J,Q)=>{let X=yJ.parse(J),q=Q.session_id||"unknown";try{let Y=await $.preCompleteTask(X.task_id,q,X.deliverable_storage_path,X.current_status);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:X.deliverable_storage_path?`Task submitted for acceptance (to_validate): #${Y.id} - ${Y.title}
2952
+ Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task submitted for acceptance (to_validate): #${Y.id} - ${Y.title}
2953
+ Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:Y}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function lJ($,J){if($.updatedAt<J.updatedAt)return 1;if($.updatedAt>J.updatedAt)return-1;if($.id<J.id)return 1;if($.id>J.id)return-1;return 0}function cJ($,J){if(J<0)return $;if(J===0)return $.map((Q)=>({...Q,children:[]}));return $.map((Q)=>({...Q,children:cJ(Q.children,J-1)}))}function dJ($){let J=0;for(let Q of $)J+=1+dJ(Q.children);return J}function UM($){let J=new Map,Q=new Map,X=[];for(let q of $)J.set(q.id,{id:q.id,title:q.title,status:q.status,type:q.type,priority:q.priority,progress:q.progress,children:[]});for(let q of $){let Y=q.parent_task_id;if(Y!==void 0&&Y!==null&&J.has(Y)){let G=Q.get(Y)||[];G.push(q),Q.set(Y,G)}else X.push(q)}for(let[q,Y]of Q.entries()){let G=J.get(q);Y.sort(lJ),G.children=Y.map((W)=>J.get(W.id))}return X.sort(lJ),X.map((q)=>J.get(q.id))}function H6($){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:
2950
2954
  - total: count of ALL tasks in the returned tree (incl. descendants)
2951
2955
  - truncated: always false for now (no pagination cap on tree)
2952
2956
  - depth: the resolved depth value
2953
2957
  - parent_task_id: the root's id, or null for forest mode
2954
2958
  - nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
2955
- Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:I3,execute:async(J,Q)=>{let X=I3.parse(J);try{let Y=[],G=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let z=await $.getTask(X.parent_task_id);if(!z)Y=[];else{let H=await $.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[z,...H]}}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((z)=>z.status===X.status);if(X.priority)Y=Y.filter((z)=>z.priority===X.priority);if(X.type)Y=Y.filter((z)=>z.type===X.type);if(!X.include_archived)Y=Y.filter((z)=>z.status!=="archived")}let q=rF(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)q=x3(q,X.depth);let W=h3(q);return{success:!0,output:JSON.stringify({total:W,truncated:!1,depth:X.depth,parent_task_id:G,nodes:q}),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 _9=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),g8=100,k8=500,A9=5000,aF=1,Z9=200,l3=K.string().min(g8,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${g8} \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(k8,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${k8} \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 ${g8}-${k8} \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"),c3=K.string().min(aF,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(Z9,{message:`milestone_title \u8D85\u8FC7 ${Z9} \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"),p3=K.string().max(A9,{message:`milestone_description \u8D85\u8FC7 ${A9} \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"),sF=K.object({task_id:K.number().describe("Task ID"),milestone_type:_9.optional(),milestone_title:c3.optional(),milestone_description:p3,process_description:l3.optional(),action_type:_9.optional(),action_title:K.string().min(1).max(Z9).optional(),action_description:K.string().max(A9).optional(),md_path:K.string().optional().describe("Path to detailed markdown documentation")}),y3=sF.transform(($)=>{let J=[],Q=$.milestone_type,X=$.milestone_title,Y=$.milestone_description;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");if(!X&&$.action_title)X=$.action_title,J.push("action_title");if(Y===void 0&&$.action_description!==void 0)Y=$.action_description,J.push("action_description");return{task_id:$.task_id,milestone_type:Q,milestone_title:X,milestone_description:Y,process_description:$.process_description,md_path:$.md_path,_deprecated_fields_used:J}}),g3=K.object({operation_id:K.number().describe("Operation ID")}),k3=K.object({task_id:K.number().describe("Task ID"),milestone_type:_9.optional(),action_type:_9.optional(),limit:K.number().optional().default(20),offset:K.number().optional().default(0)}).transform(($)=>{let J=[],Q=$.milestone_type;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");return{task_id:$.task_id,milestone_type:Q,limit:$.limit,offset:$.offset,_deprecated_fields_used:J}}),oF=K.object({operation_id:K.number().describe("Operation ID"),milestone_title:c3.optional(),milestone_description:p3,process_description:l3.optional(),action_title:K.string().min(1).max(Z9).optional(),action_description:K.string().max(A9).optional()}),m3=oF.transform(($)=>{let J=[],Q=$.milestone_title,X=$.milestone_description;if(!Q&&$.action_title)Q=$.action_title,J.push("action_title");if(X===void 0&&$.action_description!==void 0)X=$.action_description,J.push("action_description");return{operation_id:$.operation_id,milestone_title:Q,milestone_description:X,process_description:$.process_description,_deprecated_fields_used:J}}),u3=K.object({operation_id:K.number().describe("Operation ID")});function tF($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function eF($){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 Y6($){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-500 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:y3,execute:async(J,Q)=>{let X;try{X=y3.parse(J)}catch(q){if(q instanceof q0)return{success:!1,output:"",error:tF(q),metadata:{execution_time_ms:0}};throw q}let Y=eF(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let G=Q.session_id||"unknown";try{let q=await $.createOperation({taskId:X.task_id,sessionId:G,milestoneType:Y.milestoneType,milestoneTitle:Y.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),W=`Operation created: #${q.id} for task #${q.taskId} [milestone=${q.milestoneType}] ${q.milestoneTitle}`,z=[];if(X._deprecated_fields_used.length>0)z.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(z.length>0)W+=`
2959
+ Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:mJ,execute:async(J,Q)=>{let X=mJ.parse(J);try{let q=[],Y=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let z=await $.getTask(X.parent_task_id);if(!z)q=[];else{let H=await $.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));q=[z,...H]}}else q=(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)q=q.filter((z)=>z.status===X.status);if(X.priority)q=q.filter((z)=>z.priority===X.priority);if(X.type)q=q.filter((z)=>z.type===X.type);if(!X.include_archived)q=q.filter((z)=>z.status!=="archived")}let G=UM(q);if(X.parent_task_id===void 0||X.parent_task_id===null)G=cJ(G,X.depth);let W=dJ(G);return{success:!0,output:JSON.stringify({total:W,truncated:!1,depth:X.depth,parent_task_id:Y,nodes:G}),metadata:{execution_time_ms:0}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}var P9=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),p8=100,i8=500,b9=5000,VM=1,E9=200,sJ=K.string().min(p8,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${p8} \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(i8,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${i8} \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 ${p8}-${i8} \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"),oJ=K.string().min(VM,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(E9,{message:`milestone_title \u8D85\u8FC7 ${E9} \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"),tJ=K.string().max(b9,{message:`milestone_description \u8D85\u8FC7 ${b9} \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"),DM=K.object({task_id:K.number().describe("Task ID"),milestone_type:P9.optional(),milestone_title:oJ.optional(),milestone_description:tJ,process_description:sJ.optional(),action_type:P9.optional(),action_title:K.string().min(1).max(E9).optional(),action_description:K.string().max(b9).optional(),md_path:K.string().optional().describe("Path to detailed markdown documentation")}),pJ=DM.transform(($)=>{let J=[],Q=$.milestone_type,X=$.milestone_title,q=$.milestone_description;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");if(!X&&$.action_title)X=$.action_title,J.push("action_title");if(q===void 0&&$.action_description!==void 0)q=$.action_description,J.push("action_description");return{task_id:$.task_id,milestone_type:Q,milestone_title:X,milestone_description:q,process_description:$.process_description,md_path:$.md_path,_deprecated_fields_used:J}}),iJ=K.object({operation_id:K.number().describe("Operation ID")}),nJ=K.object({task_id:K.number().describe("Task ID"),milestone_type:P9.optional(),action_type:P9.optional(),limit:K.number().optional().default(20),offset:K.number().optional().default(0)}).transform(($)=>{let J=[],Q=$.milestone_type;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");return{task_id:$.task_id,milestone_type:Q,limit:$.limit,offset:$.offset,_deprecated_fields_used:J}}),FM=K.object({operation_id:K.number().describe("Operation ID"),milestone_title:oJ.optional(),milestone_description:tJ,process_description:sJ.optional(),action_title:K.string().min(1).max(E9).optional(),action_description:K.string().max(b9).optional()}),rJ=FM.transform(($)=>{let J=[],Q=$.milestone_title,X=$.milestone_description;if(!Q&&$.action_title)Q=$.action_title,J.push("action_title");if(X===void 0&&$.action_description!==void 0)X=$.action_description,J.push("action_description");return{operation_id:$.operation_id,milestone_title:Q,milestone_description:X,process_description:$.process_description,_deprecated_fields_used:J}}),aJ=K.object({operation_id:K.number().describe("Operation ID")});function MM($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function OM($){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 B6($){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-500 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:pJ,execute:async(J,Q)=>{let X;try{X=pJ.parse(J)}catch(G){if(G instanceof W0)return{success:!1,output:"",error:MM(G),metadata:{execution_time_ms:0}};throw G}let q=OM(X);if(!q.ok)return{success:!1,output:"",error:q.error,metadata:{execution_time_ms:0}};let Y=Q.session_id||"unknown";try{let G=await $.createOperation({taskId:X.task_id,sessionId:Y,milestoneType:q.milestoneType,milestoneTitle:q.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),W=`Operation created: #${G.id} for task #${G.taskId} [milestone=${G.milestoneType}] ${G.milestoneTitle}`,z=[];if(X._deprecated_fields_used.length>0)z.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(z.length>0)W+=`
2956
2960
 
2957
2961
  `+z.join(`
2958
- `);return{success:!0,output:W,metadata:{execution_time_ms:0,operation_id:q.id,task_id:q.taskId,session_id:q.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function m8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:g3,execute:async(J,Q)=>{let X=g3.parse(J);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 G6($){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:k3,execute:async(J,Q)=>{let X=k3.parse(J);try{let Y=await $.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),G=JSON.stringify({operations:Y,count:Y.length});if(X._deprecated_fields_used.length>0)G=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
2962
+ `);return{success:!0,output:W,metadata:{execution_time_ms:0,operation_id:G.id,task_id:G.taskId,session_id:G.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function n8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:iJ,execute:async(J,Q)=>{let X=iJ.parse(J);try{let q=await $.getOperation(X.operation_id);if(!q)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(q,null,2),metadata:{execution_time_ms:0}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function U6($){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:nJ,execute:async(J,Q)=>{let X=nJ.parse(J);try{let q=await $.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),Y=JSON.stringify({operations:q,count:q.length});if(X._deprecated_fields_used.length>0)Y=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
2959
2963
 
2960
- `+G;return{success:!0,output:G,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 $M($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function u8($){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-500 chars).",parameters:m3,execute:async(J,Q)=>{let X;try{X=m3.parse(J)}catch(Y){if(Y instanceof q0)return{success:!1,output:"",error:$M(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 G=`Operation updated: #${Y.id}`;if(X._deprecated_fields_used.length>0)G+=`
2964
+ `+Y;return{success:!0,output:Y,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function KM($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function r8($){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-500 chars).",parameters:rJ,execute:async(J,Q)=>{let X;try{X=rJ.parse(J)}catch(q){if(q instanceof W0)return{success:!1,output:"",error:KM(q),metadata:{execution_time_ms:0}};throw q}try{let q=await $.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!q)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let Y=`Operation updated: #${q.id}`;if(X._deprecated_fields_used.length>0)Y+=`
2961
2965
 
2962
- \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:G,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 l8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:u3,execute:async(J,Q)=>{let X=u3.parse(J);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 t3}from"path";function o($){d3.warn($)}var d3,q6=a(()=>{n(),d3=i("task:migration")}),i3={};r0(i3,{runMigration:()=>JM});function JM($){o(`[Migration 001] Starting migration for: ${$}`);let J=H2($);try{try{J.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch(Q){if(Q.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw Q}try{J.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch(Q){if(Q.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw Q}o("[Migration 001] Migration completed successfully")}finally{J.close()}}var QM=a(()=>{U$(),q6()}),n3={};r0(n3,{runMigration:()=>XM});function XM($){o(`[Migration 002] Starting migration for: ${$}`);let J=H2($);try{try{J.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch(Q){if(Q.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw Q}o("[Migration 002] Migration completed successfully")}finally{J.close()}}var YM=a(()=>{U$(),q6()}),r3={};r0(r3,{runMigration:()=>GM});function GM($){o(`[Migration 003] Starting migration for: ${$}`);let J=H2($);try{try{J.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch(Q){if(Q.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw Q}o("[Migration 003] Migration completed successfully")}finally{J.close()}}var qM=a(()=>{U$(),q6()}),a3={};r0(a3,{runMigration:()=>WM});function WM($){o(`[Migration 004] Starting migration for: ${$}`);let J=H2($);try{let Q=new Set,X=J.query("PRAGMA table_info(task_operation)").all();for(let Y of X)Q.add(Y.name);for(let{oldName:Y,newName:G}of s3){let q=Q.has(Y),W=Q.has(G);if(q&&!W)J.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${G}`),o(`[Migration 004] Renamed ${Y} -> ${G}`);else if(W)o(`[Migration 004] ${G} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${G}`)}o("[Migration 004] Migration completed successfully")}finally{J.close()}}var s3,zM=a(()=>{U$(),q6(),s3=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),o3={};r0(o3,{runMigration:()=>HM});function HM($){o(`[Migration 005] Starting migration for: ${$}`);let J=H2($),Q={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(J.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"),Q;let Y=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if(Q.blobCountBefore=Y[0]?.cnt??0,Q.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),Q;J.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),Q.ran=!0;let G=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();Q.blobCountAfter=G[0]?.cnt??0,o(`[Migration 005] Converted ${Q.blobCountBefore-Q.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{J.close()}return Q}var BM=a(()=>{U$(),q6()});function UM(){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 H2($){let J=UM();return VM(new J($))}function VM($){if(typeof $.run!=="function")$.run=function(J,...Q){if(Q.length>0)return this.prepare(J).run(...Q);else return this.exec(J)};return $.query=function(J,...Q){if(Q.length===0){let Y=this.prepare(J);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(J);return{all:(...Y)=>X.all(...Q,...Y),get:(...Y)=>X.get(...Q,...Y),run:(...Y)=>X.run(...Q,...Y)}},$}function DM(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";return t3($,".local","share")}function w9(){return t3(DM(),"roy-agent","tasks.db")}var E$,S$,U$=a(()=>{n(),V0(),E$=i("task:store"),S$=class ${db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(J){this.dbPath=J||w9()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let J=e("fs"),X=e("path").dirname(this.dbPath);if(!J.existsSync(X))J.mkdirSync(X,{recursive:!0})}if(this.db=H2(this.dbPath),this.db.run(`
2966
+ \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:Y,metadata:{execution_time_ms:0,operation:q,deprecated_fields_used:X._deprecated_fields_used}}}catch(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}function a8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:aJ,execute:async(J,Q)=>{let X=aJ.parse(J);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(q){return{success:!1,output:"",error:q instanceof Error?q.message:String(q),metadata:{execution_time_ms:0}}}}}}import{join as W1}from"path";function a($){eJ.warn($)}var eJ,F2=s(()=>{i(),eJ=d("task:migration")}),$1={};d0($1,{runMigration:()=>jM});function jM($){a(`[Migration 001] Starting migration for: ${$}`);let J=x$($);try{try{J.run("ALTER TABLE task ADD COLUMN project_path TEXT"),a("[Migration 001] Added project_path column")}catch(Q){if(Q.message?.includes("duplicate column name"))a("[Migration 001] project_path column already exists, skipping");else throw Q}try{J.run("ALTER TABLE task ADD COLUMN context TEXT"),a("[Migration 001] Added context column")}catch(Q){if(Q.message?.includes("duplicate column name"))a("[Migration 001] context column already exists, skipping");else throw Q}a("[Migration 001] Migration completed successfully")}finally{J.close()}}var LM=s(()=>{v0(),F2()}),J1={};d0(J1,{runMigration:()=>NM});function NM($){a(`[Migration 002] Starting migration for: ${$}`);let J=x$($);try{try{J.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),a("[Migration 002] Added type column")}catch(Q){if(Q.message?.includes("duplicate column name"))a("[Migration 002] type column already exists, skipping");else throw Q}a("[Migration 002] Migration completed successfully")}finally{J.close()}}var AM=s(()=>{v0(),F2()}),Q1={};d0(Q1,{runMigration:()=>_M});function _M($){a(`[Migration 003] Starting migration for: ${$}`);let J=x$($);try{try{J.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),a("[Migration 003] Added process_description column")}catch(Q){if(Q.message?.includes("duplicate column name"))a("[Migration 003] process_description column already exists, skipping");else throw Q}a("[Migration 003] Migration completed successfully")}finally{J.close()}}var RM=s(()=>{v0(),F2()}),X1={};d0(X1,{runMigration:()=>ZM});function ZM($){a(`[Migration 004] Starting migration for: ${$}`);let J=x$($);try{let Q=new Set,X=J.query("PRAGMA table_info(task_operation)").all();for(let q of X)Q.add(q.name);for(let{oldName:q,newName:Y}of q1){let G=Q.has(q),W=Q.has(Y);if(G&&!W)J.run(`ALTER TABLE task_operation RENAME COLUMN ${q} TO ${Y}`),a(`[Migration 004] Renamed ${q} -> ${Y}`);else if(W)a(`[Migration 004] ${Y} already exists, skipping rename of ${q}`);else a(`[Migration 004] ${q} not present, skipping rename to ${Y}`)}a("[Migration 004] Migration completed successfully")}finally{J.close()}}var q1,wM=s(()=>{v0(),F2(),q1=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),Y1={};d0(Y1,{runMigration:()=>PM});function PM($){a(`[Migration 005] Starting migration for: ${$}`);let J=x$($),Q={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(J.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return a("[Migration 005] task table does not exist, skipping"),Q;let q=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if(Q.blobCountBefore=q[0]?.cnt??0,Q.blobCountBefore===0)return a("[Migration 005] No BLOB descriptions found, no action needed"),Q;J.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),Q.ran=!0;let Y=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();Q.blobCountAfter=Y[0]?.cnt??0,a(`[Migration 005] Converted ${Q.blobCountBefore-Q.blobCountAfter} BLOB description(s) to TEXT`),a("[Migration 005] Migration completed successfully")}finally{J.close()}return Q}var bM=s(()=>{v0(),F2()}),G1={};d0(G1,{runMigration:()=>EM});function EM($){a(`[Migration 006] Starting migration for: ${$}`);let J=x$($);try{try{J.run("ALTER TABLE task ADD COLUMN owner TEXT"),a("[Migration 006] Added owner column")}catch(Q){if(Q.message?.includes("duplicate column name"))a("[Migration 006] owner column already exists, skipping");else throw Q}J.run("CREATE INDEX IF NOT EXISTS idx_task_owner ON task(owner)"),a("[Migration 006] Migration completed successfully")}finally{J.close()}}var SM=s(()=>{v0(),F2()});function CM(){if(typeof Bun<"u"){let{Database:$}=$0("bun:sqlite");return $}try{let{DatabaseSync:$}=$0("node:sqlite");if(typeof $==="function")return $}catch{}return $0("better-sqlite3")}function x$($){let J=CM();return fM(new J($))}function fM($){if(typeof $.run!=="function")$.run=function(J,...Q){if(Q.length>0)return this.prepare(J).run(...Q);else return this.exec(J)};return $.query=function(J,...Q){if(Q.length===0){let q=this.prepare(J);return{all:()=>q.all(),get:()=>q.get(),run:()=>q.run()}}let X=this.prepare(J);return{all:(...q)=>X.all(...Q,...q),get:(...q)=>X.get(...Q,...q),run:(...q)=>X.run(...Q,...q)}},$}function IM(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";return W1($,".local","share")}function S9(){return W1(IM(),"roy-agent","tasks.db")}var t0,O$,v0=s(()=>{i(),D0(),t0=d("task:store"),O$=class ${db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(J){this.dbPath=J||S9()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let J=$0("fs"),X=$0("path").dirname(this.dbPath);if(!J.existsSync(X))J.mkdirSync(X,{recursive:!0})}if(this.db=x$(this.dbPath),this.db.run(`
2963
2967
  CREATE TABLE IF NOT EXISTS task (
2964
2968
  id INTEGER PRIMARY KEY AUTOINCREMENT,
2965
2969
  title TEXT NOT NULL,
@@ -2976,7 +2980,8 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
2976
2980
  due_date TEXT,
2977
2981
  tags TEXT,
2978
2982
  project_path TEXT NOT NULL DEFAULT 'unknown',
2979
- context TEXT NOT NULL DEFAULT '{}'
2983
+ context TEXT NOT NULL DEFAULT '{}',
2984
+ owner TEXT
2980
2985
  )
2981
2986
  `),this.db.run(`
2982
2987
  CREATE TABLE IF NOT EXISTS task_operation (
@@ -3007,69 +3012,69 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
3007
3012
  FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
3008
3013
  FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
3009
3014
  )
3010
- `),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:J}=(QM(),f$(i3));J(this.dbPath)}catch(J){E$.warn(`[Migration 001] Failed to run: ${J.message}`)}try{let{runMigration:J}=(YM(),f$(n3));J(this.dbPath)}catch(J){E$.warn(`[Migration 002] Failed to run: ${J.message}`)}try{let{runMigration:J}=(qM(),f$(r3));J(this.dbPath)}catch(J){E$.warn(`[Migration 003] Failed to run: ${J.message}`)}try{let{runMigration:J}=(zM(),f$(a3));J(this.dbPath)}catch(J){E$.warn(`[Migration 004] Failed to run: ${J.message}`)}try{let{runMigration:J}=(BM(),f$(o3));J(this.dbPath)}catch(J){E$.warn(`[Migration 005] Failed to run: ${J.message}`)}}this.initialized=!0,E$.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(J){await this.initialize();let Q=Date.now(),Y=this.db.prepare(`
3015
+ `),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:J}=(LM(),j$($1));J(this.dbPath)}catch(J){t0.warn(`[Migration 001] Failed to run: ${J.message}`)}try{let{runMigration:J}=(AM(),j$(J1));J(this.dbPath)}catch(J){t0.warn(`[Migration 002] Failed to run: ${J.message}`)}try{let{runMigration:J}=(RM(),j$(Q1));J(this.dbPath)}catch(J){t0.warn(`[Migration 003] Failed to run: ${J.message}`)}try{let{runMigration:J}=(wM(),j$(X1));J(this.dbPath)}catch(J){t0.warn(`[Migration 004] Failed to run: ${J.message}`)}try{let{runMigration:J}=(bM(),j$(Y1));J(this.dbPath)}catch(J){t0.warn(`[Migration 005] Failed to run: ${J.message}`)}try{let{runMigration:J}=(SM(),j$(G1));J(this.dbPath)}catch(J){t0.warn(`[Migration 006] Failed to run: ${J.message}`)}}try{this.db.run("CREATE INDEX IF NOT EXISTS idx_task_owner ON task(owner)")}catch(J){t0.warn(`[TaskStore] idx_task_owner creation failed: ${J.message}`)}this.initialized=!0,t0.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(J){await this.initialize();let Q=Date.now(),q=this.db.prepare(`
3011
3016
  INSERT INTO task (title, description, priority, type, parent_task_id,
3012
3017
  goals_and_expected_deliverables, due_date, tags, status,
3013
- current_status, created_at, updated_at, project_path, context)
3014
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
3015
- `).run(J.title,J.description||"",J.priority||"medium",J.type||"normal",J.parent_task_id||null,J.goals_and_expected_deliverables||"",J.due_date||null,J.tags?JSON.stringify(J.tags):null,Q,Q,J.project_path,J.context),G=await this.getTask(Y.lastInsertRowid);if(G)return this.tasksCache.set(G.id,G),G;throw Error("Failed to create task")}async getTask(J){if(await this.initialize(),this.tasksCache.has(J))return this.tasksCache.get(J);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(J);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(J,Y),Y}async updateTask(J,Q){await this.initialize();let X=await this.getTask(J);if(!X)return;let Y=[],G=[];if(Q.title!==void 0)Y.push("title = ?"),G.push(Q.title);if(Q.description!==void 0)Y.push("description = ?"),G.push(Q.description);if(Q.status!==void 0)Y.push("status = ?"),G.push(Q.status);if(Q.priority!==void 0)Y.push("priority = ?"),G.push(Q.priority);if(Q.type!==void 0)Y.push("type = ?"),G.push(Q.type);if(Q.progress!==void 0)Y.push("progress = ?"),G.push(Q.progress);if(Q.current_status!==void 0)Y.push("current_status = ?"),G.push(Q.current_status);if(Q.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),G.push(Q.goals_and_expected_deliverables);if(Q.due_date!==void 0)Y.push("due_date = ?"),G.push(Q.due_date);if(Q.tags!==void 0)Y.push("tags = ?"),G.push(JSON.stringify(Q.tags));if(Q.project_path!==void 0)Y.push("project_path = ?"),G.push(Q.project_path);if(Q.context!==void 0)Y.push("context = ?"),G.push(Q.context);if(Q.parent_task_id!==void 0)Y.push("parent_task_id = ?"),G.push(Q.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),G.push(Date.now()),G.push(J),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...G),this.tasksCache.delete(J),this.getTask(J)}async deleteTask(J){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(J);if(X.changes>0)this.tasksCache.delete(J),this.operationsCache.delete(J);return X.changes>0}async listTasks(J){if(await this.initialize(),J?.depth!==void 0&&J.depth>=0&&J.parent_task_id===void 0)return this.listTasksByDepth(J);let Q=["1=1"],X=[];if(J?.status)Q.push("status = ?"),X.push(J.status);if(J?.priority)Q.push("priority = ?"),X.push(J.priority);if(J?.type)Q.push("type = ?"),X.push(J.type);if(J?.parent_task_id!==void 0)Q.push("parent_task_id = ?"),X.push(J.parent_task_id);if(!J?.include_archived&&J?.status!=="archived")Q.push("status != 'archived'");let Y=Q.join(" AND "),G=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,W=this.db.prepare(G).get(...X)?.total??0,z=`SELECT * FROM task WHERE ${Y}`,H=[...X];if(z+=" ORDER BY updated_at DESC",J?.limit)z+=" LIMIT ?",H.push(J.limit);if(J?.offset)z+=" OFFSET ?",H.push(J.offset);return{tasks:this.db.prepare(z).all(...H).map((O)=>{let F=this.rowToTask(O);return this.tasksCache.set(F.id,F),F}),total:W}}async listTasksByDepth(J){let Q=J.depth??0,X=["1=1"],Y=[];if(J.status)X.push("status = ?"),Y.push(J.status);if(J.priority)X.push("priority = ?"),Y.push(J.priority);if(J.type)X.push("type = ?"),Y.push(J.type);if(!J?.include_archived&&J?.status!=="archived")X.push("status != 'archived'");let G=X.join(" AND "),q=[];if(Q===0){let U=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${G} ORDER BY updated_at DESC`,V=this.db.prepare(U).all(...Y);for(let O of V){let F=this.rowToTask(O);this.tasksCache.set(F.id,F),q.push(F)}}else{let V=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${G} ORDER BY updated_at DESC`).all(...Y).map((O)=>{let F=this.rowToTask(O);return this.tasksCache.set(F.id,F),F});q.push(...V);for(let O=1;O<=Q;O++){if(V.length===0)break;let F=V.map((N)=>N.id),M=`SELECT * FROM task WHERE parent_task_id IN (${F.map(()=>"?").join(",")}) AND ${G} ORDER BY updated_at DESC`,L=this.db.prepare(M).all(...F,...Y).map((N)=>{let Z=this.rowToTask(N);return this.tasksCache.set(Z.id,Z),Z});q.push(...L),V=L}}let W=q.length,z=J.offset??0,H=J.limit??W;return{tasks:q.slice(z,z+H),total:W}}async getTaskTree(J,Q=-1){await this.initialize();let X=[],Y=[J],G=0;while(Y.length>0){if(Q!==-1&&G>=Q)break;let q=Y.map(()=>"?").join(","),W=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${q}) ORDER BY updated_at DESC`).all(...Y),z=[];for(let H of W){let B=this.rowToTask(H);this.tasksCache.set(B.id,B),X.push(B),z.push(B.id)}Y=z,G++}return X}async getChildTasks(J,Q={}){return this.listTasks({...Q,parent_task_id:J})}async createOperation(J){await this.initialize();let Q=J.milestoneType??J.actionType,X=J.milestoneTitle??J.actionTitle,Y=J.milestoneDescription??J.actionDescription;if(!Q||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let G=Date.now(),W=this.db.prepare(`
3018
+ current_status, created_at, updated_at, project_path, context, owner)
3019
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?, ?)
3020
+ `).run(J.title,J.description||"",J.priority||"medium",J.type||"normal",J.parent_task_id||null,J.goals_and_expected_deliverables||"",J.due_date||null,J.tags?JSON.stringify(J.tags):null,Q,Q,J.project_path,J.context,J.owner||null),Y=await this.getTask(q.lastInsertRowid);if(Y)return this.tasksCache.set(Y.id,Y),Y;throw Error("Failed to create task")}async getTask(J){if(await this.initialize(),this.tasksCache.has(J))return this.tasksCache.get(J);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(J);if(!X)return;let q=this.rowToTask(X);return this.tasksCache.set(J,q),q}async updateTask(J,Q){await this.initialize();let X=await this.getTask(J);if(!X)return;let q=[],Y=[];if(Q.title!==void 0)q.push("title = ?"),Y.push(Q.title);if(Q.description!==void 0)q.push("description = ?"),Y.push(Q.description);if(Q.status!==void 0)q.push("status = ?"),Y.push(Q.status);if(Q.priority!==void 0)q.push("priority = ?"),Y.push(Q.priority);if(Q.type!==void 0)q.push("type = ?"),Y.push(Q.type);if(Q.progress!==void 0)q.push("progress = ?"),Y.push(Q.progress);if(Q.current_status!==void 0)q.push("current_status = ?"),Y.push(Q.current_status);if(Q.goals_and_expected_deliverables!==void 0)q.push("goals_and_expected_deliverables = ?"),Y.push(Q.goals_and_expected_deliverables);if(Q.due_date!==void 0)q.push("due_date = ?"),Y.push(Q.due_date);if(Q.tags!==void 0)q.push("tags = ?"),Y.push(JSON.stringify(Q.tags));if(Q.project_path!==void 0)q.push("project_path = ?"),Y.push(Q.project_path);if(Q.context!==void 0)q.push("context = ?"),Y.push(Q.context);if(Q.parent_task_id!==void 0)q.push("parent_task_id = ?"),Y.push(Q.parent_task_id);if(Q.owner!==void 0)q.push("owner = ?"),Y.push(Q.owner||null);if(q.length===0)return X;return q.push("updated_at = ?"),Y.push(Date.now()),Y.push(J),this.db.prepare(`UPDATE task SET ${q.join(", ")} WHERE id = ?`).run(...Y),this.tasksCache.delete(J),this.getTask(J)}async deleteTask(J){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(J);if(X.changes>0)this.tasksCache.delete(J),this.operationsCache.delete(J);return X.changes>0}async listTasks(J){if(await this.initialize(),J?.depth!==void 0&&J.depth>=0&&J.parent_task_id===void 0)return this.listTasksByDepth(J);let Q=["1=1"],X=[];if(J?.status)Q.push("status = ?"),X.push(J.status);if(J?.priority)Q.push("priority = ?"),X.push(J.priority);if(J?.type)Q.push("type = ?"),X.push(J.type);if(J?.parent_task_id!==void 0)Q.push("parent_task_id = ?"),X.push(J.parent_task_id);if(!J?.include_archived&&J?.status!=="archived")Q.push("status != 'archived'");let q=Q.join(" AND "),Y=`SELECT COUNT(*) as total FROM task WHERE ${q}`,W=this.db.prepare(Y).get(...X)?.total??0,z=`SELECT * FROM task WHERE ${q}`,H=[...X];if(z+=" ORDER BY updated_at DESC",J?.limit)z+=" LIMIT ?",H.push(J.limit);if(J?.offset)z+=" OFFSET ?",H.push(J.offset);return{tasks:this.db.prepare(z).all(...H).map((O)=>{let F=this.rowToTask(O);return this.tasksCache.set(F.id,F),F}),total:W}}async listTasksByDepth(J){let Q=J.depth??0,X=["1=1"],q=[];if(J.status)X.push("status = ?"),q.push(J.status);if(J.priority)X.push("priority = ?"),q.push(J.priority);if(J.type)X.push("type = ?"),q.push(J.type);if(!J?.include_archived&&J?.status!=="archived")X.push("status != 'archived'");let Y=X.join(" AND "),G=[];if(Q===0){let U=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`,V=this.db.prepare(U).all(...q);for(let O of V){let F=this.rowToTask(O);this.tasksCache.set(F.id,F),G.push(F)}}else{let V=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`).all(...q).map((O)=>{let F=this.rowToTask(O);return this.tasksCache.set(F.id,F),F});G.push(...V);for(let O=1;O<=Q;O++){if(V.length===0)break;let F=V.map((A)=>A.id),M=`SELECT * FROM task WHERE parent_task_id IN (${F.map(()=>"?").join(",")}) AND ${Y} ORDER BY updated_at DESC`,L=this.db.prepare(M).all(...F,...q).map((A)=>{let R=this.rowToTask(A);return this.tasksCache.set(R.id,R),R});G.push(...L),V=L}}let W=G.length,z=J.offset??0,H=J.limit??W;return{tasks:G.slice(z,z+H),total:W}}async getTaskTree(J,Q=-1){await this.initialize();let X=[],q=[J],Y=0;while(q.length>0){if(Q!==-1&&Y>=Q)break;let G=q.map(()=>"?").join(","),W=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${G}) ORDER BY updated_at DESC`).all(...q),z=[];for(let H of W){let B=this.rowToTask(H);this.tasksCache.set(B.id,B),X.push(B),z.push(B.id)}q=z,Y++}return X}async getChildTasks(J,Q={}){return this.listTasks({...Q,parent_task_id:J})}async createOperation(J){await this.initialize();let Q=J.milestoneType??J.actionType,X=J.milestoneTitle??J.actionTitle,q=J.milestoneDescription??J.actionDescription;if(!Q||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let Y=Date.now(),W=this.db.prepare(`
3016
3021
  INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
3017
3022
  milestone_description, process_description, timestamp, md_path)
3018
3023
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
3019
- `).run(J.taskId,J.sessionId,Q,X,Y||"",J.processDescription||"",G,J.mdPath||null);this.operationsCache.delete(J.taskId);let z=await this.getOperation(W.lastInsertRowid);if(!z)throw Error("Failed to create operation");return z}async getOperation(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(J);if(!X)return;return this.rowToOperation(X)}async updateOperation(J,Q){await this.initialize();let X=await this.getOperation(J);if(!X)return;let Y=Q.milestoneTitle??Q.actionTitle,G=Q.milestoneDescription??Q.actionDescription,q=[],W=[];if(Y!==void 0)q.push("milestone_title = ?"),W.push(Y);if(G!==void 0)q.push("milestone_description = ?"),W.push(G);if(Q.processDescription!==void 0)q.push("process_description = ?"),W.push(Q.processDescription);if(q.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${q.join(", ")} WHERE id = ?`).run(...W,J),this.operationsCache.delete(X.taskId),this.getOperation(J)}async deleteOperation(J){await this.initialize();let Q=await this.getOperation(J);if(!Q)return!1;let Y=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(J);if(Y.changes>0)this.operationsCache.delete(Q.taskId);return Y.changes>0}async listOperations(J){await this.initialize();let Q=J.taskId;if(!this.operationsCache.has(Q)){let z=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(J.taskId);this.operationsCache.set(Q,z.map((H)=>this.rowToOperation(H)))}let X=this.operationsCache.get(Q),Y=J.milestoneType??J.actionType;if(Y)X=X.filter((W)=>W.milestoneType===Y);let G=J.offset||0,q=J.limit||20;return X.slice(G,G+q)}async listOperationsFresh(J){await this.initialize();let Y=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY id DESC").all(J.taskId).map((z)=>this.rowToOperation(z)),G=J.milestoneType??J.actionType;if(G)Y=Y.filter((z)=>z.milestoneType===G);let q=J.offset||0,W=J.limit||20;return Y.slice(q,q+W)}invalidateOperationsCache(J){this.operationsCache.delete(J)}async getTaskIdBySessionId(J){if(await this.initialize(),!J)return;let Q=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(J);return typeof Q?.task_id==="number"?Q.task_id:void 0}async getTaskIdsBySessionId(J){if(await this.initialize(),!J)return[];return this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE session_id = ? ORDER BY task_id ASC").all(J).map((X)=>X.task_id).filter((X)=>typeof X==="number")}rowToTask(J){return{id:J.id,title:String(J.title??""),description:String(J.description??""),status:String(J.status??"todo"),priority:String(J.priority??"medium"),type:String(J.type??"normal"),progress:J.progress,current_status:String(J.current_status??""),goals_and_expected_deliverables:String(J.goals_and_expected_deliverables??""),parent_task_id:J.parent_task_id||void 0,createdAt:new Date(J.created_at).toISOString(),updatedAt:new Date(J.updated_at).toISOString(),due_date:J.due_date?String(J.due_date):void 0,tags:$.parseTagsSafely(J.tags),project_path:String(J.project_path??"unknown"),context:J.context}}static parseTagsSafely(J){if(J===null||J===void 0||J==="")return;let Q=typeof J==="string"?J:String(J);try{let X=JSON.parse(Q);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[Q]}}rowToOperation(J){let Q=J.milestone_type??J.action_type,X=J.milestone_title??J.action_title,Y=J.milestone_description??J.action_description??"";return{id:J.id,taskId:J.task_id,sessionId:J.session_id,milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:J.process_description??"",timestamp:new Date(J.timestamp).toISOString(),mdPath:J.md_path||void 0,actionType:Q,actionTitle:X,actionDescription:Y}}async createTag(J){await this.initialize();let Q=Date.now(),X=await this.getTagByName(J);if(X)return X;return{id:this.db.prepare(`
3024
+ `).run(J.taskId,J.sessionId,Q,X,q||"",J.processDescription||"",Y,J.mdPath||null);this.operationsCache.delete(J.taskId);let z=await this.getOperation(W.lastInsertRowid);if(!z)throw Error("Failed to create operation");return z}async getOperation(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(J);if(!X)return;return this.rowToOperation(X)}async updateOperation(J,Q){await this.initialize();let X=await this.getOperation(J);if(!X)return;let q=Q.milestoneTitle??Q.actionTitle,Y=Q.milestoneDescription??Q.actionDescription,G=[],W=[];if(q!==void 0)G.push("milestone_title = ?"),W.push(q);if(Y!==void 0)G.push("milestone_description = ?"),W.push(Y);if(Q.processDescription!==void 0)G.push("process_description = ?"),W.push(Q.processDescription);if(G.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${G.join(", ")} WHERE id = ?`).run(...W,J),this.operationsCache.delete(X.taskId),this.getOperation(J)}async deleteOperation(J){await this.initialize();let Q=await this.getOperation(J);if(!Q)return!1;let q=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(J);if(q.changes>0)this.operationsCache.delete(Q.taskId);return q.changes>0}async listOperations(J){await this.initialize();let Q=J.taskId;if(!this.operationsCache.has(Q)){let z=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(J.taskId);this.operationsCache.set(Q,z.map((H)=>this.rowToOperation(H)))}let X=this.operationsCache.get(Q),q=J.milestoneType??J.actionType;if(q)X=X.filter((W)=>W.milestoneType===q);let Y=J.offset||0,G=J.limit||20;return X.slice(Y,Y+G)}async listOperationsFresh(J){await this.initialize();let q=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY id DESC").all(J.taskId).map((z)=>this.rowToOperation(z)),Y=J.milestoneType??J.actionType;if(Y)q=q.filter((z)=>z.milestoneType===Y);let G=J.offset||0,W=J.limit||20;return q.slice(G,G+W)}invalidateOperationsCache(J){this.operationsCache.delete(J)}async getTaskIdBySessionId(J){if(await this.initialize(),!J)return;let Q=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(J);return typeof Q?.task_id==="number"?Q.task_id:void 0}async getTaskIdsBySessionId(J){if(await this.initialize(),!J)return[];return this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE session_id = ? ORDER BY task_id ASC").all(J).map((X)=>X.task_id).filter((X)=>typeof X==="number")}rowToTask(J){return{id:J.id,title:String(J.title??""),description:String(J.description??""),status:String(J.status??"todo"),priority:String(J.priority??"medium"),type:String(J.type??"normal"),progress:J.progress,current_status:String(J.current_status??""),goals_and_expected_deliverables:String(J.goals_and_expected_deliverables??""),parent_task_id:J.parent_task_id||void 0,createdAt:new Date(J.created_at).toISOString(),updatedAt:new Date(J.updated_at).toISOString(),due_date:J.due_date?String(J.due_date):void 0,tags:$.parseTagsSafely(J.tags),project_path:String(J.project_path??"unknown"),context:J.context,owner:J.owner===void 0||J.owner===null?null:String(J.owner)}}static parseTagsSafely(J){if(J===null||J===void 0||J==="")return;let Q=typeof J==="string"?J:String(J);try{let X=JSON.parse(Q);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[Q]}}rowToOperation(J){let Q=J.milestone_type??J.action_type,X=J.milestone_title??J.action_title,q=J.milestone_description??J.action_description??"";return{id:J.id,taskId:J.task_id,sessionId:J.session_id,milestoneType:Q,milestoneTitle:X,milestoneDescription:q,processDescription:J.process_description??"",timestamp:new Date(J.timestamp).toISOString(),mdPath:J.md_path||void 0,actionType:Q,actionTitle:X,actionDescription:q}}async createTag(J){await this.initialize();let Q=Date.now(),X=await this.getTagByName(J);if(X)return X;return{id:this.db.prepare(`
3020
3025
  INSERT INTO task_tag (name, created_at, task_count)
3021
3026
  VALUES (?, ?, 0)
3022
- `).run(J,Q).lastInsertRowid,name:J,createdAt:new Date(Q).toISOString(),taskCount:0}}async getTag(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(J);if(!X)return;return this.rowToTag(X)}async getTagByName(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(J);if(!X)return;return this.rowToTag(X)}async listTags(J){await this.initialize();let Q="SELECT * FROM task_tag",X=[],Y=J?.orderBy||"count";if(Y==="count")Q+=" ORDER BY task_count DESC";else if(Y==="name")Q+=" ORDER BY name ASC";else Q+=" ORDER BY created_at DESC";if(J?.limit)Q+=" LIMIT ?",X.push(J.limit);if(J?.offset)Q+=" OFFSET ?",X.push(J.offset);return this.db.prepare(Q).all(...X).map((W)=>this.rowToTag(W))}async searchTags(J){await this.initialize();let Q=`
3027
+ `).run(J,Q).lastInsertRowid,name:J,createdAt:new Date(Q).toISOString(),taskCount:0}}async getTag(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(J);if(!X)return;return this.rowToTag(X)}async getTagByName(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(J);if(!X)return;return this.rowToTag(X)}async listTags(J){await this.initialize();let Q="SELECT * FROM task_tag",X=[],q=J?.orderBy||"count";if(q==="count")Q+=" ORDER BY task_count DESC";else if(q==="name")Q+=" ORDER BY name ASC";else Q+=" ORDER BY created_at DESC";if(J?.limit)Q+=" LIMIT ?",X.push(J.limit);if(J?.offset)Q+=" OFFSET ?",X.push(J.offset);return this.db.prepare(Q).all(...X).map((W)=>this.rowToTag(W))}async searchTags(J){await this.initialize();let Q=`
3023
3028
  SELECT * FROM task_tag
3024
3029
  WHERE name LIKE ?
3025
3030
  ORDER BY task_count DESC
3026
3031
  LIMIT ?
3027
- `;return this.db.prepare(Q).all(`%${J.query}%`,J.limit||20).map((G)=>this.rowToTag(G))}async deleteTag(J){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(J).changes>0}async addTagsToTask(J,Q){await this.initialize();let X=Date.now(),Y=this.db.prepare(`
3032
+ `;return this.db.prepare(Q).all(`%${J.query}%`,J.limit||20).map((Y)=>this.rowToTag(Y))}async deleteTag(J){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(J).changes>0}async addTagsToTask(J,Q){await this.initialize();let X=Date.now(),q=this.db.prepare(`
3028
3033
  INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
3029
3034
  VALUES (?, ?, ?)
3030
- `);for(let G of Q)Y.run(J,G,X),this.db.run(`
3035
+ `);for(let Y of Q)q.run(J,Y,X),this.db.run(`
3031
3036
  UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
3032
- `,G);await this.syncTaskTagsJson(J)}async removeTagsFromTask(J,Q){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let Y of Q)X.run(J,Y),this.db.run(`
3037
+ `,Y);await this.syncTaskTagsJson(J)}async removeTagsFromTask(J,Q){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let q of Q)X.run(J,q),this.db.run(`
3033
3038
  UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
3034
- `,Y);await this.syncTaskTagsJson(J)}async getTagsForTask(J){await this.initialize();let Q=`
3039
+ `,q);await this.syncTaskTagsJson(J)}async getTagsForTask(J){await this.initialize();let Q=`
3035
3040
  SELECT t.* FROM task_tag t
3036
3041
  INNER JOIN task_tag_relation r ON t.id = r.tag_id
3037
3042
  WHERE r.task_id = ?
3038
3043
  ORDER BY t.name ASC
3039
- `;return this.db.prepare(Q).all(J).map((G)=>this.rowToTag(G))}async getTaskIdsByTags(J){if(await this.initialize(),J.length===0)return[];let X=`
3044
+ `;return this.db.prepare(Q).all(J).map((Y)=>this.rowToTag(Y))}async getTaskIdsByTags(J){if(await this.initialize(),J.length===0)return[];let X=`
3040
3045
  SELECT DISTINCT r.task_id FROM task_tag_relation r
3041
3046
  INNER JOIN task_tag t ON r.tag_id = t.id
3042
3047
  WHERE t.name IN (${J.map(()=>"?").join(", ")})
3043
- `;return this.db.prepare(X).all(...J).map((q)=>q.task_id)}async updateTaskTags(J,Q){await this.initialize();let X=await this.getTagsForTask(J);if(X.length>0)await this.removeTagsFromTask(J,X.map((G)=>G.id));let Y=[];for(let G of Q){let q=await this.getTagByName(G);if(!q)q=await this.createTag(G);Y.push(q.id)}if(Y.length>0)await this.addTagsToTask(J,Y)}async searchTasksByKeywords(J,Q={}){if(await this.initialize(),!J||J.length===0)return{tasks:[],total:0};let{limit:X=20,offset:Y=0,excludeTaskId:G,status:q,priority:W,type:z,depth:H}=Q,B=null;if(H!==void 0&&H>=0)B=await this.collectTaskIdsByDepth(H);let U=new Map,V="SELECT * FROM task WHERE 1=1",O=[];if(G)V+=" AND id != ?",O.push(G);if(q)V+=" AND status = ?",O.push(q);if(W)V+=" AND priority = ?",O.push(W);if(z)V+=" AND type = ?",O.push(z);if(!Q?.include_archived&&Q?.status!=="archived")V+=" AND status != 'archived'";let F=Math.max(X*5,200);V+=" ORDER BY updated_at DESC LIMIT ?",O.push(F);let D=this.db.prepare(V).all(...O);for(let b of D){let w=this.rowToTask(b),f=new Set,A=0;if(typeof w.title==="string"&&w.title){let S=w.title.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))A++,f.add(x)}if(w.tags&&Array.isArray(w.tags))for(let S of J){let x=S.toLowerCase();if(w.tags.some((r)=>r.toLowerCase().includes(x)))A+=2,f.add(S)}if(typeof w.description==="string"&&w.description){let S=w.description.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))A++,f.add(x)}if(typeof w.goals_and_expected_deliverables==="string"&&w.goals_and_expected_deliverables){let S=w.goals_and_expected_deliverables.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))A++,f.add(x)}if(f.size===J.length)U.set(w.id,{task:w,matchCount:A})}let M=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let b of M){let f=new Set;for(let r of J){let g=`%${r}%`;if(this.db.prepare(`
3048
+ `;return this.db.prepare(X).all(...J).map((G)=>G.task_id)}async updateTaskTags(J,Q){await this.initialize();let X=await this.getTagsForTask(J);if(X.length>0)await this.removeTagsFromTask(J,X.map((Y)=>Y.id));let q=[];for(let Y of Q){let G=await this.getTagByName(Y);if(!G)G=await this.createTag(Y);q.push(G.id)}if(q.length>0)await this.addTagsToTask(J,q)}async searchTasksByKeywords(J,Q={}){if(await this.initialize(),!J||J.length===0)return{tasks:[],total:0};let{limit:X=20,offset:q=0,excludeTaskId:Y,status:G,priority:W,type:z,depth:H}=Q,B=null;if(H!==void 0&&H>=0)B=await this.collectTaskIdsByDepth(H);let U=new Map,V="SELECT * FROM task WHERE 1=1",O=[];if(Y)V+=" AND id != ?",O.push(Y);if(G)V+=" AND status = ?",O.push(G);if(W)V+=" AND priority = ?",O.push(W);if(z)V+=" AND type = ?",O.push(z);if(!Q?.include_archived&&Q?.status!=="archived")V+=" AND status != 'archived'";let F=Math.max(X*5,200);V+=" ORDER BY updated_at DESC LIMIT ?",O.push(F);let D=this.db.prepare(V).all(...O);for(let b of D){let w=this.rowToTask(b),T=new Set,Z=0;if(typeof w.title==="string"&&w.title){let I=w.title.toLowerCase();for(let y of J)if(I.includes(y.toLowerCase()))Z++,T.add(y)}if(w.tags&&Array.isArray(w.tags))for(let I of J){let y=I.toLowerCase();if(w.tags.some((n)=>n.toLowerCase().includes(y)))Z+=2,T.add(I)}if(typeof w.description==="string"&&w.description){let I=w.description.toLowerCase();for(let y of J)if(I.includes(y.toLowerCase()))Z++,T.add(y)}if(typeof w.goals_and_expected_deliverables==="string"&&w.goals_and_expected_deliverables){let I=w.goals_and_expected_deliverables.toLowerCase();for(let y of J)if(I.includes(y.toLowerCase()))Z++,T.add(y)}if(T.size===J.length)U.set(w.id,{task:w,matchCount:Z})}let M=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let b of M){let T=new Set;for(let n of J){let C=`%${n}%`;if(this.db.prepare(`
3044
3049
  SELECT * FROM task_operation
3045
3050
  WHERE task_id = ?
3046
3051
  AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
3047
3052
  LIMIT 10
3048
- `).all(b.task_id,g,g,g).length>0)f.add(r)}if(f.size===0)continue;let A=this.db.prepare("SELECT * FROM task WHERE id = ?").get(b.task_id);if(!A)continue;let S=this.rowToTask(A);if(G&&S.id===G)continue;if(q&&S.status!==q)continue;if(W&&S.priority!==W)continue;if(z&&S.type!==z)continue;if(!Q?.include_archived&&S.status==="archived")continue;let x=U.get(S.id);if(x)x.matchCount+=2;else{let r=new Set(f);if(typeof S.title==="string"&&S.title){let g=S.title.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))r.add(c)}if(typeof S.description==="string"&&S.description){let g=S.description.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))r.add(c)}if(typeof S.goals_and_expected_deliverables==="string"&&S.goals_and_expected_deliverables){let g=S.goals_and_expected_deliverables.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))r.add(c)}if(S.tags&&Array.isArray(S.tags)){for(let g of J)if(S.tags.some((c)=>c.toLowerCase().includes(g.toLowerCase())))r.add(g)}if(r.size===J.length)U.set(S.id,{task:S,matchCount:2})}}let R=Array.from(U.values()).sort((b,w)=>w.matchCount-b.matchCount);if(B!==null)R=R.filter((b)=>B.has(b.task.id));let L=R.length;return{tasks:R.slice(Y,Y+X).map((b)=>b.task),total:L}}async collectTaskIdsByDepth(J){let Q=new Set,Y=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((G)=>G.id);for(let G of Y)Q.add(G);if(J===0)return Q;for(let G=1;G<=J;G++){if(Y.length===0)break;let q=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${q})`).all(...Y).map((z)=>z.id);for(let z of Y)Q.add(z)}return Q}async findSimilarTasksByKeywords(J,Q={}){let X={...Q,limit:Q.limit??5};return(await this.searchTasksByKeywords(J,X)).tasks}async findSimilarTasks(J,Q=5){await this.initialize();let X=await this.getTagsForTask(J);if(X.length===0)return[];let Y=X.map((H)=>H.id),q=`
3053
+ `).all(b.task_id,C,C,C).length>0)T.add(n)}if(T.size===0)continue;let Z=this.db.prepare("SELECT * FROM task WHERE id = ?").get(b.task_id);if(!Z)continue;let I=this.rowToTask(Z);if(Y&&I.id===Y)continue;if(G&&I.status!==G)continue;if(W&&I.priority!==W)continue;if(z&&I.type!==z)continue;if(!Q?.include_archived&&I.status==="archived")continue;let y=U.get(I.id);if(y)y.matchCount+=2;else{let n=new Set(T);if(typeof I.title==="string"&&I.title){let C=I.title.toLowerCase();for(let r of J)if(C.includes(r.toLowerCase()))n.add(r)}if(typeof I.description==="string"&&I.description){let C=I.description.toLowerCase();for(let r of J)if(C.includes(r.toLowerCase()))n.add(r)}if(typeof I.goals_and_expected_deliverables==="string"&&I.goals_and_expected_deliverables){let C=I.goals_and_expected_deliverables.toLowerCase();for(let r of J)if(C.includes(r.toLowerCase()))n.add(r)}if(I.tags&&Array.isArray(I.tags)){for(let C of J)if(I.tags.some((r)=>r.toLowerCase().includes(C.toLowerCase())))n.add(C)}if(n.size===J.length)U.set(I.id,{task:I,matchCount:2})}}let j=Array.from(U.values()).sort((b,w)=>w.matchCount-b.matchCount);if(B!==null)j=j.filter((b)=>B.has(b.task.id));let L=j.length;return{tasks:j.slice(q,q+X).map((b)=>b.task),total:L}}async collectTaskIdsByDepth(J){let Q=new Set,q=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((Y)=>Y.id);for(let Y of q)Q.add(Y);if(J===0)return Q;for(let Y=1;Y<=J;Y++){if(q.length===0)break;let G=q.map(()=>"?").join(",");q=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${G})`).all(...q).map((z)=>z.id);for(let z of q)Q.add(z)}return Q}async findSimilarTasksByKeywords(J,Q={}){let X={...Q,limit:Q.limit??5};return(await this.searchTasksByKeywords(J,X)).tasks}async findSimilarTasks(J,Q=5){await this.initialize();let X=await this.getTagsForTask(J);if(X.length===0)return[];let q=X.map((H)=>H.id),G=`
3049
3054
  SELECT t.*, COUNT(r2.tag_id) as match_count
3050
3055
  FROM task t
3051
3056
  INNER JOIN task_tag_relation r ON t.id = r.task_id
3052
3057
  INNER JOIN task_tag_relation r2 ON t.id = r2.task_id
3053
- WHERE r.tag_id IN (${Y.map(()=>"?").join(", ")})
3058
+ WHERE r.tag_id IN (${q.map(()=>"?").join(", ")})
3054
3059
  AND t.id != ?
3055
3060
  GROUP BY t.id
3056
3061
  ORDER BY match_count DESC, t.updated_at DESC
3057
3062
  LIMIT ?
3058
- `;return this.db.prepare(q).all(...Y,J,Q).map((H)=>this.rowToTask(H))}async searchTasks(J,Q=20){await this.initialize();let X=`
3063
+ `;return this.db.prepare(G).all(...q,J,Q).map((H)=>this.rowToTask(H))}async searchTasks(J,Q=20){await this.initialize();let X=`
3059
3064
  SELECT * FROM task
3060
3065
  WHERE title LIKE ? OR description LIKE ?
3061
3066
  ORDER BY updated_at DESC
3062
3067
  LIMIT ?
3063
- `;return this.db.prepare(X).all(`%${J}%`,`%${J}%`,Q).map((q)=>this.rowToTask(q))}async findTasksByContextValue(J,Q=50){if(await this.initialize(),!J)return[];let X=`
3068
+ `;return this.db.prepare(X).all(`%${J}%`,`%${J}%`,Q).map((G)=>this.rowToTask(G))}async findTasksByContextValue(J,Q=50){if(await this.initialize(),!J)return[];let X=`
3064
3069
  SELECT * FROM task
3065
3070
  WHERE context LIKE ?
3066
3071
  ORDER BY updated_at DESC
3067
3072
  LIMIT ?
3068
- `;return this.db.prepare(X).all(`%${J}%`,Q).map((G)=>this.rowToTask(G))}rowToTag(J){return{id:J.id,name:J.name,createdAt:new Date(J.created_at).toISOString(),taskCount:J.task_count}}async syncTaskTagsJson(J){let X=(await this.getTagsForTask(J)).map((G)=>G.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,J),this.tasksCache.delete(J)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},k([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],S$.prototype,"rowToTask",null),k([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],S$.prototype,"searchTasksByKeywords",null)});function e3($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let Y=Q.replace(/-/g,"_").toUpperCase(),G=$.slice(X.length);if(G.startsWith("_"))G=G.slice(1);if(!G)return;let q=G.indexOf("_"),W;if(q===-1)W=G;else{let H=G.slice(0,q),B=G.slice(q+1);if(H===Y)W=B;else W=G}if(!W)return;let z=W.replace(/_/g,".");return`${Q}.${z.toLowerCase()}`}function $1($,J){return{...$,execute:J}}var FM=()=>{},J1=a(()=>{FM(),w8(),z2()});J1();class c8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new K9}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($,J){this.hookManager.register($,J)}addHook($,J,Q,X){this.hookManager.register($,$1({name:J,priority:X},Q))}removeHook($,J){return this.hookManager.unregister($,J)}async executeHooks($,J,Q){await this.hookManager.execute($,J,Q)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig($,J){let Q=this.getConfigComponent();if(Q){let X=Q.get($);if(X!==void 0)return X}return J}}n();var MM={"task.storage.type":"sqlite","task.storage.dbPath":void 0},OM={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"]}]};z2();B$();n();var W6=i("task:tag");class Y1{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return W6.debug(`[TagService] Created tag: ${J.name} (id=${J.id})`),J}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 J=await this.store.deleteTag($);if(J)W6.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),W6.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),W6.debug(`[TagService] Removed ${J.length} tags from task ${$}`)}async getTagsForTask($){return this.store.getTagsForTask($)}async getTaskIdsByTags($){return this.store.getTaskIdsByTags($)}async findSimilarTasks($,J=5){return this.store.findSimilarTasks($,J)}async searchTasks($,J=20){return this.store.searchTasks($,J)}async searchTasksByKeywords($,J){return(await this.store.searchTasksByKeywords($,J)).tasks}async findSimilarTasksByKeywords($,J){return this.store.findSimilarTasksByKeywords($,J)}async syncTagsToTask($,J){let Q=[];for(let z of J){let H=await this.store.getTagByName(z);if(!H)H=await this.store.createTag(z);Q.push(H.id)}let X=await this.store.getTagsForTask($),Y=new Set(X.map((z)=>z.id)),G=new Set(Q),q=Q.filter((z)=>!Y.has(z)),W=X.filter((z)=>!G.has(z.id)).map((z)=>z.id);if(W.length>0)await this.store.removeTagsFromTask($,W);if(q.length>0)await this.store.addTagsToTask($,q);await this.store.updateTaskTags($,J),W6.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}V0();var Q0=i("task");function Q1($){return $==="completed"||$==="cancelled"||$==="archived"}function KM($){if(!$)return!1;let J=$.trim();if(!J)return!1;return a7.some((Q)=>J.startsWith(Q))}var RM="Deliverable: ";function X1($){if(!$)return;return`${RM}${$}`}class V$ extends c8{name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;skipAbortRunningTasksOnDispose=!1;waitForRunningTasksOnDispose=!1;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent($,J,Q){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.component",trigger_session_id:Q}}),Q0.info(`[TaskComponent] Event published: ${$}`)}constructor(){super()}async init($){await super.init($);let J=$?.options;if(!J?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=J.configComponent,this.skipAbortRunningTasksOnDispose=J.skipAbortRunningTasksOnDispose===!0,this.waitForRunningTasksOnDispose=J.waitForRunningTasksOnDispose===!0,await this.registerConfig(J),this.setStatus("running"),Q0.info("[TaskComponent] Initialized")}async registerConfig($){let J=this.configComponent;if(!J)return;let{configPath:Q,envPrefix:X,config:Y}=$,G=X??"TASK";if(J.registerComponent(OM),Q)J.registerSource({type:"file",relativePath:Q,optional:!0,watch:!1});J.registerSource({type:"env",envPrefix:G,priority:20,watch:!1}),await J.load("task");for(let q of Object.keys(process.env)){let W=e3(q,G,"task");if(!W)continue;let z=process.env[q];if(z!==void 0)await J.set(W,z)}for(let[q,W]of Object.entries(MM))if(J.get(q)===void 0)await J.set(q,W);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",w9());if(Y){let q=this.flattenConfig(Y);for(let[W,z]of Object.entries(q))await J.set(W,z)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new Y1(this.store)}async initStore(){let $=this.configComponent;if(!$)return;let J=$.get("task.storage.type")??"sqlite",Q=$.get("task.storage.dbPath");if(J==="sqlite")this.store=new S$(Q),Q0.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`);else this.store=new S$,Q0.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig($,J="task"){let Q={};for(let[X,Y]of Object.entries($)){let G=`${J}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign(Q,this.flattenConfig(Y,G));else Q[G]=Y}return Q}registerConfigWatcher($){if(typeof $.watch!=="function")return;this.configWatcher=$.watch("task.*",(J)=>{this.onConfigChange(J)})}onConfigChange($){if(Q0.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 J0(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent){await this.registerTools(),this.toolComponent.register(N6(this.backgroundTaskManager),"built-in"),Q0.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");let $=this.env?.getComponent("session");this.toolComponent.register(X4(this.backgroundTaskManager,$??null),"built-in"),Q0.debug("[TaskComponent] Registered compact_session tool (factory pattern)")}else Q0.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(N6(null),"built-in"),Q0.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch($){Q0.warn(`[TaskComponent] Failed to reset query_background_process tool: ${$.message}`)}try{this.toolComponent.register(k7,"built-in"),Q0.debug("[TaskComponent] Reset compact_session tool to no-deps default (cleanup)")}catch($){Q0.warn(`[TaskComponent] Failed to reset compact_session tool: ${$.message}`)}}if(this.backgroundTaskManager)await this.backgroundTaskManager.dispose(this.skipAbortRunningTasksOnDispose?{skipAbortRunningTasks:!0,waitForRunningTasks:this.waitForRunningTasksOnDispose}:void 0),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let $=[s2(this),o2(this),t2(this),X6(this),e2(this),v8(this),x8(this),$6(this),h8(this),J6(this),y8(this),Q6(this)],J=[Y6(this),m8(this),G6(this),u8(this),l8(this)],Q=[R3(this),u7(this.backgroundTaskManager)];for(let X of[...$,...J,...Q])this.toolComponent.register(X),Q0.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook($,J,Q={}){let X={component:{name:this.name,version:this.version},data:J,metadata:Q,phase:$.includes("before")?"before":"after",hookPoint:$};await S0.execute($,J,Q)}async createTask($){let J=$.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 Q={options:{...$},sessionId:J,tagService:this.tagService,taskComponent:this};await this.executeHook(X0.BEFORE_CREATE,Q);let X=await this.store.createTask(Q.options);await this.store.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(X0.AFTER_CREATE,Y),this.publishEvent(b$.CREATED,{task:X,sessionId:J},J),Q0.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask($){return this.store.getTask($)}async getTaskIdBySessionId($){return this.store.getTaskIdBySessionId($)}async getTaskIdsBySessionId($){let J=this.store;if(typeof J.getTaskIdsBySessionId==="function"){let X=await J.getTaskIdsBySessionId($);return Array.isArray(X)?X:[]}let Q=await this.store.getTaskIdBySessionId($);return typeof Q==="number"?[Q]:[]}async getTaskWithOperations($){let J=await this.store.getTask($);if(!J)return;let Q=await this.store.listOperations({taskId:$});return{...J,operations:Q,task:J}}withTerminalCurrentStatus($,J){let Q=$.status;if(!Q)return $;if($.current_status!==void 0)return $;let X;switch(Q){case"completed":X=p0;break;case"cancelled":X=R$;break;case"archived":X=L$;break;default:if(J&&Q1(J.status)&&KM(J.current_status))return{...$,current_status:r7};return $}return{...$,current_status:X}}async updateTask($,J){let Q={id:$,options:{...J},tagService:this.tagService};await this.executeHook(X0.BEFORE_UPDATE,Q);let X=Q.options.status,Y;if(X&&!Q1(X))Y=await this.store.getTask($);let G=this.withTerminalCurrentStatus(Q.options,Y),q=await this.store.updateTask($,G);if(q){let W={task:q,changes:J,tagService:this.tagService};await this.executeHook(X0.AFTER_UPDATE,W),this.publishEvent(b$.UPDATED,{task:q,changes:J,sessionId:""},""),Q0.info(`[TaskComponent] Task updated: ${$}`)}return q}async deleteTask($){let J={id:$};await this.executeHook(X0.BEFORE_DELETE,J);let Q=await this.store.deleteTask($),X={id:$,deleted:Q};if(await this.executeHook(X0.AFTER_DELETE,X),Q)this.publishEvent(b$.DELETED,{taskId:$,sessionId:""},""),Q0.info(`[TaskComponent] Task deleted: ${$}`);return Q}async listTasks($){return this.store.listTasks($)}async searchTasksByKeywords($,J){return this.store.searchTasksByKeywords($,J||{})}async getTaskTree($,J=-1){return this.store.getTaskTree($,J)}async getChildTasks($,J){return this.store.getChildTasks($,J)}async completeTask($,J,Q){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.`);if(X&&Z6.includes(X.status))throw Error(`Cannot complete task: #${$} - ${X.title}. It is already in terminal status "${X.status}". Reopen it first via task_update(status="active") if acceptance should proceed.`);let Y={status:"completed",progress:100,current_status:Q?`${p0}\uFF08${_2}\uFF1A${Q}\uFF09`:p0};if(Q){let q={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))q=W}catch{Q0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}q.deliverable_storage_path=Q,Y.context=JSON.stringify(q)}let G=await this.updateTask($,Y);if(G)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:X1(Q)}),this.publishEvent(b$.COMPLETED,{task:G,sessionId:J},J),Q0.info(`[TaskComponent] Task completed: ${$}, deliverable=${Q||"(none)"}`);return G}async updateTaskContext($,J){return this.store.updateTask($,{context:J})}async preCompleteTask($,J,Q,X){let Y=await this.store.getTask($);if(Y&&Y.type==="cycle")throw Error(`Cannot pre-complete cycle task: #${$} - ${Y.title}. Cycle tasks are not meant to be completed or submitted for acceptance.`);let q={status:"to_validate",current_status:X?`${x0}\uFF1A${X}`:x0};if(Q){let z={};if(Y?.context)try{let H=JSON.parse(Y.context);if(H&&typeof H==="object"&&!Array.isArray(H))z=H}catch{Q0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}z.deliverable_storage_path=Q,q.context=JSON.stringify(z)}let W=await this.updateTask($,q);if(W){let z=M9(),H={task:W,changes:q,terminalStatus:"to_validate",sessionId:z.sessionId??J,tagService:this.tagService};await this.executeHook(X0.AFTER_COMPLETE,H);let B=[],U=X1(Q);if(U)B.push(U);if(X)B.push(X);await this.createOperation({taskId:$,sessionId:J,milestoneType:"milestone",milestoneTitle:`${x0}\uFF08to_validate\uFF09\uFF1ATask #${$} submitted for acceptance`,milestoneDescription:B.join(" / ")||x0}),Q0.info(`[TaskComponent] Task submitted for acceptance (to_validate): ${$}, deliverable=${Q||"(none)"}`)}return W}async createOperation($){let J={options:{...$}};await this.executeHook(X0.OPERATION_BEFORE_CREATE,J);let Q=await this.store.createOperation(J.options),X=await this.store.getTask(Q.taskId),Y={operation:Q};return await this.executeHook(X0.OPERATION_AFTER_CREATE,Y,{task:X,operation:Q}),this.publishEvent(b$.OPERATION_ADDED,{operation:Q,taskId:Q.taskId},Q.sessionId),Q0.info(`[TaskComponent] Operation created: ${Q.id} for task ${Q.taskId}`),Q}async getOperation($){return this.store.getOperation($)}async updateOperation($,J){return this.store.updateOperation($,J)}async deleteOperation($){return this.store.deleteOperation($)}async listOperations($){return this.store.listOperations($)}async listOperationsFresh($){let J=this.store;if(typeof J.listOperationsFresh==="function")return await J.listOperationsFresh($);if(typeof J.invalidateOperationsCache==="function")J.invalidateOperationsCache($.taskId);return await this.store.listOperations($)}getTagService(){return this.tagService}registerHook($,J){S0.register($,J),this.plugins.set(this.makePluginKey($,J.name),J),Q0.debug(`[TaskComponent] Registered hook: ${J.name} at ${$}`)}registerHooks($){for(let{hookPoint:J,hook:Q}of $)this.registerHook(J,Q)}unregisterHook($,J){let Q=S0.unregister($,J);if(Q)this.plugins.delete(this.makePluginKey($,J)),Q0.info(`[TaskComponent] Unregistered hook: ${J} from ${$}`);return Q}listHooks(){return Array.from(this.plugins.values())}makePluginKey($,J){return`${$}::${J}`}countHooks($){return S0.count($)}}k([u("task.component.executeHook",{recordParams:!0})],V$.prototype,"executeHook",null);k([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],V$.prototype,"createTask",null);k([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],V$.prototype,"updateTask",null);k([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],V$.prototype,"completeTask",null);k([u("task.component.preCompleteTask",{recordParams:!0,recordResult:!0,log:!0})],V$.prototype,"preCompleteTask",null);k([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],V$.prototype,"createOperation",null);var p8=K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]),d8=K.enum(["low","medium","high"]),i8=K.enum(["normal","cycle","longterm"]),n8=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),LM=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});U$();U$();var jM="Deliverable: ";function G1($){if(!$)return;return`${jM}${$}`}var P9=1e6;class r8{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=NM($);if(J!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(J);return(await this.scanAllTasks()).find((Q)=>Q.id===J)??null}return await this.port.getTask(String($))}toTask($){let{nativeId:J,...Q}=$;return Q}toOperation($){let{nativeId:J,...Q}=$;return Q}async scanAllTasks(){return(await this.port.listTasks({limit:P9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;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.`);Q=Y.id}let X=await this.port.createTask({title:$.title,description:$.description,priority:$.priority,type:$.type,goals_and_expected_deliverables:$.goals_and_expected_deliverables,...Q!==void 0?{parent_task_id:Q}:{},due_date:$.due_date,tags:$.tags,project_path:$.project_path,context:$.context,sessionId:J});return await this.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask($){let J=await this.resolve($);return J?this.toTask(J):null}async getTaskWithOperations($){let J=await this.getTask($);if(!J)return null;let Q=await this.listOperations({taskId:J.id,limit:P9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,$),{tasks:X.slice(Q,Q+J),total:X.length}}async updateTask($,J){let Q=await this.resolve($);if(!Q)return null;let X;if(J.parent_task_id!==void 0)if(J.parent_task_id===null)X=null;else{let G=await this.resolve(J.parent_task_id);if(!G)throw Error(`Parent task #${J.parent_task_id} not found.`);X=G.id}let Y=await this.port.updateTask(Q.nativeId,{title:J.title,description:J.description,status:J.status,priority:J.priority,type:J.type,progress:J.progress,current_status:J.current_status,goals_and_expected_deliverables:J.goals_and_expected_deliverables,due_date:J.due_date,tags:J.tags,project_path:J.project_path,context:J.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask($){let J=await this.resolve($);if(!J)return!1;return await this.port.deleteTask(J.nativeId)}async completeTask($,J,Q){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,current_status:Q?`${p0}\uFF08${_2}\uFF1A${Q}\uFF09`:p0};if(Q)Y.context=q1(X.context,Q);let G=await this.port.updateTask(X.nativeId,Y);if(!G)return null;let q=G1(Q);await this.createOperation({taskId:G.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${G.title}`,milestoneDescription:q??"Task completed",...Q?{mdPath:Q}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??G)}async preCompleteTask($,J,Q,X){let Y=await this.resolve($);if(!Y)return null;if(Y.type==="cycle")throw Error(`Cannot pre-complete cycle task: #${Y.id} - ${Y.title}. Cycle tasks are not meant to be completed or submitted for acceptance.`);let q={status:"to_validate",current_status:X?`${x0}\uFF1A${X}`:x0};if(Q)q.context=q1(Y.context,Q);let W=await this.port.updateTask(Y.nativeId,q);if(!W)return null;let z=[],H=G1(Q);if(H)z.push(H);if(X)z.push(X);await this.createOperation({taskId:W.id,sessionId:J??this.defaultSessionId,milestoneType:"milestone",milestoneTitle:`${x0}\uFF08to_validate\uFF09\uFF1ATask #${W.id} submitted for acceptance`,milestoneDescription:z.join(" / ")||x0,...Q?{mdPath:Q}:{}});let B=await this.resolve(Y.nativeId);return this.toTask(B??W)}async getTaskTree($,J=-1){let Q=await this.resolve($);if(!Q)return[];if(J===0)return[];let X=(await this.scanAllTasks()).map((H)=>this.toTask(H)),Y=new Map;for(let H of X){if(H.parent_task_id===void 0)continue;let B=Y.get(H.parent_task_id)??[];B.push(H),Y.set(H.parent_task_id,B)}let G=[],q=new Set([Q.id]),W=[Q.id],z=0;while(W.length>0){if(J!==-1&&z>=J)break;let H=[];for(let B of W)for(let U of Y.get(B)??[]){if(q.has(U.id))continue;q.add(U.id),G.push(U),H.push(U.id)}W=H,z++}return G}async searchTasksByKeywords($,J={}){let Q=J.limit??20,X=J.offset??0,Y=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(Y=this.applyFilters(Y,J),J.excludeTaskId!==void 0)Y=Y.filter((W)=>W.id!==J.excludeTaskId);let G=$.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),q=G.length===0?Y:Y.filter((W)=>{let z=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return G.every((H)=>z.includes(H))});return{tasks:q.slice(X,X+Q),total:q.length}}async createOperation($){let J=await this.resolve($.taskId);if(!J)throw Error(`Task not found: ${$.taskId}`);let Q=$.milestoneType??$.actionType??"progress",X=$.milestoneTitle??$.actionTitle??"",Y=$.milestoneDescription??$.actionDescription??"",G=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:$.processDescription??"",...$.mdPath?{mdPath:$.mdPath}:{}});return this.toOperation(G)}async listOperations($={}){let J=$.limit??100,Q=$.offset??0,X=$.milestoneType??$.actionType;if($.taskId===void 0)return[];let Y=await this.resolve($.taskId);if(!Y)return[];let q=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?P9:J,offset:X?0:Q})).operations.map((W)=>this.toOperation(W));if(X)q=q.filter((W)=>W.milestoneType===X),q=q.slice(Q,Q+J);return q}async getOperation($){if(typeof this.port.getOperationByNum==="function"){let Q=await this.port.getOperationByNum($);return Q?this.toOperation(Q):null}let J=await this.scanAllTasks();for(let Q of J){let Y=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:P9})).operations.find((G)=>G.id===$);if(Y)return this.toOperation(Y)}return null}async updateOperation($,J){let Q=await this.getOperation($);if(!Q)return null;if(typeof this.port.updateOperationByNum!=="function")return Q;let X=await this.port.updateOperationByNum($,{sessionId:J.sessionId??Q.sessionId,milestoneType:J.milestoneType??J.actionType??Q.milestoneType,milestoneTitle:J.milestoneTitle??J.actionTitle??Q.milestoneTitle,milestoneDescription:J.milestoneDescription??J.actionDescription??Q.milestoneDescription,processDescription:J.processDescription??Q.processDescription,...J.mdPath!==void 0?{mdPath:J.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation($){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum($)}applyFilters($,J){let Q=$;if(J.include_archived!==!0&&J.status!=="archived")Q=Q.filter((Y)=>Y.status!=="archived");if(J.status!==void 0)Q=Q.filter((Y)=>Y.status===J.status);if(J.priority!==void 0)Q=Q.filter((Y)=>Y.priority===J.priority);if(J.type!==void 0)Q=Q.filter((Y)=>Y.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((Y)=>Y.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let Y=_M(Q,J.depth);Q=Q.filter((G)=>Y.has(G.id))}return Q}}function NM($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function _M($,J){if(J<0)return new Set($.map((q)=>q.id));let Q=new Set($.map((q)=>q.id)),X=new Map;for(let q of $){let W=q.parent_task_id;if(W===void 0||!Q.has(W))continue;let z=X.get(W)??[];z.push(q),X.set(W,z)}let Y=new Set,G=$.filter((q)=>q.parent_task_id===void 0||!Q.has(q.parent_task_id));for(let q of G)Y.add(q.id);for(let q=1;q<=J;q++){let W=[];for(let z of G)for(let H of X.get(z.id)??[]){if(Y.has(H.id))continue;Y.add(H.id),W.push(H)}if(W.length===0)break;G=W}return Y}function q1($,J){let Q={};if(typeof $==="string"&&$.trim().length>0)try{let X=JSON.parse($);if(X&&typeof X==="object"&&!Array.isArray(X))Q=X}catch{}return Q.deliverable_storage_path=J,JSON.stringify(Q)}var AM=1e6;function ZM($){let J={};if($.type!==void 0)J.type=$.type;if($.progress!==void 0)J.progress=$.progress;if($.current_status!==void 0)J.current_status=$.current_status;if($.goals_and_expected_deliverables!==void 0)J.goals_and_expected_deliverables=$.goals_and_expected_deliverables;if($.project_path!==void 0)J.project_path=$.project_path;if($.context!==void 0)J.context=$.context;if($.due_date!==void 0)J.due_date=$.due_date;return J}function z6($,J,Q){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:J.toRoyStatus($.status),priority:J.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??"",...Q!==void 0?{parent_task_id:Q}:{},createdAt:$.created_at,updatedAt:$.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:J.toRoyTags($.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function H6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),Y=String(J.milestoneDescription??J.actionDescription??""),G=J.taskId??$.task_id,q=typeof G==="number"?G:typeof G==="string"&&/^\d+$/.test(G)?Number(G):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:q,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:Y}}function W1($,J,Q={}){let X=Q.operationType??"roy.milestone",Y=Q.agent??"roy",G=Q.scanLimit??AM;async function q(){let H=await $.listTasks({limit:G});return new Map(H.tasks.filter((B)=>typeof B.num==="number").map((B)=>[B.id,B.num]))}async function W(H){if(typeof $.getTaskByNum==="function")return await $.getTaskByNum(H);return(await $.listTasks({limit:G})).tasks.find((U)=>U.num===H)??null}async function z(H){let U=[...(await q()).entries()].find(([,V])=>V===H);if(!U)throw Error(`parent task not found: ${H}`);return U[0]}return{async createTask(H){let B=H.parent_task_id!==void 0?await z(H.parent_task_id):null,U={type:H.type??"normal",progress:H.progress??0,current_status:H.current_status??"",goals_and_expected_deliverables:H.goals_and_expected_deliverables??"",project_path:H.project_path,context:H.context,...H.due_date?{due_date:H.due_date}:{}},V=await $.createTask({title:H.title,description:H.description,priority:J.toStorePriority(H.priority),owner:Y,tags:J.toStoreTags(H.tags),parent_id:B,session_id:H.sessionId??"unknown",roy:U});return z6(V,J,H.parent_task_id)},async getTask(H){let B=await $.getTask(H);if(!B)return null;let U=await q();return z6(B,J,B.parent_id?U.get(B.parent_id):void 0)},async getTaskByNum(H){let B=await W(H);if(!B)return null;let U=await q();return z6(B,J,B.parent_id?U.get(B.parent_id):void 0)},async listTasks(H){let B=await $.listTasks({limit:H?.limit??20,offset:H?.offset??0}),U=await q();return{tasks:B.tasks.map((V)=>z6(V,J,V.parent_id?U.get(V.parent_id):void 0)),total:B.total}},async updateTask(H,B){let U=ZM(B),V=await $.updateTask(H,{...B.title!==void 0?{title:B.title}:{},...B.description!==void 0?{description:B.description}:{},...B.status!==void 0?{status:J.toStoreStatus(B.status)}:{},...B.priority!==void 0?{priority:J.toStorePriority(B.priority)}:{},...B.tags!==void 0?{tags:J.toStoreTags(B.tags)}:{},...Object.keys(U).length>0?{roy:U}:{}});if(!V)return null;let O;if(B.parent_task_id!==void 0){let D=B.parent_task_id===null?null:await z(B.parent_task_id);if(typeof $.setParentId==="function")await $.setParentId(H,D);O=B.parent_task_id===null?void 0:B.parent_task_id}let F=await $.getTask(H)??V;if(O===void 0&&F.parent_id)O=(await q()).get(F.parent_id);return z6(F,J,O)},async deleteTask(H){return await $.deleteTask(H)},async createOperation(H){let B=await $.appendOperation({task_id:H.taskNativeId??String(H.taskId),type:X,data:{taskId:H.taskId,sessionId:H.sessionId,milestoneType:H.milestoneType,milestoneTitle:H.milestoneTitle,milestoneDescription:H.milestoneDescription,processDescription:H.processDescription,...H.mdPath?{mdPath:H.mdPath}:{}}});return H6(B)},async listOperations(H){let B=await $.listOperations({...H?.taskNativeId?{task_id:H.taskNativeId}:{},type:X,limit:H?.limit??G,offset:H?.offset??0});return{operations:B.operations.map(H6),total:B.total}},async getOperationByNum(H){if(typeof $.getOperationByNum!=="function")return null;let B=await $.getOperationByNum(H);return B?H6(B):null},async updateOperationByNum(H,B){if(typeof $.updateOperation!=="function")return null;if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(H);if(!U)return null;let V=H6(U),O=await $.updateOperation(H,{data:{taskId:V.taskId,sessionId:B.sessionId??V.sessionId,milestoneType:B.milestoneType??V.milestoneType,milestoneTitle:B.milestoneTitle??V.milestoneTitle,milestoneDescription:B.milestoneDescription??V.milestoneDescription,processDescription:B.processDescription??V.processDescription,...B.mdPath??V.mdPath?{mdPath:B.mdPath??V.mdPath}:{}}});return O?H6(O):null},async deleteOperationByNum(H){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(H)}}}var wM="roy.milestone",PM={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",to_validate:"review",archived:"archived"},bM={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"to_validate",archived:"archived"};function z1($){return PM[$]??"pending"}function H1($){return bM[$]??"todo"}function B1($){if($==="high")return 1;if($==="low")return 5;return 3}function U1($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function V1($){if(!$||$.length===0)return;return $.join(",")}function D1($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var EM={toRoyStatus:($)=>H1($),toStoreStatus:($)=>z1($),toRoyPriority:($)=>U1($),toStorePriority:($)=>B1($),toRoyTags:($)=>D1($),toStoreTags:($)=>V1($)};function F1($,J={}){return new r8(W1($,EM,{operationType:wM,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var GN=p8.options,qN=d8.options,WN=i8.options,zN=n8.options;var O1=Symbol("Let zodToJsonSchema decide on which parser to use");var M1={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"},K1=($)=>typeof $==="string"?{...M1,name:$}:{...M1,...$};var R1=($)=>{let J=K1($),Q=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function a8($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function p($,J,Q,X,Y){$[J]=Q,a8($,J,X,Y)}var b9=($,J)=>{let Q=0;for(;Q<$.length&&Q<J.length;Q++)if($[Q]!==J[Q])break;return[($.length-Q).toString(),...J.slice(Q)].join("/")};function t($){if($.target!=="openAi")return{};let J=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?b9(J,$.currentPath):J.join("/")}}function L1($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==_.ZodAny)Q.items=v($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)p(Q,"minItems",$.minLength.value,$.minLength.message,J);if($.maxLength)p(Q,"maxItems",$.maxLength.value,$.maxLength.message,J);if($.exactLength)p(Q,"minItems",$.exactLength.value,$.exactLength.message,J),p(Q,"maxItems",$.exactLength.value,$.exactLength.message,J);return Q}function j1($,J){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"min":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"minimum",X.value,X.message,J);else p(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;p(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"maximum",X.value,X.message,J);else p(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;p(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":p(Q,"multipleOf",X.value,X.message,J);break}return Q}function N1(){return{type:"boolean"}}function E9($,J){return v($.type._def,J)}var _1=($,J)=>{return v($.innerType._def,J)};function s8($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,G)=>s8($,J,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 CM($,J)}}var CM=($,J)=>{let Q={type:"integer",format:"unix-time"};if(J.target==="openApi3")return Q;for(let X of $.checks)switch(X.kind){case"min":p(Q,"minimum",X.value,X.message,J);break;case"max":p(Q,"maximum",X.value,X.message,J);break}return Q};function A1($,J){return{...v($.innerType._def,J),default:$.defaultValue()}}function Z1($,J){return J.effectStrategy==="input"?v($.schema._def,J):t(J)}function w1($){return{type:"string",enum:Array.from($.values)}}var fM=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function P1($,J){let Q=[v($.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),v($.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((G)=>!!G),X=J.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return Q.forEach((G)=>{if(fM(G)){if(Y.push(...G.allOf),G.unevaluatedProperties===void 0)X=void 0}else{let q=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:W,...z}=G;q=z}else X=void 0;Y.push(q)}}),Y.length?{allOf:Y,...X}:void 0}function b1($,J){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(J.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}var o8=void 0,C0={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(o8===void 0)o8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return o8},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 S9($,J){let Q={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":p(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J);break;case"max":p(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"email":switch(J.emailStrategy){case"format:email":f0(Q,"email",X.message,J);break;case"format:idn-email":f0(Q,"idn-email",X.message,J);break;case"pattern:zod":U0(Q,C0.email,X.message,J);break}break;case"url":f0(Q,"uri",X.message,J);break;case"uuid":f0(Q,"uuid",X.message,J);break;case"regex":U0(Q,X.regex,X.message,J);break;case"cuid":U0(Q,C0.cuid,X.message,J);break;case"cuid2":U0(Q,C0.cuid2,X.message,J);break;case"startsWith":U0(Q,RegExp(`^${t8(X.value,J)}`),X.message,J);break;case"endsWith":U0(Q,RegExp(`${t8(X.value,J)}$`),X.message,J);break;case"datetime":f0(Q,"date-time",X.message,J);break;case"date":f0(Q,"date",X.message,J);break;case"time":f0(Q,"time",X.message,J);break;case"duration":f0(Q,"duration",X.message,J);break;case"length":p(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J),p(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"includes":{U0(Q,RegExp(t8(X.value,J)),X.message,J);break}case"ip":{if(X.version!=="v6")f0(Q,"ipv4",X.message,J);if(X.version!=="v4")f0(Q,"ipv6",X.message,J);break}case"base64url":U0(Q,C0.base64url,X.message,J);break;case"jwt":U0(Q,C0.jwt,X.message,J);break;case"cidr":{if(X.version!=="v6")U0(Q,C0.ipv4Cidr,X.message,J);if(X.version!=="v4")U0(Q,C0.ipv6Cidr,X.message,J);break}case"emoji":U0(Q,C0.emoji(),X.message,J);break;case"ulid":{U0(Q,C0.ulid,X.message,J);break}case"base64":{switch(J.base64Strategy){case"format:binary":{f0(Q,"binary",X.message,J);break}case"contentEncoding:base64":{p(Q,"contentEncoding","base64",X.message,J);break}case"pattern:zod":{U0(Q,C0.base64,X.message,J);break}}break}case"nanoid":U0(Q,C0.nanoid,X.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return Q}function t8($,J){return J.patternStrategy==="escape"?TM($):$}var IM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function TM($){let J="";for(let Q=0;Q<$.length;Q++){if(!IM.has($[Q]))J+="\\";J+=$[Q]}return J}function f0($,J,Q,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:J,...Q&&X.errorMessages&&{errorMessage:{format:Q}}})}else p($,"format",J,Q,X)}function U0($,J,Q,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:E1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else p($,"pattern",E1(J,X),Q,X)}function E1($,J){if(!J.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},X=Q.i?$.source.toLowerCase():$.source,Y="",G=!1,q=!1,W=!1;for(let z=0;z<X.length;z++){if(G){Y+=X[z],G=!1;continue}if(Q.i){if(q){if(X[z].match(/[a-z]/)){if(W)Y+=X[z],Y+=`${X[z-2]}-${X[z]}`.toUpperCase(),W=!1;else if(X[z+1]==="-"&&X[z+2]?.match(/[a-z]/))Y+=X[z],W=!0;else Y+=`${X[z]}${X[z].toUpperCase()}`;continue}}else if(X[z].match(/[a-z]/)){Y+=`[${X[z]}${X[z].toUpperCase()}]`;continue}}if(Q.m){if(X[z]==="^"){Y+=`(^|(?<=[\r
3069
- ]))`;continue}else if(X[z]==="$"){Y+=`($|(?=[\r
3070
- ]))`;continue}}if(Q.s&&X[z]==="."){Y+=q?`${X[z]}\r
3073
+ `;return this.db.prepare(X).all(`%${J}%`,Q).map((Y)=>this.rowToTask(Y))}rowToTag(J){return{id:J.id,name:J.name,createdAt:new Date(J.created_at).toISOString(),taskCount:J.task_count}}async syncTaskTagsJson(J){let X=(await this.getTagsForTask(J)).map((Y)=>Y.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,J),this.tasksCache.delete(J)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},k([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],O$.prototype,"rowToTask",null),k([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],O$.prototype,"searchTasksByKeywords",null)});function z1($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let q=Q.replace(/-/g,"_").toUpperCase(),Y=$.slice(X.length);if(Y.startsWith("_"))Y=Y.slice(1);if(!Y)return;let G=Y.indexOf("_"),W;if(G===-1)W=Y;else{let H=Y.slice(0,G),B=Y.slice(G+1);if(H===q)W=B;else W=Y}if(!W)return;let z=W.replace(/_/g,".");return`${Q}.${z.toLowerCase()}`}function H1($,J){return{...$,execute:J}}var TM=()=>{},B1=s(()=>{TM(),S8(),V2()});B1();class s8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new A9}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($,J){this.hookManager.register($,J)}addHook($,J,Q,X){this.hookManager.register($,H1({name:J,priority:X},Q))}removeHook($,J){return this.hookManager.unregister($,J)}async executeHooks($,J,Q){await this.hookManager.execute($,J,Q)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig($,J){let Q=this.getConfigComponent();if(Q){let X=Q.get($);if(X!==void 0)return X}return J}}i();var vM={"task.storage.type":"sqlite","task.storage.dbPath":void 0,"task.storage.endpoint":void 0,"task.storage.authToken":void 0},xM={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"]},{key:"task.storage.endpoint",sources:["env","file"]},{key:"task.storage.authToken",sources:["env","file"]}]};V2();M$();i();var V6=d("task:tag");class o8{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return V6.debug(`[TagService] Created tag: ${J.name} (id=${J.id})`),J}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 J=await this.store.deleteTag($);if(J)V6.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),V6.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),V6.debug(`[TagService] Removed ${J.length} tags from task ${$}`)}async getTagsForTask($){return this.store.getTagsForTask($)}async getTaskIdsByTags($){return this.store.getTaskIdsByTags($)}async findSimilarTasks($,J=5){return this.store.findSimilarTasks($,J)}async searchTasks($,J=20){return this.store.searchTasks($,J)}async searchTasksByKeywords($,J){return(await this.store.searchTasksByKeywords($,J)).tasks}async findSimilarTasksByKeywords($,J){return this.store.findSimilarTasksByKeywords($,J)}async syncTagsToTask($,J){let Q=[];for(let z of J){let H=await this.store.getTagByName(z);if(!H)H=await this.store.createTag(z);Q.push(H.id)}let X=await this.store.getTagsForTask($),q=new Set(X.map((z)=>z.id)),Y=new Set(Q),G=Q.filter((z)=>!q.has(z)),W=X.filter((z)=>!Y.has(z.id)).map((z)=>z.id);if(W.length>0)await this.store.removeTagsFromTask($,W);if(G.length>0)await this.store.addTagsToTask($,G);await this.store.updateTaskTags($,J),V6.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}D0();var o=d("task");function U1($){return $==="completed"||$==="cancelled"||$==="archived"}function yM($){if(!$)return!1;let J=$.trim();if(!J)return!1;return Q7.some((Q)=>J.startsWith(Q))}var hM="Deliverable: ";function V1($){if(!$)return;return`${hM}${$}`}class K$ extends s8{name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;skipAbortRunningTasksOnDispose=!1;waitForRunningTasksOnDispose=!1;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent($,J,Q){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.component",trigger_session_id:Q}}),o.info(`[TaskComponent] Event published: ${$}`)}constructor(){super()}async init($){await super.init($);let J=$?.options;if(!J?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=J.configComponent,this.skipAbortRunningTasksOnDispose=J.skipAbortRunningTasksOnDispose===!0,this.waitForRunningTasksOnDispose=J.waitForRunningTasksOnDispose===!0,await this.registerConfig(J),this.setStatus("running"),o.info("[TaskComponent] Initialized")}async registerConfig($){let J=this.configComponent;if(!J)return;let{configPath:Q,envPrefix:X,config:q}=$,Y=X??"TASK";if(J.registerComponent(xM),Q)J.registerSource({type:"file",relativePath:Q,optional:!0,watch:!1});J.registerSource({type:"env",envPrefix:Y,priority:20,watch:!1}),await J.load("task");for(let G of Object.keys(process.env)){let W=z1(G,Y,"task");if(!W)continue;let z=process.env[G];if(z!==void 0)await J.set(W,z)}for(let[G,W]of Object.entries(vM))if(J.get(G)===void 0)await J.set(G,W);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",S9());if(q){let G=this.flattenConfig(q);for(let[W,z]of Object.entries(G))await J.set(W,z)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new o8(this.store)}async initStore(){let $=this.configComponent;if(!$)return;let J=$.get("task.storage.type")??"sqlite",Q=$.get("task.storage.dbPath"),X=this.store,q=this.buildStore(J,Q);if(X)try{X.close()}catch(Y){o.warn(`[TaskComponent] Failed to close previous store: ${Y instanceof Error?Y.message:String(Y)}`)}if(this.store=q,this.tagService=new o8(this.store),J==="remote"){let Y=$.get("task.storage.endpoint");o.info(`[TaskComponent] Using remote task-service: ${Y}${$.get("task.storage.authToken")?" (with bearer token)":" (no auth token)"}`)}else if(J==="sqlite")o.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`)}buildStore($,J){let Q=this.configComponent;if($==="remote"){let X=Q?.get("task.storage.endpoint"),q=Q?.get("task.storage.authToken");if(!X)throw Error("[TaskComponent] task.storage.type=remote requires task.storage.endpoint (e.g. http://127.0.0.1:7820). Set task.storage.endpoint and task.storage.authToken to match the running roy-task-service. No local fallback is performed by design.");return new T$({endpoint:X,authToken:q})}if($==="sqlite")return new O$(J);return o.warn(`[TaskComponent] Unknown task.storage.type="${String($)}", falling back to default SQLite storage. Supported: "sqlite" | "remote".`),new O$}flattenConfig($,J="task"){let Q={};for(let[X,q]of Object.entries($)){let Y=`${J}.${X}`;if(q&&typeof q==="object"&&!Array.isArray(q))Object.assign(Q,this.flattenConfig(q,Y));else Q[Y]=q}return Q}registerConfigWatcher($){if(typeof $.watch!=="function")return;this.configWatcher=$.watch("task.*",(J)=>{this.onConfigChange(J)})}onConfigChange($){if(o.info(`[TaskComponent] Config changed: ${$.key}`,{oldValue:$.oldValue,newValue:$.newValue}),$.key==="task.storage.type"||$.key==="task.storage.dbPath"||$.key==="task.storage.endpoint"||$.key==="task.storage.authToken")Promise.resolve(this.initStore()).catch((J)=>{o.error(`[TaskComponent] Failed to re-init store after ${$.key} change: ${J instanceof Error?J.message:String(J)} (keeping previous store)`)})}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new Q0(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent){await this.registerTools(),this.toolComponent.register(w6(this.backgroundTaskManager),"built-in"),o.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");let $=this.env?.getComponent("session");this.toolComponent.register(W4(this.backgroundTaskManager,$??null),"built-in"),o.debug("[TaskComponent] Registered compact_session tool (factory pattern)")}else o.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(w6(null),"built-in"),o.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch($){o.warn(`[TaskComponent] Failed to reset query_background_process tool: ${$.message}`)}try{this.toolComponent.register(i5,"built-in"),o.debug("[TaskComponent] Reset compact_session tool to no-deps default (cleanup)")}catch($){o.warn(`[TaskComponent] Failed to reset compact_session tool: ${$.message}`)}}if(this.backgroundTaskManager)await this.backgroundTaskManager.dispose(this.skipAbortRunningTasksOnDispose?{skipAbortRunningTasks:!0,waitForRunningTasks:this.waitForRunningTasksOnDispose}:void 0),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let $=[Q6(this),X6(this),q6(this),H6(this),Y6(this),u8(this),l8(this),G6(this),c8(this),W6(this),d8(this),z6(this)],J=[B6(this),n8(this),U6(this),r8(this),a8(this)],Q=[wJ(this),r5(this.backgroundTaskManager)];for(let X of[...$,...J,...Q])this.toolComponent.register(X),o.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook($,J,Q={}){let X={component:{name:this.name,version:this.version},data:J,metadata:Q,phase:$.includes("before")?"before":"after",hookPoint:$};await T0.execute($,J,Q)}async createTask($){let J=$.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 Q={options:{...$},sessionId:J,tagService:this.tagService,taskComponent:this};await this.executeHook(q0.BEFORE_CREATE,Q);let X=await this.store.createTask(Q.options);await this.store.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let q={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(q0.AFTER_CREATE,q),this.publishEvent(v$.CREATED,{task:X,sessionId:J},J),o.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask($){return this.store.getTask($)}async getTaskIdBySessionId($){return this.store.getTaskIdBySessionId($)}async getTaskIdsBySessionId($){let J=this.store;if(typeof J.getTaskIdsBySessionId==="function"){let X=await J.getTaskIdsBySessionId($);return Array.isArray(X)?X:[]}let Q=await this.store.getTaskIdBySessionId($);return typeof Q==="number"?[Q]:[]}async getTaskWithOperations($){let J=await this.store.getTask($);if(!J)return;let Q=await this.store.listOperations({taskId:$});return{...J,operations:Q,task:J}}withTerminalCurrentStatus($,J){let Q=$.status;if(!Q)return $;if($.current_status!==void 0)return $;let X;switch(Q){case"completed":X=a0;break;case"cancelled":X=Z$;break;case"archived":X=w$;break;default:if(J&&U1(J.status)&&yM(J.current_status))return{...$,current_status:J7};return $}return{...$,current_status:X}}async updateTask($,J){let Q={id:$,options:{...J},tagService:this.tagService};await this.executeHook(q0.BEFORE_UPDATE,Q);let X=Q.options.status,q;if(X&&!U1(X))q=await this.store.getTask($);let Y=this.withTerminalCurrentStatus(Q.options,q),G=await this.store.updateTask($,Y);if(G){let W={task:G,changes:J,tagService:this.tagService};await this.executeHook(q0.AFTER_UPDATE,W),this.publishEvent(v$.UPDATED,{task:G,changes:J,sessionId:""},""),o.info(`[TaskComponent] Task updated: ${$}`)}return G}async deleteTask($){let J={id:$};await this.executeHook(q0.BEFORE_DELETE,J);let Q=await this.store.deleteTask($),X={id:$,deleted:Q};if(await this.executeHook(q0.AFTER_DELETE,X),Q)this.publishEvent(v$.DELETED,{taskId:$,sessionId:""},""),o.info(`[TaskComponent] Task deleted: ${$}`);return Q}async listTasks($){return this.store.listTasks($)}async searchTasksByKeywords($,J){return this.store.searchTasksByKeywords($,J||{})}async getTaskTree($,J=-1){return this.store.getTaskTree($,J)}async getChildTasks($,J){return this.store.getChildTasks($,J)}async completeTask($,J,Q){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.`);if(X&&E6.includes(X.status))throw Error(`Cannot complete task: #${$} - ${X.title}. It is already in terminal status "${X.status}". Reopen it first via task_update(status="active") if acceptance should proceed.`);let q={status:"completed",progress:100,current_status:Q?`${a0}\uFF08${E2}\uFF1A${Q}\uFF09`:a0};if(Q){let G={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))G=W}catch{o.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}G.deliverable_storage_path=Q,q.context=JSON.stringify(G)}let Y=await this.updateTask($,q);if(Y)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:V1(Q)}),this.publishEvent(v$.COMPLETED,{task:Y,sessionId:J},J),o.info(`[TaskComponent] Task completed: ${$}, deliverable=${Q||"(none)"}`);return Y}async updateTaskContext($,J){return this.store.updateTask($,{context:J})}async preCompleteTask($,J,Q,X){let q=await this.store.getTask($);if(q&&q.type==="cycle")throw Error(`Cannot pre-complete cycle task: #${$} - ${q.title}. Cycle tasks are not meant to be completed or submitted for acceptance.`);let G={status:"to_validate",current_status:X?`${u0}\uFF1A${X}`:u0};if(Q){let z={};if(q?.context)try{let H=JSON.parse(q.context);if(H&&typeof H==="object"&&!Array.isArray(H))z=H}catch{o.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}z.deliverable_storage_path=Q,G.context=JSON.stringify(z)}let W=await this.updateTask($,G);if(W){let z=L9(),H={task:W,changes:G,terminalStatus:"to_validate",sessionId:z.sessionId??J,tagService:this.tagService};await this.executeHook(q0.AFTER_COMPLETE,H);let B=[],U=V1(Q);if(U)B.push(U);if(X)B.push(X);await this.createOperation({taskId:$,sessionId:J,milestoneType:"milestone",milestoneTitle:`${u0}\uFF08to_validate\uFF09\uFF1ATask #${$} submitted for acceptance`,milestoneDescription:B.join(" / ")||u0}),o.info(`[TaskComponent] Task submitted for acceptance (to_validate): ${$}, deliverable=${Q||"(none)"}`)}return W}async createOperation($){let J={options:{...$}};await this.executeHook(q0.OPERATION_BEFORE_CREATE,J);let Q=await this.store.createOperation(J.options),X=await this.store.getTask(Q.taskId),q={operation:Q};return await this.executeHook(q0.OPERATION_AFTER_CREATE,q,{task:X,operation:Q}),this.publishEvent(v$.OPERATION_ADDED,{operation:Q,taskId:Q.taskId},Q.sessionId),o.info(`[TaskComponent] Operation created: ${Q.id} for task ${Q.taskId}`),Q}async getOperation($){return this.store.getOperation($)}async updateOperation($,J){return this.store.updateOperation($,J)}async deleteOperation($){return this.store.deleteOperation($)}async listOperations($){return this.store.listOperations($)}async listOperationsFresh($){let J=this.store;if(typeof J.listOperationsFresh==="function")return await J.listOperationsFresh($);if(typeof J.invalidateOperationsCache==="function")J.invalidateOperationsCache($.taskId);return await this.store.listOperations($)}getTagService(){return this.tagService}registerHook($,J){T0.register($,J),this.plugins.set(this.makePluginKey($,J.name),J),o.debug(`[TaskComponent] Registered hook: ${J.name} at ${$}`)}registerHooks($){for(let{hookPoint:J,hook:Q}of $)this.registerHook(J,Q)}unregisterHook($,J){let Q=T0.unregister($,J);if(Q)this.plugins.delete(this.makePluginKey($,J)),o.info(`[TaskComponent] Unregistered hook: ${J} from ${$}`);return Q}listHooks(){return Array.from(this.plugins.values())}makePluginKey($,J){return`${$}::${J}`}countHooks($){return T0.count($)}}k([u("task.component.executeHook",{recordParams:!0})],K$.prototype,"executeHook",null);k([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],K$.prototype,"createTask",null);k([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],K$.prototype,"updateTask",null);k([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],K$.prototype,"completeTask",null);k([u("task.component.preCompleteTask",{recordParams:!0,recordResult:!0,log:!0})],K$.prototype,"preCompleteTask",null);k([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],K$.prototype,"createOperation",null);var t8=K.enum(["todo","active","to_validate","completed","paused","cancelled","archived"]),e8=K.enum(["low","medium","high"]),$5=K.enum(["normal","cycle","longterm"]),J5=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),gM=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});v0();v0();var kM="Deliverable: ";function D1($){if(!$)return;return`${kM}${$}`}var C9=1e6;class Q5{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=mM($);if(J!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(J);return(await this.scanAllTasks()).find((Q)=>Q.id===J)??null}return await this.port.getTask(String($))}toTask($){let{nativeId:J,...Q}=$;return Q}toOperation($){let{nativeId:J,...Q}=$;return Q}async scanAllTasks(){return(await this.port.listTasks({limit:C9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;if($.parent_task_id!==void 0&&$.parent_task_id!==null){let q=await this.resolve($.parent_task_id);if(!q)throw Error(`Parent task #${$.parent_task_id} not found.`);Q=q.id}let X=await this.port.createTask({title:$.title,description:$.description,priority:$.priority,type:$.type,goals_and_expected_deliverables:$.goals_and_expected_deliverables,...Q!==void 0?{parent_task_id:Q}:{},due_date:$.due_date,tags:$.tags,project_path:$.project_path,context:$.context,sessionId:J,...$.owner!==void 0&&$.owner!==null?{owner:$.owner}:{}});return await this.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask($){let J=await this.resolve($);return J?this.toTask(J):null}async getTaskWithOperations($){let J=await this.getTask($);if(!J)return null;let Q=await this.listOperations({taskId:J.id,limit:C9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((q)=>this.toTask(q));return X=this.applyFilters(X,$),{tasks:X.slice(Q,Q+J),total:X.length}}async updateTask($,J){let Q=await this.resolve($);if(!Q)return null;let X;if(J.parent_task_id!==void 0)if(J.parent_task_id===null)X=null;else{let Y=await this.resolve(J.parent_task_id);if(!Y)throw Error(`Parent task #${J.parent_task_id} not found.`);X=Y.id}let q=await this.port.updateTask(Q.nativeId,{title:J.title,description:J.description,status:J.status,priority:J.priority,type:J.type,progress:J.progress,current_status:J.current_status,goals_and_expected_deliverables:J.goals_and_expected_deliverables,due_date:J.due_date,tags:J.tags,project_path:J.project_path,context:J.context,...X!==void 0?{parent_task_id:X}:{},...J.owner!==void 0?{owner:J.owner}:{}});return q?this.toTask(q):null}async deleteTask($){let J=await this.resolve($);if(!J)return!1;return await this.port.deleteTask(J.nativeId)}async completeTask($,J,Q){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 q={status:"completed",progress:100,current_status:Q?`${a0}\uFF08${E2}\uFF1A${Q}\uFF09`:a0};if(Q)q.context=F1(X.context,Q);let Y=await this.port.updateTask(X.nativeId,q);if(!Y)return null;let G=D1(Q);await this.createOperation({taskId:Y.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${Y.title}`,milestoneDescription:G??"Task completed",...Q?{mdPath:Q}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??Y)}async preCompleteTask($,J,Q,X){let q=await this.resolve($);if(!q)return null;if(q.type==="cycle")throw Error(`Cannot pre-complete cycle task: #${q.id} - ${q.title}. Cycle tasks are not meant to be completed or submitted for acceptance.`);let G={status:"to_validate",current_status:X?`${u0}\uFF1A${X}`:u0};if(Q)G.context=F1(q.context,Q);let W=await this.port.updateTask(q.nativeId,G);if(!W)return null;let z=[],H=D1(Q);if(H)z.push(H);if(X)z.push(X);await this.createOperation({taskId:W.id,sessionId:J??this.defaultSessionId,milestoneType:"milestone",milestoneTitle:`${u0}\uFF08to_validate\uFF09\uFF1ATask #${W.id} submitted for acceptance`,milestoneDescription:z.join(" / ")||u0,...Q?{mdPath:Q}:{}});let B=await this.resolve(q.nativeId);return this.toTask(B??W)}async getTaskTree($,J=-1){let Q=await this.resolve($);if(!Q)return[];if(J===0)return[];let X=(await this.scanAllTasks()).map((H)=>this.toTask(H)),q=new Map;for(let H of X){if(H.parent_task_id===void 0)continue;let B=q.get(H.parent_task_id)??[];B.push(H),q.set(H.parent_task_id,B)}let Y=[],G=new Set([Q.id]),W=[Q.id],z=0;while(W.length>0){if(J!==-1&&z>=J)break;let H=[];for(let B of W)for(let U of q.get(B)??[]){if(G.has(U.id))continue;G.add(U.id),Y.push(U),H.push(U.id)}W=H,z++}return Y}async searchTasksByKeywords($,J={}){let Q=J.limit??20,X=J.offset??0,q=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(q=this.applyFilters(q,J),J.excludeTaskId!==void 0)q=q.filter((W)=>W.id!==J.excludeTaskId);let Y=$.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),G=Y.length===0?q:q.filter((W)=>{let z=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return Y.every((H)=>z.includes(H))});return{tasks:G.slice(X,X+Q),total:G.length}}async createOperation($){let J=await this.resolve($.taskId);if(!J)throw Error(`Task not found: ${$.taskId}`);let Q=$.milestoneType??$.actionType??"progress",X=$.milestoneTitle??$.actionTitle??"",q=$.milestoneDescription??$.actionDescription??"",Y=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:q,processDescription:$.processDescription??"",...$.mdPath?{mdPath:$.mdPath}:{}});return this.toOperation(Y)}async listOperations($={}){let J=$.limit??100,Q=$.offset??0,X=$.milestoneType??$.actionType;if($.taskId===void 0)return[];let q=await this.resolve($.taskId);if(!q)return[];let G=(await this.port.listOperations({taskNativeId:q.nativeId,limit:X?C9:J,offset:X?0:Q})).operations.map((W)=>this.toOperation(W));if(X)G=G.filter((W)=>W.milestoneType===X),G=G.slice(Q,Q+J);return G}async getOperation($){if(typeof this.port.getOperationByNum==="function"){let Q=await this.port.getOperationByNum($);return Q?this.toOperation(Q):null}let J=await this.scanAllTasks();for(let Q of J){let q=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:C9})).operations.find((Y)=>Y.id===$);if(q)return this.toOperation(q)}return null}async updateOperation($,J){let Q=await this.getOperation($);if(!Q)return null;if(typeof this.port.updateOperationByNum!=="function")return Q;let X=await this.port.updateOperationByNum($,{sessionId:J.sessionId??Q.sessionId,milestoneType:J.milestoneType??J.actionType??Q.milestoneType,milestoneTitle:J.milestoneTitle??J.actionTitle??Q.milestoneTitle,milestoneDescription:J.milestoneDescription??J.actionDescription??Q.milestoneDescription,processDescription:J.processDescription??Q.processDescription,...J.mdPath!==void 0?{mdPath:J.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation($){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum($)}applyFilters($,J){let Q=$;if(J.include_archived!==!0&&J.status!=="archived")Q=Q.filter((q)=>q.status!=="archived");if(J.status!==void 0)Q=Q.filter((q)=>q.status===J.status);if(J.priority!==void 0)Q=Q.filter((q)=>q.priority===J.priority);if(J.type!==void 0)Q=Q.filter((q)=>q.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((q)=>q.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let q=uM(Q,J.depth);Q=Q.filter((Y)=>q.has(Y.id))}return Q}}function mM($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function uM($,J){if(J<0)return new Set($.map((G)=>G.id));let Q=new Set($.map((G)=>G.id)),X=new Map;for(let G of $){let W=G.parent_task_id;if(W===void 0||!Q.has(W))continue;let z=X.get(W)??[];z.push(G),X.set(W,z)}let q=new Set,Y=$.filter((G)=>G.parent_task_id===void 0||!Q.has(G.parent_task_id));for(let G of Y)q.add(G.id);for(let G=1;G<=J;G++){let W=[];for(let z of Y)for(let H of X.get(z.id)??[]){if(q.has(H.id))continue;q.add(H.id),W.push(H)}if(W.length===0)break;Y=W}return q}function F1($,J){let Q={};if(typeof $==="string"&&$.trim().length>0)try{let X=JSON.parse($);if(X&&typeof X==="object"&&!Array.isArray(X))Q=X}catch{}return Q.deliverable_storage_path=J,JSON.stringify(Q)}v0();i();var vA=d("task-remote-port");var lM=1e6;function cM($){let J={};if($.type!==void 0)J.type=$.type;if($.progress!==void 0)J.progress=$.progress;if($.current_status!==void 0)J.current_status=$.current_status;if($.goals_and_expected_deliverables!==void 0)J.goals_and_expected_deliverables=$.goals_and_expected_deliverables;if($.project_path!==void 0)J.project_path=$.project_path;if($.context!==void 0)J.context=$.context;if($.due_date!==void 0)J.due_date=$.due_date;return J}function D6($,J,Q){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:J.toRoyStatus($.status),priority:J.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??"",...Q!==void 0?{parent_task_id:Q}:{},createdAt:$.created_at,updatedAt:$.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:J.toRoyTags($.tags),project_path:X.project_path??"unknown",context:X.context??"{}",...$.owner!==void 0?{owner:$.owner}:{}}}function F6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),q=String(J.milestoneDescription??J.actionDescription??""),Y=J.taskId??$.task_id,G=typeof Y==="number"?Y:typeof Y==="string"&&/^\d+$/.test(Y)?Number(Y):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:G,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:q,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:q}}function M1($,J,Q={}){let X=Q.operationType??"roy.milestone",q=Q.agent??"roy",Y=Q.scanLimit??lM;async function G(){let H=await $.listTasks({limit:Y});return new Map(H.tasks.filter((B)=>typeof B.num==="number").map((B)=>[B.id,B.num]))}async function W(H){if(typeof $.getTaskByNum==="function")return await $.getTaskByNum(H);return(await $.listTasks({limit:Y})).tasks.find((U)=>U.num===H)??null}async function z(H){let U=[...(await G()).entries()].find(([,V])=>V===H);if(!U)throw Error(`parent task not found: ${H}`);return U[0]}return{async createTask(H){let B=H.parent_task_id!==void 0?await z(H.parent_task_id):null,U={type:H.type??"normal",progress:H.progress??0,current_status:H.current_status??"",goals_and_expected_deliverables:H.goals_and_expected_deliverables??"",project_path:H.project_path,context:H.context,...H.due_date?{due_date:H.due_date}:{}},V=await $.createTask({title:H.title,description:H.description,priority:J.toStorePriority(H.priority),owner:H.owner??q,tags:J.toStoreTags(H.tags),parent_id:B,session_id:H.sessionId??"unknown",roy:U});return D6(V,J,H.parent_task_id)},async getTask(H){let B=await $.getTask(H);if(!B)return null;let U=await G();return D6(B,J,B.parent_id?U.get(B.parent_id):void 0)},async getTaskByNum(H){let B=await W(H);if(!B)return null;let U=await G();return D6(B,J,B.parent_id?U.get(B.parent_id):void 0)},async listTasks(H){let B=await $.listTasks({limit:H?.limit??20,offset:H?.offset??0}),U=await G();return{tasks:B.tasks.map((V)=>D6(V,J,V.parent_id?U.get(V.parent_id):void 0)),total:B.total}},async updateTask(H,B){let U=cM(B),V=await $.updateTask(H,{...B.title!==void 0?{title:B.title}:{},...B.description!==void 0?{description:B.description}:{},...B.status!==void 0?{status:J.toStoreStatus(B.status)}:{},...B.priority!==void 0?{priority:J.toStorePriority(B.priority)}:{},...B.tags!==void 0?{tags:J.toStoreTags(B.tags)}:{},...B.owner!==void 0?{owner:B.owner}:{},...Object.keys(U).length>0?{roy:U}:{}});if(!V)return null;let O;if(B.parent_task_id!==void 0){let D=B.parent_task_id===null?null:await z(B.parent_task_id);if(typeof $.setParentId==="function")await $.setParentId(H,D);O=B.parent_task_id===null?void 0:B.parent_task_id}let F=await $.getTask(H)??V;if(O===void 0&&F.parent_id)O=(await G()).get(F.parent_id);return D6(F,J,O)},async deleteTask(H){return await $.deleteTask(H)},async createOperation(H){let B=await $.appendOperation({task_id:H.taskNativeId??String(H.taskId),type:X,data:{taskId:H.taskId,sessionId:H.sessionId,milestoneType:H.milestoneType,milestoneTitle:H.milestoneTitle,milestoneDescription:H.milestoneDescription,processDescription:H.processDescription,...H.mdPath?{mdPath:H.mdPath}:{}}});return F6(B)},async listOperations(H){let B=await $.listOperations({...H?.taskNativeId?{task_id:H.taskNativeId}:{},type:X,limit:H?.limit??Y,offset:H?.offset??0});return{operations:B.operations.map(F6),total:B.total}},async getOperationByNum(H){if(typeof $.getOperationByNum!=="function")return null;let B=await $.getOperationByNum(H);return B?F6(B):null},async updateOperationByNum(H,B){if(typeof $.updateOperation!=="function")return null;if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(H);if(!U)return null;let V=F6(U),O=await $.updateOperation(H,{data:{taskId:V.taskId,sessionId:B.sessionId??V.sessionId,milestoneType:B.milestoneType??V.milestoneType,milestoneTitle:B.milestoneTitle??V.milestoneTitle,milestoneDescription:B.milestoneDescription??V.milestoneDescription,processDescription:B.processDescription??V.processDescription,...B.mdPath??V.mdPath?{mdPath:B.mdPath??V.mdPath}:{}}});return O?F6(O):null},async deleteOperationByNum(H){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(H)}}}var dM="roy.milestone",pM={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",to_validate:"review",archived:"archived"},iM={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"to_validate",archived:"archived"};function O1($){return pM[$]??"pending"}function K1($){return iM[$]??"todo"}function j1($){if($==="high")return 1;if($==="low")return 5;return 3}function L1($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function N1($){if(!$||$.length===0)return;return $.join(",")}function A1($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var nM={toRoyStatus:($)=>K1($),toStoreStatus:($)=>O1($),toRoyPriority:($)=>L1($),toStorePriority:($)=>j1($),toRoyTags:($)=>A1($),toStoreTags:($)=>N1($)};function _1($,J={}){return new Q5(M1($,nM,{operationType:dM,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var kA=t8.options,mA=e8.options,uA=$5.options,lA=J5.options;var Z1=Symbol("Let zodToJsonSchema decide on which parser to use");var R1={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"},w1=($)=>typeof $==="string"?{...R1,name:$}:{...R1,...$};var P1=($)=>{let J=w1($),Q=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([X,q])=>[q._def,{def:q._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function X5($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function c($,J,Q,X,q){$[J]=Q,X5($,J,X,q)}var f9=($,J)=>{let Q=0;for(;Q<$.length&&Q<J.length;Q++)if($[Q]!==J[Q])break;return[($.length-Q).toString(),...J.slice(Q)].join("/")};function e($){if($.target!=="openAi")return{};let J=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?f9(J,$.currentPath):J.join("/")}}function b1($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==_.ZodAny)Q.items=x($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)c(Q,"minItems",$.minLength.value,$.minLength.message,J);if($.maxLength)c(Q,"maxItems",$.maxLength.value,$.maxLength.message,J);if($.exactLength)c(Q,"minItems",$.exactLength.value,$.exactLength.message,J),c(Q,"maxItems",$.exactLength.value,$.exactLength.message,J);return Q}function E1($,J){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"min":if(J.target==="jsonSchema7")if(X.inclusive)c(Q,"minimum",X.value,X.message,J);else c(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;c(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)c(Q,"maximum",X.value,X.message,J);else c(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;c(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":c(Q,"multipleOf",X.value,X.message,J);break}return Q}function S1(){return{type:"boolean"}}function I9($,J){return x($.type._def,J)}var C1=($,J)=>{return x($.innerType._def,J)};function q5($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((q,Y)=>q5($,J,q))};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 aM($,J)}}var aM=($,J)=>{let Q={type:"integer",format:"unix-time"};if(J.target==="openApi3")return Q;for(let X of $.checks)switch(X.kind){case"min":c(Q,"minimum",X.value,X.message,J);break;case"max":c(Q,"maximum",X.value,X.message,J);break}return Q};function f1($,J){return{...x($.innerType._def,J),default:$.defaultValue()}}function I1($,J){return J.effectStrategy==="input"?x($.schema._def,J):e(J)}function T1($){return{type:"string",enum:Array.from($.values)}}var sM=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function v1($,J){let Q=[x($.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),x($.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((Y)=>!!Y),X=J.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,q=[];return Q.forEach((Y)=>{if(sM(Y)){if(q.push(...Y.allOf),Y.unevaluatedProperties===void 0)X=void 0}else{let G=Y;if("additionalProperties"in Y&&Y.additionalProperties===!1){let{additionalProperties:W,...z}=Y;G=z}else X=void 0;q.push(G)}}),q.length?{allOf:q,...X}:void 0}function x1($,J){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(J.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}var Y5=void 0,x0={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(Y5===void 0)Y5=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Y5},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 T9($,J){let Q={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":c(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J);break;case"max":c(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"email":switch(J.emailStrategy){case"format:email":y0(Q,"email",X.message,J);break;case"format:idn-email":y0(Q,"idn-email",X.message,J);break;case"pattern:zod":V0(Q,x0.email,X.message,J);break}break;case"url":y0(Q,"uri",X.message,J);break;case"uuid":y0(Q,"uuid",X.message,J);break;case"regex":V0(Q,X.regex,X.message,J);break;case"cuid":V0(Q,x0.cuid,X.message,J);break;case"cuid2":V0(Q,x0.cuid2,X.message,J);break;case"startsWith":V0(Q,RegExp(`^${G5(X.value,J)}`),X.message,J);break;case"endsWith":V0(Q,RegExp(`${G5(X.value,J)}$`),X.message,J);break;case"datetime":y0(Q,"date-time",X.message,J);break;case"date":y0(Q,"date",X.message,J);break;case"time":y0(Q,"time",X.message,J);break;case"duration":y0(Q,"duration",X.message,J);break;case"length":c(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J),c(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"includes":{V0(Q,RegExp(G5(X.value,J)),X.message,J);break}case"ip":{if(X.version!=="v6")y0(Q,"ipv4",X.message,J);if(X.version!=="v4")y0(Q,"ipv6",X.message,J);break}case"base64url":V0(Q,x0.base64url,X.message,J);break;case"jwt":V0(Q,x0.jwt,X.message,J);break;case"cidr":{if(X.version!=="v6")V0(Q,x0.ipv4Cidr,X.message,J);if(X.version!=="v4")V0(Q,x0.ipv6Cidr,X.message,J);break}case"emoji":V0(Q,x0.emoji(),X.message,J);break;case"ulid":{V0(Q,x0.ulid,X.message,J);break}case"base64":{switch(J.base64Strategy){case"format:binary":{y0(Q,"binary",X.message,J);break}case"contentEncoding:base64":{c(Q,"contentEncoding","base64",X.message,J);break}case"pattern:zod":{V0(Q,x0.base64,X.message,J);break}}break}case"nanoid":V0(Q,x0.nanoid,X.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:((q)=>{})(X)}return Q}function G5($,J){return J.patternStrategy==="escape"?tM($):$}var oM=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function tM($){let J="";for(let Q=0;Q<$.length;Q++){if(!oM.has($[Q]))J+="\\";J+=$[Q]}return J}function y0($,J,Q,X){if($.format||$.anyOf?.some((q)=>q.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:J,...Q&&X.errorMessages&&{errorMessage:{format:Q}}})}else c($,"format",J,Q,X)}function V0($,J,Q,X){if($.pattern||$.allOf?.some((q)=>q.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:y1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else c($,"pattern",y1(J,X),Q,X)}function y1($,J){if(!J.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},X=Q.i?$.source.toLowerCase():$.source,q="",Y=!1,G=!1,W=!1;for(let z=0;z<X.length;z++){if(Y){q+=X[z],Y=!1;continue}if(Q.i){if(G){if(X[z].match(/[a-z]/)){if(W)q+=X[z],q+=`${X[z-2]}-${X[z]}`.toUpperCase(),W=!1;else if(X[z+1]==="-"&&X[z+2]?.match(/[a-z]/))q+=X[z],W=!0;else q+=`${X[z]}${X[z].toUpperCase()}`;continue}}else if(X[z].match(/[a-z]/)){q+=`[${X[z]}${X[z].toUpperCase()}]`;continue}}if(Q.m){if(X[z]==="^"){q+=`(^|(?<=[\r
3074
+ ]))`;continue}else if(X[z]==="$"){q+=`($|(?=[\r
3075
+ ]))`;continue}}if(Q.s&&X[z]==="."){q+=G?`${X[z]}\r
3071
3076
  `:`[${X[z]}\r
3072
- ]`;continue}if(Y+=X[z],X[z]==="\\")G=!0;else if(q&&X[z]==="]")q=!1;else if(!q&&X[z]==="[")q=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return Y}function C9($,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&$.keyType?._def.typeName===_.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,Y)=>({...X,[Y]:v($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",Y]})??t(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:v($.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return Q;if($.keyType?._def.typeName===_.ZodString&&$.keyType._def.checks?.length){let{type:X,...Y}=S9($.keyType._def,J);return{...Q,propertyNames:Y}}else if($.keyType?._def.typeName===_.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===_.ZodBranded&&$.keyType._def.type._def.typeName===_.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...Y}=E9($.keyType._def,J);return{...Q,propertyNames:Y}}return Q}function S1($,J){if(J.mapStrategy==="record")return C9($,J);let Q=v($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||t(J),X=v($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||t(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,X],minItems:2,maxItems:2}}}function C1($){let J=$.values,X=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),Y=Array.from(new Set(X.map((G)=>typeof G)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function f1($){return $.target==="openAi"?void 0:{not:t({...$,currentPath:[...$.currentPath,"not"]})}}function I1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var B6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function v1($,J){if(J.target==="openApi3")return T1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in B6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((Y,G)=>{let q=B6[G._def.typeName];return q&&!Y.includes(q)?[...Y,q]:Y},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((Y,G)=>{let q=typeof G._def.value;switch(q){case"string":case"number":case"boolean":return[...Y,q];case"bigint":return[...Y,"integer"];case"object":if(G._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===Q.length){let Y=X.filter((G,q,W)=>W.indexOf(G)===q);return{type:Y.length>1?Y:Y[0],enum:Q.reduce((G,q)=>{return G.includes(q._def.value)?G:[...G,q._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,Y)=>[...X,...Y._def.values.filter((G)=>!X.includes(G))],[])};return T1($,J)}var T1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,Y)=>v(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function x1($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:B6[$.innerType._def.typeName],nullable:!0};return{type:[B6[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let X=v($.innerType._def,{...J,currentPath:[...J.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let Q=v($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function h1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",a8(Q,"type",X.message,J);break;case"min":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"minimum",X.value,X.message,J);else p(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;p(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"maximum",X.value,X.message,J);else p(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;p(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":p(Q,"multipleOf",X.value,X.message,J);break}return Q}function y1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},Y=[],G=$.shape();for(let W in G){let z=G[W];if(z===void 0||z._def===void 0)continue;let H=xM(z);if(H&&Q){if(z._def.typeName==="ZodOptional")z=z._def.innerType;if(!z.isNullable())z=z.nullable();H=!1}let B=v(z._def,{...J,currentPath:[...J.currentPath,"properties",W],propertyPath:[...J.currentPath,"properties",W]});if(B===void 0)continue;if(X.properties[W]=B,!H)Y.push(W)}if(Y.length)X.required=Y;let q=vM($,J);if(q!==void 0)X.additionalProperties=q;return X}function vM($,J){if($.catchall._def.typeName!=="ZodNever")return v($.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function xM($){try{return $.isOptional()}catch{return!0}}var g1=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return v($.innerType._def,J);let Q=v($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:t(J)},Q]}:t(J)};var k1=($,J)=>{if(J.pipeStrategy==="input")return v($.in._def,J);else if(J.pipeStrategy==="output")return v($.out._def,J);let Q=v($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),X=v($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,X].filter((Y)=>Y!==void 0)}};function m1($,J){return v($.type._def,J)}function u1($,J){let X={type:"array",uniqueItems:!0,items:v($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)p(X,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)p(X,"maxItems",$.maxSize.value,$.maxSize.message,J);return X}function l1($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,X)=>v(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[]),additionalItems:v($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,X)=>v(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[])}}function c1($){return{not:t($)}}function p1($){return t($)}var d1=($,J)=>{return v($.innerType._def,J)};var i1=($,J,Q)=>{switch(J){case _.ZodString:return S9($,Q);case _.ZodNumber:return h1($,Q);case _.ZodObject:return y1($,Q);case _.ZodBigInt:return j1($,Q);case _.ZodBoolean:return N1();case _.ZodDate:return s8($,Q);case _.ZodUndefined:return c1(Q);case _.ZodNull:return I1(Q);case _.ZodArray:return L1($,Q);case _.ZodUnion:case _.ZodDiscriminatedUnion:return v1($,Q);case _.ZodIntersection:return P1($,Q);case _.ZodTuple:return l1($,Q);case _.ZodRecord:return C9($,Q);case _.ZodLiteral:return b1($,Q);case _.ZodEnum:return w1($);case _.ZodNativeEnum:return C1($);case _.ZodNullable:return x1($,Q);case _.ZodOptional:return g1($,Q);case _.ZodMap:return S1($,Q);case _.ZodSet:return u1($,Q);case _.ZodLazy:return()=>$.getter()._def;case _.ZodPromise:return m1($,Q);case _.ZodNaN:case _.ZodNever:return f1(Q);case _.ZodEffects:return Z1($,Q);case _.ZodAny:return t(Q);case _.ZodUnknown:return p1(Q);case _.ZodDefault:return A1($,Q);case _.ZodBranded:return E9($,Q);case _.ZodReadonly:return d1($,Q);case _.ZodCatch:return _1($,Q);case _.ZodPipeline:return k1($,Q);case _.ZodFunction:case _.ZodVoid:case _.ZodSymbol:return;default:return((X)=>{return})(J)}};function v($,J,Q=!1){let X=J.seen.get($);if(J.override){let W=J.override?.($,J,X,Q);if(W!==O1)return W}if(X&&!Q){let W=hM(X,J);if(W!==void 0)return W}let Y={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,Y);let G=i1($,$.typeName,J),q=typeof G==="function"?v(G(),J):G;if(q)yM($,J,q);if(J.postProcess){let W=J.postProcess(q,$,J);return Y.jsonSchema=q,W}return Y.jsonSchema=q,q}var hM=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:b9(J.currentPath,$.path)};case"none":case"seen":{if($.path.length<J.currentPath.length&&$.path.every((Q,X)=>J.currentPath[X]===Q))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),t(J);return J.$refStrategy==="seen"?t(J):void 0}}},yM=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var e8=($,J)=>{let Q=R1(J),X=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((z,[H,B])=>({...z,[H]:v(B._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,H]},!0)??t(Q)}),{}):void 0,Y=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=v($._def,Y===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,Y]},!1)??t(Q),q=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(q!==void 0)G.title=q;if(Q.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[Q.openAiAnyTypeName])X[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let W=Y===void 0?X?{...G,[Q.definitionPath]:X}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,Y].join("/"),[Q.definitionPath]:{...X,[Y]:G}};if(Q.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.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 n1=[s2,X6,o2,t2,e2,$6,J6,Y6,G6];function gM($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=e8(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...G}=X;return G}catch{return{}}}function r1($,J={}){let Q=F1($,J),X=Q6;return(X?[...n1,X]:n1).map((G)=>{let q=G(Q);return{name:q.name,description:q.description,input:gM(q.parameters),options:{codemode:!1},execute:async(W,z)=>{let H={session_id:z?.sessionID??J.sessionId??"unknown",workdir:z?.directory};try{let B=await q.execute(W??{},H),U=typeof B.output==="string"?B.output:JSON.stringify(B.output??"");return{content:B.success?U:`ERROR: ${B.error??"unknown error"}`,metadata:{tool:q.name,ok:B.success}}}catch(B){return{content:`ERROR: ${B instanceof Error?B.message:String(B)}`,metadata:{tool:q.name,ok:!1}}}}}})}function a1($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function s1($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let Y=$??{},G=J.agent??U2;if(typeof Y.agent?.transform==="function")try{let W=await Y.agent.transform((z)=>{y9(z)});a1(W,X.disposers),X.agentId=G}catch(W){X.errors.push(`roy agent registration failed: ${$7(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let q=[];try{q=r1(J.store,{agent:G,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${$7(W)}`),X}if(typeof Y.tool?.transform==="function")try{let W=await Y.tool.transform((z)=>{for(let H of q)z.add(H)});a1(W,X.disposers),X.toolNames=q.map((z)=>z.name)}catch(W){X.errors.push(`roy tool registration failed: ${$7(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function $7($){return $ instanceof Error?$.message:String($)}import{join as X7}from"path";import{homedir as iM}from"os";import{mkdirSync as nM}from"fs";import{Database as kM}from"bun:sqlite";import{createHash as mM,randomUUID as uM}from"crypto";var lM=`
3077
+ ]`;continue}if(q+=X[z],X[z]==="\\")Y=!0;else if(G&&X[z]==="]")G=!1;else if(!G&&X[z]==="[")G=!0}try{new RegExp(q)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return q}function v9($,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&$.keyType?._def.typeName===_.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,q)=>({...X,[q]:x($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",q]})??e(J)}),{}),additionalProperties:J.rejectedAdditionalProperties};let Q={type:"object",additionalProperties:x($.valueType._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]})??J.allowedAdditionalProperties};if(J.target==="openApi3")return Q;if($.keyType?._def.typeName===_.ZodString&&$.keyType._def.checks?.length){let{type:X,...q}=T9($.keyType._def,J);return{...Q,propertyNames:q}}else if($.keyType?._def.typeName===_.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===_.ZodBranded&&$.keyType._def.type._def.typeName===_.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...q}=I9($.keyType._def,J);return{...Q,propertyNames:q}}return Q}function h1($,J){if(J.mapStrategy==="record")return v9($,J);let Q=x($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||e(J),X=x($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||e(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,X],minItems:2,maxItems:2}}}function g1($){let J=$.values,X=Object.keys($.values).filter((Y)=>{return typeof J[J[Y]]!=="number"}).map((Y)=>J[Y]),q=Array.from(new Set(X.map((Y)=>typeof Y)));return{type:q.length===1?q[0]==="string"?"string":"number":["string","number"],enum:X}}function k1($){return $.target==="openAi"?void 0:{not:e({...$,currentPath:[...$.currentPath,"not"]})}}function m1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var M6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function l1($,J){if(J.target==="openApi3")return u1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in M6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((q,Y)=>{let G=M6[Y._def.typeName];return G&&!q.includes(G)?[...q,G]:q},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((q,Y)=>{let G=typeof Y._def.value;switch(G){case"string":case"number":case"boolean":return[...q,G];case"bigint":return[...q,"integer"];case"object":if(Y._def.value===null)return[...q,"null"];case"symbol":case"undefined":case"function":default:return q}},[]);if(X.length===Q.length){let q=X.filter((Y,G,W)=>W.indexOf(Y)===G);return{type:q.length>1?q:q[0],enum:Q.reduce((Y,G)=>{return Y.includes(G._def.value)?Y:[...Y,G._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,q)=>[...X,...q._def.values.filter((Y)=>!X.includes(Y))],[])};return u1($,J)}var u1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,q)=>x(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${q}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function c1($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:M6[$.innerType._def.typeName],nullable:!0};return{type:[M6[$.innerType._def.typeName],"null"]}}if(J.target==="openApi3"){let X=x($.innerType._def,{...J,currentPath:[...J.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let Q=x($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","0"]});return Q&&{anyOf:[Q,{type:"null"}]}}function d1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",X5(Q,"type",X.message,J);break;case"min":if(J.target==="jsonSchema7")if(X.inclusive)c(Q,"minimum",X.value,X.message,J);else c(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;c(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)c(Q,"maximum",X.value,X.message,J);else c(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;c(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":c(Q,"multipleOf",X.value,X.message,J);break}return Q}function p1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},q=[],Y=$.shape();for(let W in Y){let z=Y[W];if(z===void 0||z._def===void 0)continue;let H=$O(z);if(H&&Q){if(z._def.typeName==="ZodOptional")z=z._def.innerType;if(!z.isNullable())z=z.nullable();H=!1}let B=x(z._def,{...J,currentPath:[...J.currentPath,"properties",W],propertyPath:[...J.currentPath,"properties",W]});if(B===void 0)continue;if(X.properties[W]=B,!H)q.push(W)}if(q.length)X.required=q;let G=eM($,J);if(G!==void 0)X.additionalProperties=G;return X}function eM($,J){if($.catchall._def.typeName!=="ZodNever")return x($.catchall._def,{...J,currentPath:[...J.currentPath,"additionalProperties"]});switch($.unknownKeys){case"passthrough":return J.allowedAdditionalProperties;case"strict":return J.rejectedAdditionalProperties;case"strip":return J.removeAdditionalStrategy==="strict"?J.allowedAdditionalProperties:J.rejectedAdditionalProperties}}function $O($){try{return $.isOptional()}catch{return!0}}var i1=($,J)=>{if(J.currentPath.toString()===J.propertyPath?.toString())return x($.innerType._def,J);let Q=x($.innerType._def,{...J,currentPath:[...J.currentPath,"anyOf","1"]});return Q?{anyOf:[{not:e(J)},Q]}:e(J)};var n1=($,J)=>{if(J.pipeStrategy==="input")return x($.in._def,J);else if(J.pipeStrategy==="output")return x($.out._def,J);let Q=x($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),X=x($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,X].filter((q)=>q!==void 0)}};function r1($,J){return x($.type._def,J)}function a1($,J){let X={type:"array",uniqueItems:!0,items:x($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)c(X,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)c(X,"maxItems",$.maxSize.value,$.maxSize.message,J);return X}function s1($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,X)=>x(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[]),additionalItems:x($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,X)=>x(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[])}}function o1($){return{not:e($)}}function t1($){return e($)}var e1=($,J)=>{return x($.innerType._def,J)};var $Q=($,J,Q)=>{switch(J){case _.ZodString:return T9($,Q);case _.ZodNumber:return d1($,Q);case _.ZodObject:return p1($,Q);case _.ZodBigInt:return E1($,Q);case _.ZodBoolean:return S1();case _.ZodDate:return q5($,Q);case _.ZodUndefined:return o1(Q);case _.ZodNull:return m1(Q);case _.ZodArray:return b1($,Q);case _.ZodUnion:case _.ZodDiscriminatedUnion:return l1($,Q);case _.ZodIntersection:return v1($,Q);case _.ZodTuple:return s1($,Q);case _.ZodRecord:return v9($,Q);case _.ZodLiteral:return x1($,Q);case _.ZodEnum:return T1($);case _.ZodNativeEnum:return g1($);case _.ZodNullable:return c1($,Q);case _.ZodOptional:return i1($,Q);case _.ZodMap:return h1($,Q);case _.ZodSet:return a1($,Q);case _.ZodLazy:return()=>$.getter()._def;case _.ZodPromise:return r1($,Q);case _.ZodNaN:case _.ZodNever:return k1(Q);case _.ZodEffects:return I1($,Q);case _.ZodAny:return e(Q);case _.ZodUnknown:return t1(Q);case _.ZodDefault:return f1($,Q);case _.ZodBranded:return I9($,Q);case _.ZodReadonly:return e1($,Q);case _.ZodCatch:return C1($,Q);case _.ZodPipeline:return n1($,Q);case _.ZodFunction:case _.ZodVoid:case _.ZodSymbol:return;default:return((X)=>{return})(J)}};function x($,J,Q=!1){let X=J.seen.get($);if(J.override){let W=J.override?.($,J,X,Q);if(W!==Z1)return W}if(X&&!Q){let W=JO(X,J);if(W!==void 0)return W}let q={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,q);let Y=$Q($,$.typeName,J),G=typeof Y==="function"?x(Y(),J):Y;if(G)QO($,J,G);if(J.postProcess){let W=J.postProcess(G,$,J);return q.jsonSchema=G,W}return q.jsonSchema=G,G}var JO=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:f9(J.currentPath,$.path)};case"none":case"seen":{if($.path.length<J.currentPath.length&&$.path.every((Q,X)=>J.currentPath[X]===Q))return console.warn(`Recursive reference detected at ${J.currentPath.join("/")}! Defaulting to any`),e(J);return J.$refStrategy==="seen"?e(J):void 0}}},QO=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var W5=($,J)=>{let Q=P1(J),X=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((z,[H,B])=>({...z,[H]:x(B._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,H]},!0)??e(Q)}),{}):void 0,q=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,Y=x($._def,q===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,q]},!1)??e(Q),G=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(G!==void 0)Y.title=G;if(Q.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[Q.openAiAnyTypeName])X[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let W=q===void 0?X?{...Y,[Q.definitionPath]:X}:Y:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,q].join("/"),[Q.definitionPath]:{...X,[q]:Y}};if(Q.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.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 JQ=[Q6,H6,X6,q6,Y6,G6,W6,B6,U6];function XO($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=W5(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:q,...Y}=X;return Y}catch{return{}}}function QQ($,J={}){let Q=_1($,J),X=z6;return(X?[...JQ,X]:JQ).map((Y)=>{let G=Y(Q);return{name:G.name,description:G.description,input:XO(G.parameters),options:{codemode:!1},execute:async(W,z)=>{let H={session_id:z?.sessionID??J.sessionId??"unknown",workdir:z?.directory};try{let B=await G.execute(W??{},H),U=typeof B.output==="string"?B.output:JSON.stringify(B.output??"");return{content:B.success?U:`ERROR: ${B.error??"unknown error"}`,metadata:{tool:G.name,ok:B.success}}}catch(B){return{content:`ERROR: ${B instanceof Error?B.message:String(B)}`,metadata:{tool:G.name,ok:!1}}}}}})}function XQ($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function qQ($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let q=$??{},Y=J.agent??K2;if(typeof q.agent?.transform==="function")try{let W=await q.agent.transform((z)=>{u9(z)});XQ(W,X.disposers),X.agentId=Y}catch(W){X.errors.push(`roy agent registration failed: ${z5(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let G=[];try{G=QQ(J.store,{agent:Y,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${z5(W)}`),X}if(typeof q.tool?.transform==="function")try{let W=await q.tool.transform((z)=>{for(let H of G)z.add(H)});XQ(W,X.disposers),X.toolNames=G.map((z)=>z.name)}catch(W){X.errors.push(`roy tool registration failed: ${z5(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function z5($){return $ instanceof Error?$.message:String($)}import{join as U5}from"path";import{homedir as UO}from"os";import{mkdirSync as VO}from"fs";import{Database as qO}from"bun:sqlite";import{createHash as YO,randomUUID as GO}from"crypto";var WO=`
3073
3078
  CREATE TABLE IF NOT EXISTS tasks (
3074
3079
  id TEXT PRIMARY KEY,
3075
3080
  title TEXT NOT NULL,
@@ -3124,13 +3129,13 @@ CREATE TABLE IF NOT EXISTS bounties (
3124
3129
  done_at TEXT
3125
3130
  );
3126
3131
  CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
3127
- `;function C$(){return new Date().toISOString()}function J7(){return uM()}function cM($){return mM("sha256").update($).digest("hex")}function o1($){let J=JSON.stringify({id:$.id,type:$.type,data:$.data,prev_hash:$.prev_hash,created_at:$.created_at});return cM(J)}function Q7($){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:pM($.roy),created_at:$.created_at,updated_at:$.updated_at}}function pM($){if($===null||$===void 0||$==="")return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}function dM($){try{let J=$.query("PRAGMA table_info(tasks)").all();if(!new Set(J.map((X)=>X.name)).has("roy"))$.exec("ALTER TABLE tasks ADD COLUMN roy TEXT")}catch{}}function t1($){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 f9($){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 I9{db;closedFlag=!1;constructor($){this.db=$}static async create($){let J=new kM($);return J.exec(lM),dM(J),new I9(J)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask($,J){if(this.closedFlag)throw Error("store closed");if(J){let q=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(J);if(q){let W=await this.getTask(q.task_id);if(W)return W}}let Q=J7(),X=C$(),Y=$.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
3132
+ `;function y$(){return new Date().toISOString()}function H5(){return GO()}function zO($){return YO("sha256").update($).digest("hex")}function YQ($){let J=JSON.stringify({id:$.id,type:$.type,data:$.data,prev_hash:$.prev_hash,created_at:$.created_at});return zO(J)}function B5($){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:HO($.roy),created_at:$.created_at,updated_at:$.updated_at}}function HO($){if($===null||$===void 0||$==="")return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}function BO($){try{let J=$.query("PRAGMA table_info(tasks)").all();if(!new Set(J.map((X)=>X.name)).has("roy"))$.exec("ALTER TABLE tasks ADD COLUMN roy TEXT")}catch{}}function GQ($){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 x9($){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 y9{db;closedFlag=!1;constructor($){this.db=$}static async create($){let J=new qO($);return J.exec(WO),BO(J),new y9(J)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask($,J){if(this.closedFlag)throw Error("store closed");if(J){let G=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(J);if(G){let W=await this.getTask(G.task_id);if(W)return W}}let Q=H5(),X=y$(),q=$.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
3128
3133
  parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
3129
- VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.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),J)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
3130
- VALUES (?, ?, ?)`).run(J,Q,X);await this.appendOperation({task_id:Q,type:"task.created",data:{title:$.title,parent_id:$.parent_id??null}});let G=await this.getTask(Q);if(!G)throw Error("internal: task vanished after insert");return G}async getTask($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get($);return J?Q7(J):null}async getTaskByNum($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM tasks WHERE rowid = ?").get($);return J?Q7(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],Y=[];if(J.title!==void 0)X.push("title = ?"),Y.push(J.title);if(J.description!==void 0)X.push("description = ?"),Y.push(J.description);if(J.status!==void 0)X.push("status = ?"),Y.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),Y.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),Y.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),Y.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),Y.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let G={...Q.roy??{},...J.roy};X.push("roy = ?"),Y.push(JSON.stringify(G))}if(X.push("updated_at = ?"),Y.push(C$()),Y.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...Y),J.status!==void 0&&J.status!==Q.status)await this.appendOperation({task_id:$,type:"task.status_changed",data:{from:Q.status,to:J.status}});else await this.appendOperation({task_id:$,type:"task.updated",data:{keys:Object.keys(J)}});return await this.getTask($)}async listTasks($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)if(Array.isArray($.status))J.push(`status IN (${$.status.map(()=>"?").join(",")})`),Q.push(...$.status);else J.push("status = ?"),Q.push($.status);if($.parent_id!==void 0)if($.parent_id===null)J.push("parent_id IS NULL");else J.push("parent_id = ?"),Q.push($.parent_id);if($.session_id!==void 0)J.push("session_id = ?"),Q.push($.session_id);if($.owner!==void 0)J.push("owner = ?"),Q.push($.owner);if($.tags!==void 0)J.push("tags LIKE ?"),Q.push(`%${$.tags}%`);if($.search!==void 0)J.push("(title LIKE ? OR description LIKE ?)"),Q.push(`%${$.search}%`,`%${$.search}%`);let X=$.limit??100,Y=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",q=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${G}`).get(...Q).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${G} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...Q,X,Y).map(Q7),total:q}}async deleteTask($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run($).changes>0}async setParentId($,J){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(J,C$(),$)}async appendOperation($){if(this.closedFlag)throw Error("store closed");let Q=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=J7(),Y=C$(),G=o1({id:X,type:$.type,data:$.data,prev_hash:Q,created_at:Y});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
3131
- VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),Y,Q,G);let q=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:q,task_id:$.task_id,type:$.type,data:$.data,created_at:Y,prev_hash:Q,hash:G}}async getOperationByNum($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get($);return J?t1(J):null}async updateOperation($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getOperationByNum($);if(!Q)return null;let X=[],Y=[];if(J.type!==void 0)X.push("type = ?"),Y.push(J.type);if(J.data!==void 0)X.push("data = ?"),Y.push(JSON.stringify(J.data));if(X.length===0)return Q;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 J=[],Q=[];if($.task_id!==void 0)J.push("task_id = ?"),Q.push($.task_id);if($.type!==void 0)J.push("type = ?"),Q.push($.type);let X=$.limit??100,Y=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",q=this.db.query(`SELECT COUNT(*) AS n FROM operations ${G}`).get(...Q).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${G} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...Q,X,Y).map(t1),total:q}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),J="0".repeat(64);for(let Q of $){let X=o1({id:Q.id,type:Q.type,data:JSON.parse(Q.data),prev_hash:J,created_at:Q.created_at});if(Q.prev_hash!==J)return!1;if(Q.hash!==X)return!1;J=Q.hash}return!0}async tamperOpForTest($,J){this.db.query("UPDATE operations SET data = ? WHERE rowid = ?").run(JSON.stringify(J),$)}async sendBounty($){if(this.closedFlag)throw Error("store closed");let J=J7(),Q=C$();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
3132
- VALUES (?, ?, ?, ?, 'open', ?)`).run(J,$.subject,$.body,$.from,Q),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:J,subject:$.subject,from:$.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(J);return f9(X)}async claimBounty($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!J)return null;let Q=C$();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run($,Q,J.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:J.id,by:$}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(J.id);return f9(X)}async completeBounty($,J){if(this.closedFlag)throw Error("store closed");let Q=C$();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
3133
- WHERE id = ? AND status = 'claimed'`).run(J,Q,$).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:$,task_id:J}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return f9(Y)}async listBounties($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.to!==void 0)J.push("to_ = ?"),Q.push($.to);let X=J.length?`WHERE ${J.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...Q).map(f9)}}var rM=X7(iM(),".roy-task-plugin"),aM=X7(rM,"tasks.db");class B2{inner;constructor($){this.inner=$}static async create($){let J=$??aM;if(J!==":memory:")nM(X7(J,".."),{recursive:!0});let Q=await I9.create(J);return new B2(Q)}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 g0 extends Error{status;body;constructor($,J,Q){super(J);this.status=$,this.body=Q}}class Y7{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($,J,Q){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if(Q?.idempotencyKey)X["idempotency-key"]=Q.idempotencyKey;let Y=await fetch(`${this.baseUrl}${J}`,{method:$,headers:X,body:Q?.body!==void 0?JSON.stringify(Q.body):void 0});if(Y.status===204)return null;let G=await Y.text(),q=null;try{q=G?JSON.parse(G):null}catch{q=G}if(!Y.ok)throw new g0(Y.status,`HTTP ${Y.status}`,q);return q}async createTask($,J){let Q=await this.request("POST","/tasks",{body:$,idempotencyKey:J});if(!Q)throw new g0(500,"empty response from POST /tasks");return Q}async getTask($){try{return await this.request("GET",`/tasks/${encodeURIComponent($)}`)}catch(J){if(J instanceof g0&&J.status===404)return null;throw J}}async updateTask($,J){try{return await this.request("PATCH",`/tasks/${encodeURIComponent($)}`,{body:J})}catch(Q){if(Q instanceof g0&&Q.status===404)return null;throw Q}}async deleteTask($){try{return await this.request("DELETE",`/tasks/${encodeURIComponent($)}`),!0}catch(J){if(J instanceof g0&&J.status===404)return!1;throw J}}async listTasks($={}){let J=new URLSearchParams;if($.status!==void 0){let X=Array.isArray($.status)?$.status.join(","):$.status;J.set("status",X)}if($.parent_id!==void 0&&$.parent_id!==null)J.set("parent_id",$.parent_id);if($.session_id!==void 0)J.set("session_id",$.session_id);if($.owner!==void 0)J.set("owner",$.owner);if($.tags!==void 0)J.set("tags",$.tags);if($.search!==void 0)J.set("search",$.search);J.set("limit",String($.limit??100)),J.set("offset",String($.offset??0));let Q=await this.request("GET",`/tasks?${J}`);if(!Q)throw new g0(500,"empty response");return Q}async appendOperation($){return await this.request("POST","/operations",{body:$})}async listOperations($={}){let J=new URLSearchParams;if($.task_id!==void 0)J.set("task_id",$.task_id);if($.type!==void 0)J.set("type",$.type);return J.set("limit",String($.limit??100)),J.set("offset",String($.offset??0)),await this.request("GET",`/operations?${J}`)}async verifyChain(){return(await this.request("GET","/verify"))?.valid===!0}async sendBounty($){let J=await this.request("POST","/bounties",{body:$});if(!J)throw new g0(500,"empty bounty response");return J}async claimBounty($){try{return await this.request("POST","/bounties/claim",{body:{agent:$}})}catch(J){if(J instanceof g0&&J.status===404)return null;throw J}}async completeBounty($,J){try{return await this.request("POST",`/bounties/${encodeURIComponent($)}/complete`,{body:{task_id:J}})}catch(Q){if(Q instanceof g0&&Q.status===404)return null;throw Q}}async listBounties($={}){let J=new URLSearchParams;if($.status!==void 0)J.set("status",$.status);if($.to!==void 0)J.set("to",$.to);return(await this.request("GET",`/bounties?${J}`))?.bounties??[]}}class U6{inner;constructor($){this.inner=new Y7($)}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 cZ($={}){let J=$.persistence??"local",Q;if(J==="remote"){if(!$.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");Q=new U6({baseUrl:$.remoteUrl,authToken:$.remoteAuthToken})}else Q=await B2.create($.localDbPath);let X={store:Q,agent:$.agent??"opencode-default"};return{handlers:M6(X),store:Q,async close(){await Q.close()}}}var sM={id:"roy-task-plugin",async setup($){let J=$.options??{},Q=J.persistence??"local",X;if(Q==="remote"){if(!J.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");X=new U6({baseUrl:J.remoteUrl,authToken:J.remoteAuthToken})}else X=await B2.create(J.localDbPath);let Y={store:X,agent:J.agent??"opencode-default"},G=M6(Y),q=await s1($,{store:X,enabled:J.royAgent!==!1,agent:"roy"}),W=await $.agent.transform(async(H)=>{let U=H.get("build");if(!U)return;let V=String(U.system??""),O=`
3134
+ VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.title,$.description??null,q,$.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),J)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
3135
+ VALUES (?, ?, ?)`).run(J,Q,X);await this.appendOperation({task_id:Q,type:"task.created",data:{title:$.title,parent_id:$.parent_id??null}});let Y=await this.getTask(Q);if(!Y)throw Error("internal: task vanished after insert");return Y}async getTask($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get($);return J?B5(J):null}async getTaskByNum($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM tasks WHERE rowid = ?").get($);return J?B5(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],q=[];if(J.title!==void 0)X.push("title = ?"),q.push(J.title);if(J.description!==void 0)X.push("description = ?"),q.push(J.description);if(J.status!==void 0)X.push("status = ?"),q.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),q.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),q.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),q.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),q.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let Y={...Q.roy??{},...J.roy};X.push("roy = ?"),q.push(JSON.stringify(Y))}if(X.push("updated_at = ?"),q.push(y$()),q.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...q),J.status!==void 0&&J.status!==Q.status)await this.appendOperation({task_id:$,type:"task.status_changed",data:{from:Q.status,to:J.status}});else await this.appendOperation({task_id:$,type:"task.updated",data:{keys:Object.keys(J)}});return await this.getTask($)}async listTasks($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)if(Array.isArray($.status))J.push(`status IN (${$.status.map(()=>"?").join(",")})`),Q.push(...$.status);else J.push("status = ?"),Q.push($.status);if($.parent_id!==void 0)if($.parent_id===null)J.push("parent_id IS NULL");else J.push("parent_id = ?"),Q.push($.parent_id);if($.session_id!==void 0)J.push("session_id = ?"),Q.push($.session_id);if($.owner!==void 0)J.push("owner = ?"),Q.push($.owner);if($.tags!==void 0)J.push("tags LIKE ?"),Q.push(`%${$.tags}%`);if($.search!==void 0)J.push("(title LIKE ? OR description LIKE ?)"),Q.push(`%${$.search}%`,`%${$.search}%`);let X=$.limit??100,q=$.offset??0,Y=J.length?`WHERE ${J.join(" AND ")}`:"",G=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${Y}`).get(...Q).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${Y} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...Q,X,q).map(B5),total:G}}async deleteTask($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run($).changes>0}async setParentId($,J){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(J,y$(),$)}async appendOperation($){if(this.closedFlag)throw Error("store closed");let Q=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=H5(),q=y$(),Y=YQ({id:X,type:$.type,data:$.data,prev_hash:Q,created_at:q});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
3136
+ VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),q,Q,Y);let G=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:G,task_id:$.task_id,type:$.type,data:$.data,created_at:q,prev_hash:Q,hash:Y}}async getOperationByNum($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get($);return J?GQ(J):null}async updateOperation($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getOperationByNum($);if(!Q)return null;let X=[],q=[];if(J.type!==void 0)X.push("type = ?"),q.push(J.type);if(J.data!==void 0)X.push("data = ?"),q.push(JSON.stringify(J.data));if(X.length===0)return Q;return q.push($),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...q),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 J=[],Q=[];if($.task_id!==void 0)J.push("task_id = ?"),Q.push($.task_id);if($.type!==void 0)J.push("type = ?"),Q.push($.type);let X=$.limit??100,q=$.offset??0,Y=J.length?`WHERE ${J.join(" AND ")}`:"",G=this.db.query(`SELECT COUNT(*) AS n FROM operations ${Y}`).get(...Q).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${Y} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...Q,X,q).map(GQ),total:G}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),J="0".repeat(64);for(let Q of $){let X=YQ({id:Q.id,type:Q.type,data:JSON.parse(Q.data),prev_hash:J,created_at:Q.created_at});if(Q.prev_hash!==J)return!1;if(Q.hash!==X)return!1;J=Q.hash}return!0}async tamperOpForTest($,J){this.db.query("UPDATE operations SET data = ? WHERE rowid = ?").run(JSON.stringify(J),$)}async sendBounty($){if(this.closedFlag)throw Error("store closed");let J=H5(),Q=y$();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
3137
+ VALUES (?, ?, ?, ?, 'open', ?)`).run(J,$.subject,$.body,$.from,Q),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:J,subject:$.subject,from:$.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(J);return x9(X)}async claimBounty($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!J)return null;let Q=y$();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run($,Q,J.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:J.id,by:$}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(J.id);return x9(X)}async completeBounty($,J){if(this.closedFlag)throw Error("store closed");let Q=y$();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
3138
+ WHERE id = ? AND status = 'claimed'`).run(J,Q,$).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:$,task_id:J}});let q=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return x9(q)}async listBounties($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.to!==void 0)J.push("to_ = ?"),Q.push($.to);let X=J.length?`WHERE ${J.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...Q).map(x9)}}var DO=U5(UO(),".roy-task-plugin"),FO=U5(DO,"tasks.db");class M2{inner;constructor($){this.inner=$}static async create($){let J=$??FO;if(J!==":memory:")VO(U5(J,".."),{recursive:!0});let Q=await y9.create(J);return new M2(Q)}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()}}import{homedir as MO}from"os";import{join as OO}from"path";import{readFile as KO}from"fs/promises";async function jO($=OO(MO(),".roy-agent","auth.json")){try{let J=await KO($,"utf-8"),Q=JSON.parse(J);return{...Q.taskService?.endpoint?{endpoint:Q.taskService.endpoint}:{},...Q.taskService?.authToken?{authToken:Q.taskService.authToken}:{}}}catch{return{}}}class O2{inner;constructor($){this.inner=new T$($)}static async create($){let J=$.remoteAuthToken;if(!J)J=(await jO()).authToken;return new O2({endpoint:$.remoteUrl,...J?{authToken:J}:{}})}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.createOperation({taskId:Number($.task_id??0)||0,sessionId:String($.data?.session_id??"plugin"),milestoneType:"progress",milestoneTitle:$.type,milestoneDescription:JSON.stringify($.data??{})})}createOperation(...$){return this.inner.createOperation(...$)}listOperations(...$){return this.inner.listOperations(...$)}close(){this.inner.close()}}async function Rw($={}){let J=$.persistence??"local",Q;if(J==="remote"){if(!$.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");Q=await O2.create({remoteUrl:$.remoteUrl,remoteAuthToken:$.remoteAuthToken})}else Q=await M2.create($.localDbPath);let X={store:Q,agent:$.agent??"opencode-default"};return{handlers:L6(X),store:Q,async close(){await Q.close()}}}var LO={id:"roy-task-plugin",async setup($){let J=$.options??{},Q=J.persistence??"local",X;if(Q==="remote"){if(!J.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");X=await O2.create({remoteUrl:J.remoteUrl,remoteAuthToken:J.remoteAuthToken})}else X=await M2.create(J.localDbPath);let q={store:X,agent:J.agent??"opencode-default"},Y=L6(q),G=await qQ($,{store:X,enabled:J.royAgent!==!1,agent:"roy"}),W=await $.agent.transform(async(H)=>{let U=H.get("build");if(!U)return;let V=String(U.system??""),O=`
3134
3139
 
3135
3140
  # Roy Task Plugin (auto-injected by roy-task-plugin v2)
3136
3141
 
@@ -3146,6 +3151,6 @@ For task-first-class-citizen work (task tree, milestones, deliverables), switch
3146
3151
  to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
3147
3152
  lifecycle as native tools.
3148
3153
  `;H.update("build",(F)=>{if(typeof F.system==="string"||F.system===void 0)F.system=V+O})}),z=await $.command.transform((H)=>{H.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(B)=>{let U=String(B?.prompt?.text??"").trim(),V=U.split(`
3149
- `)[0]?.trim()||`task-${Date.now()}`;await G.session({type:"session.created",payload:{id:B?.sessionID??`cmd-${Date.now()}`,title:V,body:U,source:"command:task-create"}})}}),H.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),H.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 H of q.disposers)try{await H()}catch{}await W.dispose(),await z.dispose(),await X.close()}}}},dZ=sM;export{dZ as default,cZ as createRoyTaskPlugin,M6 as createHandlers,U6 as RemoteTaskStore,B2 as LocalTaskStore};
3154
+ `)[0]?.trim()||`task-${Date.now()}`;await Y.session({type:"session.created",payload:{id:B?.sessionID??`cmd-${Date.now()}`,title:V,body:U,source:"command:task-create"}})}}),H.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),H.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 H of G.disposers)try{await H()}catch{}await W.dispose(),await z.dispose(),await X.close()}}}},ww=LO;export{ww as default,Rw as createRoyTaskPlugin,L6 as createHandlers,O2 as RemoteTaskStore,M2 as LocalTaskStore};
3150
3155
 
3151
- //# debugId=85D8D4EEDE8A554A64756E2164756E21
3156
+ //# debugId=A590F7713B1E47EE64756E2164756E21