@ai-setting/roy-task-plugin 0.7.12 → 0.7.13
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/claude-plugin/agents/roy.md +1 -2
- package/dist/cli.js +66 -14
- package/dist/index.js +114 -113
- package/dist/index.js.map +3 -3
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
2
|
+
var l1=Object.create;var{getPrototypeOf:c1,defineProperty:f9,getOwnPropertyNames:d1}=Object;var p1=Object.prototype.hasOwnProperty;function i1($){return this[$]}var n1,r1,a1=($,J,Q)=>{var X=$!=null&&typeof $==="object";if(X){var W=J?n1??=new WeakMap:r1??=new WeakMap,G=W.get($);if(G)return G}Q=$!=null?l1(c1($)):{};let Y=J||!$||!$.__esModule?f9(Q,"default",{value:$,enumerable:!0}):Q;for(let q of d1($))if(!p1.call(Y,q))f9(Y,q,{get:i1.bind($,q),enumerable:!0});if(X)W.set($,Y);return Y};var C=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var s1=($)=>$;function o1($,J){this[$]=s1.bind(null,J)}var t1=($,J)=>{for(var Q in J)f9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:o1.bind(J,Q)})};var B6=import.meta.require;var p=C((gW)=>{var q4=Symbol.for("yaml.alias"),a7=Symbol.for("yaml.document"),N6=Symbol.for("yaml.map"),s7=Symbol.for("yaml.pair"),H4=Symbol.for("yaml.scalar"),Z6=Symbol.for("yaml.seq"),c0=Symbol.for("yaml.node.type"),fW=($)=>!!$&&typeof $==="object"&&$[c0]===q4,TW=($)=>!!$&&typeof $==="object"&&$[c0]===a7,IW=($)=>!!$&&typeof $==="object"&&$[c0]===N6,vW=($)=>!!$&&typeof $==="object"&&$[c0]===s7,o7=($)=>!!$&&typeof $==="object"&&$[c0]===H4,xW=($)=>!!$&&typeof $==="object"&&$[c0]===Z6;function t7($){if($&&typeof $==="object")switch($[c0]){case N6:case Z6:return!0}return!1}function hW($){if($&&typeof $==="object")switch($[c0]){case q4:case N6:case H4:case Z6:return!0}return!1}var yW=($)=>(o7($)||t7($))&&!!$.anchor;gW.ALIAS=q4;gW.DOC=a7;gW.MAP=N6;gW.NODE_TYPE=c0;gW.PAIR=s7;gW.SCALAR=H4;gW.SEQ=Z6;gW.hasAnchor=yW;gW.isAlias=fW;gW.isCollection=t7;gW.isDocument=TW;gW.isMap=IW;gW.isNode=hW;gW.isPair=vW;gW.isScalar=o7;gW.isSeq=xW});var A2=C((JG)=>{var G0=p(),D0=Symbol("break visit"),e7=Symbol("skip children"),x0=Symbol("remove node");function w6($,J){let Q=$5(J);if(G0.isDocument($)){if(d$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else d$(null,$,Q,Object.freeze([]))}w6.BREAK=D0;w6.SKIP=e7;w6.REMOVE=x0;function d$($,J,Q,X){let W=J5($,J,Q,X);if(G0.isNode(W)||G0.isPair(W))return Q5($,X,W),d$($,W,Q,X);if(typeof W!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let Y=d$(G,J.items[G],Q,X);if(typeof Y==="number")G=Y-1;else if(Y===D0)return D0;else if(Y===x0)J.items.splice(G,1),G-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let G=d$("key",J.key,Q,X);if(G===D0)return D0;else if(G===x0)J.key=null;let Y=d$("value",J.value,Q,X);if(Y===D0)return D0;else if(Y===x0)J.value=null}}return W}async function b6($,J){let Q=$5(J);if(G0.isDocument($)){if(await p$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else await p$(null,$,Q,Object.freeze([]))}b6.BREAK=D0;b6.SKIP=e7;b6.REMOVE=x0;async function p$($,J,Q,X){let W=await J5($,J,Q,X);if(G0.isNode(W)||G0.isPair(W))return Q5($,X,W),p$($,W,Q,X);if(typeof W!=="symbol"){if(G0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let Y=await p$(G,J.items[G],Q,X);if(typeof Y==="number")G=Y-1;else if(Y===D0)return D0;else if(Y===x0)J.items.splice(G,1),G-=1}}else if(G0.isPair(J)){X=Object.freeze(X.concat(J));let G=await p$("key",J.key,Q,X);if(G===D0)return D0;else if(G===x0)J.key=null;let Y=await p$("value",J.value,Q,X);if(Y===D0)return D0;else if(Y===x0)J.value=null}}return W}function $5($){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 J5($,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 Q5($,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 W=G0.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${W} parent`)}}JG.visit=w6;JG.visitAsync=b6});var B4=C((qG)=>{var X5=p(),WG=A2(),GG={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},YG=($)=>$.replace(/[!,[\]{}]/g,(J)=>GG[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[W,G]=Q;return this.tags[W]=G,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return J(0,"%YAML directive should contain exactly one part"),!1;let[W]=Q;if(W==="1.1"||W==="1.2")return this.yaml.version=W,!0;else{let G=/^\d+\.\d+$/.test(W);return J(6,`Unsupported YAML version ${W}`,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 W=this.tags[Q];if(W)try{return W+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+YG($.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&&X5.isNode($.contents)){let W={};WG.visit($.contents,(G,Y)=>{if(X5.isNode(Y)&&Y.tag)W[Y.tag]=!0}),X=Object.keys(W)}else X=[];for(let[W,G]of Q){if(W==="!!"&&G==="tag:yaml.org,2002:")continue;if(!$||X.some((Y)=>Y.startsWith(G)))J.push(`%TAG ${W} ${G}`)}return J.join(`
|
|
3
|
+
`)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};qG.Directives=K0});var P6=C((zG)=>{var W5=p(),BG=A2();function UG($){if(/[\x00-\x19\s,[\]{}]/.test($)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(Q)}return!0}function G5($){let J=new Set;return BG.visit($,{Value(Q,X){if(X.anchor)J.add(X.anchor)}}),J}function Y5($,J){for(let Q=1;;++Q){let X=`${$}${Q}`;if(!J.has(X))return X}}function VG($,J){let Q=[],X=new Map,W=null;return{onAnchor:(G)=>{Q.push(G),W??(W=G5($));let Y=Y5(J,W);return W.add(Y),Y},setAnchors:()=>{for(let G of Q){let Y=X.get(G);if(typeof Y==="object"&&Y.anchor&&(W5.isScalar(Y.node)||W5.isCollection(Y.node)))Y.node.anchor=Y.anchor;else{let q=Error("Failed to resolve repeated object (this should not happen)");throw q.source=G,q}}},sourceObjects:X}}zG.anchorIsValid=UG;zG.anchorNames=G5;zG.createNodeAnchors=VG;zG.findNewAnchor=Y5});var U4=C((KG)=>{function _2($,J,Q,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let W=0,G=X.length;W<G;++W){let Y=X[W],q=_2($,X,String(W),Y);if(q===void 0)delete X[W];else if(q!==Y)X[W]=q}else if(X instanceof Map)for(let W of Array.from(X.keys())){let G=X.get(W),Y=_2($,X,W,G);if(Y===void 0)X.delete(W);else if(Y!==G)X.set(W,Y)}else if(X instanceof Set)for(let W of Array.from(X)){let G=_2($,X,W,W);if(G===void 0)X.delete(W);else if(G!==W)X.delete(W),X.add(G)}else for(let[W,G]of Object.entries(X)){let Y=_2($,X,W,G);if(Y===void 0)delete X[W];else if(Y!==G)X[W]=Y}return $.call(J,Q,X)}KG.applyReviver=_2});var t0=C((AG)=>{var LG=p();function q5($,J,Q){if(Array.isArray($))return $.map((X,W)=>q5(X,String(W),Q));if($&&typeof $.toJSON==="function"){if(!Q||!LG.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 W=$.toJSON(J,Q);if(Q.onCreate)Q.onCreate(W);return W}if(typeof $==="bigint"&&!Q?.keep)return Number($);return $}AG.toJS=q5});var S6=C((ZG)=>{var jG=U4(),H5=p(),NG=t0();class B5{constructor($){Object.defineProperty(this,H5.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:W}={}){if(!H5.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},Y=NG.toJS(this,"",G);if(typeof X==="function")for(let{count:q,res:H}of G.anchors.values())X(H,q);return typeof W==="function"?jG.applyReviver(W,{"":Y},"",Y):Y}}ZG.NodeBase=B5});var j2=C((CG)=>{var bG=P6(),PG=A2(),i$=p(),SG=S6(),EG=t0();class U5 extends SG.NodeBase{constructor($){super(i$.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=[],PG.visit($,{Node:(W,G)=>{if(i$.isAlias(G)||i$.hasAnchor(G))Q.push(G)}}),J)J.aliasResolveCache=Q;let X=void 0;for(let W of Q){if(W===this)break;if(W.anchor===this.source)X=W}if(X&&J){let{anchors:W,doc:G,maxAliasCount:Y}=J,q=W.get(X);if(!q)EG.toJS(X,null,J),q=W.get(X);if(q?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(Y>=0){if(q.count+=1,q.aliasCount===0)q.aliasCount=E6(G,X,W);if(q.count*q.aliasCount>Y)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(bG.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let W=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(W)}if($.implicitKey)return`${X} `}return X}}function E6($,J,Q){if(i$.isAlias(J)){let X=J.resolve($),W=Q&&X&&Q.get(X);return W?W.count*W.aliasCount:0}else if(i$.isCollection(J)){let X=0;for(let W of J.items){let G=E6($,W,Q);if(G>X)X=G}return X}else if(i$.isPair(J)){let X=E6($,J.key,Q),W=E6($,J.value,Q);return Math.max(X,W)}return 1}CG.Alias=U5});var W0=C((hG)=>{var TG=p(),IG=S6(),vG=t0(),xG=($)=>!$||typeof $!=="function"&&typeof $!=="object";class O$ extends IG.NodeBase{constructor($){super(TG.SCALAR);this.value=$}toJSON($,J){return J?.keep?this.value:vG.toJS(this.value,$,J)}toString(){return String(this.value)}}O$.BLOCK_FOLDED="BLOCK_FOLDED";O$.BLOCK_LITERAL="BLOCK_LITERAL";O$.PLAIN="PLAIN";O$.QUOTE_DOUBLE="QUOTE_DOUBLE";O$.QUOTE_SINGLE="QUOTE_SINGLE";hG.Scalar=O$;hG.isScalarValue=xG});var N2=C((cG)=>{var kG=j2(),M$=p(),V5=W0(),mG="tag:yaml.org,2002:";function uG($,J,Q){if(J){let X=Q.filter((G)=>G.tag===J),W=X.find((G)=>!G.format)??X[0];if(!W)throw Error(`Tag ${J} not found`);return W}return Q.find((X)=>X.identify?.($)&&!X.format)}function lG($,J,Q){if(M$.isDocument($))$=$.contents;if(M$.isNode($))return $;if(M$.isPair($)){let z=Q.schema[M$.MAP].createNode?.(Q.schema,null,Q);return z.items.push($),z}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:X,onAnchor:W,onTagObj:G,schema:Y,sourceObjects:q}=Q,H=void 0;if(X&&$&&typeof $==="object")if(H=q.get($),H)return H.anchor??(H.anchor=W($)),new kG.Alias(H.anchor);else H={anchor:null,node:null},q.set($,H);if(J?.startsWith("!!"))J=mG+J.slice(2);let B=uG($,J,Y.tags);if(!B){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let z=new V5.Scalar($);if(H)H.node=z;return z}B=$ instanceof Map?Y[M$.MAP]:(Symbol.iterator in Object($))?Y[M$.SEQ]:Y[M$.MAP]}if(G)G(B),delete Q.onTagObj;let U=B?.createNode?B.createNode(Q.schema,$,Q):typeof B?.nodeClass?.from==="function"?B.nodeClass.from(Q.schema,$,Q):new V5.Scalar($);if(J)U.tag=J;else if(!B.default)U.tag=B.tag;if(H)H.node=U;return U}cG.createNode=lG});var C6=C((nG)=>{var pG=N2(),h0=p(),iG=S6();function V4($,J,Q){let X=Q;for(let W=J.length-1;W>=0;--W){let G=J[W];if(typeof G==="number"&&Number.isInteger(G)&&G>=0){let Y=[];Y[G]=X,X=Y}else X=new Map([[G,X]])}return pG.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var z5=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class D5 extends iG.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)=>h0.isNode(Q)||h0.isPair(Q)?Q.clone($):Q),this.range)J.range=this.range.slice();return J}addIn($,J){if(z5($))this.add(J);else{let[Q,...X]=$,W=this.get(Q,!0);if(h0.isCollection(W))W.addIn(X,J);else if(W===void 0&&this.schema)this.set(Q,V4(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(h0.isCollection(X))return X.deleteIn(Q);else throw Error(`Expected YAML collection at ${J}. Remaining path: ${Q}`)}getIn($,J){let[Q,...X]=$,W=this.get(Q,!0);if(X.length===0)return!J&&h0.isScalar(W)?W.value:W;else return h0.isCollection(W)?W.getIn(X,J):void 0}hasAllNullValues($){return this.items.every((J)=>{if(!h0.isPair(J))return!1;let Q=J.value;return Q==null||$&&h0.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 h0.isCollection(X)?X.hasIn(Q):!1}setIn($,J){let[Q,...X]=$;if(X.length===0)this.set(Q,J);else{let W=this.get(Q,!0);if(h0.isCollection(W))W.setIn(X,J);else if(W===void 0&&this.schema)this.set(Q,V4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}}nG.Collection=D5;nG.collectionFromPath=V4;nG.isEmptyPath=z5});var Z2=C((eG)=>{var oG=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function z4($,J){if(/^\n+$/.test($))return $.substring(1);return J?$.replace(/^(?! *$)/gm,J):$}var tG=($,J,Q)=>$.endsWith(`
|
|
4
4
|
`)?z4(Q,J):Q.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
`+z4(Q,J):($.endsWith(" ")?"":" ")+Q;
|
|
7
|
-
`){if(Q==="block")D=
|
|
6
|
+
`+z4(Q,J):($.endsWith(" ")?"":" ")+Q;eG.indentComment=z4;eG.lineComment=tG;eG.stringifyComment=oG});var O5=C((WY)=>{function XY($,J,Q="flow",{indentAtStart:X,lineWidth:W=80,minContentWidth:G=20,onFold:Y,onOverflow:q}={}){if(!W||W<0)return $;if(W<G)G=0;let H=Math.max(1+G,1+W-J.length);if($.length<=H)return $;let B=[],U={},z=W-J.length;if(typeof X==="number")if(X>W-Math.max(2,G))B.push(0);else z=W-X;let V=void 0,M=void 0,F=!1,D=-1,O=-1,R=-1;if(Q==="block"){if(D=F5($,D,J.length),D!==-1)z=D+H}for(let _;_=$[D+=1];){if(Q==="quoted"&&_==="\\"){switch(O=D,$[D+1]){case"x":D+=3;break;case"u":D+=5;break;case"U":D+=9;break;default:D+=1}R=D}if(_===`
|
|
7
|
+
`){if(Q==="block")D=F5($,D,J.length);z=D+J.length+H,V=void 0}else{if(_===" "&&M&&M!==" "&&M!==`
|
|
8
8
|
`&&M!=="\t"){let Z=$[D+1];if(Z&&Z!==" "&&Z!==`
|
|
9
9
|
`&&Z!=="\t")V=D}if(D>=z)if(V)B.push(V),z=V+H,V=void 0;else if(Q==="quoted"){while(M===" "||M==="\t")M=_,_=$[D+=1],F=!0;let Z=D>R+1?D-2:O-1;if(U[Z])return $;B.push(Z),U[Z]=!0,z=Z+H,V=void 0}else F=!0}M=_}if(F&&q)q();if(B.length===0)return $;if(Y)Y();let L=$.slice(0,B[0]);for(let _=0;_<B.length;++_){let Z=B[_],P=B[_+1]||$.length;if(Z===0)L=`
|
|
10
10
|
${J}${$.slice(0,P)}`;else{if(Q==="quoted"&&U[Z])L+=`${$[Z]}\\`;L+=`
|
|
11
|
-
${J}${$.slice(Z+1,P)}`}}return L}function
|
|
12
|
-
`);X=J,W=J+1,G=$[W]}return X}
|
|
11
|
+
${J}${$.slice(Z+1,P)}`}}return L}function F5($,J,Q){let X=J,W=J+1,G=$[W];while(G===" "||G==="\t")if(J<W+Q)G=$[++J];else{do G=$[++J];while(G&&G!==`
|
|
12
|
+
`);X=J,W=J+1,G=$[W]}return X}WY.FOLD_BLOCK="block";WY.FOLD_FLOW="flow";WY.FOLD_QUOTED="quoted";WY.foldFlowLines=XY});var b2=C((zY)=>{var P0=W0(),e0=O5(),T6=($,J)=>({indentAtStart:J?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),I6=($)=>/^(%|---|\.\.\.)/m.test($);function BY($,J,Q){if(!J||J<0)return!1;let X=J-Q,W=$.length;if(W<=X)return!1;for(let G=0,Y=0;G<W;++G)if($[G]===`
|
|
13
13
|
`){if(G-Y>X)return!0;if(Y=G+1,W-Y<=X)return!1}return!0}function w2($,J){let Q=JSON.stringify($);if(J.options.doubleQuotedAsJSON)return Q;let{implicitKey:X}=J,W=J.options.doubleQuotedMinMultiLineLength,G=J.indent||(I6($)?" ":""),Y="",q=0;for(let H=0,B=Q[H];B;B=Q[++H]){if(B===" "&&Q[H+1]==="\\"&&Q[H+2]==="n")Y+=Q.slice(q,H)+"\\ ",H+=1,q=H,B="\\";if(B==="\\")switch(Q[H+1]){case"u":{Y+=Q.slice(q,H);let U=Q.substr(H+2,4);switch(U){case"0000":Y+="\\0";break;case"0007":Y+="\\a";break;case"000b":Y+="\\v";break;case"001b":Y+="\\e";break;case"0085":Y+="\\N";break;case"00a0":Y+="\\_";break;case"2028":Y+="\\L";break;case"2029":Y+="\\P";break;default:if(U.substr(0,2)==="00")Y+="\\x"+U.substr(2);else Y+=Q.substr(H,6)}H+=5,q=H+1}break;case"n":if(X||Q[H+2]==='"'||Q.length<W)H+=1;else{Y+=Q.slice(q,H)+`
|
|
14
14
|
|
|
15
15
|
`;while(Q[H+2]==="\\"&&Q[H+3]==="n"&&Q[H+4]!=='"')Y+=`
|
|
@@ -18,7 +18,7 @@ ${J}${$.slice(Z+1,P)}`}}return L}function D5($,J,Q){let X=J,W=J+1,G=$[W];while(G
|
|
|
18
18
|
${Q}`)+"'";return J.implicitKey?X:e0.foldFlowLines(X,Q,e0.FOLD_FLOW,T6(J,!1))}function n$($,J){let{singleQuote:Q}=J.options,X;if(Q===!1)X=w2;else{let W=$.includes('"'),G=$.includes("'");if(W&&!G)X=D4;else if(G&&!W)X=w2;else X=Q?D4:w2}return X($,J)}var F4;try{F4=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{F4=/\n+(?!\n|$)/g}function f6({comment:$,type:J,value:Q},X,W,G){let{blockQuote:Y,commentString:q,lineWidth:H}=X.options;if(!Y||/\n[\t ]+$/.test(Q))return n$(Q,X);let B=X.indent||(X.forceBlockIndent||I6(Q)?" ":""),U=Y==="literal"?!0:Y==="folded"||J===P0.Scalar.BLOCK_FOLDED?!1:J===P0.Scalar.BLOCK_LITERAL?!0:!
|
|
21
|
+
|$)`,"g")}catch{F4=/\n+(?!\n|$)/g}function f6({comment:$,type:J,value:Q},X,W,G){let{blockQuote:Y,commentString:q,lineWidth:H}=X.options;if(!Y||/\n[\t ]+$/.test(Q))return n$(Q,X);let B=X.indent||(X.forceBlockIndent||I6(Q)?" ":""),U=Y==="literal"?!0:Y==="folded"||J===P0.Scalar.BLOCK_FOLDED?!1:J===P0.Scalar.BLOCK_LITERAL?!0:!BY(Q,H,B.length);if(!Q)return U?`|
|
|
22
22
|
`:`>
|
|
23
23
|
`;let z,V;for(V=Q.length;V>0;--V){let P=Q[V-1];if(P!==`
|
|
24
24
|
`&&P!=="\t"&&P!==" ")break}let M=Q.substring(V),F=M.indexOf(`
|
|
@@ -27,13 +27,13 @@ ${Q}`)+"'";return J.implicitKey?X:e0.foldFlowLines(X,Q,e0.FOLD_FLOW,T6(J,!1))}fu
|
|
|
27
27
|
`)R=O;else break}let L=Q.substring(0,R<O?R+1:O);if(L)Q=Q.substring(L.length),L=L.replace(/\n+/g,`$&${B}`);let Z=(D?B?"2":"1":"")+z;if($){if(Z+=" "+q($.replace(/ ?[\r\n]+/g," ")),W)W()}if(!U){let P=Q.replace(/\n+/g,`
|
|
28
28
|
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${B}`),w=!1,f=T6(X,!0);if(Y!=="folded"&&J!==P0.Scalar.BLOCK_FOLDED)f.onOverflow=()=>{w=!0};let N=e0.foldFlowLines(`${L}${P}${M}`,B,e0.FOLD_BLOCK,f);if(!w)return`>${Z}
|
|
29
29
|
${B}${N}`}return Q=Q.replace(/\n+/g,`$&${B}`),`|${Z}
|
|
30
|
-
${B}${L}${Q}${M}`}function
|
|
30
|
+
${B}${L}${Q}${M}`}function UY($,J,Q,X){let{type:W,value:G}=$,{actualString:Y,implicitKey:q,indent:H,indentStep:B,inFlow:U}=J;if(q&&G.includes(`
|
|
31
31
|
`)||U&&/[[\]{},]/.test(G))return n$(G,J);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(G))return q||U||!G.includes(`
|
|
32
32
|
`)?n$(G,J):f6($,J,Q,X);if(!q&&!U&&W!==P0.Scalar.PLAIN&&G.includes(`
|
|
33
33
|
`))return f6($,J,Q,X);if(I6(G)){if(H==="")return J.forceBlockIndent=!0,f6($,J,Q,X);else if(q&&H===B)return n$(G,J)}let z=G.replace(/\n+/g,`$&
|
|
34
|
-
${H}`);if(Y){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(z),{compat:M,tags:F}=J.doc.schema;if(F.some(V)||M?.some(V))return n$(G,J)}return q?z:e0.foldFlowLines(z,H,e0.FOLD_FLOW,T6(J,!1))}function
|
|
35
|
-
${J.indent}${q}`}
|
|
36
|
-
${q}:`}else if(O=`${O}:`,V)O+=S2.lineComment(O,Q.indent,B(V));let R,L,_;if(d0.isNode(J))R=!!J.spaceBefore,L=J.commentBefore,_=J.comment;else if(R=!1,L=null,_=null,J&&typeof J==="object")J=Y.createNode(J);if(Q.implicitKey=!1,!M&&!V&&d0.isScalar(J))Q.indentAtStart=O.length+1;if(D=!1,!U&&H.length>=2&&!Q.inFlow&&!M&&d0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let Z=!1,P=
|
|
34
|
+
${H}`);if(Y){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(z),{compat:M,tags:F}=J.doc.schema;if(F.some(V)||M?.some(V))return n$(G,J)}return q?z:e0.foldFlowLines(z,H,e0.FOLD_FLOW,T6(J,!1))}function VY($,J,Q,X){let{implicitKey:W,inFlow:G}=J,Y=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:q}=$;if(q!==P0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(Y.value))q=P0.Scalar.QUOTE_DOUBLE}let H=(U)=>{switch(U){case P0.Scalar.BLOCK_FOLDED:case P0.Scalar.BLOCK_LITERAL:return W||G?n$(Y.value,J):f6(Y,J,Q,X);case P0.Scalar.QUOTE_DOUBLE:return w2(Y.value,J);case P0.Scalar.QUOTE_SINGLE:return D4(Y.value,J);case P0.Scalar.PLAIN:return UY(Y,J,Q,X);default:return null}},B=H(q);if(B===null){let{defaultKeyType:U,defaultStringType:z}=J.options,V=W&&U||z;if(B=H(V),B===null)throw Error(`Unsupported default string type ${V}`)}return B}zY.stringifyString=VY});var P2=C((_Y)=>{var FY=P6(),$$=p(),OY=Z2(),MY=b2();function KY($,J){let Q=Object.assign({blockQuote:!0,commentString:OY.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 RY($,J){if(J.tag){let W=$.filter((G)=>G.tag===J.tag);if(W.length>0)return W.find((G)=>G.format===J.format)??W[0]}let Q=void 0,X;if($$.isScalar(J)){X=J.value;let W=$.filter((G)=>G.identify?.(X));if(W.length>1){let G=W.filter((Y)=>Y.test);if(G.length>0)W=G}Q=W.find((G)=>G.format===J.format)??W.find((G)=>!G.format)}else X=J,Q=$.find((W)=>W.nodeClass&&X instanceof W.nodeClass);if(!Q){let W=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${W} value`)}return Q}function LY($,J,{anchors:Q,doc:X}){if(!X.directives)return"";let W=[],G=($$.isScalar($)||$$.isCollection($))&&$.anchor;if(G&&FY.anchorIsValid(G))Q.add(G),W.push(`&${G}`);let Y=$.tag??(J.default?null:J.tag);if(Y)W.push(X.directives.tagString(Y));return W.join(" ")}function AY($,J,Q,X){if($$.isPair($))return $.toString(J,Q,X);if($$.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 W=void 0,G=$$.isNode($)?$:J.doc.createNode($,{onTagObj:(H)=>W=H});W??(W=RY(J.doc.schema.tags,G));let Y=LY(G,W,J);if(Y.length>0)J.indentAtStart=(J.indentAtStart??0)+Y.length+1;let q=typeof W.stringify==="function"?W.stringify(G,J,Q,X):$$.isScalar(G)?MY.stringifyString(G,J,Q,X):G.toString(J,Q,X);if(!Y)return q;return $$.isScalar(G)||q[0]==="{"||q[0]==="["?`${Y} ${q}`:`${Y}
|
|
35
|
+
${J.indent}${q}`}_Y.createStringifyContext=KY;_Y.stringify=AY});var R5=C((wY)=>{var d0=p(),M5=W0(),K5=P2(),S2=Z2();function ZY({key:$,value:J},Q,X,W){let{allNullValues:G,doc:Y,indent:q,indentStep:H,options:{commentString:B,indentSeq:U,simpleKeys:z}}=Q,V=d0.isNode($)&&$.comment||null;if(z){if(V)throw Error("With simple keys, key nodes cannot have comments");if(d0.isCollection($)||!d0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let M=!z&&(!$||V&&J==null&&!Q.inFlow||d0.isCollection($)||(d0.isScalar($)?$.type===M5.Scalar.BLOCK_FOLDED||$.type===M5.Scalar.BLOCK_LITERAL:typeof $==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!M&&(z||!G),indent:q+H});let F=!1,D=!1,O=K5.stringify($,Q,()=>F=!0,()=>D=!0);if(!M&&!Q.inFlow&&O.length>1024){if(z)throw Error("With simple keys, single line scalar must not span more than 1024 characters");M=!0}if(Q.inFlow){if(G||J==null){if(F&&X)X();return O===""?"?":M?`? ${O}`:O}}else if(G&&!z||J==null&&M){if(O=`? ${O}`,V&&!F)O+=S2.lineComment(O,Q.indent,B(V));else if(D&&W)W();return O}if(F)V=null;if(M){if(V)O+=S2.lineComment(O,Q.indent,B(V));O=`? ${O}
|
|
36
|
+
${q}:`}else if(O=`${O}:`,V)O+=S2.lineComment(O,Q.indent,B(V));let R,L,_;if(d0.isNode(J))R=!!J.spaceBefore,L=J.commentBefore,_=J.comment;else if(R=!1,L=null,_=null,J&&typeof J==="object")J=Y.createNode(J);if(Q.implicitKey=!1,!M&&!V&&d0.isScalar(J))Q.indentAtStart=O.length+1;if(D=!1,!U&&H.length>=2&&!Q.inFlow&&!M&&d0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let Z=!1,P=K5.stringify(J,Q,()=>Z=!0,()=>D=!0),w=" ";if(V||R||L){if(w=R?`
|
|
37
37
|
`:"",L){let f=B(L);w+=`
|
|
38
38
|
${S2.indentComment(f,Q.indent)}`}if(P===""&&!Q.inFlow){if(w===`
|
|
39
39
|
`&&_)w=`
|
|
@@ -42,32 +42,32 @@ ${S2.indentComment(f,Q.indent)}`}if(P===""&&!Q.inFlow){if(w===`
|
|
|
42
42
|
${Q.indent}`}else if(!M&&d0.isCollection(J)){let f=P[0],N=P.indexOf(`
|
|
43
43
|
`),E=N!==-1,x=Q.inFlow??J.flow??J.items.length===0;if(E||!x){let n=!1;if(E&&(f==="&"||f==="!")){let g=P.indexOf(" ");if(f==="&"&&g!==-1&&g<N&&P[g+1]==="!")g=P.indexOf(" ",g+1);if(g===-1||N<g)n=!0}if(!n)w=`
|
|
44
44
|
${Q.indent}`}}else if(P===""||P[0]===`
|
|
45
|
-
`)w="";if(O+=w+P,Q.inFlow){if(Z&&X)X()}else if(_&&!Z)O+=S2.lineComment(O,Q.indent,B(_));else if(D&&W)W();return O}
|
|
45
|
+
`)w="";if(O+=w+P,Q.inFlow){if(Z&&X)X()}else if(_&&!Z)O+=S2.lineComment(O,Q.indent,B(_));else if(D&&W)W();return O}wY.stringifyPair=ZY});var O4=C((EY)=>{var L5=B6("process");function PY($,...J){if($==="debug")console.log(...J)}function SY($,J){if($==="debug"||$==="warn")if(typeof L5.emitWarning==="function")L5.emitWarning(J);else console.warn(J)}EY.debug=PY;EY.warn=SY});var y6=C((IY)=>{var h6=p(),A5=W0(),v6="<<",x6={identify:($)=>$===v6||typeof $==="symbol"&&$.description===v6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new A5.Scalar(Symbol(v6)),{addToJSMap:_5}),stringify:()=>v6},TY=($,J)=>(x6.identify(J)||h6.isScalar(J)&&(!J.type||J.type===A5.Scalar.PLAIN)&&x6.identify(J.value))&&$?.doc.schema.tags.some((Q)=>Q.tag===x6.tag&&Q.default);function _5($,J,Q){let X=j5($,Q);if(h6.isSeq(X))for(let W of X.items)M4($,J,W);else if(Array.isArray(X))for(let W of X)M4($,J,W);else M4($,J,X)}function M4($,J,Q){let X=j5($,Q);if(!h6.isMap(X))throw Error("Merge sources must be maps or map aliases");let W=X.toJSON(null,$,Map);for(let[G,Y]of W)if(J instanceof Map){if(!J.has(G))J.set(G,Y)}else if(J instanceof Set)J.add(G);else if(!Object.prototype.hasOwnProperty.call(J,G))Object.defineProperty(J,G,{value:Y,writable:!0,enumerable:!0,configurable:!0});return J}function j5($,J){return $&&h6.isAlias(J)?J.resolve($.doc,$):J}IY.addMergeToJSMap=_5;IY.isMergeKey=TY;IY.merge=x6});var R4=C((uY)=>{var yY=O4(),N5=y6(),gY=P2(),Z5=p(),K4=t0();function kY($,J,{key:Q,value:X}){if(Z5.isNode(Q)&&Q.addToJSMap)Q.addToJSMap($,J,X);else if(N5.isMergeKey($,Q))N5.addMergeToJSMap($,J,X);else{let W=K4.toJS(Q,"",$);if(J instanceof Map)J.set(W,K4.toJS(X,W,$));else if(J instanceof Set)J.add(W);else{let G=mY(Q,W,$),Y=K4.toJS(X,G,$);if(G in J)Object.defineProperty(J,G,{value:Y,writable:!0,enumerable:!0,configurable:!0});else J[G]=Y}}return J}function mY($,J,Q){if(J===null)return"";if(typeof J!=="object")return String(J);if(Z5.isNode($)&&Q?.doc){let X=gY.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 W=$.toString(X);if(!Q.mapKeyWarned){let G=JSON.stringify(W);if(G.length>40)G=G.substring(0,36)+'..."';yY.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 W}return JSON.stringify(J)}uY.addPairToJSMap=kY});var J$=C((iY)=>{var w5=N2(),cY=R5(),dY=R4(),g6=p();function pY($,J,Q){let X=w5.createNode($,void 0,Q),W=w5.createNode(J,void 0,Q);return new k6(X,W)}class k6{constructor($,J=null){Object.defineProperty(this,g6.NODE_TYPE,{value:g6.PAIR}),this.key=$,this.value=J}clone($){let{key:J,value:Q}=this;if(g6.isNode(J))J=J.clone($);if(g6.isNode(Q))Q=Q.clone($);return new k6(J,Q)}toJSON($,J){let Q=J?.mapAsMap?new Map:{};return dY.addPairToJSMap(J,Q,this)}toString($,J,Q){return $?.doc?cY.stringifyPair(this,$,J,Q):JSON.stringify(this)}}iY.Pair=k6;iY.createPair=pY});var L4=C((tY)=>{var K$=p(),b5=P2(),m6=Z2();function aY($,J,Q){return(J.inFlow??$.flow?oY:sY)($,J,Q)}function sY({comment:$,items:J},Q,{blockItemPrefix:X,flowChars:W,itemIndent:G,onChompKeep:Y,onComment:q}){let{indent:H,options:{commentString:B}}=Q,U=Object.assign({},Q,{indent:G,type:null}),z=!1,V=[];for(let F=0;F<J.length;++F){let D=J[F],O=null;if(K$.isNode(D)){if(!z&&D.spaceBefore)V.push("");if(u6(Q,V,D.commentBefore,z),D.comment)O=D.comment}else if(K$.isPair(D)){let L=K$.isNode(D.key)?D.key:null;if(L){if(!z&&L.spaceBefore)V.push("");u6(Q,V,L.commentBefore,z)}}z=!1;let R=b5.stringify(D,U,()=>O=null,()=>z=!0);if(O)R+=m6.lineComment(R,G,B(O));if(z&&O)z=!1;V.push(X+R)}let M;if(V.length===0)M=W.start+W.end;else{M=V[0];for(let F=1;F<V.length;++F){let D=V[F];M+=D?`
|
|
46
46
|
${H}${D}`:`
|
|
47
47
|
`}}if($){if(M+=`
|
|
48
|
-
`+m6.indentComment(B($),H),q)q()}else if(z&&Y)Y();return M}function
|
|
48
|
+
`+m6.indentComment(B($),H),q)q()}else if(z&&Y)Y();return M}function oY({items:$},J,{flowChars:Q,itemIndent:X}){let{indent:W,indentStep:G,flowCollectionPadding:Y,options:{commentString:q}}=J;X+=G;let H=Object.assign({},J,{indent:X,inFlow:!0,type:null}),B=!1,U=0,z=[];for(let F=0;F<$.length;++F){let D=$[F],O=null;if(K$.isNode(D)){if(D.spaceBefore)z.push("");if(u6(J,z,D.commentBefore,!1),D.comment)O=D.comment}else if(K$.isPair(D)){let L=K$.isNode(D.key)?D.key:null;if(L){if(L.spaceBefore)z.push("");if(u6(J,z,L.commentBefore,!1),L.comment)B=!0}let _=K$.isNode(D.value)?D.value:null;if(_){if(_.comment)O=_.comment;if(_.commentBefore)B=!0}else if(D.value==null&&L?.comment)O=L.comment}if(O)B=!0;let R=b5.stringify(D,H,()=>O=null);if(B||(B=z.length>U||R.includes(`
|
|
49
49
|
`)),F<$.length-1)R+=",";else if(J.options.trailingComma){if(J.options.lineWidth>0)B||(B=z.reduce((L,_)=>L+_.length+2,2)+(R.length+2)>J.options.lineWidth);if(B)R+=","}if(O)R+=m6.lineComment(R,X,q(O));z.push(R),U=z.length}let{start:V,end:M}=Q;if(z.length===0)return V+M;else{if(!B){let F=z.reduce((D,O)=>D+O.length+2,2);B=J.options.lineWidth>0&&F>J.options.lineWidth}if(B){let F=V;for(let D of z)F+=D?`
|
|
50
50
|
${G}${W}${D}`:`
|
|
51
51
|
`;return`${F}
|
|
52
|
-
${W}${M}`}else return`${V}${Y}${z.join(" ")}${Y}${M}`}}function u6({indent:$,options:{commentString:J}},Q,X,W){if(X&&W)X=X.replace(/^\n+/,"");if(X){let G=m6.indentComment(J(X),$);Q.push(G.trimStart())}}
|
|
53
|
-
`:" ")}return
|
|
52
|
+
${W}${M}`}else return`${V}${Y}${z.join(" ")}${Y}${M}`}}function u6({indent:$,options:{commentString:J}},Q,X,W){if(X&&W)X=X.replace(/^\n+/,"");if(X){let G=m6.indentComment(J(X),$);Q.push(G.trimStart())}}tY.stringifyCollection=aY});var X$=C((Wq)=>{var $q=L4(),Jq=R4(),Qq=C6(),Q$=p(),l6=J$(),Xq=W0();function E2($,J){let Q=Q$.isScalar(J)?J.value:J;for(let X of $)if(Q$.isPair(X)){if(X.key===J||X.key===Q)return X;if(Q$.isScalar(X.key)&&X.key.value===Q)return X}return}class P5 extends Qq.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(Q$.MAP,$);this.items=[]}static from($,J,Q){let{keepUndefined:X,replacer:W}=Q,G=new this($),Y=(q,H)=>{if(typeof W==="function")H=W.call(J,q,H);else if(Array.isArray(W)&&!W.includes(q))return;if(H!==void 0||X)G.items.push(l6.createPair(q,H,Q))};if(J instanceof Map)for(let[q,H]of J)Y(q,H);else if(J&&typeof J==="object")for(let q of Object.keys(J))Y(q,J[q]);if(typeof $.sortMapEntries==="function")G.items.sort($.sortMapEntries);return G}add($,J){let Q;if(Q$.isPair($))Q=$;else if(!$||typeof $!=="object"||!("key"in $))Q=new l6.Pair($,$?.value);else Q=new l6.Pair($.key,$.value);let X=E2(this.items,Q.key),W=this.schema?.sortMapEntries;if(X){if(!J)throw Error(`Key ${Q.key} already set`);if(Q$.isScalar(X.value)&&Xq.isScalarValue(Q.value))X.value.value=Q.value;else X.value=Q.value}else if(W){let G=this.items.findIndex((Y)=>W(Q,Y)<0);if(G===-1)this.items.push(Q);else this.items.splice(G,0,Q)}else this.items.push(Q)}delete($){let J=E2(this.items,$);if(!J)return!1;return this.items.splice(this.items.indexOf(J),1).length>0}get($,J){let X=E2(this.items,$)?.value;return(!J&&Q$.isScalar(X)?X.value:X)??void 0}has($){return!!E2(this.items,$)}set($,J){this.add(new l6.Pair($,J),!0)}toJSON($,J,Q){let X=Q?new Q:J?.mapAsMap?new Map:{};if(J?.onCreate)J.onCreate(X);for(let W of this.items)Jq.addPairToJSMap(J,X,W);return X}toString($,J,Q){if(!$)return JSON.stringify(this);for(let X of this.items)if(!Q$.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 $q.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:Q,onComment:J})}}Wq.YAMLMap=P5;Wq.findPair=E2});var r$=C((Bq)=>{var qq=p(),S5=X$(),Hq={collection:"map",default:!0,nodeClass:S5.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,J){if(!qq.isMap($))J("Expected a mapping for this tag");return $},createNode:($,J,Q)=>S5.YAMLMap.from($,J,Q)};Bq.map=Hq});var W$=C((Mq)=>{var Vq=N2(),zq=L4(),Dq=C6(),d6=p(),Fq=W0(),Oq=t0();class E5 extends Dq.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(d6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let J=c6($);if(typeof J!=="number")return!1;return this.items.splice(J,1).length>0}get($,J){let Q=c6($);if(typeof Q!=="number")return;let X=this.items[Q];return!J&&d6.isScalar(X)?X.value:X}has($){let J=c6($);return typeof J==="number"&&J<this.items.length}set($,J){let Q=c6($);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${$}.`);let X=this.items[Q];if(d6.isScalar(X)&&Fq.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 W of this.items)Q.push(Oq.toJS(W,String(X++),J));return Q}toString($,J,Q){if(!$)return JSON.stringify(this);return zq.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:Q,onComment:J})}static from($,J,Q){let{replacer:X}=Q,W=new this($);if(J&&Symbol.iterator in Object(J)){let G=0;for(let Y of J){if(typeof X==="function"){let q=J instanceof Set?Y:String(G++);Y=X.call(J,q,Y)}W.items.push(Vq.createNode(Y,void 0,Q))}}return W}}function c6($){let J=d6.isScalar($)?$.value:$;if(J&&typeof J==="string")J=Number(J);return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:null}Mq.YAMLSeq=E5});var a$=C((Aq)=>{var Rq=p(),C5=W$(),Lq={collection:"seq",default:!0,nodeClass:C5.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,J){if(!Rq.isSeq($))J("Expected a sequence for this tag");return $},createNode:($,J,Q)=>C5.YAMLSeq.from($,J,Q)};Aq.seq=Lq});var C2=C((Zq)=>{var jq=b2(),Nq={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,J,Q,X){return J=Object.assign({actualString:!0},J),jq.stringifyString($,J,Q,X)}};Zq.string=Nq});var p6=C((bq)=>{var f5=W0(),T5={identify:($)=>$==null,createNode:()=>new f5.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new f5.Scalar(null),stringify:({source:$},J)=>typeof $==="string"&&T5.test.test($)?$:J.options.nullStr};bq.nullTag=T5});var A4=C((Eq)=>{var Sq=W0(),I5={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new Sq.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:J},Q){if($&&I5.test.test($)){let X=$[0]==="t"||$[0]==="T";if(J===X)return $}return J?Q.options.trueStr:Q.options.falseStr}};Eq.boolTag=I5});var s$=C((Tq)=>{function fq({format:$,minFractionDigits:J,tag:Q,value:X}){if(typeof X==="bigint")return String(X);let W=typeof X==="number"?X:Number(X);if(!isFinite(W))return isNaN(W)?".nan":W<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 Y=G.indexOf(".");if(Y<0)Y=G.length,G+=".";let q=J-(G.length-Y-1);while(q-- >0)G+="0"}return G}Tq.stringifyNumber=fq});var j4=C((gq)=>{var vq=W0(),_4=s$(),xq={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:_4.stringifyNumber},hq={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():_4.stringifyNumber($)}},yq={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let J=new vq.Scalar(parseFloat($)),Q=$.indexOf(".");if(Q!==-1&&$[$.length-1]==="0")J.minFractionDigits=$.length-Q-1;return J},stringify:_4.stringifyNumber};gq.float=yq;gq.floatExp=hq;gq.floatNaN=xq});var Z4=C((pq)=>{var v5=s$(),i6=($)=>typeof $==="bigint"||Number.isInteger($),N4=($,J,Q,{intAsBigInt:X})=>X?BigInt($):parseInt($.substring(J),Q);function x5($,J,Q){let{value:X}=$;if(i6(X)&&X>=0)return Q+X.toString(J);return v5.stringifyNumber($)}var lq={identify:($)=>i6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,J,Q)=>N4($,2,8,Q),stringify:($)=>x5($,8,"0o")},cq={identify:i6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,J,Q)=>N4($,0,10,Q),stringify:v5.stringifyNumber},dq={identify:($)=>i6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,J,Q)=>N4($,2,16,Q),stringify:($)=>x5($,16,"0x")};pq.int=cq;pq.intHex=dq;pq.intOct=lq});var h5=C((JH)=>{var aq=r$(),sq=p6(),oq=a$(),tq=C2(),eq=A4(),w4=j4(),b4=Z4(),$H=[aq.map,oq.seq,tq.string,sq.nullTag,eq.boolTag,b4.intOct,b4.int,b4.intHex,w4.floatNaN,w4.floatExp,w4.float];JH.schema=$H});var g5=C((BH)=>{var XH=W0(),WH=r$(),GH=a$();function y5($){return typeof $==="bigint"||Number.isInteger($)}var n6=({value:$})=>JSON.stringify($),YH=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:n6},{identify:($)=>$==null,createNode:()=>new XH.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:n6},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:n6},{identify:y5,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,J,{intAsBigInt:Q})=>Q?BigInt($):parseInt($,10),stringify:({value:$})=>y5($)?$.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:n6}],qH={default:!0,tag:"",test:/^/,resolve($,J){return J(`Unresolved plain scalar ${JSON.stringify($)}`),$}},HH=[WH.map,GH.seq].concat(YH,qH);BH.schema=HH});var S4=C((DH)=>{var f2=B6("buffer"),P4=W0(),VH=b2(),zH={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,J){if(typeof f2.Buffer==="function")return f2.Buffer.from($,"base64");else if(typeof atob==="function"){let Q=atob($.replace(/[\n\r]/g,"")),X=new Uint8Array(Q.length);for(let W=0;W<Q.length;++W)X[W]=Q.charCodeAt(W);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,W,G){if(!Q)return"";let Y=Q,q;if(typeof f2.Buffer==="function")q=Y instanceof f2.Buffer?Y.toString("base64"):f2.Buffer.from(Y.buffer).toString("base64");else if(typeof btoa==="function"){let H="";for(let B=0;B<Y.length;++B)H+=String.fromCharCode(Y[B]);q=btoa(H)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(J??(J=P4.Scalar.BLOCK_LITERAL),J!==P4.Scalar.QUOTE_DOUBLE){let H=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),B=Math.ceil(q.length/H),U=Array(B);for(let z=0,V=0;z<B;++z,V+=H)U[z]=q.substr(V,H);q=U.join(J===P4.Scalar.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return VH.stringifyString({comment:$,type:J,value:q},X,W,G)}};DH.binary=zH});var a6=C((RH)=>{var r6=p(),E4=J$(),OH=W0(),MH=W$();function k5($,J){if(r6.isSeq($))for(let Q=0;Q<$.items.length;++Q){let X=$.items[Q];if(r6.isPair(X))continue;else if(r6.isMap(X)){if(X.items.length>1)J("Each pair must have its own sequence indicator");let W=X.items[0]||new E4.Pair(new OH.Scalar(null));if(X.commentBefore)W.key.commentBefore=W.key.commentBefore?`${X.commentBefore}
|
|
54
54
|
${W.key.commentBefore}`:X.commentBefore;if(X.comment){let G=W.value??W.key;G.comment=G.comment?`${X.comment}
|
|
55
|
-
${G.comment}`:X.comment}X=W}$.items[Q]=r6.isPair(X)?X:new E4.Pair(X)}else J("Expected a sequence for this tag");return $}function k5($,J,Q){let{replacer:X}=Q,W=new DH.YAMLSeq($);W.tag="tag:yaml.org,2002:pairs";let G=0;if(J&&Symbol.iterator in Object(J))for(let Y of J){if(typeof X==="function")Y=X.call(J,String(G++),Y);let q,H;if(Array.isArray(Y))if(Y.length===2)q=Y[0],H=Y[1];else throw TypeError(`Expected [key, value] tuple: ${Y}`);else if(Y&&Y instanceof Object){let B=Object.keys(Y);if(B.length===1)q=B[0],H=Y[q];else throw TypeError(`Expected tuple with one key, not ${B.length} keys`)}else q=Y;W.items.push(E4.createPair(q,H,Q))}return W}var FH={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:g5,createNode:k5};OH.createPairs=k5;OH.pairs=FH;OH.resolvePairs=g5});var f4=C((_H)=>{var m5=p(),C4=t0(),T2=X$(),LH=W$(),u5=a6();class R$ extends LH.YAMLSeq{constructor(){super();this.add=T2.YAMLMap.prototype.add.bind(this),this.delete=T2.YAMLMap.prototype.delete.bind(this),this.get=T2.YAMLMap.prototype.get.bind(this),this.has=T2.YAMLMap.prototype.has.bind(this),this.set=T2.YAMLMap.prototype.set.bind(this),this.tag=R$.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 W,G;if(m5.isPair(X))W=C4.toJS(X.key,"",J),G=C4.toJS(X.value,W,J);else W=C4.toJS(X,"",J);if(Q.has(W))throw Error("Ordered maps must not include duplicate keys");Q.set(W,G)}return Q}static from($,J,Q){let X=u5.createPairs($,J,Q),W=new this;return W.items=X.items,W}}R$.tag="tag:yaml.org,2002:omap";var AH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:R$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=u5.resolvePairs($,J),X=[];for(let{key:W}of Q.items)if(m5.isScalar(W))if(X.includes(W.value))J(`Ordered maps must not include duplicate keys: ${W.value}`);else X.push(W.value);return Object.assign(new R$,Q)},createNode:($,J,Q)=>R$.from($,J,Q)};_H.YAMLOMap=R$;_H.omap=AH});var i5=C((ZH)=>{var l5=W0();function c5({value:$,source:J},Q){if(J&&($?d5:p5).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var d5={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new l5.Scalar(!0),stringify:c5},p5={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new l5.Scalar(!1),stringify:c5};ZH.falseTag=p5;ZH.trueTag=d5});var n5=C((fH)=>{var PH=W0(),T4=s$(),SH={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:T4.stringifyNumber},EH={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():T4.stringifyNumber($)}},CH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new PH.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:T4.stringifyNumber};fH.float=CH;fH.floatExp=EH;fH.floatNaN=SH});var a5=C((kH)=>{var r5=s$(),I2=($)=>typeof $==="bigint"||Number.isInteger($);function s6($,J,Q,{intAsBigInt:X}){let W=$[0];if(W==="-"||W==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let Y=BigInt($);return W==="-"?BigInt(-1)*Y:Y}let G=parseInt($,Q);return W==="-"?-1*G:G}function I4($,J,Q){let{value:X}=$;if(I2(X)){let W=X.toString(J);return X<0?"-"+Q+W.substr(1):Q+W}return r5.stringifyNumber($)}var xH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>s6($,2,2,Q),stringify:($)=>I4($,2,"0b")},hH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>s6($,1,8,Q),stringify:($)=>I4($,8,"0")},yH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>s6($,0,10,Q),stringify:r5.stringifyNumber},gH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>s6($,2,16,Q),stringify:($)=>I4($,16,"0x")};kH.int=yH;kH.intBin=xH;kH.intHex=gH;kH.intOct=hH});var v4=C((pH)=>{var e6=p(),o6=J$(),t6=X$();class L$ extends t6.YAMLMap{constructor($){super($);this.tag=L$.tag}add($){let J;if(e6.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new o6.Pair($.key,null);else J=new o6.Pair($,null);if(!t6.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=t6.findPair(this.items,$);return!J&&e6.isPair(Q)?e6.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=t6.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new o6.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,W=new this($);if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,G,G);W.items.push(o6.createPair(G,null,Q))}return W}}L$.tag="tag:yaml.org,2002:set";var dH={collection:"map",identify:($)=>$ instanceof Set,nodeClass:L$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>L$.from($,J,Q),resolve($,J){if(e6.isMap($))if($.hasAllNullValues(!0))return Object.assign(new L$,$);else J("Set items must all have null values");else J("Expected a mapping for this tag");return $}};pH.YAMLSet=L$;pH.set=dH});var h4=C((oH)=>{var rH=s$();function x4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,W=(Y)=>J?BigInt(Y):Number(Y),G=X.replace(/_/g,"").split(":").reduce((Y,q)=>Y*W(60)+W(q),W(0));return Q==="-"?W(-1)*G:G}function s5($){let{value:J}=$,Q=(Y)=>Y;if(typeof J==="bigint")Q=(Y)=>BigInt(Y);else if(isNaN(J)||!isFinite(J))return rH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let W=Q(60),G=[J%W];if(J<60)G.unshift(0);else if(J=(J-G[0])/W,G.unshift(J%W),J>=60)J=(J-G[0])/W,G.unshift(J);return X+G.map((Y)=>String(Y).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var aH={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})=>x4($,Q),stringify:s5},sH={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:($)=>x4($,!1),stringify:s5},o5={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(o5.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,W,G,Y,q]=J.map(Number),H=J[7]?Number((J[7]+"00").substr(1,3)):0,B=Date.UTC(Q,X-1,W,G||0,Y||0,q||0,H),U=J[8];if(U&&U!=="Z"){let z=x4(U,!1);if(Math.abs(z)<30)z*=60;B-=60000*z}return new Date(B)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};oH.floatTime=sH;oH.intTime=aH;oH.timestamp=o5});var e5=C((VB)=>{var JB=r$(),QB=p6(),XB=a$(),WB=C2(),GB=S4(),t5=i5(),y4=n5(),$9=a5(),YB=y6(),qB=f4(),HB=a6(),BB=v4(),g4=h4(),UB=[JB.map,XB.seq,WB.string,QB.nullTag,t5.trueTag,t5.falseTag,$9.intBin,$9.intOct,$9.int,$9.intHex,y4.floatNaN,y4.floatExp,y4.float,GB.binary,YB.merge,qB.omap,HB.pairs,BB.set,g4.intTime,g4.floatTime,g4.timestamp];VB.schema=UB});var BJ=C((AB)=>{var XJ=r$(),DB=p6(),WJ=a$(),FB=C2(),OB=A4(),k4=j4(),m4=Z4(),MB=x5(),KB=y5(),GJ=S4(),v2=y6(),YJ=f4(),qJ=a6(),$J=e5(),HJ=v4(),J9=h4(),JJ=new Map([["core",MB.schema],["failsafe",[XJ.map,WJ.seq,FB.string]],["json",KB.schema],["yaml11",$J.schema],["yaml-1.1",$J.schema]]),QJ={binary:GJ.binary,bool:OB.boolTag,float:k4.float,floatExp:k4.floatExp,floatNaN:k4.floatNaN,floatTime:J9.floatTime,int:m4.int,intHex:m4.intHex,intOct:m4.intOct,intTime:J9.intTime,map:XJ.map,merge:v2.merge,null:DB.nullTag,omap:YJ.omap,pairs:qJ.pairs,seq:WJ.seq,set:HJ.set,timestamp:J9.timestamp},RB={"tag:yaml.org,2002:binary":GJ.binary,"tag:yaml.org,2002:merge":v2.merge,"tag:yaml.org,2002:omap":YJ.omap,"tag:yaml.org,2002:pairs":qJ.pairs,"tag:yaml.org,2002:set":HJ.set,"tag:yaml.org,2002:timestamp":J9.timestamp};function LB($,J,Q){let X=JJ.get(J);if(X&&!$)return Q&&!X.includes(v2.merge)?X.concat(v2.merge):X.slice();let W=X;if(!W)if(Array.isArray($))W=[];else{let G=Array.from(JJ.keys()).filter((Y)=>Y!=="yaml11").map((Y)=>JSON.stringify(Y)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${G} or define customTags array`)}if(Array.isArray($))for(let G of $)W=W.concat(G);else if(typeof $==="function")W=$(W.slice());if(Q)W=W.concat(v2.merge);return W.reduce((G,Y)=>{let q=typeof Y==="string"?QJ[Y]:Y;if(!q){let H=JSON.stringify(Y),B=Object.keys(QJ).map((U)=>JSON.stringify(U)).join(", ");throw Error(`Unknown custom tag ${H}; use one of ${B}`)}if(!G.includes(q))G.push(q);return G},[])}AB.coreKnownTags=RB;AB.getTags=LB});var c4=C((PB)=>{var u4=p(),NB=r$(),ZB=a$(),wB=C2(),Q9=BJ(),bB=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class l4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:W,sortMapEntries:G,toStringDefaults:Y}){this.compat=Array.isArray($)?Q9.getTags($,"compat"):$?Q9.getTags(null,$):null,this.name=typeof W==="string"&&W||"core",this.knownTags=X?Q9.coreKnownTags:{},this.tags=Q9.getTags(J,this.name,Q),this.toStringOptions=Y??null,Object.defineProperty(this,u4.MAP,{value:NB.map}),Object.defineProperty(this,u4.SCALAR,{value:wB.string}),Object.defineProperty(this,u4.SEQ,{value:ZB.seq}),this.sortMapEntries=typeof G==="function"?G:G===!0?bB:null}clone(){let $=Object.create(l4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}PB.Schema=l4});var UJ=C((fB)=>{var EB=p(),d4=P2(),x2=Z2();function CB($,J){let Q=[],X=J.directives===!0;if(J.directives!==!1&&$.directives){let H=$.directives.toString($);if(H)Q.push(H),X=!0;else if($.directives.docStart)X=!0}if(X)Q.push("---");let W=d4.createStringifyContext($,J),{commentString:G}=W.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let H=G($.commentBefore);Q.unshift(x2.indentComment(H,""))}let Y=!1,q=null;if($.contents){if(EB.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let U=G($.contents.commentBefore);Q.push(x2.indentComment(U,""))}W.forceBlockIndent=!!$.comment,q=$.contents.comment}let H=q?void 0:()=>Y=!0,B=d4.stringify($.contents,W,()=>q=null,H);if(q)B+=x2.lineComment(B,"",G(q));if((B[0]==="|"||B[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${B}`;else Q.push(B)}else Q.push(d4.stringify($.contents,W));if($.directives?.docEnd)if($.comment){let H=G($.comment);if(H.includes(`
|
|
55
|
+
${G.comment}`:X.comment}X=W}$.items[Q]=r6.isPair(X)?X:new E4.Pair(X)}else J("Expected a sequence for this tag");return $}function m5($,J,Q){let{replacer:X}=Q,W=new MH.YAMLSeq($);W.tag="tag:yaml.org,2002:pairs";let G=0;if(J&&Symbol.iterator in Object(J))for(let Y of J){if(typeof X==="function")Y=X.call(J,String(G++),Y);let q,H;if(Array.isArray(Y))if(Y.length===2)q=Y[0],H=Y[1];else throw TypeError(`Expected [key, value] tuple: ${Y}`);else if(Y&&Y instanceof Object){let B=Object.keys(Y);if(B.length===1)q=B[0],H=Y[q];else throw TypeError(`Expected tuple with one key, not ${B.length} keys`)}else q=Y;W.items.push(E4.createPair(q,H,Q))}return W}var KH={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:k5,createNode:m5};RH.createPairs=m5;RH.pairs=KH;RH.resolvePairs=k5});var f4=C((ZH)=>{var u5=p(),C4=t0(),T2=X$(),jH=W$(),l5=a6();class R$ extends jH.YAMLSeq{constructor(){super();this.add=T2.YAMLMap.prototype.add.bind(this),this.delete=T2.YAMLMap.prototype.delete.bind(this),this.get=T2.YAMLMap.prototype.get.bind(this),this.has=T2.YAMLMap.prototype.has.bind(this),this.set=T2.YAMLMap.prototype.set.bind(this),this.tag=R$.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 W,G;if(u5.isPair(X))W=C4.toJS(X.key,"",J),G=C4.toJS(X.value,W,J);else W=C4.toJS(X,"",J);if(Q.has(W))throw Error("Ordered maps must not include duplicate keys");Q.set(W,G)}return Q}static from($,J,Q){let X=l5.createPairs($,J,Q),W=new this;return W.items=X.items,W}}R$.tag="tag:yaml.org,2002:omap";var NH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:R$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=l5.resolvePairs($,J),X=[];for(let{key:W}of Q.items)if(u5.isScalar(W))if(X.includes(W.value))J(`Ordered maps must not include duplicate keys: ${W.value}`);else X.push(W.value);return Object.assign(new R$,Q)},createNode:($,J,Q)=>R$.from($,J,Q)};ZH.YAMLOMap=R$;ZH.omap=NH});var n5=C((PH)=>{var c5=W0();function d5({value:$,source:J},Q){if(J&&($?p5:i5).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var p5={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new c5.Scalar(!0),stringify:d5},i5={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new c5.Scalar(!1),stringify:d5};PH.falseTag=i5;PH.trueTag=p5});var r5=C((vH)=>{var CH=W0(),T4=s$(),fH={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:T4.stringifyNumber},TH={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():T4.stringifyNumber($)}},IH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new CH.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:T4.stringifyNumber};vH.float=IH;vH.floatExp=TH;vH.floatNaN=fH});var s5=C((lH)=>{var a5=s$(),I2=($)=>typeof $==="bigint"||Number.isInteger($);function s6($,J,Q,{intAsBigInt:X}){let W=$[0];if(W==="-"||W==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let Y=BigInt($);return W==="-"?BigInt(-1)*Y:Y}let G=parseInt($,Q);return W==="-"?-1*G:G}function I4($,J,Q){let{value:X}=$;if(I2(X)){let W=X.toString(J);return X<0?"-"+Q+W.substr(1):Q+W}return a5.stringifyNumber($)}var gH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>s6($,2,2,Q),stringify:($)=>I4($,2,"0b")},kH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>s6($,1,8,Q),stringify:($)=>I4($,8,"0")},mH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>s6($,0,10,Q),stringify:a5.stringifyNumber},uH={identify:I2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>s6($,2,16,Q),stringify:($)=>I4($,16,"0x")};lH.int=mH;lH.intBin=gH;lH.intHex=uH;lH.intOct=kH});var v4=C((rH)=>{var e6=p(),o6=J$(),t6=X$();class L$ extends t6.YAMLMap{constructor($){super($);this.tag=L$.tag}add($){let J;if(e6.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new o6.Pair($.key,null);else J=new o6.Pair($,null);if(!t6.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=t6.findPair(this.items,$);return!J&&e6.isPair(Q)?e6.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=t6.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new o6.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,W=new this($);if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,G,G);W.items.push(o6.createPair(G,null,Q))}return W}}L$.tag="tag:yaml.org,2002:set";var nH={collection:"map",identify:($)=>$ instanceof Set,nodeClass:L$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>L$.from($,J,Q),resolve($,J){if(e6.isMap($))if($.hasAllNullValues(!0))return Object.assign(new L$,$);else J("Set items must all have null values");else J("Expected a mapping for this tag");return $}};rH.YAMLSet=L$;rH.set=nH});var h4=C(($B)=>{var oH=s$();function x4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,W=(Y)=>J?BigInt(Y):Number(Y),G=X.replace(/_/g,"").split(":").reduce((Y,q)=>Y*W(60)+W(q),W(0));return Q==="-"?W(-1)*G:G}function o5($){let{value:J}=$,Q=(Y)=>Y;if(typeof J==="bigint")Q=(Y)=>BigInt(Y);else if(isNaN(J)||!isFinite(J))return oH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let W=Q(60),G=[J%W];if(J<60)G.unshift(0);else if(J=(J-G[0])/W,G.unshift(J%W),J>=60)J=(J-G[0])/W,G.unshift(J);return X+G.map((Y)=>String(Y).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var tH={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})=>x4($,Q),stringify:o5},eH={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:($)=>x4($,!1),stringify:o5},t5={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(t5.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,W,G,Y,q]=J.map(Number),H=J[7]?Number((J[7]+"00").substr(1,3)):0,B=Date.UTC(Q,X-1,W,G||0,Y||0,q||0,H),U=J[8];if(U&&U!=="Z"){let z=x4(U,!1);if(Math.abs(z)<30)z*=60;B-=60000*z}return new Date(B)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};$B.floatTime=eH;$B.intTime=tH;$B.timestamp=t5});var $J=C((FB)=>{var WB=r$(),GB=p6(),YB=a$(),qB=C2(),HB=S4(),e5=n5(),y4=r5(),$9=s5(),BB=y6(),UB=f4(),VB=a6(),zB=v4(),g4=h4(),DB=[WB.map,YB.seq,qB.string,GB.nullTag,e5.trueTag,e5.falseTag,$9.intBin,$9.intOct,$9.int,$9.intHex,y4.floatNaN,y4.floatExp,y4.float,HB.binary,BB.merge,UB.omap,VB.pairs,zB.set,g4.intTime,g4.floatTime,g4.timestamp];FB.schema=DB});var UJ=C((NB)=>{var WJ=r$(),MB=p6(),GJ=a$(),KB=C2(),RB=A4(),k4=j4(),m4=Z4(),LB=h5(),AB=g5(),YJ=S4(),v2=y6(),qJ=f4(),HJ=a6(),JJ=$J(),BJ=v4(),J9=h4(),QJ=new Map([["core",LB.schema],["failsafe",[WJ.map,GJ.seq,KB.string]],["json",AB.schema],["yaml11",JJ.schema],["yaml-1.1",JJ.schema]]),XJ={binary:YJ.binary,bool:RB.boolTag,float:k4.float,floatExp:k4.floatExp,floatNaN:k4.floatNaN,floatTime:J9.floatTime,int:m4.int,intHex:m4.intHex,intOct:m4.intOct,intTime:J9.intTime,map:WJ.map,merge:v2.merge,null:MB.nullTag,omap:qJ.omap,pairs:HJ.pairs,seq:GJ.seq,set:BJ.set,timestamp:J9.timestamp},_B={"tag:yaml.org,2002:binary":YJ.binary,"tag:yaml.org,2002:merge":v2.merge,"tag:yaml.org,2002:omap":qJ.omap,"tag:yaml.org,2002:pairs":HJ.pairs,"tag:yaml.org,2002:set":BJ.set,"tag:yaml.org,2002:timestamp":J9.timestamp};function jB($,J,Q){let X=QJ.get(J);if(X&&!$)return Q&&!X.includes(v2.merge)?X.concat(v2.merge):X.slice();let W=X;if(!W)if(Array.isArray($))W=[];else{let G=Array.from(QJ.keys()).filter((Y)=>Y!=="yaml11").map((Y)=>JSON.stringify(Y)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${G} or define customTags array`)}if(Array.isArray($))for(let G of $)W=W.concat(G);else if(typeof $==="function")W=$(W.slice());if(Q)W=W.concat(v2.merge);return W.reduce((G,Y)=>{let q=typeof Y==="string"?XJ[Y]:Y;if(!q){let H=JSON.stringify(Y),B=Object.keys(XJ).map((U)=>JSON.stringify(U)).join(", ");throw Error(`Unknown custom tag ${H}; use one of ${B}`)}if(!G.includes(q))G.push(q);return G},[])}NB.coreKnownTags=_B;NB.getTags=jB});var c4=C((CB)=>{var u4=p(),bB=r$(),PB=a$(),SB=C2(),Q9=UJ(),EB=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class l4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:W,sortMapEntries:G,toStringDefaults:Y}){this.compat=Array.isArray($)?Q9.getTags($,"compat"):$?Q9.getTags(null,$):null,this.name=typeof W==="string"&&W||"core",this.knownTags=X?Q9.coreKnownTags:{},this.tags=Q9.getTags(J,this.name,Q),this.toStringOptions=Y??null,Object.defineProperty(this,u4.MAP,{value:bB.map}),Object.defineProperty(this,u4.SCALAR,{value:SB.string}),Object.defineProperty(this,u4.SEQ,{value:PB.seq}),this.sortMapEntries=typeof G==="function"?G:G===!0?EB:null}clone(){let $=Object.create(l4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}CB.Schema=l4});var VJ=C((vB)=>{var TB=p(),d4=P2(),x2=Z2();function IB($,J){let Q=[],X=J.directives===!0;if(J.directives!==!1&&$.directives){let H=$.directives.toString($);if(H)Q.push(H),X=!0;else if($.directives.docStart)X=!0}if(X)Q.push("---");let W=d4.createStringifyContext($,J),{commentString:G}=W.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let H=G($.commentBefore);Q.unshift(x2.indentComment(H,""))}let Y=!1,q=null;if($.contents){if(TB.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let U=G($.contents.commentBefore);Q.push(x2.indentComment(U,""))}W.forceBlockIndent=!!$.comment,q=$.contents.comment}let H=q?void 0:()=>Y=!0,B=d4.stringify($.contents,W,()=>q=null,H);if(q)B+=x2.lineComment(B,"",G(q));if((B[0]==="|"||B[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${B}`;else Q.push(B)}else Q.push(d4.stringify($.contents,W));if($.directives?.docEnd)if($.comment){let H=G($.comment);if(H.includes(`
|
|
56
56
|
`))Q.push("..."),Q.push(x2.indentComment(H,""));else Q.push(`... ${H}`)}else Q.push("...");else{let H=$.comment;if(H&&Y)H=H.replace(/^\n+/,"");if(H){if((!Y||q)&&Q[Q.length-1]!=="")Q.push("");Q.push(x2.indentComment(G(H),""))}}return Q.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
58
|
+
`}vB.stringifyDocument=IB});var h2=C((cB)=>{var hB=j2(),o$=C6(),R0=p(),yB=J$(),gB=t0(),kB=c4(),mB=VJ(),p4=P6(),uB=U4(),lB=N2(),i4=B4();class n4{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 W=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=W;let{version:G}=W;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)G=this.directives.yaml.version}else this.directives=new i4.Directives({version:G});this.setSchema(G,Q),this.contents=$===void 0?null:this.createNode($,X,Q)}clone(){let $=Object.create(n4.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(t$(this.contents))this.contents.add($)}addIn($,J){if(t$(this.contents))this.contents.addIn($,J)}createAlias($,J){if(!$.anchor){let Q=p4.anchorNames(this);$.anchor=!J||Q.has(J)?p4.findNewAnchor(J||"a",Q):J}return new hB.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,O=J.filter(D).map(String);if(O.length>0)J=J.concat(O);X=J}else if(Q===void 0&&J)Q=J,J=void 0;let{aliasDuplicateObjects:W,anchorPrefix:G,flow:Y,keepUndefined:q,onTagObj:H,tag:B}=Q??{},{onAnchor:U,setAnchors:z,sourceObjects:V}=p4.createNodeAnchors(this,G||"a"),M={aliasDuplicateObjects:W??!0,keepUndefined:q??!1,onAnchor:U,onTagObj:H,replacer:X,schema:this.schema,sourceObjects:V},F=lB.createNode($,B,M);if(Y&&R0.isCollection(F))F.flow=!0;return z(),F}createPair($,J,Q={}){let X=this.createNode($,null,Q),W=this.createNode(J,null,Q);return new yB.Pair(X,W)}delete($){return t$(this.contents)?this.contents.delete($):!1}deleteIn($){if(o$.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return t$(this.contents)?this.contents.deleteIn($):!1}get($,J){return R0.isCollection(this.contents)?this.contents.get($,J):void 0}getIn($,J){if(o$.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(o$.isEmptyPath($))return this.contents!==void 0;return R0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,J){if(this.contents==null)this.contents=o$.collectionFromPath(this.schema,[$],J);else if(t$(this.contents))this.contents.set($,J)}setIn($,J){if(o$.isEmptyPath($))this.contents=J;else if(this.contents==null)this.contents=o$.collectionFromPath(this.schema,Array.from($),J);else if(t$(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 i4.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 i4.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 kB.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:W,reviver:G}={}){let Y={anchors:new Map,doc:this,keep:!$,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},q=gB.toJS(this.contents,J??"",Y);if(typeof W==="function")for(let{count:H,res:B}of Y.anchors.values())W(B,H);return typeof G==="function"?uB.applyReviver(G,{"":q},"",q):q}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 mB.stringifyDocument(this,$)}}function t$($){if(R0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}cB.Document=n4});var y2=C((iB)=>{class X9 extends Error{constructor($,J,Q,X){super();this.name=$,this.code=Q,this.message=X,this.pos=J}}class zJ extends X9{constructor($,J,Q){super("YAMLParseError",$,J,Q)}}class DJ extends X9{constructor($,J,Q){super("YAMLWarning",$,J,Q)}}var pB=($,J)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((q)=>J.linePos(q));let{line:X,col:W}=Q.linePos[0];Q.message+=` at line ${X}, column ${W}`;let G=W-1,Y=$.substring(J.lineStarts[X-1],J.lineStarts[X]).replace(/[\n\r]+$/,"");if(G>=60&&Y.length>80){let q=Math.min(G-39,Y.length-79);Y="\u2026"+Y.substring(q),G-=q-1}if(Y.length>80)Y=Y.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(Y.substring(0,G))){let q=$.substring(J.lineStarts[X-2],J.lineStarts[X-1]);if(q.length>80)q=q.substring(0,79)+`\u2026
|
|
59
59
|
`;Y=q+Y}if(/[^ ]/.test(Y)){let q=1,H=Q.linePos[1];if(H?.line===X&&H.col>W)q=Math.max(1,Math.min(H.col-W,80-G));let B=" ".repeat(G)+"^".repeat(q);Q.message+=`:
|
|
60
60
|
|
|
61
61
|
${Y}
|
|
62
62
|
${B}
|
|
63
|
-
`}};
|
|
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(r4(J.key)||r4(J.value))return!0}return!1;default:return!0}}
|
|
65
|
-
`+D.comment;else q.comment=D.comment;continue}if(D.newlineAfterProp||
|
|
66
|
-
`+_.comment;else L.comment=_.comment;let Z=new
|
|
67
|
-
`+w.comment;else B.comment=w.comment;z=w.end;continue}if(!Y&&Q.options.strict&&
|
|
68
|
-
`+f;else N.comment=f;w.comment=w.comment.substring(f.length+1)}}}if(!Y&&!Z&&!w.found){let f=P?$(Q,P,w,W):J(Q,w.end,Z,null,w,W);if(B.items.push(f),z=f.range[2],t4(P))W(f.range,"BLOCK_IN_FLOW",o4)}else{Q.atKey=!0;let f=w.end,N=_?$(Q,_,w,W):J(Q,f,L,null,w,W);if(t4(_))W(N.range,"BLOCK_IN_FLOW",o4);Q.atKey=!1;let E=
|
|
69
|
-
`+E.comment;else N.comment=E.comment;let n=new
|
|
70
|
-
`+O.comment;else B.comment=O.comment;B.range=[X.offset,D,O.offset]}else B.range=[X.offset,D,D];return B}
|
|
63
|
+
`}};iB.YAMLError=X9;iB.YAMLParseError=zJ;iB.YAMLWarning=DJ;iB.prettifyError=pB});var g2=C((tB)=>{function oB($,{flow:J,indicator:Q,next:X,offset:W,onError:G,parentIndent:Y,startOnNewline:q}){let H=!1,B=q,U=q,z="",V="",M=!1,F=!1,D=null,O=null,R=null,L=null,_=null,Z=null,P=null;for(let N of $){if(F){if(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma")G(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");F=!1}if(D){if(B&&N.type!=="comment"&&N.type!=="newline")G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");D=null}switch(N.type){case"space":if(!J&&(Q!=="doc-start"||X?.type!=="flow-collection")&&N.source.includes("\t"))D=N;U=!0;break;case"comment":{if(!U)G(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=N.source.substring(1)||" ";if(!z)z=E;else z+=V+E;V="",B=!1;break}case"newline":if(B){if(z)z+=N.source;else if(!Z||Q!=="seq-item-ind")H=!0}else V+=N.source;if(B=!0,M=!0,O||R)L=N;U=!0;break;case"anchor":if(O)G(N,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(N.source.endsWith(":"))G(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);O=N,P??(P=N.offset),B=!1,U=!1,F=!0;break;case"tag":{if(R)G(N,"MULTIPLE_TAGS","A node can have at most one tag");R=N,P??(P=N.offset),B=!1,U=!1,F=!0;break}case Q:if(O||R)G(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`);if(Z)G(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${J??"collection"}`);Z=N,B=Q==="seq-item-ind"||Q==="explicit-key-ind",U=!1;break;case"comma":if(J){if(_)G(N,"UNEXPECTED_TOKEN",`Unexpected , in ${J}`);_=N,B=!1,U=!1;break}default:G(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),B=!1,U=!1}}let w=$[$.length-1],f=w?w.offset+w.source.length:W;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&&(B&&D.indent<=Y||X?.type==="block-map"||X?.type==="block-seq"))G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:_,found:Z,spaceBefore:H,comment:z,hasNewline:M,anchor:O,tag:R,newlineAfterProp:L,end:f,start:P??f}}tB.resolveProps=oB});var W9=C(($U)=>{function r4($){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(r4(J.key)||r4(J.value))return!0}return!1;default:return!0}}$U.containsNewline=r4});var a4=C((WU)=>{var QU=W9();function XU($,J,Q){if(J?.type==="flow-collection"){let X=J.end[0];if(X.indent===$&&(X.source==="]"||X.source==="}")&&QU.containsNewline(J))Q(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}WU.flowIndentCheck=XU});var s4=C((qU)=>{var FJ=p();function YU($,J,Q){let{uniqueKeys:X}=$.options;if(X===!1)return!1;let W=typeof X==="function"?X:(G,Y)=>G===Y||FJ.isScalar(G)&&FJ.isScalar(Y)&&G.value===Y.value;return J.some((G)=>W(G.key,Q))}qU.mapIncludes=YU});var LJ=C((DU)=>{var OJ=J$(),BU=X$(),MJ=g2(),UU=W9(),KJ=a4(),VU=s4(),RJ="All mapping items must start at the same column";function zU({composeNode:$,composeEmptyNode:J},Q,X,W,G){let q=new(G?.nodeClass??BU.YAMLMap)(Q.schema);if(Q.atRoot)Q.atRoot=!1;let H=X.offset,B=null;for(let U of X.items){let{start:z,key:V,sep:M,value:F}=U,D=MJ.resolveProps(z,{indicator:"explicit-key-ind",next:V??M?.[0],offset:H,onError:W,parentIndent:X.indent,startOnNewline:!0}),O=!D.found;if(O){if(V){if(V.type==="block-seq")W(H,"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)W(H,"BAD_INDENT",RJ)}if(!D.anchor&&!D.tag&&!M){if(B=D.end,D.comment)if(q.comment)q.comment+=`
|
|
65
|
+
`+D.comment;else q.comment=D.comment;continue}if(D.newlineAfterProp||UU.containsNewline(V))W(V??z[z.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(D.found?.indent!==X.indent)W(H,"BAD_INDENT",RJ);Q.atKey=!0;let R=D.end,L=V?$(Q,V,D,W):J(Q,R,z,null,D,W);if(Q.schema.compat)KJ.flowIndentCheck(X.indent,V,W);if(Q.atKey=!1,VU.mapIncludes(Q,q.items,L))W(R,"DUPLICATE_KEY","Map keys must be unique");let _=MJ.resolveProps(M??[],{indicator:"map-value-ind",next:F,offset:L.range[2],onError:W,parentIndent:X.indent,startOnNewline:!V||V.type==="block-scalar"});if(H=_.end,_.found){if(O){if(F?.type==="block-map"&&!_.hasNewline)W(H,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&D.start<_.found.offset-1024)W(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,_,W):J(Q,H,M,null,_,W);if(Q.schema.compat)KJ.flowIndentCheck(X.indent,F,W);H=Z.range[2];let P=new OJ.Pair(L,Z);if(Q.options.keepSourceTokens)P.srcToken=U;q.items.push(P)}else{if(O)W(L.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(_.comment)if(L.comment)L.comment+=`
|
|
66
|
+
`+_.comment;else L.comment=_.comment;let Z=new OJ.Pair(L);if(Q.options.keepSourceTokens)Z.srcToken=U;q.items.push(Z)}}if(B&&B<H)W(B,"IMPOSSIBLE","Map comment with trailing content");return q.range=[X.offset,H,B??H],q}DU.resolveBlockMap=zU});var AJ=C((LU)=>{var OU=W$(),MU=g2(),KU=a4();function RU({composeNode:$,composeEmptyNode:J},Q,X,W,G){let q=new(G?.nodeClass??OU.YAMLSeq)(Q.schema);if(Q.atRoot)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let H=X.offset,B=null;for(let{start:U,value:z}of X.items){let V=MU.resolveProps(U,{indicator:"seq-item-ind",next:z,offset:H,onError:W,parentIndent:X.indent,startOnNewline:!0});if(!V.found)if(V.anchor||V.tag||z)if(z?.type==="block-seq")W(V.end,"BAD_INDENT","All sequence items must start at the same column");else W(H,"MISSING_CHAR","Sequence item without - indicator");else{if(B=V.end,V.comment)q.comment=V.comment;continue}let M=z?$(Q,z,V,W):J(Q,V.end,U,null,V,W);if(Q.schema.compat)KU.flowIndentCheck(X.indent,z,W);H=M.range[2],q.items.push(M)}return q.range=[X.offset,H,B??H],q}LU.resolveBlockSeq=RU});var e$=C((jU)=>{function _U($,J,Q,X){let W="";if($){let G=!1,Y="";for(let q of $){let{source:H,type:B}=q;switch(B){case"space":G=!0;break;case"comment":{if(Q&&!G)X(q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let U=H.substring(1)||" ";if(!W)W=U;else W+=Y+U;Y="";break}case"newline":if(W)Y+=H;G=!0;break;default:X(q,"UNEXPECTED_TOKEN",`Unexpected ${B} at node end`)}J+=H.length}}return{comment:W,offset:J}}jU.resolveEnd=_U});var NJ=C((fU)=>{var ZU=p(),wU=J$(),_J=X$(),bU=W$(),PU=e$(),jJ=g2(),SU=W9(),EU=s4(),o4="Block collections are not allowed within flow collections",t4=($)=>$&&($.type==="block-map"||$.type==="block-seq");function CU({composeNode:$,composeEmptyNode:J},Q,X,W,G){let Y=X.start.source==="{",q=Y?"flow map":"flow sequence",B=new(G?.nodeClass??(Y?_J.YAMLMap:bU.YAMLSeq))(Q.schema);B.flow=!0;let U=Q.atRoot;if(U)Q.atRoot=!1;if(Q.atKey)Q.atKey=!1;let z=X.offset+X.start.source.length;for(let O=0;O<X.items.length;++O){let R=X.items[O],{start:L,key:_,sep:Z,value:P}=R,w=jJ.resolveProps(L,{flow:q,indicator:"explicit-key-ind",next:_??Z?.[0],offset:z,onError:W,parentIndent:X.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!Z&&!P){if(O===0&&w.comma)W(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`);else if(O<X.items.length-1)W(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${q}`);if(w.comment)if(B.comment)B.comment+=`
|
|
67
|
+
`+w.comment;else B.comment=w.comment;z=w.end;continue}if(!Y&&Q.options.strict&&SU.containsNewline(_))W(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(O===0){if(w.comma)W(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`)}else{if(!w.comma)W(w.start,"MISSING_CHAR",`Missing , between ${q} items`);if(w.comment){let f="";$:for(let N of L)switch(N.type){case"comma":case"space":break;case"comment":f=N.source.substring(1);break $;default:break $}if(f){let N=B.items[B.items.length-1];if(ZU.isPair(N))N=N.value??N.key;if(N.comment)N.comment+=`
|
|
68
|
+
`+f;else N.comment=f;w.comment=w.comment.substring(f.length+1)}}}if(!Y&&!Z&&!w.found){let f=P?$(Q,P,w,W):J(Q,w.end,Z,null,w,W);if(B.items.push(f),z=f.range[2],t4(P))W(f.range,"BLOCK_IN_FLOW",o4)}else{Q.atKey=!0;let f=w.end,N=_?$(Q,_,w,W):J(Q,f,L,null,w,W);if(t4(_))W(N.range,"BLOCK_IN_FLOW",o4);Q.atKey=!1;let E=jJ.resolveProps(Z??[],{flow:q,indicator:"map-value-ind",next:P,offset:N.range[2],onError:W,parentIndent:X.indent,startOnNewline:!1});if(E.found){if(!Y&&!w.found&&Q.options.strict){if(Z)for(let g of Z){if(g===E.found)break;if(g.type==="newline"){W(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(w.start<E.found.offset-1024)W(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(P)if("source"in P&&P.source?.[0]===":")W(P,"MISSING_CHAR",`Missing space after : in ${q}`);else W(E.start,"MISSING_CHAR",`Missing , or : between ${q} items`);let x=P?$(Q,P,E,W):E.found?J(Q,E.end,Z,null,E,W):null;if(x){if(t4(P))W(x.range,"BLOCK_IN_FLOW",o4)}else if(E.comment)if(N.comment)N.comment+=`
|
|
69
|
+
`+E.comment;else N.comment=E.comment;let n=new wU.Pair(N,x);if(Q.options.keepSourceTokens)n.srcToken=R;if(Y){let g=B;if(EU.mapIncludes(Q,g.items,N))W(f,"DUPLICATE_KEY","Map keys must be unique");g.items.push(n)}else{let g=new _J.YAMLMap(Q.schema);g.flow=!0,g.items.push(n);let c=(x??N).range;g.range=[N.range[0],c[1],c[2]],B.items.push(g)}z=x?x.range[2]:E.end}}let V=Y?"}":"]",[M,...F]=X.end,D=z;if(M?.source===V)D=M.offset+M.source.length;else{let O=q[0].toUpperCase()+q.substring(1),R=U?`${O} must end with a ${V}`:`${O} in block collection must be sufficiently indented and end with a ${V}`;if(W(z,U?"MISSING_CHAR":"BAD_INDENT",R),M&&M.source.length!==1)F.unshift(M)}if(F.length>0){let O=PU.resolveEnd(F,D,Q.options.strict,W);if(O.comment)if(B.comment)B.comment+=`
|
|
70
|
+
`+O.comment;else B.comment=O.comment;B.range=[X.offset,D,O.offset]}else B.range=[X.offset,D,D];return B}fU.resolveFlowCollection=CU});var ZJ=C((uU)=>{var IU=p(),vU=W0(),xU=X$(),hU=W$(),yU=LJ(),gU=AJ(),kU=NJ();function e4($,J,Q,X,W,G){let Y=Q.type==="block-map"?yU.resolveBlockMap($,J,Q,X,G):Q.type==="block-seq"?gU.resolveBlockSeq($,J,Q,X,G):kU.resolveFlowCollection($,J,Q,X,G),q=Y.constructor;if(W==="!"||W===q.tagName)return Y.tag=q.tagName,Y;if(W)Y.tag=W;return Y}function mU($,J,Q,X,W){let G=X.tag,Y=!G?null:J.directives.tagName(G.source,(V)=>W(G,"TAG_RESOLVE_FAILED",V));if(Q.type==="block-seq"){let{anchor:V,newlineAfterProp:M}=X,F=V&&G?V.offset>G.offset?V:G:V??G;if(F&&(!M||M.offset<F.offset))W(F,"MISSING_CHAR","Missing newline after block sequence props")}let q=Q.type==="block-map"?"map":Q.type==="block-seq"?"seq":Q.start.source==="{"?"map":"seq";if(!G||!Y||Y==="!"||Y===xU.YAMLMap.tagName&&q==="map"||Y===hU.YAMLSeq.tagName&&q==="seq")return e4($,J,Q,W,Y);let H=J.schema.tags.find((V)=>V.tag===Y&&V.collection===q);if(!H){let V=J.schema.knownTags[Y];if(V?.collection===q)J.schema.tags.push(Object.assign({},V,{default:!1})),H=V;else{if(V)W(G,"BAD_COLLECTION_TYPE",`${V.tag} used for ${q} collection, but expects ${V.collection??"scalar"}`,!0);else W(G,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Y}`,!0);return e4($,J,Q,W,Y)}}let B=e4($,J,Q,W,Y,H),U=H.resolve?.(B,(V)=>W(G,"TAG_RESOLVE_FAILED",V),J.options)??B,z=IU.isNode(U)?U:new vU.Scalar(U);if(z.range=B.range,z.tag=Y,H?.format)z.format=H.format;return z}uU.composeCollection=mU});var J8=C((iU)=>{var $8=W0();function cU($,J,Q){let X=J.offset,W=dU(J,$.options.strict,Q);if(!W)return{value:"",type:null,comment:"",range:[X,X,X]};let G=W.mode===">"?$8.Scalar.BLOCK_FOLDED:$8.Scalar.BLOCK_LITERAL,Y=J.source?pU(J.source):[],q=Y.length;for(let D=Y.length-1;D>=0;--D){let O=Y[D][1];if(O===""||O==="\r")q=D;else break}if(q===0){let D=W.chomp==="+"&&Y.length>0?`
|
|
71
71
|
`.repeat(Math.max(1,Y.length-1)):"",O=X+W.length;if(J.source)O+=J.source.length;return{value:D,type:G,comment:W.comment,range:[X,O,O]}}let H=J.indent+W.indent,B=J.offset+W.length,U=0;for(let D=0;D<q;++D){let[O,R]=Y[D];if(R===""||R==="\r"){if(W.indent===0&&O.length>H)H=O.length}else{if(O.length<H)Q(B+O.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(W.indent===0)H=O.length;if(U=D,H===0&&!$.atRoot)Q(B,"BAD_INDENT","Block scalar values in collections must be indented");break}B+=O.length+R.length+1}for(let D=Y.length-1;D>=q;--D)if(Y[D][0].length>H)q=D+1;let z="",V="",M=!1;for(let D=0;D<U;++D)z+=Y[D][0].slice(H)+`
|
|
72
72
|
`;for(let D=U;D<q;++D){let[O,R]=Y[D];B+=O.length+R.length+1;let L=R[R.length-1]==="\r";if(L)R=R.slice(0,-1);if(R&&O.length<H){let Z=`Block scalar lines must not be less indented than their ${W.indent?"explicit indentation indicator":"first line"}`;Q(B-R.length-(L?2:1),"BAD_INDENT",Z),O=""}if(G===$8.Scalar.BLOCK_LITERAL)z+=V+O.slice(H)+R,V=`
|
|
73
73
|
`;else if(O.length>H||R[0]==="\t"){if(V===" ")V=`
|
|
@@ -82,39 +82,39 @@ ${B}
|
|
|
82
82
|
`+Y[D][0].slice(H);if(z[z.length-1]!==`
|
|
83
83
|
`)z+=`
|
|
84
84
|
`;break;default:z+=`
|
|
85
|
-
`}let F=X+W.length+J.source.length;return{value:z,type:G,comment:W.comment,range:[X,F,F]}}function
|
|
85
|
+
`}let F=X+W.length+J.source.length;return{value:z,type:G,comment:W.comment,range:[X,F,F]}}function dU({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:W}=J[0],G=W[0],Y=0,q="",H=-1;for(let V=1;V<W.length;++V){let M=W[V];if(!q&&(M==="-"||M==="+"))q=M;else{let F=Number(M);if(!Y&&F)Y=F;else if(H===-1)H=$+V}}if(H!==-1)X(H,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${W}`);let B=!1,U="",z=W.length;for(let V=1;V<J.length;++V){let M=J[V];switch(M.type){case"space":B=!0;case"newline":z+=M.source.length;break;case"comment":if(Q&&!B)X(M,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");z+=M.source.length,U=M.source.substring(1);break;case"error":X(M,"UNEXPECTED_TOKEN",M.message),z+=M.source.length;break;default:{let F=`Unexpected token in block scalar header: ${M.type}`;X(M,"UNEXPECTED_TOKEN",F);let D=M.source;if(D&&typeof D==="string")z+=D.length}}}return{mode:G,indent:Y,chomp:q,comment:U,length:z}}function pU($){let J=$.split(/\n( *)/),Q=J[0],X=Q.match(/^( *)/),G=[X?.[1]?[X[1],Q.slice(X[1].length)]:["",Q]];for(let Y=1;Y<J.length;Y+=2)G.push([J[Y],J[Y+1]]);return G}iU.resolveBlockScalar=cU});var X8=C((QV)=>{var Q8=W0(),rU=e$();function aU($,J,Q){let{offset:X,type:W,source:G,end:Y}=$,q,H,B=(V,M,F)=>Q(X+V,M,F);switch(W){case"scalar":q=Q8.Scalar.PLAIN,H=sU(G,B);break;case"single-quoted-scalar":q=Q8.Scalar.QUOTE_SINGLE,H=oU(G,B);break;case"double-quoted-scalar":q=Q8.Scalar.QUOTE_DOUBLE,H=tU(G,B);break;default:return Q($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${W}`),{value:"",type:null,comment:"",range:[X,X+G.length,X+G.length]}}let U=X+G.length,z=rU.resolveEnd(Y,U,J,Q);return{value:H,type:q,comment:z.comment,range:[X,U,z.offset]}}function sU($,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 wJ($)}function oU($,J){if($[$.length-1]!=="'"||$.length===1)J($.length,"MISSING_CHAR","Missing closing 'quote");return wJ($.slice(1,-1)).replace(/''/g,"'")}function wJ($){let J=/(.*?)\r?\n/sy,Q=J.exec($);if(!Q)return $;let X,W;try{X=new RegExp("(?<![ \t])[ \t]+$"),W=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,W=/^[ \t]+|[ \t]+$/g}let G=Q[1].replace(X,""),Y=" ",q=J.lastIndex;while(Q=J.exec($)){let B=Q[1].replace(W,"");if(B==="")if(Y===`
|
|
86
86
|
`)G+=Y;else Y=`
|
|
87
|
-
`;else G+=Y+B,Y=" ";q=J.lastIndex}let H=/[ \t]*(.*)/sy;return H.lastIndex=q,Q=H.exec($),G+Y+(Q?.[1]??"")}function
|
|
87
|
+
`;else G+=Y+B,Y=" ";q=J.lastIndex}let H=/[ \t]*(.*)/sy;return H.lastIndex=q,Q=H.exec($),G+Y+(Q?.[1]??"")}function tU($,J){let Q="";for(let X=1;X<$.length-1;++X){let W=$[X];if(W==="\r"&&$[X+1]===`
|
|
88
88
|
`)continue;if(W===`
|
|
89
|
-
`){let{fold:G,offset:Y}=
|
|
89
|
+
`){let{fold:G,offset:Y}=eU($,X);Q+=G,X=Y}else if(W==="\\"){let G=$[++X],Y=$V[G];if(Y)Q+=Y;else if(G===`
|
|
90
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 q=G==="x"?2:G==="u"?4:8;Q+=
|
|
91
|
+
`){G=$[++X+1];while(G===" "||G==="\t")G=$[++X+1]}else if(G==="x"||G==="u"||G==="U"){let q=G==="x"?2:G==="u"?4:8;Q+=JV($,X+1,q,J),X+=q}else{let q=$.substr(X-1,2);J(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${q}`),Q+=q}}else if(W===" "||W==="\t"){let G=X,Y=$[X+1];while(Y===" "||Y==="\t")Y=$[++X+1];if(Y!==`
|
|
92
92
|
`&&!(Y==="\r"&&$[X+2]===`
|
|
93
|
-
`))Q+=X>G?$.slice(G,X+1):W}else Q+=W}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function
|
|
93
|
+
`))Q+=X>G?$.slice(G,X+1):W}else Q+=W}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function eU($,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
|
|
98
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
97
|
+
`;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var $V={"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 JV($,J,Q,X){let W=$.substr(J,Q),Y=W.length===Q&&/^[0-9a-fA-F]+$/.test(W)?parseInt(W,16):NaN;try{return String.fromCodePoint(Y)}catch{let q=$.substr(J-2,Q+2);return X(J-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${q}`),q}}QV.resolveFlowScalar=aU});var PJ=C((BV)=>{var A$=p(),bJ=W0(),WV=J8(),GV=X8();function YV($,J,Q,X){let{value:W,type:G,comment:Y,range:q}=J.type==="block-scalar"?WV.resolveBlockScalar($,J,X):GV.resolveFlowScalar(J,$.options.strict,X),H=Q?$.directives.tagName(Q.source,(z)=>X(Q,"TAG_RESOLVE_FAILED",z)):null,B;if($.options.stringKeys&&$.atKey)B=$.schema[A$.SCALAR];else if(H)B=qV($.schema,W,H,Q,X);else if(J.type==="scalar")B=HV($,W,J,X);else B=$.schema[A$.SCALAR];let U;try{let z=B.resolve(W,(V)=>X(Q??J,"TAG_RESOLVE_FAILED",V),$.options);U=A$.isScalar(z)?z:new bJ.Scalar(z)}catch(z){let V=z instanceof Error?z.message:String(z);X(Q??J,"TAG_RESOLVE_FAILED",V),U=new bJ.Scalar(W)}if(U.range=q,U.source=W,G)U.type=G;if(H)U.tag=H;if(B.format)U.format=B.format;if(Y)U.comment=Y;return U}function qV($,J,Q,X,W){if(Q==="!")return $[A$.SCALAR];let G=[];for(let q of $.tags)if(!q.collection&&q.tag===Q)if(q.default&&q.test)G.push(q);else return q;for(let q of G)if(q.test?.test(J))return q;let Y=$.knownTags[Q];if(Y&&!Y.collection)return $.tags.push(Object.assign({},Y,{default:!1,test:void 0})),Y;return W(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),$[A$.SCALAR]}function HV({atKey:$,directives:J,schema:Q},X,W,G){let Y=Q.tags.find((q)=>(q.default===!0||$&&q.default==="key")&&q.test?.test(X))||Q[A$.SCALAR];if(Q.compat){let q=Q.compat.find((H)=>H.default&&H.test?.test(X))??Q[A$.SCALAR];if(Y.tag!==q.tag){let H=J.tagString(Y.tag),B=J.tagString(q.tag),U=`Value may be parsed as either ${H} or ${B}`;G(W,"TAG_RESOLVE_FAILED",U,!0)}}return Y}BV.composeScalar=YV});var SJ=C((zV)=>{function VV($,J,Q){if(J){Q??(Q=J.length);for(let X=Q-1;X>=0;--X){let W=J[X];switch(W.type){case"space":case"comment":case"newline":$-=W.source.length;continue}W=J[++X];while(W?.type==="space")$+=W.source.length,W=J[++X];break}}return $}zV.emptyScalarPosition=VV});var fJ=C((_V)=>{var FV=j2(),OV=p(),MV=ZJ(),EJ=PJ(),KV=e$(),RV=SJ(),LV={composeNode:CJ,composeEmptyNode:W8};function CJ($,J,Q,X){let W=$.atKey,{spaceBefore:G,comment:Y,anchor:q,tag:H}=Q,B,U=!0;switch(J.type){case"alias":if(B=AV($,J,X),q||H)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(B=EJ.composeScalar($,J,H,X),q)B.anchor=q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(B=MV.composeCollection(LV,$,J,Q,X),q)B.anchor=q.source.substring(1)}catch(z){let V=z instanceof Error?z.message:String(z);X(J,"RESOURCE_EXHAUSTION",V)}break;default:{let z=J.type==="error"?J.message:`Unsupported token (type: ${J.type})`;X(J,"UNEXPECTED_TOKEN",z),U=!1}}if(B??(B=W8($,J.offset,void 0,null,Q,X)),q&&B.anchor==="")X(q,"BAD_ALIAS","Anchor cannot be an empty string");if(W&&$.options.stringKeys&&(!OV.isScalar(B)||typeof B.value!=="string"||B.tag&&B.tag!=="tag:yaml.org,2002:str"))X(H??J,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(G)B.spaceBefore=!0;if(Y)if(J.type==="scalar"&&J.source==="")B.comment=Y;else B.commentBefore=Y;if($.options.keepSourceTokens&&U)B.srcToken=J;return B}function W8($,J,Q,X,{spaceBefore:W,comment:G,anchor:Y,tag:q,end:H},B){let U={type:"scalar",offset:RV.emptyScalarPosition(J,Q,X),indent:-1,source:""},z=EJ.composeScalar($,U,q,B);if(Y){if(z.anchor=Y.source.substring(1),z.anchor==="")B(Y,"BAD_ALIAS","Anchor cannot be an empty string")}if(W)z.spaceBefore=!0;if(G)z.comment=G,z.range[2]=H;return z}function AV({options:$},{offset:J,source:Q,end:X},W){let G=new FV.Alias(Q.substring(1));if(G.source==="")W(J,"BAD_ALIAS","Alias cannot be an empty string");if(G.source.endsWith(":"))W(J+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let Y=J+Q.length,q=KV.resolveEnd(X,Y,$.strict,W);if(G.range=[J,Y,q.offset],q.comment)G.comment=q.comment;return G}_V.composeEmptyNode=W8;_V.composeNode=CJ});var IJ=C((SV)=>{var ZV=h2(),TJ=fJ(),wV=e$(),bV=g2();function PV($,J,{offset:Q,start:X,value:W,end:G},Y){let q=Object.assign({_directives:J},$),H=new ZV.Document(void 0,q),B={atKey:!1,atRoot:!0,directives:H.directives,options:H.options,schema:H.schema},U=bV.resolveProps(X,{indicator:"doc-start",next:W??G?.[0],offset:Q,onError:Y,parentIndent:0,startOnNewline:!0});if(U.found){if(H.directives.docStart=!0,W&&(W.type==="block-map"||W.type==="block-seq")&&!U.hasNewline)Y(U.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}H.contents=W?TJ.composeNode(B,W,U,Y):TJ.composeEmptyNode(B,U.end,X,null,U,Y);let z=H.contents.range[2],V=wV.resolveEnd(G,z,!1,Y);if(V.comment)H.comment=V.comment;return H.range=[Q,z,V.offset],H}SV.composeDoc=PV});var G8=C((xV)=>{var CV=B6("process"),fV=B4(),TV=h2(),k2=y2(),vJ=p(),IV=IJ(),vV=e$();function m2($){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 xJ($){let J="",Q=!1,X=!1;for(let W=0;W<$.length;++W){let G=$[W];switch(G[0]){case"#":J+=(J===""?"":X?`
|
|
99
99
|
|
|
100
100
|
`:`
|
|
101
|
-
`)+(G.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[W+1]?.[0]!=="#")W+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class
|
|
102
|
-
${Q}`:Q;else if(X||$.directives.docStart||!W)$.commentBefore=Q;else if(
|
|
101
|
+
`)+(G.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[W+1]?.[0]!=="#")W+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class hJ{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(J,Q,X,W)=>{let G=m2(J);if(W)this.warnings.push(new k2.YAMLWarning(G,Q,X));else this.errors.push(new k2.YAMLParseError(G,Q,X))},this.directives=new fV.Directives({version:$.version||"1.2"}),this.options=$}decorate($,J){let{comment:Q,afterEmptyLine:X}=xJ(this.prelude);if(Q){let W=$.contents;if(J)$.comment=$.comment?`${$.comment}
|
|
102
|
+
${Q}`:Q;else if(X||$.directives.docStart||!W)$.commentBefore=Q;else if(vJ.isCollection(W)&&!W.flow&&W.items.length>0){let G=W.items[0];if(vJ.isPair(G))G=G.key;let Y=G.commentBefore;G.commentBefore=Y?`${Q}
|
|
103
103
|
${Y}`:Q}else{let G=W.commentBefore;W.commentBefore=G?`${Q}
|
|
104
|
-
${G}`:Q}}if(J){for(let W=0;W<this.errors.length;++W)$.errors.push(this.errors[W]);for(let W=0;W<this.warnings.length;++W)$.warnings.push(this.warnings[W])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
105
|
-
${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.push(new k2.YAMLParseError(m2($),"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
|
|
104
|
+
${G}`:Q}}if(J){for(let W=0;W<this.errors.length;++W)$.errors.push(this.errors[W]);for(let W=0;W<this.warnings.length;++W)$.warnings.push(this.warnings[W])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:xJ(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(CV.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(J,Q,X)=>{let W=m2($);W[0]+=J,this.onError(W,"BAD_DIRECTIVE",Q,X)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let J=IV.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 k2.YAMLParseError(m2($),"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 k2.YAMLParseError(m2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let J=vV.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 k2.YAMLParseError(m2($),"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 TV.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}}}xV.Composer=hJ});var kJ=C((dV)=>{var yV=J8(),gV=X8(),kV=y2(),yJ=b2();function mV($,J=!0,Q){if($){let X=(W,G,Y)=>{let q=typeof W==="number"?W:Array.isArray(W)?W[0]:W.offset;if(Q)Q(q,G,Y);else throw new kV.YAMLParseError([q,q+1],G,Y)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return gV.resolveFlowScalar($,J,X);case"block-scalar":return yV.resolveBlockScalar({options:{strict:J}},$,X)}}return null}function uV($,J){let{implicitKey:Q=!1,indent:X,inFlow:W=!1,offset:G=-1,type:Y="PLAIN"}=J,q=yJ.stringifyString({type:Y,value:$},{implicitKey:Q,indent:X>0?" ".repeat(X):"",inFlow:W,options:{blockQuote:!0,lineWidth:-1}}),H=J.end??[{type:"newline",offset:-1,indent:X,source:`
|
|
106
106
|
`}];switch(q[0]){case"|":case">":{let B=q.indexOf(`
|
|
107
107
|
`),U=q.substring(0,B),z=q.substring(B+1)+`
|
|
108
|
-
`,V=[{type:"block-scalar-header",offset:G,indent:X,source:U}];if(!
|
|
109
|
-
`});return{type:"block-scalar",offset:G,indent:X,props:V,source:z}}case'"':return{type:"double-quoted-scalar",offset:G,indent:X,source:q,end:H};case"'":return{type:"single-quoted-scalar",offset:G,indent:X,source:q,end:H};default:return{type:"scalar",offset:G,indent:X,source:q,end:H}}}function
|
|
108
|
+
`,V=[{type:"block-scalar-header",offset:G,indent:X,source:U}];if(!gJ(V,H))V.push({type:"newline",offset:-1,indent:X,source:`
|
|
109
|
+
`});return{type:"block-scalar",offset:G,indent:X,props:V,source:z}}case'"':return{type:"double-quoted-scalar",offset:G,indent:X,source:q,end:H};case"'":return{type:"single-quoted-scalar",offset:G,indent:X,source:q,end:H};default:return{type:"scalar",offset:G,indent:X,source:q,end:H}}}function lV($,J,Q={}){let{afterKey:X=!1,implicitKey:W=!1,inFlow:G=!1,type:Y}=Q,q="indent"in $?$.indent:null;if(X&&typeof q==="number")q+=2;if(!Y)switch($.type){case"single-quoted-scalar":Y="QUOTE_SINGLE";break;case"double-quoted-scalar":Y="QUOTE_DOUBLE";break;case"block-scalar":{let B=$.props[0];if(B.type!=="block-scalar-header")throw Error("Invalid block scalar header");Y=B.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:Y="PLAIN"}let H=yJ.stringifyString({type:Y,value:J},{implicitKey:W||q===null,indent:q!==null&&q>0?" ".repeat(q):"",inFlow:G,options:{blockQuote:!0,lineWidth:-1}});switch(H[0]){case"|":case">":cV($,H);break;case'"':Y8($,H,"double-quoted-scalar");break;case"'":Y8($,H,"single-quoted-scalar");break;default:Y8($,H,"scalar")}}function cV($,J){let Q=J.indexOf(`
|
|
110
110
|
`),X=J.substring(0,Q),W=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=W}else{let{offset:G}=$,Y="indent"in $?$.indent:-1,q=[{type:"block-scalar-header",offset:G,indent:Y,source:X}];if(!
|
|
112
|
-
`});for(let H of Object.keys($))if(H!=="type"&&H!=="offset")delete $[H];Object.assign($,{type:"block-scalar",indent:Y,props:q,source:W})}}function
|
|
113
|
-
`};delete $.items,Object.assign($,{type:Q,source:J,end:[W]});break}default:{let X="indent"in $?$.indent:-1,W="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:W})}}}
|
|
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=W}else{let{offset:G}=$,Y="indent"in $?$.indent:-1,q=[{type:"block-scalar-header",offset:G,indent:Y,source:X}];if(!gJ(q,"end"in $?$.end:void 0))q.push({type:"newline",offset:-1,indent:Y,source:`
|
|
112
|
+
`});for(let H of Object.keys($))if(H!=="type"&&H!=="offset")delete $[H];Object.assign($,{type:"block-scalar",indent:Y,props:q,source:W})}}function gJ($,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 Y8($,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),W=J.length;if($.props[0].type==="block-scalar-header")W-=$.props[0].source.length;for(let G of X)G.offset+=W;delete $.props,Object.assign($,{type:Q,source:J,end:X});break}case"block-map":case"block-seq":{let W={type:"newline",offset:$.offset+J.length,indent:$.indent,source:`
|
|
113
|
+
`};delete $.items,Object.assign($,{type:Q,source:J,end:[W]});break}default:{let X="indent"in $?$.indent:-1,W="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:W})}}}dV.createScalarToken=uV;dV.resolveAsScalar=mV;dV.setScalarValue=lV});var mJ=C((aV)=>{var rV=($)=>("type"in $)?Y9($):G9($);function Y9($){switch($.type){case"block-scalar":{let J="";for(let Q of $.props)J+=Y9(Q);return J+$.source}case"block-map":case"block-seq":{let J="";for(let Q of $.items)J+=G9(Q);return J}case"flow-collection":{let J=$.start.source;for(let Q of $.items)J+=G9(Q);for(let Q of $.end)J+=Q.source;return J}case"document":{let J=G9($);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 G9({start:$,key:J,sep:Q,value:X}){let W="";for(let G of $)W+=G.source;if(J)W+=Y9(J);if(Q)for(let G of Q)W+=G.source;if(X)W+=Y9(X);return W}aV.stringify=rV});var cJ=C((tV)=>{var q8=Symbol("break visit"),oV=Symbol("skip children"),uJ=Symbol("remove item");function _$($,J){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};lJ(Object.freeze([]),$,J)}_$.BREAK=q8;_$.SKIP=oV;_$.REMOVE=uJ;_$.itemAtPath=($,J)=>{let Q=$;for(let[X,W]of J){let G=Q?.[X];if(G&&"items"in G)Q=G.items[W];else return}return Q};_$.parentCollection=($,J)=>{let Q=_$.itemAtPath($,J.slice(0,-1)),X=J[J.length-1][0],W=Q?.[X];if(W&&"items"in W)return W;throw Error("Parent collection not found")};function lJ($,J,Q){let X=Q(J,$);if(typeof X==="symbol")return X;for(let W of["key","value"]){let G=J[W];if(G&&"items"in G){for(let Y=0;Y<G.items.length;++Y){let q=lJ(Object.freeze($.concat([[W,Y]])),G.items[Y],Q);if(typeof q==="number")Y=q-1;else if(q===q8)return q8;else if(q===uJ)G.items.splice(Y,1),Y-=1}if(typeof X==="function"&&W==="key")X=X(J,$)}}return typeof X==="function"?X(J,$):X}tV.visit=_$});var q9=C((Yz)=>{var H8=kJ(),$z=mJ(),Jz=cJ(),B8="\uFEFF",U8="\x02",V8="\x18",z8="\x1F",Qz=($)=>!!$&&("items"in $),Xz=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function Wz($){switch($){case B8:return"<BOM>";case U8:return"<DOC>";case V8:return"<FLOW_END>";case z8:return"<SCALAR>";default:return JSON.stringify($)}}function Gz($){switch($){case B8:return"byte-order-mark";case U8:return"doc-mode";case V8:return"flow-error-end";case z8: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}
|
|
116
|
-
`:case"\r":case"\t":return!0;default:return!1}}var
|
|
117
|
-
\r `),D8=($)=>!$||
|
|
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}Yz.createScalarToken=H8.createScalarToken;Yz.resolveAsScalar=H8.resolveAsScalar;Yz.setScalarValue=H8.setScalarValue;Yz.stringify=$z.stringify;Yz.visit=Jz.visit;Yz.BOM=B8;Yz.DOCUMENT=U8;Yz.FLOW_END=V8;Yz.SCALAR=z8;Yz.isCollection=Qz;Yz.isScalar=Xz;Yz.prettyToken=Wz;Yz.tokenType=Gz});var F8=C((jz)=>{var u2=q9();function S0($){switch($){case void 0:case" ":case`
|
|
116
|
+
`:case"\r":case"\t":return!0;default:return!1}}var dJ=new Set("0123456789ABCDEFabcdef"),Az=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),H9=new Set(",[]{}"),_z=new Set(` ,[]{}
|
|
117
|
+
\r `),D8=($)=>!$||_z.has($);class pJ{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===`
|
|
@@ -129,13 +129,13 @@ ${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.pus
|
|
|
129
129
|
`&&W>=this.pos&&W+1+J>Y)$=W;else break}while(!0);return yield u2.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 W=this.buffer[Q+1];if(S0(W)||$&&H9.has(W))break;J=Q}else if(S0(X)){let W=this.buffer[Q+1];if(X==="\r")if(W===`
|
|
130
130
|
`)Q+=1,X=`
|
|
131
131
|
`,W=this.buffer[Q+1];else J=Q;if(W==="#"||$&&H9.has(W))break;if(X===`
|
|
132
|
-
`){let G=this.continueScalar(Q+1);if(G===-1)break;Q=Math.max(Q,G-2)}}else{if($&&H9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield u2.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(D8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(S0(Q)||J&&H9.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(!S0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(
|
|
132
|
+
`){let G=this.continueScalar(Q+1);if(G===-1)break;Q=Math.max(Q,G-2)}}else{if($&&H9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield u2.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(D8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(S0(Q)||J&&H9.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(!S0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(Az.has(J))J=this.buffer[++$];else if(J==="%"&&dJ.has(this.buffer[$+1])&&dJ.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)}}
|
|
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)}}jz.Lexer=pJ});var O8=C((Zz)=>{class iJ{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let J=0,Q=this.lineStarts.length;while(J<Q){let W=J+Q>>1;if(this.lineStarts[W]<$)J=W+1;else Q=W}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}}}}Zz.LineCounter=iJ});var M8=C((Sz)=>{var bz=B6("process"),nJ=q9(),Pz=F8();function G$($,J){for(let Q=0;Q<$.length;++Q)if($[Q].type===J)return!0;return!1}function rJ($){for(let J=0;J<$.length;++J)switch($[J].type){case"space":case"comment":case"newline":break;default:return J}return-1}function sJ($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function B9($){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 $2($){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 U9($,J){if(J.length<1e5)Array.prototype.push.apply($,J);else for(let Q=0;Q<J.length;++Q)$.push(J[Q])}function aJ($){if($.start.type==="flow-seq-start"){for(let J of $.items)if(J.sep&&!J.value&&!G$(J.start,"explicit-key-ind")&&!G$(J.sep,"map-value-ind")){if(J.key)J.value=J.key;if(delete J.key,sJ(J.value))if(J.value.end)U9(J.value.end,J.sep);else J.value.end=J.sep;else U9(J.start,J.sep);delete J.sep}}}class oJ{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 Pz.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=$,bz.env.LOG_TOKENS)console.log("|",nJ.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let J=nJ.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")aJ(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&&rJ(X.start)===-1&&(J.indent===0||X.start.every((W)=>W.type!=="comment"||W.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(rJ($.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=B9(this.peek(2)),Q=$2(J),X;if($.end)X=$.end,X.push(this.sourceToken),delete $.end;else X=[this.sourceToken];let W={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Q,key:$,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}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)){U9(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",W=[];if(X&&J.sep&&!J.value){let G=[];for(let Y=0;Y<J.sep.length;++Y){let q=J.sep[Y];switch(q.type){case"newline":G.push(Y);break;case"space":break;case"comment":if(q.indent>$.indent)G.length=0;break;default:G.length=0}}if(G.length>=2)W=J.sep.splice(G[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)W.push(this.sourceToken),$.items.push({start:W}),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)W.push(this.sourceToken),$.items.push({start:W,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(G$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let G=$2(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(G$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:W,key:null,sep:[this.sourceToken]}]});else if(
|
|
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)){U9(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",W=[];if(X&&J.sep&&!J.value){let G=[];for(let Y=0;Y<J.sep.length;++Y){let q=J.sep[Y];switch(q.type){case"newline":G.push(Y);break;case"space":break;case"comment":if(q.indent>$.indent)G.length=0;break;default:G.length=0}}if(G.length>=2)W=J.sep.splice(G[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)W.push(this.sourceToken),$.items.push({start:W}),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)W.push(this.sourceToken),$.items.push({start:W,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(G$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let G=$2(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(G$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:W,key:null,sep:[this.sourceToken]}]});else if(sJ(J.key)&&!G$(J.sep,"newline")){let G=$2(J.start),Y=J.key,q=J.sep;q.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:Y,sep:q}]})}else if(W.length>0)J.sep=J.sep.concat(W,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:W,key:null,sep:[this.sourceToken]});else if(G$(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:W,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&&!G$(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:W});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)){U9(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||G$(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=B9(Q),W=$2(X);aJ($);let G=$.end.splice(1,$.end.length);G.push(this.sourceToken);let Y={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:W,key:$,sep:G}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}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=B9($),Q=$2(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=B9($),Q=$2(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()}}}
|
|
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=B9($),Q=$2(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=B9($),Q=$2(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()}}}Sz.Parser=oJ});var Q3=C((yz)=>{var tJ=G8(),Cz=h2(),l2=y2(),fz=O4(),Tz=p(),Iz=O8(),eJ=M8();function $3($){let J=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||J&&new Iz.LineCounter||null,prettyErrors:J}}function vz($,J={}){let{lineCounter:Q,prettyErrors:X}=$3(J),W=new eJ.Parser(Q?.addNewLine),G=new tJ.Composer(J),Y=Array.from(G.compose(W.parse($)));if(X&&Q)for(let q of Y)q.errors.forEach(l2.prettifyError($,Q)),q.warnings.forEach(l2.prettifyError($,Q));if(Y.length>0)return Y;return Object.assign([],{empty:!0},G.streamInfo())}function J3($,J={}){let{lineCounter:Q,prettyErrors:X}=$3(J),W=new eJ.Parser(Q?.addNewLine),G=new tJ.Composer(J),Y=null;for(let q of G.compose(W.parse($),!0,$.length))if(!Y)Y=q;else if(Y.options.logLevel!=="silent"){Y.errors.push(new l2.YAMLParseError(q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Q)Y.errors.forEach(l2.prettifyError($,Q)),Y.warnings.forEach(l2.prettifyError($,Q));return Y}function xz($,J,Q){let X=void 0;if(typeof J==="function")X=J;else if(Q===void 0&&J&&typeof J==="object")Q=J;let W=J3($,Q);if(!W)return null;if(W.warnings.forEach((G)=>fz.warn(W.options.logLevel,G)),W.errors.length>0)if(W.options.logLevel!=="silent")throw W.errors[0];else W.errors=[];return W.toJS(Object.assign({reviver:X},Q))}function hz($,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 W=Math.round(Q);Q=W<1?void 0:W>8?{indent:8}:{indent:W}}if($===void 0){let{keepUndefined:W}=Q??J??{};if(!W)return}if(Tz.isDocument($)&&!X)return $.toString(Q);return new Cz.Document($,X,Q).toString(Q)}yz.parse=xz;yz.parseAllDocuments=vz;yz.parseDocument=J3;yz.stringify=hz});var W3=C(($D)=>{var lz=G8(),cz=h2(),dz=c4(),K8=y2(),pz=j2(),Y$=p(),iz=J$(),nz=W0(),rz=X$(),az=W$(),sz=q9(),oz=F8(),tz=O8(),ez=M8(),V9=Q3(),X3=A2();$D.Composer=lz.Composer;$D.Document=cz.Document;$D.Schema=dz.Schema;$D.YAMLError=K8.YAMLError;$D.YAMLParseError=K8.YAMLParseError;$D.YAMLWarning=K8.YAMLWarning;$D.Alias=pz.Alias;$D.isAlias=Y$.isAlias;$D.isCollection=Y$.isCollection;$D.isDocument=Y$.isDocument;$D.isMap=Y$.isMap;$D.isNode=Y$.isNode;$D.isPair=Y$.isPair;$D.isScalar=Y$.isScalar;$D.isSeq=Y$.isSeq;$D.Pair=iz.Pair;$D.Scalar=nz.Scalar;$D.YAMLMap=rz.YAMLMap;$D.YAMLSeq=az.YAMLSeq;$D.CST=sz;$D.Lexer=oz.Lexer;$D.LineCounter=tz.LineCounter;$D.Parser=ez.Parser;$D.parse=V9.parse;$D.parseAllDocuments=V9.parseAllDocuments;$D.parseDocument=V9.parseDocument;$D.stringify=V9.stringify;$D.visit=X3.visit;$D.visitAsync=X3.visitAsync});var e1=($)=>$.payload.title?.trim()||`session:${$.payload.id}`;function U6($){let{store:J,agent:Q}=$;return{async session(X){let W=X.payload.id,G=await Y7(J,W);switch(X.type){case"session.created":{if(G)return{task_id:G.id};let Y=e1(X);return{task_id:(await J.createTask({title:Y,session_id:W,owner:Q,priority:3})).id}}case"session.idle":{if(!G)return null;if(G.status==="pending"){let Y=await J.updateTask(G.id,{status:"in_progress"});return Y?{task_id:Y.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:W,agent:Q}}),null;default:return null}},async tool(X){let W=X.payload.sessionID,G=await Y7(J,W);if(!G)return await J.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:W,tool:X.payload.tool}}),{task_id:(await J.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:Q,priority:3})).id};let Y=$Q(X),H=(await J.listTasks({parent_id:G.id,limit:20})).tasks.find((U)=>U.title===Y&&Date.now()-new Date(U.created_at).getTime()<60000);if(H)return{task_id:H.id};let B=await J.createTask({title:Y,parent_id:G.id,session_id:W,owner:Q,priority:3});return await J.updateTask(B.id,{status:"in_progress"}),{task_id:B.id}},async catchAll(X){try{await J.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:Q}})}catch{}}}}async function Y7($,J){return(await $.listTasks({session_id:J,limit:1})).tasks[0]??null}function $Q($){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 Y2="\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536",B$="TASK_COMPLETION_HINT",q2="\u6838\u5B9E\u4E49\u52A1";var V6="### 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` \u2014\u2014 \u7EC8\u6001\u7531\u9A8C\u6536\u65B9\u843D\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\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 `task_update(progress=100)`\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(),z6=`### Operation Record \u2014 \u53CC\u7EF4\u5EA6\u5206\u5DE5\u89C4\u8303
|
|
139
139
|
|
|
140
140
|
**Record milestones as you work** \u2014 call \`task_operation_create\` the moment a
|
|
141
141
|
stage is reached, **not after the fact** (not in a batch at the end).
|
|
@@ -256,9 +256,10 @@ Before calling \`task_complete\`, you MUST:
|
|
|
256
256
|
The \`deliverable_storage_path\` will be persisted to the task's
|
|
257
257
|
\`context.deliverable_storage_path\` for future reference and traceability.`,T9=[V6,z6,P$,D6].join(`
|
|
258
258
|
|
|
259
|
-
`);import{createRequire as
|
|
260
|
-
`),Q=[];for(let
|
|
261
|
-
`)}
|
|
259
|
+
`);import{createRequire as JQ}from"module";var{defineProperty:I9,getOwnPropertyNames:QQ,getOwnPropertyDescriptor:XQ}=Object,WQ=Object.prototype.hasOwnProperty;function GQ($){return this[$]}var S$=($)=>{var J=(q7??=new WeakMap).get($),Q;if(J)return J;if(J=I9({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of QQ($))if(!WQ.call(J,X))I9(J,X,{get:GQ.bind($,X),enumerable:!(Q=XQ($,X))||Q.enumerable})}return q7.set($,J),J},q7,YQ=($)=>$;function qQ($,J){this[$]=YQ.bind(null,J)}var i0=($,J)=>{for(var Q in J)I9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:qQ.bind(J,Q)})},m=function($,J,Q,X){var W=arguments.length,G=W<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,Q):X,Y;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")G=Reflect.decorate($,J,Q,X);else for(var q=$.length-1;q>=0;q--)if(Y=$[q])G=(W<3?Y(G):W>3?Y(J,Q,G):Y(J,Q))||G;return W>3&&G&&Object.defineProperty(J,Q,G),G},a=($,J)=>()=>($&&(J=$($=0)),J),e=JQ(import.meta.url);var HQ=/\u9A8C\u6536\u65B9|\u6536\u5C3E\u5206\u4E24\u79CD\u89D2\u8272/,BQ=Object.freeze([{name:"complete-\u7981\u6B62\u8C03\u7528",match:($)=>/(\u4E0D\u8981|\u7981\u6B62|\u522B|\u65E0\u9700|\u4E0D\u9700\u8981|\u4E0D\u80FD|\u65E0\u6743|\u4E0D\u5F97|\u4ECD\u65E0|\u4E0D\u6301\u6709|\u4E0D\u5177\u5907|\u672A\u83B7\u5F97)/.test($)&&/task_complete/.test($)},{name:"\u89D2\u8272\u6743\u9650\u65AD\u8A00",match:($)=>/(\u6267\u884C\u65B9|\u9A8C\u6536\u65B9)/.test($)&&/(\u6743\u9650|\u8D44\u683C|\u65E0\u6743|\u4E0D\u80FD|\u6CA1\u6709)/.test($)&&/task_complete/.test($)&&!/\u4F60\u7684\u6536\u5C3E\u52A8\u4F5C\u662F/.test($)},{name:"track-\u7981\u6B62\u7F6E\u7EC8\u6001",match:($)=>/\u7EC8\u6001\u7531\u9A8C\u6536\u65B9\u843D/.test($)||/\u4E0D\u8981/.test($)&&/\u7F6E\u4E3A/.test($)&&/completed/.test($)},{name:"lifecycle-\u89D2\u8272\u4E8C\u5206\u6807\u9898",match:($)=>/\u6536\u5C3E\u5206\u4E24\u79CD\u89D2\u8272/.test($),replace:()=>"6. COMPLETE \u2014 \u6536\u5C3E\uFF1A\u7528 `task_complete` after item-by-item verification"+" (see Complete Discipline below)"},{name:"lifecycle-\u6267\u884C\u65B9\u6761\u76EE",match:($)=>/\u6267\u884C\u65B9/.test($)&&/(roy )?sub-agent/.test($)},{name:"lifecycle-\u6267\u884C\u65B9\u6536\u5C3E\u6307\u4EE4",match:($,J)=>(/\u7ED3\u675F\u5E76\u8FD4\u56DE\u7ED3\u679C|\u7ED3\u675F\u5E76\u8FD4\u56DE/.test($)||/\u6700\u540E\u4E00\u6761/.test($)&&/task_operation_create/.test($))&&(/\u6267\u884C\u65B9/.test($)||/\u6267\u884C\u65B9/.test(J.prevLine??""))},{name:"lifecycle-\u9A8C\u6536\u65B9\u6761\u76EE",match:($)=>/\u9A8C\u6536\u65B9/.test($)&&/(default agent|\u63A5\u5F85\u5458)/.test($)},{name:"complete-\u6807\u9898\u89D2\u8272\u9650\u5B9A",match:($)=>/^#{1,6}\s/.test($)&&/\u9A8C\u6536\u65B9/.test($),replace:($)=>$.replace(/\s*[\uFF08(][^\uFF09)]*\u9A8C\u6536\u65B9[^\uFF09)]*[\uFF09)]/g,"")},{name:"complete-\u89D2\u8272\u4F5C\u7528\u57DF\u5F15\u7528\u5757",match:($)=>/\u89D2\u8272\u4F5C\u7528\u57DF/.test($)||/\u82E5\u4F60\u662F/.test($)&&/\u6267\u884C\u65B9/.test($)&&/\u6743\u9650/.test($)||/\u4F60\u7684\u6536\u5C3E\u52A8\u4F5C\u662F/.test($)&&/\u9A8C\u6536\u7531\u4E3B\u667A\u80FD\u4F53\u8D1F\u8D23/.test($)}]);function H7($){return/^\s*([-*+]\s|\d+\.\s)/.test($)}function UQ($,J){if(H7($))return!1;if(/^\s*(#{1,6}\s|>)/.test($))return!1;if(/^\s*```/.test($))return!1;if($.trim()==="")return!1;let Q=(X)=>X.match(/^\s*/)?.[0].length??0;return Q($)>Q(J)}function H2($){if(!$)return $;let J=$.split(`
|
|
260
|
+
`),Q=[];for(let G=0;G<J.length;G++){let Y=J[G],q=BQ.find((H)=>H.match(Y,{prevLine:J[G-1]}));if(!q){Q.push(Y);continue}if(q.replace){let H=q.replace(Y);if(HQ.test(H))throw Error(`trim-permission: rule "${q.name}" matched the line but its replace() `+"left the role qualifier in place \u2014 core's wording drifted and this "+`trim rule must be updated.
|
|
261
|
+
line: ${Y}`);Q.push(H)}if(!q.replace&&H7(Y))while(G+1<J.length&&UQ(J[G+1],Y))G++}let X=[],W=!1;for(let G of Q){if(/^\s*```/.test(G)){W=!W,X.push(G);continue}if(!W&&G.trim()===""&&X.length>0&&X[X.length-1].trim()==="")continue;X.push(G)}return X.join(`
|
|
262
|
+
`)}var VQ=H2(V6),zQ=H2(P$),DQ=H2(z6),FQ=H2(D6),v9=`# Roy \u2014 task-first-class-citizen agent
|
|
262
263
|
|
|
263
264
|
You are **Roy**, an agent whose defining rule is simple:
|
|
264
265
|
|
|
@@ -267,16 +268,16 @@ You are **Roy**, an agent whose defining rule is simple:
|
|
|
267
268
|
You are a worker agent: you act through the tools, and your output is what
|
|
268
269
|
the user sees.
|
|
269
270
|
|
|
270
|
-
${
|
|
271
|
+
${VQ}
|
|
271
272
|
|
|
272
|
-
${
|
|
273
|
+
${zQ}
|
|
273
274
|
|
|
274
275
|
The tool returns a **numeric task id** \u2014 that number is your handle for the
|
|
275
276
|
rest of the conversation.
|
|
276
277
|
|
|
277
|
-
${
|
|
278
|
+
${DQ}
|
|
278
279
|
|
|
279
|
-
${
|
|
280
|
+
${FQ}
|
|
280
281
|
|
|
281
282
|
#### Several deliverables in one field
|
|
282
283
|
\`deliverable_storage_path\` may name **multiple paths**, space-separated
|
|
@@ -311,7 +312,7 @@ if it is not in the task store, it is not tracked.
|
|
|
311
312
|
- Be direct and concrete; the user is reading task titles and milestones.
|
|
312
313
|
- Report the task id and its state whenever you finish a step.
|
|
313
314
|
- If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
|
|
314
|
-
\`problem\` milestone explaining the blocker instead of going silent.`,
|
|
315
|
+
\`problem\` milestone explaining the blocker instead of going silent.`,OQ=`
|
|
315
316
|
## Milestone discipline (Claude runtime)
|
|
316
317
|
|
|
317
318
|
The task card renders **your** milestones. A run that calls tools but
|
|
@@ -380,8 +381,8 @@ continue.
|
|
|
380
381
|
For a task with 3\u20134 stages you should end up with **3\u20134 hand-written
|
|
381
382
|
milestones** in the card \u2014 not 2 automatic hooks and nothing else. The
|
|
382
383
|
automatic \`\u6536\u5230\u6D88\u606F\` / \`Task \u5B8C\u6210\` hooks are not a substitute for yours.
|
|
383
|
-
`,
|
|
384
|
-
${
|
|
384
|
+
`,MQ=`
|
|
385
|
+
${OQ}
|
|
385
386
|
## Tool surface on Claude Code
|
|
386
387
|
|
|
387
388
|
The \`task_*\` tools are served by the **\`roy-task\` MCP server** this runtime
|
|
@@ -405,7 +406,7 @@ progress card renders the task these tools create.
|
|
|
405
406
|
Measured: it has no way to write a milestone (its \`operations <id>\` subcommand
|
|
406
407
|
is a *reader*), and it targets a different database than this server. Use the
|
|
407
408
|
MCP tools above; if they are genuinely unavailable, say so in your answer
|
|
408
|
-
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_complete) "+"so every piece of work is tracked in the local task store.",h9=v9;var B2="roy",
|
|
409
|
+
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_complete) "+"so every piece of work is tracked in the local task store.",h9=v9;var B2="roy",B7={action:"execute",resource:"*",effect:"deny"};function U7(){return{id:B2,mode:"primary",description:x9,system:h9,permissions:[{...B7}]}}function KQ($,J){if(!Array.isArray($.permissions))$.permissions=[];for(let Q of J)if(!$.permissions.some((W)=>W.action===Q.action&&W.resource===Q.resource&&W.effect===Q.effect))$.permissions.push({...Q})}function y9($){let J=U7();return $.update(B2,(Q)=>{if(Q.mode=J.mode,Q.description=J.description,Q.system=J.system,Q.hidden===void 0)Q.hidden=!1;KQ(Q,J.permissions)}),J}function g9(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function V7($){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 RQ(){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 LQ($){let Q=new(RQ())($);if(typeof Q.run!=="function")Q.run=function(X,...W){if(W.length>0)return this.prepare(X).run(...W);else return this.exec(X)};return Q}class k9{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=LQ(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(`
|
|
409
410
|
CREATE TABLE IF NOT EXISTS span (
|
|
410
411
|
span_id TEXT PRIMARY KEY,
|
|
411
412
|
trace_id TEXT NOT NULL,
|
|
@@ -424,7 +425,7 @@ instead of silently skipping the lifecycle.`;var x9="Roy \u2014 task-as-first-cl
|
|
|
424
425
|
INSERT OR REPLACE INTO span
|
|
425
426
|
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
426
427
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
427
|
-
`),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:
|
|
428
|
+
`),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:V7($.result):null;if(g9())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,V7($.attributes),Q,$.error||null,Date.now());if(g9())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(`
|
|
428
429
|
SELECT trace_id,
|
|
429
430
|
MIN(start_time) as start_time,
|
|
430
431
|
MAX(end_time) as end_time,
|
|
@@ -439,9 +440,9 @@ instead of silently skipping the lifecycle.`;var x9="Roy \u2014 task-as-first-cl
|
|
|
439
440
|
GROUP BY trace_id
|
|
440
441
|
ORDER BY start_time DESC
|
|
441
442
|
LIMIT ?
|
|
442
|
-
`).all($).map((Q)=>{let X=Number(Q.span_count)||0,W=Number(Q.error_count)||0,G=Q.end_time??void 0,Y=W===0?"ok":W>=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:Y}})}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 W=J.get(X.parentSpanId);if(W)W.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var
|
|
443
|
-
`)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let W=Q[X];if(W.includes("at ")&&!W.includes("logger.ts")&&!W.includes("formatMessage")){let G=W.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||W.match(/at\s+(.+):(\d+):\d+/);if(G){let Y=G[1];return{file:this.getRelativePath(Y),line:parseInt(G[2],10)}}}}return null}getRelativePath($){return n9($)}formatMessage($,J,Q){let X=new Date,W=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}]`:"",Y="";try{let V=V2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)Y=`[traceId=${V.traceId}]`}catch{}let q="";if(Q&&typeof Q==="object"&&"callerLocation"in Q){let U=Q;q=U.callerLocation?` [${U.callerLocation}]`:"";let{callerLocation:z,...V}=U;Q=Object.keys(V).length>0?V:void 0}else{let U=this.getCallerLocation();if(U)q=` [${U.file}:${U.line}]`}let H=`${W} [${$.toUpperCase()}]${Y}${q}${G} ${J}`;if(Q!==void 0)if(typeof Q==="object")H+=" "+JSON.stringify(Q).replace(/\n/g,"");else H+=" "+String(Q);let B=r9();if(B&&B>0&&H.length>B)H=H.substring(0,B)+" [TRUNCATED]";return H}writeToFile($){try{let J=
|
|
444
|
-
`,"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),!EQ())if(yQ)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(!F6.has($))F6.set($,new L7($));return F6.get($)}var _0=null,hQ=!1,yQ=!1;var d9,F6,r=a(()=>{o9(),d9={debug:0,info:1,warn:2,error:3},F6=new Map}),gQ={};i0(gQ,{setTracerProvider:()=>mQ,resetTracerProvider:()=>kQ,getTracerProvider:()=>V2,OTelTracerProvider:()=>s9});function a9(){if(!l9)l9=i("otel-tracer");return l9}function A7(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function _7($,...J){a9().info($,...J)}function F7($,...J){a9().warn($,...J)}function O7($,...J){a9().error($,...J)}class p9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,W){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=W}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())_7(`[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)F7(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=V2().getStorage();if(X){if(!(X.db||X.initialized))F7(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((G)=>{O7("[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 O7(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class j7{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,W=J&&"context"in J,G=this.provider.getGlobalContext(),Y,q,H,B,U;if(W&&J?.context){let V=J.context;q=V.traceId,H=this.generateSpanId(),B=V.spanId,U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let M=new p9($,U,this.storage,V,()=>this.handleSpanEnd(U.spanId,V.spanId));if(J?.attributes)for(let[F,D]of Object.entries(J.attributes))M.setAttribute(F,D);return this.activeSpans.set(H,M),M}if(X)Y=Q;else if(this.currentContext)Y=this.currentContext;else if(G)Y=G;if(q=Y?.traceId||this.generateTraceId(),H=this.generateSpanId(),X&&Q)B=Q.parentSpanId||Q.spanId;else if(this.currentContext)B=this.currentContext.spanId;else if(G)B=G.spanId;U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let z=new p9($,U,this.storage,Y,()=>this.handleSpanEnd(U.spanId,Y?.spanId));if(J?.attributes)for(let[V,M]of Object.entries(J.attributes))z.setAttribute(V,M);if(this.activeSpans.set(H,z),A7())_7(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${q} spanId=${H} parentSpanId=${B||"-"}`);return z}injectToEnv($){if(this.currentContext)i9.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 W=this.activeSpans.get(J.parentSpanId);if(W){let G={traceId:J.traceId,spanId:W.spanContext.spanId,parentSpanId:W.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 W={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=W,W}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 s9{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new D7;tracerContexts=new Map;tracerContextScope=new D7;instanceId;constructor($,J){M7++,this.instanceId=`Provider#${M7}`,this.storage=$||new k9(J||uQ())}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 j7($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=i9.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 V2(){if(!k0)k0=new s9;return k0}function kQ(){if(k0)k0.shutdown(),k0=null}function mQ($){if(k0)k0.shutdown();k0=$}function uQ(){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 l9=null,k0=null,M7=0,o9=a(()=>{V7(),_Q(),ZQ(),r()});var K={};o1(K,{void:()=>wX,util:()=>l,unknown:()=>NX,union:()=>EX,undefined:()=>AX,tuple:()=>TX,transformer:()=>lX,symbol:()=>LX,string:()=>f7,strictObject:()=>SX,setErrorMap:()=>dQ,set:()=>xX,record:()=>IX,quotelessJson:()=>lQ,promise:()=>uX,preprocess:()=>pX,pipeline:()=>iX,ostring:()=>nX,optional:()=>cX,onumber:()=>rX,oboolean:()=>aX,objectUtil:()=>t9,object:()=>PX,number:()=>T7,nullable:()=>dX,null:()=>_X,never:()=>ZX,nativeEnum:()=>mX,nan:()=>MX,map:()=>vX,makeIssue:()=>z2,literal:()=>gX,lazy:()=>yX,late:()=>FX,isValid:()=>n0,isDirty:()=>M6,isAsync:()=>C$,isAborted:()=>O6,intersection:()=>fX,instanceof:()=>OX,getParsedType:()=>T0,getErrorMap:()=>E$,function:()=>hX,enum:()=>kX,effect:()=>lX,discriminatedUnion:()=>CX,defaultErrorMap:()=>m0,datetimeRegex:()=>S7,date:()=>RX,custom:()=>C7,coerce:()=>sX,boolean:()=>I7,bigint:()=>KX,array:()=>bX,any:()=>jX,addIssueToContext:()=>S,ZodVoid:()=>F2,ZodUnknown:()=>r0,ZodUnion:()=>h$,ZodUndefined:()=>v$,ZodType:()=>k,ZodTuple:()=>v0,ZodTransformer:()=>b0,ZodSymbol:()=>D2,ZodString:()=>j0,ZodSet:()=>D$,ZodSchema:()=>k,ZodRecord:()=>O2,ZodReadonly:()=>c$,ZodPromise:()=>F$,ZodPipeline:()=>R2,ZodParsedType:()=>b,ZodOptional:()=>Z0,ZodObject:()=>$0,ZodNumber:()=>a0,ZodNullable:()=>l0,ZodNull:()=>x$,ZodNever:()=>I0,ZodNativeEnum:()=>m$,ZodNaN:()=>K2,ZodMap:()=>M2,ZodLiteral:()=>k$,ZodLazy:()=>g$,ZodIssueCode:()=>A,ZodIntersection:()=>y$,ZodFunction:()=>T$,ZodFirstPartyTypeKind:()=>j,ZodError:()=>Y0,ZodEnum:()=>o0,ZodEffects:()=>b0,ZodDiscriminatedUnion:()=>K6,ZodDefault:()=>u$,ZodDate:()=>V$,ZodCatch:()=>l$,ZodBranded:()=>R6,ZodBoolean:()=>I$,ZodBigInt:()=>s0,ZodArray:()=>N0,ZodAny:()=>z$,Schema:()=>k,ParseStatus:()=>q0,OK:()=>B0,NEVER:()=>oX,INVALID:()=>I,EMPTY_PATH:()=>pQ,DIRTY:()=>U$,BRAND:()=>DX});var l;(function($){$.assertEqual=(W)=>{};function J(W){}$.assertIs=J;function Q(W){throw Error()}$.assertNever=Q,$.arrayToEnum=(W)=>{let G={};for(let Y of W)G[Y]=Y;return G},$.getValidEnumValues=(W)=>{let G=$.objectKeys(W).filter((q)=>typeof W[W[q]]!=="number"),Y={};for(let q of G)Y[q]=W[q];return $.objectValues(Y)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(G){return W[G]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let G=[];for(let Y in W)if(Object.prototype.hasOwnProperty.call(W,Y))G.push(Y);return G},$.find=(W,G)=>{for(let Y of W)if(G(Y))return Y;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function X(W,G=" | "){return W.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(G)}$.joinValues=X,$.jsonStringifyReplacer=(W,G)=>{if(typeof G==="bigint")return G.toString();return G}})(l||(l={}));var t9;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(t9||(t9={}));var b=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T0=($)=>{switch(typeof $){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN($)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":if(Array.isArray($))return b.array;if($===null)return b.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return b.promise;if(typeof Map<"u"&&$ instanceof Map)return b.map;if(typeof Set<"u"&&$ instanceof Set)return b.set;if(typeof Date<"u"&&$ instanceof Date)return b.date;return b.object;default:return b.unknown}};var A=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"]),lQ=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class Y0 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(W){return W.message},Q={_errors:[]},X=(W)=>{for(let G of W.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 Y=Q,q=0;while(q<G.path.length){let H=G.path[q];if(q!==G.path.length-1)Y[H]=Y[H]||{_errors:[]};else Y[H]=Y[H]||{_errors:[]},Y[H]._errors.push(J(G));Y=Y[H],q++}}};return X(this),Q}static assert($){if(!($ instanceof Y0))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 W=X.path[0];J[W]=J[W]||[],J[W].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}Y0.create=($)=>{return new Y0($)};var cQ=($,J)=>{let Q;switch($.code){case A.invalid_type:if($.received===b.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case A.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case A.invalid_union:Q="Invalid input";break;case A.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case A.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case A.invalid_arguments:Q="Invalid function arguments";break;case A.invalid_return_type:Q="Invalid function return type";break;case A.invalid_date:Q="Invalid date";break;case A.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 A.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 A.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 A.custom:Q="Invalid input";break;case A.invalid_intersection_types:Q="Intersection results could not be merged";break;case A.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case A.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},m0=cQ;var N7=m0;function dQ($){N7=$}function E$(){return N7}var z2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:W}=$,G=[...Q,...W.path||[]],Y={...W,path:G};if(W.message!==void 0)return{...W,path:G,message:W.message};let q="",H=X.filter((B)=>!!B).slice().reverse();for(let B of H)q=B(Y,{data:J,defaultError:q}).message;return{...W,path:G,message:q}},pQ=[];function S($,J){let Q=E$(),X=z2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===m0?void 0:m0].filter((W)=>!!W)});$.common.issues.push(X)}class q0{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 I;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 W=await X.key,G=await X.value;Q.push({key:W,value:G})}return q0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:W,value:G}=X;if(W.status==="aborted")return I;if(G.status==="aborted")return I;if(W.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof G.value<"u"||X.alwaysSet))Q[W.value]=G.value}return{status:$.value,value:Q}}}var I=Object.freeze({status:"aborted"}),U$=($)=>({status:"dirty",value:$}),B0=($)=>({status:"valid",value:$}),O6=($)=>$.status==="aborted",M6=($)=>$.status==="dirty",n0=($)=>$.status==="valid",C$=($)=>typeof Promise<"u"&&$ instanceof Promise;var T;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(T||(T={}));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 Z7=($,J)=>{if(n0(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 Y0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:W}=$;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:W};return{errorMap:(Y,q)=>{let{message:H}=$;if(Y.code==="invalid_enum_value")return{message:H??q.defaultError};if(typeof q.data>"u")return{message:H??X??q.defaultError};if(Y.code!=="invalid_type")return{message:q.defaultError};return{message:H??Q??q.defaultError}},description:W}}class k{get description(){return this._def.description}_getType($){return T0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new q0,ctx:{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(C$(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:T0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return Z7(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return n0(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)=>n0(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:T0($)},X=this._parse({data:$,path:Q.path,parent:Q}),W=await(C$(X)?X:Promise.resolve(X));return Z7(Q,W)}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,W)=>{let G=$(X),Y=()=>W.addIssue({code:A.custom,...Q(X)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((q)=>{if(!q)return Y(),!1;else return!0});if(!G)return Y(),!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 b0({schema:this,typeName:j.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 l0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return N0.create(this)}promise(){return F$.create(this,this._def)}or($){return h$.create([this,$],this._def)}and($){return y$.create(this,$,this._def)}transform($){return new b0({...h(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new u$({...h(this._def),innerType:this,defaultValue:J,typeName:j.ZodDefault})}brand(){return new R6({typeName:j.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new l$({...h(this._def),innerType:this,catchValue:J,typeName:j.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return R2.create(this,$)}readonly(){return c$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var iQ=/^c[^\s-]{8,}$/i,nQ=/^[0-9a-z]+$/,rQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,aQ=/^[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,sQ=/^[a-z0-9_-]{21}$/i,oQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tQ=/^[-+]?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)?)??$/,eQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,$X="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",e9,JX=/^(?:(?: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])$/,QX=/^(?:(?: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])$/,XX=/^(([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]))$/,WX=/^(([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])$/,GX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,YX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,b7="((\\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])))",qX=new RegExp(`^${b7}$`);function P7($){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 HX($){return new RegExp(`^${P7($)}$`)}function S7($){let J=`${b7}T${P7($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function BX($,J){if((J==="v4"||!J)&&JX.test($))return!0;if((J==="v6"||!J)&&XX.test($))return!0;return!1}function UX($,J){if(!oQ.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,"="),W=JSON.parse(atob(X));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(J&&W.alg!==J)return!1;return!0}catch{return!1}}function VX($,J){if((J==="v4"||!J)&&QX.test($))return!0;if((J==="v6"||!J)&&WX.test($))return!0;return!1}class j0 extends k{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==b.string){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.string,received:W.parsedType}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.length<W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="max"){if($.data.length>W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="length"){let G=$.data.length>W.value,Y=$.data.length<W.value;if(G||Y){if(X=this._getOrReturnCtx($,X),G)S(X,{code:A.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});else if(Y)S(X,{code:A.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});Q.dirty()}}else if(W.kind==="email"){if(!eQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"email",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="emoji"){if(!e9)e9=new RegExp($X,"u");if(!e9.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"emoji",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="uuid"){if(!aQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"uuid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="nanoid"){if(!sQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"nanoid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid"){if(!iQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid2"){if(!nQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid2",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ulid"){if(!rQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"ulid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),S(X,{validation:"url",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="regex"){if(W.regex.lastIndex=0,!W.regex.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"regex",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="trim")$.data=$.data.trim();else if(W.kind==="includes"){if(!$.data.includes(W.value,W.position))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{includes:W.value,position:W.position},message:W.message}),Q.dirty()}else if(W.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(W.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(W.kind==="startsWith"){if(!$.data.startsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{startsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="endsWith"){if(!$.data.endsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{endsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="datetime"){if(!S7(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"datetime",message:W.message}),Q.dirty()}else if(W.kind==="date"){if(!qX.test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"date",message:W.message}),Q.dirty()}else if(W.kind==="time"){if(!HX(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"time",message:W.message}),Q.dirty()}else if(W.kind==="duration"){if(!tQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"duration",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ip"){if(!BX($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"ip",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="jwt"){if(!UX($.data,W.alg))X=this._getOrReturnCtx($,X),S(X,{validation:"jwt",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cidr"){if(!VX($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"cidr",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64"){if(!GX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64url"){if(!YX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64url",code:A.invalid_string,message:W.message}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:A.invalid_string,...T.errToObj(Q)})}_addCheck($){return new j0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...T.errToObj($)})}url($){return this._addCheck({kind:"url",...T.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...T.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...T.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...T.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...T.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...T.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...T.errToObj($)})}base64($){return this._addCheck({kind:"base64",...T.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...T.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...T.errToObj($)})}ip($){return this._addCheck({kind:"ip",...T.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...T.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...T.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...T.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...T.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...T.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...T.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...T.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...T.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...T.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...T.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...T.errToObj(J)})}nonempty($){return this.min(1,T.errToObj($))}trim(){return new j0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new j0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new j0({...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 $}}j0.create=($)=>{return new j0({checks:[],typeName:j.ZodString,coerce:$?.coerce??!1,...h($)})};function zX($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,W=Q>X?Q:X,G=Number.parseInt($.toFixed(W).replace(".","")),Y=Number.parseInt(J.toFixed(W).replace(".",""));return G%Y/10**W}class a0 extends k{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($)!==b.number){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.number,received:W.parsedType}),I}let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.invalid_type,expected:"integer",received:"float",message:W.message}),X.dirty()}else if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_small,minimum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if(zX($.data,W.value)!==0)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_finite,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new a0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new a0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:T.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.toString(J)})}finite($){return this._addCheck({kind:"finite",message:T.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString($)})}get minValue(){let $=null;for(let 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($)}}a0.create=($)=>{return new a0({checks:[],typeName:j.ZodNumber,coerce:$?.coerce||!1,...h($)})};class s0 extends k{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($)!==b.bigint)return this._getInvalidInput($);let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_small,type:"bigint",minimum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return S(J,{code:A.invalid_type,expected:b.bigint,received:J.parsedType}),I}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new s0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.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 $}}s0.create=($)=>{return new s0({checks:[],typeName:j.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class I$ extends k{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==b.boolean){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.boolean,received:Q.parsedType}),I}return B0($.data)}}I$.create=($)=>{return new I$({typeName:j.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class V$ extends k{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==b.date){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.date,received:W.parsedType}),I}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_date}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()<W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_small,message:W.message,inclusive:!0,exact:!1,minimum:W.value,type:"date"}),Q.dirty()}else if(W.kind==="max"){if($.data.getTime()>W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new V$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:T.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:T.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}}V$.create=($)=>{return new V$({checks:[],coerce:$?.coerce||!1,typeName:j.ZodDate,...h($)})};class D2 extends k{_parse($){if(this._getType($)!==b.symbol){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.symbol,received:Q.parsedType}),I}return B0($.data)}}D2.create=($)=>{return new D2({typeName:j.ZodSymbol,...h($)})};class v$ extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.undefined,received:Q.parsedType}),I}return B0($.data)}}v$.create=($)=>{return new v$({typeName:j.ZodUndefined,...h($)})};class x$ extends k{_parse($){if(this._getType($)!==b.null){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.null,received:Q.parsedType}),I}return B0($.data)}}x$.create=($)=>{return new x$({typeName:j.ZodNull,...h($)})};class z$ extends k{constructor(){super(...arguments);this._any=!0}_parse($){return B0($.data)}}z$.create=($)=>{return new z$({typeName:j.ZodAny,...h($)})};class r0 extends k{constructor(){super(...arguments);this._unknown=!0}_parse($){return B0($.data)}}r0.create=($)=>{return new r0({typeName:j.ZodUnknown,...h($)})};class I0 extends k{_parse($){let J=this._getOrReturnCtx($);return S(J,{code:A.invalid_type,expected:b.never,received:J.parsedType}),I}}I0.create=($)=>{return new I0({typeName:j.ZodNever,...h($)})};class F2 extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.void,received:Q.parsedType}),I}return B0($.data)}}F2.create=($)=>{return new F2({typeName:j.ZodVoid,...h($)})};class N0 extends k{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==b.array)return S(J,{code:A.invalid_type,expected:b.array,received:J.parsedType}),I;if(X.exactLength!==null){let G=J.data.length>X.exactLength.value,Y=J.data.length<X.exactLength.value;if(G||Y)S(J,{code:G?A.too_big:A.too_small,minimum:Y?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)S(J,{code:A.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)S(J,{code:A.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,Y)=>{return X.type._parseAsync(new w0(J,G,J.path,Y))})).then((G)=>{return q0.mergeArray(Q,G)});let W=[...J.data].map((G,Y)=>{return X.type._parseSync(new w0(J,G,J.path,Y))});return q0.mergeArray(Q,W)}get element(){return this._def.type}min($,J){return new N0({...this._def,minLength:{value:$,message:T.toString(J)}})}max($,J){return new N0({...this._def,maxLength:{value:$,message:T.toString(J)}})}length($,J){return new N0({...this._def,exactLength:{value:$,message:T.toString(J)}})}nonempty($){return this.min(1,$)}}N0.create=($,J)=>{return new N0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...h(J)})};function f$($){if($ instanceof $0){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=Z0.create(f$(X))}return new $0({...$._def,shape:()=>J})}else if($ instanceof N0)return new N0({...$._def,type:f$($.element)});else if($ instanceof Z0)return Z0.create(f$($.unwrap()));else if($ instanceof l0)return l0.create(f$($.unwrap()));else if($ instanceof v0)return v0.create($.items.map((J)=>f$(J)));else return $}class $0 extends k{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($)!==b.object){let H=this._getOrReturnCtx($);return S(H,{code:A.invalid_type,expected:b.object,received:H.parsedType}),I}let{status:Q,ctx:X}=this._processInputParams($),{shape:W,keys:G}=this._getCached(),Y=[];if(!(this._def.catchall instanceof I0&&this._def.unknownKeys==="strip")){for(let H in X.data)if(!G.includes(H))Y.push(H)}let q=[];for(let H of G){let B=W[H],U=X.data[H];q.push({key:{status:"valid",value:H},value:B._parse(new w0(X,U,X.path,H)),alwaysSet:H in X.data})}if(this._def.catchall instanceof I0){let H=this._def.unknownKeys;if(H==="passthrough")for(let B of Y)q.push({key:{status:"valid",value:B},value:{status:"valid",value:X.data[B]}});else if(H==="strict"){if(Y.length>0)S(X,{code:A.unrecognized_keys,keys:Y}),Q.dirty()}else if(H==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let H=this._def.catchall;for(let B of Y){let U=X.data[B];q.push({key:{status:"valid",value:B},value:H._parse(new w0(X,U,X.path,B)),alwaysSet:B in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let H=[];for(let B of q){let U=await B.key,z=await B.value;H.push({key:U,value:z,alwaysSet:B.alwaysSet})}return H}).then((H)=>{return q0.mergeObjectSync(Q,H)});else return q0.mergeObjectSync(Q,q)}get shape(){return this._def.shape()}strict($){return T.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:T.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:j.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 f$(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 W=this.shape[Q];while(W instanceof Z0)W=W._def.innerType;J[Q]=W}return new $0({...this._def,shape:()=>J})}keyof(){return E7(l.objectKeys(this.shape))}}$0.create=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};$0.strictCreate=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strict",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};$0.lazycreate=($,J)=>{return new $0({shape:$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};class h$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(W){for(let Y of W)if(Y.result.status==="valid")return Y.result;for(let Y of W)if(Y.result.status==="dirty")return J.common.issues.push(...Y.ctx.common.issues),Y.result;let G=W.map((Y)=>new Y0(Y.ctx.common.issues));return S(J,{code:A.invalid_union,unionErrors:G}),I}if(J.common.async)return Promise.all(Q.map(async(W)=>{let G={...J,common:{...J.common,issues:[]},parent:null};return{result:await W._parseAsync({data:J.data,path:J.path,parent:G}),ctx:G}})).then(X);else{let W=void 0,G=[];for(let q of Q){let H={...J,common:{...J.common,issues:[]},parent:null},B=q._parseSync({data:J.data,path:J.path,parent:H});if(B.status==="valid")return B;else if(B.status==="dirty"&&!W)W={result:B,ctx:H};if(H.common.issues.length)G.push(H.common.issues)}if(W)return J.common.issues.push(...W.ctx.common.issues),W.result;let Y=G.map((q)=>new Y0(q));return S(J,{code:A.invalid_union,unionErrors:Y}),I}}get options(){return this._def.options}}h$.create=($,J)=>{return new h$({options:$,typeName:j.ZodUnion,...h(J)})};var u0=($)=>{if($ instanceof g$)return u0($.schema);else if($ instanceof b0)return u0($.innerType());else if($ instanceof k$)return[$.value];else if($ instanceof o0)return $.options;else if($ instanceof m$)return l.objectValues($.enum);else if($ instanceof u$)return u0($._def.innerType);else if($ instanceof v$)return[void 0];else if($ instanceof x$)return[null];else if($ instanceof Z0)return[void 0,...u0($.unwrap())];else if($ instanceof l0)return[null,...u0($.unwrap())];else if($ instanceof R6)return u0($.unwrap());else if($ instanceof c$)return u0($.unwrap());else if($ instanceof l$)return u0($._def.innerType);else return[]};class K6 extends k{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.object)return S(J,{code:A.invalid_type,expected:b.object,received:J.parsedType}),I;let Q=this.discriminator,X=J.data[Q],W=this.optionsMap.get(X);if(!W)return S(J,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),I;if(J.common.async)return W._parseAsync({data:J.data,path:J.path,parent:J});else return W._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 W of J){let G=u0(W.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Y of G){if(X.has(Y))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Y)}`);X.set(Y,W)}}return new K6({typeName:j.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function $4($,J){let Q=T0($),X=T0(J);if($===J)return{valid:!0,data:$};else if(Q===b.object&&X===b.object){let W=l.objectKeys(J),G=l.objectKeys($).filter((q)=>W.indexOf(q)!==-1),Y={...$,...J};for(let q of G){let H=$4($[q],J[q]);if(!H.valid)return{valid:!1};Y[q]=H.data}return{valid:!0,data:Y}}else if(Q===b.array&&X===b.array){if($.length!==J.length)return{valid:!1};let W=[];for(let G=0;G<$.length;G++){let Y=$[G],q=J[G],H=$4(Y,q);if(!H.valid)return{valid:!1};W.push(H.data)}return{valid:!0,data:W}}else if(Q===b.date&&X===b.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class y$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(W,G)=>{if(O6(W)||O6(G))return I;let Y=$4(W.value,G.value);if(!Y.valid)return S(Q,{code:A.invalid_intersection_types}),I;if(M6(W)||M6(G))J.dirty();return{status:J.value,value:Y.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(([W,G])=>X(W,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}))}}y$.create=($,J,Q)=>{return new y$({left:$,right:J,typeName:j.ZodIntersection,...h(Q)})};class v0 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.array)return S(Q,{code:A.invalid_type,expected:b.array,received:Q.parsedType}),I;if(Q.data.length<this._def.items.length)return S(Q,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&Q.data.length>this._def.items.length)S(Q,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let W=[...Q.data].map((G,Y)=>{let q=this._def.items[Y]||this._def.rest;if(!q)return null;return q._parse(new w0(Q,G,Q.path,Y))}).filter((G)=>!!G);if(Q.common.async)return Promise.all(W).then((G)=>{return q0.mergeArray(J,G)});else return q0.mergeArray(J,W)}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:j.ZodTuple,rest:null,...h(J)})};class O2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.object)return S(Q,{code:A.invalid_type,expected:b.object,received:Q.parsedType}),I;let X=[],W=this._def.keyType,G=this._def.valueType;for(let Y in Q.data)X.push({key:W._parse(new w0(Q,Y,Q.path,Y)),value:G._parse(new w0(Q,Q.data[Y],Q.path,Y)),alwaysSet:Y in Q.data});if(Q.common.async)return q0.mergeObjectAsync(J,X);else return q0.mergeObjectSync(J,X)}get element(){return this._def.valueType}static create($,J,Q){if(J instanceof k)return new O2({keyType:$,valueType:J,typeName:j.ZodRecord,...h(Q)});return new O2({keyType:j0.create(),valueType:$,typeName:j.ZodRecord,...h(J)})}}class M2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.map)return S(Q,{code:A.invalid_type,expected:b.map,received:Q.parsedType}),I;let X=this._def.keyType,W=this._def.valueType,G=[...Q.data.entries()].map(([Y,q],H)=>{return{key:X._parse(new w0(Q,Y,Q.path,[H,"key"])),value:W._parse(new w0(Q,q,Q.path,[H,"value"]))}});if(Q.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let q of G){let H=await q.key,B=await q.value;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();Y.set(H.value,B.value)}return{status:J.value,value:Y}})}else{let Y=new Map;for(let q of G){let{key:H,value:B}=q;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();Y.set(H.value,B.value)}return{status:J.value,value:Y}}}}M2.create=($,J,Q)=>{return new M2({valueType:J,keyType:$,typeName:j.ZodMap,...h(Q)})};class D$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.set)return S(Q,{code:A.invalid_type,expected:b.set,received:Q.parsedType}),I;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)S(Q,{code:A.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)S(Q,{code:A.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let W=this._def.valueType;function G(q){let H=new Set;for(let B of q){if(B.status==="aborted")return I;if(B.status==="dirty")J.dirty();H.add(B.value)}return{status:J.value,value:H}}let Y=[...Q.data.values()].map((q,H)=>W._parse(new w0(Q,q,Q.path,H)));if(Q.common.async)return Promise.all(Y).then((q)=>G(q));else return G(Y)}min($,J){return new D$({...this._def,minSize:{value:$,message:T.toString(J)}})}max($,J){return new D$({...this._def,maxSize:{value:$,message:T.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}D$.create=($,J)=>{return new D$({valueType:$,minSize:null,maxSize:null,typeName:j.ZodSet,...h(J)})};class T$ extends k{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.function)return S(J,{code:A.invalid_type,expected:b.function,received:J.parsedType}),I;function Q(Y,q){return z2({data:Y,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),m0].filter((H)=>!!H),issueData:{code:A.invalid_arguments,argumentsError:q}})}function X(Y,q){return z2({data:Y,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),m0].filter((H)=>!!H),issueData:{code:A.invalid_return_type,returnTypeError:q}})}let W={errorMap:J.common.contextualErrorMap},G=J.data;if(this._def.returns instanceof F$){let Y=this;return B0(async function(...q){let H=new Y0([]),B=await Y._def.args.parseAsync(q,W).catch((V)=>{throw H.addIssue(Q(q,V)),H}),U=await Reflect.apply(G,this,B);return await Y._def.returns._def.type.parseAsync(U,W).catch((V)=>{throw H.addIssue(X(U,V)),H})})}else{let Y=this;return B0(function(...q){let H=Y._def.args.safeParse(q,W);if(!H.success)throw new Y0([Q(q,H.error)]);let B=Reflect.apply(G,this,H.data),U=Y._def.returns.safeParse(B,W);if(!U.success)throw new Y0([X(B,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new T$({...this._def,args:v0.create($).rest(r0.create())})}returns($){return new T$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new T$({args:$?$:v0.create([]).rest(r0.create()),returns:J||r0.create(),typeName:j.ZodFunction,...h(Q)})}}class g$ extends k{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})}}g$.create=($,J)=>{return new g$({getter:$,typeName:j.ZodLazy,...h(J)})};class k$ extends k{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return S(J,{received:J.data,code:A.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:$.data}}get value(){return this._def.value}}k$.create=($,J)=>{return new k$({value:$,typeName:j.ZodLiteral,...h(J)})};function E7($,J){return new o0({values:$,typeName:j.ZodEnum,...h(J)})}class o0 extends k{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{expected:l.joinValues(Q),received:J.parsedType,code:A.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{received:J.data,code:A.invalid_enum_value,options:Q}),I}return B0($.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 o0.create($,{...this._def,...J})}exclude($,J=this._def){return o0.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}o0.create=E7;class m$ extends k{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==b.string&&Q.parsedType!==b.number){let X=l.objectValues(J);return S(Q,{expected:l.joinValues(X),received:Q.parsedType,code:A.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return S(Q,{received:Q.data,code:A.invalid_enum_value,options:X}),I}return B0($.data)}get enum(){return this._def.values}}m$.create=($,J)=>{return new m$({values:$,typeName:j.ZodNativeEnum,...h(J)})};class F$ extends k{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.promise&&J.common.async===!1)return S(J,{code:A.invalid_type,expected:b.promise,received:J.parsedType}),I;let Q=J.parsedType===b.promise?J.data:Promise.resolve(J.data);return B0(Q.then((X)=>{return this._def.type.parseAsync(X,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}F$.create=($,J)=>{return new F$({type:$,typeName:j.ZodPromise,...h(J)})};class b0 extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,W={addIssue:(G)=>{if(S(Q,G),G.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(W.addIssue=W.addIssue.bind(W),X.type==="preprocess"){let G=X.transform(Q.data,W);if(Q.common.async)return Promise.resolve(G).then(async(Y)=>{if(J.value==="aborted")return I;let q=await this._def.schema._parseAsync({data:Y,path:Q.path,parent:Q});if(q.status==="aborted")return I;if(q.status==="dirty")return U$(q.value);if(J.value==="dirty")return U$(q.value);return q});else{if(J.value==="aborted")return I;let Y=this._def.schema._parseSync({data:G,path:Q.path,parent:Q});if(Y.status==="aborted")return I;if(Y.status==="dirty")return U$(Y.value);if(J.value==="dirty")return U$(Y.value);return Y}}if(X.type==="refinement"){let G=(Y)=>{let q=X.refinement(Y,W);if(Q.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Y};if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return I;if(Y.status==="dirty")J.dirty();return G(Y.value),{status:J.value,value:Y.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(Y.status==="aborted")return I;if(Y.status==="dirty")J.dirty();return G(Y.value).then(()=>{return{status:J.value,value:Y.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(!n0(G))return I;let Y=X.transform(G.value,W);if(Y instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:Y}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(!n0(G))return I;return Promise.resolve(X.transform(G.value,W)).then((Y)=>({status:J.value,value:Y}))});l.assertNever(X)}}b0.create=($,J,Q)=>{return new b0({schema:$,typeName:j.ZodEffects,effect:J,...h(Q)})};b0.createWithPreprocess=($,J,Q)=>{return new b0({schema:J,effect:{type:"preprocess",transform:$},typeName:j.ZodEffects,...h(Q)})};class Z0 extends k{_parse($){if(this._getType($)===b.undefined)return B0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z0.create=($,J)=>{return new Z0({innerType:$,typeName:j.ZodOptional,...h(J)})};class l0 extends k{_parse($){if(this._getType($)===b.null)return B0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}l0.create=($,J)=>{return new l0({innerType:$,typeName:j.ZodNullable,...h(J)})};class u$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===b.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}u$.create=($,J)=>{return new u$({innerType:$,typeName:j.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class l$ extends k{_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(C$(X))return X.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new Y0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new Y0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}l$.create=($,J)=>{return new l$({innerType:$,typeName:j.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class K2 extends k{_parse($){if(this._getType($)!==b.nan){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.nan,received:Q.parsedType}),I}return{status:"valid",value:$.data}}}K2.create=($)=>{return new K2({typeName:j.ZodNaN,...h($)})};var DX=Symbol("zod_brand");class R6 extends k{_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 R2 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return I;if(W.status==="dirty")return J.dirty(),U$(W.value);else return this._def.out._parseAsync({data:W.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 I;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 R2({in:$,out:J,typeName:j.ZodPipeline})}}class c$ extends k{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(n0(X))X.value=Object.freeze(X.value);return X};return C$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}c$.create=($,J)=>{return new c$({innerType:$,typeName:j.ZodReadonly,...h(J)})};function w7($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function C7($,J={},Q){if($)return z$.create().superRefine((X,W)=>{let G=$(X);if(G instanceof Promise)return G.then((Y)=>{if(!Y){let q=w7(J,X),H=q.fatal??Q??!0;W.addIssue({code:"custom",...q,fatal:H})}});if(!G){let Y=w7(J,X),q=Y.fatal??Q??!0;W.addIssue({code:"custom",...Y,fatal:q})}return});return z$.create()}var FX={object:$0.lazycreate},j;(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"})(j||(j={}));var OX=($,J={message:`Input not instance of ${$.name}`})=>C7((Q)=>Q instanceof $,J),f7=j0.create,T7=a0.create,MX=K2.create,KX=s0.create,I7=I$.create,RX=V$.create,LX=D2.create,AX=v$.create,_X=x$.create,jX=z$.create,NX=r0.create,ZX=I0.create,wX=F2.create,bX=N0.create,PX=$0.create,SX=$0.strictCreate,EX=h$.create,CX=K6.create,fX=y$.create,TX=v0.create,IX=O2.create,vX=M2.create,xX=D$.create,hX=T$.create,yX=g$.create,gX=k$.create,kX=o0.create,mX=m$.create,uX=F$.create,lX=b0.create,cX=Z0.create,dX=l0.create,pX=b0.createWithPreprocess,iX=R2.create,nX=()=>f7().optional(),rX=()=>T7().optional(),aX=()=>I7().optional(),sX={string:($)=>j0.create({...$,coerce:!0}),number:($)=>a0.create({...$,coerce:!0}),boolean:($)=>I$.create({...$,coerce:!0}),bigint:($)=>s0.create({...$,coerce:!0}),date:($)=>V$.create({...$,coerce:!0})};var oX=I;var J4=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 tX($){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 v7($){let J=Date.now();return{alive:!1,status:"not_found",createdAt:J,lastUpdatedAt:J,description:`No background process found with id '${$}'.`}}var oM={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
443
|
+
`).all($).map((Q)=>{let X=Number(Q.span_count)||0,W=Number(Q.error_count)||0,G=Q.end_time??void 0,Y=W===0?"ok":W>=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:Y}})}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 W=J.get(X.parentSpanId);if(W)W.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var z7=()=>{};import{appendFileSync as SQ,existsSync as EQ,mkdirSync as CQ}from"fs";import{join as U2}from"path";import{AsyncLocalStorage as F7}from"async_hooks";function D7($,J){return $.padStart(J,"0")}function m9($){return/^[0-9a-f]+$/i.test($)}function AQ($){let J=D7($.traceId.toLowerCase(),R7),Q=D7($.spanId.toLowerCase(),L7);return[c9,J,Q,jQ].join("-")}function _Q($){if(!$||typeof $!=="string")return;let Q=$.trim().split("-");if(Q.length!==4)return;let[X,W,G,Y]=Q;if(X!==c9){if(X>c9)return}if(W.length!==R7||!m9(W))return;if(G.length!==L7||!m9(G))return;if(Y.length!==NQ||!m9(Y))return;return{traceId:W.toLowerCase(),spanId:G.toLowerCase()}}var c9="00",jQ="01",u9="TRACEPARENT",R7=32,L7=16,NQ=2,i9,ZQ=a(()=>{i9={inject($,J){$[u9]=AQ(J)},extract($){let J=$[u9];if(!J)return;return _Q(J)},getTraceparentHeader(){return u9}}}),wQ,bQ,PQ=a(()=>{(($)=>{$.CLIENT="client",$.SERVER="server",$.INTERNAL="internal"})(wQ||={}),(($)=>{$.OK="ok",$.ERROR="error"})(bQ||={})});function n9($){let J=$.replace(/\\/g,"/"),Q=J.match(/\/\$bunfs\/root\/(.+)$/);if(Q){let Y=Q[1],q=Y.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(q)return q[1];return Y}let X=J.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let Y=X[1].replace(/\+/g,"/"),q=X[2],H=Y,B=q.startsWith("src/")?q:`src/${q}`;return`${H}/${B}`}let W=J.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];let G=["packages/core/src","packages/core","packages"];for(let Y of G){let q=J.indexOf(Y);if(q!==-1)return J.substring(q)}return J}function fQ(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let J=e("xdg-basedir");if(J.xdgData)return U2(J.xdgData,"roy-agent","logs")}catch{}return U2($,".local","share","roy-agent","logs")}function TQ(){return kQ}function IQ(){if(_0){let J=_0.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 vQ($){if(_0){let X=_0.get("log_trace.logging.levels");if(X&&typeof X==="object"){let G=X[$];if(G&&["debug","info","warn","error"].includes(G))return G}let W=_0.get(`log_trace.logging.levels.${$}`);if(W&&["debug","info","warn","error"].includes(W))return W}let J=`LOG_LEVEL_${$.toUpperCase().replace(/:/g,"_")}`,Q=process.env[J];if(Q&&["debug","info","warn","error"].includes(Q))return Q;return IQ()}function xQ($){if($.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test($))return!0;return!1}function hQ($){if($.startsWith("~")){let J=process.env.HOME||process.env.USERPROFILE||"/tmp";return U2(J,$.slice(1))}return $}function yQ(){if(_0){let $=_0.get("log-trace.logging.file");if($)return $}return"app.log"}function gQ(){if(_0){let $=_0.get("log-trace.logging.dir");if($)return $}return fQ()}function r9(){if(_0){let $=_0.get("log-trace.logging.maxOutput");if(typeof $==="number")return $}return}class A7{prefix;constructor($){this.prefix=$}shouldLog($){let J=vQ(this.prefix);return d9[$]>=d9[J]}ensureLogDirectory($){if(!EQ($))try{CQ($,{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(`
|
|
444
|
+
`)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let W=Q[X];if(W.includes("at ")&&!W.includes("logger.ts")&&!W.includes("formatMessage")){let G=W.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||W.match(/at\s+(.+):(\d+):\d+/);if(G){let Y=G[1];return{file:this.getRelativePath(Y),line:parseInt(G[2],10)}}}}return null}getRelativePath($){return n9($)}formatMessage($,J,Q){let X=new Date,W=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}]`:"",Y="";try{let V=V2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)Y=`[traceId=${V.traceId}]`}catch{}let q="";if(Q&&typeof Q==="object"&&"callerLocation"in Q){let U=Q;q=U.callerLocation?` [${U.callerLocation}]`:"";let{callerLocation:z,...V}=U;Q=Object.keys(V).length>0?V:void 0}else{let U=this.getCallerLocation();if(U)q=` [${U.file}:${U.line}]`}let H=`${W} [${$.toUpperCase()}]${Y}${q}${G} ${J}`;if(Q!==void 0)if(typeof Q==="object")H+=" "+JSON.stringify(Q).replace(/\n/g,"");else H+=" "+String(Q);let B=r9();if(B&&B>0&&H.length>B)H=H.substring(0,B)+" [TRUNCATED]";return H}writeToFile($){try{let J=gQ(),Q=yQ(),X=hQ(J),W=xQ(X)?X:U2(process.cwd(),X);this.ensureLogDirectory(W);let G=U2(W,Q);SQ(G,$+`
|
|
445
|
+
`,"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),!TQ())if(mQ)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(!F6.has($))F6.set($,new A7($));return F6.get($)}var _0=null,kQ=!1,mQ=!1;var d9,F6,r=a(()=>{o9(),d9={debug:0,info:1,warn:2,error:3},F6=new Map}),uQ={};i0(uQ,{setTracerProvider:()=>cQ,resetTracerProvider:()=>lQ,getTracerProvider:()=>V2,OTelTracerProvider:()=>s9});function a9(){if(!l9)l9=i("otel-tracer");return l9}function _7(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function j7($,...J){a9().info($,...J)}function O7($,...J){a9().warn($,...J)}function M7($,...J){a9().error($,...J)}class p9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,W){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=W}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(_7())j7(`[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)O7(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=V2().getStorage();if(X){if(!(X.db||X.initialized))O7(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((G)=>{M7("[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 M7(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class N7{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,W=J&&"context"in J,G=this.provider.getGlobalContext(),Y,q,H,B,U;if(W&&J?.context){let V=J.context;q=V.traceId,H=this.generateSpanId(),B=V.spanId,U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let M=new p9($,U,this.storage,V,()=>this.handleSpanEnd(U.spanId,V.spanId));if(J?.attributes)for(let[F,D]of Object.entries(J.attributes))M.setAttribute(F,D);return this.activeSpans.set(H,M),M}if(X)Y=Q;else if(this.currentContext)Y=this.currentContext;else if(G)Y=G;if(q=Y?.traceId||this.generateTraceId(),H=this.generateSpanId(),X&&Q)B=Q.parentSpanId||Q.spanId;else if(this.currentContext)B=this.currentContext.spanId;else if(G)B=G.spanId;U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let z=new p9($,U,this.storage,Y,()=>this.handleSpanEnd(U.spanId,Y?.spanId));if(J?.attributes)for(let[V,M]of Object.entries(J.attributes))z.setAttribute(V,M);if(this.activeSpans.set(H,z),_7())j7(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${q} spanId=${H} parentSpanId=${B||"-"}`);return z}injectToEnv($){if(this.currentContext)i9.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 W=this.activeSpans.get(J.parentSpanId);if(W){let G={traceId:J.traceId,spanId:W.spanContext.spanId,parentSpanId:W.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 W={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=W,W}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 s9{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new F7;tracerContexts=new Map;tracerContextScope=new F7;instanceId;constructor($,J){K7++,this.instanceId=`Provider#${K7}`,this.storage=$||new k9(J||dQ())}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 N7($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=i9.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 V2(){if(!k0)k0=new s9;return k0}function lQ(){if(k0)k0.shutdown(),k0=null}function cQ($){if(k0)k0.shutdown();k0=$}function dQ(){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 l9=null,k0=null,K7=0,o9=a(()=>{z7(),ZQ(),PQ(),r()});var K={};t1(K,{void:()=>SX,util:()=>l,unknown:()=>bX,union:()=>TX,undefined:()=>NX,tuple:()=>xX,transformer:()=>pX,symbol:()=>jX,string:()=>T7,strictObject:()=>fX,setErrorMap:()=>nQ,set:()=>gX,record:()=>hX,quotelessJson:()=>pQ,promise:()=>dX,preprocess:()=>rX,pipeline:()=>aX,ostring:()=>sX,optional:()=>iX,onumber:()=>oX,oboolean:()=>tX,objectUtil:()=>t9,object:()=>CX,number:()=>I7,nullable:()=>nX,null:()=>ZX,never:()=>PX,nativeEnum:()=>cX,nan:()=>LX,map:()=>yX,makeIssue:()=>z2,literal:()=>uX,lazy:()=>mX,late:()=>KX,isValid:()=>n0,isDirty:()=>M6,isAsync:()=>C$,isAborted:()=>O6,intersection:()=>vX,instanceof:()=>RX,getParsedType:()=>T0,getErrorMap:()=>E$,function:()=>kX,enum:()=>lX,effect:()=>pX,discriminatedUnion:()=>IX,defaultErrorMap:()=>m0,datetimeRegex:()=>E7,date:()=>_X,custom:()=>f7,coerce:()=>eX,boolean:()=>v7,bigint:()=>AX,array:()=>EX,any:()=>wX,addIssueToContext:()=>S,ZodVoid:()=>F2,ZodUnknown:()=>r0,ZodUnion:()=>h$,ZodUndefined:()=>v$,ZodType:()=>k,ZodTuple:()=>v0,ZodTransformer:()=>b0,ZodSymbol:()=>D2,ZodString:()=>j0,ZodSet:()=>D$,ZodSchema:()=>k,ZodRecord:()=>O2,ZodReadonly:()=>c$,ZodPromise:()=>F$,ZodPipeline:()=>R2,ZodParsedType:()=>b,ZodOptional:()=>Z0,ZodObject:()=>$0,ZodNumber:()=>a0,ZodNullable:()=>l0,ZodNull:()=>x$,ZodNever:()=>I0,ZodNativeEnum:()=>m$,ZodNaN:()=>K2,ZodMap:()=>M2,ZodLiteral:()=>k$,ZodLazy:()=>g$,ZodIssueCode:()=>A,ZodIntersection:()=>y$,ZodFunction:()=>T$,ZodFirstPartyTypeKind:()=>j,ZodError:()=>Y0,ZodEnum:()=>o0,ZodEffects:()=>b0,ZodDiscriminatedUnion:()=>K6,ZodDefault:()=>u$,ZodDate:()=>V$,ZodCatch:()=>l$,ZodBranded:()=>R6,ZodBoolean:()=>I$,ZodBigInt:()=>s0,ZodArray:()=>N0,ZodAny:()=>z$,Schema:()=>k,ParseStatus:()=>q0,OK:()=>B0,NEVER:()=>$W,INVALID:()=>I,EMPTY_PATH:()=>rQ,DIRTY:()=>U$,BRAND:()=>MX});var l;(function($){$.assertEqual=(W)=>{};function J(W){}$.assertIs=J;function Q(W){throw Error()}$.assertNever=Q,$.arrayToEnum=(W)=>{let G={};for(let Y of W)G[Y]=Y;return G},$.getValidEnumValues=(W)=>{let G=$.objectKeys(W).filter((q)=>typeof W[W[q]]!=="number"),Y={};for(let q of G)Y[q]=W[q];return $.objectValues(Y)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(G){return W[G]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let G=[];for(let Y in W)if(Object.prototype.hasOwnProperty.call(W,Y))G.push(Y);return G},$.find=(W,G)=>{for(let Y of W)if(G(Y))return Y;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function X(W,G=" | "){return W.map((Y)=>typeof Y==="string"?`'${Y}'`:Y).join(G)}$.joinValues=X,$.jsonStringifyReplacer=(W,G)=>{if(typeof G==="bigint")return G.toString();return G}})(l||(l={}));var t9;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(t9||(t9={}));var b=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T0=($)=>{switch(typeof $){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN($)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":if(Array.isArray($))return b.array;if($===null)return b.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return b.promise;if(typeof Map<"u"&&$ instanceof Map)return b.map;if(typeof Set<"u"&&$ instanceof Set)return b.set;if(typeof Date<"u"&&$ instanceof Date)return b.date;return b.object;default:return b.unknown}};var A=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"]),pQ=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class Y0 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(W){return W.message},Q={_errors:[]},X=(W)=>{for(let G of W.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 Y=Q,q=0;while(q<G.path.length){let H=G.path[q];if(q!==G.path.length-1)Y[H]=Y[H]||{_errors:[]};else Y[H]=Y[H]||{_errors:[]},Y[H]._errors.push(J(G));Y=Y[H],q++}}};return X(this),Q}static assert($){if(!($ instanceof Y0))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 W=X.path[0];J[W]=J[W]||[],J[W].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}Y0.create=($)=>{return new Y0($)};var iQ=($,J)=>{let Q;switch($.code){case A.invalid_type:if($.received===b.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case A.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case A.invalid_union:Q="Invalid input";break;case A.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case A.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case A.invalid_arguments:Q="Invalid function arguments";break;case A.invalid_return_type:Q="Invalid function return type";break;case A.invalid_date:Q="Invalid date";break;case A.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 A.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 A.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 A.custom:Q="Invalid input";break;case A.invalid_intersection_types:Q="Intersection results could not be merged";break;case A.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case A.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},m0=iQ;var Z7=m0;function nQ($){Z7=$}function E$(){return Z7}var z2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:W}=$,G=[...Q,...W.path||[]],Y={...W,path:G};if(W.message!==void 0)return{...W,path:G,message:W.message};let q="",H=X.filter((B)=>!!B).slice().reverse();for(let B of H)q=B(Y,{data:J,defaultError:q}).message;return{...W,path:G,message:q}},rQ=[];function S($,J){let Q=E$(),X=z2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===m0?void 0:m0].filter((W)=>!!W)});$.common.issues.push(X)}class q0{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 I;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 W=await X.key,G=await X.value;Q.push({key:W,value:G})}return q0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:W,value:G}=X;if(W.status==="aborted")return I;if(G.status==="aborted")return I;if(W.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof G.value<"u"||X.alwaysSet))Q[W.value]=G.value}return{status:$.value,value:Q}}}var I=Object.freeze({status:"aborted"}),U$=($)=>({status:"dirty",value:$}),B0=($)=>({status:"valid",value:$}),O6=($)=>$.status==="aborted",M6=($)=>$.status==="dirty",n0=($)=>$.status==="valid",C$=($)=>typeof Promise<"u"&&$ instanceof Promise;var T;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(T||(T={}));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 w7=($,J)=>{if(n0(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 Y0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:W}=$;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:W};return{errorMap:(Y,q)=>{let{message:H}=$;if(Y.code==="invalid_enum_value")return{message:H??q.defaultError};if(typeof q.data>"u")return{message:H??X??q.defaultError};if(Y.code!=="invalid_type")return{message:q.defaultError};return{message:H??Q??q.defaultError}},description:W}}class k{get description(){return this._def.description}_getType($){return T0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new q0,ctx:{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(C$(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:T0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return w7(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return n0(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)=>n0(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:T0($)},X=this._parse({data:$,path:Q.path,parent:Q}),W=await(C$(X)?X:Promise.resolve(X));return w7(Q,W)}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,W)=>{let G=$(X),Y=()=>W.addIssue({code:A.custom,...Q(X)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((q)=>{if(!q)return Y(),!1;else return!0});if(!G)return Y(),!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 b0({schema:this,typeName:j.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 l0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return N0.create(this)}promise(){return F$.create(this,this._def)}or($){return h$.create([this,$],this._def)}and($){return y$.create(this,$,this._def)}transform($){return new b0({...h(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new u$({...h(this._def),innerType:this,defaultValue:J,typeName:j.ZodDefault})}brand(){return new R6({typeName:j.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new l$({...h(this._def),innerType:this,catchValue:J,typeName:j.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return R2.create(this,$)}readonly(){return c$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var aQ=/^c[^\s-]{8,}$/i,sQ=/^[0-9a-z]+$/,oQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,tQ=/^[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,eQ=/^[a-z0-9_-]{21}$/i,$X=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JX=/^[-+]?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,XX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",e9,WX=/^(?:(?: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])$/,GX=/^(?:(?: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])$/,YX=/^(([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]))$/,qX=/^(([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])$/,HX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,P7="((\\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])))",UX=new RegExp(`^${P7}$`);function S7($){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 VX($){return new RegExp(`^${S7($)}$`)}function E7($){let J=`${P7}T${S7($)}`,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)&&WX.test($))return!0;if((J==="v6"||!J)&&YX.test($))return!0;return!1}function DX($,J){if(!$X.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,"="),W=JSON.parse(atob(X));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(J&&W.alg!==J)return!1;return!0}catch{return!1}}function FX($,J){if((J==="v4"||!J)&&GX.test($))return!0;if((J==="v6"||!J)&&qX.test($))return!0;return!1}class j0 extends k{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==b.string){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.string,received:W.parsedType}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.length<W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="max"){if($.data.length>W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="length"){let G=$.data.length>W.value,Y=$.data.length<W.value;if(G||Y){if(X=this._getOrReturnCtx($,X),G)S(X,{code:A.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});else if(Y)S(X,{code:A.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});Q.dirty()}}else if(W.kind==="email"){if(!QX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"email",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="emoji"){if(!e9)e9=new RegExp(XX,"u");if(!e9.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"emoji",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="uuid"){if(!tQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"uuid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="nanoid"){if(!eQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"nanoid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid"){if(!aQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid2"){if(!sQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid2",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ulid"){if(!oQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"ulid",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),S(X,{validation:"url",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="regex"){if(W.regex.lastIndex=0,!W.regex.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"regex",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="trim")$.data=$.data.trim();else if(W.kind==="includes"){if(!$.data.includes(W.value,W.position))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{includes:W.value,position:W.position},message:W.message}),Q.dirty()}else if(W.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(W.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(W.kind==="startsWith"){if(!$.data.startsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{startsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="endsWith"){if(!$.data.endsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:{endsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="datetime"){if(!E7(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"datetime",message:W.message}),Q.dirty()}else if(W.kind==="date"){if(!UX.test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"date",message:W.message}),Q.dirty()}else if(W.kind==="time"){if(!VX(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:A.invalid_string,validation:"time",message:W.message}),Q.dirty()}else if(W.kind==="duration"){if(!JX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"duration",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ip"){if(!zX($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"ip",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="jwt"){if(!DX($.data,W.alg))X=this._getOrReturnCtx($,X),S(X,{validation:"jwt",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cidr"){if(!FX($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"cidr",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64"){if(!HX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64",code:A.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64url"){if(!BX.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64url",code:A.invalid_string,message:W.message}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:A.invalid_string,...T.errToObj(Q)})}_addCheck($){return new j0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...T.errToObj($)})}url($){return this._addCheck({kind:"url",...T.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...T.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...T.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...T.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...T.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...T.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...T.errToObj($)})}base64($){return this._addCheck({kind:"base64",...T.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...T.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...T.errToObj($)})}ip($){return this._addCheck({kind:"ip",...T.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...T.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...T.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...T.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...T.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...T.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...T.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...T.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...T.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...T.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...T.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...T.errToObj(J)})}nonempty($){return this.min(1,T.errToObj($))}trim(){return new j0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new j0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new j0({...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 $}}j0.create=($)=>{return new j0({checks:[],typeName:j.ZodString,coerce:$?.coerce??!1,...h($)})};function OX($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,W=Q>X?Q:X,G=Number.parseInt($.toFixed(W).replace(".","")),Y=Number.parseInt(J.toFixed(W).replace(".",""));return G%Y/10**W}class a0 extends k{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($)!==b.number){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.number,received:W.parsedType}),I}let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.invalid_type,expected:"integer",received:"float",message:W.message}),X.dirty()}else if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_small,minimum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if(OX($.data,W.value)!==0)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_finite,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new a0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new a0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:T.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.toString(J)})}finite($){return this._addCheck({kind:"finite",message:T.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString($)})}get minValue(){let $=null;for(let 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($)}}a0.create=($)=>{return new a0({checks:[],typeName:j.ZodNumber,coerce:$?.coerce||!1,...h($)})};class s0 extends k{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($)!==b.bigint)return this._getInvalidInput($);let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_small,type:"bigint",minimum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:A.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),S(Q,{code:A.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return S(J,{code:A.invalid_type,expected:b.bigint,received:J.parsedType}),I}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new s0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.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 $}}s0.create=($)=>{return new s0({checks:[],typeName:j.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class I$ extends k{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==b.boolean){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.boolean,received:Q.parsedType}),I}return B0($.data)}}I$.create=($)=>{return new I$({typeName:j.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class V$ extends k{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==b.date){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_type,expected:b.date,received:W.parsedType}),I}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return S(W,{code:A.invalid_date}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()<W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_small,message:W.message,inclusive:!0,exact:!1,minimum:W.value,type:"date"}),Q.dirty()}else if(W.kind==="max"){if($.data.getTime()>W.value)X=this._getOrReturnCtx($,X),S(X,{code:A.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new V$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:T.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:T.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}}V$.create=($)=>{return new V$({checks:[],coerce:$?.coerce||!1,typeName:j.ZodDate,...h($)})};class D2 extends k{_parse($){if(this._getType($)!==b.symbol){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.symbol,received:Q.parsedType}),I}return B0($.data)}}D2.create=($)=>{return new D2({typeName:j.ZodSymbol,...h($)})};class v$ extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.undefined,received:Q.parsedType}),I}return B0($.data)}}v$.create=($)=>{return new v$({typeName:j.ZodUndefined,...h($)})};class x$ extends k{_parse($){if(this._getType($)!==b.null){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.null,received:Q.parsedType}),I}return B0($.data)}}x$.create=($)=>{return new x$({typeName:j.ZodNull,...h($)})};class z$ extends k{constructor(){super(...arguments);this._any=!0}_parse($){return B0($.data)}}z$.create=($)=>{return new z$({typeName:j.ZodAny,...h($)})};class r0 extends k{constructor(){super(...arguments);this._unknown=!0}_parse($){return B0($.data)}}r0.create=($)=>{return new r0({typeName:j.ZodUnknown,...h($)})};class I0 extends k{_parse($){let J=this._getOrReturnCtx($);return S(J,{code:A.invalid_type,expected:b.never,received:J.parsedType}),I}}I0.create=($)=>{return new I0({typeName:j.ZodNever,...h($)})};class F2 extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.void,received:Q.parsedType}),I}return B0($.data)}}F2.create=($)=>{return new F2({typeName:j.ZodVoid,...h($)})};class N0 extends k{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==b.array)return S(J,{code:A.invalid_type,expected:b.array,received:J.parsedType}),I;if(X.exactLength!==null){let G=J.data.length>X.exactLength.value,Y=J.data.length<X.exactLength.value;if(G||Y)S(J,{code:G?A.too_big:A.too_small,minimum:Y?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)S(J,{code:A.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)S(J,{code:A.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,Y)=>{return X.type._parseAsync(new w0(J,G,J.path,Y))})).then((G)=>{return q0.mergeArray(Q,G)});let W=[...J.data].map((G,Y)=>{return X.type._parseSync(new w0(J,G,J.path,Y))});return q0.mergeArray(Q,W)}get element(){return this._def.type}min($,J){return new N0({...this._def,minLength:{value:$,message:T.toString(J)}})}max($,J){return new N0({...this._def,maxLength:{value:$,message:T.toString(J)}})}length($,J){return new N0({...this._def,exactLength:{value:$,message:T.toString(J)}})}nonempty($){return this.min(1,$)}}N0.create=($,J)=>{return new N0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...h(J)})};function f$($){if($ instanceof $0){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=Z0.create(f$(X))}return new $0({...$._def,shape:()=>J})}else if($ instanceof N0)return new N0({...$._def,type:f$($.element)});else if($ instanceof Z0)return Z0.create(f$($.unwrap()));else if($ instanceof l0)return l0.create(f$($.unwrap()));else if($ instanceof v0)return v0.create($.items.map((J)=>f$(J)));else return $}class $0 extends k{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($)!==b.object){let H=this._getOrReturnCtx($);return S(H,{code:A.invalid_type,expected:b.object,received:H.parsedType}),I}let{status:Q,ctx:X}=this._processInputParams($),{shape:W,keys:G}=this._getCached(),Y=[];if(!(this._def.catchall instanceof I0&&this._def.unknownKeys==="strip")){for(let H in X.data)if(!G.includes(H))Y.push(H)}let q=[];for(let H of G){let B=W[H],U=X.data[H];q.push({key:{status:"valid",value:H},value:B._parse(new w0(X,U,X.path,H)),alwaysSet:H in X.data})}if(this._def.catchall instanceof I0){let H=this._def.unknownKeys;if(H==="passthrough")for(let B of Y)q.push({key:{status:"valid",value:B},value:{status:"valid",value:X.data[B]}});else if(H==="strict"){if(Y.length>0)S(X,{code:A.unrecognized_keys,keys:Y}),Q.dirty()}else if(H==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let H=this._def.catchall;for(let B of Y){let U=X.data[B];q.push({key:{status:"valid",value:B},value:H._parse(new w0(X,U,X.path,B)),alwaysSet:B in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let H=[];for(let B of q){let U=await B.key,z=await B.value;H.push({key:U,value:z,alwaysSet:B.alwaysSet})}return H}).then((H)=>{return q0.mergeObjectSync(Q,H)});else return q0.mergeObjectSync(Q,q)}get shape(){return this._def.shape()}strict($){return T.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:T.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:j.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 f$(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 W=this.shape[Q];while(W instanceof Z0)W=W._def.innerType;J[Q]=W}return new $0({...this._def,shape:()=>J})}keyof(){return C7(l.objectKeys(this.shape))}}$0.create=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};$0.strictCreate=($,J)=>{return new $0({shape:()=>$,unknownKeys:"strict",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};$0.lazycreate=($,J)=>{return new $0({shape:$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};class h$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(W){for(let Y of W)if(Y.result.status==="valid")return Y.result;for(let Y of W)if(Y.result.status==="dirty")return J.common.issues.push(...Y.ctx.common.issues),Y.result;let G=W.map((Y)=>new Y0(Y.ctx.common.issues));return S(J,{code:A.invalid_union,unionErrors:G}),I}if(J.common.async)return Promise.all(Q.map(async(W)=>{let G={...J,common:{...J.common,issues:[]},parent:null};return{result:await W._parseAsync({data:J.data,path:J.path,parent:G}),ctx:G}})).then(X);else{let W=void 0,G=[];for(let q of Q){let H={...J,common:{...J.common,issues:[]},parent:null},B=q._parseSync({data:J.data,path:J.path,parent:H});if(B.status==="valid")return B;else if(B.status==="dirty"&&!W)W={result:B,ctx:H};if(H.common.issues.length)G.push(H.common.issues)}if(W)return J.common.issues.push(...W.ctx.common.issues),W.result;let Y=G.map((q)=>new Y0(q));return S(J,{code:A.invalid_union,unionErrors:Y}),I}}get options(){return this._def.options}}h$.create=($,J)=>{return new h$({options:$,typeName:j.ZodUnion,...h(J)})};var u0=($)=>{if($ instanceof g$)return u0($.schema);else if($ instanceof b0)return u0($.innerType());else if($ instanceof k$)return[$.value];else if($ instanceof o0)return $.options;else if($ instanceof m$)return l.objectValues($.enum);else if($ instanceof u$)return u0($._def.innerType);else if($ instanceof v$)return[void 0];else if($ instanceof x$)return[null];else if($ instanceof Z0)return[void 0,...u0($.unwrap())];else if($ instanceof l0)return[null,...u0($.unwrap())];else if($ instanceof R6)return u0($.unwrap());else if($ instanceof c$)return u0($.unwrap());else if($ instanceof l$)return u0($._def.innerType);else return[]};class K6 extends k{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.object)return S(J,{code:A.invalid_type,expected:b.object,received:J.parsedType}),I;let Q=this.discriminator,X=J.data[Q],W=this.optionsMap.get(X);if(!W)return S(J,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),I;if(J.common.async)return W._parseAsync({data:J.data,path:J.path,parent:J});else return W._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 W of J){let G=u0(W.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Y of G){if(X.has(Y))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Y)}`);X.set(Y,W)}}return new K6({typeName:j.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function $4($,J){let Q=T0($),X=T0(J);if($===J)return{valid:!0,data:$};else if(Q===b.object&&X===b.object){let W=l.objectKeys(J),G=l.objectKeys($).filter((q)=>W.indexOf(q)!==-1),Y={...$,...J};for(let q of G){let H=$4($[q],J[q]);if(!H.valid)return{valid:!1};Y[q]=H.data}return{valid:!0,data:Y}}else if(Q===b.array&&X===b.array){if($.length!==J.length)return{valid:!1};let W=[];for(let G=0;G<$.length;G++){let Y=$[G],q=J[G],H=$4(Y,q);if(!H.valid)return{valid:!1};W.push(H.data)}return{valid:!0,data:W}}else if(Q===b.date&&X===b.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class y$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(W,G)=>{if(O6(W)||O6(G))return I;let Y=$4(W.value,G.value);if(!Y.valid)return S(Q,{code:A.invalid_intersection_types}),I;if(M6(W)||M6(G))J.dirty();return{status:J.value,value:Y.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(([W,G])=>X(W,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}))}}y$.create=($,J,Q)=>{return new y$({left:$,right:J,typeName:j.ZodIntersection,...h(Q)})};class v0 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.array)return S(Q,{code:A.invalid_type,expected:b.array,received:Q.parsedType}),I;if(Q.data.length<this._def.items.length)return S(Q,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&Q.data.length>this._def.items.length)S(Q,{code:A.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let W=[...Q.data].map((G,Y)=>{let q=this._def.items[Y]||this._def.rest;if(!q)return null;return q._parse(new w0(Q,G,Q.path,Y))}).filter((G)=>!!G);if(Q.common.async)return Promise.all(W).then((G)=>{return q0.mergeArray(J,G)});else return q0.mergeArray(J,W)}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:j.ZodTuple,rest:null,...h(J)})};class O2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.object)return S(Q,{code:A.invalid_type,expected:b.object,received:Q.parsedType}),I;let X=[],W=this._def.keyType,G=this._def.valueType;for(let Y in Q.data)X.push({key:W._parse(new w0(Q,Y,Q.path,Y)),value:G._parse(new w0(Q,Q.data[Y],Q.path,Y)),alwaysSet:Y in Q.data});if(Q.common.async)return q0.mergeObjectAsync(J,X);else return q0.mergeObjectSync(J,X)}get element(){return this._def.valueType}static create($,J,Q){if(J instanceof k)return new O2({keyType:$,valueType:J,typeName:j.ZodRecord,...h(Q)});return new O2({keyType:j0.create(),valueType:$,typeName:j.ZodRecord,...h(J)})}}class M2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.map)return S(Q,{code:A.invalid_type,expected:b.map,received:Q.parsedType}),I;let X=this._def.keyType,W=this._def.valueType,G=[...Q.data.entries()].map(([Y,q],H)=>{return{key:X._parse(new w0(Q,Y,Q.path,[H,"key"])),value:W._parse(new w0(Q,q,Q.path,[H,"value"]))}});if(Q.common.async){let Y=new Map;return Promise.resolve().then(async()=>{for(let q of G){let H=await q.key,B=await q.value;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();Y.set(H.value,B.value)}return{status:J.value,value:Y}})}else{let Y=new Map;for(let q of G){let{key:H,value:B}=q;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();Y.set(H.value,B.value)}return{status:J.value,value:Y}}}}M2.create=($,J,Q)=>{return new M2({valueType:J,keyType:$,typeName:j.ZodMap,...h(Q)})};class D$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.set)return S(Q,{code:A.invalid_type,expected:b.set,received:Q.parsedType}),I;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)S(Q,{code:A.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)S(Q,{code:A.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let W=this._def.valueType;function G(q){let H=new Set;for(let B of q){if(B.status==="aborted")return I;if(B.status==="dirty")J.dirty();H.add(B.value)}return{status:J.value,value:H}}let Y=[...Q.data.values()].map((q,H)=>W._parse(new w0(Q,q,Q.path,H)));if(Q.common.async)return Promise.all(Y).then((q)=>G(q));else return G(Y)}min($,J){return new D$({...this._def,minSize:{value:$,message:T.toString(J)}})}max($,J){return new D$({...this._def,maxSize:{value:$,message:T.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}D$.create=($,J)=>{return new D$({valueType:$,minSize:null,maxSize:null,typeName:j.ZodSet,...h(J)})};class T$ extends k{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.function)return S(J,{code:A.invalid_type,expected:b.function,received:J.parsedType}),I;function Q(Y,q){return z2({data:Y,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),m0].filter((H)=>!!H),issueData:{code:A.invalid_arguments,argumentsError:q}})}function X(Y,q){return z2({data:Y,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),m0].filter((H)=>!!H),issueData:{code:A.invalid_return_type,returnTypeError:q}})}let W={errorMap:J.common.contextualErrorMap},G=J.data;if(this._def.returns instanceof F$){let Y=this;return B0(async function(...q){let H=new Y0([]),B=await Y._def.args.parseAsync(q,W).catch((V)=>{throw H.addIssue(Q(q,V)),H}),U=await Reflect.apply(G,this,B);return await Y._def.returns._def.type.parseAsync(U,W).catch((V)=>{throw H.addIssue(X(U,V)),H})})}else{let Y=this;return B0(function(...q){let H=Y._def.args.safeParse(q,W);if(!H.success)throw new Y0([Q(q,H.error)]);let B=Reflect.apply(G,this,H.data),U=Y._def.returns.safeParse(B,W);if(!U.success)throw new Y0([X(B,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new T$({...this._def,args:v0.create($).rest(r0.create())})}returns($){return new T$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new T$({args:$?$:v0.create([]).rest(r0.create()),returns:J||r0.create(),typeName:j.ZodFunction,...h(Q)})}}class g$ extends k{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})}}g$.create=($,J)=>{return new g$({getter:$,typeName:j.ZodLazy,...h(J)})};class k$ extends k{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return S(J,{received:J.data,code:A.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:$.data}}get value(){return this._def.value}}k$.create=($,J)=>{return new k$({value:$,typeName:j.ZodLiteral,...h(J)})};function C7($,J){return new o0({values:$,typeName:j.ZodEnum,...h(J)})}class o0 extends k{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{expected:l.joinValues(Q),received:J.parsedType,code:A.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{received:J.data,code:A.invalid_enum_value,options:Q}),I}return B0($.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 o0.create($,{...this._def,...J})}exclude($,J=this._def){return o0.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}o0.create=C7;class m$ extends k{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==b.string&&Q.parsedType!==b.number){let X=l.objectValues(J);return S(Q,{expected:l.joinValues(X),received:Q.parsedType,code:A.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return S(Q,{received:Q.data,code:A.invalid_enum_value,options:X}),I}return B0($.data)}get enum(){return this._def.values}}m$.create=($,J)=>{return new m$({values:$,typeName:j.ZodNativeEnum,...h(J)})};class F$ extends k{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.promise&&J.common.async===!1)return S(J,{code:A.invalid_type,expected:b.promise,received:J.parsedType}),I;let Q=J.parsedType===b.promise?J.data:Promise.resolve(J.data);return B0(Q.then((X)=>{return this._def.type.parseAsync(X,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}F$.create=($,J)=>{return new F$({type:$,typeName:j.ZodPromise,...h(J)})};class b0 extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,W={addIssue:(G)=>{if(S(Q,G),G.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(W.addIssue=W.addIssue.bind(W),X.type==="preprocess"){let G=X.transform(Q.data,W);if(Q.common.async)return Promise.resolve(G).then(async(Y)=>{if(J.value==="aborted")return I;let q=await this._def.schema._parseAsync({data:Y,path:Q.path,parent:Q});if(q.status==="aborted")return I;if(q.status==="dirty")return U$(q.value);if(J.value==="dirty")return U$(q.value);return q});else{if(J.value==="aborted")return I;let Y=this._def.schema._parseSync({data:G,path:Q.path,parent:Q});if(Y.status==="aborted")return I;if(Y.status==="dirty")return U$(Y.value);if(J.value==="dirty")return U$(Y.value);return Y}}if(X.type==="refinement"){let G=(Y)=>{let q=X.refinement(Y,W);if(Q.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Y};if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return I;if(Y.status==="dirty")J.dirty();return G(Y.value),{status:J.value,value:Y.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(Y.status==="aborted")return I;if(Y.status==="dirty")J.dirty();return G(Y.value).then(()=>{return{status:J.value,value:Y.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(!n0(G))return I;let Y=X.transform(G.value,W);if(Y instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:Y}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(!n0(G))return I;return Promise.resolve(X.transform(G.value,W)).then((Y)=>({status:J.value,value:Y}))});l.assertNever(X)}}b0.create=($,J,Q)=>{return new b0({schema:$,typeName:j.ZodEffects,effect:J,...h(Q)})};b0.createWithPreprocess=($,J,Q)=>{return new b0({schema:J,effect:{type:"preprocess",transform:$},typeName:j.ZodEffects,...h(Q)})};class Z0 extends k{_parse($){if(this._getType($)===b.undefined)return B0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}Z0.create=($,J)=>{return new Z0({innerType:$,typeName:j.ZodOptional,...h(J)})};class l0 extends k{_parse($){if(this._getType($)===b.null)return B0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}l0.create=($,J)=>{return new l0({innerType:$,typeName:j.ZodNullable,...h(J)})};class u$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===b.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}u$.create=($,J)=>{return new u$({innerType:$,typeName:j.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class l$ extends k{_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(C$(X))return X.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new Y0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new Y0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}l$.create=($,J)=>{return new l$({innerType:$,typeName:j.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class K2 extends k{_parse($){if(this._getType($)!==b.nan){let Q=this._getOrReturnCtx($);return S(Q,{code:A.invalid_type,expected:b.nan,received:Q.parsedType}),I}return{status:"valid",value:$.data}}}K2.create=($)=>{return new K2({typeName:j.ZodNaN,...h($)})};var MX=Symbol("zod_brand");class R6 extends k{_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 R2 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return I;if(W.status==="dirty")return J.dirty(),U$(W.value);else return this._def.out._parseAsync({data:W.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 I;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 R2({in:$,out:J,typeName:j.ZodPipeline})}}class c$ extends k{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(n0(X))X.value=Object.freeze(X.value);return X};return C$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}c$.create=($,J)=>{return new c$({innerType:$,typeName:j.ZodReadonly,...h(J)})};function b7($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function f7($,J={},Q){if($)return z$.create().superRefine((X,W)=>{let G=$(X);if(G instanceof Promise)return G.then((Y)=>{if(!Y){let q=b7(J,X),H=q.fatal??Q??!0;W.addIssue({code:"custom",...q,fatal:H})}});if(!G){let Y=b7(J,X),q=Y.fatal??Q??!0;W.addIssue({code:"custom",...Y,fatal:q})}return});return z$.create()}var KX={object:$0.lazycreate},j;(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"})(j||(j={}));var RX=($,J={message:`Input not instance of ${$.name}`})=>f7((Q)=>Q instanceof $,J),T7=j0.create,I7=a0.create,LX=K2.create,AX=s0.create,v7=I$.create,_X=V$.create,jX=D2.create,NX=v$.create,ZX=x$.create,wX=z$.create,bX=r0.create,PX=I0.create,SX=F2.create,EX=N0.create,CX=$0.create,fX=$0.strictCreate,TX=h$.create,IX=K6.create,vX=y$.create,xX=v0.create,hX=O2.create,yX=M2.create,gX=D$.create,kX=T$.create,mX=g$.create,uX=k$.create,lX=o0.create,cX=m$.create,dX=F$.create,pX=b0.create,iX=Z0.create,nX=l0.create,rX=b0.createWithPreprocess,aX=R2.create,sX=()=>T7().optional(),oX=()=>I7().optional(),tX=()=>v7().optional(),eX={string:($)=>j0.create({...$,coerce:!0}),number:($)=>a0.create({...$,coerce:!0}),boolean:($)=>I$.create({...$,coerce:!0}),bigint:($)=>s0.create({...$,coerce:!0}),date:($)=>V$.create({...$,coerce:!0})};var $W=I;var J4=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 JW($){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 x7($){let J=Date.now();return{alive:!1,status:"not_found",createdAt:J,lastUpdatedAt:J,description:`No background process found with id '${$}'.`}}var $K={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
445
446
|
|
|
446
447
|
Use this tool when:
|
|
447
448
|
- 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.
|
|
@@ -475,7 +476,7 @@ Use this tool when:
|
|
|
475
476
|
- result: present when status is 'completed'
|
|
476
477
|
- error: present when status is 'failed'
|
|
477
478
|
|
|
478
|
-
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:J4,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(),W=J4.parse(J),{bgProcessId:G}=W;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 Y;try{Y=$.getTask(G)}catch(H){return{success:!1,output:"",error:`failed to query background task: ${H.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(Y){let H=Q.session_id;if(!H||Y.parentSessionId!==H)return{success:!0,output:JSON.stringify(
|
|
479
|
+
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:J4,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(),W=J4.parse(J),{bgProcessId:G}=W;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 Y;try{Y=$.getTask(G)}catch(H){return{success:!1,output:"",error:`failed to query background task: ${H.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(Y){let H=Q.session_id;if(!H||Y.parentSessionId!==H)return{success:!0,output:JSON.stringify(x7(G),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:G,status:"not_found",alive:!1}}}let q=Y?JW(Y):x7(G);if(q.alive)try{let H=await $.getSubSessionActivity?.(G);if(H)q.lastUpdatedAt=Math.max(q.lastUpdatedAt,H.updatedAt),q.messageCount=H.messageCount,q.subSessionUpdatedAt=H.updatedAt}catch{}return{success:!0,output:JSON.stringify(q,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:G,status:q.status,alive:q.alive}}}}}r();var L2=i("compact-session-tool"),h7=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 QW($){return{status:"not_found",sessionId:$}}function XW($,J){let X=($.listTasks()??[]).find((W)=>W.subSessionId===J);if(X)return X;return $.getTask(J)}function WW($,J){if(!$||!J)return!1;return $.parentSessionId===J}function GW($){return $?.status==="running"||$?.status==="pending"}function Q4($=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.
|
|
479
480
|
|
|
480
481
|
Use this tool when:
|
|
481
482
|
- 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.
|
|
@@ -494,7 +495,7 @@ Guards:
|
|
|
494
495
|
- You can only compact sub-sessions YOU delegated (ownership check).
|
|
495
496
|
- A session whose background task is still running/pending cannot be compacted (stop_task it first to avoid corrupting live state).
|
|
496
497
|
|
|
497
|
-
Only the default receptionist agent has this tool.`,parameters:
|
|
498
|
+
Only the default receptionist agent has this tool.`,parameters:h7,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 W=Date.now(),Y=h7.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()-W}};let q=X.session_id;if(q&&Y===q)return{success:!1,output:"",error:`Refusing to compact session '${Y}': 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()-W}};if(!q)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()-W}};let H=XW($,Y);if(!H||!WW(H,q))return L2.warn("[compact_session] not_found (unknown or foreign sub-session)",{sessionId:Y,currentSessionId:q}),{success:!0,output:JSON.stringify(QW(Y),null,2),metadata:{execution_time_ms:Date.now()-W,sessionId:Y,status:"not_found"}};if(GW(H))return{success:!1,output:"",error:`Cannot compact session '${Y}': its background task '${H.id}' is still ${H.status}. The sub-agent writes to this session every ReAct iteration; archiving messages now would corrupt live state. Run stop_task(task_id="${H.id}") first, then compact the session.`,metadata:{execution_time_ms:Date.now()-W,sessionId:Y,bgProcessId:H.id,taskStatus:H.status}};let B;try{B=await J.previewCompact(Y)}catch(M){return{success:!1,output:"",error:`failed to preview compaction for session '${Y}': ${M.message}`,metadata:{execution_time_ms:Date.now()-W}}}if(!B||B.messageCountToCompact<3)return{success:!1,output:"",error:`Cannot compact session '${Y}': minimum 3 compactable messages required (found ${B?.messageCountToCompact??0}).`,metadata:{execution_time_ms:Date.now()-W,sessionId:Y,messageCountToCompact:B?.messageCountToCompact??0}};let U="";try{U=await J.generateCompactHint(Y)}catch(M){L2.warn("[compact_session] hint generation failed, continuing with empty hint",{sessionId:Y,error:M.message}),U=""}let z;try{z=await J.compact(Y,{scenarioHint:U})}catch(M){let F=M.message;return L2.error(`[compact_session] compact failed: ${F}`,{sessionId:Y}),{success:!1,output:"",error:`compaction failed for session '${Y}': ${F}`,metadata:{execution_time_ms:Date.now()-W,sessionId:Y}}}try{$.env?.pushEnvEvent?.({type:"context.compacted",metadata:{sessionId:Y},payload:{checkpointId:z.checkpoint.id,messagesCompacted:z.deletedMessageCount,scenarioHintUsed:U.length>0,source:"compact_session_tool"}})}catch(M){L2.warn("[compact_session] failed to push context.compacted event",{sessionId:Y,error:M.message})}let V={status:"compacted",sessionId:Y,checkpointId:z.checkpoint.id,checkpointTitle:z.checkpoint.title,contentLength:z.checkpoint.content?.length??0,originalMessages:B.messageCountToCompact,deletedMessages:z.deletedMessageCount,remainingMessages:z.remainingMessageCount,hintUsed:U.length>0};return L2.info("[compact_session] session compacted",{sessionId:Y,checkpointId:V.checkpointId,deletedMessages:V.deletedMessages,remainingMessages:V.remainingMessages}),{success:!0,output:JSON.stringify(V,null,2),metadata:{execution_time_ms:Date.now()-W,sessionId:Y,status:"compacted",checkpointId:V.checkpointId}}}}}var y7=Q4(null,null);var g7=K.object({task_id:K.string().describe("The ID of the background task to stop")}),YW=`Stop a running background task.
|
|
498
499
|
|
|
499
500
|
Use this tool to stop a background task that is currently running. This is useful when:
|
|
500
501
|
- The user wants to cancel a long-running task
|
|
@@ -504,11 +505,11 @@ Use this tool to stop a background task that is currently running. This is usefu
|
|
|
504
505
|
When stopped, the task will be terminated immediately and you will receive a confirmation.
|
|
505
506
|
|
|
506
507
|
Parameters:
|
|
507
|
-
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function
|
|
508
|
+
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function qW($){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 k7($){return{name:"stop_task",description:YW,parameters:g7,execute:async(J,Q)=>{let X=Date.now(),W=g7.parse(J),{task_id:G}=W,Y=await $.stopTask(G);if(Y.success){let q=Y.task,H=q.startedAt?Date.now()-q.startedAt:Date.now()-q.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${G}`,`\uD83D\uDCDD Description: ${q.description}`,`\uD83D\uDD04 Status: ${q.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${qW(H)}`,"",Y.message].join(`
|
|
508
509
|
`),metadata:{execution_time_ms:Date.now()-X,task_id:G,previous_status:q.status}}}else{let q=Y.task,H;if(q)H=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${G}`,`\uD83D\uDCDD Description: ${q.description}`,`\uD83D\uDD04 Current Status: ${q.status}`,"",Y.message].join(`
|
|
509
510
|
`);else H=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${G}`,"",Y.message].join(`
|
|
510
|
-
`);return{success:!1,output:H,error:Y.message,metadata:{execution_time_ms:Date.now()-X,task_id:G}}}}}}import{AsyncLocalStorage as
|
|
511
|
-
`)||[];Error.stackTraceLimit=F;for(let R=1;R<O.length;R++){let L=O[R];if(L.includes("decorator.ts")||L.includes("decorator.js")||L.includes("logFn")||L.includes("getCallerLocation"))continue;let _=L.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||L.match(/at\s+(.+):(\d+):\d+/);if(_){let Z=_[1];if(!Z||Z==="native")continue;return`${n9(Z)}:${_[2]}`}}return""},M=(F,D,O)=>{if(!W)return;let R=i("traced:"+J),_=`[TRACE] ${F==="enter"?">>>":F==="quit"?"<<<":"!!!"} ${J}`,Z=O||V(),P=(w,f)=>{if(f!==void 0)R.info(`${_} ${w}: ${q(f)}`,{callerLocation:Z});else R.info(`${_} ${w}`,{callerLocation:Z})};if(F==="enter")P("enter",D);else if(F==="quit")P("quit",X.logResult??X.recordResult?D:void 0);else P("error",D)};return function(...F){let D=V2().getTracer("roy-tracer"),O={};if(X.recordParams!==!1)if(X.paramFilter){let _=U(()=>X.paramFilter(F));if(O.params=H(_),X.flattenParamFilter&&_&&typeof _==="object"&&!Array.isArray(_)){for(let[Z,P]of Object.entries(_))if(!(Z in O))O[Z]=H(P)}}else O.params=H(F);let R=V(),L;try{L=D.startSpan(J,{attributes:O})}catch{}M("enter",F,R);try{let _=$.call(this,...F);if(_&&typeof _==="object"&&typeof _.then==="function")return _.then((Z)=>{if(L){let P=X.resultFilter!==void 0,w=X.resultFilter?U(()=>X.resultFilter(Z)):void 0;if(w&&typeof w==="object"&&!Array.isArray(w))for(let[E,x]of Object.entries(w))L.setAttribute(E,H(x));let f=z(Z,{ran:P,value:w});if(f.store)L.setAttribute("result",JSON.stringify(H(f.value)));let N=X.errorIf?U(()=>X.errorIf(Z)):void 0;if(N){let E=N instanceof Error?N:Error(String(N));L.setAttribute("error",E.message),L.end(void 0,E)}else L.end(f.store?f.value:void 0)}return M("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 M("error",Z.message,R),Z});if(L){let Z=X.resultFilter!==void 0,P=X.resultFilter?U(()=>X.resultFilter(_)):void 0;if(P&&typeof P==="object"&&!Array.isArray(P))for(let[N,E]of Object.entries(P))L.setAttribute(N,H(E));let w=z(_,{ran:Z,value:P});if(w.store)L.setAttribute("result",JSON.stringify(H(w.value)));let f=X.errorIf?U(()=>X.errorIf(_)):void 0;if(f){let N=f instanceof Error?f:Error(String(f));L.setAttribute("error",N.message),L.end(void 0,N)}else L.end(w.store?w.value:void 0)}return M("quit",X.logResult??X.recordResult?_:void 0,R),_}catch(_){if(L)L.setAttribute("error",String(_)),L.end(void 0,_ instanceof Error?_:Error(String(_)));throw M("error",_.message,R),_}}}var z0=a(()=>{o9(),r(),
|
|
511
|
+
`);return{success:!1,output:H,error:Y.message,metadata:{execution_time_ms:Date.now()-X,task_id:G}}}}}}import{AsyncLocalStorage as HW}from"async_hooks";r();var A6=i("process-tree-killer");function l7(){return e("child_process")}var m7;function BW($,J,Q){if(m7)return m7($,J,Q);return l7().spawn($,J,Q)}var u7;function UW($,J,Q){if(u7)return u7($,J,Q);let X=l7();if(typeof X.spawnSync!=="function")return;return X.spawnSync($,J,Q)}var VW;function zW(){return VW??process.platform}function DW($){try{return process.kill($,0),!0}catch(J){if(J.code==="ESRCH")return!1;return!0}}function FW($){try{let J=UW("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 OW($){return new Promise((J)=>setTimeout(J,$))}async function MW($,J){if(!Number.isInteger($)||$<=0)throw Error(`Invalid PID: ${$} (must be a positive integer)`);let Q=zW(),X=J?.signal??"SIGKILL",W=J?.retry??3,G=J?.retryDelayMs??500;A6.info(`[bg-process:kill-begin] pid=${$} signal=${X} retry=${W} delayMs=${G}`);for(let Y=1;Y<=W;Y++){let q=Q==="win32"?KW($):RW($,X,Q);if(await OW(G),!(Q==="win32"?FW($):DW($)))return A6.info(`[bg-process:kill-done] pid=${$} attempts=${Y} stillAlive=false`),{pid:$,platform:Q,signal:q.signal,success:!0,attempts:Y,stillAlive:!1};if(Y<W)A6.warn(`[bg-process:kill-retry] pid=${$} attempt=${Y}/${W}`)}return A6.error(`[bg-process:kill-failed] pid=${$} attempts=${W} stillAlive=true`),{pid:$,platform:Q,signal:Q==="win32"?"taskkill /f /t":X,success:!1,attempts:W,stillAlive:!0}}function KW($){try{return BW("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 RW($,J,Q){try{return process.kill(-$,J),{pid:$,platform:Q,signal:J,success:!0}}catch(X){let W=X.code;if(W==="ESRCH"||W==="EPERM")return{pid:$,platform:Q,signal:J,success:!0};return{pid:$,platform:Q,signal:J,success:!1}}}r();var X4=i("task:process-registry");class W4{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);X4.info(`[bg-process:killAll-begin] count=${$.length} pids=[${$.join(",")}]`);for(let J of $)try{let Q=await MW(J,{retry:3,retryDelayMs:500});if(Q.stillAlive)X4.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{}X4.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var LW=new HW;function c7($,J){return LW.run($,J)}function AW(){if(_6!==void 0)return _6;let $=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return _6=$==="1"||$==="true"||$==="yes",_6}var _6;var _W=()=>{};function jW($){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,W){if(W!==void 0&&W!==null&&typeof W==="object"&&"value"in W){let q=W.value,H=$?.name||String(X);return W.value=U0(q,H,J()),W}let G=Q,Y=X||{};if(typeof G==="function"){let q=$?.name||(Y?.name?String(Y.name):"anonymous");return U0(G,q,J())}return G}}function u($,J){return jW({name:$,...J})}function U0($,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},W=X.log,G=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let F=r9();return F!==void 0?F:500},Y=(F)=>{if(F===void 0)return;if(F===null)return null;let D=G(),O;try{O=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(R){O=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}if(D>0&&O.length>D)return O.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(O)}catch{return O}},q=(F)=>{if(F===void 0)return"undefined";if(F===null)return"null";let D=G(),O;try{O=typeof F==="string"?F:JSON.stringify(F,null,0).replace(/\n/g,"")}catch(R){O=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}return D>0&&O.length>D?O.slice(0,D)+" [TRUNCATED]":O},H=(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)}]`}},B="[TRACE]",U=(F)=>{try{return F()}catch(D){try{i("traced:"+J).warn(`[trace] filter threw, ignoring: ${D instanceof Error?D.message:String(D)}`)}catch{}return}},z=(F,D)=>{if(X.recordResultToDb===!0)return{value:F,store:!0};if(AW())return{value:F,store:!0};if(X.resultFilter){let O=D?.ran?D.value:U(()=>X.resultFilter(F));if(O&&typeof O==="object"&&!Array.isArray(O))return{value:O,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 O=D.stack?.split(`
|
|
512
|
+
`)||[];Error.stackTraceLimit=F;for(let R=1;R<O.length;R++){let L=O[R];if(L.includes("decorator.ts")||L.includes("decorator.js")||L.includes("logFn")||L.includes("getCallerLocation"))continue;let _=L.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||L.match(/at\s+(.+):(\d+):\d+/);if(_){let Z=_[1];if(!Z||Z==="native")continue;return`${n9(Z)}:${_[2]}`}}return""},M=(F,D,O)=>{if(!W)return;let R=i("traced:"+J),_=`[TRACE] ${F==="enter"?">>>":F==="quit"?"<<<":"!!!"} ${J}`,Z=O||V(),P=(w,f)=>{if(f!==void 0)R.info(`${_} ${w}: ${q(f)}`,{callerLocation:Z});else R.info(`${_} ${w}`,{callerLocation:Z})};if(F==="enter")P("enter",D);else if(F==="quit")P("quit",X.logResult??X.recordResult?D:void 0);else P("error",D)};return function(...F){let D=V2().getTracer("roy-tracer"),O={};if(X.recordParams!==!1)if(X.paramFilter){let _=U(()=>X.paramFilter(F));if(O.params=H(_),X.flattenParamFilter&&_&&typeof _==="object"&&!Array.isArray(_)){for(let[Z,P]of Object.entries(_))if(!(Z in O))O[Z]=H(P)}}else O.params=H(F);let R=V(),L;try{L=D.startSpan(J,{attributes:O})}catch{}M("enter",F,R);try{let _=$.call(this,...F);if(_&&typeof _==="object"&&typeof _.then==="function")return _.then((Z)=>{if(L){let P=X.resultFilter!==void 0,w=X.resultFilter?U(()=>X.resultFilter(Z)):void 0;if(w&&typeof w==="object"&&!Array.isArray(w))for(let[E,x]of Object.entries(w))L.setAttribute(E,H(x));let f=z(Z,{ran:P,value:w});if(f.store)L.setAttribute("result",JSON.stringify(H(f.value)));let N=X.errorIf?U(()=>X.errorIf(Z)):void 0;if(N){let E=N instanceof Error?N:Error(String(N));L.setAttribute("error",E.message),L.end(void 0,E)}else L.end(f.store?f.value:void 0)}return M("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 M("error",Z.message,R),Z});if(L){let Z=X.resultFilter!==void 0,P=X.resultFilter?U(()=>X.resultFilter(_)):void 0;if(P&&typeof P==="object"&&!Array.isArray(P))for(let[N,E]of Object.entries(P))L.setAttribute(N,H(E));let w=z(_,{ran:Z,value:P});if(w.store)L.setAttribute("result",JSON.stringify(H(w.value)));let f=X.errorIf?U(()=>X.errorIf(_)):void 0;if(f){let N=f instanceof Error?f:Error(String(f));L.setAttribute("error",N.message),L.end(void 0,N)}else L.end(w.store?w.value:void 0)}return M("quit",X.logResult??X.recordResult?_:void 0,R),_}catch(_){if(L)L.setAttribute("error",String(_)),L.end(void 0,_ instanceof Error?_:Error(String(_)));throw M("error",_.message,R),_}}}var z0=a(()=>{o9(),r(),_W()});import{randomUUID as NW}from"crypto";z0();function ZW(){if(typeof Bun<"u"){let{Database:$}=e("bun:sqlite");return $}else return e("better-sqlite3")}function wW($){let Q=new(ZW())($);if(typeof Q.run!=="function")Q.run=function(X,...W){if(W.length>0)return this.prepare(X).run(...W);else return this.exec(X)};return Q}class G4{db;insertStmt;getByIdStmt;recentStmt;constructor($){this.db=wW($.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 (
|
|
512
513
|
event_id TEXT PRIMARY KEY,
|
|
513
514
|
es_type TEXT NOT NULL,
|
|
514
515
|
sender_id TEXT NOT NULL,
|
|
@@ -523,7 +524,7 @@ Parameters:
|
|
|
523
524
|
FROM event_store
|
|
524
525
|
WHERE es_type = ? AND sender_id = ?
|
|
525
526
|
ORDER BY created_at DESC
|
|
526
|
-
LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${
|
|
527
|
+
LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${NW()}`,X=Date.now(),W=JSON.stringify($.metadata??{}),G=$.rawEvent===void 0?null:bW($.rawEvent);return this.insertStmt.run(Q,J,$.senderId,$.text??null,W,G,X),Q}async getEventById($){let J=this.getByIdStmt.get($);if(!J)return null;return d7(J)}async getRecentEvents($,J,Q){return this.recentStmt.all($,J,Q).map((W)=>d7(W))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],G4.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],G4.prototype,"getEventById",null);function d7($){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 bW($){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 PW=null;function p7(){return PW}var Y4={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
|
|
527
528
|
|
|
528
529
|
## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
|
|
529
530
|
|
|
@@ -2207,8 +2208,8 @@ task_operation_create({
|
|
|
2207
2208
|
\u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
|
|
2208
2209
|
|
|
2209
2210
|
> \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
|
|
2210
|
-
`},FK=Y4["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 p7 from"os";import M0 from"path";var j6="roy-agent";function wW(){let $=p7.homedir();try{let J=e("xdg-basedir");return{config:J.xdgConfig||M0.join($,".config"),state:J.xdgState||M0.join($,".local","state"),data:J.xdgData||M0.join($,".local","share"),cache:J.xdgCache||M0.join($,".cache")}}catch{return{config:M0.join($,".config"),state:M0.join($,".local","state"),data:M0.join($,".local","share"),cache:M0.join($,".cache")}}}function bW(){let $=p7.homedir(),J=wW();return{home:$,config:M0.join(J.config,j6),state:M0.join(J.state,j6),data:M0.join(J.data,j6),cache:M0.join(J.cache,j6)}}class i7{_paths;get paths(){if(!this._paths)this._paths=bW();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return M0.join(this.paths[$],J)}reset(){this._paths=void 0}}var PW=new i7;function n7($){return PW.getPath($)}import*as PD from"fs/promises";import*as SD from"fs";import{join as J2}from"path";var L8=r1(X3(),1);r();z0();var s=i("agent:registry"),R8=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||SD,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=J2($.baseDir,"agents");else this.configDir=J2(n7("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=R8.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 W=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(W)return s.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),W}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 W=J2($,X.name);if(X.isDirectory())continue;if(!ED(X.name))continue;try{let G=await this.fsPromises.readFile(W,"utf-8"),Y=this.parseAgentConfig(G,W);if(Y)this.agents.set(Y.name,Y),s.info(`[AgentRegistry] Loaded agent: ${Y.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=L8.default.parse($),X=R8.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=R8.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=J2(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 L8.default.stringify(J).trimEnd()+`
|
|
2211
|
-
`}async deleteAgent($){if(!this.agents.get($))return s.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=J2(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 J2(this.configDir,`${$}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],L0.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],L0.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],L0.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"loadFromDirectory",null);function
|
|
2211
|
+
`},KK=Y4["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 i7 from"os";import M0 from"path";var j6="roy-agent";function SW(){let $=i7.homedir();try{let J=e("xdg-basedir");return{config:J.xdgConfig||M0.join($,".config"),state:J.xdgState||M0.join($,".local","state"),data:J.xdgData||M0.join($,".local","share"),cache:J.xdgCache||M0.join($,".cache")}}catch{return{config:M0.join($,".config"),state:M0.join($,".local","state"),data:M0.join($,".local","share"),cache:M0.join($,".cache")}}}function EW(){let $=i7.homedir(),J=SW();return{home:$,config:M0.join(J.config,j6),state:M0.join(J.state,j6),data:M0.join(J.data,j6),cache:M0.join(J.cache,j6)}}class n7{_paths;get paths(){if(!this._paths)this._paths=EW();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return M0.join(this.paths[$],J)}reset(){this._paths=void 0}}var CW=new n7;function r7($){return CW.getPath($)}import*as CD from"fs/promises";import*as fD from"fs";import{join as J2}from"path";var L8=a1(W3(),1);r();z0();var s=i("agent:registry"),R8=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||fD,this.fsPromises=$.fsPromises||CD;let J=this.configComponent?.get?.("agent.configDir");if(J&&typeof J==="string"&&J.length>0)this.configDir=J;else if($.baseDir)this.configDir=J2($.baseDir,"agents");else this.configDir=J2(r7("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=R8.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 W=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(W)return s.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),W}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 W=J2($,X.name);if(X.isDirectory())continue;if(!TD(X.name))continue;try{let G=await this.fsPromises.readFile(W,"utf-8"),Y=this.parseAgentConfig(G,W);if(Y)this.agents.set(Y.name,Y),s.info(`[AgentRegistry] Loaded agent: ${Y.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=L8.default.parse($),X=R8.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=R8.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=J2(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 L8.default.stringify(J).trimEnd()+`
|
|
2212
|
+
`}async deleteAgent($){if(!this.agents.get($))return s.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=J2(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 J2(this.configDir,`${$}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],L0.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],L0.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],L0.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],L0.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],L0.prototype,"loadFromDirectory",null);function TD($){return $.endsWith(".yaml")||$.endsWith(".yml")}var A8=`You are a subagent created by the main agent to handle a specific task.
|
|
2212
2213
|
|
|
2213
2214
|
## Your Role
|
|
2214
2215
|
- You were created to handle: {task_description}
|
|
@@ -2225,14 +2226,14 @@ task_operation_create({
|
|
|
2225
2226
|
## Execution
|
|
2226
2227
|
- Use the available tools to complete the task
|
|
2227
2228
|
- If you need more information, ask the main agent through the result
|
|
2228
|
-
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as
|
|
2229
|
+
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as ID}from"async_hooks";var vD=new ID;function _8($,J){return vD.run($,J)}import{AsyncLocalStorage as xD}from"async_hooks";var j8=()=>{};function Q2(){return c2.getStore()}function z9(){return c2.getStore()||{}}function d2(){return c2.getStore()?.agentContext?.currentTaskId}function G3($){return typeof $==="number"&&Number.isInteger($)&&$>0?$:void 0}var Y3,c2,hD,p2,q$=a(()=>{r(),z0(),j8(),Y3=i("env:context:env-context"),c2=new xD,hD=U0(function(J,Q){return G3(J?.metadata?.parentTaskId)??G3(Q?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:($)=>({parentTaskId:$??null})}),p2=U0(function(J){let Q=d2(),X=c2.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=J}Y3.info(`[setCurrentTaskId] taskId=${J??"undefined"} (was: ${Q??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var D9=a(()=>{q$(),j8()});class F9{_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((W)=>W.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($),W=process.env.ROY_HOOK_DEBUG==="1";if(W)console.error(`[DEBUG hook-manager.execute] hookPoint=${$}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(W)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${$})`);return}let G=Q2();if(W){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 Y=this.sortHooks(X),q=this.createContext($,J,Q,"before"),H=Q.pluginEnabled||{};if(W){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(H)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${Y.length}:`);for(let B of Y)console.error(`[DEBUG hook-manager.execute] - name=${B.name} pluginName=${B.pluginName} sourceId=${B.sourceId}`)}for(let B of Y){if(B.pluginName&&B.sourceId){let U=`${B.sourceId}:${B.pluginName}`,z=H[U];if(W)console.error(`[DEBUG hook-manager.execute] hook ${B.name} (${U}) enabled=${z}`);if(z!==!0){if(W)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${U}] !== true, got ${JSON.stringify(z)})`);continue}}else if(W)console.error(`[DEBUG hook-manager.execute] hook ${B.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(W)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${B.name}`);await this.safeExecute(B,q)}}async executeAndCollect($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return[];let W=this.sortHooks(X),G=this.createContext($,J,Q,"before"),Y=[];for(let q of W){let H=await this.safeExecuteAndReturn(q,G);if(H!==void 0)Y.push(H)}return Y}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 W=this.sortHooks(X),G=this.createContext($,J,Q,"before"),Y=[],q=!1,H;for(let B of W){if(q)break;let U=await this.safeExecuteAndReturn(B,G);if(Y.push(U),U&&typeof U==="object"&&"stopped"in U){let z=U;if(z.stopped)q=!0,H=z.action}}return{stopped:q,action:H,results:Y}}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,W=Q.priority??this.defaultPriority;return X-W})}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 N8=a(()=>{D9()});function yD(){let $=E0.register.bind(E0);E0.register=function(J,Q){$(J,Q);let X=q3[J];if(X)$(X,Q)}}var E0,gD,kD,mD,q3,X2=a(()=>{N8(),E0=new F9,gD={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"},kD={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},mD={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"},q3={"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"},yD()});r();z0();D9();function uD($,J){if(P8($))return!0;return J?.hasAgent($)??!1}async function lD($,J={}){let X=(J.getBuiltIn??P8)($),W=J.registry?.get($);if(!X&&!W)return;if(W)return cD($,W,X,J.registry);return{subagentType:$,description:X.description,basePrompt:X.promptOverride||A8,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function cD($,J,Q,X){let W=X?await X.getSystemPrompt($):J.systemPrompt;return{subagentType:$,description:J.description||Q?.description||"Custom agent",basePrompt:W||Q?.promptOverride||A8,allowedTools:J.allowedTools??Q?.allowedTools,deniedTools:J.deniedTools??Q?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function dD($){return`
|
|
2229
2230
|
## Agent Selection Guide
|
|
2230
2231
|
|
|
2231
2232
|
- Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
|
|
2232
2233
|
${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
|
|
2233
|
-
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function
|
|
2234
|
-
`)+G}X2();var cD=[/\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 dD($){let J=$;for(let Q of cD)J=J.replace(Q,"<redacted>");return J}function pD($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function q3($,J){return pD(dD($),J)}class b8{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 W={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,W),this.childrenIndex.delete(W.taskId),this.indexParentChild(W),this.evictIfNeeded(),W}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??[]),W=$.excludeAncestorOf??$.excludeSelfOrDescendant,G=W?this.collectSubtree(W):new Set,Y=$.sinceHours?Date.now()-$.sinceHours*60*60*1000:0,q=Date.now(),H=new Set([...X,...G]),B=[];for(let U of this.records.values()){if(q-Date.parse(U.updatedAt)>this.ttlMs)continue;if(Y>0&&Date.parse(U.updatedAt)<Y)continue;if(H.has(U.taskId))continue;if($.scope){if($.scope.sessionId!==void 0&&U.source.sessionId!==$.scope.sessionId)continue;if($.scope.parentSessionId!==void 0&&U.source.parentSessionId!==$.scope.parentSessionId)continue;if($.scope.subagentType!==void 0&&U.source.subagentType!==$.scope.subagentType)continue}if(Q){if(!Q.includes(U.status))continue}else if(U.status==="archived")continue;B.push(U)}if($.activeChildFirst){let U=new Map;for(let z of B)U.set(z.taskId,this.hasActiveChild(z.taskId));B.sort((z,V)=>{let M=U.get(z.taskId)?1:0,F=U.get(V.taskId)?1:0;if(M!==F)return F-M;let D=Date.parse(V.updatedAt)-Date.parse(z.updatedAt);if(D!==0)return D;return V.taskId-z.taskId})}else B.sort((U,z)=>{let V=Date.parse(z.updatedAt)-Date.parse(U.updatedAt);if(V!==0)return V;return z.taskId-U.taskId});return B.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 W=this.childrenIndex.get($),G=W?Array.from(W):[],Y=G.length>0?1:0;X.maxDepth=Y;let q=G;while(q.length>0){let H=[];for(let B of q){let U=this.records.get(B);if(!U)continue;if(!Q&&U.status==="archived")continue;if(X.descendantCount++,U.status==="active")X.activeCount++;else if(U.status==="completed")X.completedCount++;let z=this.childrenIndex.get(B);if(z&&z.size>0)for(let V of z)H.push(V)}if(H.length>0)Y++,X.maxDepth=Y;q=H}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),W=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:q3($.description||"",this.maxDescriptionChars),goals:q3($.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(W,"branch"),worktree_path:this.pickString(W,"worktree_path"),parentBranch:this.pickString(W,"parent_branch"),context:W}}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=b8.STRIPPED_KEYS;for(let[X,W]of Object.entries($)){let G=X.toLowerCase();if(Q.some((Y)=>G.includes(Y)))continue;J[X]=this.stripSensitiveKeys(W)}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(),W=this.childrenIndex.get(X);if(!W)continue;for(let G of W)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)}}r();var O9=i("registry-hook-installer");function iD($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,W=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,G=Q.priority??100,Y=!1,q=(D,O)=>{try{J.record(D,O)}catch(R){O9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},H=(D,O)=>{try{J.update(D,O)}catch(R){O9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},B=(D)=>{try{J.remove(D)}catch(O){O9.warn(`[registry-hook-installer] remove failed for task #${D}: ${O instanceof Error?O.message:String(O)}`)}},U=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),z={name:`${W}:after-create`,priority:G,execute:async(D)=>{let O=D.data;if(O?.task)q(O.task,U())}},V={name:`${W}:after-update`,priority:G,execute:async(D)=>{let O=D.data;if(!O?.task)return;if(J.peekById(O.task.id))H(O.task,U());else q(O.task,U())}},M={name:`${W}:after-complete`,priority:G,execute:async(D)=>{let O=D.data;if(O?.task)H(O.task,U())}},F={name:`${W}:after-delete`,priority:G,execute:async(D)=>{let O=D.data;if(typeof O?.id==="number")B(O.id)}};return $.registerHook(X0.AFTER_CREATE,z),$.registerHook(X0.AFTER_UPDATE,V),$.registerHook(X0.AFTER_COMPLETE,M),$.registerHook(X0.AFTER_DELETE,F),{uninstall(){if(Y)return;Y=!0,$.unregisterHook(X0.AFTER_CREATE,z.name),$.unregisterHook(X0.AFTER_UPDATE,V.name),$.unregisterHook(X0.AFTER_COMPLETE,M.name),$.unregisterHook(X0.AFTER_DELETE,F.name),O9.debug(`[registry-hook-installer] uninstalled hooks (name=${W})`)}}}r();var Z8=i("task-reuse-registry"),nD={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},H3=new WeakMap;function rD($){let J=H3.get($);if(J)return J.registry;let Q=new b8(nD),X={uninstall:()=>{}};try{let G=$.getComponent?.("task");if(G?.registerHook)X=iD(G,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),Z8.debug("[task-reuse-registry] hook installed");else Z8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(G){Z8.warn(`[task-reuse-registry] hook install failed: ${G instanceof Error?G.message:String(G)}`)}let W={registry:Q,installHandle:X};return H3.set($,W),Q}var aD=[/\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 sD($){let J=$;for(let Q of aD)J=J.replace(Q,"<redacted>");return J}function B3($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function oD($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,W=$.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 Y=[];Y.push(`## ${W}`),Y.push(""),Y.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."),Y.push("");for(let H of G){if(Y.push(`### Task #${H.taskId}: ${H.title}`),Y.push(`- Status: ${H.status}`),H.parentTaskId!==void 0&&H.parentTaskId!==null)Y.push(`- Parent: #${H.parentTaskId}`);if(H.source.subagentType)Y.push(`- Created by: ${H.source.subagentType}`);if(Y.push(`- Updated: ${H.updatedAt}`),H.project_path)Y.push(`- Project: ${H.project_path}`);if(H.worktree_path)Y.push(`- Worktree: ${H.worktree_path}`);if(H.branch)Y.push(`- Branch: ${H.branch}`);if(H.parentBranch)Y.push(`- Parent branch: ${H.parentBranch}`);let B;try{B=$.registry.getSubtreeSummary(H.taskId)}catch{B=void 0}if(B&&B.descendantCount>0)Y.push(`- Children: ${B.descendantCount} (active: ${B.activeCount}, completed: ${B.completedCount}, max depth: ${B.maxDepth})`);let U=B!==void 0&&B.activeCount>0;if(H.status==="completed"&&U)Y.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let z=sD(B3(H.description,X));if(z)Y.push(`- Description: ${z}`);if(H.tags&&H.tags.length>0)Y.push(`- Tags: ${H.tags.join(", ")}`);Y.push("")}Y.push("---"),Y.push(""),Y.push("### Reuse instructions"),Y.push(""),Y.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),Y.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),Y.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),Y.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),Y.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),Y.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),Y.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),Y.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),Y.push(""),Y.push("### Decision matrix \u2014 three legal paths"),Y.push(""),Y.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),Y.push("remains the default, but the matrix adds two new paths for independent work."),Y.push(""),Y.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),Y.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),Y.push("append description/goals. Do **not** create a new task id."),Y.push(""),Y.push("```"),Y.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),Y.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),Y.push(' milestone_title: "Reopened for <new-scope>",'),Y.push(' milestone_description: "<why this is the same work>" })'),Y.push("```"),Y.push(""),Y.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),Y.push("distinct: an independent bug fix, optimization, parallel delivery or"),Y.push("independent acceptance item under the same feature. Create a child task so"),Y.push("the audit trail is preserved. Always pair with an audit operation."),Y.push(""),Y.push("```");for(let H of G){let B=H.project_path??"<project_path>";Y.push(`task_create(parent_task_id=${H.taskId}, title="<distinguishing title>", project_path="${B}", context=<inherit or override>)`);break}Y.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),Y.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),Y.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),Y.push("```"),Y.push(""),Y.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),Y.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),Y.push("should stay \u2264 ~10 to keep the tree readable."),Y.push(""),Y.push("```"),Y.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),Y.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),Y.push(' milestone_title: "New root: <topic>",'),Y.push(' milestone_description: "<why this is not a child of any existing task>" })'),Y.push("```"),Y.push(""),Y.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),Y.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),Y.push("chosen. Use the appropriate `milestone_type`:"),Y.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),Y.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),Y.push(" - new root \u2192 `create` (then `progress` per phase)"),Y.push(""),Y.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),Y.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),Y.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),Y.push("tokens, secrets) are stripped automatically. Use the helper:"),Y.push(""),Y.push("```"),Y.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),Y.push("```"),Y.push("");let q=Y.join(`
|
|
2235
|
-
`);if(q.length>Q)q=
|
|
2234
|
+
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function pD($){let J=w8.map((Y)=>`- ${Y.id}: ${Y.description}`),X=($?.list()??[]).filter((Y)=>!w8.some((q)=>q.id===Y.name)).map((Y)=>{if(Y.type==="workflow"){let q=Y.workflow?` (workflow: ${Y.workflow})`:"";return`- ${Y.name}: ${Y.description||"Workflow agent"}${q}`}return`- ${Y.name}: ${Y.description||"Custom agent"}`}),W=[...J,...X],G=dD({hasCustomAgents:X.length>0});return W.join(`
|
|
2235
|
+
`)+G}X2();var iD=[/\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 nD($){let J=$;for(let Q of iD)J=J.replace(Q,"<redacted>");return J}function rD($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function H3($,J){return rD(nD($),J)}class b8{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 W={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,W),this.childrenIndex.delete(W.taskId),this.indexParentChild(W),this.evictIfNeeded(),W}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??[]),W=$.excludeAncestorOf??$.excludeSelfOrDescendant,G=W?this.collectSubtree(W):new Set,Y=$.sinceHours?Date.now()-$.sinceHours*60*60*1000:0,q=Date.now(),H=new Set([...X,...G]),B=[];for(let U of this.records.values()){if(q-Date.parse(U.updatedAt)>this.ttlMs)continue;if(Y>0&&Date.parse(U.updatedAt)<Y)continue;if(H.has(U.taskId))continue;if($.scope){if($.scope.sessionId!==void 0&&U.source.sessionId!==$.scope.sessionId)continue;if($.scope.parentSessionId!==void 0&&U.source.parentSessionId!==$.scope.parentSessionId)continue;if($.scope.subagentType!==void 0&&U.source.subagentType!==$.scope.subagentType)continue}if(Q){if(!Q.includes(U.status))continue}else if(U.status==="archived")continue;B.push(U)}if($.activeChildFirst){let U=new Map;for(let z of B)U.set(z.taskId,this.hasActiveChild(z.taskId));B.sort((z,V)=>{let M=U.get(z.taskId)?1:0,F=U.get(V.taskId)?1:0;if(M!==F)return F-M;let D=Date.parse(V.updatedAt)-Date.parse(z.updatedAt);if(D!==0)return D;return V.taskId-z.taskId})}else B.sort((U,z)=>{let V=Date.parse(z.updatedAt)-Date.parse(U.updatedAt);if(V!==0)return V;return z.taskId-U.taskId});return B.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 W=this.childrenIndex.get($),G=W?Array.from(W):[],Y=G.length>0?1:0;X.maxDepth=Y;let q=G;while(q.length>0){let H=[];for(let B of q){let U=this.records.get(B);if(!U)continue;if(!Q&&U.status==="archived")continue;if(X.descendantCount++,U.status==="active")X.activeCount++;else if(U.status==="completed")X.completedCount++;let z=this.childrenIndex.get(B);if(z&&z.size>0)for(let V of z)H.push(V)}if(H.length>0)Y++,X.maxDepth=Y;q=H}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),W=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:H3($.description||"",this.maxDescriptionChars),goals:H3($.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(W,"branch"),worktree_path:this.pickString(W,"worktree_path"),parentBranch:this.pickString(W,"parent_branch"),context:W}}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=b8.STRIPPED_KEYS;for(let[X,W]of Object.entries($)){let G=X.toLowerCase();if(Q.some((Y)=>G.includes(Y)))continue;J[X]=this.stripSensitiveKeys(W)}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(),W=this.childrenIndex.get(X);if(!W)continue;for(let G of W)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)}}r();var O9=i("registry-hook-installer");function aD($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,W=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,G=Q.priority??100,Y=!1,q=(D,O)=>{try{J.record(D,O)}catch(R){O9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},H=(D,O)=>{try{J.update(D,O)}catch(R){O9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},B=(D)=>{try{J.remove(D)}catch(O){O9.warn(`[registry-hook-installer] remove failed for task #${D}: ${O instanceof Error?O.message:String(O)}`)}},U=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),z={name:`${W}:after-create`,priority:G,execute:async(D)=>{let O=D.data;if(O?.task)q(O.task,U())}},V={name:`${W}:after-update`,priority:G,execute:async(D)=>{let O=D.data;if(!O?.task)return;if(J.peekById(O.task.id))H(O.task,U());else q(O.task,U())}},M={name:`${W}:after-complete`,priority:G,execute:async(D)=>{let O=D.data;if(O?.task)H(O.task,U())}},F={name:`${W}:after-delete`,priority:G,execute:async(D)=>{let O=D.data;if(typeof O?.id==="number")B(O.id)}};return $.registerHook(X0.AFTER_CREATE,z),$.registerHook(X0.AFTER_UPDATE,V),$.registerHook(X0.AFTER_COMPLETE,M),$.registerHook(X0.AFTER_DELETE,F),{uninstall(){if(Y)return;Y=!0,$.unregisterHook(X0.AFTER_CREATE,z.name),$.unregisterHook(X0.AFTER_UPDATE,V.name),$.unregisterHook(X0.AFTER_COMPLETE,M.name),$.unregisterHook(X0.AFTER_DELETE,F.name),O9.debug(`[registry-hook-installer] uninstalled hooks (name=${W})`)}}}r();var Z8=i("task-reuse-registry"),sD={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},B3=new WeakMap;function oD($){let J=B3.get($);if(J)return J.registry;let Q=new b8(sD),X={uninstall:()=>{}};try{let G=$.getComponent?.("task");if(G?.registerHook)X=aD(G,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),Z8.debug("[task-reuse-registry] hook installed");else Z8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(G){Z8.warn(`[task-reuse-registry] hook install failed: ${G instanceof Error?G.message:String(G)}`)}let W={registry:Q,installHandle:X};return B3.set($,W),Q}var tD=[/\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 eD($){let J=$;for(let Q of tD)J=J.replace(Q,"<redacted>");return J}function U3($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function $F($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,W=$.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 Y=[];Y.push(`## ${W}`),Y.push(""),Y.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."),Y.push("");for(let H of G){if(Y.push(`### Task #${H.taskId}: ${H.title}`),Y.push(`- Status: ${H.status}`),H.parentTaskId!==void 0&&H.parentTaskId!==null)Y.push(`- Parent: #${H.parentTaskId}`);if(H.source.subagentType)Y.push(`- Created by: ${H.source.subagentType}`);if(Y.push(`- Updated: ${H.updatedAt}`),H.project_path)Y.push(`- Project: ${H.project_path}`);if(H.worktree_path)Y.push(`- Worktree: ${H.worktree_path}`);if(H.branch)Y.push(`- Branch: ${H.branch}`);if(H.parentBranch)Y.push(`- Parent branch: ${H.parentBranch}`);let B;try{B=$.registry.getSubtreeSummary(H.taskId)}catch{B=void 0}if(B&&B.descendantCount>0)Y.push(`- Children: ${B.descendantCount} (active: ${B.activeCount}, completed: ${B.completedCount}, max depth: ${B.maxDepth})`);let U=B!==void 0&&B.activeCount>0;if(H.status==="completed"&&U)Y.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let z=eD(U3(H.description,X));if(z)Y.push(`- Description: ${z}`);if(H.tags&&H.tags.length>0)Y.push(`- Tags: ${H.tags.join(", ")}`);Y.push("")}Y.push("---"),Y.push(""),Y.push("### Reuse instructions"),Y.push(""),Y.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),Y.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),Y.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),Y.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),Y.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),Y.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),Y.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),Y.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),Y.push(""),Y.push("### Decision matrix \u2014 three legal paths"),Y.push(""),Y.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),Y.push("remains the default, but the matrix adds two new paths for independent work."),Y.push(""),Y.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),Y.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),Y.push("append description/goals. Do **not** create a new task id."),Y.push(""),Y.push("```"),Y.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),Y.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),Y.push(' milestone_title: "Reopened for <new-scope>",'),Y.push(' milestone_description: "<why this is the same work>" })'),Y.push("```"),Y.push(""),Y.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),Y.push("distinct: an independent bug fix, optimization, parallel delivery or"),Y.push("independent acceptance item under the same feature. Create a child task so"),Y.push("the audit trail is preserved. Always pair with an audit operation."),Y.push(""),Y.push("```");for(let H of G){let B=H.project_path??"<project_path>";Y.push(`task_create(parent_task_id=${H.taskId}, title="<distinguishing title>", project_path="${B}", context=<inherit or override>)`);break}Y.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),Y.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),Y.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),Y.push("```"),Y.push(""),Y.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),Y.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),Y.push("should stay \u2264 ~10 to keep the tree readable."),Y.push(""),Y.push("```"),Y.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),Y.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),Y.push(' milestone_title: "New root: <topic>",'),Y.push(' milestone_description: "<why this is not a child of any existing task>" })'),Y.push("```"),Y.push(""),Y.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),Y.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),Y.push("chosen. Use the appropriate `milestone_type`:"),Y.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),Y.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),Y.push(" - new root \u2192 `create` (then `progress` per phase)"),Y.push(""),Y.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),Y.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),Y.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),Y.push("tokens, secrets) are stripped automatically. Use the helper:"),Y.push(""),Y.push("```"),Y.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),Y.push("```"),Y.push("");let q=Y.join(`
|
|
2236
|
+
`);if(q.length>Q)q=U3(q,Q);return{markdown:q,candidateIds:G.map((H)=>H.taskId),isEmpty:!1}}var y=i("task:delegate"),p0={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"},w8=[{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.
|
|
2236
2237
|
|
|
2237
2238
|
## Your Role
|
|
2238
2239
|
- You were created to handle: {task_description}
|
|
@@ -2283,7 +2284,7 @@ ${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
|
|
|
2283
2284
|
## Execution
|
|
2284
2285
|
- Use the available tools to complete the task
|
|
2285
2286
|
- If you need more information, ask the main agent through the result
|
|
2286
|
-
- 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:Y4.roy,deniedTools:["delegate_task","stop_task","task_complete","task_cancel"]}];function P8($){return w8.find((J)=>J.id===$)}function
|
|
2287
|
+
- 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:Y4.roy,deniedTools:["delegate_task","stop_task","task_complete","task_cancel"]}];function P8($){return w8.find((J)=>J.id===$)}function JF($,J,Q,X,W){let G=$.getRegistry?.();if(G){if(G.get(J)?.type==="workflow")return y.debug(`[delegate] Skipping registration for workflow agent: ${J}`),null}let Y=$.getAgent(J);if(!Y){let q={type:"sub",systemPrompt:Q};if(X?.allowedTools&&X.allowedTools.length>0)q.allowedTools=X.allowedTools;if(W.length>0)q.deniedTools=W;Y=$.registerAgent(J,q),y.debug(`[delegate] Registered subagent: ${J}`)}return Y}var V3=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 QF($){let{workflowName:J,originalPrompt:Q,description:X}=$;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
|
|
2287
2288
|
|
|
2288
2289
|
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${J}**\u3002
|
|
2289
2290
|
\u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
|
|
@@ -2307,7 +2308,7 @@ ${Q}
|
|
|
2307
2308
|
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2308
2309
|
|
|
2309
2310
|
\u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
|
|
2310
|
-
`}var $F=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),M9=1800000,JF=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 W=[];for(let G of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${G}`),W.push({runId:G,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(G,J),W.push({runId:G,success:!0})}catch(Y){let q=Y instanceof Error?Y.message:String(Y);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${G}) failed (likely already terminal): ${q}`),W.push({runId:G,success:!1,error:q})}}return Q.clear(),{runIds:X,stopResults:W}}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 W=this.processRegistries.get($);if(W&&W.size()>0)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${W.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=U0(($)=>$F.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,W){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...W?{replyChannel:W}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:W?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,W){this.publishBackgroundEvent($,J,Q,X,W)}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),W=JSON.parse(X);return{query:W.query,sessionId:W.sessionId,nodeId:W.nodeId,nodeType:W.nodeType||"agent",agentSessionId:W.agentSessionId,delivered:W.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:W,timeout:G,similarTaskIds:Y,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z}=$,V=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,M=this.getSessionComponent();if(!M)throw Error("SessionComponent not found");if(!await M.get(J))throw Error(`Parent session not found: ${J}`);let D;if(q){let f=await M.get(q);if(!f)throw Error(`Sub session not found for resume: ${q}`);let N=f?.metadata?.created_by;if(N&&N!=="subagent")y.warn(`[BackgroundTaskManager] Session ${q} was not created by a sub-agent (created_by=${N}); reusing anyway`);D=f;try{let E=f?.metadata??{};await M.update(q,{metadata:{...E,reused_sub_session:!0,reused_at:Date.now()}})}catch(E){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:q,error:E instanceof Error?E.message:String(E)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${q} for task ${V}`)}else{let f={subagent_type:W,created_by:"subagent",task_description:Q},N=Q2();if(N){if(N.messageId)f.messageId=N.messageId;let E=N.replyChannel;if(E?.messageId)f.larkMessageId=E.messageId;if(E?.chatId)f.chatId=E.chatId;if(E?.userId)f.larkUserId=E.userId;let x=E?.profile;if(x)f.larkProfile=x}if(H)f.triggerEventId=H;if(D=await M.create({title:`${Q} (@${W} subagent)`,parentSessionId:J,metadata:f}),!D)throw Error("Failed to create sub-session")}let O=GF(),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 W4;this.processRegistries.set(V,L);let _=Date.now(),Z=`${W}:bg_${V}`,P={id:V,runId:Z,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,status:"pending",createdAt:_,lastUpdatedAt:_,timeoutMs:G||M9,abortController:R,similarTaskIds:Y,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z,replyChannel:O};this.tasks.set(V,P),this.abortControllers.set(V,R);let w={backgroundTaskId:V,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,startedAt:_,timeoutMs:G||M9};return this.publishBackgroundEvent(p0.STARTED,w,J,H,O),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 W=this.tasks.get($);if(!W){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let G=Date.now();W.status="running",W.startedAt=G,W.lastUpdatedAt=G;let Y=Q||M9,q=this.abortControllers.get($);this.startProgressReporter($,X||W.parentSessionId);try{let B=await this.getSessionComponent().get(W.subSessionId);if(!B)throw Error(`Sub session not found: ${W.subSessionId}`);let U=this.processRegistries.get($),z=await this.executeWithAbort(B,J,Y,$,q?.signal,W.similarTaskIds,U,()=>q?.abort(),W.subagentType);if(q?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();W.status="completed",W.completedAt=V,W.lastUpdatedAt=V,W.result=z;let M=W.completedAt-W.startedAt;if(W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId),W.associatedTaskId===void 0)W.associatedTaskId=d2();let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"completed",result:W.result,description:W.description,executionTimeMs:M,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.COMPLETED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:M})}catch(H){let B=H instanceof Error?H.message:String(H),U=J0.parseAskUserErrorFromMessage(H),z=B.toLowerCase().includes("stopped")||B.toLowerCase().includes("aborted"),V=W.startedAt?Date.now()-W.startedAt:0,M=Date.now();if(W.completedAt=M,W.lastUpdatedAt=M,W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId),W.associatedTaskId===void 0)W.associatedTaskId=d2();if(U){W.status="awaiting-user",W.error=U.rawErrorMessage,W.pendingAskUserQuery=U.query;let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,subagentType:W.subagentType,description:W.description,query:U.query,sessionId:U.sessionId,nodeId:U.nodeId,nodeType:U.nodeType,agentSessionId:U.agentSessionId,delivered:U.delivered===!0,error:U.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="${W.subagentType}", existingSubSessionId="${W.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:W.associatedTaskId};this.publishBackgroundEvent(p0.ASK_USER,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:W.subSessionId,nodeId:U.nodeId,queryPreview:U.query.substring(0,80)}),W._preserveSubSessionOnExit=!0;return}if(z){W.status="stopped";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"stopped",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.STOPPED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else if(B.startsWith("Task execution timeout after")){W.status="timeout";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"timeout",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.TIMEOUT,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else{W.status="failed";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"failed",error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.FAILED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}W.error=B,y.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:W.status,error:B})}finally{this.finalizeTask($,W.status);let H=W?._preserveSubSessionOnExit===!0,B=this.getSessionComponent();if(!H&&B?.endSessionCleanup&&W?.subSessionId)try{await B.endSessionCleanup(W.subSessionId)}catch(U){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${W.subSessionId}`,{error:U instanceof Error?U.message:String(U)})}else if(H)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${W.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let W=d2();if(W!==void 0&&X.associatedTaskId===void 0)X.associatedTaskId=W;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(p0.PROGRESS,G,J,X.triggerEventId,X.replyChannel)},JF);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,W,G,Y,q,H){let B=$?.metadata??{},U=B.task_id,z=B.task_description||"",V=$.id,M=B.subagent_type,F=M||H||"general";if(!M&&!H)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"),O=D?.getRegistry?.(),R=await kD(F,{registry:O}),L=P8(F),_=R?.basePrompt||L?.promptOverride||"You are a subagent. Complete this task: {task_description}",Z=R?.deniedTools||L?.deniedTools||[],P=R?.allowedTools||L?.allowedTools,w=_.replace(/{task_description}/g,z||"N/A");if(w+=`
|
|
2311
|
+
`}var XF=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),M9=1800000,WF=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 W=[];for(let G of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${G}`),W.push({runId:G,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(G,J),W.push({runId:G,success:!0})}catch(Y){let q=Y instanceof Error?Y.message:String(Y);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${G}) failed (likely already terminal): ${q}`),W.push({runId:G,success:!1,error:q})}}return Q.clear(),{runIds:X,stopResults:W}}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 W=this.processRegistries.get($);if(W&&W.size()>0)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${W.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=U0(($)=>XF.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,W){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...W?{replyChannel:W}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:W?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,W){this.publishBackgroundEvent($,J,Q,X,W)}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),W=JSON.parse(X);return{query:W.query,sessionId:W.sessionId,nodeId:W.nodeId,nodeType:W.nodeType||"agent",agentSessionId:W.agentSessionId,delivered:W.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:W,timeout:G,similarTaskIds:Y,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z}=$,V=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,M=this.getSessionComponent();if(!M)throw Error("SessionComponent not found");if(!await M.get(J))throw Error(`Parent session not found: ${J}`);let D;if(q){let f=await M.get(q);if(!f)throw Error(`Sub session not found for resume: ${q}`);let N=f?.metadata?.created_by;if(N&&N!=="subagent")y.warn(`[BackgroundTaskManager] Session ${q} was not created by a sub-agent (created_by=${N}); reusing anyway`);D=f;try{let E=f?.metadata??{};await M.update(q,{metadata:{...E,reused_sub_session:!0,reused_at:Date.now()}})}catch(E){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:q,error:E instanceof Error?E.message:String(E)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${q} for task ${V}`)}else{let f={subagent_type:W,created_by:"subagent",task_description:Q},N=Q2();if(N){if(N.messageId)f.messageId=N.messageId;let E=N.replyChannel;if(E?.messageId)f.larkMessageId=E.messageId;if(E?.chatId)f.chatId=E.chatId;if(E?.userId)f.larkUserId=E.userId;let x=E?.profile;if(x)f.larkProfile=x}if(H)f.triggerEventId=H;if(D=await M.create({title:`${Q} (@${W} subagent)`,parentSessionId:J,metadata:f}),!D)throw Error("Failed to create sub-session")}let O=HF(),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 W4;this.processRegistries.set(V,L);let _=Date.now(),Z=`${W}:bg_${V}`,P={id:V,runId:Z,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,status:"pending",createdAt:_,lastUpdatedAt:_,timeoutMs:G||M9,abortController:R,similarTaskIds:Y,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z,replyChannel:O};this.tasks.set(V,P),this.abortControllers.set(V,R);let w={backgroundTaskId:V,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,startedAt:_,timeoutMs:G||M9};return this.publishBackgroundEvent(p0.STARTED,w,J,H,O),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 W=this.tasks.get($);if(!W){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let G=Date.now();W.status="running",W.startedAt=G,W.lastUpdatedAt=G;let Y=Q||M9,q=this.abortControllers.get($);this.startProgressReporter($,X||W.parentSessionId);try{let B=await this.getSessionComponent().get(W.subSessionId);if(!B)throw Error(`Sub session not found: ${W.subSessionId}`);let U=this.processRegistries.get($),z=await this.executeWithAbort(B,J,Y,$,q?.signal,W.similarTaskIds,U,()=>q?.abort(),W.subagentType);if(q?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();W.status="completed",W.completedAt=V,W.lastUpdatedAt=V,W.result=z;let M=W.completedAt-W.startedAt;if(W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId),W.associatedTaskId===void 0)W.associatedTaskId=d2();let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"completed",result:W.result,description:W.description,executionTimeMs:M,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.COMPLETED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:M})}catch(H){let B=H instanceof Error?H.message:String(H),U=J0.parseAskUserErrorFromMessage(H),z=B.toLowerCase().includes("stopped")||B.toLowerCase().includes("aborted"),V=W.startedAt?Date.now()-W.startedAt:0,M=Date.now();if(W.completedAt=M,W.lastUpdatedAt=M,W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId),W.associatedTaskId===void 0)W.associatedTaskId=d2();if(U){W.status="awaiting-user",W.error=U.rawErrorMessage,W.pendingAskUserQuery=U.query;let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,subagentType:W.subagentType,description:W.description,query:U.query,sessionId:U.sessionId,nodeId:U.nodeId,nodeType:U.nodeType,agentSessionId:U.agentSessionId,delivered:U.delivered===!0,error:U.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="${W.subagentType}", existingSubSessionId="${W.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:W.associatedTaskId};this.publishBackgroundEvent(p0.ASK_USER,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:W.subSessionId,nodeId:U.nodeId,queryPreview:U.query.substring(0,80)}),W._preserveSubSessionOnExit=!0;return}if(z){W.status="stopped";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"stopped",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.STOPPED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else if(B.startsWith("Task execution timeout after")){W.status="timeout";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"timeout",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.TIMEOUT,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else{W.status="failed";let F={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"failed",error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.FAILED,F,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}W.error=B,y.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:W.status,error:B})}finally{this.finalizeTask($,W.status);let H=W?._preserveSubSessionOnExit===!0,B=this.getSessionComponent();if(!H&&B?.endSessionCleanup&&W?.subSessionId)try{await B.endSessionCleanup(W.subSessionId)}catch(U){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${W.subSessionId}`,{error:U instanceof Error?U.message:String(U)})}else if(H)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${W.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let W=d2();if(W!==void 0&&X.associatedTaskId===void 0)X.associatedTaskId=W;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(p0.PROGRESS,G,J,X.triggerEventId,X.replyChannel)},WF);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,W,G,Y,q,H){let B=$?.metadata??{},U=B.task_id,z=B.task_description||"",V=$.id,M=B.subagent_type,F=M||H||"general";if(!M&&!H)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"),O=D?.getRegistry?.(),R=await lD(F,{registry:O}),L=P8(F),_=R?.basePrompt||L?.promptOverride||"You are a subagent. Complete this task: {task_description}",Z=R?.deniedTools||L?.deniedTools||[],P=R?.allowedTools||L?.allowedTools,w=_.replace(/{task_description}/g,z||"N/A");if(w+=`
|
|
2311
2312
|
|
|
2312
2313
|
---
|
|
2313
2314
|
|
|
@@ -2345,14 +2346,14 @@ The following similar tasks and their operation records can serve as reference:
|
|
|
2345
2346
|
|
|
2346
2347
|
---
|
|
2347
2348
|
|
|
2348
|
-
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=
|
|
2349
|
+
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=oD(this.env),n=$F({registry:x,similarTaskIds:G??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!n.isEmpty)w+=`
|
|
2349
2350
|
|
|
2350
2351
|
---
|
|
2351
2352
|
|
|
2352
|
-
${n.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:P}:P?{id:F,name:F,mode:"subagent",description:R?.description||"Custom agent",allowedTools:P,deniedTools:Z}:void 0;
|
|
2353
|
+
${n.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:P}:P?{id:F,name:F,mode:"subagent",description:R?.description||"Custom agent",allowedTools:P,deniedTools:Z}:void 0;JF(D,F,_,f,Z);let E=O?.get(F)?.type==="workflow"?J:w;return new Promise((x,n)=>{let g=async()=>{try{await Y?.killAll()}catch(H0){y.warn("[delegate] ProcessRegistry.killAll failed",{error:H0 instanceof Error?H0.message:String(H0)})}},c=!1,F0,O0,g0=this.tasks.get(X);if(g0?.runId)O0=g0.runId;let q6=()=>{if(W&&H6)try{W.removeEventListener("abort",H6)}catch{}},H6;if(H6=()=>{if(c)return;if(c=!0,F0)clearTimeout(F0);q6();try{let H0=this.env?.getComponent?.("agent");if(H0?.abortRun&&O0)H0.abortRun(O0,"task_signal_abort")}catch{}g().catch(()=>{}).then(()=>{n(Error("Task execution stopped"))})},F0=setTimeout(()=>{if(c)return;if(c=!0,F0)clearTimeout(F0);q6();try{q?.()}catch{}try{let H0=this.env?.getComponent?.("agent");if(H0?.abortRun&&O0)H0.abortRun(O0,"task_timeout")}catch{}g().catch(()=>{}).then(()=>{n(Error(`Task execution timeout after ${Q}ms`))})},Q),W)W.addEventListener("abort",H6);let X7=()=>{let H0=g0?.model,W7=g0?.fallbackModel,G7=g0?.fallbackModels;return this.env.handle_query?.(E,{sessionId:V,deniedTools:Z.length>0?Z:void 0,agentType:F,abort:W,runId:O0,...H0?{model:H0}:{},...W7?{fallbackModel:W7}:{},...Array.isArray(G7)?{fallbackModels:G7}:{}})};(Y?c7(Y,()=>_8(X,()=>X7())):_8(X,()=>X7()))?.then((H0)=>{if(c)return;if(c=!0,F0)clearTimeout(F0);q6(),x(H0)}).catch((H0)=>{if(c)return;if(c=!0,F0)clearTimeout(F0);q6(),n(H0)})})}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(Y){y.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:$,runId:J.runId,error:Y instanceof Error?Y.message:String(Y)})}J.completedAt=Q,J.lastUpdatedAt=Q;try{await this.processRegistries.get($)?.killAll()}catch(Y){y.warn("[delegate] stopTask killAll failed",{taskId:$,error:Y instanceof Error?Y.message:String(Y)})}let{runIds:X,stopResults:W}=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(p0.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:W}}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(W){y.warn(`[BackgroundTaskManager] stopAllForParent failed for ${Q}: ${W instanceof Error?W.message:String(W)}`)}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 W=this.tasks.get(Q)??this.terminalTasks.get(Q);try{await this.processRegistries.get(Q)?.killAll()}catch(Y){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}try{await this.propagateStopToWorkflowRuns(Q,"force stop all")}catch(Y){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}let G=!1;if(W&&(W.status==="running"||W.status==="pending"))try{W.status="stopped",W.completedAt=Date.now(),W.lastUpdatedAt=W.completedAt,W.abortController?.abort(),G=!0}catch(Y){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}if(G&&W){let Y={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:W.parentSessionId,status:"stopped",description:W.description,error:"force stop all",executionTimeMs:W.startedAt&&W.completedAt?W.completedAt-W.startedAt:0,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(p0.STOPPED,Y,W.parentSessionId,W.triggerEventId,W.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(),W=600000;while(Date.now()-X<600000){let G=0;for(let[,Y]of this.tasks)if(Y.status==="running"||Y.status==="pending")G++;if(G===0)break;y.info(`[BackgroundTaskManager] dispose waiting for ${G} running task(s)`),await new Promise((Y)=>setTimeout(Y,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(W){y.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:W instanceof Error?W.message:String(W)})}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")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],J0.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"forceStopAllAcrossParents",null);function z3($){return $.env?.getComponent?.("agent")?.getRegistry?.()}function D3($){let J=$.env,X=$.backgroundTaskManager??new J0(J),W=z3($);$._backgroundTaskManager=X;let G={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
|
|
2353
2354
|
|
|
2354
2355
|
Available agent types:
|
|
2355
|
-
${
|
|
2356
|
+
${pD(W)}
|
|
2356
2357
|
|
|
2357
2358
|
When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
2358
2359
|
|
|
@@ -2381,14 +2382,14 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2381
2382
|
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2382
2383
|
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2383
2384
|
- **reason**: Brief reason for calling this tool (optional)
|
|
2384
|
-
- **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:
|
|
2385
|
-
`),metadata:{execution_time_ms:Date.now()-V,sessionId:L,background:!0,status:"accepted",bgProcessId:R}}}catch(M){return{success:!1,output:"",error:M instanceof Error?M.message:String(M),metadata:{execution_time_ms:Date.now()-V}}}}var j$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};z0();var
|
|
2386
|
-
\u72B6\u6001\uFF1A${J.status}`}function
|
|
2387
|
-
`)}function
|
|
2388
|
-
`)}function
|
|
2389
|
-
`)}function
|
|
2390
|
-
`)}function
|
|
2391
|
-
`)}function
|
|
2385
|
+
- **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:V3,execute:async(Y,q)=>{let H=Date.now(),B=V3.parse(Y),{description:U,prompt:z,subagent_type:V="general",timeout:M,reason:F,similar_task_ids:D}=B,O=q.session_id||"default",R=B.triggerEventId??YF();if(R&&R!==B.triggerEventId)y.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${R}`);if(y.info(`[delegate_task] Called: description=${U}, subagent_type=${V}, triggerEventId=${R??"(none)"}`),R){let f=p7();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()-H}}}catch(N){return{success:!1,output:"",error:`Failed to verify triggerEventId ${R}: ${N instanceof Error?N.message:String(N)}`,metadata:{execution_time_ms:Date.now()-H}}}else y.warn(`[delegate_task] triggerEventId=${R} supplied but no shared EventStore registered; skipping verification`)}let L=z3($);if(!uD(V,L))return{success:!1,output:"",error:`Unknown subagent type: ${V}`,metadata:{execution_time_ms:Date.now()-H}};let _=$.getTagService(),Z=z,P={prompt:Z,subagentType:V,timeout:M,reason:F,tagService:_},w={component:{name:"task",version:"1.0.0"},data:P,metadata:{sessionId:O},phase:"before",hookPoint:X0.DELEGATE_BEFORE};return await E0.execute(X0.DELEGATE_BEFORE,P,{sessionId:O}),Z=P.prompt,await BF(X,O,U,Z,P.subagentType,P.timeout,D,B.sub_session_id,R,q.model,q.fallbackModel,q.fallbackModels)}};return G.execute=U0(G.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),G}function GF(){let $=Q2();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 YF=U0(GF,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function qF(){let $=Q2()?.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 HF=U0(qF,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function BF($,J,Q,X,W,G,Y,q,H,B,U,z){let V=Date.now();try{let M=W,F=X,D,O=$.resolveEntryAgent(W);if(O)D=W,M=O,F=QF({workflowName:D,originalPrompt:X,description:Q}),y.info(`[delegate_task] Routing workflow subagent '${W}' \u2192 entry-agent '${O}'`);let{taskId:R,subSessionId:L}=await $.createTask({parentSessionId:J,description:Q,prompt:F,subagentType:M,timeout:G,similarTaskIds:Y,originalWorkflowName:D,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${R}`,`\uD83D\uDCDD Description: ${Q}`,`\uD83E\uDD16 Sub-agent: ${M}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(G||M9)/1000}s`,"",`Use stop_task with task_id="${R}" to cancel this task.`].join(`
|
|
2386
|
+
`),metadata:{execution_time_ms:Date.now()-V,sessionId:L,background:!0,status:"accepted",bgProcessId:R}}}catch(M){return{success:!1,output:"",error:M instanceof Error?M.message:String(M),metadata:{execution_time_ms:Date.now()-V}}}}var j$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};z0();var UF=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 zF($){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=[],W=new Set;for(let G of Q){if(typeof G!=="number")continue;if(!Number.isInteger(G)||G<=0)continue;if(W.has(G))continue;if(W.add(G),X.push(G),X.length>=UF)break}return X}function DF($){switch($){case"completed":case"cancelled":case"paused":case"archived":return"reopen";case"todo":case"active":default:return"enhance"}}function F3($){return $==="paused"?"active":"todo"}var E8="__NEW_TASK_ID__",C8="#__NEW_TASK_ID__";function FF($){switch($.scenario){case"reuse":return OF($);case"reopen":return MF($);case"reopen_enhance":return KF($);case"remount":return RF($);case"soft_reuse":return LF($)}}function S8($){return $.newTaskId>0?String($.newTaskId):E8}function A0($){return $.newTaskId>0?`#${$.newTaskId}`:C8}function R9($){let J=$.targetTask;if(!J)return"";return`#${$.targetTaskId} [${J.type}] ${J.title}
|
|
2387
|
+
\u72B6\u6001\uFF1A${J.status}`}function OF($){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","",R9($),"\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 ${A0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${A0($)}\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 ${A0($)}\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(`
|
|
2388
|
+
`)}function MF($){let J=$.targetTask?.status??"completed",Q=F3(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","",R9($),`\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 ${A0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${A0($)}\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 ${A0($)}\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(`
|
|
2389
|
+
`)}function KF($){let J=$.targetTask?.status??"completed",Q=F3(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","",R9($),`\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 ${A0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${A0($)}\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 ${A0($)}\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(`
|
|
2390
|
+
`)}function RF($){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=${S8($)}, parent_task_id=${$.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${A0($)}\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(${S8($)}) \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=${S8($)}, 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(`
|
|
2391
|
+
`)}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","",R9($),"","\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 ${A0($)}\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 ${A0($)}\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(`
|
|
2392
|
+
`)}function AF($){let J=$.toLowerCase();return VF.some((Q)=>Q.endsWith("_")||Q.endsWith("*")?J.startsWith(Q.slice(0,-1)):J===Q)}function _F($,J){let Q=(X,W)=>{if(Array.isArray(X)){X.forEach((G,Y)=>Q(G,`${W}[${Y}]`));return}if(!X||typeof X!=="object")return;for(let[G,Y]of Object.entries(X)){let q=W?`${W}.${G}`:G;if(AF(G))throw Error(`[assertNoLeakage] leakage key detected at ${q}: "${G}"`);Q(Y,q)}};Q($,"state"),Q(J,"questions")}function jF($,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 wL=U0(zF,"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(",")})}),bL=U0(DF,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),PL=U0(FF,"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($)})}),SL=U0(_F,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:($)=>({stateKeys:K9($[0]),questionKeys:K9($[1])})}),EL=U0(jF,"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 K9($,J=[],Q=0){if(J.length>=40||Q>4)return J;if(Array.isArray($)){for(let X of $.slice(0,3))K9(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);K9($[X],J,Q+1)}return J}import{execSync as bF}from"child_process";var O3="unknown",NF='{"type":"unknown"}';function ZF(){return{task_id:K.number().describe("Task ID")}}function wF($){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 L9($){return K.preprocess(wF,K.object({...ZF(),...$}))}var M3=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
|
|
2392
2393
|
`+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
|
|
2393
2394
|
`+`**\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
|
|
2394
2395
|
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
@@ -2396,9 +2397,9 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2396
2397
|
`+` 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
|
|
2397
2398
|
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
2398
2399
|
`+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
|
|
2399
|
-
`+"\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]}')}),
|
|
2400
|
+
`+"\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]}')}),K3=L9({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.")}),R3=K.object({status:K.enum(["todo","active","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")}),L3=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","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")}),A3=L9({title:K.string().optional(),description:K.string().optional(),status:K.enum(["todo","active","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)")}),_3=K.object({task_id:K.number().describe("Task ID")}),j3=L9({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"+"\u8C03\u7528\u672C\u5DE5\u5177\u524D\uFF0C\u8BF7\u5148\u8BFB\u53D6\u4EFB\u52A1\u7684 goal\uFF08description\uFF09\u548C delivery\uFF08goals_and_expected_deliverables\uFF09\u680F\u4F4D\uFF0C"+"\u5EFA\u8BAE\u9A8C\u8BC1\u76EE\u6807\u548C\u4EA4\u4ED8\u7269\u662F\u5426\u7B26\u5408\u9884\u671F\uFF0C\u7136\u540E\u5C06\u5B9E\u9645\u4EA4\u4ED8\u7269\u7684\u5BFB\u5740\u5730\u5740\u586B\u5165\u6B64\u53C2\u6570\u3002")}),N3=L9({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")}),Z3=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")}),w3=K.object({task_ids:K.array(K.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),b3=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","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")});q$();r();r();var PF=i("task-child-context"),SF=["commit","token","secret","password","api_key"];function f8($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map(f8);if(typeof $!=="object")return $;let J={};for(let[Q,X]of Object.entries($)){let W=Q.toLowerCase();if(SF.some((G)=>W.includes(G)))continue;J[Q]=f8(X)}return J}function EF($){let{parent:J,overrides:Q={}}=$,X=Q.contextInherit!==!1,W=Q.inheritTags===!0,G=Q.projectPath??J.projectPath??"unknown",Y={};if(J.contextJson&&J.contextJson.trim().length>0)try{let U=JSON.parse(J.contextJson);if(U&&typeof U==="object"&&!Array.isArray(U))Y=U}catch(U){PF.debug(`[task-child-context] parent #${J.taskId} context is malformed JSON; continuing with empty inherited context (${U instanceof Error?U.message:String(U)})`),Y={}}let q={};if(X){if(Y.worktree_path!==void 0&&Q.worktreePath===void 0)q.worktree_path=Y.worktree_path;if(Y.branch!==void 0&&Q.branch===void 0)q.branch=Y.branch;if(Y.parent_branch!==void 0)q.parent_branch=Y.parent_branch;if(Y.type!==void 0)q.type=Y.type;if(Y.prior_context&&typeof Y.prior_context==="object"){let z=Y.prior_context,V={};for(let[M,F]of Object.entries(z)){if(M.toLowerCase()==="commit")continue;V[M]=F}if(Object.keys(V).length>0)q.prior_context=V}let U=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[z,V]of Object.entries(Y)){if(U.has(z))continue;q[z]=V}}if(Q.worktreePath!==void 0)q.worktree_path=Q.worktreePath;if(Q.branch!==void 0)q.branch=Q.branch;let H=Q.createdAt??new Date().toISOString();q.created_at=H,q.child_of=J.taskId;let B=f8(q);return{project_path:G,context:JSON.stringify(B),inheritedTags:W?J.tags??[]:[]}}var P3=i("task:tools:create"),CF=P$.split(`
|
|
2400
2401
|
`).map(($)=>$.trim()?" "+$:$).join(`
|
|
2401
|
-
`);function
|
|
2402
|
+
`);function fF($){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 TF(){try{let $=bF("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 i2($){return{name:"task_create",description:`
|
|
2402
2403
|
Create a new task for tracking work.
|
|
2403
2404
|
|
|
2404
2405
|
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
@@ -2467,7 +2468,7 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2467
2468
|
- Depth \u2264 5 (avoid deep nesting)
|
|
2468
2469
|
- Same-theme tasks cluster under one parent
|
|
2469
2470
|
- Long-tail/stranded tasks should be archived or merged
|
|
2470
|
-
${
|
|
2471
|
+
${CF}
|
|
2471
2472
|
|
|
2472
2473
|
## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
|
|
2473
2474
|
|
|
@@ -2563,22 +2564,22 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2563
2564
|
env-injected value is 0 / negative / non-integer, it's treated as
|
|
2564
2565
|
missing \u2014 only positive integers are honored.
|
|
2565
2566
|
|
|
2566
|
-
`,parameters:
|
|
2567
|
+
`,parameters:M3,execute:async(J,Q)=>{let X=M3.parse(J),W=Q.session_id||"unknown",G=TF(),Y=X.context,q=z9().parentTaskId,H=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:q!==void 0&&q!==null&&Number.isInteger(q)&&q>0?q:void 0,B=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,U=B!==void 0&&B!==O3,z=U?B:void 0,V=X.tags,M;if(H!==void 0)try{let F=await $.getTask(H);if(F){let D=EF({parent:{taskId:F.id,projectPath:F.project_path,contextJson:F.context??"",tags:F.tags},overrides:{projectPath:z,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(z===void 0)z=D.project_path;if(X.tags===void 0)V=D.inheritedTags;M=D.context}}catch(F){P3.debug(`[task_create] failed to pre-load parent #${H} for context inheritance: ${F instanceof Error?F.message:String(F)}`)}try{let F=X.context===NF?void 0:X.context,D=F?JSON.parse(F):{},O=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(M)try{let R=JSON.parse(M);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[L,_]of Object.entries(R))if(O[L]===void 0)O[L]=_}}catch{}if(!O.created_at)O.created_at=new Date().toISOString();if(!O.worktree_path&&G)O.worktree_path=G;Y=JSON.stringify(O)}catch{Y=X.context}try{let F=await $.createTask({parent_task_id:H,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:W,project_path:z??(U?B:O3),context:Y});p2(F.id),P3.info(`[createTask] Trace: Task #${F.id} created, currentTaskId=${F.id} set in EnvContext`);let D=fF(F.context),O=D?D.replaceAll(C8,`#${F.id}`).replaceAll(E8,String(F.id)):"";return{success:!0,output:`Task created successfully: #${F.id} - ${F.title}`+(O?`
|
|
2567
2568
|
|
|
2568
|
-
${O}`:""),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 n2($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:
|
|
2569
|
-
`+"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:
|
|
2569
|
+
${O}`:""),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 n2($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:K3,execute:async(J,Q)=>{let X=K3.parse(J);try{if(X.include_operations){let W=await $.getTaskWithOperations(X.task_id);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let G=W.task,Y=G&&typeof G==="object"?{...G,operations:W.operations}:W;return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}else{let W=await $.getTask(X.task_id);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function r2($){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
|
|
2570
|
+
`+"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:R3,execute:async(J,Q)=>{let X=R3.parse(J);try{let W=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:W.total,count:W.tasks.length,truncated:W.total>W.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:W.tasks}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function a2($){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.
|
|
2570
2571
|
|
|
2571
2572
|
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
2572
2573
|
|
|
2573
|
-
If \`keywords\` is empty, returns no results.`,parameters:
|
|
2574
|
+
If \`keywords\` is empty, returns no results.`,parameters:L3,execute:async(J,Q)=>{let X=L3.parse(J);try{let W=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:W.tasks,total:W.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function T8($){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.
|
|
2574
2575
|
|
|
2575
2576
|
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
2576
2577
|
|
|
2577
|
-
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:
|
|
2578
|
+
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:Z3,execute:async(J,Q)=>{let X=Z3.parse(J),W=X.task_ids,G=Q.session_id||"batch-archive";if(!W||W.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let Y=[],q=0;for(let B of W)try{if(await $.updateTask(B,{status:"archived"}))await $.createOperation({taskId:B,sessionId:G,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),q++,Y.push({id:B,success:!0});else Y.push({id:B,success:!1,error:"Task not found"})}catch(U){Y.push({id:B,success:!1,error:U instanceof Error?U.message:String(U)})}return{success:!Y.some((B)=>!B.success),output:JSON.stringify({archived_count:q,total:W.length,errors:Y.filter((B)=>!B.success).map((B)=>({id:B.id,error:B.error})),results:Y},null,2),metadata:{execution_time_ms:0}}}}}function I8($){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
2578
2579
|
|
|
2579
2580
|
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
2580
2581
|
|
|
2581
|
-
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:
|
|
2582
|
+
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:w3,execute:async(J,Q)=>{let W=w3.parse(J).task_ids;if(!W||W.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let G=[],Y=0;for(let H of W)try{if(await $.deleteTask(H))Y++,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({deleted_count:Y,total:W.length,errors:G.filter((H)=>!H.success).map((H)=>({id:H.id,error:H.error})),results:G},null,2),metadata:{execution_time_ms:0}}}}}q$();r();var IF=i("tool:update-task");async function vF($,J,Q){let X=new Set,W=Q;while(W!==null&&W!==void 0){if(W===J)return!0;if(X.has(W))break;X.add(W);let G=await $.getTask(W);if(!G)break;W=G.parent_task_id}return!1}function s2($){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:A3,execute:async(J,Q)=>{let X=A3.parse(J),W=Q.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await vF($,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,Y=Q.metadata?.agentName??void 0;if(X.status==="completed"&&G==="sub"){let H=$.env?.getComponent?.("agent"),U=(Y&&H?.getAgent?H.getAgent(Y):void 0)?.config;if(!(U?Array.isArray(U.allowedTools)&&U.allowedTools.includes("task_complete")||!Array.isArray(U.allowedTools)&&!(Array.isArray(U.deniedTools)&&U.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 q=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(!q)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:W,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 p2(q.id),IF.info(`[updateTask] Trace: Task #${q.id} updated, currentTaskId=${q.id} set in EnvContext`),{success:!0,output:`Task updated: #${q.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}}}}}}function v8($){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:_3,execute:async(J,Q)=>{let X=_3.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(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}q$();r();var xF=i("task:tools:complete"),hF=`
|
|
2582
2583
|
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
2583
2584
|
|
|
2584
2585
|
**Before calling this tool**, you MUST:
|
|
@@ -2622,9 +2623,9 @@ The \`deliverable_storage_path\` will be persisted to the task's \`context.deliv
|
|
|
2622
2623
|
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
2623
2624
|
|
|
2624
2625
|
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
2625
|
-
`.trim();function o2($){return{name:"task_complete",description:
|
|
2626
|
+
`.trim();function o2($){return{name:"task_complete",description:hF,parameters:j3,execute:async(J,Q)=>{let X=j3.parse(J),W=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}};let Y=await $.completeTask(X.task_id,W,X.deliverable_storage_path);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return p2(void 0),xF.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${Y.id} - ${Y.title}
|
|
2626
2627
|
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${Y.id} - ${Y.title}
|
|
2627
|
-
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:Y}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}r();var
|
|
2628
|
+
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:Y}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}r();var yF=i("tool:cancel-task"),gF=new Set(["completed","cancelled","archived"]),kF=`
|
|
2628
2629
|
Cancel a task (task.status = "cancelled"). This is the **acceptance-side** cancel:
|
|
2629
2630
|
use it when the work is abandoned, the user asked to stop, or acceptance failed.
|
|
2630
2631
|
|
|
@@ -2647,20 +2648,20 @@ use it when the work is abandoned, the user asked to stop, or acceptance failed.
|
|
|
2647
2648
|
**Parameters**:
|
|
2648
2649
|
- \`task_id\` (required): the task to cancel
|
|
2649
2650
|
- \`reason\` (optional): why it is being cancelled \u2014 recorded in the operation trail
|
|
2650
|
-
`.trim();function x8($){return{name:"task_cancel",description:
|
|
2651
|
+
`.trim();function x8($){return{name:"task_cancel",description:kF,parameters:N3,execute:async(J,Q)=>{let X=N3.parse(J),W=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(gF.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 Y=await $.updateTask(X.task_id,{status:"cancelled"});if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return await $.createOperation({taskId:X.task_id,sessionId:W,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)."}),yF.info(`[cancelTask] Task #${X.task_id} cancelled (previous status: ${G.status})`),{success:!0,output:`Task cancelled: #${X.task_id} - ${Y.title}`,metadata:{execution_time_ms:0,task:Y}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function S3($,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 E3($,J){if(J<0)return $;if(J===0)return $.map((Q)=>({...Q,children:[]}));return $.map((Q)=>({...Q,children:E3(Q.children,J-1)}))}function C3($){let J=0;for(let Q of $)J+=1+C3(Q.children);return J}function mF($){let J=new Map,Q=new Map,X=[];for(let W of $)J.set(W.id,{id:W.id,title:W.title,status:W.status,type:W.type,priority:W.priority,progress:W.progress,children:[]});for(let W of $){let G=W.parent_task_id;if(G!==void 0&&G!==null&&J.has(G)){let Y=Q.get(G)||[];Y.push(W),Q.set(G,Y)}else X.push(W)}for(let[W,G]of Q.entries()){let Y=J.get(W);G.sort(S3),Y.children=G.map((q)=>J.get(q.id))}return X.sort(S3),X.map((W)=>J.get(W.id))}function t2($){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:
|
|
2651
2652
|
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
2652
2653
|
- truncated: always false for now (no pagination cap on tree)
|
|
2653
2654
|
- depth: the resolved depth value
|
|
2654
2655
|
- parent_task_id: the root's id, or null for forest mode
|
|
2655
2656
|
- nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
|
|
2656
|
-
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:
|
|
2657
|
+
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:b3,execute:async(J,Q)=>{let X=b3.parse(J);try{let W=[],G=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let H=await $.getTask(X.parent_task_id);if(!H)W=[];else{let B=await $.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));W=[H,...B]}}else W=(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)W=W.filter((H)=>H.status===X.status);if(X.priority)W=W.filter((H)=>H.priority===X.priority);if(X.type)W=W.filter((H)=>H.type===X.type);if(!X.include_archived)W=W.filter((H)=>H.status!=="archived")}let Y=mF(W);if(X.parent_task_id===void 0||X.parent_task_id===null)Y=E3(Y,X.depth);let q=C3(Y);return{success:!0,output:JSON.stringify({total:q,truncated:!1,depth:X.depth,parent_task_id:G,nodes:Y}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}var A9=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),h8=100,y8=500,_9=5000,uF=1,j9=200,h3=K.string().min(h8,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${h8} \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(y8,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${y8} \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 ${h8}-${y8} \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"),y3=K.string().min(uF,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(j9,{message:`milestone_title \u8D85\u8FC7 ${j9} \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"),g3=K.string().max(_9,{message:`milestone_description \u8D85\u8FC7 ${_9} \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"),lF=K.object({task_id:K.number().describe("Task ID"),milestone_type:A9.optional(),milestone_title:y3.optional(),milestone_description:g3,process_description:h3.optional(),action_type:A9.optional(),action_title:K.string().min(1).max(j9).optional(),action_description:K.string().max(_9).optional(),md_path:K.string().optional().describe("Path to detailed markdown documentation")}),f3=lF.transform(($)=>{let J=[],Q=$.milestone_type,X=$.milestone_title,W=$.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(W===void 0&&$.action_description!==void 0)W=$.action_description,J.push("action_description");return{task_id:$.task_id,milestone_type:Q,milestone_title:X,milestone_description:W,process_description:$.process_description,md_path:$.md_path,_deprecated_fields_used:J}}),T3=K.object({operation_id:K.number().describe("Operation ID")}),I3=K.object({task_id:K.number().describe("Task ID"),milestone_type:A9.optional(),action_type:A9.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}}),cF=K.object({operation_id:K.number().describe("Operation ID"),milestone_title:y3.optional(),milestone_description:g3,process_description:h3.optional(),action_title:K.string().min(1).max(j9).optional(),action_description:K.string().max(_9).optional()}),v3=cF.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}}),x3=K.object({operation_id:K.number().describe("Operation ID")});function dF($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function pF($){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 e2($){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:f3,execute:async(J,Q)=>{let X;try{X=f3.parse(J)}catch(Y){if(Y instanceof Y0)return{success:!1,output:"",error:dF(Y),metadata:{execution_time_ms:0}};throw Y}let W=pF(X);if(!W.ok)return{success:!1,output:"",error:W.error,metadata:{execution_time_ms:0}};let G=Q.session_id||"unknown";try{let Y=await $.createOperation({taskId:X.task_id,sessionId:G,milestoneType:W.milestoneType,milestoneTitle:W.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),q=`Operation created: #${Y.id} for task #${Y.taskId} [milestone=${Y.milestoneType}] ${Y.milestoneTitle}`,H=[];if(X._deprecated_fields_used.length>0)H.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(H.length>0)q+=`
|
|
2657
2658
|
|
|
2658
2659
|
`+H.join(`
|
|
2659
|
-
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:Y.id,task_id:Y.taskId,session_id:Y.sessionId,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 g8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:
|
|
2660
|
+
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:Y.id,task_id:Y.taskId,session_id:Y.sessionId,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 g8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:T3,execute:async(J,Q)=>{let X=T3.parse(J);try{let W=await $.getOperation(X.operation_id);if(!W)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function $6($){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:I3,execute:async(J,Q)=>{let X=I3.parse(J);try{let W=await $.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),G=JSON.stringify({operations:W,count:W.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
|
|
2660
2661
|
|
|
2661
|
-
`+G;return{success:!0,output:G,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function
|
|
2662
|
+
`+G;return{success:!0,output:G,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function iF($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function k8($){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:v3,execute:async(J,Q)=>{let X;try{X=v3.parse(J)}catch(W){if(W instanceof Y0)return{success:!1,output:"",error:iF(W),metadata:{execution_time_ms:0}};throw W}try{let W=await $.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!W)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let G=`Operation updated: #${W.id}`;if(X._deprecated_fields_used.length>0)G+=`
|
|
2662
2663
|
|
|
2663
|
-
\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:W,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function m8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:
|
|
2664
|
+
\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:W,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function m8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:x3,execute:async(J,Q)=>{let X=x3.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(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}import{join as i3}from"path";function o($){k3.warn($)}var k3,J6=a(()=>{r(),k3=i("task:migration")}),m3={};i0(m3,{runMigration:()=>nF});function nF($){o(`[Migration 001] Starting migration for: ${$}`);let J=W2($);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 rF=a(()=>{H$(),J6()}),u3={};i0(u3,{runMigration:()=>aF});function aF($){o(`[Migration 002] Starting migration for: ${$}`);let J=W2($);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 sF=a(()=>{H$(),J6()}),l3={};i0(l3,{runMigration:()=>oF});function oF($){o(`[Migration 003] Starting migration for: ${$}`);let J=W2($);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 tF=a(()=>{H$(),J6()}),c3={};i0(c3,{runMigration:()=>eF});function eF($){o(`[Migration 004] Starting migration for: ${$}`);let J=W2($);try{let Q=new Set,X=J.query("PRAGMA table_info(task_operation)").all();for(let W of X)Q.add(W.name);for(let{oldName:W,newName:G}of d3){let Y=Q.has(W),q=Q.has(G);if(Y&&!q)J.run(`ALTER TABLE task_operation RENAME COLUMN ${W} TO ${G}`),o(`[Migration 004] Renamed ${W} -> ${G}`);else if(q)o(`[Migration 004] ${G} already exists, skipping rename of ${W}`);else o(`[Migration 004] ${W} not present, skipping rename to ${G}`)}o("[Migration 004] Migration completed successfully")}finally{J.close()}}var d3,$O=a(()=>{H$(),J6(),d3=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),p3={};i0(p3,{runMigration:()=>JO});function JO($){o(`[Migration 005] Starting migration for: ${$}`);let J=W2($),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 W=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if(Q.blobCountBefore=W[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 QO=a(()=>{H$(),J6()});function XO(){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 W2($){let J=XO();return WO(new J($))}function WO($){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 W=this.prepare(J);return{all:()=>W.all(),get:()=>W.get(),run:()=>W.run()}}let X=this.prepare(J);return{all:(...W)=>X.all(...Q,...W),get:(...W)=>X.get(...Q,...W),run:(...W)=>X.run(...Q,...W)}},$}function GO(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";return i3($,".local","share")}function N9(){return i3(GO(),"roy-agent","tasks.db")}var N$,Z$,H$=a(()=>{r(),z0(),N$=i("task:store"),Z$=class ${db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(J){this.dbPath=J||N9()}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=W2(this.dbPath),this.db.run(`
|
|
2664
2665
|
CREATE TABLE IF NOT EXISTS task (
|
|
2665
2666
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2666
2667
|
title TEXT NOT NULL,
|
|
@@ -2708,7 +2709,7 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2708
2709
|
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
2709
2710
|
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
2710
2711
|
)
|
|
2711
|
-
`),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}=(
|
|
2712
|
+
`),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}=(rF(),S$(m3));J(this.dbPath)}catch(J){N$.warn(`[Migration 001] Failed to run: ${J.message}`)}try{let{runMigration:J}=(sF(),S$(u3));J(this.dbPath)}catch(J){N$.warn(`[Migration 002] Failed to run: ${J.message}`)}try{let{runMigration:J}=(tF(),S$(l3));J(this.dbPath)}catch(J){N$.warn(`[Migration 003] Failed to run: ${J.message}`)}try{let{runMigration:J}=($O(),S$(c3));J(this.dbPath)}catch(J){N$.warn(`[Migration 004] Failed to run: ${J.message}`)}try{let{runMigration:J}=(QO(),S$(p3));J(this.dbPath)}catch(J){N$.warn(`[Migration 005] Failed to run: ${J.message}`)}}this.initialized=!0,N$.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(J){await this.initialize();let Q=Date.now(),W=this.db.prepare(`
|
|
2712
2713
|
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
2713
2714
|
goals_and_expected_deliverables, due_date, tags, status,
|
|
2714
2715
|
current_status, created_at, updated_at, project_path, context)
|
|
@@ -2766,11 +2767,11 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2766
2767
|
WHERE context LIKE ?
|
|
2767
2768
|
ORDER BY updated_at DESC
|
|
2768
2769
|
LIMIT ?
|
|
2769
|
-
`;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()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"searchTasksByKeywords",null)});function i3($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let W=Q.replace(/-/g,"_").toUpperCase(),G=$.slice(X.length);if(G.startsWith("_"))G=G.slice(1);if(!G)return;let Y=G.indexOf("_"),q;if(Y===-1)q=G;else{let B=G.slice(0,Y),U=G.slice(Y+1);if(B===W)q=U;else q=G}if(!q)return;let H=q.replace(/_/g,".");return`${Q}.${H.toLowerCase()}`}function n3($,J){return{...$,execute:J}}var XO=()=>{},r3=a(()=>{XO(),N8(),X2()});r3();class u8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new F9}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($,n3({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}}r();var WO={"task.storage.type":"sqlite","task.storage.dbPath":void 0},GO={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"]}]};X2();var YO=["completed","failed","cancelled","timeout"];q$();r();var Q6=i("task:tag");class a3{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return Q6.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)Q6.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),Q6.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),Q6.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 H of J){let B=await this.store.getTagByName(H);if(!B)B=await this.store.createTag(H);Q.push(B.id)}let X=await this.store.getTagsForTask($),W=new Set(X.map((H)=>H.id)),G=new Set(Q),Y=Q.filter((H)=>!W.has(H)),q=X.filter((H)=>!G.has(H.id)).map((H)=>H.id);if(q.length>0)await this.store.removeTagsFromTask($,q);if(Y.length>0)await this.store.addTagsToTask($,Y);await this.store.updateTaskTags($,J),Q6.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}z0();var Q0=i("task"),qO="Deliverable: ";function HO($){if(!$)return;return`${qO}${$}`}class w$ extends u8{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:W}=$,G=X??"TASK";if(J.registerComponent(GO),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 Y of Object.keys(process.env)){let q=i3(Y,G,"task");if(!q)continue;let H=process.env[Y];if(H!==void 0)await J.set(q,H)}for(let[Y,q]of Object.entries(WO))if(J.get(Y)===void 0)await J.set(Y,q);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",N9());if(W){let Y=this.flattenConfig(W);for(let[q,H]of Object.entries(Y))await J.set(q,H)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new a3(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 Z$(Q),Q0.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`);else this.store=new Z$,Q0.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig($,J="task"){let Q={};for(let[X,W]of Object.entries($)){let G=`${J}.${X}`;if(W&&typeof W==="object"&&!Array.isArray(W))Object.assign(Q,this.flattenConfig(W,G));else Q[G]=W}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(L6(this.backgroundTaskManager),"built-in"),Q0.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");let $=this.env?.getComponent("session");this.toolComponent.register(Q4(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(L6(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(h7,"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 $=[i2(this),n2(this),r2(this),t2(this),a2(this),T8(this),I8(this),s2(this),v8(this),o2(this),x8(this)],J=[e2(this),g8(this),$6(this),k8(this),m8(this)],Q=[z3(this),g7(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 E0.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 W={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(X0.AFTER_CREATE,W),this.publishEvent(j$.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 getTaskWithOperations($){let J=await this.store.getTask($);if(!J)return;let Q=await this.store.listOperations({taskId:$});return{...J,operations:Q,task:J}}async updateTask($,J){let Q={id:$,options:{...J},tagService:this.tagService};await this.executeHook(X0.BEFORE_UPDATE,Q);let X=await this.store.updateTask($,Q.options);if(X){let W={task:X,changes:J,tagService:this.tagService};if(await this.executeHook(X0.AFTER_UPDATE,W),this.publishEvent(j$.UPDATED,{task:X,changes:J,sessionId:""},""),Q0.info(`[TaskComponent] Task updated: ${$}`),J.status&&YO.includes(J.status)){let G=z9(),Y={task:X,changes:J,terminalStatus:J.status,sessionId:G.sessionId??"",tagService:this.tagService};await this.executeHook(X0.AFTER_COMPLETE,Y),Q0.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${$} -> ${J.status}`)}}return X}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(j$.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.`);let W={status:"completed",progress:100};if(Q){let Y={};if(X?.context)try{let q=JSON.parse(X.context);if(q&&typeof q==="object"&&!Array.isArray(q))Y=q}catch{Q0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}Y.deliverable_storage_path=Q,W.context=JSON.stringify(Y)}let G=await this.updateTask($,W);if(G)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:HO(Q)}),this.publishEvent(j$.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 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),W={operation:Q};return await this.executeHook(X0.OPERATION_AFTER_CREATE,W,{task:X,operation:Q}),this.publishEvent(j$.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($)}getTagService(){return this.tagService}registerHook($,J){E0.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=E0.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 E0.count($)}}m([u("task.component.executeHook",{recordParams:!0})],w$.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createOperation",null);var l8=K.enum(["todo","active","completed","paused","cancelled","archived"]),c8=K.enum(["low","medium","high"]),d8=K.enum(["normal","cycle","longterm"]),p8=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),BO=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});H$();H$();var UO="Deliverable: ";function VO($){if(!$)return;return`${UO}${$}`}var Z9=1e6;class i8{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=zO($);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:Z9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;if($.parent_task_id!==void 0&&$.parent_task_id!==null){let W=await this.resolve($.parent_task_id);if(!W)throw Error(`Parent task #${$.parent_task_id} not found.`);Q=W.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:Z9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((W)=>this.toTask(W));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 W=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 W?this.toTask(W):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 W={status:"completed",progress:100};if(Q)W.context=FO(X.context,Q);let G=await this.port.updateTask(X.nativeId,W);if(!G)return null;let Y=VO(Q);await this.createOperation({taskId:G.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${G.title}`,milestoneDescription:Y??"Task completed",...Q?{mdPath:Q}:{}});let q=await this.resolve(X.nativeId);return this.toTask(q??G)}async getTaskTree($,J=-1){let Q=await this.resolve($);if(!Q)return[];if(J===0)return[];let X=(await this.scanAllTasks()).map((B)=>this.toTask(B)),W=new Map;for(let B of X){if(B.parent_task_id===void 0)continue;let U=W.get(B.parent_task_id)??[];U.push(B),W.set(B.parent_task_id,U)}let G=[],Y=new Set([Q.id]),q=[Q.id],H=0;while(q.length>0){if(J!==-1&&H>=J)break;let B=[];for(let U of q)for(let z of W.get(U)??[]){if(Y.has(z.id))continue;Y.add(z.id),G.push(z),B.push(z.id)}q=B,H++}return G}async searchTasksByKeywords($,J={}){let Q=J.limit??20,X=J.offset??0,W=(await this.scanAllTasks()).map((q)=>this.toTask(q));if(W=this.applyFilters(W,J),J.excludeTaskId!==void 0)W=W.filter((q)=>q.id!==J.excludeTaskId);let G=$.map((q)=>q.toLowerCase()).filter((q)=>q.length>0),Y=G.length===0?W:W.filter((q)=>{let H=[q.title,q.description,q.goals_and_expected_deliverables,q.current_status,(q.tags??[]).join(" "),q.project_path].join(" ").toLowerCase();return G.every((B)=>H.includes(B))});return{tasks:Y.slice(X,X+Q),total:Y.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??"",W=$.milestoneDescription??$.actionDescription??"",G=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:W,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 W=await this.resolve($.taskId);if(!W)return[];let Y=(await this.port.listOperations({taskNativeId:W.nativeId,limit:X?Z9:J,offset:X?0:Q})).operations.map((q)=>this.toOperation(q));if(X)Y=Y.filter((q)=>q.milestoneType===X),Y=Y.slice(Q,Q+J);return Y}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 W=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:Z9})).operations.find((G)=>G.id===$);if(W)return this.toOperation(W)}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((W)=>W.status!=="archived");if(J.status!==void 0)Q=Q.filter((W)=>W.status===J.status);if(J.priority!==void 0)Q=Q.filter((W)=>W.priority===J.priority);if(J.type!==void 0)Q=Q.filter((W)=>W.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((W)=>W.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let W=DO(Q,J.depth);Q=Q.filter((G)=>W.has(G.id))}return Q}}function zO($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function DO($,J){if(J<0)return new Set($.map((Y)=>Y.id));let Q=new Set($.map((Y)=>Y.id)),X=new Map;for(let Y of $){let q=Y.parent_task_id;if(q===void 0||!Q.has(q))continue;let H=X.get(q)??[];H.push(Y),X.set(q,H)}let W=new Set,G=$.filter((Y)=>Y.parent_task_id===void 0||!Q.has(Y.parent_task_id));for(let Y of G)W.add(Y.id);for(let Y=1;Y<=J;Y++){let q=[];for(let H of G)for(let B of X.get(H.id)??[]){if(W.has(B.id))continue;W.add(B.id),q.push(B)}if(q.length===0)break;G=q}return W}function FO($,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 OO=1e6;function MO($){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 X6($,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 W6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),W=String(J.milestoneDescription??J.actionDescription??""),G=J.taskId??$.task_id,Y=typeof G==="number"?G:typeof G==="string"&&/^\d+$/.test(G)?Number(G):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:Y,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:W,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:W}}function s3($,J,Q={}){let X=Q.operationType??"roy.milestone",W=Q.agent??"roy",G=Q.scanLimit??OO;async function Y(){let B=await $.listTasks({limit:G});return new Map(B.tasks.filter((U)=>typeof U.num==="number").map((U)=>[U.id,U.num]))}async function q(B){if(typeof $.getTaskByNum==="function")return await $.getTaskByNum(B);return(await $.listTasks({limit:G})).tasks.find((z)=>z.num===B)??null}async function H(B){let z=[...(await Y()).entries()].find(([,V])=>V===B);if(!z)throw Error(`parent task not found: ${B}`);return z[0]}return{async createTask(B){let U=B.parent_task_id!==void 0?await H(B.parent_task_id):null,z={type:B.type??"normal",progress:B.progress??0,current_status:B.current_status??"",goals_and_expected_deliverables:B.goals_and_expected_deliverables??"",project_path:B.project_path,context:B.context,...B.due_date?{due_date:B.due_date}:{}},V=await $.createTask({title:B.title,description:B.description,priority:J.toStorePriority(B.priority),owner:W,tags:J.toStoreTags(B.tags),parent_id:U,session_id:B.sessionId??"unknown",roy:z});return X6(V,J,B.parent_task_id)},async getTask(B){let U=await $.getTask(B);if(!U)return null;let z=await Y();return X6(U,J,U.parent_id?z.get(U.parent_id):void 0)},async getTaskByNum(B){let U=await q(B);if(!U)return null;let z=await Y();return X6(U,J,U.parent_id?z.get(U.parent_id):void 0)},async listTasks(B){let U=await $.listTasks({limit:B?.limit??20,offset:B?.offset??0}),z=await Y();return{tasks:U.tasks.map((V)=>X6(V,J,V.parent_id?z.get(V.parent_id):void 0)),total:U.total}},async updateTask(B,U){let z=MO(U),V=await $.updateTask(B,{...U.title!==void 0?{title:U.title}:{},...U.description!==void 0?{description:U.description}:{},...U.status!==void 0?{status:J.toStoreStatus(U.status)}:{},...U.priority!==void 0?{priority:J.toStorePriority(U.priority)}:{},...U.tags!==void 0?{tags:J.toStoreTags(U.tags)}:{},...Object.keys(z).length>0?{roy:z}:{}});if(!V)return null;let M;if(U.parent_task_id!==void 0){let D=U.parent_task_id===null?null:await H(U.parent_task_id);if(typeof $.setParentId==="function")await $.setParentId(B,D);M=U.parent_task_id===null?void 0:U.parent_task_id}let F=await $.getTask(B)??V;if(M===void 0&&F.parent_id)M=(await Y()).get(F.parent_id);return X6(F,J,M)},async deleteTask(B){return await $.deleteTask(B)},async createOperation(B){let U=await $.appendOperation({task_id:B.taskNativeId??String(B.taskId),type:X,data:{taskId:B.taskId,sessionId:B.sessionId,milestoneType:B.milestoneType,milestoneTitle:B.milestoneTitle,milestoneDescription:B.milestoneDescription,processDescription:B.processDescription,...B.mdPath?{mdPath:B.mdPath}:{}}});return W6(U)},async listOperations(B){let U=await $.listOperations({...B?.taskNativeId?{task_id:B.taskNativeId}:{},type:X,limit:B?.limit??G,offset:B?.offset??0});return{operations:U.operations.map(W6),total:U.total}},async getOperationByNum(B){if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(B);return U?W6(U):null},async updateOperationByNum(B,U){if(typeof $.updateOperation!=="function")return null;if(typeof $.getOperationByNum!=="function")return null;let z=await $.getOperationByNum(B);if(!z)return null;let V=W6(z),M=await $.updateOperation(B,{data:{taskId:V.taskId,sessionId:U.sessionId??V.sessionId,milestoneType:U.milestoneType??V.milestoneType,milestoneTitle:U.milestoneTitle??V.milestoneTitle,milestoneDescription:U.milestoneDescription??V.milestoneDescription,processDescription:U.processDescription??V.processDescription,...U.mdPath??V.mdPath?{mdPath:U.mdPath??V.mdPath}:{}}});return M?W6(M):null},async deleteOperationByNum(B){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(B)}}}var KO="roy.milestone",RO={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},LO={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function o3($){return RO[$]??"pending"}function t3($){return LO[$]??"todo"}function e3($){if($==="high")return 1;if($==="low")return 5;return 3}function $1($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function J1($){if(!$||$.length===0)return;return $.join(",")}function Q1($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var AO={toRoyStatus:($)=>t3($),toStoreStatus:($)=>o3($),toRoyPriority:($)=>$1($),toStorePriority:($)=>e3($),toRoyTags:($)=>Q1($),toStoreTags:($)=>J1($)};function X1($,J={}){return new i8(s3($,AO,{operationType:KO,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var aA=l8.options,sA=c8.options,oA=d8.options,tA=p8.options;var G1=Symbol("Let zodToJsonSchema decide on which parser to use");var W1={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"},Y1=($)=>typeof $==="string"?{...W1,name:$}:{...W1,...$};var q1=($)=>{let J=Y1($),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,W])=>[W._def,{def:W._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function n8($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function d($,J,Q,X,W){$[J]=Q,n8($,J,X,W)}var w9=($,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"?w9(J,$.currentPath):J.join("/")}}function H1($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==j.ZodAny)Q.items=v($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)d(Q,"minItems",$.minLength.value,$.minLength.message,J);if($.maxLength)d(Q,"maxItems",$.maxLength.value,$.maxLength.message,J);if($.exactLength)d(Q,"minItems",$.exactLength.value,$.exactLength.message,J),d(Q,"maxItems",$.exactLength.value,$.exactLength.message,J);return Q}function B1($,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)d(Q,"minimum",X.value,X.message,J);else d(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;d(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"maximum",X.value,X.message,J);else d(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;d(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":d(Q,"multipleOf",X.value,X.message,J);break}return Q}function U1(){return{type:"boolean"}}function b9($,J){return v($.type._def,J)}var V1=($,J)=>{return v($.innerType._def,J)};function r8($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((W,G)=>r8($,J,W))};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 _O($,J)}}var _O=($,J)=>{let Q={type:"integer",format:"unix-time"};if(J.target==="openApi3")return Q;for(let X of $.checks)switch(X.kind){case"min":d(Q,"minimum",X.value,X.message,J);break;case"max":d(Q,"maximum",X.value,X.message,J);break}return Q};function z1($,J){return{...v($.innerType._def,J),default:$.defaultValue()}}function D1($,J){return J.effectStrategy==="input"?v($.schema._def,J):t(J)}function F1($){return{type:"string",enum:Array.from($.values)}}var jO=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function O1($,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,W=[];return Q.forEach((G)=>{if(jO(G)){if(W.push(...G.allOf),G.unevaluatedProperties===void 0)X=void 0}else{let Y=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:q,...H}=G;Y=H}else X=void 0;W.push(Y)}}),W.length?{allOf:W,...X}:void 0}function M1($,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 a8=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(a8===void 0)a8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return a8},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 P9($,J){let Q={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":d(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J);break;case"max":d(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":V0(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":V0(Q,X.regex,X.message,J);break;case"cuid":V0(Q,C0.cuid,X.message,J);break;case"cuid2":V0(Q,C0.cuid2,X.message,J);break;case"startsWith":V0(Q,RegExp(`^${s8(X.value,J)}`),X.message,J);break;case"endsWith":V0(Q,RegExp(`${s8(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":d(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J),d(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"includes":{V0(Q,RegExp(s8(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":V0(Q,C0.base64url,X.message,J);break;case"jwt":V0(Q,C0.jwt,X.message,J);break;case"cidr":{if(X.version!=="v6")V0(Q,C0.ipv4Cidr,X.message,J);if(X.version!=="v4")V0(Q,C0.ipv6Cidr,X.message,J);break}case"emoji":V0(Q,C0.emoji(),X.message,J);break;case"ulid":{V0(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":{d(Q,"contentEncoding","base64",X.message,J);break}case"pattern:zod":{V0(Q,C0.base64,X.message,J);break}}break}case"nanoid":V0(Q,C0.nanoid,X.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:((W)=>{})(X)}return Q}function s8($,J){return J.patternStrategy==="escape"?ZO($):$}var NO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ZO($){let J="";for(let Q=0;Q<$.length;Q++){if(!NO.has($[Q]))J+="\\";J+=$[Q]}return J}function f0($,J,Q,X){if($.format||$.anyOf?.some((W)=>W.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 d($,"format",J,Q,X)}function V0($,J,Q,X){if($.pattern||$.allOf?.some((W)=>W.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:K1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else d($,"pattern",K1(J,X),Q,X)}function K1($,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,W="",G=!1,Y=!1,q=!1;for(let H=0;H<X.length;H++){if(G){W+=X[H],G=!1;continue}if(Q.i){if(Y){if(X[H].match(/[a-z]/)){if(q)W+=X[H],W+=`${X[H-2]}-${X[H]}`.toUpperCase(),q=!1;else if(X[H+1]==="-"&&X[H+2]?.match(/[a-z]/))W+=X[H],q=!0;else W+=`${X[H]}${X[H].toUpperCase()}`;continue}}else if(X[H].match(/[a-z]/)){W+=`[${X[H]}${X[H].toUpperCase()}]`;continue}}if(Q.m){if(X[H]==="^"){W+=`(^|(?<=[\r
|
|
2770
|
+
`;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()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"searchTasksByKeywords",null)});function n3($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let W=Q.replace(/-/g,"_").toUpperCase(),G=$.slice(X.length);if(G.startsWith("_"))G=G.slice(1);if(!G)return;let Y=G.indexOf("_"),q;if(Y===-1)q=G;else{let B=G.slice(0,Y),U=G.slice(Y+1);if(B===W)q=U;else q=G}if(!q)return;let H=q.replace(/_/g,".");return`${Q}.${H.toLowerCase()}`}function r3($,J){return{...$,execute:J}}var YO=()=>{},a3=a(()=>{YO(),N8(),X2()});a3();class u8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new F9}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($,r3({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}}r();var qO={"task.storage.type":"sqlite","task.storage.dbPath":void 0},HO={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"]}]};X2();var BO=["completed","failed","cancelled","timeout"];q$();r();var Q6=i("task:tag");class s3{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return Q6.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)Q6.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),Q6.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),Q6.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 H of J){let B=await this.store.getTagByName(H);if(!B)B=await this.store.createTag(H);Q.push(B.id)}let X=await this.store.getTagsForTask($),W=new Set(X.map((H)=>H.id)),G=new Set(Q),Y=Q.filter((H)=>!W.has(H)),q=X.filter((H)=>!G.has(H.id)).map((H)=>H.id);if(q.length>0)await this.store.removeTagsFromTask($,q);if(Y.length>0)await this.store.addTagsToTask($,Y);await this.store.updateTaskTags($,J),Q6.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}z0();var Q0=i("task"),UO="Deliverable: ";function VO($){if(!$)return;return`${UO}${$}`}class w$ extends u8{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:W}=$,G=X??"TASK";if(J.registerComponent(HO),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 Y of Object.keys(process.env)){let q=n3(Y,G,"task");if(!q)continue;let H=process.env[Y];if(H!==void 0)await J.set(q,H)}for(let[Y,q]of Object.entries(qO))if(J.get(Y)===void 0)await J.set(Y,q);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",N9());if(W){let Y=this.flattenConfig(W);for(let[q,H]of Object.entries(Y))await J.set(q,H)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new s3(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 Z$(Q),Q0.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`);else this.store=new Z$,Q0.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig($,J="task"){let Q={};for(let[X,W]of Object.entries($)){let G=`${J}.${X}`;if(W&&typeof W==="object"&&!Array.isArray(W))Object.assign(Q,this.flattenConfig(W,G));else Q[G]=W}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(L6(this.backgroundTaskManager),"built-in"),Q0.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");let $=this.env?.getComponent("session");this.toolComponent.register(Q4(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(L6(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(y7,"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 $=[i2(this),n2(this),r2(this),t2(this),a2(this),T8(this),I8(this),s2(this),v8(this),o2(this),x8(this)],J=[e2(this),g8(this),$6(this),k8(this),m8(this)],Q=[D3(this),k7(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 E0.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 W={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(X0.AFTER_CREATE,W),this.publishEvent(j$.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 getTaskWithOperations($){let J=await this.store.getTask($);if(!J)return;let Q=await this.store.listOperations({taskId:$});return{...J,operations:Q,task:J}}async updateTask($,J){let Q={id:$,options:{...J},tagService:this.tagService};await this.executeHook(X0.BEFORE_UPDATE,Q);let X=await this.store.updateTask($,Q.options);if(X){let W={task:X,changes:J,tagService:this.tagService};if(await this.executeHook(X0.AFTER_UPDATE,W),this.publishEvent(j$.UPDATED,{task:X,changes:J,sessionId:""},""),Q0.info(`[TaskComponent] Task updated: ${$}`),J.status&&BO.includes(J.status)){let G=z9(),Y={task:X,changes:J,terminalStatus:J.status,sessionId:G.sessionId??"",tagService:this.tagService};await this.executeHook(X0.AFTER_COMPLETE,Y),Q0.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${$} -> ${J.status}`)}}return X}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(j$.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.`);let W={status:"completed",progress:100};if(Q){let Y={};if(X?.context)try{let q=JSON.parse(X.context);if(q&&typeof q==="object"&&!Array.isArray(q))Y=q}catch{Q0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}Y.deliverable_storage_path=Q,W.context=JSON.stringify(Y)}let G=await this.updateTask($,W);if(G)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:VO(Q)}),this.publishEvent(j$.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 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),W={operation:Q};return await this.executeHook(X0.OPERATION_AFTER_CREATE,W,{task:X,operation:Q}),this.publishEvent(j$.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($)}getTagService(){return this.tagService}registerHook($,J){E0.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=E0.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 E0.count($)}}m([u("task.component.executeHook",{recordParams:!0})],w$.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createOperation",null);var l8=K.enum(["todo","active","completed","paused","cancelled","archived"]),c8=K.enum(["low","medium","high"]),d8=K.enum(["normal","cycle","longterm"]),p8=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),zO=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});H$();H$();var DO="Deliverable: ";function FO($){if(!$)return;return`${DO}${$}`}var Z9=1e6;class i8{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=OO($);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:Z9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;if($.parent_task_id!==void 0&&$.parent_task_id!==null){let W=await this.resolve($.parent_task_id);if(!W)throw Error(`Parent task #${$.parent_task_id} not found.`);Q=W.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:Z9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((W)=>this.toTask(W));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 W=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 W?this.toTask(W):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 W={status:"completed",progress:100};if(Q)W.context=KO(X.context,Q);let G=await this.port.updateTask(X.nativeId,W);if(!G)return null;let Y=FO(Q);await this.createOperation({taskId:G.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${G.title}`,milestoneDescription:Y??"Task completed",...Q?{mdPath:Q}:{}});let q=await this.resolve(X.nativeId);return this.toTask(q??G)}async getTaskTree($,J=-1){let Q=await this.resolve($);if(!Q)return[];if(J===0)return[];let X=(await this.scanAllTasks()).map((B)=>this.toTask(B)),W=new Map;for(let B of X){if(B.parent_task_id===void 0)continue;let U=W.get(B.parent_task_id)??[];U.push(B),W.set(B.parent_task_id,U)}let G=[],Y=new Set([Q.id]),q=[Q.id],H=0;while(q.length>0){if(J!==-1&&H>=J)break;let B=[];for(let U of q)for(let z of W.get(U)??[]){if(Y.has(z.id))continue;Y.add(z.id),G.push(z),B.push(z.id)}q=B,H++}return G}async searchTasksByKeywords($,J={}){let Q=J.limit??20,X=J.offset??0,W=(await this.scanAllTasks()).map((q)=>this.toTask(q));if(W=this.applyFilters(W,J),J.excludeTaskId!==void 0)W=W.filter((q)=>q.id!==J.excludeTaskId);let G=$.map((q)=>q.toLowerCase()).filter((q)=>q.length>0),Y=G.length===0?W:W.filter((q)=>{let H=[q.title,q.description,q.goals_and_expected_deliverables,q.current_status,(q.tags??[]).join(" "),q.project_path].join(" ").toLowerCase();return G.every((B)=>H.includes(B))});return{tasks:Y.slice(X,X+Q),total:Y.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??"",W=$.milestoneDescription??$.actionDescription??"",G=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:W,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 W=await this.resolve($.taskId);if(!W)return[];let Y=(await this.port.listOperations({taskNativeId:W.nativeId,limit:X?Z9:J,offset:X?0:Q})).operations.map((q)=>this.toOperation(q));if(X)Y=Y.filter((q)=>q.milestoneType===X),Y=Y.slice(Q,Q+J);return Y}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 W=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:Z9})).operations.find((G)=>G.id===$);if(W)return this.toOperation(W)}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((W)=>W.status!=="archived");if(J.status!==void 0)Q=Q.filter((W)=>W.status===J.status);if(J.priority!==void 0)Q=Q.filter((W)=>W.priority===J.priority);if(J.type!==void 0)Q=Q.filter((W)=>W.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((W)=>W.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let W=MO(Q,J.depth);Q=Q.filter((G)=>W.has(G.id))}return Q}}function OO($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function MO($,J){if(J<0)return new Set($.map((Y)=>Y.id));let Q=new Set($.map((Y)=>Y.id)),X=new Map;for(let Y of $){let q=Y.parent_task_id;if(q===void 0||!Q.has(q))continue;let H=X.get(q)??[];H.push(Y),X.set(q,H)}let W=new Set,G=$.filter((Y)=>Y.parent_task_id===void 0||!Q.has(Y.parent_task_id));for(let Y of G)W.add(Y.id);for(let Y=1;Y<=J;Y++){let q=[];for(let H of G)for(let B of X.get(H.id)??[]){if(W.has(B.id))continue;W.add(B.id),q.push(B)}if(q.length===0)break;G=q}return W}function KO($,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 RO=1e6;function LO($){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 X6($,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 W6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),W=String(J.milestoneDescription??J.actionDescription??""),G=J.taskId??$.task_id,Y=typeof G==="number"?G:typeof G==="string"&&/^\d+$/.test(G)?Number(G):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:Y,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:W,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:W}}function o3($,J,Q={}){let X=Q.operationType??"roy.milestone",W=Q.agent??"roy",G=Q.scanLimit??RO;async function Y(){let B=await $.listTasks({limit:G});return new Map(B.tasks.filter((U)=>typeof U.num==="number").map((U)=>[U.id,U.num]))}async function q(B){if(typeof $.getTaskByNum==="function")return await $.getTaskByNum(B);return(await $.listTasks({limit:G})).tasks.find((z)=>z.num===B)??null}async function H(B){let z=[...(await Y()).entries()].find(([,V])=>V===B);if(!z)throw Error(`parent task not found: ${B}`);return z[0]}return{async createTask(B){let U=B.parent_task_id!==void 0?await H(B.parent_task_id):null,z={type:B.type??"normal",progress:B.progress??0,current_status:B.current_status??"",goals_and_expected_deliverables:B.goals_and_expected_deliverables??"",project_path:B.project_path,context:B.context,...B.due_date?{due_date:B.due_date}:{}},V=await $.createTask({title:B.title,description:B.description,priority:J.toStorePriority(B.priority),owner:W,tags:J.toStoreTags(B.tags),parent_id:U,session_id:B.sessionId??"unknown",roy:z});return X6(V,J,B.parent_task_id)},async getTask(B){let U=await $.getTask(B);if(!U)return null;let z=await Y();return X6(U,J,U.parent_id?z.get(U.parent_id):void 0)},async getTaskByNum(B){let U=await q(B);if(!U)return null;let z=await Y();return X6(U,J,U.parent_id?z.get(U.parent_id):void 0)},async listTasks(B){let U=await $.listTasks({limit:B?.limit??20,offset:B?.offset??0}),z=await Y();return{tasks:U.tasks.map((V)=>X6(V,J,V.parent_id?z.get(V.parent_id):void 0)),total:U.total}},async updateTask(B,U){let z=LO(U),V=await $.updateTask(B,{...U.title!==void 0?{title:U.title}:{},...U.description!==void 0?{description:U.description}:{},...U.status!==void 0?{status:J.toStoreStatus(U.status)}:{},...U.priority!==void 0?{priority:J.toStorePriority(U.priority)}:{},...U.tags!==void 0?{tags:J.toStoreTags(U.tags)}:{},...Object.keys(z).length>0?{roy:z}:{}});if(!V)return null;let M;if(U.parent_task_id!==void 0){let D=U.parent_task_id===null?null:await H(U.parent_task_id);if(typeof $.setParentId==="function")await $.setParentId(B,D);M=U.parent_task_id===null?void 0:U.parent_task_id}let F=await $.getTask(B)??V;if(M===void 0&&F.parent_id)M=(await Y()).get(F.parent_id);return X6(F,J,M)},async deleteTask(B){return await $.deleteTask(B)},async createOperation(B){let U=await $.appendOperation({task_id:B.taskNativeId??String(B.taskId),type:X,data:{taskId:B.taskId,sessionId:B.sessionId,milestoneType:B.milestoneType,milestoneTitle:B.milestoneTitle,milestoneDescription:B.milestoneDescription,processDescription:B.processDescription,...B.mdPath?{mdPath:B.mdPath}:{}}});return W6(U)},async listOperations(B){let U=await $.listOperations({...B?.taskNativeId?{task_id:B.taskNativeId}:{},type:X,limit:B?.limit??G,offset:B?.offset??0});return{operations:U.operations.map(W6),total:U.total}},async getOperationByNum(B){if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(B);return U?W6(U):null},async updateOperationByNum(B,U){if(typeof $.updateOperation!=="function")return null;if(typeof $.getOperationByNum!=="function")return null;let z=await $.getOperationByNum(B);if(!z)return null;let V=W6(z),M=await $.updateOperation(B,{data:{taskId:V.taskId,sessionId:U.sessionId??V.sessionId,milestoneType:U.milestoneType??V.milestoneType,milestoneTitle:U.milestoneTitle??V.milestoneTitle,milestoneDescription:U.milestoneDescription??V.milestoneDescription,processDescription:U.processDescription??V.processDescription,...U.mdPath??V.mdPath?{mdPath:U.mdPath??V.mdPath}:{}}});return M?W6(M):null},async deleteOperationByNum(B){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(B)}}}var AO="roy.milestone",_O={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},jO={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function t3($){return _O[$]??"pending"}function e3($){return jO[$]??"todo"}function $1($){if($==="high")return 1;if($==="low")return 5;return 3}function J1($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function Q1($){if(!$||$.length===0)return;return $.join(",")}function X1($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var NO={toRoyStatus:($)=>e3($),toStoreStatus:($)=>t3($),toRoyPriority:($)=>J1($),toStorePriority:($)=>$1($),toRoyTags:($)=>X1($),toStoreTags:($)=>Q1($)};function W1($,J={}){return new i8(o3($,NO,{operationType:AO,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var tA=l8.options,eA=c8.options,$_=d8.options,J_=p8.options;var Y1=Symbol("Let zodToJsonSchema decide on which parser to use");var G1={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"},q1=($)=>typeof $==="string"?{...G1,name:$}:{...G1,...$};var H1=($)=>{let J=q1($),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,W])=>[W._def,{def:W._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function n8($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function d($,J,Q,X,W){$[J]=Q,n8($,J,X,W)}var w9=($,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"?w9(J,$.currentPath):J.join("/")}}function B1($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==j.ZodAny)Q.items=v($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)d(Q,"minItems",$.minLength.value,$.minLength.message,J);if($.maxLength)d(Q,"maxItems",$.maxLength.value,$.maxLength.message,J);if($.exactLength)d(Q,"minItems",$.exactLength.value,$.exactLength.message,J),d(Q,"maxItems",$.exactLength.value,$.exactLength.message,J);return Q}function U1($,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)d(Q,"minimum",X.value,X.message,J);else d(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;d(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"maximum",X.value,X.message,J);else d(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;d(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":d(Q,"multipleOf",X.value,X.message,J);break}return Q}function V1(){return{type:"boolean"}}function b9($,J){return v($.type._def,J)}var z1=($,J)=>{return v($.innerType._def,J)};function r8($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((W,G)=>r8($,J,W))};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 ZO($,J)}}var ZO=($,J)=>{let Q={type:"integer",format:"unix-time"};if(J.target==="openApi3")return Q;for(let X of $.checks)switch(X.kind){case"min":d(Q,"minimum",X.value,X.message,J);break;case"max":d(Q,"maximum",X.value,X.message,J);break}return Q};function D1($,J){return{...v($.innerType._def,J),default:$.defaultValue()}}function F1($,J){return J.effectStrategy==="input"?v($.schema._def,J):t(J)}function O1($){return{type:"string",enum:Array.from($.values)}}var wO=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function M1($,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,W=[];return Q.forEach((G)=>{if(wO(G)){if(W.push(...G.allOf),G.unevaluatedProperties===void 0)X=void 0}else{let Y=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:q,...H}=G;Y=H}else X=void 0;W.push(Y)}}),W.length?{allOf:W,...X}:void 0}function K1($,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 a8=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(a8===void 0)a8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return a8},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 P9($,J){let Q={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":d(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J);break;case"max":d(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":V0(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":V0(Q,X.regex,X.message,J);break;case"cuid":V0(Q,C0.cuid,X.message,J);break;case"cuid2":V0(Q,C0.cuid2,X.message,J);break;case"startsWith":V0(Q,RegExp(`^${s8(X.value,J)}`),X.message,J);break;case"endsWith":V0(Q,RegExp(`${s8(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":d(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J),d(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"includes":{V0(Q,RegExp(s8(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":V0(Q,C0.base64url,X.message,J);break;case"jwt":V0(Q,C0.jwt,X.message,J);break;case"cidr":{if(X.version!=="v6")V0(Q,C0.ipv4Cidr,X.message,J);if(X.version!=="v4")V0(Q,C0.ipv6Cidr,X.message,J);break}case"emoji":V0(Q,C0.emoji(),X.message,J);break;case"ulid":{V0(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":{d(Q,"contentEncoding","base64",X.message,J);break}case"pattern:zod":{V0(Q,C0.base64,X.message,J);break}}break}case"nanoid":V0(Q,C0.nanoid,X.message,J);case"toLowerCase":case"toUpperCase":case"trim":break;default:((W)=>{})(X)}return Q}function s8($,J){return J.patternStrategy==="escape"?PO($):$}var bO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function PO($){let J="";for(let Q=0;Q<$.length;Q++){if(!bO.has($[Q]))J+="\\";J+=$[Q]}return J}function f0($,J,Q,X){if($.format||$.anyOf?.some((W)=>W.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 d($,"format",J,Q,X)}function V0($,J,Q,X){if($.pattern||$.allOf?.some((W)=>W.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:R1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else d($,"pattern",R1(J,X),Q,X)}function R1($,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,W="",G=!1,Y=!1,q=!1;for(let H=0;H<X.length;H++){if(G){W+=X[H],G=!1;continue}if(Q.i){if(Y){if(X[H].match(/[a-z]/)){if(q)W+=X[H],W+=`${X[H-2]}-${X[H]}`.toUpperCase(),q=!1;else if(X[H+1]==="-"&&X[H+2]?.match(/[a-z]/))W+=X[H],q=!0;else W+=`${X[H]}${X[H].toUpperCase()}`;continue}}else if(X[H].match(/[a-z]/)){W+=`[${X[H]}${X[H].toUpperCase()}]`;continue}}if(Q.m){if(X[H]==="^"){W+=`(^|(?<=[\r
|
|
2770
2771
|
]))`;continue}else if(X[H]==="$"){W+=`($|(?=[\r
|
|
2771
2772
|
]))`;continue}}if(Q.s&&X[H]==="."){W+=Y?`${X[H]}\r
|
|
2772
2773
|
`:`[${X[H]}\r
|
|
2773
|
-
]`;continue}if(W+=X[H],X[H]==="\\")G=!0;else if(Y&&X[H]==="]")Y=!1;else if(!Y&&X[H]==="[")Y=!0}try{new RegExp(W)}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 W}function S9($,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===j.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,W)=>({...X,[W]:v($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",W]})??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===j.ZodString&&$.keyType._def.checks?.length){let{type:X,...W}=P9($.keyType._def,J);return{...Q,propertyNames:W}}else if($.keyType?._def.typeName===j.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===j.ZodBranded&&$.keyType._def.type._def.typeName===j.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...W}=b9($.keyType._def,J);return{...Q,propertyNames:W}}return Q}function R1($,J){if(J.mapStrategy==="record")return S9($,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 L1($){let J=$.values,X=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),W=Array.from(new Set(X.map((G)=>typeof G)));return{type:W.length===1?W[0]==="string"?"string":"number":["string","number"],enum:X}}function A1($){return $.target==="openAi"?void 0:{not:t({...$,currentPath:[...$.currentPath,"not"]})}}function _1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var G6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function N1($,J){if(J.target==="openApi3")return j1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in G6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((W,G)=>{let Y=G6[G._def.typeName];return Y&&!W.includes(Y)?[...W,Y]:W},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((W,G)=>{let Y=typeof G._def.value;switch(Y){case"string":case"number":case"boolean":return[...W,Y];case"bigint":return[...W,"integer"];case"object":if(G._def.value===null)return[...W,"null"];case"symbol":case"undefined":case"function":default:return W}},[]);if(X.length===Q.length){let W=X.filter((G,Y,q)=>q.indexOf(G)===Y);return{type:W.length>1?W:W[0],enum:Q.reduce((G,Y)=>{return G.includes(Y._def.value)?G:[...G,Y._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,W)=>[...X,...W._def.values.filter((G)=>!X.includes(G))],[])};return j1($,J)}var j1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,W)=>v(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${W}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function Z1($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:G6[$.innerType._def.typeName],nullable:!0};return{type:[G6[$.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 w1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",n8(Q,"type",X.message,J);break;case"min":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"minimum",X.value,X.message,J);else d(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;d(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"maximum",X.value,X.message,J);else d(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;d(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":d(Q,"multipleOf",X.value,X.message,J);break}return Q}function b1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},W=[],G=$.shape();for(let q in G){let H=G[q];if(H===void 0||H._def===void 0)continue;let B=bO(H);if(B&&Q){if(H._def.typeName==="ZodOptional")H=H._def.innerType;if(!H.isNullable())H=H.nullable();B=!1}let U=v(H._def,{...J,currentPath:[...J.currentPath,"properties",q],propertyPath:[...J.currentPath,"properties",q]});if(U===void 0)continue;if(X.properties[q]=U,!B)W.push(q)}if(W.length)X.required=W;let Y=wO($,J);if(Y!==void 0)X.additionalProperties=Y;return X}function wO($,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 bO($){try{return $.isOptional()}catch{return!0}}var P1=($,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 S1=($,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((W)=>W!==void 0)}};function E1($,J){return v($.type._def,J)}function C1($,J){let X={type:"array",uniqueItems:!0,items:v($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)d(X,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)d(X,"maxItems",$.maxSize.value,$.maxSize.message,J);return X}function f1($,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 T1($){return{not:t($)}}function I1($){return t($)}var v1=($,J)=>{return v($.innerType._def,J)};var x1=($,J,Q)=>{switch(J){case j.ZodString:return P9($,Q);case j.ZodNumber:return w1($,Q);case j.ZodObject:return b1($,Q);case j.ZodBigInt:return B1($,Q);case j.ZodBoolean:return U1();case j.ZodDate:return r8($,Q);case j.ZodUndefined:return T1(Q);case j.ZodNull:return _1(Q);case j.ZodArray:return H1($,Q);case j.ZodUnion:case j.ZodDiscriminatedUnion:return N1($,Q);case j.ZodIntersection:return O1($,Q);case j.ZodTuple:return f1($,Q);case j.ZodRecord:return S9($,Q);case j.ZodLiteral:return M1($,Q);case j.ZodEnum:return F1($);case j.ZodNativeEnum:return L1($);case j.ZodNullable:return Z1($,Q);case j.ZodOptional:return P1($,Q);case j.ZodMap:return R1($,Q);case j.ZodSet:return C1($,Q);case j.ZodLazy:return()=>$.getter()._def;case j.ZodPromise:return E1($,Q);case j.ZodNaN:case j.ZodNever:return A1(Q);case j.ZodEffects:return D1($,Q);case j.ZodAny:return t(Q);case j.ZodUnknown:return I1(Q);case j.ZodDefault:return z1($,Q);case j.ZodBranded:return b9($,Q);case j.ZodReadonly:return v1($,Q);case j.ZodCatch:return V1($,Q);case j.ZodPipeline:return S1($,Q);case j.ZodFunction:case j.ZodVoid:case j.ZodSymbol:return;default:return((X)=>{return})(J)}};function v($,J,Q=!1){let X=J.seen.get($);if(J.override){let q=J.override?.($,J,X,Q);if(q!==G1)return q}if(X&&!Q){let q=PO(X,J);if(q!==void 0)return q}let W={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,W);let G=x1($,$.typeName,J),Y=typeof G==="function"?v(G(),J):G;if(Y)SO($,J,Y);if(J.postProcess){let q=J.postProcess(Y,$,J);return W.jsonSchema=Y,q}return W.jsonSchema=Y,Y}var PO=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:w9(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}}},SO=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var o8=($,J)=>{let Q=q1(J),X=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((H,[B,U])=>({...H,[B]:v(U._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,B]},!0)??t(Q)}),{}):void 0,W=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=v($._def,W===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,W]},!1)??t(Q),Y=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(Y!==void 0)G.title=Y;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 q=W===void 0?X?{...G,[Q.definitionPath]:X}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,W].join("/"),[Q.definitionPath]:{...X,[W]:G}};if(Q.target==="jsonSchema7")q.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")q.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.target==="openAi"&&(("anyOf"in q)||("oneOf"in q)||("allOf"in q)||("type"in q)&&Array.isArray(q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return q};var EO=[i2,t2,n2,r2,a2,s2,o2,e2,$6];function CO($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=o8(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:W,...G}=X;return G}catch{return{}}}function h1($,J={}){let Q=X1($,J);return EO.map((X)=>{let W=X(Q);return{name:W.name,description:W.description,input:CO(W.parameters),options:{codemode:!1},execute:async(G,Y)=>{let q={session_id:Y?.sessionID??J.sessionId??"unknown",workdir:Y?.directory};try{let H=await W.execute(G??{},q),B=typeof H.output==="string"?H.output:JSON.stringify(H.output??"");return{content:H.success?B:`ERROR: ${H.error??"unknown error"}`,metadata:{tool:W.name,ok:H.success}}}catch(H){return{content:`ERROR: ${H instanceof Error?H.message:String(H)}`,metadata:{tool:W.name,ok:!1}}}}}})}function y1($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function g1($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let W=$??{},G=J.agent??B2;if(typeof W.agent?.transform==="function")try{let q=await W.agent.transform((H)=>{y9(H)});y1(q,X.disposers),X.agentId=G}catch(q){X.errors.push(`roy agent registration failed: ${t8(q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let Y=[];try{Y=h1(J.store,{agent:G,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(q){return X.errors.push(`roy tool construction failed: ${t8(q)}`),X}if(typeof W.tool?.transform==="function")try{let q=await W.tool.transform((H)=>{for(let B of Y)H.add(B)});y1(q,X.disposers),X.toolNames=Y.map((H)=>H.name)}catch(q){X.errors.push(`roy tool registration failed: ${t8(q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function t8($){return $ instanceof Error?$.message:String($)}import{join as J7}from"path";import{homedir as gO}from"os";import{mkdirSync as kO}from"fs";import{Database as fO}from"bun:sqlite";import{createHash as TO,randomUUID as IO}from"crypto";var vO=`
|
|
2774
|
+
]`;continue}if(W+=X[H],X[H]==="\\")G=!0;else if(Y&&X[H]==="]")Y=!1;else if(!Y&&X[H]==="[")Y=!0}try{new RegExp(W)}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 W}function S9($,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===j.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,W)=>({...X,[W]:v($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",W]})??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===j.ZodString&&$.keyType._def.checks?.length){let{type:X,...W}=P9($.keyType._def,J);return{...Q,propertyNames:W}}else if($.keyType?._def.typeName===j.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===j.ZodBranded&&$.keyType._def.type._def.typeName===j.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...W}=b9($.keyType._def,J);return{...Q,propertyNames:W}}return Q}function L1($,J){if(J.mapStrategy==="record")return S9($,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 A1($){let J=$.values,X=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),W=Array.from(new Set(X.map((G)=>typeof G)));return{type:W.length===1?W[0]==="string"?"string":"number":["string","number"],enum:X}}function _1($){return $.target==="openAi"?void 0:{not:t({...$,currentPath:[...$.currentPath,"not"]})}}function j1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var G6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Z1($,J){if(J.target==="openApi3")return N1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in G6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((W,G)=>{let Y=G6[G._def.typeName];return Y&&!W.includes(Y)?[...W,Y]:W},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((W,G)=>{let Y=typeof G._def.value;switch(Y){case"string":case"number":case"boolean":return[...W,Y];case"bigint":return[...W,"integer"];case"object":if(G._def.value===null)return[...W,"null"];case"symbol":case"undefined":case"function":default:return W}},[]);if(X.length===Q.length){let W=X.filter((G,Y,q)=>q.indexOf(G)===Y);return{type:W.length>1?W:W[0],enum:Q.reduce((G,Y)=>{return G.includes(Y._def.value)?G:[...G,Y._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,W)=>[...X,...W._def.values.filter((G)=>!X.includes(G))],[])};return N1($,J)}var N1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,W)=>v(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${W}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function w1($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:G6[$.innerType._def.typeName],nullable:!0};return{type:[G6[$.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 b1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",n8(Q,"type",X.message,J);break;case"min":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"minimum",X.value,X.message,J);else d(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;d(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)d(Q,"maximum",X.value,X.message,J);else d(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;d(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":d(Q,"multipleOf",X.value,X.message,J);break}return Q}function P1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},W=[],G=$.shape();for(let q in G){let H=G[q];if(H===void 0||H._def===void 0)continue;let B=EO(H);if(B&&Q){if(H._def.typeName==="ZodOptional")H=H._def.innerType;if(!H.isNullable())H=H.nullable();B=!1}let U=v(H._def,{...J,currentPath:[...J.currentPath,"properties",q],propertyPath:[...J.currentPath,"properties",q]});if(U===void 0)continue;if(X.properties[q]=U,!B)W.push(q)}if(W.length)X.required=W;let Y=SO($,J);if(Y!==void 0)X.additionalProperties=Y;return X}function SO($,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 EO($){try{return $.isOptional()}catch{return!0}}var S1=($,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 E1=($,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((W)=>W!==void 0)}};function C1($,J){return v($.type._def,J)}function f1($,J){let X={type:"array",uniqueItems:!0,items:v($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)d(X,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)d(X,"maxItems",$.maxSize.value,$.maxSize.message,J);return X}function T1($,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 I1($){return{not:t($)}}function v1($){return t($)}var x1=($,J)=>{return v($.innerType._def,J)};var h1=($,J,Q)=>{switch(J){case j.ZodString:return P9($,Q);case j.ZodNumber:return b1($,Q);case j.ZodObject:return P1($,Q);case j.ZodBigInt:return U1($,Q);case j.ZodBoolean:return V1();case j.ZodDate:return r8($,Q);case j.ZodUndefined:return I1(Q);case j.ZodNull:return j1(Q);case j.ZodArray:return B1($,Q);case j.ZodUnion:case j.ZodDiscriminatedUnion:return Z1($,Q);case j.ZodIntersection:return M1($,Q);case j.ZodTuple:return T1($,Q);case j.ZodRecord:return S9($,Q);case j.ZodLiteral:return K1($,Q);case j.ZodEnum:return O1($);case j.ZodNativeEnum:return A1($);case j.ZodNullable:return w1($,Q);case j.ZodOptional:return S1($,Q);case j.ZodMap:return L1($,Q);case j.ZodSet:return f1($,Q);case j.ZodLazy:return()=>$.getter()._def;case j.ZodPromise:return C1($,Q);case j.ZodNaN:case j.ZodNever:return _1(Q);case j.ZodEffects:return F1($,Q);case j.ZodAny:return t(Q);case j.ZodUnknown:return v1(Q);case j.ZodDefault:return D1($,Q);case j.ZodBranded:return b9($,Q);case j.ZodReadonly:return x1($,Q);case j.ZodCatch:return z1($,Q);case j.ZodPipeline:return E1($,Q);case j.ZodFunction:case j.ZodVoid:case j.ZodSymbol:return;default:return((X)=>{return})(J)}};function v($,J,Q=!1){let X=J.seen.get($);if(J.override){let q=J.override?.($,J,X,Q);if(q!==Y1)return q}if(X&&!Q){let q=CO(X,J);if(q!==void 0)return q}let W={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,W);let G=h1($,$.typeName,J),Y=typeof G==="function"?v(G(),J):G;if(Y)fO($,J,Y);if(J.postProcess){let q=J.postProcess(Y,$,J);return W.jsonSchema=Y,q}return W.jsonSchema=Y,Y}var CO=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:w9(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}}},fO=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var o8=($,J)=>{let Q=H1(J),X=typeof J==="object"&&J.definitions?Object.entries(J.definitions).reduce((H,[B,U])=>({...H,[B]:v(U._def,{...Q,currentPath:[...Q.basePath,Q.definitionPath,B]},!0)??t(Q)}),{}):void 0,W=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=v($._def,W===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,W]},!1)??t(Q),Y=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(Y!==void 0)G.title=Y;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 q=W===void 0?X?{...G,[Q.definitionPath]:X}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,W].join("/"),[Q.definitionPath]:{...X,[W]:G}};if(Q.target==="jsonSchema7")q.$schema="http://json-schema.org/draft-07/schema#";else if(Q.target==="jsonSchema2019-09"||Q.target==="openAi")q.$schema="https://json-schema.org/draft/2019-09/schema#";if(Q.target==="openAi"&&(("anyOf"in q)||("oneOf"in q)||("allOf"in q)||("type"in q)&&Array.isArray(q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return q};var TO=[i2,t2,n2,r2,a2,s2,o2,e2,$6];function IO($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=o8(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:W,...G}=X;return G}catch{return{}}}function y1($,J={}){let Q=W1($,J);return TO.map((X)=>{let W=X(Q);return{name:W.name,description:W.description,input:IO(W.parameters),options:{codemode:!1},execute:async(G,Y)=>{let q={session_id:Y?.sessionID??J.sessionId??"unknown",workdir:Y?.directory};try{let H=await W.execute(G??{},q),B=typeof H.output==="string"?H.output:JSON.stringify(H.output??"");return{content:H.success?B:`ERROR: ${H.error??"unknown error"}`,metadata:{tool:W.name,ok:H.success}}}catch(H){return{content:`ERROR: ${H instanceof Error?H.message:String(H)}`,metadata:{tool:W.name,ok:!1}}}}}})}function g1($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function k1($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let W=$??{},G=J.agent??B2;if(typeof W.agent?.transform==="function")try{let q=await W.agent.transform((H)=>{y9(H)});g1(q,X.disposers),X.agentId=G}catch(q){X.errors.push(`roy agent registration failed: ${t8(q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let Y=[];try{Y=y1(J.store,{agent:G,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(q){return X.errors.push(`roy tool construction failed: ${t8(q)}`),X}if(typeof W.tool?.transform==="function")try{let q=await W.tool.transform((H)=>{for(let B of Y)H.add(B)});g1(q,X.disposers),X.toolNames=Y.map((H)=>H.name)}catch(q){X.errors.push(`roy tool registration failed: ${t8(q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function t8($){return $ instanceof Error?$.message:String($)}import{join as J7}from"path";import{homedir as uO}from"os";import{mkdirSync as lO}from"fs";import{Database as vO}from"bun:sqlite";import{createHash as xO,randomUUID as hO}from"crypto";var yO=`
|
|
2774
2775
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
2775
2776
|
id TEXT PRIMARY KEY,
|
|
2776
2777
|
title TEXT NOT NULL,
|
|
@@ -2825,13 +2826,13 @@ CREATE TABLE IF NOT EXISTS bounties (
|
|
|
2825
2826
|
done_at TEXT
|
|
2826
2827
|
);
|
|
2827
2828
|
CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
|
|
2828
|
-
`;function b$(){return new Date().toISOString()}function e8(){return
|
|
2829
|
+
`;function b$(){return new Date().toISOString()}function e8(){return hO()}function gO($){return xO("sha256").update($).digest("hex")}function m1($){let J=JSON.stringify({id:$.id,type:$.type,data:$.data,prev_hash:$.prev_hash,created_at:$.created_at});return gO(J)}function $7($){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:kO($.roy),created_at:$.created_at,updated_at:$.updated_at}}function kO($){if($===null||$===void 0||$==="")return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}function mO($){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 u1($){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 E9($){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 C9{db;closedFlag=!1;constructor($){this.db=$}static async create($){let J=new vO($);return J.exec(yO),mO(J),new C9(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 Y=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(J);if(Y){let q=await this.getTask(Y.task_id);if(q)return q}}let Q=e8(),X=b$(),W=$.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
|
|
2829
2830
|
parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
|
|
2830
2831
|
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.title,$.description??null,W,$.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)
|
|
2831
|
-
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?$7(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?$7(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],W=[];if(J.title!==void 0)X.push("title = ?"),W.push(J.title);if(J.description!==void 0)X.push("description = ?"),W.push(J.description);if(J.status!==void 0)X.push("status = ?"),W.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),W.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),W.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),W.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),W.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let G={...Q.roy??{},...J.roy};X.push("roy = ?"),W.push(JSON.stringify(G))}if(X.push("updated_at = ?"),W.push(b$()),W.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...W),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,W=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",Y=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,W).map($7),total:Y}}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,b$(),$)}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=e8(),W=b$(),G=
|
|
2832
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),W,Q,G);let Y=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:Y,task_id:$.task_id,type:$.type,data:$.data,created_at:W,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?
|
|
2832
|
+
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?$7(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?$7(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],W=[];if(J.title!==void 0)X.push("title = ?"),W.push(J.title);if(J.description!==void 0)X.push("description = ?"),W.push(J.description);if(J.status!==void 0)X.push("status = ?"),W.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),W.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),W.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),W.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),W.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let G={...Q.roy??{},...J.roy};X.push("roy = ?"),W.push(JSON.stringify(G))}if(X.push("updated_at = ?"),W.push(b$()),W.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...W),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,W=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",Y=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,W).map($7),total:Y}}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,b$(),$)}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=e8(),W=b$(),G=m1({id:X,type:$.type,data:$.data,prev_hash:Q,created_at:W});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
|
|
2833
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),W,Q,G);let Y=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:Y,task_id:$.task_id,type:$.type,data:$.data,created_at:W,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?u1(J):null}async updateOperation($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getOperationByNum($);if(!Q)return null;let X=[],W=[];if(J.type!==void 0)X.push("type = ?"),W.push(J.type);if(J.data!==void 0)X.push("data = ?"),W.push(JSON.stringify(J.data));if(X.length===0)return Q;return W.push($),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...W),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,W=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",Y=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,W).map(u1),total:Y}}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=m1({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=e8(),Q=b$();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
|
|
2833
2834
|
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 E9(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=b$();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 E9(X)}async completeBounty($,J){if(this.closedFlag)throw Error("store closed");let Q=b$();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
|
|
2834
|
-
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 W=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return E9(W)}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(E9)}}var
|
|
2835
|
+
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 W=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return E9(W)}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(E9)}}var cO=J7(uO(),".roy-task-plugin"),dO=J7(cO,"tasks.db");class G2{inner;constructor($){this.inner=$}static async create($){let J=$??dO;if(J!==":memory:")lO(J7(J,".."),{recursive:!0});let Q=await C9.create(J);return new G2(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 y0 extends Error{status;body;constructor($,J,Q){super(J);this.status=$,this.body=Q}}class Q7{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 W=await fetch(`${this.baseUrl}${J}`,{method:$,headers:X,body:Q?.body!==void 0?JSON.stringify(Q.body):void 0});if(W.status===204)return null;let G=await W.text(),Y=null;try{Y=G?JSON.parse(G):null}catch{Y=G}if(!W.ok)throw new y0(W.status,`HTTP ${W.status}`,Y);return Y}async createTask($,J){let Q=await this.request("POST","/tasks",{body:$,idempotencyKey:J});if(!Q)throw new y0(500,"empty response from POST /tasks");return Q}async getTask($){try{return await this.request("GET",`/tasks/${encodeURIComponent($)}`)}catch(J){if(J instanceof y0&&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 y0&&Q.status===404)return null;throw Q}}async deleteTask($){try{return await this.request("DELETE",`/tasks/${encodeURIComponent($)}`),!0}catch(J){if(J instanceof y0&&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 y0(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 y0(500,"empty bounty response");return J}async claimBounty($){try{return await this.request("POST","/bounties/claim",{body:{agent:$}})}catch(J){if(J instanceof y0&&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 y0&&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 Y6{inner;constructor($){this.inner=new Q7($)}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 hZ($={}){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 Y6({baseUrl:$.remoteUrl,authToken:$.remoteAuthToken})}else Q=await G2.create($.localDbPath);let X={store:Q,agent:$.agent??"opencode-default"};return{handlers:U6(X),store:Q,async close(){await Q.close()}}}var pO={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 Y6({baseUrl:J.remoteUrl,authToken:J.remoteAuthToken})}else X=await G2.create(J.localDbPath);let W={store:X,agent:J.agent??"opencode-default"},G=U6(W),Y=await k1($,{store:X,enabled:J.royAgent!==!1,agent:"roy"}),q=await $.agent.transform(async(B)=>{let z=B.get("build");if(!z)return;let V=String(z.system??""),M=`
|
|
2835
2836
|
|
|
2836
2837
|
# Roy Task Plugin (auto-injected by roy-task-plugin v2)
|
|
2837
2838
|
|
|
@@ -2847,6 +2848,6 @@ For task-first-class-citizen work (task tree, milestones, deliverables), switch
|
|
|
2847
2848
|
to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
|
|
2848
2849
|
lifecycle as native tools.
|
|
2849
2850
|
`;B.update("build",(F)=>{if(typeof F.system==="string"||F.system===void 0)F.system=V+M})}),H=await $.command.transform((B)=>{B.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(U)=>{let z=String(U?.prompt?.text??"").trim(),V=z.split(`
|
|
2850
|
-
`)[0]?.trim()||`task-${Date.now()}`;await G.session({type:"session.created",payload:{id:U?.sessionID??`cmd-${Date.now()}`,title:V,body:z,source:"command:task-create"}})}}),B.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),B.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 B of Y.disposers)try{await B()}catch{}await q.dispose(),await H.dispose(),await X.close()}}}},
|
|
2851
|
+
`)[0]?.trim()||`task-${Date.now()}`;await G.session({type:"session.created",payload:{id:U?.sessionID??`cmd-${Date.now()}`,title:V,body:z,source:"command:task-create"}})}}),B.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),B.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 B of Y.disposers)try{await B()}catch{}await q.dispose(),await H.dispose(),await X.close()}}}},gZ=pO;export{gZ as default,hZ as createRoyTaskPlugin,U6 as createHandlers,Y6 as RemoteTaskStore,G2 as LocalTaskStore};
|
|
2851
2852
|
|
|
2852
|
-
//# debugId=
|
|
2853
|
+
//# debugId=F3E03D2336A3457064756E2164756E21
|