@ai-setting/roy-task-plugin 0.7.5 → 0.7.7
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 +62 -12
- package/dist/claude-plugin/commands/task-milestone.md +1 -1
- package/dist/cli.js +228 -57
- package/dist/index.js +370 -232
- package/dist/index.js.map +15 -12
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,141 +1,141 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}}
|
|
4
|
-
`)?
|
|
2
|
+
var S1=Object.create;var{getPrototypeOf:C1,defineProperty:Z9,getOwnPropertyNames:f1}=Object;var I1=Object.prototype.hasOwnProperty;function T1($){return this[$]}var v1,x1,h1=($,J,Q)=>{var X=$!=null&&typeof $==="object";if(X){var Y=J?v1??=new WeakMap:x1??=new WeakMap,G=Y.get($);if(G)return G}Q=$!=null?S1(C1($)):{};let W=J||!$||!$.__esModule?Z9(Q,"default",{value:$,enumerable:!0}):Q;for(let q of f1($))if(!I1.call(W,q))Z9(W,q,{get:T1.bind($,q),enumerable:!0});if(X)Y.set($,W);return W};var C=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var y1=($)=>$;function g1($,J){this[$]=y1.bind(null,J)}var k1=($,J)=>{for(var Q in J)Z9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:g1.bind(J,Q)})};var W6=import.meta.require;var d=C((zY)=>{var t9=Symbol.for("yaml.alias"),y7=Symbol.for("yaml.document"),K6=Symbol.for("yaml.map"),g7=Symbol.for("yaml.pair"),e9=Symbol.for("yaml.scalar"),_6=Symbol.for("yaml.seq"),c0=Symbol.for("yaml.node.type"),GY=($)=>!!$&&typeof $==="object"&&$[c0]===t9,WY=($)=>!!$&&typeof $==="object"&&$[c0]===y7,qY=($)=>!!$&&typeof $==="object"&&$[c0]===K6,HY=($)=>!!$&&typeof $==="object"&&$[c0]===g7,k7=($)=>!!$&&typeof $==="object"&&$[c0]===e9,BY=($)=>!!$&&typeof $==="object"&&$[c0]===_6;function m7($){if($&&typeof $==="object")switch($[c0]){case K6:case _6:return!0}return!1}function UY($){if($&&typeof $==="object")switch($[c0]){case t9:case K6:case e9:case _6:return!0}return!1}var VY=($)=>(k7($)||m7($))&&!!$.anchor;zY.ALIAS=t9;zY.DOC=y7;zY.MAP=K6;zY.NODE_TYPE=c0;zY.PAIR=g7;zY.SCALAR=e9;zY.SEQ=_6;zY.hasAnchor=VY;zY.isAlias=GY;zY.isCollection=m7;zY.isDocument=WY;zY.isMap=qY;zY.isNode=UY;zY.isPair=HY;zY.isScalar=k7;zY.isSeq=BY});var K2=C((SY)=>{var Y0=d(),D0=Symbol("break visit"),u7=Symbol("skip children"),x0=Symbol("remove node");function L6($,J){let Q=l7(J);if(Y0.isDocument($)){if(c$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else c$(null,$,Q,Object.freeze([]))}L6.BREAK=D0;L6.SKIP=u7;L6.REMOVE=x0;function c$($,J,Q,X){let Y=c7($,J,Q,X);if(Y0.isNode(Y)||Y0.isPair(Y))return p7($,X,Y),c$($,Y,Q,X);if(typeof Y!=="symbol"){if(Y0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let W=c$(G,J.items[G],Q,X);if(typeof W==="number")G=W-1;else if(W===D0)return D0;else if(W===x0)J.items.splice(G,1),G-=1}}else if(Y0.isPair(J)){X=Object.freeze(X.concat(J));let G=c$("key",J.key,Q,X);if(G===D0)return D0;else if(G===x0)J.key=null;let W=c$("value",J.value,Q,X);if(W===D0)return D0;else if(W===x0)J.value=null}}return Y}async function R6($,J){let Q=l7(J);if(Y0.isDocument($)){if(await p$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else await p$(null,$,Q,Object.freeze([]))}R6.BREAK=D0;R6.SKIP=u7;R6.REMOVE=x0;async function p$($,J,Q,X){let Y=await c7($,J,Q,X);if(Y0.isNode(Y)||Y0.isPair(Y))return p7($,X,Y),p$($,Y,Q,X);if(typeof Y!=="symbol"){if(Y0.isCollection(J)){X=Object.freeze(X.concat(J));for(let G=0;G<J.items.length;++G){let W=await p$(G,J.items[G],Q,X);if(typeof W==="number")G=W-1;else if(W===D0)return D0;else if(W===x0)J.items.splice(G,1),G-=1}}else if(Y0.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 W=await p$("value",J.value,Q,X);if(W===D0)return D0;else if(W===x0)J.value=null}}return Y}function l7($){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 c7($,J,Q,X){if(typeof Q==="function")return Q($,J,X);if(Y0.isMap(J))return Q.Map?.($,J,X);if(Y0.isSeq(J))return Q.Seq?.($,J,X);if(Y0.isPair(J))return Q.Pair?.($,J,X);if(Y0.isScalar(J))return Q.Scalar?.($,J,X);if(Y0.isAlias(J))return Q.Alias?.($,J,X);return}function p7($,J,Q){let X=J[J.length-1];if(Y0.isCollection(X))X.items[$]=Q;else if(Y0.isPair(X))if($==="key")X.key=Q;else X.value=Q;else if(Y0.isDocument(X))X.contents=Q;else{let Y=Y0.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${Y} parent`)}}SY.visit=L6;SY.visitAsync=R6});var $4=C((xY)=>{var d7=d(),IY=K2(),TY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},vY=($)=>$.replace(/[!,[\]{}]/g,(J)=>TY[J]);class K0{constructor($,J){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},K0.defaultYaml,$),this.tags=Object.assign({},K0.defaultTags,J)}clone(){let $=new K0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new K0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:K0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},K0.defaultTags);break}return $}add($,J){if(this.atNextDocument)this.yaml={explicit:K0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},K0.defaultTags),this.atNextDocument=!1;let Q=$.trim().split(/[ \t]+/),X=Q.shift();switch(X){case"%TAG":{if(Q.length!==2){if(J(0,"%TAG directive should contain exactly two parts"),Q.length<2)return!1}let[Y,G]=Q;return this.tags[Y]=G,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return J(0,"%YAML directive should contain exactly one part"),!1;let[Y]=Q;if(Y==="1.1"||Y==="1.2")return this.yaml.version=Y,!0;else{let G=/^\d+\.\d+$/.test(Y);return J(6,`Unsupported YAML version ${Y}`,G),!1}}default:return J(0,`Unknown directive ${X}`,!0),!1}}tagName($,J){if($==="!")return"!";if($[0]!=="!")return J(`Not a valid tag: ${$}`),null;if($[1]==="<"){let G=$.slice(2,-1);if(G==="!"||G==="!!")return J(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")J("Verbatim tags must end with a >");return G}let[,Q,X]=$.match(/^(.*!)([^!]*)$/s);if(!X)J(`The ${$} tag has no suffix`);let Y=this.tags[Q];if(Y)try{return Y+decodeURIComponent(X)}catch(G){return J(String(G)),null}if(Q==="!")return $;return J(`Could not resolve tag: ${$}`),null}tagString($){for(let[J,Q]of Object.entries(this.tags))if($.startsWith(Q))return J+vY($.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&&d7.isNode($.contents)){let Y={};IY.visit($.contents,(G,W)=>{if(d7.isNode(W)&&W.tag)Y[W.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,G]of Q){if(Y==="!!"&&G==="tag:yaml.org,2002:")continue;if(!$||X.some((W)=>W.startsWith(G)))J.push(`%TAG ${Y} ${G}`)}return J.join(`
|
|
3
|
+
`)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};xY.Directives=K0});var A6=C((mY)=>{var i7=d(),yY=K2();function gY($){if(/[\x00-\x19\s,[\]{}]/.test($)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(Q)}return!0}function n7($){let J=new Set;return yY.visit($,{Value(Q,X){if(X.anchor)J.add(X.anchor)}}),J}function r7($,J){for(let Q=1;;++Q){let X=`${$}${Q}`;if(!J.has(X))return X}}function kY($,J){let Q=[],X=new Map,Y=null;return{onAnchor:(G)=>{Q.push(G),Y??(Y=n7($));let W=r7(J,Y);return Y.add(W),W},setAnchors:()=>{for(let G of Q){let W=X.get(G);if(typeof W==="object"&&W.anchor&&(i7.isScalar(W.node)||i7.isCollection(W.node)))W.node.anchor=W.anchor;else{let q=Error("Failed to resolve repeated object (this should not happen)");throw q.source=G,q}}},sourceObjects:X}}mY.anchorIsValid=gY;mY.anchorNames=n7;mY.createNodeAnchors=kY;mY.findNewAnchor=r7});var J4=C((dY)=>{function _2($,J,Q,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,G=X.length;Y<G;++Y){let W=X[Y],q=_2($,X,String(Y),W);if(q===void 0)delete X[Y];else if(q!==W)X[Y]=q}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let G=X.get(Y),W=_2($,X,Y,G);if(W===void 0)X.delete(Y);else if(W!==G)X.set(Y,W)}else if(X instanceof Set)for(let Y of Array.from(X)){let G=_2($,X,Y,Y);if(G===void 0)X.delete(Y);else if(G!==Y)X.delete(Y),X.add(G)}else for(let[Y,G]of Object.entries(X)){let W=_2($,X,Y,G);if(W===void 0)delete X[Y];else if(W!==G)X[Y]=W}return $.call(J,Q,X)}dY.applyReviver=_2});var t0=C((rY)=>{var nY=d();function a7($,J,Q){if(Array.isArray($))return $.map((X,Y)=>a7(X,String(Y),Q));if($&&typeof $.toJSON==="function"){if(!Q||!nY.hasAnchor($))return $.toJSON(J,Q);let X={aliasCount:0,count:1,res:void 0};Q.anchors.set($,X),Q.onCreate=(G)=>{X.res=G,delete Q.onCreate};let Y=$.toJSON(J,Q);if(Q.onCreate)Q.onCreate(Y);return Y}if(typeof $==="bigint"&&!Q?.keep)return Number($);return $}rY.toJS=a7});var N6=C((tY)=>{var sY=J4(),s7=d(),oY=t0();class o7{constructor($){Object.defineProperty(this,s7.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:J,maxAliasCount:Q,onAnchor:X,reviver:Y}={}){if(!s7.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},W=oY.toJS(this,"",G);if(typeof X==="function")for(let{count:q,res:H}of G.anchors.values())X(H,q);return typeof Y==="function"?sY.applyReviver(Y,{"":W},"",W):W}}tY.NodeBase=o7});var L2=C((YG)=>{var $G=A6(),JG=K2(),d$=d(),QG=N6(),XG=t0();class t7 extends QG.NodeBase{constructor($){super(d$.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=[],JG.visit($,{Node:(Y,G)=>{if(d$.isAlias(G)||d$.hasAnchor(G))Q.push(G)}}),J)J.aliasResolveCache=Q;let X=void 0;for(let Y of Q){if(Y===this)break;if(Y.anchor===this.source)X=Y}if(X&&J){let{anchors:Y,doc:G,maxAliasCount:W}=J,q=Y.get(X);if(!q)XG.toJS(X,null,J),q=Y.get(X);if(q?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(W>=0){if(q.count+=1,q.aliasCount===0)q.aliasCount=j6(G,X,Y);if(q.count*q.aliasCount>W)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($G.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let Y=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(Y)}if($.implicitKey)return`${X} `}return X}}function j6($,J,Q){if(d$.isAlias(J)){let X=J.resolve($),Y=Q&&X&&Q.get(X);return Y?Y.count*Y.aliasCount:0}else if(d$.isCollection(J)){let X=0;for(let Y of J.items){let G=j6($,Y,Q);if(G>X)X=G}return X}else if(d$.isPair(J)){let X=j6($,J.key,Q),Y=j6($,J.value,Q);return Math.max(X,Y)}return 1}YG.Alias=t7});var X0=C((UG)=>{var WG=d(),qG=N6(),HG=t0(),BG=($)=>!$||typeof $!=="function"&&typeof $!=="object";class O$ extends qG.NodeBase{constructor($){super(WG.SCALAR);this.value=$}toJSON($,J){return J?.keep?this.value:HG.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";UG.Scalar=O$;UG.isScalarValue=BG});var R2=C((KG)=>{var DG=L2(),M$=d(),e7=X0(),OG="tag:yaml.org,2002:";function MG($,J,Q){if(J){let X=Q.filter((G)=>G.tag===J),Y=X.find((G)=>!G.format)??X[0];if(!Y)throw Error(`Tag ${J} not found`);return Y}return Q.find((X)=>X.identify?.($)&&!X.format)}function FG($,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:Y,onTagObj:G,schema:W,sourceObjects:q}=Q,H=void 0;if(X&&$&&typeof $==="object")if(H=q.get($),H)return H.anchor??(H.anchor=Y($)),new DG.Alias(H.anchor);else H={anchor:null,node:null},q.set($,H);if(J?.startsWith("!!"))J=OG+J.slice(2);let B=MG($,J,W.tags);if(!B){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let z=new e7.Scalar($);if(H)H.node=z;return z}B=$ instanceof Map?W[M$.MAP]:(Symbol.iterator in Object($))?W[M$.SEQ]:W[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 e7.Scalar($);if(J)U.tag=J;else if(!B.default)U.tag=B.tag;if(H)H.node=U;return U}KG.createNode=FG});var Z6=C((AG)=>{var LG=R2(),h0=d(),RG=N6();function Q4($,J,Q){let X=Q;for(let Y=J.length-1;Y>=0;--Y){let G=J[Y];if(typeof G==="number"&&Number.isInteger(G)&&G>=0){let W=[];W[G]=X,X=W}else X=new Map([[G,X]])}return LG.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var $5=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class J5 extends RG.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($5($))this.add(J);else{let[Q,...X]=$,Y=this.get(Q,!0);if(h0.isCollection(Y))Y.addIn(X,J);else if(Y===void 0&&this.schema)this.set(Q,Q4(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]=$,Y=this.get(Q,!0);if(X.length===0)return!J&&h0.isScalar(Y)?Y.value:Y;else return h0.isCollection(Y)?Y.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 Y=this.get(Q,!0);if(h0.isCollection(Y))Y.setIn(X,J);else if(Y===void 0&&this.schema)this.set(Q,Q4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}}AG.Collection=J5;AG.collectionFromPath=Q4;AG.isEmptyPath=$5});var A2=C((bG)=>{var PG=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function X4($,J){if(/^\n+$/.test($))return $.substring(1);return J?$.replace(/^(?! *$)/gm,J):$}var wG=($,J,Q)=>$.endsWith(`
|
|
4
|
+
`)?X4(Q,J):Q.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
`+
|
|
7
|
-
`){if(
|
|
8
|
-
`&&
|
|
9
|
-
`&&
|
|
10
|
-
${
|
|
11
|
-
${
|
|
12
|
-
`);X=
|
|
13
|
-
`){if(
|
|
14
|
-
|
|
15
|
-
`;while(
|
|
16
|
-
`,
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test(
|
|
18
|
-
${
|
|
6
|
+
`+X4(Q,J):($.endsWith(" ")?"":" ")+Q;bG.indentComment=X4;bG.lineComment=wG;bG.stringifyComment=PG});var X5=C((IG)=>{function fG($,J,Q="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:G=20,onFold:W,onOverflow:q}={}){if(!Y||Y<0)return $;if(Y<G)G=0;let H=Math.max(1+G,1+Y-J.length);if($.length<=H)return $;let B=[],U={},z=Y-J.length;if(typeof X==="number")if(X>Y-Math.max(2,G))B.push(0);else z=Y-X;let V=void 0,F=void 0,O=!1,D=-1,M=-1,_=-1;if(Q==="block"){if(D=Q5($,D,J.length),D!==-1)z=D+H}for(let A;A=$[D+=1];){if(Q==="quoted"&&A==="\\"){switch(M=D,$[D+1]){case"x":D+=3;break;case"u":D+=5;break;case"U":D+=9;break;default:D+=1}_=D}if(A===`
|
|
7
|
+
`){if(Q==="block")D=Q5($,D,J.length);z=D+J.length+H,V=void 0}else{if(A===" "&&F&&F!==" "&&F!==`
|
|
8
|
+
`&&F!=="\t"){let Z=$[D+1];if(Z&&Z!==" "&&Z!==`
|
|
9
|
+
`&&Z!=="\t")V=D}if(D>=z)if(V)B.push(V),z=V+H,V=void 0;else if(Q==="quoted"){while(F===" "||F==="\t")F=A,A=$[D+=1],O=!0;let Z=D>_+1?D-2:M-1;if(U[Z])return $;B.push(Z),U[Z]=!0,z=Z+H,V=void 0}else O=!0}F=A}if(O&&q)q();if(B.length===0)return $;if(W)W();let L=$.slice(0,B[0]);for(let A=0;A<B.length;++A){let Z=B[A],b=B[A+1]||$.length;if(Z===0)L=`
|
|
10
|
+
${J}${$.slice(0,b)}`;else{if(Q==="quoted"&&U[Z])L+=`${$[Z]}\\`;L+=`
|
|
11
|
+
${J}${$.slice(Z+1,b)}`}}return L}function Q5($,J,Q){let X=J,Y=J+1,G=$[Y];while(G===" "||G==="\t")if(J<Y+Q)G=$[++J];else{do G=$[++J];while(G&&G!==`
|
|
12
|
+
`);X=J,Y=J+1,G=$[Y]}return X}IG.FOLD_BLOCK="block";IG.FOLD_FLOW="flow";IG.FOLD_QUOTED="quoted";IG.foldFlowLines=fG});var j2=C((mG)=>{var b0=X0(),e0=X5(),w6=($,J)=>({indentAtStart:J?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),b6=($)=>/^(%|---|\.\.\.)/m.test($);function yG($,J,Q){if(!J||J<0)return!1;let X=J-Q,Y=$.length;if(Y<=X)return!1;for(let G=0,W=0;G<Y;++G)if($[G]===`
|
|
13
|
+
`){if(G-W>X)return!0;if(W=G+1,Y-W<=X)return!1}return!0}function N2($,J){let Q=JSON.stringify($);if(J.options.doubleQuotedAsJSON)return Q;let{implicitKey:X}=J,Y=J.options.doubleQuotedMinMultiLineLength,G=J.indent||(b6($)?" ":""),W="",q=0;for(let H=0,B=Q[H];B;B=Q[++H]){if(B===" "&&Q[H+1]==="\\"&&Q[H+2]==="n")W+=Q.slice(q,H)+"\\ ",H+=1,q=H,B="\\";if(B==="\\")switch(Q[H+1]){case"u":{W+=Q.slice(q,H);let U=Q.substr(H+2,4);switch(U){case"0000":W+="\\0";break;case"0007":W+="\\a";break;case"000b":W+="\\v";break;case"001b":W+="\\e";break;case"0085":W+="\\N";break;case"00a0":W+="\\_";break;case"2028":W+="\\L";break;case"2029":W+="\\P";break;default:if(U.substr(0,2)==="00")W+="\\x"+U.substr(2);else W+=Q.substr(H,6)}H+=5,q=H+1}break;case"n":if(X||Q[H+2]==='"'||Q.length<Y)H+=1;else{W+=Q.slice(q,H)+`
|
|
14
|
+
|
|
15
|
+
`;while(Q[H+2]==="\\"&&Q[H+3]==="n"&&Q[H+4]!=='"')W+=`
|
|
16
|
+
`,H+=2;if(W+=G,Q[H+2]===" ")W+="\\";H+=1,q=H+1}break;default:H+=1}}return W=q?W+Q.slice(q):Q,X?W:e0.foldFlowLines(W,G,e0.FOLD_QUOTED,w6(J,!1))}function Y4($,J){if(J.options.singleQuote===!1||J.implicitKey&&$.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test($))return N2($,J);let Q=J.indent||(b6($)?" ":""),X="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${Q}`)+"'";return J.implicitKey?X:e0.foldFlowLines(X,Q,e0.FOLD_FLOW,w6(J,!1))}function i$($,J){let{singleQuote:Q}=J.options,X;if(Q===!1)X=N2;else{let Y=$.includes('"'),G=$.includes("'");if(Y&&!G)X=Y4;else if(G&&!Y)X=N2;else X=Q?Y4:N2}return X($,J)}var G4;try{G4=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{G4=/\n+(?!\n|$)/g}function P6({comment:$,type:J,value:Q},X,Y,G){let{blockQuote:W,commentString:q,lineWidth:H}=X.options;if(!W||/\n[\t ]+$/.test(Q))return i$(Q,X);let B=X.indent||(X.forceBlockIndent||b6(Q)?" ":""),U=W==="literal"?!0:W==="folded"||J===b0.Scalar.BLOCK_FOLDED?!1:J===b0.Scalar.BLOCK_LITERAL?!0:!yG(Q,H,B.length);if(!Q)return U?`|
|
|
22
22
|
`:`>
|
|
23
|
-
`;let
|
|
24
|
-
`&&
|
|
25
|
-
`);if(
|
|
26
|
-
`)
|
|
27
|
-
`)M
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
`)||
|
|
32
|
-
`)?
|
|
33
|
-
`))return
|
|
34
|
-
${
|
|
35
|
-
${
|
|
36
|
-
${
|
|
37
|
-
`:"",
|
|
38
|
-
${
|
|
39
|
-
`&&
|
|
40
|
-
|
|
41
|
-
`}else
|
|
42
|
-
${
|
|
43
|
-
`),
|
|
44
|
-
${
|
|
45
|
-
`)
|
|
46
|
-
${
|
|
47
|
-
`}}if(
|
|
48
|
-
`+
|
|
49
|
-
`)),
|
|
50
|
-
${
|
|
51
|
-
`;return`${
|
|
52
|
-
${Y}${
|
|
53
|
-
`:" ")}return
|
|
54
|
-
${Y.key.commentBefore}`:X.commentBefore;if(X.comment){let
|
|
55
|
-
${J.comment}`:X.comment}X=Y}_.items[$]=v1.isPair(X)?X:new U3.Pair(X)}else w("Expected a sequence for this tag");return _}function A8(_,w,$){let{replacer:X}=$,Y=new CW.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let D of w){if(typeof X==="function")D=X.call(w,String(J++),D);let W,G;if(Array.isArray(D))if(D.length===2)W=D[0],G=D[1];else throw TypeError(`Expected [key, value] tuple: ${D}`);else if(D&&D instanceof Object){let Q=Object.keys(D);if(Q.length===1)W=Q[0],G=D[W];else throw TypeError(`Expected tuple with one key, not ${Q.length} keys`)}else W=D;Y.items.push(U3.createPair(W,G,$))}return Y}var TW={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:O8,createNode:A8};IW.createPairs=A8;IW.pairs=TW;IW.resolvePairs=O8});var V3=P((xW)=>{var M8=p(),z3=s_(),b0=$w(),yW=Xw(),R8=x1();class Ow extends yW.YAMLSeq{constructor(){super();this.add=b0.YAMLMap.prototype.add.bind(this),this.delete=b0.YAMLMap.prototype.delete.bind(this),this.get=b0.YAMLMap.prototype.get.bind(this),this.has=b0.YAMLMap.prototype.has.bind(this),this.set=b0.YAMLMap.prototype.set.bind(this),this.tag=Ow.tag}toJSON(_,w){if(!w)return super.toJSON(_);let $=new Map;if(w?.onCreate)w.onCreate($);for(let X of this.items){let Y,J;if(M8.isPair(X))Y=z3.toJS(X.key,"",w),J=z3.toJS(X.value,Y,w);else Y=z3.toJS(X,"",w);if($.has(Y))throw Error("Ordered maps must not include duplicate keys");$.set(Y,J)}return $}static from(_,w,$){let X=R8.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Ow.tag="tag:yaml.org,2002:omap";var vW={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Ow,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=R8.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(M8.isScalar(Y))if(X.includes(Y.value))w(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new Ow,$)},createNode:(_,w,$)=>Ow.from(_,w,$)};xW.YAMLOMap=Ow;xW.omap=vW});var N8=P((lW)=>{var f8=X_();function L8({value:_,source:w},$){if(w&&(_?F8:K8).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var F8={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new f8.Scalar(!0),stringify:L8},K8={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new f8.Scalar(!1),stringify:L8};lW.falseTag=K8;lW.trueTag=F8});var b8=P((aW)=>{var pW=X_(),O3=nw(),iW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:O3.stringifyNumber},nW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_.replace(/_/g,"")),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():O3.stringifyNumber(_)}},rW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new pW.Scalar(parseFloat(_.replace(/_/g,""))),$=_.indexOf(".");if($!==-1){let X=_.substring($+1).replace(/_/g,"");if(X[X.length-1]==="0")w.minFractionDigits=X.length}return w},stringify:O3.stringifyNumber};aW.float=rW;aW.floatExp=nW;aW.floatNaN=iW});var E8=P((XG)=>{var j8=nw(),j0=(_)=>typeof _==="bigint"||Number.isInteger(_);function m1(_,w,$,{intAsBigInt:X}){let Y=_[0];if(Y==="-"||Y==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let D=BigInt(_);return Y==="-"?BigInt(-1)*D:D}let J=parseInt(_,$);return Y==="-"?-1*J:J}function A3(_,w,$){let{value:X}=_;if(j0(X)){let Y=X.toString(w);return X<0?"-"+$+Y.substr(1):$+Y}return j8.stringifyNumber(_)}var eW={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>m1(_,2,2,$),stringify:(_)=>A3(_,2,"0b")},_G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>m1(_,1,8,$),stringify:(_)=>A3(_,8,"0")},wG={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>m1(_,0,10,$),stringify:j8.stringifyNumber},$G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>m1(_,2,16,$),stringify:(_)=>A3(_,16,"0x")};XG.int=wG;XG.intBin=eW;XG.intHex=$G;XG.intOct=_G});var M3=P((QG)=>{var c1=p(),u1=_w(),l1=$w();class Aw extends l1.YAMLMap{constructor(_){super(_);this.tag=Aw.tag}add(_){let w;if(c1.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new u1.Pair(_.key,null);else w=new u1.Pair(_,null);if(!l1.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=l1.findPair(this.items,_);return!w&&c1.isPair($)?c1.isScalar($.key)?$.key.value:$.key:$}set(_,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let $=l1.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new u1.Pair(_))}toJSON(_,w){return super.toJSON(_,w,Set)}toString(_,w,$){if(!_)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},_,{allNullValues:!0}),w,$);else throw Error("Set items must all have null values")}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof X==="function")J=X.call(w,J,J);Y.items.push(u1.createPair(J,null,$))}return Y}}Aw.tag="tag:yaml.org,2002:set";var GG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Aw,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Aw.from(_,w,$),resolve(_,w){if(c1.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Aw,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};QG.YAMLSet=Aw;QG.set=GG});var f3=P((VG)=>{var BG=nw();function R3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(D)=>w?BigInt(D):Number(D),J=X.replace(/_/g,"").split(":").reduce((D,W)=>D*Y(60)+Y(W),Y(0));return $==="-"?Y(-1)*J:J}function S8(_){let{value:w}=_,$=(D)=>D;if(typeof w==="bigint")$=(D)=>BigInt(D);else if(isNaN(w)||!isFinite(w))return BG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let Y=$(60),J=[w%Y];if(w<60)J.unshift(0);else if(w=(w-J[0])/Y,J.unshift(w%Y),w>=60)w=(w-J[0])/Y,J.unshift(w);return X+J.map((D)=>String(D).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var UG={identify:(_)=>typeof _==="bigint"||Number.isInteger(_),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(_,w,{intAsBigInt:$})=>R3(_,$),stringify:S8},zG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(_)=>R3(_,!1),stringify:S8},P8={identify:(_)=>_ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(_){let w=_.match(P8.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,D,W]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,Q=Date.UTC($,X-1,Y,J||0,D||0,W||0,G),q=w[8];if(q&&q!=="Z"){let H=R3(q,!1);if(Math.abs(H)<30)H*=60;Q-=60000*H}return new Date(Q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};VG.floatTime=zG;VG.intTime=UG;VG.timestamp=P8});var C8=P((PG)=>{var RG=pw(),fG=g1(),LG=iw(),FG=K0(),KG=B3(),Z8=N8(),L3=b8(),d1=E8(),NG=E1(),bG=V3(),jG=x1(),EG=M3(),F3=f3(),SG=[RG.map,LG.seq,FG.string,fG.nullTag,Z8.trueTag,Z8.falseTag,d1.intBin,d1.intOct,d1.int,d1.intHex,L3.floatNaN,L3.floatExp,L3.float,KG.binary,NG.merge,bG.omap,jG.pairs,EG.set,F3.intTime,F3.floatTime,F3.timestamp];PG.schema=SG});var u8=P((vG)=>{var g8=pw(),CG=g1(),h8=iw(),TG=K0(),IG=Y3(),K3=D3(),N3=G3(),kG=U8(),gG=V8(),y8=B3(),E0=E1(),v8=V3(),x8=x1(),T8=C8(),m8=M3(),p1=f3(),I8=new Map([["core",kG.schema],["failsafe",[g8.map,h8.seq,TG.string]],["json",gG.schema],["yaml11",T8.schema],["yaml-1.1",T8.schema]]),k8={binary:y8.binary,bool:IG.boolTag,float:K3.float,floatExp:K3.floatExp,floatNaN:K3.floatNaN,floatTime:p1.floatTime,int:N3.int,intHex:N3.intHex,intOct:N3.intOct,intTime:p1.intTime,map:g8.map,merge:E0.merge,null:CG.nullTag,omap:v8.omap,pairs:x8.pairs,seq:h8.seq,set:m8.set,timestamp:p1.timestamp},hG={"tag:yaml.org,2002:binary":y8.binary,"tag:yaml.org,2002:merge":E0.merge,"tag:yaml.org,2002:omap":v8.omap,"tag:yaml.org,2002:pairs":x8.pairs,"tag:yaml.org,2002:set":m8.set,"tag:yaml.org,2002:timestamp":p1.timestamp};function yG(_,w,$){let X=I8.get(w);if(X&&!_)return $&&!X.includes(E0.merge)?X.concat(E0.merge):X.slice();let Y=X;if(!Y)if(Array.isArray(_))Y=[];else{let J=Array.from(I8.keys()).filter((D)=>D!=="yaml11").map((D)=>JSON.stringify(D)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${J} or define customTags array`)}if(Array.isArray(_))for(let J of _)Y=Y.concat(J);else if(typeof _==="function")Y=_(Y.slice());if($)Y=Y.concat(E0.merge);return Y.reduce((J,D)=>{let W=typeof D==="string"?k8[D]:D;if(!W){let G=JSON.stringify(D),Q=Object.keys(k8).map((q)=>JSON.stringify(q)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${Q}`)}if(!J.includes(W))J.push(W);return J},[])}vG.coreKnownTags=hG;vG.getTags=yG});var E3=P((pG)=>{var b3=p(),uG=pw(),lG=iw(),cG=K0(),i1=u8(),dG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class j3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:D}){this.compat=Array.isArray(_)?i1.getTags(_,"compat"):_?i1.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?i1.coreKnownTags:{},this.tags=i1.getTags(w,this.name,$),this.toStringOptions=D??null,Object.defineProperty(this,b3.MAP,{value:uG.map}),Object.defineProperty(this,b3.SCALAR,{value:cG.string}),Object.defineProperty(this,b3.SEQ,{value:lG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?dG:null}clone(){let _=Object.create(j3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}pG.Schema=j3});var l8=P((aG)=>{var nG=p(),S3=f0(),S0=A0();function rG(_,w){let $=[],X=w.directives===!0;if(w.directives!==!1&&_.directives){let G=_.directives.toString(_);if(G)$.push(G),X=!0;else if(_.directives.docStart)X=!0}if(X)$.push("---");let Y=S3.createStringifyContext(_,w),{commentString:J}=Y.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=J(_.commentBefore);$.unshift(S0.indentComment(G,""))}let D=!1,W=null;if(_.contents){if(nG.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let q=J(_.contents.commentBefore);$.push(S0.indentComment(q,""))}Y.forceBlockIndent=!!_.comment,W=_.contents.comment}let G=W?void 0:()=>D=!0,Q=S3.stringify(_.contents,Y,()=>W=null,G);if(W)Q+=S0.lineComment(Q,"",J(W));if((Q[0]==="|"||Q[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${Q}`;else $.push(Q)}else $.push(S3.stringify(_.contents,Y));if(_.directives?.docEnd)if(_.comment){let G=J(_.comment);if(G.includes(`
|
|
56
|
-
`))
|
|
23
|
+
`;let z,V;for(V=Q.length;V>0;--V){let b=Q[V-1];if(b!==`
|
|
24
|
+
`&&b!=="\t"&&b!==" ")break}let F=Q.substring(V),O=F.indexOf(`
|
|
25
|
+
`);if(O===-1)z="-";else if(Q===F||O!==F.length-1){if(z="+",G)G()}else z="";if(F){if(Q=Q.slice(0,-F.length),F[F.length-1]===`
|
|
26
|
+
`)F=F.slice(0,-1);F=F.replace(G4,`$&${B}`)}let D=!1,M,_=-1;for(M=0;M<Q.length;++M){let b=Q[M];if(b===" ")D=!0;else if(b===`
|
|
27
|
+
`)_=M;else break}let L=Q.substring(0,_<M?_+1:M);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," ")),Y)Y()}if(!U){let b=Q.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${B}`),P=!1,f=w6(X,!0);if(W!=="folded"&&J!==b0.Scalar.BLOCK_FOLDED)f.onOverflow=()=>{P=!0};let j=e0.foldFlowLines(`${L}${b}${F}`,B,e0.FOLD_BLOCK,f);if(!P)return`>${Z}
|
|
29
|
+
${B}${j}`}return Q=Q.replace(/\n+/g,`$&${B}`),`|${Z}
|
|
30
|
+
${B}${L}${Q}${F}`}function gG($,J,Q,X){let{type:Y,value:G}=$,{actualString:W,implicitKey:q,indent:H,indentStep:B,inFlow:U}=J;if(q&&G.includes(`
|
|
31
|
+
`)||U&&/[[\]{},]/.test(G))return i$(G,J);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(G))return q||U||!G.includes(`
|
|
32
|
+
`)?i$(G,J):P6($,J,Q,X);if(!q&&!U&&Y!==b0.Scalar.PLAIN&&G.includes(`
|
|
33
|
+
`))return P6($,J,Q,X);if(b6(G)){if(H==="")return J.forceBlockIndent=!0,P6($,J,Q,X);else if(q&&H===B)return i$(G,J)}let z=G.replace(/\n+/g,`$&
|
|
34
|
+
${H}`);if(W){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(z),{compat:F,tags:O}=J.doc.schema;if(O.some(V)||F?.some(V))return i$(G,J)}return q?z:e0.foldFlowLines(z,H,e0.FOLD_FLOW,w6(J,!1))}function kG($,J,Q,X){let{implicitKey:Y,inFlow:G}=J,W=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:q}=$;if(q!==b0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(W.value))q=b0.Scalar.QUOTE_DOUBLE}let H=(U)=>{switch(U){case b0.Scalar.BLOCK_FOLDED:case b0.Scalar.BLOCK_LITERAL:return Y||G?i$(W.value,J):P6(W,J,Q,X);case b0.Scalar.QUOTE_DOUBLE:return N2(W.value,J);case b0.Scalar.QUOTE_SINGLE:return Y4(W.value,J);case b0.Scalar.PLAIN:return gG(W,J,Q,X);default:return null}},B=H(q);if(B===null){let{defaultKeyType:U,defaultStringType:z}=J.options,V=Y&&U||z;if(B=H(V),B===null)throw Error(`Unsupported default string type ${V}`)}return B}mG.stringifyString=kG});var Z2=C((aG)=>{var lG=A6(),$$=d(),cG=A2(),pG=j2();function dG($,J){let Q=Object.assign({blockQuote:!0,commentString:cG.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},$.schema.toStringOptions,J),X;switch(Q.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:$,flowCollectionPadding:Q.flowCollectionPadding?" ":"",indent:"",indentStep:typeof Q.indent==="number"?" ".repeat(Q.indent):" ",inFlow:X,options:Q}}function iG($,J){if(J.tag){let Y=$.filter((G)=>G.tag===J.tag);if(Y.length>0)return Y.find((G)=>G.format===J.format)??Y[0]}let Q=void 0,X;if($$.isScalar(J)){X=J.value;let Y=$.filter((G)=>G.identify?.(X));if(Y.length>1){let G=Y.filter((W)=>W.test);if(G.length>0)Y=G}Q=Y.find((G)=>G.format===J.format)??Y.find((G)=>!G.format)}else X=J,Q=$.find((Y)=>Y.nodeClass&&X instanceof Y.nodeClass);if(!Q){let Y=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${Y} value`)}return Q}function nG($,J,{anchors:Q,doc:X}){if(!X.directives)return"";let Y=[],G=($$.isScalar($)||$$.isCollection($))&&$.anchor;if(G&&lG.anchorIsValid(G))Q.add(G),Y.push(`&${G}`);let W=$.tag??(J.default?null:J.tag);if(W)Y.push(X.directives.tagString(W));return Y.join(" ")}function rG($,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 Y=void 0,G=$$.isNode($)?$:J.doc.createNode($,{onTagObj:(H)=>Y=H});Y??(Y=iG(J.doc.schema.tags,G));let W=nG(G,Y,J);if(W.length>0)J.indentAtStart=(J.indentAtStart??0)+W.length+1;let q=typeof Y.stringify==="function"?Y.stringify(G,J,Q,X):$$.isScalar(G)?pG.stringifyString(G,J,Q,X):G.toString(J,Q,X);if(!W)return q;return $$.isScalar(G)||q[0]==="{"||q[0]==="["?`${W} ${q}`:`${W}
|
|
35
|
+
${J.indent}${q}`}aG.createStringifyContext=dG;aG.stringify=rG});var W5=C((eG)=>{var p0=d(),Y5=X0(),G5=Z2(),P2=A2();function tG({key:$,value:J},Q,X,Y){let{allNullValues:G,doc:W,indent:q,indentStep:H,options:{commentString:B,indentSeq:U,simpleKeys:z}}=Q,V=p0.isNode($)&&$.comment||null;if(z){if(V)throw Error("With simple keys, key nodes cannot have comments");if(p0.isCollection($)||!p0.isNode($)&&typeof $==="object")throw Error("With simple keys, collection cannot be used as a key value")}let F=!z&&(!$||V&&J==null&&!Q.inFlow||p0.isCollection($)||(p0.isScalar($)?$.type===Y5.Scalar.BLOCK_FOLDED||$.type===Y5.Scalar.BLOCK_LITERAL:typeof $==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!F&&(z||!G),indent:q+H});let O=!1,D=!1,M=G5.stringify($,Q,()=>O=!0,()=>D=!0);if(!F&&!Q.inFlow&&M.length>1024){if(z)throw Error("With simple keys, single line scalar must not span more than 1024 characters");F=!0}if(Q.inFlow){if(G||J==null){if(O&&X)X();return M===""?"?":F?`? ${M}`:M}}else if(G&&!z||J==null&&F){if(M=`? ${M}`,V&&!O)M+=P2.lineComment(M,Q.indent,B(V));else if(D&&Y)Y();return M}if(O)V=null;if(F){if(V)M+=P2.lineComment(M,Q.indent,B(V));M=`? ${M}
|
|
36
|
+
${q}:`}else if(M=`${M}:`,V)M+=P2.lineComment(M,Q.indent,B(V));let _,L,A;if(p0.isNode(J))_=!!J.spaceBefore,L=J.commentBefore,A=J.comment;else if(_=!1,L=null,A=null,J&&typeof J==="object")J=W.createNode(J);if(Q.implicitKey=!1,!F&&!V&&p0.isScalar(J))Q.indentAtStart=M.length+1;if(D=!1,!U&&H.length>=2&&!Q.inFlow&&!F&&p0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let Z=!1,b=G5.stringify(J,Q,()=>Z=!0,()=>D=!0),P=" ";if(V||_||L){if(P=_?`
|
|
37
|
+
`:"",L){let f=B(L);P+=`
|
|
38
|
+
${P2.indentComment(f,Q.indent)}`}if(b===""&&!Q.inFlow){if(P===`
|
|
39
|
+
`&&A)P=`
|
|
40
|
+
|
|
41
|
+
`}else P+=`
|
|
42
|
+
${Q.indent}`}else if(!F&&p0.isCollection(J)){let f=b[0],j=b.indexOf(`
|
|
43
|
+
`),S=j!==-1,x=Q.inFlow??J.flow??J.items.length===0;if(S||!x){let i=!1;if(S&&(f==="&"||f==="!")){let g=b.indexOf(" ");if(f==="&"&&g!==-1&&g<j&&b[g+1]==="!")g=b.indexOf(" ",g+1);if(g===-1||j<g)i=!0}if(!i)P=`
|
|
44
|
+
${Q.indent}`}}else if(b===""||b[0]===`
|
|
45
|
+
`)P="";if(M+=P+b,Q.inFlow){if(Z&&X)X()}else if(A&&!Z)M+=P2.lineComment(M,Q.indent,B(A));else if(D&&Y)Y();return M}eG.stringifyPair=tG});var W4=C((XW)=>{var q5=W6("process");function JW($,...J){if($==="debug")console.log(...J)}function QW($,J){if($==="debug"||$==="warn")if(typeof q5.emitWarning==="function")q5.emitWarning(J);else console.warn(J)}XW.debug=JW;XW.warn=QW});var f6=C((qW)=>{var C6=d(),H5=X0(),E6="<<",S6={identify:($)=>$===E6||typeof $==="symbol"&&$.description===E6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new H5.Scalar(Symbol(E6)),{addToJSMap:B5}),stringify:()=>E6},WW=($,J)=>(S6.identify(J)||C6.isScalar(J)&&(!J.type||J.type===H5.Scalar.PLAIN)&&S6.identify(J.value))&&$?.doc.schema.tags.some((Q)=>Q.tag===S6.tag&&Q.default);function B5($,J,Q){let X=U5($,Q);if(C6.isSeq(X))for(let Y of X.items)q4($,J,Y);else if(Array.isArray(X))for(let Y of X)q4($,J,Y);else q4($,J,X)}function q4($,J,Q){let X=U5($,Q);if(!C6.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,$,Map);for(let[G,W]of Y)if(J instanceof Map){if(!J.has(G))J.set(G,W)}else if(J instanceof Set)J.add(G);else if(!Object.prototype.hasOwnProperty.call(J,G))Object.defineProperty(J,G,{value:W,writable:!0,enumerable:!0,configurable:!0});return J}function U5($,J){return $&&C6.isAlias(J)?J.resolve($.doc,$):J}qW.addMergeToJSMap=B5;qW.isMergeKey=WW;qW.merge=S6});var B4=C((MW)=>{var VW=W4(),V5=f6(),zW=Z2(),z5=d(),H4=t0();function DW($,J,{key:Q,value:X}){if(z5.isNode(Q)&&Q.addToJSMap)Q.addToJSMap($,J,X);else if(V5.isMergeKey($,Q))V5.addMergeToJSMap($,J,X);else{let Y=H4.toJS(Q,"",$);if(J instanceof Map)J.set(Y,H4.toJS(X,Y,$));else if(J instanceof Set)J.add(Y);else{let G=OW(Q,Y,$),W=H4.toJS(X,G,$);if(G in J)Object.defineProperty(J,G,{value:W,writable:!0,enumerable:!0,configurable:!0});else J[G]=W}}return J}function OW($,J,Q){if(J===null)return"";if(typeof J!=="object")return String(J);if(z5.isNode($)&&Q?.doc){let X=zW.createStringifyContext(Q.doc,{});X.anchors=new Set;for(let G of Q.anchors.keys())X.anchors.add(G.anchor);X.inFlow=!0,X.inStringifyKey=!0;let Y=$.toString(X);if(!Q.mapKeyWarned){let G=JSON.stringify(Y);if(G.length>40)G=G.substring(0,36)+'..."';VW.warn(Q.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${G}. Set mapAsMap: true to use object keys.`),Q.mapKeyWarned=!0}return Y}return JSON.stringify(J)}MW.addPairToJSMap=DW});var J$=C((RW)=>{var D5=R2(),KW=W5(),_W=B4(),I6=d();function LW($,J,Q){let X=D5.createNode($,void 0,Q),Y=D5.createNode(J,void 0,Q);return new T6(X,Y)}class T6{constructor($,J=null){Object.defineProperty(this,I6.NODE_TYPE,{value:I6.PAIR}),this.key=$,this.value=J}clone($){let{key:J,value:Q}=this;if(I6.isNode(J))J=J.clone($);if(I6.isNode(Q))Q=Q.clone($);return new T6(J,Q)}toJSON($,J){let Q=J?.mapAsMap?new Map:{};return _W.addPairToJSMap(J,Q,this)}toString($,J,Q){return $?.doc?KW.stringifyPair(this,$,J,Q):JSON.stringify(this)}}RW.Pair=T6;RW.createPair=LW});var U4=C((wW)=>{var F$=d(),O5=Z2(),v6=A2();function jW($,J,Q){return(J.inFlow??$.flow?PW:ZW)($,J,Q)}function ZW({comment:$,items:J},Q,{blockItemPrefix:X,flowChars:Y,itemIndent:G,onChompKeep:W,onComment:q}){let{indent:H,options:{commentString:B}}=Q,U=Object.assign({},Q,{indent:G,type:null}),z=!1,V=[];for(let O=0;O<J.length;++O){let D=J[O],M=null;if(F$.isNode(D)){if(!z&&D.spaceBefore)V.push("");if(x6(Q,V,D.commentBefore,z),D.comment)M=D.comment}else if(F$.isPair(D)){let L=F$.isNode(D.key)?D.key:null;if(L){if(!z&&L.spaceBefore)V.push("");x6(Q,V,L.commentBefore,z)}}z=!1;let _=O5.stringify(D,U,()=>M=null,()=>z=!0);if(M)_+=v6.lineComment(_,G,B(M));if(z&&M)z=!1;V.push(X+_)}let F;if(V.length===0)F=Y.start+Y.end;else{F=V[0];for(let O=1;O<V.length;++O){let D=V[O];F+=D?`
|
|
46
|
+
${H}${D}`:`
|
|
47
|
+
`}}if($){if(F+=`
|
|
48
|
+
`+v6.indentComment(B($),H),q)q()}else if(z&&W)W();return F}function PW({items:$},J,{flowChars:Q,itemIndent:X}){let{indent:Y,indentStep:G,flowCollectionPadding:W,options:{commentString:q}}=J;X+=G;let H=Object.assign({},J,{indent:X,inFlow:!0,type:null}),B=!1,U=0,z=[];for(let O=0;O<$.length;++O){let D=$[O],M=null;if(F$.isNode(D)){if(D.spaceBefore)z.push("");if(x6(J,z,D.commentBefore,!1),D.comment)M=D.comment}else if(F$.isPair(D)){let L=F$.isNode(D.key)?D.key:null;if(L){if(L.spaceBefore)z.push("");if(x6(J,z,L.commentBefore,!1),L.comment)B=!0}let A=F$.isNode(D.value)?D.value:null;if(A){if(A.comment)M=A.comment;if(A.commentBefore)B=!0}else if(D.value==null&&L?.comment)M=L.comment}if(M)B=!0;let _=O5.stringify(D,H,()=>M=null);if(B||(B=z.length>U||_.includes(`
|
|
49
|
+
`)),O<$.length-1)_+=",";else if(J.options.trailingComma){if(J.options.lineWidth>0)B||(B=z.reduce((L,A)=>L+A.length+2,2)+(_.length+2)>J.options.lineWidth);if(B)_+=","}if(M)_+=v6.lineComment(_,X,q(M));z.push(_),U=z.length}let{start:V,end:F}=Q;if(z.length===0)return V+F;else{if(!B){let O=z.reduce((D,M)=>D+M.length+2,2);B=J.options.lineWidth>0&&O>J.options.lineWidth}if(B){let O=V;for(let D of z)O+=D?`
|
|
50
|
+
${G}${Y}${D}`:`
|
|
51
|
+
`;return`${O}
|
|
52
|
+
${Y}${F}`}else return`${V}${W}${z.join(" ")}${W}${F}`}}function x6({indent:$,options:{commentString:J}},Q,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let G=v6.indentComment(J(X),$);Q.push(G.trimStart())}}wW.stringifyCollection=jW});var X$=C((IW)=>{var EW=U4(),SW=B4(),CW=Z6(),Q$=d(),h6=J$(),fW=X0();function w2($,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 M5 extends CW.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(Q$.MAP,$);this.items=[]}static from($,J,Q){let{keepUndefined:X,replacer:Y}=Q,G=new this($),W=(q,H)=>{if(typeof Y==="function")H=Y.call(J,q,H);else if(Array.isArray(Y)&&!Y.includes(q))return;if(H!==void 0||X)G.items.push(h6.createPair(q,H,Q))};if(J instanceof Map)for(let[q,H]of J)W(q,H);else if(J&&typeof J==="object")for(let q of Object.keys(J))W(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 h6.Pair($,$?.value);else Q=new h6.Pair($.key,$.value);let X=w2(this.items,Q.key),Y=this.schema?.sortMapEntries;if(X){if(!J)throw Error(`Key ${Q.key} already set`);if(Q$.isScalar(X.value)&&fW.isScalarValue(Q.value))X.value.value=Q.value;else X.value=Q.value}else if(Y){let G=this.items.findIndex((W)=>Y(Q,W)<0);if(G===-1)this.items.push(Q);else this.items.splice(G,0,Q)}else this.items.push(Q)}delete($){let J=w2(this.items,$);if(!J)return!1;return this.items.splice(this.items.indexOf(J),1).length>0}get($,J){let X=w2(this.items,$)?.value;return(!J&&Q$.isScalar(X)?X.value:X)??void 0}has($){return!!w2(this.items,$)}set($,J){this.add(new h6.Pair($,J),!0)}toJSON($,J,Q){let X=Q?new Q:J?.mapAsMap?new Map:{};if(J?.onCreate)J.onCreate(X);for(let Y of this.items)SW.addPairToJSMap(J,X,Y);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 EW.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:Q,onComment:J})}}IW.YAMLMap=M5;IW.findPair=w2});var n$=C((yW)=>{var xW=d(),F5=X$(),hW={collection:"map",default:!0,nodeClass:F5.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,J){if(!xW.isMap($))J("Expected a mapping for this tag");return $},createNode:($,J,Q)=>F5.YAMLMap.from($,J,Q)};yW.map=hW});var Y$=C((pW)=>{var kW=R2(),mW=U4(),uW=Z6(),g6=d(),lW=X0(),cW=t0();class K5 extends uW.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(g6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let J=y6($);if(typeof J!=="number")return!1;return this.items.splice(J,1).length>0}get($,J){let Q=y6($);if(typeof Q!=="number")return;let X=this.items[Q];return!J&&g6.isScalar(X)?X.value:X}has($){let J=y6($);return typeof J==="number"&&J<this.items.length}set($,J){let Q=y6($);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${$}.`);let X=this.items[Q];if(g6.isScalar(X)&&lW.isScalarValue(J))X.value=J;else this.items[Q]=J}toJSON($,J){let Q=[];if(J?.onCreate)J.onCreate(Q);let X=0;for(let Y of this.items)Q.push(cW.toJS(Y,String(X++),J));return Q}toString($,J,Q){if(!$)return JSON.stringify(this);return mW.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:Q,onComment:J})}static from($,J,Q){let{replacer:X}=Q,Y=new this($);if(J&&Symbol.iterator in Object(J)){let G=0;for(let W of J){if(typeof X==="function"){let q=J instanceof Set?W:String(G++);W=X.call(J,q,W)}Y.items.push(kW.createNode(W,void 0,Q))}}return Y}}function y6($){let J=g6.isScalar($)?$.value:$;if(J&&typeof J==="string")J=Number(J);return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:null}pW.YAMLSeq=K5});var r$=C((rW)=>{var iW=d(),_5=Y$(),nW={collection:"seq",default:!0,nodeClass:_5.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,J){if(!iW.isSeq($))J("Expected a sequence for this tag");return $},createNode:($,J,Q)=>_5.YAMLSeq.from($,J,Q)};rW.seq=nW});var b2=C((tW)=>{var sW=j2(),oW={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,J,Q,X){return J=Object.assign({actualString:!0},J),sW.stringifyString($,J,Q,X)}};tW.string=oW});var k6=C(($q)=>{var L5=X0(),R5={identify:($)=>$==null,createNode:()=>new L5.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new L5.Scalar(null),stringify:({source:$},J)=>typeof $==="string"&&R5.test.test($)?$:J.options.nullStr};$q.nullTag=R5});var V4=C((Xq)=>{var Qq=X0(),A5={identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:($)=>new Qq.Scalar($[0]==="t"||$[0]==="T"),stringify({source:$,value:J},Q){if($&&A5.test.test($)){let X=$[0]==="t"||$[0]==="T";if(J===X)return $}return J?Q.options.trueStr:Q.options.falseStr}};Xq.boolTag=A5});var a$=C((Wq)=>{function Gq({format:$,minFractionDigits:J,tag:Q,value:X}){if(typeof X==="bigint")return String(X);let Y=typeof X==="number"?X:Number(X);if(!isFinite(Y))return isNaN(Y)?".nan":Y<0?"-.inf":".inf";let G=Object.is(X,-0)?"-0":JSON.stringify(X);if(!$&&J&&(!Q||Q==="tag:yaml.org,2002:float")&&/^-?\d/.test(G)&&!G.includes("e")){let W=G.indexOf(".");if(W<0)W=G.length,G+=".";let q=J-(G.length-W-1);while(q-- >0)G+="0"}return G}Wq.stringifyNumber=Gq});var D4=C((zq)=>{var Hq=X0(),z4=a$(),Bq={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:z4.stringifyNumber},Uq={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():z4.stringifyNumber($)}},Vq={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let J=new Hq.Scalar(parseFloat($)),Q=$.indexOf(".");if(Q!==-1&&$[$.length-1]==="0")J.minFractionDigits=$.length-Q-1;return J},stringify:z4.stringifyNumber};zq.float=Vq;zq.floatExp=Uq;zq.floatNaN=Bq});var M4=C((Lq)=>{var N5=a$(),m6=($)=>typeof $==="bigint"||Number.isInteger($),O4=($,J,Q,{intAsBigInt:X})=>X?BigInt($):parseInt($.substring(J),Q);function j5($,J,Q){let{value:X}=$;if(m6(X)&&X>=0)return Q+X.toString(J);return N5.stringifyNumber($)}var Fq={identify:($)=>m6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,J,Q)=>O4($,2,8,Q),stringify:($)=>j5($,8,"0o")},Kq={identify:m6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,J,Q)=>O4($,0,10,Q),stringify:N5.stringifyNumber},_q={identify:($)=>m6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,J,Q)=>O4($,2,16,Q),stringify:($)=>j5($,16,"0x")};Lq.int=Kq;Lq.intHex=_q;Lq.intOct=Fq});var Z5=C((Sq)=>{var jq=n$(),Zq=k6(),Pq=r$(),wq=b2(),bq=V4(),F4=D4(),K4=M4(),Eq=[jq.map,Pq.seq,wq.string,Zq.nullTag,bq.boolTag,K4.intOct,K4.int,K4.intHex,F4.floatNaN,F4.floatExp,F4.float];Sq.schema=Eq});var w5=C((yq)=>{var fq=X0(),Iq=n$(),Tq=r$();function P5($){return typeof $==="bigint"||Number.isInteger($)}var u6=({value:$})=>JSON.stringify($),vq=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:u6},{identify:($)=>$==null,createNode:()=>new fq.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:u6},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:u6},{identify:P5,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,J,{intAsBigInt:Q})=>Q?BigInt($):parseInt($,10),stringify:({value:$})=>P5($)?$.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:u6}],xq={default:!0,tag:"",test:/^/,resolve($,J){return J(`Unresolved plain scalar ${JSON.stringify($)}`),$}},hq=[Iq.map,Tq.seq].concat(vq,xq);yq.schema=hq});var L4=C((uq)=>{var E2=W6("buffer"),_4=X0(),kq=j2(),mq={identify:($)=>$ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve($,J){if(typeof E2.Buffer==="function")return E2.Buffer.from($,"base64");else if(typeof atob==="function"){let Q=atob($.replace(/[\n\r]/g,"")),X=new Uint8Array(Q.length);for(let Y=0;Y<Q.length;++Y)X[Y]=Q.charCodeAt(Y);return X}else return J("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:J,value:Q},X,Y,G){if(!Q)return"";let W=Q,q;if(typeof E2.Buffer==="function")q=W instanceof E2.Buffer?W.toString("base64"):E2.Buffer.from(W.buffer).toString("base64");else if(typeof btoa==="function"){let H="";for(let B=0;B<W.length;++B)H+=String.fromCharCode(W[B]);q=btoa(H)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(J??(J=_4.Scalar.BLOCK_LITERAL),J!==_4.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===_4.Scalar.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return kq.stringifyString({comment:$,type:J,value:q},X,Y,G)}};uq.binary=mq});var c6=C((iq)=>{var l6=d(),R4=J$(),cq=X0(),pq=Y$();function b5($,J){if(l6.isSeq($))for(let Q=0;Q<$.items.length;++Q){let X=$.items[Q];if(l6.isPair(X))continue;else if(l6.isMap(X)){if(X.items.length>1)J("Each pair must have its own sequence indicator");let Y=X.items[0]||new R4.Pair(new cq.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
|
|
54
|
+
${Y.key.commentBefore}`:X.commentBefore;if(X.comment){let G=Y.value??Y.key;G.comment=G.comment?`${X.comment}
|
|
55
|
+
${G.comment}`:X.comment}X=Y}$.items[Q]=l6.isPair(X)?X:new R4.Pair(X)}else J("Expected a sequence for this tag");return $}function E5($,J,Q){let{replacer:X}=Q,Y=new pq.YAMLSeq($);Y.tag="tag:yaml.org,2002:pairs";let G=0;if(J&&Symbol.iterator in Object(J))for(let W of J){if(typeof X==="function")W=X.call(J,String(G++),W);let q,H;if(Array.isArray(W))if(W.length===2)q=W[0],H=W[1];else throw TypeError(`Expected [key, value] tuple: ${W}`);else if(W&&W instanceof Object){let B=Object.keys(W);if(B.length===1)q=B[0],H=W[q];else throw TypeError(`Expected tuple with one key, not ${B.length} keys`)}else q=W;Y.items.push(R4.createPair(q,H,Q))}return Y}var dq={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:b5,createNode:E5};iq.createPairs=E5;iq.pairs=dq;iq.resolvePairs=b5});var N4=C((tq)=>{var S5=d(),A4=t0(),S2=X$(),sq=Y$(),C5=c6();class K$ extends sq.YAMLSeq{constructor(){super();this.add=S2.YAMLMap.prototype.add.bind(this),this.delete=S2.YAMLMap.prototype.delete.bind(this),this.get=S2.YAMLMap.prototype.get.bind(this),this.has=S2.YAMLMap.prototype.has.bind(this),this.set=S2.YAMLMap.prototype.set.bind(this),this.tag=K$.tag}toJSON($,J){if(!J)return super.toJSON($);let Q=new Map;if(J?.onCreate)J.onCreate(Q);for(let X of this.items){let Y,G;if(S5.isPair(X))Y=A4.toJS(X.key,"",J),G=A4.toJS(X.value,Y,J);else Y=A4.toJS(X,"",J);if(Q.has(Y))throw Error("Ordered maps must not include duplicate keys");Q.set(Y,G)}return Q}static from($,J,Q){let X=C5.createPairs($,J,Q),Y=new this;return Y.items=X.items,Y}}K$.tag="tag:yaml.org,2002:omap";var oq={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:K$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=C5.resolvePairs($,J),X=[];for(let{key:Y}of Q.items)if(S5.isScalar(Y))if(X.includes(Y.value))J(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new K$,Q)},createNode:($,J,Q)=>K$.from($,J,Q)};tq.YAMLOMap=K$;tq.omap=oq});var x5=C((JH)=>{var f5=X0();function I5({value:$,source:J},Q){if(J&&($?T5:v5).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var T5={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new f5.Scalar(!0),stringify:I5},v5={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new f5.Scalar(!1),stringify:I5};JH.falseTag=v5;JH.trueTag=T5});var h5=C((HH)=>{var YH=X0(),j4=a$(),GH={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:j4.stringifyNumber},WH={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():j4.stringifyNumber($)}},qH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new YH.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:j4.stringifyNumber};HH.float=qH;HH.floatExp=WH;HH.floatNaN=GH});var g5=C((FH)=>{var y5=a$(),C2=($)=>typeof $==="bigint"||Number.isInteger($);function p6($,J,Q,{intAsBigInt:X}){let Y=$[0];if(Y==="-"||Y==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let W=BigInt($);return Y==="-"?BigInt(-1)*W:W}let G=parseInt($,Q);return Y==="-"?-1*G:G}function Z4($,J,Q){let{value:X}=$;if(C2(X)){let Y=X.toString(J);return X<0?"-"+Q+Y.substr(1):Q+Y}return y5.stringifyNumber($)}var zH={identify:C2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>p6($,2,2,Q),stringify:($)=>Z4($,2,"0b")},DH={identify:C2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>p6($,1,8,Q),stringify:($)=>Z4($,8,"0")},OH={identify:C2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>p6($,0,10,Q),stringify:y5.stringifyNumber},MH={identify:C2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>p6($,2,16,Q),stringify:($)=>Z4($,16,"0x")};FH.int=OH;FH.intBin=zH;FH.intHex=MH;FH.intOct=DH});var P4=C((NH)=>{var n6=d(),d6=J$(),i6=X$();class _$ extends i6.YAMLMap{constructor($){super($);this.tag=_$.tag}add($){let J;if(n6.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new d6.Pair($.key,null);else J=new d6.Pair($,null);if(!i6.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=i6.findPair(this.items,$);return!J&&n6.isPair(Q)?n6.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=i6.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new d6.Pair($))}toJSON($,J){return super.toJSON($,J,Set)}toString($,J,Q){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),J,Q);else throw Error("Set items must all have null values")}static from($,J,Q){let{replacer:X}=Q,Y=new this($);if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,G,G);Y.items.push(d6.createPair(G,null,Q))}return Y}}_$.tag="tag:yaml.org,2002:set";var AH={collection:"map",identify:($)=>$ instanceof Set,nodeClass:_$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>_$.from($,J,Q),resolve($,J){if(n6.isMap($))if($.hasAllNullValues(!0))return Object.assign(new _$,$);else J("Set items must all have null values");else J("Expected a mapping for this tag");return $}};NH.YAMLSet=_$;NH.set=AH});var b4=C((EH)=>{var PH=a$();function w4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,Y=(W)=>J?BigInt(W):Number(W),G=X.replace(/_/g,"").split(":").reduce((W,q)=>W*Y(60)+Y(q),Y(0));return Q==="-"?Y(-1)*G:G}function k5($){let{value:J}=$,Q=(W)=>W;if(typeof J==="bigint")Q=(W)=>BigInt(W);else if(isNaN(J)||!isFinite(J))return PH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let Y=Q(60),G=[J%Y];if(J<60)G.unshift(0);else if(J=(J-G[0])/Y,G.unshift(J%Y),J>=60)J=(J-G[0])/Y,G.unshift(J);return X+G.map((W)=>String(W).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var wH={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})=>w4($,Q),stringify:k5},bH={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:($)=>w4($,!1),stringify:k5},m5={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(m5.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,Y,G,W,q]=J.map(Number),H=J[7]?Number((J[7]+"00").substr(1,3)):0,B=Date.UTC(Q,X-1,Y,G||0,W||0,q||0,H),U=J[8];if(U&&U!=="Z"){let z=w4(U,!1);if(Math.abs(z)<30)z*=60;B-=60000*z}return new Date(B)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};EH.floatTime=bH;EH.intTime=wH;EH.timestamp=m5});var l5=C((lH)=>{var IH=n$(),TH=k6(),vH=r$(),xH=b2(),hH=L4(),u5=x5(),E4=h5(),r6=g5(),yH=f6(),gH=N4(),kH=c6(),mH=P4(),S4=b4(),uH=[IH.map,vH.seq,xH.string,TH.nullTag,u5.trueTag,u5.falseTag,r6.intBin,r6.intOct,r6.int,r6.intHex,E4.floatNaN,E4.floatExp,E4.float,hH.binary,yH.merge,gH.omap,kH.pairs,mH.set,S4.intTime,S4.floatTime,S4.timestamp];lH.schema=uH});var t5=C((oH)=>{var i5=n$(),pH=k6(),n5=r$(),dH=b2(),iH=V4(),C4=D4(),f4=M4(),nH=Z5(),rH=w5(),r5=L4(),f2=f6(),a5=N4(),s5=c6(),c5=l5(),o5=P4(),a6=b4(),p5=new Map([["core",nH.schema],["failsafe",[i5.map,n5.seq,dH.string]],["json",rH.schema],["yaml11",c5.schema],["yaml-1.1",c5.schema]]),d5={binary:r5.binary,bool:iH.boolTag,float:C4.float,floatExp:C4.floatExp,floatNaN:C4.floatNaN,floatTime:a6.floatTime,int:f4.int,intHex:f4.intHex,intOct:f4.intOct,intTime:a6.intTime,map:i5.map,merge:f2.merge,null:pH.nullTag,omap:a5.omap,pairs:s5.pairs,seq:n5.seq,set:o5.set,timestamp:a6.timestamp},aH={"tag:yaml.org,2002:binary":r5.binary,"tag:yaml.org,2002:merge":f2.merge,"tag:yaml.org,2002:omap":a5.omap,"tag:yaml.org,2002:pairs":s5.pairs,"tag:yaml.org,2002:set":o5.set,"tag:yaml.org,2002:timestamp":a6.timestamp};function sH($,J,Q){let X=p5.get(J);if(X&&!$)return Q&&!X.includes(f2.merge)?X.concat(f2.merge):X.slice();let Y=X;if(!Y)if(Array.isArray($))Y=[];else{let G=Array.from(p5.keys()).filter((W)=>W!=="yaml11").map((W)=>JSON.stringify(W)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${G} or define customTags array`)}if(Array.isArray($))for(let G of $)Y=Y.concat(G);else if(typeof $==="function")Y=$(Y.slice());if(Q)Y=Y.concat(f2.merge);return Y.reduce((G,W)=>{let q=typeof W==="string"?d5[W]:W;if(!q){let H=JSON.stringify(W),B=Object.keys(d5).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},[])}oH.coreKnownTags=aH;oH.getTags=sH});var v4=C((YB)=>{var I4=d(),$B=n$(),JB=r$(),QB=b2(),s6=t5(),XB=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class T4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:Y,sortMapEntries:G,toStringDefaults:W}){this.compat=Array.isArray($)?s6.getTags($,"compat"):$?s6.getTags(null,$):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?s6.coreKnownTags:{},this.tags=s6.getTags(J,this.name,Q),this.toStringOptions=W??null,Object.defineProperty(this,I4.MAP,{value:$B.map}),Object.defineProperty(this,I4.SCALAR,{value:QB.string}),Object.defineProperty(this,I4.SEQ,{value:JB.seq}),this.sortMapEntries=typeof G==="function"?G:G===!0?XB:null}clone(){let $=Object.create(T4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}YB.Schema=T4});var e5=C((HB)=>{var WB=d(),x4=Z2(),I2=A2();function qB($,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 Y=x4.createStringifyContext($,J),{commentString:G}=Y.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let H=G($.commentBefore);Q.unshift(I2.indentComment(H,""))}let W=!1,q=null;if($.contents){if(WB.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let U=G($.contents.commentBefore);Q.push(I2.indentComment(U,""))}Y.forceBlockIndent=!!$.comment,q=$.contents.comment}let H=q?void 0:()=>W=!0,B=x4.stringify($.contents,Y,()=>q=null,H);if(q)B+=I2.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(x4.stringify($.contents,Y));if($.directives?.docEnd)if($.comment){let H=G($.comment);if(H.includes(`
|
|
56
|
+
`))Q.push("..."),Q.push(I2.indentComment(H,""));else Q.push(`... ${H}`)}else Q.push("...");else{let H=$.comment;if(H&&W)H=H.replace(/^\n+/,"");if(H){if((!W||q)&&Q[Q.length-1]!=="")Q.push("");Q.push(I2.indentComment(G(H),""))}}return Q.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
59
|
-
`;
|
|
60
|
-
|
|
61
|
-
${
|
|
62
|
-
${
|
|
63
|
-
`}};
|
|
64
|
-
`))return!0;if(
|
|
65
|
-
`+
|
|
66
|
-
`+
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`.repeat(Math.max(1,
|
|
72
|
-
`;for(let U
|
|
73
|
-
`;else if(
|
|
74
|
-
`;else if(!
|
|
75
|
-
`)
|
|
76
|
-
|
|
77
|
-
`;
|
|
78
|
-
`,
|
|
79
|
-
`)
|
|
80
|
-
`;else
|
|
81
|
-
`;else
|
|
82
|
-
`+D
|
|
83
|
-
`)
|
|
84
|
-
`;break;default:
|
|
85
|
-
`}let
|
|
86
|
-
`)
|
|
87
|
-
`;else
|
|
58
|
+
`}HB.stringifyDocument=qB});var T2=C((KB)=>{var UB=L2(),s$=Z6(),_0=d(),VB=J$(),zB=t0(),DB=v4(),OB=e5(),h4=A6(),MB=J4(),FB=R2(),y4=$4();class g4{constructor($,J,Q){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,_0.NODE_TYPE,{value:_0.DOC});let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J,J=void 0;let Y=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=Y;let{version:G}=Y;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)G=this.directives.yaml.version}else this.directives=new y4.Directives({version:G});this.setSchema(G,Q),this.contents=$===void 0?null:this.createNode($,X,Q)}clone(){let $=Object.create(g4.prototype,{[_0.NODE_TYPE]:{value:_0.DOC}});if($.commentBefore=this.commentBefore,$.comment=this.comment,$.errors=this.errors.slice(),$.warnings=this.warnings.slice(),$.options=Object.assign({},this.options),this.directives)$.directives=this.directives.clone();if($.schema=this.schema.clone(),$.contents=_0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(o$(this.contents))this.contents.add($)}addIn($,J){if(o$(this.contents))this.contents.addIn($,J)}createAlias($,J){if(!$.anchor){let Q=h4.anchorNames(this);$.anchor=!J||Q.has(J)?h4.findNewAnchor(J||"a",Q):J}return new UB.Alias($.anchor)}createNode($,J,Q){let X=void 0;if(typeof J==="function")$=J.call({"":$},"",$),X=J;else if(Array.isArray(J)){let D=(_)=>typeof _==="number"||_ instanceof String||_ instanceof Number,M=J.filter(D).map(String);if(M.length>0)J=J.concat(M);X=J}else if(Q===void 0&&J)Q=J,J=void 0;let{aliasDuplicateObjects:Y,anchorPrefix:G,flow:W,keepUndefined:q,onTagObj:H,tag:B}=Q??{},{onAnchor:U,setAnchors:z,sourceObjects:V}=h4.createNodeAnchors(this,G||"a"),F={aliasDuplicateObjects:Y??!0,keepUndefined:q??!1,onAnchor:U,onTagObj:H,replacer:X,schema:this.schema,sourceObjects:V},O=FB.createNode($,B,F);if(W&&_0.isCollection(O))O.flow=!0;return z(),O}createPair($,J,Q={}){let X=this.createNode($,null,Q),Y=this.createNode(J,null,Q);return new VB.Pair(X,Y)}delete($){return o$(this.contents)?this.contents.delete($):!1}deleteIn($){if(s$.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return o$(this.contents)?this.contents.deleteIn($):!1}get($,J){return _0.isCollection(this.contents)?this.contents.get($,J):void 0}getIn($,J){if(s$.isEmptyPath($))return!J&&_0.isScalar(this.contents)?this.contents.value:this.contents;return _0.isCollection(this.contents)?this.contents.getIn($,J):void 0}has($){return _0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(s$.isEmptyPath($))return this.contents!==void 0;return _0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,J){if(this.contents==null)this.contents=s$.collectionFromPath(this.schema,[$],J);else if(o$(this.contents))this.contents.set($,J)}setIn($,J){if(s$.isEmptyPath($))this.contents=J;else if(this.contents==null)this.contents=s$.collectionFromPath(this.schema,Array.from($),J);else if(o$(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 y4.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 y4.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 DB.Schema(Object.assign(Q,J));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:J,mapAsMap:Q,maxAliasCount:X,onAnchor:Y,reviver:G}={}){let W={anchors:new Map,doc:this,keep:!$,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},q=zB.toJS(this.contents,J??"",W);if(typeof Y==="function")for(let{count:H,res:B}of W.anchors.values())Y(B,H);return typeof G==="function"?MB.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 OB.stringifyDocument(this,$)}}function o$($){if(_0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}KB.Document=g4});var v2=C((RB)=>{class o6 extends Error{constructor($,J,Q,X){super();this.name=$,this.code=Q,this.message=X,this.pos=J}}class $J extends o6{constructor($,J,Q){super("YAMLParseError",$,J,Q)}}class JJ extends o6{constructor($,J,Q){super("YAMLWarning",$,J,Q)}}var LB=($,J)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((q)=>J.linePos(q));let{line:X,col:Y}=Q.linePos[0];Q.message+=` at line ${X}, column ${Y}`;let G=Y-1,W=$.substring(J.lineStarts[X-1],J.lineStarts[X]).replace(/[\n\r]+$/,"");if(G>=60&&W.length>80){let q=Math.min(G-39,W.length-79);W="\u2026"+W.substring(q),G-=q-1}if(W.length>80)W=W.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(W.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
|
+
`;W=q+W}if(/[^ ]/.test(W)){let q=1,H=Q.linePos[1];if(H?.line===X&&H.col>Y)q=Math.max(1,Math.min(H.col-Y,80-G));let B=" ".repeat(G)+"^".repeat(q);Q.message+=`:
|
|
60
|
+
|
|
61
|
+
${W}
|
|
62
|
+
${B}
|
|
63
|
+
`}};RB.YAMLError=o6;RB.YAMLParseError=$J;RB.YAMLWarning=JJ;RB.prettifyError=LB});var x2=C((wB)=>{function PB($,{flow:J,indicator:Q,next:X,offset:Y,onError:G,parentIndent:W,startOnNewline:q}){let H=!1,B=q,U=q,z="",V="",F=!1,O=!1,D=null,M=null,_=null,L=null,A=null,Z=null,b=null;for(let j of $){if(O){if(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma")G(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");O=!1}if(D){if(B&&j.type!=="comment"&&j.type!=="newline")G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");D=null}switch(j.type){case"space":if(!J&&(Q!=="doc-start"||X?.type!=="flow-collection")&&j.source.includes("\t"))D=j;U=!0;break;case"comment":{if(!U)G(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let S=j.source.substring(1)||" ";if(!z)z=S;else z+=V+S;V="",B=!1;break}case"newline":if(B){if(z)z+=j.source;else if(!Z||Q!=="seq-item-ind")H=!0}else V+=j.source;if(B=!0,F=!0,M||_)L=j;U=!0;break;case"anchor":if(M)G(j,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(j.source.endsWith(":"))G(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);M=j,b??(b=j.offset),B=!1,U=!1,O=!0;break;case"tag":{if(_)G(j,"MULTIPLE_TAGS","A node can have at most one tag");_=j,b??(b=j.offset),B=!1,U=!1,O=!0;break}case Q:if(M||_)G(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`);if(Z)G(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${J??"collection"}`);Z=j,B=Q==="seq-item-ind"||Q==="explicit-key-ind",U=!1;break;case"comma":if(J){if(A)G(j,"UNEXPECTED_TOKEN",`Unexpected , in ${J}`);A=j,B=!1,U=!1;break}default:G(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),B=!1,U=!1}}let P=$[$.length-1],f=P?P.offset+P.source.length:Y;if(O&&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<=W||X?.type==="block-map"||X?.type==="block-seq"))G(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:A,found:Z,spaceBefore:H,comment:z,hasNewline:F,anchor:M,tag:_,newlineAfterProp:L,end:f,start:b??f}}wB.resolveProps=PB});var t6=C((EB)=>{function k4($){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(k4(J.key)||k4(J.value))return!0}return!1;default:return!0}}EB.containsNewline=k4});var m4=C((IB)=>{var CB=t6();function fB($,J,Q){if(J?.type==="flow-collection"){let X=J.end[0];if(X.indent===$&&(X.source==="]"||X.source==="}")&&CB.containsNewline(J))Q(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}IB.flowIndentCheck=fB});var u4=C((xB)=>{var QJ=d();function vB($,J,Q){let{uniqueKeys:X}=$.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(G,W)=>G===W||QJ.isScalar(G)&&QJ.isScalar(W)&&G.value===W.value;return J.some((G)=>Y(G.key,Q))}xB.mapIncludes=vB});var qJ=C((uB)=>{var XJ=J$(),yB=X$(),YJ=x2(),gB=t6(),GJ=m4(),kB=u4(),WJ="All mapping items must start at the same column";function mB({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let q=new(G?.nodeClass??yB.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:F,value:O}=U,D=YJ.resolveProps(z,{indicator:"explicit-key-ind",next:V??F?.[0],offset:H,onError:Y,parentIndent:X.indent,startOnNewline:!0}),M=!D.found;if(M){if(V){if(V.type==="block-seq")Y(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)Y(H,"BAD_INDENT",WJ)}if(!D.anchor&&!D.tag&&!F){if(B=D.end,D.comment)if(q.comment)q.comment+=`
|
|
65
|
+
`+D.comment;else q.comment=D.comment;continue}if(D.newlineAfterProp||gB.containsNewline(V))Y(V??z[z.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(D.found?.indent!==X.indent)Y(H,"BAD_INDENT",WJ);Q.atKey=!0;let _=D.end,L=V?$(Q,V,D,Y):J(Q,_,z,null,D,Y);if(Q.schema.compat)GJ.flowIndentCheck(X.indent,V,Y);if(Q.atKey=!1,kB.mapIncludes(Q,q.items,L))Y(_,"DUPLICATE_KEY","Map keys must be unique");let A=YJ.resolveProps(F??[],{indicator:"map-value-ind",next:O,offset:L.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!V||V.type==="block-scalar"});if(H=A.end,A.found){if(M){if(O?.type==="block-map"&&!A.hasNewline)Y(H,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&D.start<A.found.offset-1024)Y(L.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let Z=O?$(Q,O,A,Y):J(Q,H,F,null,A,Y);if(Q.schema.compat)GJ.flowIndentCheck(X.indent,O,Y);H=Z.range[2];let b=new XJ.Pair(L,Z);if(Q.options.keepSourceTokens)b.srcToken=U;q.items.push(b)}else{if(M)Y(L.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(A.comment)if(L.comment)L.comment+=`
|
|
66
|
+
`+A.comment;else L.comment=A.comment;let Z=new XJ.Pair(L);if(Q.options.keepSourceTokens)Z.srcToken=U;q.items.push(Z)}}if(B&&B<H)Y(B,"IMPOSSIBLE","Map comment with trailing content");return q.range=[X.offset,H,B??H],q}uB.resolveBlockMap=mB});var HJ=C((nB)=>{var cB=Y$(),pB=x2(),dB=m4();function iB({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let q=new(G?.nodeClass??cB.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=pB.resolveProps(U,{indicator:"seq-item-ind",next:z,offset:H,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!V.found)if(V.anchor||V.tag||z)if(z?.type==="block-seq")Y(V.end,"BAD_INDENT","All sequence items must start at the same column");else Y(H,"MISSING_CHAR","Sequence item without - indicator");else{if(B=V.end,V.comment)q.comment=V.comment;continue}let F=z?$(Q,z,V,Y):J(Q,V.end,U,null,V,Y);if(Q.schema.compat)dB.flowIndentCheck(X.indent,z,Y);H=F.range[2],q.items.push(F)}return q.range=[X.offset,H,B??H],q}nB.resolveBlockSeq=iB});var t$=C((sB)=>{function aB($,J,Q,X){let Y="";if($){let G=!1,W="";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(!Y)Y=U;else Y+=W+U;W="";break}case"newline":if(Y)W+=H;G=!0;break;default:X(q,"UNEXPECTED_TOKEN",`Unexpected ${B} at node end`)}J+=H.length}}return{comment:Y,offset:J}}sB.resolveEnd=aB});var VJ=C((GU)=>{var tB=d(),eB=J$(),BJ=X$(),$U=Y$(),JU=t$(),UJ=x2(),QU=t6(),XU=u4(),l4="Block collections are not allowed within flow collections",c4=($)=>$&&($.type==="block-map"||$.type==="block-seq");function YU({composeNode:$,composeEmptyNode:J},Q,X,Y,G){let W=X.start.source==="{",q=W?"flow map":"flow sequence",B=new(G?.nodeClass??(W?BJ.YAMLMap:$U.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 M=0;M<X.items.length;++M){let _=X.items[M],{start:L,key:A,sep:Z,value:b}=_,P=UJ.resolveProps(L,{flow:q,indicator:"explicit-key-ind",next:A??Z?.[0],offset:z,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!P.found){if(!P.anchor&&!P.tag&&!Z&&!b){if(M===0&&P.comma)Y(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`);else if(M<X.items.length-1)Y(P.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${q}`);if(P.comment)if(B.comment)B.comment+=`
|
|
67
|
+
`+P.comment;else B.comment=P.comment;z=P.end;continue}if(!W&&Q.options.strict&&QU.containsNewline(A))Y(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(M===0){if(P.comma)Y(P.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`)}else{if(!P.comma)Y(P.start,"MISSING_CHAR",`Missing , between ${q} items`);if(P.comment){let f="";$:for(let j of L)switch(j.type){case"comma":case"space":break;case"comment":f=j.source.substring(1);break $;default:break $}if(f){let j=B.items[B.items.length-1];if(tB.isPair(j))j=j.value??j.key;if(j.comment)j.comment+=`
|
|
68
|
+
`+f;else j.comment=f;P.comment=P.comment.substring(f.length+1)}}}if(!W&&!Z&&!P.found){let f=b?$(Q,b,P,Y):J(Q,P.end,Z,null,P,Y);if(B.items.push(f),z=f.range[2],c4(b))Y(f.range,"BLOCK_IN_FLOW",l4)}else{Q.atKey=!0;let f=P.end,j=A?$(Q,A,P,Y):J(Q,f,L,null,P,Y);if(c4(A))Y(j.range,"BLOCK_IN_FLOW",l4);Q.atKey=!1;let S=UJ.resolveProps(Z??[],{flow:q,indicator:"map-value-ind",next:b,offset:j.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(S.found){if(!W&&!P.found&&Q.options.strict){if(Z)for(let g of Z){if(g===S.found)break;if(g.type==="newline"){Y(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(P.start<S.found.offset-1024)Y(S.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(b)if("source"in b&&b.source?.[0]===":")Y(b,"MISSING_CHAR",`Missing space after : in ${q}`);else Y(S.start,"MISSING_CHAR",`Missing , or : between ${q} items`);let x=b?$(Q,b,S,Y):S.found?J(Q,S.end,Z,null,S,Y):null;if(x){if(c4(b))Y(x.range,"BLOCK_IN_FLOW",l4)}else if(S.comment)if(j.comment)j.comment+=`
|
|
69
|
+
`+S.comment;else j.comment=S.comment;let i=new eB.Pair(j,x);if(Q.options.keepSourceTokens)i.srcToken=_;if(W){let g=B;if(XU.mapIncludes(Q,g.items,j))Y(f,"DUPLICATE_KEY","Map keys must be unique");g.items.push(i)}else{let g=new BJ.YAMLMap(Q.schema);g.flow=!0,g.items.push(i);let c=(x??j).range;g.range=[j.range[0],c[1],c[2]],B.items.push(g)}z=x?x.range[2]:S.end}}let V=W?"}":"]",[F,...O]=X.end,D=z;if(F?.source===V)D=F.offset+F.source.length;else{let M=q[0].toUpperCase()+q.substring(1),_=U?`${M} must end with a ${V}`:`${M} in block collection must be sufficiently indented and end with a ${V}`;if(Y(z,U?"MISSING_CHAR":"BAD_INDENT",_),F&&F.source.length!==1)O.unshift(F)}if(O.length>0){let M=JU.resolveEnd(O,D,Q.options.strict,Y);if(M.comment)if(B.comment)B.comment+=`
|
|
70
|
+
`+M.comment;else B.comment=M.comment;B.range=[X.offset,D,M.offset]}else B.range=[X.offset,D,D];return B}GU.resolveFlowCollection=YU});var zJ=C((MU)=>{var qU=d(),HU=X0(),BU=X$(),UU=Y$(),VU=qJ(),zU=HJ(),DU=VJ();function p4($,J,Q,X,Y,G){let W=Q.type==="block-map"?VU.resolveBlockMap($,J,Q,X,G):Q.type==="block-seq"?zU.resolveBlockSeq($,J,Q,X,G):DU.resolveFlowCollection($,J,Q,X,G),q=W.constructor;if(Y==="!"||Y===q.tagName)return W.tag=q.tagName,W;if(Y)W.tag=Y;return W}function OU($,J,Q,X,Y){let G=X.tag,W=!G?null:J.directives.tagName(G.source,(V)=>Y(G,"TAG_RESOLVE_FAILED",V));if(Q.type==="block-seq"){let{anchor:V,newlineAfterProp:F}=X,O=V&&G?V.offset>G.offset?V:G:V??G;if(O&&(!F||F.offset<O.offset))Y(O,"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||!W||W==="!"||W===BU.YAMLMap.tagName&&q==="map"||W===UU.YAMLSeq.tagName&&q==="seq")return p4($,J,Q,Y,W);let H=J.schema.tags.find((V)=>V.tag===W&&V.collection===q);if(!H){let V=J.schema.knownTags[W];if(V?.collection===q)J.schema.tags.push(Object.assign({},V,{default:!1})),H=V;else{if(V)Y(G,"BAD_COLLECTION_TYPE",`${V.tag} used for ${q} collection, but expects ${V.collection??"scalar"}`,!0);else Y(G,"TAG_RESOLVE_FAILED",`Unresolved tag: ${W}`,!0);return p4($,J,Q,Y,W)}}let B=p4($,J,Q,Y,W,H),U=H.resolve?.(B,(V)=>Y(G,"TAG_RESOLVE_FAILED",V),J.options)??B,z=qU.isNode(U)?U:new HU.Scalar(U);if(z.range=B.range,z.tag=W,H?.format)z.format=H.format;return z}MU.composeCollection=OU});var i4=C((RU)=>{var d4=X0();function KU($,J,Q){let X=J.offset,Y=_U(J,$.options.strict,Q);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let G=Y.mode===">"?d4.Scalar.BLOCK_FOLDED:d4.Scalar.BLOCK_LITERAL,W=J.source?LU(J.source):[],q=W.length;for(let D=W.length-1;D>=0;--D){let M=W[D][1];if(M===""||M==="\r")q=D;else break}if(q===0){let D=Y.chomp==="+"&&W.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,W.length-1)):"",M=X+Y.length;if(J.source)M+=J.source.length;return{value:D,type:G,comment:Y.comment,range:[X,M,M]}}let H=J.indent+Y.indent,B=J.offset+Y.length,U=0;for(let D=0;D<q;++D){let[M,_]=W[D];if(_===""||_==="\r"){if(Y.indent===0&&M.length>H)H=M.length}else{if(M.length<H)Q(B+M.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(Y.indent===0)H=M.length;if(U=D,H===0&&!$.atRoot)Q(B,"BAD_INDENT","Block scalar values in collections must be indented");break}B+=M.length+_.length+1}for(let D=W.length-1;D>=q;--D)if(W[D][0].length>H)q=D+1;let z="",V="",F=!1;for(let D=0;D<U;++D)z+=W[D][0].slice(H)+`
|
|
72
|
+
`;for(let D=U;D<q;++D){let[M,_]=W[D];B+=M.length+_.length+1;let L=_[_.length-1]==="\r";if(L)_=_.slice(0,-1);if(_&&M.length<H){let Z=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;Q(B-_.length-(L?2:1),"BAD_INDENT",Z),M=""}if(G===d4.Scalar.BLOCK_LITERAL)z+=V+M.slice(H)+_,V=`
|
|
73
|
+
`;else if(M.length>H||_[0]==="\t"){if(V===" ")V=`
|
|
74
|
+
`;else if(!F&&V===`
|
|
75
|
+
`)V=`
|
|
76
|
+
|
|
77
|
+
`;z+=V+M.slice(H)+_,V=`
|
|
78
|
+
`,F=!0}else if(_==="")if(V===`
|
|
79
|
+
`)z+=`
|
|
80
|
+
`;else V=`
|
|
81
|
+
`;else z+=V+_,V=" ",F=!1}switch(Y.chomp){case"-":break;case"+":for(let D=q;D<W.length;++D)z+=`
|
|
82
|
+
`+W[D][0].slice(H);if(z[z.length-1]!==`
|
|
83
|
+
`)z+=`
|
|
84
|
+
`;break;default:z+=`
|
|
85
|
+
`}let O=X+Y.length+J.source.length;return{value:z,type:G,comment:Y.comment,range:[X,O,O]}}function _U({offset:$,props:J},Q,X){if(J[0].type!=="block-scalar-header")return X(J[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:Y}=J[0],G=Y[0],W=0,q="",H=-1;for(let V=1;V<Y.length;++V){let F=Y[V];if(!q&&(F==="-"||F==="+"))q=F;else{let O=Number(F);if(!W&&O)W=O;else if(H===-1)H=$+V}}if(H!==-1)X(H,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let B=!1,U="",z=Y.length;for(let V=1;V<J.length;++V){let F=J[V];switch(F.type){case"space":B=!0;case"newline":z+=F.source.length;break;case"comment":if(Q&&!B)X(F,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");z+=F.source.length,U=F.source.substring(1);break;case"error":X(F,"UNEXPECTED_TOKEN",F.message),z+=F.source.length;break;default:{let O=`Unexpected token in block scalar header: ${F.type}`;X(F,"UNEXPECTED_TOKEN",O);let D=F.source;if(D&&typeof D==="string")z+=D.length}}}return{mode:G,indent:W,chomp:q,comment:U,length:z}}function LU($){let J=$.split(/\n( *)/),Q=J[0],X=Q.match(/^( *)/),G=[X?.[1]?[X[1],Q.slice(X[1].length)]:["",Q]];for(let W=1;W<J.length;W+=2)G.push([J[W],J[W+1]]);return G}RU.resolveBlockScalar=KU});var r4=C((CU)=>{var n4=X0(),NU=t$();function jU($,J,Q){let{offset:X,type:Y,source:G,end:W}=$,q,H,B=(V,F,O)=>Q(X+V,F,O);switch(Y){case"scalar":q=n4.Scalar.PLAIN,H=ZU(G,B);break;case"single-quoted-scalar":q=n4.Scalar.QUOTE_SINGLE,H=PU(G,B);break;case"double-quoted-scalar":q=n4.Scalar.QUOTE_DOUBLE,H=wU(G,B);break;default:return Q($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${Y}`),{value:"",type:null,comment:"",range:[X,X+G.length,X+G.length]}}let U=X+G.length,z=NU.resolveEnd(W,U,J,Q);return{value:H,type:q,comment:z.comment,range:[X,U,z.offset]}}function ZU($,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 DJ($)}function PU($,J){if($[$.length-1]!=="'"||$.length===1)J($.length,"MISSING_CHAR","Missing closing 'quote");return DJ($.slice(1,-1)).replace(/''/g,"'")}function DJ($){let J=/(.*?)\r?\n/sy,Q=J.exec($);if(!Q)return $;let X,Y;try{X=new RegExp("(?<![ \t])[ \t]+$"),Y=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,Y=/^[ \t]+|[ \t]+$/g}let G=Q[1].replace(X,""),W=" ",q=J.lastIndex;while(Q=J.exec($)){let B=Q[1].replace(Y,"");if(B==="")if(W===`
|
|
86
|
+
`)G+=W;else W=`
|
|
87
|
+
`;else G+=W+B,W=" ";q=J.lastIndex}let H=/[ \t]*(.*)/sy;return H.lastIndex=q,Q=H.exec($),G+W+(Q?.[1]??"")}function wU($,J){let Q="";for(let X=1;X<$.length-1;++X){let Y=$[X];if(Y==="\r"&&$[X+1]===`
|
|
88
88
|
`)continue;if(Y===`
|
|
89
|
-
`){let{fold:
|
|
90
|
-
`){
|
|
91
|
-
`){
|
|
92
|
-
`&&!(
|
|
93
|
-
`))
|
|
94
|
-
`||X==="\r"){if(X==="\r"
|
|
89
|
+
`){let{fold:G,offset:W}=bU($,X);Q+=G,X=W}else if(Y==="\\"){let G=$[++X],W=EU[G];if(W)Q+=W;else if(G===`
|
|
90
|
+
`){G=$[X+1];while(G===" "||G==="\t")G=$[++X+1]}else if(G==="\r"&&$[X+1]===`
|
|
91
|
+
`){G=$[++X+1];while(G===" "||G==="\t")G=$[++X+1]}else if(G==="x"||G==="u"||G==="U"){let q=G==="x"?2:G==="u"?4:8;Q+=SU($,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(Y===" "||Y==="\t"){let G=X,W=$[X+1];while(W===" "||W==="\t")W=$[++X+1];if(W!==`
|
|
92
|
+
`&&!(W==="\r"&&$[X+2]===`
|
|
93
|
+
`))Q+=X>G?$.slice(G,X+1):Y}else Q+=Y}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function bU($,J){let Q="",X=$[J+1];while(X===" "||X==="\t"||X===`
|
|
94
|
+
`||X==="\r"){if(X==="\r"&&$[J+2]!==`
|
|
95
95
|
`)break;if(X===`
|
|
96
|
-
`)
|
|
97
|
-
`;
|
|
98
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
96
|
+
`)Q+=`
|
|
97
|
+
`;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var EU={"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 SU($,J,Q,X){let Y=$.substr(J,Q),W=Y.length===Q&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(W)}catch{let q=$.substr(J-2,Q+2);return X(J-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${q}`),q}}CU.resolveFlowScalar=jU});var MJ=C((yU)=>{var L$=d(),OJ=X0(),IU=i4(),TU=r4();function vU($,J,Q,X){let{value:Y,type:G,comment:W,range:q}=J.type==="block-scalar"?IU.resolveBlockScalar($,J,X):TU.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[L$.SCALAR];else if(H)B=xU($.schema,Y,H,Q,X);else if(J.type==="scalar")B=hU($,Y,J,X);else B=$.schema[L$.SCALAR];let U;try{let z=B.resolve(Y,(V)=>X(Q??J,"TAG_RESOLVE_FAILED",V),$.options);U=L$.isScalar(z)?z:new OJ.Scalar(z)}catch(z){let V=z instanceof Error?z.message:String(z);X(Q??J,"TAG_RESOLVE_FAILED",V),U=new OJ.Scalar(Y)}if(U.range=q,U.source=Y,G)U.type=G;if(H)U.tag=H;if(B.format)U.format=B.format;if(W)U.comment=W;return U}function xU($,J,Q,X,Y){if(Q==="!")return $[L$.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 W=$.knownTags[Q];if(W&&!W.collection)return $.tags.push(Object.assign({},W,{default:!1,test:void 0})),W;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),$[L$.SCALAR]}function hU({atKey:$,directives:J,schema:Q},X,Y,G){let W=Q.tags.find((q)=>(q.default===!0||$&&q.default==="key")&&q.test?.test(X))||Q[L$.SCALAR];if(Q.compat){let q=Q.compat.find((H)=>H.default&&H.test?.test(X))??Q[L$.SCALAR];if(W.tag!==q.tag){let H=J.tagString(W.tag),B=J.tagString(q.tag),U=`Value may be parsed as either ${H} or ${B}`;G(Y,"TAG_RESOLVE_FAILED",U,!0)}}return W}yU.composeScalar=vU});var FJ=C((mU)=>{function kU($,J,Q){if(J){Q??(Q=J.length);for(let X=Q-1;X>=0;--X){let Y=J[X];switch(Y.type){case"space":case"comment":case"newline":$-=Y.source.length;continue}Y=J[++X];while(Y?.type==="space")$+=Y.source.length,Y=J[++X];break}}return $}mU.emptyScalarPosition=kU});var LJ=C((aU)=>{var lU=L2(),cU=d(),pU=zJ(),KJ=MJ(),dU=t$(),iU=FJ(),nU={composeNode:_J,composeEmptyNode:a4};function _J($,J,Q,X){let Y=$.atKey,{spaceBefore:G,comment:W,anchor:q,tag:H}=Q,B,U=!0;switch(J.type){case"alias":if(B=rU($,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=KJ.composeScalar($,J,H,X),q)B.anchor=q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(B=pU.composeCollection(nU,$,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=a4($,J.offset,void 0,null,Q,X)),q&&B.anchor==="")X(q,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&$.options.stringKeys&&(!cU.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(W)if(J.type==="scalar"&&J.source==="")B.comment=W;else B.commentBefore=W;if($.options.keepSourceTokens&&U)B.srcToken=J;return B}function a4($,J,Q,X,{spaceBefore:Y,comment:G,anchor:W,tag:q,end:H},B){let U={type:"scalar",offset:iU.emptyScalarPosition(J,Q,X),indent:-1,source:""},z=KJ.composeScalar($,U,q,B);if(W){if(z.anchor=W.source.substring(1),z.anchor==="")B(W,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)z.spaceBefore=!0;if(G)z.comment=G,z.range[2]=H;return z}function rU({options:$},{offset:J,source:Q,end:X},Y){let G=new lU.Alias(Q.substring(1));if(G.source==="")Y(J,"BAD_ALIAS","Alias cannot be an empty string");if(G.source.endsWith(":"))Y(J+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let W=J+Q.length,q=dU.resolveEnd(X,W,$.strict,Y);if(G.range=[J,W,q.offset],q.comment)G.comment=q.comment;return G}aU.composeEmptyNode=a4;aU.composeNode=_J});var AJ=C((QV)=>{var tU=T2(),RJ=LJ(),eU=t$(),$V=x2();function JV($,J,{offset:Q,start:X,value:Y,end:G},W){let q=Object.assign({_directives:J},$),H=new tU.Document(void 0,q),B={atKey:!1,atRoot:!0,directives:H.directives,options:H.options,schema:H.schema},U=$V.resolveProps(X,{indicator:"doc-start",next:Y??G?.[0],offset:Q,onError:W,parentIndent:0,startOnNewline:!0});if(U.found){if(H.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!U.hasNewline)W(U.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}H.contents=Y?RJ.composeNode(B,Y,U,W):RJ.composeEmptyNode(B,U.end,X,null,U,W);let z=H.contents.range[2],V=eU.resolveEnd(G,z,!1,W);if(V.comment)H.comment=V.comment;return H.range=[Q,z,V.offset],H}QV.composeDoc=JV});var s4=C((BV)=>{var YV=W6("process"),GV=$4(),WV=T2(),h2=v2(),NJ=d(),qV=AJ(),HV=t$();function y2($){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 jJ($){let J="",Q=!1,X=!1;for(let Y=0;Y<$.length;++Y){let G=$[Y];switch(G[0]){case"#":J+=(J===""?"":X?`
|
|
99
99
|
|
|
100
100
|
`:`
|
|
101
|
-
`)+(
|
|
102
|
-
${
|
|
103
|
-
${
|
|
104
|
-
${
|
|
105
|
-
${
|
|
106
|
-
`}];switch(
|
|
107
|
-
`),q
|
|
108
|
-
`,
|
|
109
|
-
`});return{type:"block-scalar",offset:
|
|
110
|
-
`),X=
|
|
111
|
-
`;if(
|
|
112
|
-
`});for(let
|
|
113
|
-
`};delete
|
|
101
|
+
`)+(G.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[Y+1]?.[0]!=="#")Y+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class ZJ{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(J,Q,X,Y)=>{let G=y2(J);if(Y)this.warnings.push(new h2.YAMLWarning(G,Q,X));else this.errors.push(new h2.YAMLParseError(G,Q,X))},this.directives=new GV.Directives({version:$.version||"1.2"}),this.options=$}decorate($,J){let{comment:Q,afterEmptyLine:X}=jJ(this.prelude);if(Q){let Y=$.contents;if(J)$.comment=$.comment?`${$.comment}
|
|
102
|
+
${Q}`:Q;else if(X||$.directives.docStart||!Y)$.commentBefore=Q;else if(NJ.isCollection(Y)&&!Y.flow&&Y.items.length>0){let G=Y.items[0];if(NJ.isPair(G))G=G.key;let W=G.commentBefore;G.commentBefore=W?`${Q}
|
|
103
|
+
${W}`:Q}else{let G=Y.commentBefore;Y.commentBefore=G?`${Q}
|
|
104
|
+
${G}`:Q}}if(J){for(let Y=0;Y<this.errors.length;++Y)$.errors.push(this.errors[Y]);for(let Y=0;Y<this.warnings.length;++Y)$.warnings.push(this.warnings[Y])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:jJ(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(YV.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(J,Q,X)=>{let Y=y2($);Y[0]+=J,this.onError(Y,"BAD_DIRECTIVE",Q,X)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let J=qV.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 h2.YAMLParseError(y2($),"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 h2.YAMLParseError(y2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let J=HV.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 h2.YAMLParseError(y2($),"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 WV.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}}}BV.Composer=ZJ});var bJ=C((_V)=>{var VV=i4(),zV=r4(),DV=v2(),PJ=j2();function OV($,J=!0,Q){if($){let X=(Y,G,W)=>{let q=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if(Q)Q(q,G,W);else throw new DV.YAMLParseError([q,q+1],G,W)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return zV.resolveFlowScalar($,J,X);case"block-scalar":return VV.resolveBlockScalar({options:{strict:J}},$,X)}}return null}function MV($,J){let{implicitKey:Q=!1,indent:X,inFlow:Y=!1,offset:G=-1,type:W="PLAIN"}=J,q=PJ.stringifyString({type:W,value:$},{implicitKey:Q,indent:X>0?" ".repeat(X):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}}),H=J.end??[{type:"newline",offset:-1,indent:X,source:`
|
|
106
|
+
`}];switch(q[0]){case"|":case">":{let B=q.indexOf(`
|
|
107
|
+
`),U=q.substring(0,B),z=q.substring(B+1)+`
|
|
108
|
+
`,V=[{type:"block-scalar-header",offset:G,indent:X,source:U}];if(!wJ(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 FV($,J,Q={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:G=!1,type:W}=Q,q="indent"in $?$.indent:null;if(X&&typeof q==="number")q+=2;if(!W)switch($.type){case"single-quoted-scalar":W="QUOTE_SINGLE";break;case"double-quoted-scalar":W="QUOTE_DOUBLE";break;case"block-scalar":{let B=$.props[0];if(B.type!=="block-scalar-header")throw Error("Invalid block scalar header");W=B.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:W="PLAIN"}let H=PJ.stringifyString({type:W,value:J},{implicitKey:Y||q===null,indent:q!==null&&q>0?" ".repeat(q):"",inFlow:G,options:{blockQuote:!0,lineWidth:-1}});switch(H[0]){case"|":case">":KV($,H);break;case'"':o4($,H,"double-quoted-scalar");break;case"'":o4($,H,"single-quoted-scalar");break;default:o4($,H,"scalar")}}function KV($,J){let Q=J.indexOf(`
|
|
110
|
+
`),X=J.substring(0,Q),Y=J.substring(Q+1)+`
|
|
111
|
+
`;if($.type==="block-scalar"){let G=$.props[0];if(G.type!=="block-scalar-header")throw Error("Invalid block scalar header");G.source=X,$.source=Y}else{let{offset:G}=$,W="indent"in $?$.indent:-1,q=[{type:"block-scalar-header",offset:G,indent:W,source:X}];if(!wJ(q,"end"in $?$.end:void 0))q.push({type:"newline",offset:-1,indent:W,source:`
|
|
112
|
+
`});for(let H of Object.keys($))if(H!=="type"&&H!=="offset")delete $[H];Object.assign($,{type:"block-scalar",indent:W,props:q,source:Y})}}function wJ($,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 o4($,J,Q){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=Q,$.source=J;break;case"block-scalar":{let X=$.props.slice(1),Y=J.length;if($.props[0].type==="block-scalar-header")Y-=$.props[0].source.length;for(let G of X)G.offset+=Y;delete $.props,Object.assign($,{type:Q,source:J,end:X});break}case"block-map":case"block-seq":{let Y={type:"newline",offset:$.offset+J.length,indent:$.indent,source:`
|
|
113
|
+
`};delete $.items,Object.assign($,{type:Q,source:J,end:[Y]});break}default:{let X="indent"in $?$.indent:-1,Y="end"in $&&Array.isArray($.end)?$.end.filter((G)=>G.type==="space"||G.type==="comment"||G.type==="newline"):[];for(let G of Object.keys($))if(G!=="type"&&G!=="offset")delete $[G];Object.assign($,{type:Q,indent:X,source:J,end:Y})}}}_V.createScalarToken=MV;_V.resolveAsScalar=OV;_V.setScalarValue=FV});var EJ=C((jV)=>{var NV=($)=>("type"in $)?$9($):e6($);function $9($){switch($.type){case"block-scalar":{let J="";for(let Q of $.props)J+=$9(Q);return J+$.source}case"block-map":case"block-seq":{let J="";for(let Q of $.items)J+=e6(Q);return J}case"flow-collection":{let J=$.start.source;for(let Q of $.items)J+=e6(Q);for(let Q of $.end)J+=Q.source;return J}case"document":{let J=e6($);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 e6({start:$,key:J,sep:Q,value:X}){let Y="";for(let G of $)Y+=G.source;if(J)Y+=$9(J);if(Q)for(let G of Q)Y+=G.source;if(X)Y+=$9(X);return Y}jV.stringify=NV});var fJ=C((wV)=>{var t4=Symbol("break visit"),PV=Symbol("skip children"),SJ=Symbol("remove item");function R$($,J){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};CJ(Object.freeze([]),$,J)}R$.BREAK=t4;R$.SKIP=PV;R$.REMOVE=SJ;R$.itemAtPath=($,J)=>{let Q=$;for(let[X,Y]of J){let G=Q?.[X];if(G&&"items"in G)Q=G.items[Y];else return}return Q};R$.parentCollection=($,J)=>{let Q=R$.itemAtPath($,J.slice(0,-1)),X=J[J.length-1][0],Y=Q?.[X];if(Y&&"items"in Y)return Y;throw Error("Parent collection not found")};function CJ($,J,Q){let X=Q(J,$);if(typeof X==="symbol")return X;for(let Y of["key","value"]){let G=J[Y];if(G&&"items"in G){for(let W=0;W<G.items.length;++W){let q=CJ(Object.freeze($.concat([[Y,W]])),G.items[W],Q);if(typeof q==="number")W=q-1;else if(q===t4)return t4;else if(q===SJ)G.items.splice(W,1),W-=1}if(typeof X==="function"&&Y==="key")X=X(J,$)}}return typeof X==="function"?X(J,$):X}wV.visit=R$});var J9=C((vV)=>{var e4=bJ(),EV=EJ(),SV=fJ(),$8="\uFEFF",J8="\x02",Q8="\x18",X8="\x1F",CV=($)=>!!$&&("items"in $),fV=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function IV($){switch($){case $8:return"<BOM>";case J8:return"<DOC>";case Q8:return"<FLOW_END>";case X8:return"<SCALAR>";default:return JSON.stringify($)}}function TV($){switch($){case $8:return"byte-order-mark";case J8:return"doc-mode";case Q8:return"flow-error-end";case X8: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(
|
|
116
|
-
`:case"\r":case"\t":return!0;default:return!1}}var
|
|
117
|
-
\r `),
|
|
118
|
-
`)return!0;if(
|
|
119
|
-
`;return!1}charAt(
|
|
120
|
-
`||!X&&!this.atEnd)return
|
|
121
|
-
|
|
122
|
-
`,this.pos),this.lineEndPos
|
|
123
|
-
`,this.pos);if(X!==-1){while(X!==-1){let Y=this.continueScalar(X+1);if(Y===-1)break;X
|
|
124
|
-
`,Y)}if(X!==-1)
|
|
125
|
-
|
|
126
|
-
`)break}default:break
|
|
127
|
-
`,Y)}while(
|
|
128
|
-
`)
|
|
129
|
-
`&&Y>=this.pos&&Y+1+
|
|
130
|
-
`)
|
|
131
|
-
`,Y=this.buffer[
|
|
132
|
-
`){let
|
|
133
|
-
`)return yield*this.pushCount(1);else if(
|
|
134
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces(
|
|
135
|
-
`)+1;while(
|
|
136
|
-
`,
|
|
137
|
-
`)+1;while(
|
|
138
|
-
`,
|
|
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}vV.createScalarToken=e4.createScalarToken;vV.resolveAsScalar=e4.resolveAsScalar;vV.setScalarValue=e4.setScalarValue;vV.stringify=EV.stringify;vV.visit=SV.visit;vV.BOM=$8;vV.DOCUMENT=J8;vV.FLOW_END=Q8;vV.SCALAR=X8;vV.isCollection=CV;vV.isScalar=fV;vV.prettyToken=IV;vV.tokenType=TV});var G8=C((sV)=>{var g2=J9();function E0($){switch($){case void 0:case" ":case`
|
|
116
|
+
`:case"\r":case"\t":return!0;default:return!1}}var IJ=new Set("0123456789ABCDEFabcdef"),rV=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Q9=new Set(",[]{}"),aV=new Set(` ,[]{}
|
|
117
|
+
\r `),Y8=($)=>!$||aV.has($);class TJ{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
|
+
`)return!0;if(J==="\r")return this.buffer[$+1]===`
|
|
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
|
+
`||!X&&!this.atEnd)return $+Q+1}return J===`
|
|
121
|
+
`||Q>=this.indentNext||!J&&!this.atEnd?$+Q:-1}if(J==="-"||J==="."){let Q=this.buffer.substr($,3);if((Q==="---"||Q==="...")&&E0(this.buffer[$+3]))return-1}return $}getLine(){let $=this.lineEndPos;if(typeof $!=="number"||$!==-1&&$<this.pos)$=this.buffer.indexOf(`
|
|
122
|
+
`,this.pos),this.lineEndPos=$;if($===-1)return this.atEnd?this.buffer.substring(this.pos):null;if(this.buffer[$-1]==="\r")$-=1;return this.buffer.substring(this.pos,$)}hasChars($){return this.pos+$<=this.buffer.length}setNext($){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=$,null}peek($){return this.buffer.substr(this.pos,$)}*parseNext($){switch($){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let $=this.getLine();if($===null)return this.setNext("stream");if($[0]===g2.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let J=$.length,Q=$.indexOf("#");while(Q!==-1){let Y=$[Q-1];if(Y===" "||Y==="\t"){J=Q-1;break}else Q=$.indexOf("#",Q+1)}while(!0){let Y=$[J-1];if(Y===" "||Y==="\t")J-=1;else break}let X=(yield*this.pushCount(J))+(yield*this.pushSpaces(!0));return yield*this.pushCount($.length-X),this.pushNewline(),"stream"}if(this.atLineEnd()){let J=yield*this.pushSpaces(!0);return yield*this.pushCount($.length-J),yield*this.pushNewline(),"stream"}return yield g2.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let $=this.charAt(0);if(!$&&!this.atEnd)return this.setNext("line-start");if($==="-"||$==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let J=this.peek(3);if((J==="---"||J==="...")&&E0(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,J==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!E0(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[$,J]=this.peek(2);if(!J&&!this.atEnd)return this.setNext("block-start");if(($==="-"||$==="?"||$===":")&&E0(J)){let Q=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=Q,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let $=this.getLine();if($===null)return this.setNext("doc");let J=yield*this.pushIndicators();switch($[J]){case"#":yield*this.pushCount($.length-J);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(Y8),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return J+=yield*this.parseBlockScalarHeader(),J+=yield*this.pushSpaces(!0),yield*this.pushCount($.length-J),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let $,J,Q=-1;do{if($=yield*this.pushNewline(),$>0)J=yield*this.pushSpaces(!1),this.indentValue=Q=J;else J=0;J+=yield*this.pushSpaces(!0)}while($+J>0);let X=this.getLine();if(X===null)return this.setNext("flow");if(Q!==-1&&Q<this.indentNext&&X[0]!=="#"||Q===0&&(X.startsWith("---")||X.startsWith("..."))&&E0(X[3])){if(!(Q===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield g2.FLOW_END,yield*this.parseLineStart()}let Y=0;while(X[Y]===",")Y+=yield*this.pushCount(1),Y+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(Y+=yield*this.pushIndicators(),X[Y]){case void 0:return"flow";case"#":return yield*this.pushCount(X.length-Y),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(Y8),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let G=this.charAt(1);if(this.flowKey||E0(G)||G===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),J=this.buffer.indexOf($,this.pos+1);if($==="'")while(J!==-1&&this.buffer[J+1]==="'")J=this.buffer.indexOf("'",J+2);else while(J!==-1){let Y=0;while(this.buffer[J-1-Y]==="\\")Y+=1;if(Y%2===0)break;J=this.buffer.indexOf('"',J+1)}let Q=this.buffer.substring(0,J),X=Q.indexOf(`
|
|
123
|
+
`,this.pos);if(X!==-1){while(X!==-1){let Y=this.continueScalar(X+1);if(Y===-1)break;X=Q.indexOf(`
|
|
124
|
+
`,Y)}if(X!==-1)J=X-(Q[X-1]==="\r"?2:1)}if(J===-1){if(!this.atEnd)return this.setNext("quoted-scalar");J=this.buffer.length}return yield*this.pushToIndex(J+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let $=this.pos;while(!0){let J=this.buffer[++$];if(J==="+")this.blockScalarKeep=!0;else if(J>"0"&&J<="9")this.blockScalarIndent=Number(J)-1;else if(J!=="-")break}return yield*this.pushUntil((J)=>E0(J)||J==="#")}*parseBlockScalar(){let $=this.pos-1,J=0,Q;$:for(let Y=this.pos;Q=this.buffer[Y];++Y)switch(Q){case" ":J+=1;break;case`
|
|
125
|
+
`:$=Y,J=0;break;case"\r":{let G=this.buffer[Y+1];if(!G&&!this.atEnd)return this.setNext("block-scalar");if(G===`
|
|
126
|
+
`)break}default:break $}if(!Q&&!this.atEnd)return this.setNext("block-scalar");if(J>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=J;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let Y=this.continueScalar($+1);if(Y===-1)break;$=this.buffer.indexOf(`
|
|
127
|
+
`,Y)}while($!==-1);if($===-1){if(!this.atEnd)return this.setNext("block-scalar");$=this.buffer.length}}let X=$+1;Q=this.buffer[X];while(Q===" ")Q=this.buffer[++X];if(Q==="\t"){while(Q==="\t"||Q===" "||Q==="\r"||Q===`
|
|
128
|
+
`)Q=this.buffer[++X];$=X-1}else if(!this.blockScalarKeep)do{let Y=$-1,G=this.buffer[Y];if(G==="\r")G=this.buffer[--Y];let W=Y;while(G===" ")G=this.buffer[--Y];if(G===`
|
|
129
|
+
`&&Y>=this.pos&&Y+1+J>W)$=Y;else break}while(!0);return yield g2.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,J=this.pos-1,Q=this.pos-1,X;while(X=this.buffer[++Q])if(X===":"){let Y=this.buffer[Q+1];if(E0(Y)||$&&Q9.has(Y))break;J=Q}else if(E0(X)){let Y=this.buffer[Q+1];if(X==="\r")if(Y===`
|
|
130
|
+
`)Q+=1,X=`
|
|
131
|
+
`,Y=this.buffer[Q+1];else J=Q;if(Y==="#"||$&&Q9.has(Y))break;if(X===`
|
|
132
|
+
`){let G=this.continueScalar(Q+1);if(G===-1)break;Q=Math.max(Q,G-2)}}else{if($&&Q9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield g2.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(Y8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(E0(Q)||J&&Q9.has(Q)){if(!J)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;$+=yield*this.pushCount(1),$+=yield*this.pushSpaces(!0);continue $}}}break $}return $}*pushTag(){if(this.charAt(1)==="<"){let $=this.pos+2,J=this.buffer[$];while(!E0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(rV.has(J))J=this.buffer[++$];else if(J==="%"&&IJ.has(this.buffer[$+1])&&IJ.has(this.buffer[$+2]))J=this.buffer[$+=3];else break;return yield*this.pushToIndex($,!1)}}*pushNewline(){let $=this.buffer[this.pos];if($===`
|
|
133
|
+
`)return yield*this.pushCount(1);else if($==="\r"&&this.charAt(1)===`
|
|
134
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces($){let J=this.pos-1,Q;do Q=this.buffer[++J];while(Q===" "||$&&Q==="\t");let X=J-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=J;return X}*pushUntil($){let J=this.pos,Q=this.buffer[J];while(!$(Q))Q=this.buffer[++J];return yield*this.pushToIndex(J,!1)}}sV.Lexer=TJ});var W8=C((tV)=>{class vJ{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let J=0,Q=this.lineStarts.length;while(J<Q){let Y=J+Q>>1;if(this.lineStarts[Y]<$)J=Y+1;else Q=Y}if(this.lineStarts[J]===$)return{line:J+1,col:1};if(J===0)return{line:0,col:$};let X=this.lineStarts[J-1];return{line:J,col:$-X+1}}}}tV.LineCounter=vJ});var q8=C((Qz)=>{var $z=W6("process"),xJ=J9(),Jz=G8();function G$($,J){for(let Q=0;Q<$.length;++Q)if($[Q].type===J)return!0;return!1}function hJ($){for(let J=0;J<$.length;++J)switch($[J].type){case"space":case"comment":case"newline":break;default:return J}return-1}function gJ($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function X9($){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 e$($){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 Y9($,J){if(J.length<1e5)Array.prototype.push.apply($,J);else for(let Q=0;Q<J.length;++Q)$.push(J[Q])}function yJ($){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,gJ(J.value))if(J.value.end)Y9(J.value.end,J.sep);else J.value.end=J.sep;else Y9(J.start,J.sep);delete J.sep}}}class kJ{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 Jz.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=$,$z.env.LOG_TOKENS)console.log("|",xJ.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let J=xJ.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")yJ(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&&hJ(X.start)===-1&&(J.indent===0||X.start.every((Y)=>Y.type!=="comment"||Y.indent<J.indent))){if(Q.type==="document")Q.end=X.start;else Q.items.push({start:X.start});J.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let $={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")$.start.push(this.sourceToken);this.stack.push($);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document($){if($.value)return yield*this.lineEnd($);switch(this.type){case"doc-start":{if(hJ($.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=X9(this.peek(2)),Q=e$(J),X;if($.end)X=$.end,X.push(this.sourceToken),delete $.end;else X=[this.sourceToken];let Y={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Q,key:$,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}else yield*this.lineEnd($)}*blockScalar($){switch(this.type){case"space":case"comment":case"newline":$.props.push(this.sourceToken);return;case"scalar":if($.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let J=this.source.indexOf(`
|
|
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)){Y9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let Q=!this.onKeyLine&&this.indent===$.indent,X=Q&&(J.sep||J.explicitKey)&&this.type!=="seq-item-ind",Y=[];if(X&&J.sep&&!J.value){let G=[];for(let W=0;W<J.sep.length;++W){let q=J.sep[W];switch(q.type){case"newline":G.push(W);break;case"space":break;case"comment":if(q.indent>$.indent)G.length=0;break;default:G.length=0}}if(G.length>=2)Y=J.sep.splice(G[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)Y.push(this.sourceToken),$.items.push({start:Y}),this.onKeyLine=!0;else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"explicit-key-ind":if(!J.sep&&!J.explicitKey)J.start.push(this.sourceToken),J.explicitKey=!0;else if(X||J.value)Y.push(this.sourceToken),$.items.push({start:Y,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(J.explicitKey)if(!J.sep)if(G$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let G=e$(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:Y,key:null,sep:[this.sourceToken]}]});else if(gJ(J.key)&&!G$(J.sep,"newline")){let G=e$(J.start),W=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:W,sep:q}]})}else if(Y.length>0)J.sep=J.sep.concat(Y,this.sourceToken);else J.sep.push(this.sourceToken);else if(!J.sep)Object.assign(J,{key:null,sep:[this.sourceToken]});else if(J.value||X)$.items.push({start:Y,key:null,sep:[this.sourceToken]});else if(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:Y,key:G,sep:[]}),this.onKeyLine=!0;else if(J.sep)this.stack.push(G);else Object.assign(J,{key:G,sep:[]}),this.onKeyLine=!0;return}default:{let G=this.startBlockValue($);if(G){if(G.type==="block-seq"){if(!J.explicitKey&&J.sep&&!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:Y});this.stack.push(G);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){Y9(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=X9(Q),Y=e$(X);yJ($);let G=$.end.splice(1,$.end.length);G.push(this.sourceToken);let W={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Y,key:$,sep:G}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let J=this.source.indexOf(`
|
|
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=X9($),Q=e$(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=X9($),Q=e$(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()}}}Qz.Parser=kJ});var pJ=C((Vz)=>{var mJ=s4(),Yz=T2(),k2=v2(),Gz=W4(),Wz=d(),qz=W8(),uJ=q8();function lJ($){let J=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||J&&new qz.LineCounter||null,prettyErrors:J}}function Hz($,J={}){let{lineCounter:Q,prettyErrors:X}=lJ(J),Y=new uJ.Parser(Q?.addNewLine),G=new mJ.Composer(J),W=Array.from(G.compose(Y.parse($)));if(X&&Q)for(let q of W)q.errors.forEach(k2.prettifyError($,Q)),q.warnings.forEach(k2.prettifyError($,Q));if(W.length>0)return W;return Object.assign([],{empty:!0},G.streamInfo())}function cJ($,J={}){let{lineCounter:Q,prettyErrors:X}=lJ(J),Y=new uJ.Parser(Q?.addNewLine),G=new mJ.Composer(J),W=null;for(let q of G.compose(Y.parse($),!0,$.length))if(!W)W=q;else if(W.options.logLevel!=="silent"){W.errors.push(new k2.YAMLParseError(q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Q)W.errors.forEach(k2.prettifyError($,Q)),W.warnings.forEach(k2.prettifyError($,Q));return W}function Bz($,J,Q){let X=void 0;if(typeof J==="function")X=J;else if(Q===void 0&&J&&typeof J==="object")Q=J;let Y=cJ($,Q);if(!Y)return null;if(Y.warnings.forEach((G)=>Gz.warn(Y.options.logLevel,G)),Y.errors.length>0)if(Y.options.logLevel!=="silent")throw Y.errors[0];else Y.errors=[];return Y.toJS(Object.assign({reviver:X},Q))}function Uz($,J,Q){let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J;if(typeof Q==="string")Q=Q.length;if(typeof Q==="number"){let Y=Math.round(Q);Q=Y<1?void 0:Y>8?{indent:8}:{indent:Y}}if($===void 0){let{keepUndefined:Y}=Q??J??{};if(!Y)return}if(Wz.isDocument($)&&!X)return $.toString(Q);return new Yz.Document($,X,Q).toString(Q)}Vz.parse=Bz;Vz.parseAllDocuments=Hz;Vz.parseDocument=cJ;Vz.stringify=Uz});var iJ=C((Ez)=>{var Fz=s4(),Kz=T2(),_z=v4(),H8=v2(),Lz=L2(),W$=d(),Rz=J$(),Az=X0(),Nz=X$(),jz=Y$(),Zz=J9(),Pz=G8(),wz=W8(),bz=q8(),G9=pJ(),dJ=K2();Ez.Composer=Fz.Composer;Ez.Document=Kz.Document;Ez.Schema=_z.Schema;Ez.YAMLError=H8.YAMLError;Ez.YAMLParseError=H8.YAMLParseError;Ez.YAMLWarning=H8.YAMLWarning;Ez.Alias=Lz.Alias;Ez.isAlias=W$.isAlias;Ez.isCollection=W$.isCollection;Ez.isDocument=W$.isDocument;Ez.isMap=W$.isMap;Ez.isNode=W$.isNode;Ez.isPair=W$.isPair;Ez.isScalar=W$.isScalar;Ez.isSeq=W$.isSeq;Ez.Pair=Rz.Pair;Ez.Scalar=Az.Scalar;Ez.YAMLMap=Nz.YAMLMap;Ez.YAMLSeq=jz.YAMLSeq;Ez.CST=Zz;Ez.Lexer=Pz.Lexer;Ez.LineCounter=wz.LineCounter;Ez.Parser=bz.Parser;Ez.parse=G9.parse;Ez.parseAllDocuments=G9.parseAllDocuments;Ez.parseDocument=G9.parseDocument;Ez.stringify=G9.stringify;Ez.visit=dJ.visit;Ez.visitAsync=dJ.visitAsync});var m1=($)=>$.payload.title?.trim()||`session:${$.payload.id}`;function q6($){let{store:J,agent:Q}=$;return{async session(X){let Y=X.payload.id,G=await o8(J,Y);switch(X.type){case"session.created":{if(G)return{task_id:G.id};let W=m1(X);return{task_id:(await J.createTask({title:W,session_id:Y,owner:Q,priority:3})).id}}case"session.idle":{if(!G)return null;if(G.status==="pending"){let W=await J.updateTask(G.id,{status:"in_progress"});return W?{task_id:W.id}:null}return null}case"session.deleted":{if(!G)return null;return await J.updateTask(G.id,{status:"cancelled"}),{task_id:G.id}}case"session.error":case"session.compacted":return await J.appendOperation({task_id:G?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:Y,agent:Q}}),null;default:return null}},async tool(X){let Y=X.payload.sessionID,G=await o8(J,Y);if(!G)return await J.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:Y,tool:X.payload.tool}}),{task_id:(await J.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:Q,priority:3})).id};let W=u1(X),H=(await J.listTasks({parent_id:G.id,limit:20})).tasks.find((U)=>U.title===W&&Date.now()-new Date(U.created_at).getTime()<60000);if(H)return{task_id:H.id};let B=await J.createTask({title:W,parent_id:G.id,session_id:Y,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 o8($,J){return(await $.listTasks({session_id:J,limit:1})).tasks[0]??null}function u1($){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 P9=`# Roy \u2014 task-first-class-citizen agent
|
|
139
139
|
|
|
140
140
|
You are **Roy**, an agent whose defining rule is simple:
|
|
141
141
|
|
|
@@ -164,6 +164,30 @@ Create the task **before** doing the work. Pass:
|
|
|
164
164
|
- \`project_path\`, \`context\` (JSON string: worktree_path / branch / type \u2026)
|
|
165
165
|
- \`parent_task_id\` when the tree said so
|
|
166
166
|
|
|
167
|
+
#### \u26A0\uFE0F Goals must be numbered sub-items
|
|
168
|
+
\`goals_and_expected_deliverables\` **MUST** be written as **numbered
|
|
169
|
+
sub-items** (\u7F16\u53F7\u5B50\u9879) that can each be verified **one by one**
|
|
170
|
+
(\u9010\u6761\u9A8C\u6536) \u2014 for \`type=normal\` tasks:
|
|
171
|
+
|
|
172
|
+
1. \u5B9E\u73B0 X\uFF08\u542B\u6587\u4EF6\u8DEF\u5F84\uFF09
|
|
173
|
+
2. \u6D4B\u8BD5 Y \u8986\u76D6 Z \u573A\u666F\uFF08pass/fail \u8BA1\u6570\uFF09
|
|
174
|
+
3. \u6587\u6863 W \u843D\u76D8\u5230 <path>
|
|
175
|
+
|
|
176
|
+
Why: the completion hook judges the goal **item by item** against the
|
|
177
|
+
operation-record chain, using each sub-item as fine-grained evidence. A
|
|
178
|
+
vague one-line goal (\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF0C\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D) gives the
|
|
179
|
+
judge nothing to check and reliably triggers a completion hint.
|
|
180
|
+
|
|
181
|
+
Reference the four atomic assertion forms when writing each sub-item:
|
|
182
|
+
- **\u6587\u4EF6\u65AD\u8A00** (file assertion) \u2014 file exists / size / content grep
|
|
183
|
+
- **\u8FDB\u7A0B\u65AD\u8A00** (process assertion) \u2014 command exit code / stdout match
|
|
184
|
+
- **\u6D4B\u8BD5\u65AD\u8A00** (test assertion) \u2014 pass/fail counts, no NEW fail
|
|
185
|
+
- **\u72B6\u6001\u65AD\u8A00** (state assertion) \u2014 version number / HTTP 200 / status field
|
|
186
|
+
|
|
187
|
+
For \`type=longterm\` / \`type=cycle\` tasks there is no per-item completion
|
|
188
|
+
acceptance \u2014 for those, split goals into staged, individually checkable
|
|
189
|
+
sub-items instead of one vague sentence.
|
|
190
|
+
|
|
167
191
|
The tool returns a **numeric task id** \u2014 that number is your handle for the
|
|
168
192
|
rest of the conversation.
|
|
169
193
|
|
|
@@ -176,13 +200,20 @@ Report progress as you go, not only at the end:
|
|
|
176
200
|
If the scope changes, \`task_update\` the description/goals instead of silently
|
|
177
201
|
doing something else.
|
|
178
202
|
|
|
179
|
-
### 4. Record milestones \u2014 \`task_operation_create\`
|
|
203
|
+
### 4. Record milestones \u2014 \`task_operation_create\` \u2014 **as you work**
|
|
204
|
+
Call this tool the moment a stage is reached \u2014 **not after the fact**,
|
|
205
|
+
not in a batch at the end. Finished a chunk of code? A test just went
|
|
206
|
+
green? Hit a blocker? Made a decision? Record it **immediately**, then
|
|
207
|
+
keep working. The record is the running log of the work, written while
|
|
208
|
+
it happens.
|
|
209
|
+
|
|
180
210
|
This tool has **two orthogonal dimensions** and you must keep them distinct:
|
|
181
211
|
- **state / milestone dimension** \u2014 \`milestone_type\` + \`milestone_title\` +
|
|
182
212
|
\`milestone_description\`: *what* was reached (e.g. "GREEN: all tests pass").
|
|
183
213
|
- **process dimension** \u2014 \`process_description\`: *how* you got there \u2014
|
|
184
|
-
|
|
185
|
-
Too short = rejected (no value);
|
|
214
|
+
the operations just performed and why, written in the moment,
|
|
215
|
+
**100\u2013500 characters**. Too short = rejected (no value);
|
|
216
|
+
too long = rejected (that is a log, not a summary).
|
|
186
217
|
|
|
187
218
|
Rules: do **not** use the process field to restate the milestone, and do not
|
|
188
219
|
use milestones as a substitute for progress. Milestones mark *state
|
|
@@ -191,12 +222,32 @@ transitions*: RED\u2192GREEN, blocker found, decision made, review passed.
|
|
|
191
222
|
### 5. Close \u2014 \`task_complete\`
|
|
192
223
|
Before completing:
|
|
193
224
|
1. \`task_get(task_id)\` and re-read goal + delivery.
|
|
194
|
-
2.
|
|
195
|
-
|
|
225
|
+
2. **Accept the goal item-by-item** (\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536): check **each** numbered
|
|
226
|
+
sub-item against the operation-record chain and the deliverable evidence.
|
|
227
|
+
If a sub-item is not met, either extend the task (\`task_update\`) or say
|
|
228
|
+
so honestly.
|
|
196
229
|
3. Call \`task_complete\` with \`deliverable_storage_path\` \u2014 a locator for the
|
|
197
230
|
work product: a file path, a git branch/worktree, a doc URL, a commit URL.
|
|
198
231
|
The path is persisted into the task context and as an operation record.
|
|
199
232
|
|
|
233
|
+
#### \u26A0\uFE0F The completion hint is a verify duty, not a notification
|
|
234
|
+
If the task context carries a \`[TASK_COMPLETION_HINT]\`, you **MUST** verify
|
|
235
|
+
it (\u6838\u5B9E\u4E49\u52A1) \u2014 never ignore it (\u4E0D\u5141\u8BB8\u65E0\u89C6). Re-read the task via
|
|
236
|
+
\`task_get\`, then do **exactly one** of:
|
|
237
|
+
- (a) the goal is **not** met \u2192 \`task_update(task_id=<id>, status=todo)\` to
|
|
238
|
+
reopen and continue the work; or
|
|
239
|
+
- (b) the goal **is** met \u2192 \`task_operation_create\`
|
|
240
|
+
(milestone_type=decision) stating why the sub-items are actually met
|
|
241
|
+
(\u8BF4\u660E\u7406\u7531 \u2014 "state why").
|
|
242
|
+
|
|
243
|
+
#### Several deliverables in one field
|
|
244
|
+
\`deliverable_storage_path\` may name **multiple paths**, space-separated
|
|
245
|
+
(\`/tmp/report.md /tmp/diff.patch\`) \u2014 the judge splits on whitespace as well
|
|
246
|
+
as \`,\` \`;\` \`\u3001\` and \` + \`. A local path may also be written in its
|
|
247
|
+
\`file://\` form (\`file:///tmp/report.md\`) \u2014 the scheme is stripped and the
|
|
248
|
+
path kept. Declare **every** artefact you produced: a path left out reads as
|
|
249
|
+
"not produced" and drags the task toward a false completion hint.
|
|
250
|
+
|
|
200
251
|
\`task_complete\` cannot be used on \`cycle\` tasks (they are periodic by
|
|
201
252
|
design) \u2014 use \`task_update\` to reset those.
|
|
202
253
|
|
|
@@ -222,7 +273,7 @@ if it is not in the task store, it is not tracked.
|
|
|
222
273
|
- Be direct and concrete; the user is reading task titles and milestones.
|
|
223
274
|
- Report the task id and its state whenever you finish a step.
|
|
224
275
|
- If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
|
|
225
|
-
\`problem\` milestone explaining the blocker instead of going silent.`;var X0="roy",u$={action:"execute",resource:"*",effect:"deny"};function l$(){return{id:X0,mode:"primary",description:R2,system:f2,permissions:[{...u$}]}}function PX(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((Y)=>Y.action===$.action&&Y.resource===$.resource&&Y.effect===$.effect))_.permissions.push({...$})}function L2(_){let w=l$();return _.update(X0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;PX($,w.permissions)}),w}var A={};jX(A,{void:()=>U9,util:()=>l,unknown:()=>H9,union:()=>A9,undefined:()=>G9,tuple:()=>f9,transformer:()=>Z9,symbol:()=>W9,string:()=>s$,strictObject:()=>O9,setErrorMap:()=>TX,set:()=>K9,record:()=>L9,quotelessJson:()=>ZX,promise:()=>P9,preprocess:()=>I9,pipeline:()=>k9,ostring:()=>g9,optional:()=>C9,onumber:()=>h9,oboolean:()=>y9,objectUtil:()=>F2,object:()=>V9,number:()=>t$,nullable:()=>T9,null:()=>Q9,never:()=>B9,nativeEnum:()=>S9,nan:()=>Y9,map:()=>F9,makeIssue:()=>Y0,literal:()=>j9,lazy:()=>b9,late:()=>$9,isValid:()=>p_,isDirty:()=>J1,isAsync:()=>jw,isAborted:()=>Y1,intersection:()=>R9,instanceof:()=>X9,getParsedType:()=>Z_,getErrorMap:()=>bw,function:()=>N9,enum:()=>E9,effect:()=>Z9,discriminatedUnion:()=>M9,defaultErrorMap:()=>y_,datetimeRegex:()=>r$,date:()=>D9,custom:()=>o$,coerce:()=>v9,boolean:()=>e$,bigint:()=>J9,array:()=>z9,any:()=>q9,addIssueToContext:()=>S,ZodVoid:()=>D0,ZodUnknown:()=>i_,ZodUnion:()=>Tw,ZodUndefined:()=>Zw,ZodType:()=>x,ZodTuple:()=>T_,ZodTransformer:()=>K_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>W0,ZodReadonly:()=>xw,ZodPromise:()=>Bw,ZodPipeline:()=>q0,ZodParsedType:()=>j,ZodOptional:()=>L_,ZodObject:()=>t,ZodNumber:()=>n_,ZodNullable:()=>x_,ZodNull:()=>Cw,ZodNever:()=>C_,ZodNativeEnum:()=>hw,ZodNaN:()=>Q0,ZodMap:()=>G0,ZodLiteral:()=>gw,ZodLazy:()=>kw,ZodIssueCode:()=>F,ZodIntersection:()=>Iw,ZodFunction:()=>Sw,ZodFirstPartyTypeKind:()=>K,ZodError:()=>D_,ZodEnum:()=>a_,ZodEffects:()=>K_,ZodDiscriminatedUnion:()=>D1,ZodDefault:()=>yw,ZodDate:()=>Qw,ZodCatch:()=>vw,ZodBranded:()=>W1,ZodBoolean:()=>Pw,ZodBigInt:()=>r_,ZodArray:()=>f_,ZodAny:()=>qw,Schema:()=>x,ParseStatus:()=>W_,OK:()=>Q_,NEVER:()=>x9,INVALID:()=>I,EMPTY_PATH:()=>IX,DIRTY:()=>Gw,BRAND:()=>w9});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let D of Y)J[D]=D;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((W)=>typeof Y[Y[W]]!=="number"),D={};for(let W of J)D[W]=Y[W];return _.objectValues(D)},_.objectValues=(Y)=>{return _.objectKeys(Y).map(function(J){return Y[J]})},_.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let J=[];for(let D in Y)if(Object.prototype.hasOwnProperty.call(Y,D))J.push(D);return J},_.find=(Y,J)=>{for(let D of Y)if(J(D))return D;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((D)=>typeof D==="string"?`'${D}'`:D).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var F2;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(F2||(F2={}));var j=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z_=(_)=>{switch(typeof _){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(_)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray(_))return j.array;if(_===null)return j.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return j.promise;if(typeof Map<"u"&&_ instanceof Map)return j.map;if(typeof Set<"u"&&_ instanceof Set)return j.set;if(typeof Date<"u"&&_ instanceof Date)return j.date;return j.object;default:return j.unknown}};var F=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZX=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class D_ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=_}format(_){let w=_||function(Y){return Y.message},$={_errors:[]},X=(Y)=>{for(let J of Y.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)$._errors.push(w(J));else{let D=$,W=0;while(W<J.path.length){let G=J.path[W];if(W!==J.path.length-1)D[G]=D[G]||{_errors:[]};else D[G]=D[G]||{_errors:[]},D[G]._errors.push(w(J));D=D[G],W++}}};return X(this),$}static assert(_){if(!(_ instanceof D_))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(w)=>w.message){let w={},$=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];w[Y]=w[Y]||[],w[Y].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}D_.create=(_)=>{return new D_(_)};var CX=(_,w)=>{let $;switch(_.code){case F.invalid_type:if(_.received===j.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case F.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case F.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case F.invalid_union:$="Invalid input";break;case F.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case F.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case F.invalid_arguments:$="Invalid function arguments";break;case F.invalid_return_type:$="Invalid function return type";break;case F.invalid_date:$="Invalid date";break;case F.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if($=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)$=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)$=`Invalid input: must end with "${_.validation.endsWith}"`;else l.assertNever(_.validation);else if(_.validation!=="regex")$=`Invalid ${_.validation}`;else $="Invalid";break;case F.too_small:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else $="Invalid input";break;case F.too_big:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")$=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else $="Invalid input";break;case F.custom:$="Invalid input";break;case F.invalid_intersection_types:$="Intersection results could not be merged";break;case F.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case F.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},y_=CX;var c$=y_;function TX(_){c$=_}function bw(){return c$}var Y0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],D={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let W="",G=X.filter((Q)=>!!Q).slice().reverse();for(let Q of G)W=Q(D,{data:w,defaultError:W}).message;return{...Y,path:J,message:W}},IX=[];function S(_,w){let $=bw(),X=Y0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===y_?void 0:y_].filter((Y)=>!!Y)});_.common.issues.push(X)}class W_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,w){let $=[];for(let X of w){if(X.status==="aborted")return I;if(X.status==="dirty")_.dirty();$.push(X.value)}return{status:_.value,value:$}}static async mergeObjectAsync(_,w){let $=[];for(let X of w){let Y=await X.key,J=await X.value;$.push({key:Y,value:J})}return W_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:Y,value:J}=X;if(Y.status==="aborted")return I;if(J.status==="aborted")return I;if(Y.status==="dirty")_.dirty();if(J.status==="dirty")_.dirty();if(Y.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))$[Y.value]=J.value}return{status:_.value,value:$}}}var I=Object.freeze({status:"aborted"}),Gw=(_)=>({status:"dirty",value:_}),Q_=(_)=>({status:"valid",value:_}),Y1=(_)=>_.status==="aborted",J1=(_)=>_.status==="dirty",p_=(_)=>_.status==="valid",jw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var T;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(T||(T={}));class F_{constructor(_,w,$,X){this._cachedPath=[],this.parent=_,this.data=w,this._path=$,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var d$=(_,w)=>{if(p_(w))return{success:!0,data:w.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new D_(_.common.issues);return this._error=$,this._error}}}};function g(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:Y}=_;if(w&&($||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:Y};return{errorMap:(D,W)=>{let{message:G}=_;if(D.code==="invalid_enum_value")return{message:G??W.defaultError};if(typeof W.data>"u")return{message:G??X??W.defaultError};if(D.code!=="invalid_type")return{message:W.defaultError};return{message:G??$??W.defaultError}},description:Y}}class x{get description(){return this._def.description}_getType(_){return Z_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new W_,ctx:{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(jw(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync(_){let w=this._parse(_);return Promise.resolve(w)}parse(_,w){let $=this.safeParse(_,w);if($.success)return $.data;throw $.error}safeParse(_,w){let $={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return d$($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return p_($)?{value:$.value}:{issues:w.common.issues}}catch($){if($?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:w}).then(($)=>p_($)?{value:$.value}:{issues:w.common.issues})}async parseAsync(_,w){let $=await this.safeParseAsync(_,w);if($.success)return $.data;throw $.error}async safeParseAsync(_,w){let $={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parse({data:_,path:$.path,parent:$}),Y=await(jw(X)?X:Promise.resolve(X));return d$($,Y)}refine(_,w){let $=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,Y)=>{let J=_(X),D=()=>Y.addIssue({code:F.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((W)=>{if(!W)return D(),!1;else return!0});if(!J)return D(),!1;else return!0})}refinement(_,w){return this._refinement(($,X)=>{if(!_($))return X.addIssue(typeof w==="function"?w($,X):w),!1;else return!0})}_refinement(_){return new K_({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(w)=>this["~validate"](w)}}optional(){return L_.create(this,this._def)}nullable(){return x_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f_.create(this)}promise(){return Bw.create(this,this._def)}or(_){return Tw.create([this,_],this._def)}and(_){return Iw.create(this,_,this._def)}transform(_){return new K_({...g(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new yw({...g(this._def),innerType:this,defaultValue:w,typeName:K.ZodDefault})}brand(){return new W1({typeName:K.ZodBranded,type:this,...g(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new vw({...g(this._def),innerType:this,catchValue:w,typeName:K.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return q0.create(this,_)}readonly(){return xw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var kX=/^c[^\s-]{8,}$/i,gX=/^[0-9a-z]+$/,hX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vX=/^[a-z0-9_-]{21}$/i,xX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mX=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,uX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K2,cX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,dX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,pX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i$="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aX=new RegExp(`^${i$}$`);function n$(_){let w="[0-5]\\d";if(_.precision)w=`${w}\\.\\d{${_.precision}}`;else if(_.precision==null)w=`${w}(\\.\\d+)?`;let $=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${$}`}function oX(_){return new RegExp(`^${n$(_)}$`)}function r$(_){let w=`${i$}T${n$(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function sX(_,w){if((w==="v4"||!w)&&cX.test(_))return!0;if((w==="v6"||!w)&&pX.test(_))return!0;return!1}function tX(_,w){if(!xX.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(w&&Y.alg!==w)return!1;return!0}catch{return!1}}function eX(_,w){if((w==="v4"||!w)&&dX.test(_))return!0;if((w==="v6"||!w)&&iX.test(_))return!0;return!1}class R_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==j.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.string,received:Y.parsedType}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.length<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="max"){if(_.data.length>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="length"){let J=_.data.length>Y.value,D=_.data.length<Y.value;if(J||D){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(D)S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!uX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!K2)K2=new RegExp(lX,"u");if(!K2.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!yX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!vX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!kX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!gX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!hX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),S(X,{validation:"url",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"regex",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="trim")_.data=_.data.trim();else if(Y.kind==="includes"){if(!_.data.includes(Y.value,Y.position))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),$.dirty()}else if(Y.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(Y.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(Y.kind==="startsWith"){if(!_.data.startsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{startsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="endsWith"){if(!_.data.endsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!r$(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!aX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!oX(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!mX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!sX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!tX(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!eX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!nX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!rX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:F.invalid_string,message:Y.message}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:F.invalid_string,...T.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...T.errToObj(_)})}url(_){return this._addCheck({kind:"url",...T.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...T.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...T.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...T.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...T.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...T.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...T.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...T.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...T.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...T.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...T.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...T.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...T.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...T.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...T.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...T.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...T.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...T.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...T.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...T.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...T.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...T.errToObj(w)})}nonempty(_){return this.min(1,T.errToObj(_))}trim(){return new R_({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxLength(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}R_.create=(_)=>{return new R_({checks:[],typeName:K.ZodString,coerce:_?.coerce??!1,...g(_)})};function _9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),D=Number.parseInt(w.toFixed(Y).replace(".",""));return J%D/10**Y}class n_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==j.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.number,received:Y.parsedType}),I}let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_9(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new n_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new n_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:T.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:T.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(_)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&l.isInteger(_.value))}get isFinite(){let _=null,w=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(w===null||$.value>w)w=$.value}else if($.kind==="max"){if(_===null||$.value<_)_=$.value}return Number.isFinite(w)&&Number.isFinite(_)}}n_.create=(_)=>{return new n_({checks:[],typeName:K.ZodNumber,coerce:_?.coerce||!1,...g(_)})};class r_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==j.bigint)return this._getInvalidInput(_);let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_.data%Y.value!==BigInt(0))$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.bigint,received:w.parsedType}),I}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new r_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new r_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}r_.create=(_)=>{return new r_({checks:[],typeName:K.ZodBigInt,coerce:_?.coerce??!1,...g(_)})};class Pw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==j.boolean){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.boolean,received:$.parsedType}),I}return Q_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:K.ZodBoolean,coerce:_?.coerce||!1,...g(_)})};class Qw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==j.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.date,received:Y.parsedType}),I}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_date}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.getTime()<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),$.dirty()}else if(Y.kind==="max"){if(_.data.getTime()>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new Qw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:T.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:T.toString(w)})}get minDate(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _!=null?new Date(_):null}}Qw.create=(_)=>{return new Qw({checks:[],coerce:_?.coerce||!1,typeName:K.ZodDate,...g(_)})};class J0 extends x{_parse(_){if(this._getType(_)!==j.symbol){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.symbol,received:$.parsedType}),I}return Q_(_.data)}}J0.create=(_)=>{return new J0({typeName:K.ZodSymbol,...g(_)})};class Zw extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.undefined,received:$.parsedType}),I}return Q_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:K.ZodUndefined,...g(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==j.null){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.null,received:$.parsedType}),I}return Q_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:K.ZodNull,...g(_)})};class qw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return Q_(_.data)}}qw.create=(_)=>{return new qw({typeName:K.ZodAny,...g(_)})};class i_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return Q_(_.data)}}i_.create=(_)=>{return new i_({typeName:K.ZodUnknown,...g(_)})};class C_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.never,received:w.parsedType}),I}}C_.create=(_)=>{return new C_({typeName:K.ZodNever,...g(_)})};class D0 extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.void,received:$.parsedType}),I}return Q_(_.data)}}D0.create=(_)=>{return new D0({typeName:K.ZodVoid,...g(_)})};class f_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==j.array)return S(w,{code:F.invalid_type,expected:j.array,received:w.parsedType}),I;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,D=w.data.length<X.exactLength.value;if(J||D)S(w,{code:J?F.too_big:F.too_small,minimum:D?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),$.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)S(w,{code:F.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),$.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)S(w,{code:F.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),$.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,D)=>{return X.type._parseAsync(new F_(w,J,w.path,D))})).then((J)=>{return W_.mergeArray($,J)});let Y=[...w.data].map((J,D)=>{return X.type._parseSync(new F_(w,J,w.path,D))});return W_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new f_({...this._def,minLength:{value:_,message:T.toString(w)}})}max(_,w){return new f_({...this._def,maxLength:{value:_,message:T.toString(w)}})}length(_,w){return new f_({...this._def,exactLength:{value:_,message:T.toString(w)}})}nonempty(_){return this.min(1,_)}}f_.create=(_,w)=>{return new f_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...g(w)})};function Ew(_){if(_ instanceof t){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=L_.create(Ew(X))}return new t({..._._def,shape:()=>w})}else if(_ instanceof f_)return new f_({..._._def,type:Ew(_.element)});else if(_ instanceof L_)return L_.create(Ew(_.unwrap()));else if(_ instanceof x_)return x_.create(Ew(_.unwrap()));else if(_ instanceof T_)return T_.create(_.items.map((w)=>Ew(w)));else return _}class t extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),w=l.objectKeys(_);return this._cached={shape:_,keys:w},this._cached}_parse(_){if(this._getType(_)!==j.object){let G=this._getOrReturnCtx(_);return S(G,{code:F.invalid_type,expected:j.object,received:G.parsedType}),I}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),D=[];if(!(this._def.catchall instanceof C_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))D.push(G)}let W=[];for(let G of J){let Q=Y[G],q=X.data[G];W.push({key:{status:"valid",value:G},value:Q._parse(new F_(X,q,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof C_){let G=this._def.unknownKeys;if(G==="passthrough")for(let Q of D)W.push({key:{status:"valid",value:Q},value:{status:"valid",value:X.data[Q]}});else if(G==="strict"){if(D.length>0)S(X,{code:F.unrecognized_keys,keys:D}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let Q of D){let q=X.data[Q];W.push({key:{status:"valid",value:Q},value:G._parse(new F_(X,q,X.path,Q)),alwaysSet:Q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let Q of W){let q=await Q.key,H=await Q.value;G.push({key:q,value:H,alwaysSet:Q.alwaysSet})}return G}).then((G)=>{return W_.mergeObjectSync($,G)});else return W_.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(_){return T.errToObj,new t({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message:T.errToObj(_).message??X};return{message:X}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(_){return new t({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new t({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:K.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new t({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}deepPartial(){return Ew(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new t({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let Y=this.shape[$];while(Y instanceof L_)Y=Y._def.innerType;w[$]=Y}return new t({...this._def,shape:()=>w})}keyof(){return a$(l.objectKeys(this.shape))}}t.create=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.strictCreate=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strict",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.lazycreate=(_,w)=>{return new t({shape:_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};class Tw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(Y){for(let D of Y)if(D.result.status==="valid")return D.result;for(let D of Y)if(D.result.status==="dirty")return w.common.issues.push(...D.ctx.common.issues),D.result;let J=Y.map((D)=>new D_(D.ctx.common.issues));return S(w,{code:F.invalid_union,unionErrors:J}),I}if(w.common.async)return Promise.all($.map(async(Y)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let Y=void 0,J=[];for(let W of $){let G={...w,common:{...w.common,issues:[]},parent:null},Q=W._parseSync({data:w.data,path:w.path,parent:G});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!Y)Y={result:Q,ctx:G};if(G.common.issues.length)J.push(G.common.issues)}if(Y)return w.common.issues.push(...Y.ctx.common.issues),Y.result;let D=J.map((W)=>new D_(W));return S(w,{code:F.invalid_union,unionErrors:D}),I}}get options(){return this._def.options}}Tw.create=(_,w)=>{return new Tw({options:_,typeName:K.ZodUnion,...g(w)})};var v_=(_)=>{if(_ instanceof kw)return v_(_.schema);else if(_ instanceof K_)return v_(_.innerType());else if(_ instanceof gw)return[_.value];else if(_ instanceof a_)return _.options;else if(_ instanceof hw)return l.objectValues(_.enum);else if(_ instanceof yw)return v_(_._def.innerType);else if(_ instanceof Zw)return[void 0];else if(_ instanceof Cw)return[null];else if(_ instanceof L_)return[void 0,...v_(_.unwrap())];else if(_ instanceof x_)return[null,...v_(_.unwrap())];else if(_ instanceof W1)return v_(_.unwrap());else if(_ instanceof xw)return v_(_.unwrap());else if(_ instanceof vw)return v_(_._def.innerType);else return[]};class D1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.object)return S(w,{code:F.invalid_type,expected:j.object,received:w.parsedType}),I;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:F.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),I;if(w.common.async)return Y._parseAsync({data:w.data,path:w.path,parent:w});else return Y._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,w,$){let X=new Map;for(let Y of w){let J=v_(Y.shape[_]);if(!J.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let D of J){if(X.has(D))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(D)}`);X.set(D,Y)}}return new D1({typeName:K.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...g($)})}}function N2(_,w){let $=Z_(_),X=Z_(w);if(_===w)return{valid:!0,data:_};else if($===j.object&&X===j.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((W)=>Y.indexOf(W)!==-1),D={..._,...w};for(let W of J){let G=N2(_[W],w[W]);if(!G.valid)return{valid:!1};D[W]=G.data}return{valid:!0,data:D}}else if($===j.array&&X===j.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let D=_[J],W=w[J],G=N2(D,W);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===j.date&&X===j.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class Iw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(Y,J)=>{if(Y1(Y)||Y1(J))return I;let D=N2(Y.value,J.value);if(!D.valid)return S($,{code:F.invalid_intersection_types}),I;if(J1(Y)||J1(J))w.dirty();return{status:w.value,value:D.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([Y,J])=>X(Y,J));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}Iw.create=(_,w,$)=>{return new Iw({left:_,right:w,typeName:K.ZodIntersection,...g($)})};class T_ extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.array)return S($,{code:F.invalid_type,expected:j.array,received:$.parsedType}),I;if($.data.length<this._def.items.length)return S($,{code:F.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&$.data.length>this._def.items.length)S($,{code:F.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,D)=>{let W=this._def.items[D]||this._def.rest;if(!W)return null;return W._parse(new F_($,J,$.path,D))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return W_.mergeArray(w,J)});else return W_.mergeArray(w,Y)}get items(){return this._def.items}rest(_){return new T_({...this._def,rest:_})}}T_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new T_({items:_,typeName:K.ZodTuple,rest:null,...g(w)})};class W0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.object)return S($,{code:F.invalid_type,expected:j.object,received:$.parsedType}),I;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let D in $.data)X.push({key:Y._parse(new F_($,D,$.path,D)),value:J._parse(new F_($,$.data[D],$.path,D)),alwaysSet:D in $.data});if($.common.async)return W_.mergeObjectAsync(w,X);else return W_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new W0({keyType:_,valueType:w,typeName:K.ZodRecord,...g($)});return new W0({keyType:R_.create(),valueType:_,typeName:K.ZodRecord,...g(w)})}}class G0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.map)return S($,{code:F.invalid_type,expected:j.map,received:$.parsedType}),I;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([D,W],G)=>{return{key:X._parse(new F_($,D,$.path,[G,"key"])),value:Y._parse(new F_($,W,$.path,[G,"value"]))}});if($.common.async){let D=new Map;return Promise.resolve().then(async()=>{for(let W of J){let G=await W.key,Q=await W.value;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}})}else{let D=new Map;for(let W of J){let{key:G,value:Q}=W;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}}}}G0.create=(_,w,$)=>{return new G0({valueType:w,keyType:_,typeName:K.ZodMap,...g($)})};class Hw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.set)return S($,{code:F.invalid_type,expected:j.set,received:$.parsedType}),I;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:F.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if($.data.size>X.maxSize.value)S($,{code:F.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let Y=this._def.valueType;function J(W){let G=new Set;for(let Q of W){if(Q.status==="aborted")return I;if(Q.status==="dirty")w.dirty();G.add(Q.value)}return{status:w.value,value:G}}let D=[...$.data.values()].map((W,G)=>Y._parse(new F_($,W,$.path,G)));if($.common.async)return Promise.all(D).then((W)=>J(W));else return J(D)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:T.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:T.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Hw.create=(_,w)=>{return new Hw({valueType:_,minSize:null,maxSize:null,typeName:K.ZodSet,...g(w)})};class Sw extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.function)return S(w,{code:F.invalid_type,expected:j.function,received:w.parsedType}),I;function $(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_arguments,argumentsError:W}})}function X(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_return_type,returnTypeError:W}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Bw){let D=this;return Q_(async function(...W){let G=new D_([]),Q=await D._def.args.parseAsync(W,Y).catch((B)=>{throw G.addIssue($(W,B)),G}),q=await Reflect.apply(J,this,Q);return await D._def.returns._def.type.parseAsync(q,Y).catch((B)=>{throw G.addIssue(X(q,B)),G})})}else{let D=this;return Q_(function(...W){let G=D._def.args.safeParse(W,Y);if(!G.success)throw new D_([$(W,G.error)]);let Q=Reflect.apply(J,this,G.data),q=D._def.returns.safeParse(Q,Y);if(!q.success)throw new D_([X(Q,q.error)]);return q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Sw({...this._def,args:T_.create(_).rest(i_.create())})}returns(_){return new Sw({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Sw({args:_?_:T_.create([]).rest(i_.create()),returns:w||i_.create(),typeName:K.ZodFunction,...g($)})}}class kw extends x{get schema(){return this._def.getter()}_parse(_){let{ctx:w}=this._processInputParams(_);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}}kw.create=(_,w)=>{return new kw({getter:_,typeName:K.ZodLazy,...g(w)})};class gw extends x{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return S(w,{received:w.data,code:F.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:_.data}}get value(){return this._def.value}}gw.create=(_,w)=>{return new gw({value:_,typeName:K.ZodLiteral,...g(w)})};function a$(_,w){return new a_({values:_,typeName:K.ZodEnum,...g(w)})}class a_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{received:w.data,code:F.invalid_enum_value,options:$}),I}return Q_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let w of this._def.values)_[w]=w;return _}get Values(){let _={};for(let w of this._def.values)_[w]=w;return _}get Enum(){let _={};for(let w of this._def.values)_[w]=w;return _}extract(_,w=this._def){return a_.create(_,{...this._def,...w})}exclude(_,w=this._def){return a_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}a_.create=a$;class hw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==j.string&&$.parsedType!==j.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:F.invalid_enum_value,options:X}),I}return Q_(_.data)}get enum(){return this._def.values}}hw.create=(_,w)=>{return new hw({values:_,typeName:K.ZodNativeEnum,...g(w)})};class Bw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.promise&&w.common.async===!1)return S(w,{code:F.invalid_type,expected:j.promise,received:w.parsedType}),I;let $=w.parsedType===j.promise?w.data:Promise.resolve(w.data);return Q_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Bw.create=(_,w)=>{return new Bw({type:_,typeName:K.ZodPromise,...g(w)})};class K_ extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=this._def.effect||null,Y={addIssue:(J)=>{if(S($,J),J.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let J=X.transform($.data,Y);if($.common.async)return Promise.resolve(J).then(async(D)=>{if(w.value==="aborted")return I;let W=await this._def.schema._parseAsync({data:D,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")return Gw(W.value);if(w.value==="dirty")return Gw(W.value);return W});else{if(w.value==="aborted")return I;let D=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")return Gw(D.value);if(w.value==="dirty")return Gw(D.value);return D}}if(X.type==="refinement"){let J=(D)=>{let W=X.refinement(D,Y);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return D};if($.common.async===!1){let D=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value),{status:w.value,value:D.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((D)=>{if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value).then(()=>{return{status:w.value,value:D.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!p_(J))return I;let D=X.transform(J.value,Y);if(D instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:D}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!p_(J))return I;return Promise.resolve(X.transform(J.value,Y)).then((D)=>({status:w.value,value:D}))});l.assertNever(X)}}K_.create=(_,w,$)=>{return new K_({schema:_,typeName:K.ZodEffects,effect:w,...g($)})};K_.createWithPreprocess=(_,w,$)=>{return new K_({schema:w,effect:{type:"preprocess",transform:_},typeName:K.ZodEffects,...g($)})};class L_ extends x{_parse(_){if(this._getType(_)===j.undefined)return Q_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}L_.create=(_,w)=>{return new L_({innerType:_,typeName:K.ZodOptional,...g(w)})};class x_ extends x{_parse(_){if(this._getType(_)===j.null)return Q_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}x_.create=(_,w)=>{return new x_({innerType:_,typeName:K.ZodNullable,...g(w)})};class yw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===j.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}yw.create=(_,w)=>{return new yw({innerType:_,typeName:K.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...g(w)})};class vw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(jw(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:K.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...g(w)})};class Q0 extends x{_parse(_){if(this._getType(_)!==j.nan){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.nan,received:$.parsedType}),I}return{status:"valid",value:_.data}}}Q0.create=(_)=>{return new Q0({typeName:K.ZodNaN,...g(_)})};var w9=Symbol("zod_brand");class W1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;return this._def.type._parse({data:$,path:w.path,parent:w})}unwrap(){return this._def.type}}class q0 extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(Y.status==="aborted")return I;if(Y.status==="dirty")return w.dirty(),Gw(Y.value);else return this._def.out._parseAsync({data:Y.value,path:$.path,parent:$})})();else{let X=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(X.status==="aborted")return I;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:$.path,parent:$})}}static create(_,w){return new q0({in:_,out:w,typeName:K.ZodPipeline})}}class xw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(p_(X))X.value=Object.freeze(X.value);return X};return jw(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}xw.create=(_,w)=>{return new xw({innerType:_,typeName:K.ZodReadonly,...g(w)})};function p$(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function o$(_,w={},$){if(_)return qw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((D)=>{if(!D){let W=p$(w,X),G=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:G})}});if(!J){let D=p$(w,X),W=D.fatal??$??!0;Y.addIssue({code:"custom",...D,fatal:W})}return});return qw.create()}var $9={object:t.lazycreate},K;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(K||(K={}));var X9=(_,w={message:`Input not instance of ${_.name}`})=>o$(($)=>$ instanceof _,w),s$=R_.create,t$=n_.create,Y9=Q0.create,J9=r_.create,e$=Pw.create,D9=Qw.create,W9=J0.create,G9=Zw.create,Q9=Cw.create,q9=qw.create,H9=i_.create,B9=C_.create,U9=D0.create,z9=f_.create,V9=t.create,O9=t.strictCreate,A9=Tw.create,M9=D1.create,R9=Iw.create,f9=T_.create,L9=W0.create,F9=G0.create,K9=Hw.create,N9=Sw.create,b9=kw.create,j9=gw.create,E9=a_.create,S9=hw.create,P9=Bw.create,Z9=K_.create,C9=L_.create,T9=x_.create,I9=K_.createWithPreprocess,k9=q0.create,g9=()=>s$().optional(),h9=()=>t$().optional(),y9=()=>e$().optional(),v9={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>n_.create({..._,coerce:!0}),boolean:(_)=>Pw.create({..._,coerce:!0}),bigint:(_)=>r_.create({..._,coerce:!0}),date:(_)=>Qw.create({..._,coerce:!0})};var x9=I;var b2=A.object({bgProcessId:A.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function m9(_){return{alive:_.status==="pending"||_.status==="running",status:_.status,createdAt:_.createdAt,lastUpdatedAt:_.lastUpdatedAt??_.completedAt??_.startedAt??_.createdAt,description:_.description,..._.result!==void 0?{result:_.result}:{},..._.error!==void 0?{error:_.error}:{}}}function _4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var EV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
276
|
+
\`problem\` milestone explaining the blocker instead of going silent.`;var w9="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.",b9=P9;var G2="roy",t8={action:"execute",resource:"*",effect:"deny"};function e8(){return{id:G2,mode:"primary",description:w9,system:b9,permissions:[{...t8}]}}function l1($,J){if(!Array.isArray($.permissions))$.permissions=[];for(let Q of J)if(!$.permissions.some((Y)=>Y.action===Q.action&&Y.resource===Q.resource&&Y.effect===Q.effect))$.permissions.push({...Q})}function E9($){let J=e8();return $.update(G2,(Q)=>{if(Q.mode=J.mode,Q.description=J.description,Q.system=J.system,Q.hidden===void 0)Q.hidden=!1;l1(Q,J.permissions)}),J}var K={};k1(K,{void:()=>wQ,util:()=>l,unknown:()=>ZQ,union:()=>CQ,undefined:()=>AQ,tuple:()=>TQ,transformer:()=>cQ,symbol:()=>RQ,string:()=>H7,strictObject:()=>SQ,setErrorMap:()=>d1,set:()=>hQ,record:()=>vQ,quotelessJson:()=>c1,promise:()=>lQ,preprocess:()=>iQ,pipeline:()=>nQ,ostring:()=>rQ,optional:()=>pQ,onumber:()=>aQ,oboolean:()=>sQ,objectUtil:()=>S9,object:()=>EQ,number:()=>B7,nullable:()=>dQ,null:()=>NQ,never:()=>PQ,nativeEnum:()=>uQ,nan:()=>KQ,map:()=>xQ,makeIssue:()=>W2,literal:()=>kQ,lazy:()=>gQ,late:()=>MQ,isValid:()=>i0,isDirty:()=>B6,isAsync:()=>b$,isAborted:()=>H6,intersection:()=>IQ,instanceof:()=>FQ,getParsedType:()=>I0,getErrorMap:()=>w$,function:()=>yQ,enum:()=>mQ,effect:()=>cQ,discriminatedUnion:()=>fQ,defaultErrorMap:()=>k0,datetimeRegex:()=>G7,date:()=>LQ,custom:()=>q7,coerce:()=>oQ,boolean:()=>U7,bigint:()=>_Q,array:()=>bQ,any:()=>jQ,addIssueToContext:()=>E,ZodVoid:()=>H2,ZodUnknown:()=>n0,ZodUnion:()=>T$,ZodUndefined:()=>f$,ZodType:()=>k,ZodTuple:()=>v0,ZodTransformer:()=>P0,ZodSymbol:()=>q2,ZodString:()=>A0,ZodSet:()=>z$,ZodSchema:()=>k,ZodRecord:()=>B2,ZodReadonly:()=>m$,ZodPromise:()=>D$,ZodPipeline:()=>z2,ZodParsedType:()=>w,ZodOptional:()=>j0,ZodObject:()=>t,ZodNumber:()=>r0,ZodNullable:()=>u0,ZodNull:()=>I$,ZodNever:()=>T0,ZodNativeEnum:()=>y$,ZodNaN:()=>V2,ZodMap:()=>U2,ZodLiteral:()=>h$,ZodLazy:()=>x$,ZodIssueCode:()=>R,ZodIntersection:()=>v$,ZodFunction:()=>S$,ZodFirstPartyTypeKind:()=>N,ZodError:()=>W0,ZodEnum:()=>s0,ZodEffects:()=>P0,ZodDiscriminatedUnion:()=>U6,ZodDefault:()=>g$,ZodDate:()=>U$,ZodCatch:()=>k$,ZodBranded:()=>V6,ZodBoolean:()=>C$,ZodBigInt:()=>a0,ZodArray:()=>N0,ZodAny:()=>V$,Schema:()=>k,ParseStatus:()=>q0,OK:()=>B0,NEVER:()=>tQ,INVALID:()=>T,EMPTY_PATH:()=>i1,DIRTY:()=>B$,BRAND:()=>OQ});var l;(function($){$.assertEqual=(Y)=>{};function J(Y){}$.assertIs=J;function Q(Y){throw Error()}$.assertNever=Q,$.arrayToEnum=(Y)=>{let G={};for(let W of Y)G[W]=W;return G},$.getValidEnumValues=(Y)=>{let G=$.objectKeys(Y).filter((q)=>typeof Y[Y[q]]!=="number"),W={};for(let q of G)W[q]=Y[q];return $.objectValues(W)},$.objectValues=(Y)=>{return $.objectKeys(Y).map(function(G){return Y[G]})},$.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let G=[];for(let W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))G.push(W);return G},$.find=(Y,G)=>{for(let W of Y)if(G(W))return W;return},$.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,G=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(G)}$.joinValues=X,$.jsonStringifyReplacer=(Y,G)=>{if(typeof G==="bigint")return G.toString();return G}})(l||(l={}));var S9;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(S9||(S9={}));var w=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I0=($)=>{switch(typeof $){case"undefined":return w.undefined;case"string":return w.string;case"number":return Number.isNaN($)?w.nan:w.number;case"boolean":return w.boolean;case"function":return w.function;case"bigint":return w.bigint;case"symbol":return w.symbol;case"object":if(Array.isArray($))return w.array;if($===null)return w.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return w.promise;if(typeof Map<"u"&&$ instanceof Map)return w.map;if(typeof Set<"u"&&$ instanceof Set)return w.set;if(typeof Date<"u"&&$ instanceof Date)return w.date;return w.object;default:return w.unknown}};var R=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"]),c1=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class W0 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(Y){return Y.message},Q={_errors:[]},X=(Y)=>{for(let G of Y.issues)if(G.code==="invalid_union")G.unionErrors.map(X);else if(G.code==="invalid_return_type")X(G.returnTypeError);else if(G.code==="invalid_arguments")X(G.argumentsError);else if(G.path.length===0)Q._errors.push(J(G));else{let W=Q,q=0;while(q<G.path.length){let H=G.path[q];if(q!==G.path.length-1)W[H]=W[H]||{_errors:[]};else W[H]=W[H]||{_errors:[]},W[H]._errors.push(J(G));W=W[H],q++}}};return X(this),Q}static assert($){if(!($ instanceof W0))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(J)=>J.message){let J={},Q=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];J[Y]=J[Y]||[],J[Y].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}W0.create=($)=>{return new W0($)};var p1=($,J)=>{let Q;switch($.code){case R.invalid_type:if($.received===w.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case R.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case R.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case R.invalid_union:Q="Invalid input";break;case R.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case R.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case R.invalid_arguments:Q="Invalid function arguments";break;case R.invalid_return_type:Q="Invalid function return type";break;case R.invalid_date:Q="Invalid date";break;case R.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 R.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 R.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 R.custom:Q="Invalid input";break;case R.invalid_intersection_types:Q="Intersection results could not be merged";break;case R.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case R.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},k0=p1;var $7=k0;function d1($){$7=$}function w$(){return $7}var W2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:Y}=$,G=[...Q,...Y.path||[]],W={...Y,path:G};if(Y.message!==void 0)return{...Y,path:G,message:Y.message};let q="",H=X.filter((B)=>!!B).slice().reverse();for(let B of H)q=B(W,{data:J,defaultError:q}).message;return{...Y,path:G,message:q}},i1=[];function E($,J){let Q=w$(),X=W2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===k0?void 0:k0].filter((Y)=>!!Y)});$.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 T;if(X.status==="dirty")$.dirty();Q.push(X.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,J){let Q=[];for(let X of J){let Y=await X.key,G=await X.value;Q.push({key:Y,value:G})}return q0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:Y,value:G}=X;if(Y.status==="aborted")return T;if(G.status==="aborted")return T;if(Y.status==="dirty")$.dirty();if(G.status==="dirty")$.dirty();if(Y.value!=="__proto__"&&(typeof G.value<"u"||X.alwaysSet))Q[Y.value]=G.value}return{status:$.value,value:Q}}}var T=Object.freeze({status:"aborted"}),B$=($)=>({status:"dirty",value:$}),B0=($)=>({status:"valid",value:$}),H6=($)=>$.status==="aborted",B6=($)=>$.status==="dirty",i0=($)=>$.status==="valid",b$=($)=>typeof Promise<"u"&&$ instanceof Promise;var I;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(I||(I={}));class Z0{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 J7=($,J)=>{if(i0(J))return{success:!0,data:J.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let Q=new W0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:Y}=$;if(J&&(Q||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:Y};return{errorMap:(W,q)=>{let{message:H}=$;if(W.code==="invalid_enum_value")return{message:H??q.defaultError};if(typeof q.data>"u")return{message:H??X??q.defaultError};if(W.code!=="invalid_type")return{message:q.defaultError};return{message:H??Q??q.defaultError}},description:Y}}class k{get description(){return this._def.description}_getType($){return I0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new q0,ctx:{common:$.parent.common,data:$.data,parsedType:I0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(b$(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let Q=this.safeParse($,J);if(Q.success)return Q.data;throw Q.error}safeParse($,J){let Q={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return J7(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return i0(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)=>i0(Q)?{value:Q.value}:{issues:J.common.issues})}async parseAsync($,J){let Q=await this.safeParseAsync($,J);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,J){let Q={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:I0($)},X=this._parse({data:$,path:Q.path,parent:Q}),Y=await(b$(X)?X:Promise.resolve(X));return J7(Q,Y)}refine($,J){let Q=(X)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(X);else return J};return this._refinement((X,Y)=>{let G=$(X),W=()=>Y.addIssue({code:R.custom,...Q(X)});if(typeof Promise<"u"&&G instanceof Promise)return G.then((q)=>{if(!q)return W(),!1;else return!0});if(!G)return W(),!1;else return!0})}refinement($,J){return this._refinement((Q,X)=>{if(!$(Q))return X.addIssue(typeof J==="function"?J(Q,X):J),!1;else return!0})}_refinement($){return new P0({schema:this,typeName:N.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 j0.create(this,this._def)}nullable(){return u0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return N0.create(this)}promise(){return D$.create(this,this._def)}or($){return T$.create([this,$],this._def)}and($){return v$.create(this,$,this._def)}transform($){return new P0({...h(this._def),schema:this,typeName:N.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new g$({...h(this._def),innerType:this,defaultValue:J,typeName:N.ZodDefault})}brand(){return new V6({typeName:N.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new k$({...h(this._def),innerType:this,catchValue:J,typeName:N.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return z2.create(this,$)}readonly(){return m$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var n1=/^c[^\s-]{8,}$/i,r1=/^[0-9a-z]+$/,a1=/^[0-9A-HJKMNP-TV-Z]{26}$/i,s1=/^[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,o1=/^[a-z0-9_-]{21}$/i,t1=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e1=/^[-+]?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)?)??$/,$Q=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,JQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",C9,QQ=/^(?:(?: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])$/,XQ=/^(?:(?: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])$/,YQ=/^(([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]))$/,GQ=/^(([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])$/,WQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,qQ=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,X7="((\\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])))",HQ=new RegExp(`^${X7}$`);function Y7($){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 BQ($){return new RegExp(`^${Y7($)}$`)}function G7($){let J=`${X7}T${Y7($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function UQ($,J){if((J==="v4"||!J)&&QQ.test($))return!0;if((J==="v6"||!J)&&YQ.test($))return!0;return!1}function VQ($,J){if(!t1.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let X=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(J&&Y.alg!==J)return!1;return!0}catch{return!1}}function zQ($,J){if((J==="v4"||!J)&&XQ.test($))return!0;if((J==="v6"||!J)&&GQ.test($))return!0;return!1}class A0 extends k{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==w.string){let Y=this._getOrReturnCtx($);return E(Y,{code:R.invalid_type,expected:w.string,received:Y.parsedType}),T}let Q=new q0,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.length<Y.value)X=this._getOrReturnCtx($,X),E(X,{code:R.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="max"){if($.data.length>Y.value)X=this._getOrReturnCtx($,X),E(X,{code:R.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),Q.dirty()}else if(Y.kind==="length"){let G=$.data.length>Y.value,W=$.data.length<Y.value;if(G||W){if(X=this._getOrReturnCtx($,X),G)E(X,{code:R.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)E(X,{code:R.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});Q.dirty()}}else if(Y.kind==="email"){if(!$Q.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"email",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="emoji"){if(!C9)C9=new RegExp(JQ,"u");if(!C9.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"emoji",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="uuid"){if(!s1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"uuid",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="nanoid"){if(!o1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"nanoid",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cuid"){if(!n1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cuid2"){if(!r1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"cuid2",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="ulid"){if(!a1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"ulid",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),E(X,{validation:"url",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"regex",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="trim")$.data=$.data.trim();else if(Y.kind==="includes"){if(!$.data.includes(Y.value,Y.position))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),Q.dirty()}else if(Y.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(Y.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(Y.kind==="startsWith"){if(!$.data.startsWith(Y.value))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:{startsWith:Y.value},message:Y.message}),Q.dirty()}else if(Y.kind==="endsWith"){if(!$.data.endsWith(Y.value))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:{endsWith:Y.value},message:Y.message}),Q.dirty()}else if(Y.kind==="datetime"){if(!G7(Y).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:"datetime",message:Y.message}),Q.dirty()}else if(Y.kind==="date"){if(!HQ.test($.data))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:"date",message:Y.message}),Q.dirty()}else if(Y.kind==="time"){if(!BQ(Y).test($.data))X=this._getOrReturnCtx($,X),E(X,{code:R.invalid_string,validation:"time",message:Y.message}),Q.dirty()}else if(Y.kind==="duration"){if(!e1.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"duration",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="ip"){if(!UQ($.data,Y.version))X=this._getOrReturnCtx($,X),E(X,{validation:"ip",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="jwt"){if(!VQ($.data,Y.alg))X=this._getOrReturnCtx($,X),E(X,{validation:"jwt",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="cidr"){if(!zQ($.data,Y.version))X=this._getOrReturnCtx($,X),E(X,{validation:"cidr",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="base64"){if(!WQ.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64",code:R.invalid_string,message:Y.message}),Q.dirty()}else if(Y.kind==="base64url"){if(!qQ.test($.data))X=this._getOrReturnCtx($,X),E(X,{validation:"base64url",code:R.invalid_string,message:Y.message}),Q.dirty()}else l.assertNever(Y);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:R.invalid_string,...I.errToObj(Q)})}_addCheck($){return new A0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...I.errToObj($)})}url($){return this._addCheck({kind:"url",...I.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...I.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...I.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...I.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...I.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...I.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...I.errToObj($)})}base64($){return this._addCheck({kind:"base64",...I.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...I.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...I.errToObj($)})}ip($){return this._addCheck({kind:"ip",...I.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...I.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...I.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...I.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...I.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...I.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...I.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...I.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...I.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...I.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...I.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...I.errToObj(J)})}nonempty($){return this.min(1,I.errToObj($))}trim(){return new A0({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new A0({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new A0({...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 $}}A0.create=($)=>{return new A0({checks:[],typeName:N.ZodString,coerce:$?.coerce??!1,...h($)})};function DQ($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,Y=Q>X?Q:X,G=Number.parseInt($.toFixed(Y).replace(".","")),W=Number.parseInt(J.toFixed(Y).replace(".",""));return G%W/10**Y}class r0 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($)!==w.number){let Y=this._getOrReturnCtx($);return E(Y,{code:R.invalid_type,expected:w.number,received:Y.parsedType}),T}let Q=void 0,X=new q0;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:R.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:R.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:R.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(DQ($.data,Y.value)!==0)Q=this._getOrReturnCtx($,Q),E(Q,{code:R.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),E(Q,{code:R.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,I.toString(J))}gt($,J){return this.setLimit("min",$,!1,I.toString(J))}lte($,J){return this.setLimit("max",$,!0,I.toString(J))}lt($,J){return this.setLimit("max",$,!1,I.toString(J))}setLimit($,J,Q,X){return new r0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:I.toString(X)}]})}_addCheck($){return new r0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:I.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:I.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:I.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:I.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:I.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:I.toString(J)})}finite($){return this._addCheck({kind:"finite",message:I.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:I.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:I.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&l.isInteger($.value))}get isFinite(){let $=null,J=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(J===null||Q.value>J)J=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(J)&&Number.isFinite($)}}r0.create=($)=>{return new r0({checks:[],typeName:N.ZodNumber,coerce:$?.coerce||!1,...h($)})};class a0 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($)!==w.bigint)return this._getInvalidInput($);let Q=void 0,X=new q0;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?$.data<Y.value:$.data<=Y.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:R.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?$.data>Y.value:$.data>=Y.value)Q=this._getOrReturnCtx($,Q),E(Q,{code:R.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if($.data%Y.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),E(Q,{code:R.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return E(J,{code:R.invalid_type,expected:w.bigint,received:J.parsedType}),T}gte($,J){return this.setLimit("min",$,!0,I.toString(J))}gt($,J){return this.setLimit("min",$,!1,I.toString(J))}lte($,J){return this.setLimit("max",$,!0,I.toString(J))}lt($,J){return this.setLimit("max",$,!1,I.toString(J))}setLimit($,J,Q,X){return new a0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:I.toString(X)}]})}_addCheck($){return new a0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:I.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:I.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:I.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:I.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:I.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}a0.create=($)=>{return new a0({checks:[],typeName:N.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class C$ extends k{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==w.boolean){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.boolean,received:Q.parsedType}),T}return B0($.data)}}C$.create=($)=>{return new C$({typeName:N.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class U$ extends k{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==w.date){let Y=this._getOrReturnCtx($);return E(Y,{code:R.invalid_type,expected:w.date,received:Y.parsedType}),T}if(Number.isNaN($.data.getTime())){let Y=this._getOrReturnCtx($);return E(Y,{code:R.invalid_date}),T}let Q=new q0,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if($.data.getTime()<Y.value)X=this._getOrReturnCtx($,X),E(X,{code:R.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),Q.dirty()}else if(Y.kind==="max"){if($.data.getTime()>Y.value)X=this._getOrReturnCtx($,X),E(X,{code:R.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),Q.dirty()}else l.assertNever(Y);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new U$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:I.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:I.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}U$.create=($)=>{return new U$({checks:[],coerce:$?.coerce||!1,typeName:N.ZodDate,...h($)})};class q2 extends k{_parse($){if(this._getType($)!==w.symbol){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.symbol,received:Q.parsedType}),T}return B0($.data)}}q2.create=($)=>{return new q2({typeName:N.ZodSymbol,...h($)})};class f$ extends k{_parse($){if(this._getType($)!==w.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.undefined,received:Q.parsedType}),T}return B0($.data)}}f$.create=($)=>{return new f$({typeName:N.ZodUndefined,...h($)})};class I$ extends k{_parse($){if(this._getType($)!==w.null){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.null,received:Q.parsedType}),T}return B0($.data)}}I$.create=($)=>{return new I$({typeName:N.ZodNull,...h($)})};class V$ extends k{constructor(){super(...arguments);this._any=!0}_parse($){return B0($.data)}}V$.create=($)=>{return new V$({typeName:N.ZodAny,...h($)})};class n0 extends k{constructor(){super(...arguments);this._unknown=!0}_parse($){return B0($.data)}}n0.create=($)=>{return new n0({typeName:N.ZodUnknown,...h($)})};class T0 extends k{_parse($){let J=this._getOrReturnCtx($);return E(J,{code:R.invalid_type,expected:w.never,received:J.parsedType}),T}}T0.create=($)=>{return new T0({typeName:N.ZodNever,...h($)})};class H2 extends k{_parse($){if(this._getType($)!==w.undefined){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.void,received:Q.parsedType}),T}return B0($.data)}}H2.create=($)=>{return new H2({typeName:N.ZodVoid,...h($)})};class N0 extends k{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==w.array)return E(J,{code:R.invalid_type,expected:w.array,received:J.parsedType}),T;if(X.exactLength!==null){let G=J.data.length>X.exactLength.value,W=J.data.length<X.exactLength.value;if(G||W)E(J,{code:G?R.too_big:R.too_small,minimum:W?X.exactLength.value:void 0,maximum:G?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),Q.dirty()}if(X.minLength!==null){if(J.data.length<X.minLength.value)E(J,{code:R.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),Q.dirty()}if(X.maxLength!==null){if(J.data.length>X.maxLength.value)E(J,{code:R.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,W)=>{return X.type._parseAsync(new Z0(J,G,J.path,W))})).then((G)=>{return q0.mergeArray(Q,G)});let Y=[...J.data].map((G,W)=>{return X.type._parseSync(new Z0(J,G,J.path,W))});return q0.mergeArray(Q,Y)}get element(){return this._def.type}min($,J){return new N0({...this._def,minLength:{value:$,message:I.toString(J)}})}max($,J){return new N0({...this._def,maxLength:{value:$,message:I.toString(J)}})}length($,J){return new N0({...this._def,exactLength:{value:$,message:I.toString(J)}})}nonempty($){return this.min(1,$)}}N0.create=($,J)=>{return new N0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:N.ZodArray,...h(J)})};function E$($){if($ instanceof t){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=j0.create(E$(X))}return new t({...$._def,shape:()=>J})}else if($ instanceof N0)return new N0({...$._def,type:E$($.element)});else if($ instanceof j0)return j0.create(E$($.unwrap()));else if($ instanceof u0)return u0.create(E$($.unwrap()));else if($ instanceof v0)return v0.create($.items.map((J)=>E$(J)));else return $}class t 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($)!==w.object){let H=this._getOrReturnCtx($);return E(H,{code:R.invalid_type,expected:w.object,received:H.parsedType}),T}let{status:Q,ctx:X}=this._processInputParams($),{shape:Y,keys:G}=this._getCached(),W=[];if(!(this._def.catchall instanceof T0&&this._def.unknownKeys==="strip")){for(let H in X.data)if(!G.includes(H))W.push(H)}let q=[];for(let H of G){let B=Y[H],U=X.data[H];q.push({key:{status:"valid",value:H},value:B._parse(new Z0(X,U,X.path,H)),alwaysSet:H in X.data})}if(this._def.catchall instanceof T0){let H=this._def.unknownKeys;if(H==="passthrough")for(let B of W)q.push({key:{status:"valid",value:B},value:{status:"valid",value:X.data[B]}});else if(H==="strict"){if(W.length>0)E(X,{code:R.unrecognized_keys,keys:W}),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 W){let U=X.data[B];q.push({key:{status:"valid",value:B},value:H._parse(new Z0(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 I.errToObj,new t({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,Q)=>{let X=this._def.errorMap?.(J,Q).message??Q.defaultError;if(J.code==="unrecognized_keys")return{message:I.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend($){return new t({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new t({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:N.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new t({...this._def,catchall:$})}pick($){let J={};for(let Q of l.objectKeys($))if($[Q]&&this.shape[Q])J[Q]=this.shape[Q];return new t({...this._def,shape:()=>J})}omit($){let J={};for(let Q of l.objectKeys(this.shape))if(!$[Q])J[Q]=this.shape[Q];return new t({...this._def,shape:()=>J})}deepPartial(){return E$(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 t({...this._def,shape:()=>J})}required($){let J={};for(let Q of l.objectKeys(this.shape))if($&&!$[Q])J[Q]=this.shape[Q];else{let Y=this.shape[Q];while(Y instanceof j0)Y=Y._def.innerType;J[Q]=Y}return new t({...this._def,shape:()=>J})}keyof(){return W7(l.objectKeys(this.shape))}}t.create=($,J)=>{return new t({shape:()=>$,unknownKeys:"strip",catchall:T0.create(),typeName:N.ZodObject,...h(J)})};t.strictCreate=($,J)=>{return new t({shape:()=>$,unknownKeys:"strict",catchall:T0.create(),typeName:N.ZodObject,...h(J)})};t.lazycreate=($,J)=>{return new t({shape:$,unknownKeys:"strip",catchall:T0.create(),typeName:N.ZodObject,...h(J)})};class T$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(Y){for(let W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return J.common.issues.push(...W.ctx.common.issues),W.result;let G=Y.map((W)=>new W0(W.ctx.common.issues));return E(J,{code:R.invalid_union,unionErrors:G}),T}if(J.common.async)return Promise.all(Q.map(async(Y)=>{let G={...J,common:{...J.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:J.data,path:J.path,parent:G}),ctx:G}})).then(X);else{let Y=void 0,G=[];for(let 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"&&!Y)Y={result:B,ctx:H};if(H.common.issues.length)G.push(H.common.issues)}if(Y)return J.common.issues.push(...Y.ctx.common.issues),Y.result;let W=G.map((q)=>new W0(q));return E(J,{code:R.invalid_union,unionErrors:W}),T}}get options(){return this._def.options}}T$.create=($,J)=>{return new T$({options:$,typeName:N.ZodUnion,...h(J)})};var m0=($)=>{if($ instanceof x$)return m0($.schema);else if($ instanceof P0)return m0($.innerType());else if($ instanceof h$)return[$.value];else if($ instanceof s0)return $.options;else if($ instanceof y$)return l.objectValues($.enum);else if($ instanceof g$)return m0($._def.innerType);else if($ instanceof f$)return[void 0];else if($ instanceof I$)return[null];else if($ instanceof j0)return[void 0,...m0($.unwrap())];else if($ instanceof u0)return[null,...m0($.unwrap())];else if($ instanceof V6)return m0($.unwrap());else if($ instanceof m$)return m0($.unwrap());else if($ instanceof k$)return m0($._def.innerType);else return[]};class U6 extends k{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==w.object)return E(J,{code:R.invalid_type,expected:w.object,received:J.parsedType}),T;let Q=this.discriminator,X=J.data[Q],Y=this.optionsMap.get(X);if(!Y)return E(J,{code:R.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),T;if(J.common.async)return Y._parseAsync({data:J.data,path:J.path,parent:J});else return Y._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,Q){let X=new Map;for(let Y of J){let G=m0(Y.shape[$]);if(!G.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let W of G){if(X.has(W))throw Error(`Discriminator property ${String($)} has duplicate value ${String(W)}`);X.set(W,Y)}}return new U6({typeName:N.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function f9($,J){let Q=I0($),X=I0(J);if($===J)return{valid:!0,data:$};else if(Q===w.object&&X===w.object){let Y=l.objectKeys(J),G=l.objectKeys($).filter((q)=>Y.indexOf(q)!==-1),W={...$,...J};for(let q of G){let H=f9($[q],J[q]);if(!H.valid)return{valid:!1};W[q]=H.data}return{valid:!0,data:W}}else if(Q===w.array&&X===w.array){if($.length!==J.length)return{valid:!1};let Y=[];for(let G=0;G<$.length;G++){let W=$[G],q=J[G],H=f9(W,q);if(!H.valid)return{valid:!1};Y.push(H.data)}return{valid:!0,data:Y}}else if(Q===w.date&&X===w.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class v$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(Y,G)=>{if(H6(Y)||H6(G))return T;let W=f9(Y.value,G.value);if(!W.valid)return E(Q,{code:R.invalid_intersection_types}),T;if(B6(Y)||B6(G))J.dirty();return{status:J.value,value:W.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([Y,G])=>X(Y,G));else return X(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}v$.create=($,J,Q)=>{return new v$({left:$,right:J,typeName:N.ZodIntersection,...h(Q)})};class v0 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.array)return E(Q,{code:R.invalid_type,expected:w.array,received:Q.parsedType}),T;if(Q.data.length<this._def.items.length)return E(Q,{code:R.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;if(!this._def.rest&&Q.data.length>this._def.items.length)E(Q,{code:R.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let Y=[...Q.data].map((G,W)=>{let q=this._def.items[W]||this._def.rest;if(!q)return null;return q._parse(new Z0(Q,G,Q.path,W))}).filter((G)=>!!G);if(Q.common.async)return Promise.all(Y).then((G)=>{return q0.mergeArray(J,G)});else return q0.mergeArray(J,Y)}get items(){return this._def.items}rest($){return new v0({...this._def,rest:$})}}v0.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new v0({items:$,typeName:N.ZodTuple,rest:null,...h(J)})};class B2 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!==w.object)return E(Q,{code:R.invalid_type,expected:w.object,received:Q.parsedType}),T;let X=[],Y=this._def.keyType,G=this._def.valueType;for(let W in Q.data)X.push({key:Y._parse(new Z0(Q,W,Q.path,W)),value:G._parse(new Z0(Q,Q.data[W],Q.path,W)),alwaysSet:W 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 B2({keyType:$,valueType:J,typeName:N.ZodRecord,...h(Q)});return new B2({keyType:A0.create(),valueType:$,typeName:N.ZodRecord,...h(J)})}}class U2 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!==w.map)return E(Q,{code:R.invalid_type,expected:w.map,received:Q.parsedType}),T;let X=this._def.keyType,Y=this._def.valueType,G=[...Q.data.entries()].map(([W,q],H)=>{return{key:X._parse(new Z0(Q,W,Q.path,[H,"key"])),value:Y._parse(new Z0(Q,q,Q.path,[H,"value"]))}});if(Q.common.async){let W=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 T;if(H.status==="dirty"||B.status==="dirty")J.dirty();W.set(H.value,B.value)}return{status:J.value,value:W}})}else{let W=new Map;for(let q of G){let{key:H,value:B}=q;if(H.status==="aborted"||B.status==="aborted")return T;if(H.status==="dirty"||B.status==="dirty")J.dirty();W.set(H.value,B.value)}return{status:J.value,value:W}}}}U2.create=($,J,Q)=>{return new U2({valueType:J,keyType:$,typeName:N.ZodMap,...h(Q)})};class z$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==w.set)return E(Q,{code:R.invalid_type,expected:w.set,received:Q.parsedType}),T;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)E(Q,{code:R.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),J.dirty()}if(X.maxSize!==null){if(Q.data.size>X.maxSize.value)E(Q,{code:R.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let Y=this._def.valueType;function G(q){let H=new Set;for(let B of q){if(B.status==="aborted")return T;if(B.status==="dirty")J.dirty();H.add(B.value)}return{status:J.value,value:H}}let W=[...Q.data.values()].map((q,H)=>Y._parse(new Z0(Q,q,Q.path,H)));if(Q.common.async)return Promise.all(W).then((q)=>G(q));else return G(W)}min($,J){return new z$({...this._def,minSize:{value:$,message:I.toString(J)}})}max($,J){return new z$({...this._def,maxSize:{value:$,message:I.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}z$.create=($,J)=>{return new z$({valueType:$,minSize:null,maxSize:null,typeName:N.ZodSet,...h(J)})};class S$ extends k{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==w.function)return E(J,{code:R.invalid_type,expected:w.function,received:J.parsedType}),T;function Q(W,q){return W2({data:W,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,w$(),k0].filter((H)=>!!H),issueData:{code:R.invalid_arguments,argumentsError:q}})}function X(W,q){return W2({data:W,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,w$(),k0].filter((H)=>!!H),issueData:{code:R.invalid_return_type,returnTypeError:q}})}let Y={errorMap:J.common.contextualErrorMap},G=J.data;if(this._def.returns instanceof D$){let W=this;return B0(async function(...q){let H=new W0([]),B=await W._def.args.parseAsync(q,Y).catch((V)=>{throw H.addIssue(Q(q,V)),H}),U=await Reflect.apply(G,this,B);return await W._def.returns._def.type.parseAsync(U,Y).catch((V)=>{throw H.addIssue(X(U,V)),H})})}else{let W=this;return B0(function(...q){let H=W._def.args.safeParse(q,Y);if(!H.success)throw new W0([Q(q,H.error)]);let B=Reflect.apply(G,this,H.data),U=W._def.returns.safeParse(B,Y);if(!U.success)throw new W0([X(B,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new S$({...this._def,args:v0.create($).rest(n0.create())})}returns($){return new S$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new S$({args:$?$:v0.create([]).rest(n0.create()),returns:J||n0.create(),typeName:N.ZodFunction,...h(Q)})}}class x$ 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})}}x$.create=($,J)=>{return new x$({getter:$,typeName:N.ZodLazy,...h(J)})};class h$ extends k{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return E(J,{received:J.data,code:R.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:$.data}}get value(){return this._def.value}}h$.create=($,J)=>{return new h$({value:$,typeName:N.ZodLiteral,...h(J)})};function W7($,J){return new s0({values:$,typeName:N.ZodEnum,...h(J)})}class s0 extends k{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{expected:l.joinValues(Q),received:J.parsedType,code:R.invalid_type}),T}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return E(J,{received:J.data,code:R.invalid_enum_value,options:Q}),T}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 s0.create($,{...this._def,...J})}exclude($,J=this._def){return s0.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}s0.create=W7;class y$ extends k{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==w.string&&Q.parsedType!==w.number){let X=l.objectValues(J);return E(Q,{expected:l.joinValues(X),received:Q.parsedType,code:R.invalid_type}),T}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return E(Q,{received:Q.data,code:R.invalid_enum_value,options:X}),T}return B0($.data)}get enum(){return this._def.values}}y$.create=($,J)=>{return new y$({values:$,typeName:N.ZodNativeEnum,...h(J)})};class D$ extends k{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==w.promise&&J.common.async===!1)return E(J,{code:R.invalid_type,expected:w.promise,received:J.parsedType}),T;let Q=J.parsedType===w.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})}))}}D$.create=($,J)=>{return new D$({type:$,typeName:N.ZodPromise,...h(J)})};class P0 extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===N.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,Y={addIssue:(G)=>{if(E(Q,G),G.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let G=X.transform(Q.data,Y);if(Q.common.async)return Promise.resolve(G).then(async(W)=>{if(J.value==="aborted")return T;let q=await this._def.schema._parseAsync({data:W,path:Q.path,parent:Q});if(q.status==="aborted")return T;if(q.status==="dirty")return B$(q.value);if(J.value==="dirty")return B$(q.value);return q});else{if(J.value==="aborted")return T;let W=this._def.schema._parseSync({data:G,path:Q.path,parent:Q});if(W.status==="aborted")return T;if(W.status==="dirty")return B$(W.value);if(J.value==="dirty")return B$(W.value);return W}}if(X.type==="refinement"){let G=(W)=>{let q=X.refinement(W,Y);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 W};if(Q.common.async===!1){let W=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return T;if(W.status==="dirty")J.dirty();return G(W.value),{status:J.value,value:W.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((W)=>{if(W.status==="aborted")return T;if(W.status==="dirty")J.dirty();return G(W.value).then(()=>{return{status:J.value,value:W.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(!i0(G))return T;let W=X.transform(G.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:W}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(!i0(G))return T;return Promise.resolve(X.transform(G.value,Y)).then((W)=>({status:J.value,value:W}))});l.assertNever(X)}}P0.create=($,J,Q)=>{return new P0({schema:$,typeName:N.ZodEffects,effect:J,...h(Q)})};P0.createWithPreprocess=($,J,Q)=>{return new P0({schema:J,effect:{type:"preprocess",transform:$},typeName:N.ZodEffects,...h(Q)})};class j0 extends k{_parse($){if(this._getType($)===w.undefined)return B0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}j0.create=($,J)=>{return new j0({innerType:$,typeName:N.ZodOptional,...h(J)})};class u0 extends k{_parse($){if(this._getType($)===w.null)return B0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}u0.create=($,J)=>{return new u0({innerType:$,typeName:N.ZodNullable,...h(J)})};class g$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===w.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}g$.create=($,J)=>{return new g$({innerType:$,typeName:N.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class k$ 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(b$(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new W0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new W0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}k$.create=($,J)=>{return new k$({innerType:$,typeName:N.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class V2 extends k{_parse($){if(this._getType($)!==w.nan){let Q=this._getOrReturnCtx($);return E(Q,{code:R.invalid_type,expected:w.nan,received:Q.parsedType}),T}return{status:"valid",value:$.data}}}V2.create=($)=>{return new V2({typeName:N.ZodNaN,...h($)})};var OQ=Symbol("zod_brand");class V6 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 z2 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(Y.status==="aborted")return T;if(Y.status==="dirty")return J.dirty(),B$(Y.value);else return this._def.out._parseAsync({data:Y.value,path:Q.path,parent:Q})})();else{let X=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(X.status==="aborted")return T;if(X.status==="dirty")return J.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:Q.path,parent:Q})}}static create($,J){return new z2({in:$,out:J,typeName:N.ZodPipeline})}}class m$ extends k{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(i0(X))X.value=Object.freeze(X.value);return X};return b$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}m$.create=($,J)=>{return new m$({innerType:$,typeName:N.ZodReadonly,...h(J)})};function Q7($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function q7($,J={},Q){if($)return V$.create().superRefine((X,Y)=>{let G=$(X);if(G instanceof Promise)return G.then((W)=>{if(!W){let q=Q7(J,X),H=q.fatal??Q??!0;Y.addIssue({code:"custom",...q,fatal:H})}});if(!G){let W=Q7(J,X),q=W.fatal??Q??!0;Y.addIssue({code:"custom",...W,fatal:q})}return});return V$.create()}var MQ={object:t.lazycreate},N;(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"})(N||(N={}));var FQ=($,J={message:`Input not instance of ${$.name}`})=>q7((Q)=>Q instanceof $,J),H7=A0.create,B7=r0.create,KQ=V2.create,_Q=a0.create,U7=C$.create,LQ=U$.create,RQ=q2.create,AQ=f$.create,NQ=I$.create,jQ=V$.create,ZQ=n0.create,PQ=T0.create,wQ=H2.create,bQ=N0.create,EQ=t.create,SQ=t.strictCreate,CQ=T$.create,fQ=U6.create,IQ=v$.create,TQ=v0.create,vQ=B2.create,xQ=U2.create,hQ=z$.create,yQ=S$.create,gQ=x$.create,kQ=h$.create,mQ=s0.create,uQ=y$.create,lQ=D$.create,cQ=P0.create,pQ=j0.create,dQ=u0.create,iQ=P0.createWithPreprocess,nQ=z2.create,rQ=()=>H7().optional(),aQ=()=>B7().optional(),sQ=()=>U7().optional(),oQ={string:($)=>A0.create({...$,coerce:!0}),number:($)=>r0.create({...$,coerce:!0}),boolean:($)=>C$.create({...$,coerce:!0}),bigint:($)=>a0.create({...$,coerce:!0}),date:($)=>U$.create({...$,coerce:!0})};var tQ=T;var I9=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 eQ($){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 YF={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
226
277
|
|
|
227
278
|
Use this tool when:
|
|
228
279
|
- You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
|
|
@@ -239,7 +290,7 @@ Use this tool when:
|
|
|
239
290
|
- result: present when status is 'completed'
|
|
240
291
|
- error: present when status is 'failed'
|
|
241
292
|
|
|
242
|
-
Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:
|
|
293
|
+
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:I9,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async($,J)=>z6(null).execute($,J)};function z6($=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
243
294
|
|
|
244
295
|
Use this tool when:
|
|
245
296
|
- You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
|
|
@@ -256,7 +307,7 @@ Use this tool when:
|
|
|
256
307
|
- result: present when status is 'completed'
|
|
257
308
|
- error: present when status is 'failed'
|
|
258
309
|
|
|
259
|
-
Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:
|
|
310
|
+
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:I9,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(J,Q)=>{let X=Date.now(),Y=I9.parse(J),{bgProcessId:G}=Y;if(!$)return{success:!1,output:"",error:"query_background_process is not initialized: no BackgroundTaskManager has been bound. TaskComponent should call createQueryBackgroundProcessTool(manager) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-X}};let W;try{W=$.getTask(G)}catch(H){return{success:!1,output:"",error:`failed to query background task: ${H.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(W){let H=Q.session_id;if(!H||W.parentSessionId!==H)return{success:!0,output:JSON.stringify(V7(G),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:G,status:"not_found",alive:!1}}}let q=W?eQ(W):V7(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}}}}}var z7=K.object({task_id:K.string().describe("The ID of the background task to stop")}),$X=`Stop a running background task.
|
|
260
311
|
|
|
261
312
|
Use this tool to stop a background task that is currently running. This is useful when:
|
|
262
313
|
- The user wants to cancel a long-running task
|
|
@@ -266,10 +317,10 @@ Use this tool to stop a background task that is currently running. This is usefu
|
|
|
266
317
|
When stopped, the task will be terminated immediately and you will receive a confirmation.
|
|
267
318
|
|
|
268
319
|
Parameters:
|
|
269
|
-
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function
|
|
270
|
-
`),metadata:{execution_time_ms:Date.now()-X,task_id:
|
|
271
|
-
`);else
|
|
272
|
-
`);return{success:!1,output:
|
|
320
|
+
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function JX($){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 D7($){return{name:"stop_task",description:$X,parameters:z7,execute:async(J,Q)=>{let X=Date.now(),Y=z7.parse(J),{task_id:G}=Y,W=await $.stopTask(G);if(W.success){let q=W.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: ${JX(H)}`,"",W.message].join(`
|
|
321
|
+
`),metadata:{execution_time_ms:Date.now()-X,task_id:G,previous_status:q.status}}}else{let q=W.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}`,"",W.message].join(`
|
|
322
|
+
`);else H=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${G}`,"",W.message].join(`
|
|
323
|
+
`);return{success:!1,output:H,error:W.message,metadata:{execution_time_ms:Date.now()-X,task_id:G}}}}}}import{createRequire as QX}from"module";var{defineProperty:T9,getOwnPropertyNames:XX,getOwnPropertyDescriptor:YX}=Object,GX=Object.prototype.hasOwnProperty;function WX($){return this[$]}var u$=($)=>{var J=(O7??=new WeakMap).get($),Q;if(J)return J;if(J=T9({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of XX($))if(!GX.call(J,X))T9(J,X,{get:WX.bind($,X),enumerable:!(Q=YX($,X))||Q.enumerable})}return O7.set($,J),J},O7,qX=($)=>$;function HX($,J){this[$]=qX.bind(null,J)}var o0=($,J)=>{for(var Q in J)T9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:HX.bind(J,Q)})},m=function($,J,Q,X){var Y=arguments.length,G=Y<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,Q):X,W;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")G=Reflect.decorate($,J,Q,X);else for(var q=$.length-1;q>=0;q--)if(W=$[q])G=(Y<3?W(G):Y>3?W(J,Q,G):W(J,Q))||G;return Y>3&&G&&Object.defineProperty(J,Q,G),G},r=($,J)=>()=>($&&(J=$($=0)),J),e=QX(import.meta.url);function v9(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function M7($){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 BX(){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 UX($){let Q=new(BX())($);if(typeof Q.run!=="function")Q.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return Q}class x9{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=UX(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(`
|
|
273
324
|
CREATE TABLE IF NOT EXISTS span (
|
|
274
325
|
span_id TEXT PRIMARY KEY,
|
|
275
326
|
trace_id TEXT NOT NULL,
|
|
@@ -284,11 +335,11 @@ Parameters:
|
|
|
284
335
|
error TEXT,
|
|
285
336
|
time_created INTEGER NOT NULL
|
|
286
337
|
)
|
|
287
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save(
|
|
338
|
+
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save($){if(!this.db){if(v9())console.log(`[SpanStorage] save() skipped: db not initialized for span "${$.name}" traceId=${$.traceId}`);return}let J=this.db.prepare(`
|
|
288
339
|
INSERT OR REPLACE INTO span
|
|
289
340
|
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
290
341
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
291
|
-
`)
|
|
342
|
+
`),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:M7($.result):null;if(v9())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,M7($.attributes),Q,$.error||null,Date.now());if(v9())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(`
|
|
292
343
|
SELECT trace_id,
|
|
293
344
|
MIN(start_time) as start_time,
|
|
294
345
|
MAX(end_time) as end_time,
|
|
@@ -303,10 +354,10 @@ Parameters:
|
|
|
303
354
|
GROUP BY trace_id
|
|
304
355
|
ORDER BY start_time DESC
|
|
305
356
|
LIMIT ?
|
|
306
|
-
`).all(
|
|
307
|
-
`)||[];Error.stackTraceLimit
|
|
308
|
-
`,"utf-8")}catch(w){console.error("[Logger] Failed to write to log file:",w)}}log(_,w,$){if(!this.shouldLog(_))return;let X=this.formatMessage(_,w,$);if(this.writeToFile(X),!q7())if(M7)console.error(X);else(_==="error"?console.error:_==="warn"?console.warn:_==="info"?console.log:console.debug)(X)}debug(_,w){this.log("debug",_,w)}info(_,w){this.log("info",_,w)}warn(_,w){this.log("warn",_,w)}error(_,w){this.log("error",_,w)}}function n(_){if(!Q1.has(_))Q1.set(_,new U4(_));return Q1.get(_)}var N_=null,A7=!1,M7=!1;var I2,Q1,a=r(()=>{m2(),I2={debug:0,info:1,warn:2,error:3},Q1=new Map}),R7={};o_(R7,{setTracerProvider:()=>L7,resetTracerProvider:()=>f7,getTracerProvider:()=>B0,OTelTracerProvider:()=>x2});function v2(){if(!C2)C2=n("otel-tracer");return C2}function z4(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function V4(_,...w){v2().info(_,...w)}function G4(_,...w){v2().warn(_,...w)}function Q4(_,...w){v2().error(_,...w)}class k2{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,Y){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=Y}setAttribute(_,w){this.attributes[_]=w}addEvent(_,w){let $=this.attributes._events||[];$.push({name:_,attributes:w}),this.attributes._events=$}end(_,w){if(this.endTime=Date.now(),w)this.error=w.message;let $=this.endTime-(this.startTime||0);if(z4())V4(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${$}ms status=${w?"ERROR":"OK"}`);let X=this.storage;if(!X)G4(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=B0().getStorage();if(X){if(!(X.db||X.initialized))G4(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{Q4("[OTelSpan] Failed to initialize storage:",J)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else Q4(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class O4{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext(_){this.provider.setTracerCurrentContext(this.instanceId,_)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor(_,w,$,X){this.name=_,this.version=w,this.storage=$,this.provider=X,this.instanceId=`${_}@${X.instanceId}`}setOnSpanEndCallback(_){this.onSpanEndCallback=_}getActiveSpanCount(){return this.activeSpans.size}startSpan(_,w){let $=w?.parent,X=w&&"parent"in w,Y=w&&"context"in w,J=this.provider.getGlobalContext(),D,W,G,Q,q;if(Y&&w?.context){let B=w.context;W=B.traceId,G=this.generateSpanId(),Q=B.spanId,q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let O=new k2(_,q,this.storage,B,()=>this.handleSpanEnd(q.spanId,B.spanId));if(w?.attributes)for(let[z,U]of Object.entries(w.attributes))O.setAttribute(z,U);return this.activeSpans.set(G,O),O}if(X)D=$;else if(this.currentContext)D=this.currentContext;else if(J)D=J;if(W=D?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)Q=$.parentSpanId||$.spanId;else if(this.currentContext)Q=this.currentContext.spanId;else if(J)Q=J.spanId;q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let H=new k2(_,q,this.storage,D,()=>this.handleSpanEnd(q.spanId,D?.spanId));if(w?.attributes)for(let[B,O]of Object.entries(w.attributes))H.setAttribute(B,O);if(this.activeSpans.set(G,H),z4())V4(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${W} spanId=${G} parentSpanId=${Q||"-"}`);return H}injectToEnv(_){if(this.currentContext)g2.inject(_,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext(_){this.currentContext=_}findStackParentSpan(_){for(let[,w]of this.activeSpans)if(w.spanContext.parentSpanId===_)return w;return}endSpan(_){let w=_.spanContext;this.activeSpans.delete(w.spanId);let $=this.currentContext?.traceId;if(w.parentSpanId){let Y=this.activeSpans.get(w.parentSpanId);if(Y){let J={traceId:w.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=J,J}if($){let J={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=J,J}}let X=this.findStackParentSpan(w.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let _=Date.now().toString(16).padStart(12,"0"),w=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return(_+w).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd(_,w){if(this.activeSpans.delete(_),w){let X=this.activeSpans.get(w);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:w,parentSpanId:void 0};return}}let $=this.findStackParentSpan(_);if($){this.currentContext={traceId:$.spanContext.traceId,spanId:$.spanContext.spanId,parentSpanId:$.spanContext.parentSpanId};return}this.currentContext=void 0}}class x2{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new W4;tracerContexts=new Map;tracerContextScope=new W4;instanceId;constructor(_,w){q4++,this.instanceId=`Provider#${q4}`,this.storage=_||new S2(w||F7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){let _=this.globalContextScope.getStore();if(_)return _.value;return this.globalContext}setGlobalContext(_){this.globalContext=_}withGlobalContext(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}runInGlobalContextSync(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}getTracerCurrentContext(_){let w=this.tracerContextScope.getStore();if(w)return w.contexts.get(_);return this.tracerContexts.get(_)}setTracerCurrentContext(_,w){let $=this.tracerContextScope.getStore();if($){$.contexts.set(_,w);return}this.tracerContexts.set(_,w)}clearAllTracerCurrentContexts(){let _=this.tracerContextScope.getStore();if(_){_.contexts.clear();return}this.tracerContexts.clear()}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new O4(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=g2.extract(process.env);if(w)_.setCurrentContext({traceId:w.traceId,spanId:w.spanId,parentSpanId:void 0})}shutdown(){for(let _ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function B0(){if(!m_)m_=new x2;return m_}function f7(){if(m_)m_.shutdown(),m_=null}function L7(_){if(m_)m_.shutdown();m_=_}function F7(){let _=e("os"),w=e("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var C2=null,m_=null,q4=0,m2=r(()=>{J4(),$7(),J7(),a()});import{AsyncLocalStorage as K7}from"async_hooks";a();var q1=n("process-tree-killer");function R4(){return e("child_process")}var A4;function N7(_,w,$){if(A4)return A4(_,w,$);return R4().spawn(_,w,$)}var M4;function b7(_,w,$){if(M4)return M4(_,w,$);let X=R4();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var j7;function E7(){return j7??process.platform}function S7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function P7(_){try{let w=b7("tasklist",["/fi",`PID eq ${_}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!w)return!0;return w.stdout.toString().includes(String(_))}catch{return!0}}function Z7(_){return new Promise((w)=>setTimeout(w,_))}async function C7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=E7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;q1.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let D=1;D<=Y;D++){let W=$==="win32"?T7(_):I7(_,X,$);if(await Z7(J),!($==="win32"?P7(_):S7(_)))return q1.info(`[bg-process:kill-done] pid=${_} attempts=${D} stillAlive=false`),{pid:_,platform:$,signal:W.signal,success:!0,attempts:D,stillAlive:!1};if(D<Y)q1.warn(`[bg-process:kill-retry] pid=${_} attempt=${D}/${Y}`)}return q1.error(`[bg-process:kill-failed] pid=${_} attempts=${Y} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function T7(_){try{return N7("taskkill",["/pid",String(_),"/f","/t"],{stdio:"ignore",windowsHide:!0}),{pid:_,platform:"win32",signal:"taskkill /f /t",success:!0}}catch{return{pid:_,platform:"win32",signal:"taskkill /f /t",success:!1}}}function I7(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var u2=n("task:process-registry");class l2{pids=new Set;register(_){if(!Number.isInteger(_)||_<=0)return;this.pids.add(_)}unregister(_){if(!Number.isInteger(_))return;this.pids.delete(_)}size(){return this.pids.size}async killAll(){if(this.pids.size===0)return;let _=Array.from(this.pids);u2.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await C7(w,{retry:3,retryDelayMs:500});if($.stillAlive)u2.error(`\u8FDB\u7A0B PID ${w} \u7ECF\u8FC7 ${$.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(w)}catch{}u2.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var k7=new K7;function f4(_,w){return k7.run(_,w)}function g7(){if(H1!==void 0)return H1;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return H1=_==="1"||_==="true"||_==="yes",H1}var H1;var h7=()=>{};function y7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordResultToDb:_?.recordResultToDb??!1,logResult:_?.logResult,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let W=Y.value,G=_?.name||String(X);return Y.value=I_(W,G,w()),Y}let J=$,D=X||{};if(typeof J==="function"){let W=_?.name||(D?.name?String(D.name):"anonymous");return I_(J,W,w())}return J}}function u(_,w){return y7({name:_,...w})}function I_(_,w,$){let X={recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!0,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter??!1,errorIf:$?.errorIf},Y=X.log,J=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let z=y2();return z!==void 0?z:500},D=(z)=>{if(z===void 0)return;if(z===null)return null;let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}if(U>0&&V.length>U)return V.slice(0,U)+" [TRUNCATED]";try{return JSON.parse(V)}catch{return V}},W=(z)=>{if(z===void 0)return"undefined";if(z===null)return"null";let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}return U>0&&V.length>U?V.slice(0,U)+" [TRUNCATED]":V},G=(z)=>{if(z===void 0)return;if(z===null)return null;if(typeof z==="string")return z;try{return JSON.parse(JSON.stringify(z))}catch(U){return`[Object with circular reference: ${U instanceof Error?U.message:String(U)}]`}},Q="[TRACE]",q=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},H=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(g7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:q(()=>X.resultFilter(z));if(V&&typeof V==="object"&&!Array.isArray(V))return{value:V,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:z,store:!0}},B=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,B);let V=U.stack?.split(`
|
|
309
|
-
`)||[];Error.stackTraceLimit=
|
|
357
|
+
`).all($).map((Q)=>{let X=Number(Q.span_count)||0,Y=Number(Q.error_count)||0,G=Q.end_time??void 0,W=Y===0?"ok":Y>=X?"error":"mixed";return{traceId:Q.trace_id,rootSpanName:Q.root_name??"unknown",startTime:Q.start_time,endTime:G,duration:G!==void 0?G-Q.start_time:void 0,spanCount:X,status:W}})}deleteByTraceId($){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run($)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan($){return{traceId:$.trace_id,spanId:$.span_id,parentSpanId:$.parent_span_id,name:$.name,kind:$.kind,status:$.status,startTime:$.start_time,endTime:$.end_time,attributes:$.attributes?JSON.parse($.attributes):{},result:$.result||void 0,error:$.error||void 0}}buildTree($){let J=new Map,Q=[];for(let X of $)J.set(X.spanId,{...X,children:[]});for(let X of J.values())if(X.parentSpanId){let Y=J.get(X.parentSpanId);if(Y)Y.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var F7=()=>{};import{appendFileSync as LX,existsSync as RX,mkdirSync as AX}from"fs";import{join as D2}from"path";import{AsyncLocalStorage as _7}from"async_hooks";function K7($,J){return $.padStart(J,"0")}function h9($){return/^[0-9a-f]+$/i.test($)}function VX($){let J=K7($.traceId.toLowerCase(),N7),Q=K7($.spanId.toLowerCase(),j7);return[k9,J,Q,DX].join("-")}function zX($){if(!$||typeof $!=="string")return;let Q=$.trim().split("-");if(Q.length!==4)return;let[X,Y,G,W]=Q;if(X!==k9){if(X>k9)return}if(Y.length!==N7||!h9(Y))return;if(G.length!==j7||!h9(G))return;if(W.length!==OX||!h9(W))return;return{traceId:Y.toLowerCase(),spanId:G.toLowerCase()}}var k9="00",DX="01",y9="TRACEPARENT",N7=32,j7=16,OX=2,l9,MX=r(()=>{l9={inject($,J){$[y9]=VX(J)},extract($){let J=$[y9];if(!J)return;return zX(J)},getTraceparentHeader(){return y9}}}),FX,KX,_X=r(()=>{(($)=>{$.CLIENT="client",$.SERVER="server",$.INTERNAL="internal"})(FX||={}),(($)=>{$.OK="ok",$.ERROR="error"})(KX||={})});function c9($){let J=$.replace(/\\/g,"/"),Q=J.match(/\/\$bunfs\/root\/(.+)$/);if(Q){let W=Q[1],q=W.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(q)return q[1];return W}let X=J.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let W=X[1].replace(/\+/g,"/"),q=X[2],H=W,B=q.startsWith("src/")?q:`src/${q}`;return`${H}/${B}`}let Y=J.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let G=["packages/core/src","packages/core","packages"];for(let W of G){let q=J.indexOf(W);if(q!==-1)return J.substring(q)}return J}function NX(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let J=e("xdg-basedir");if(J.xdgData)return D2(J.xdgData,"roy-agent","logs")}catch{}return D2($,".local","share","roy-agent","logs")}function jX(){return CX}function ZX(){if(w0){let J=w0.get("log_trace.logging.level");if(J&&["debug","info","warn","error"].includes(J))return J}let $=process.env.LOG_LEVEL;if($&&["debug","info","warn","error"].includes($))return $;return"info"}function PX($){if(w0){let X=w0.get("log_trace.logging.levels");if(X&&typeof X==="object"){let G=X[$];if(G&&["debug","info","warn","error"].includes(G))return G}let Y=w0.get(`log_trace.logging.levels.${$}`);if(Y&&["debug","info","warn","error"].includes(Y))return Y}let J=`LOG_LEVEL_${$.toUpperCase().replace(/:/g,"_")}`,Q=process.env[J];if(Q&&["debug","info","warn","error"].includes(Q))return Q;return ZX()}function wX($){if($.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test($))return!0;return!1}function bX($){if($.startsWith("~")){let J=process.env.HOME||process.env.USERPROFILE||"/tmp";return D2(J,$.slice(1))}return $}function EX(){if(w0){let $=w0.get("log-trace.logging.file");if($)return $}return"app.log"}function SX(){if(w0){let $=w0.get("log-trace.logging.dir");if($)return $}return NX()}function p9(){if(w0){let $=w0.get("log-trace.logging.maxOutput");if(typeof $==="number")return $}return}class Z7{prefix;constructor($){this.prefix=$}shouldLog($){let J=PX(this.prefix);return m9[$]>=m9[J]}ensureLogDirectory($){if(!RX($))try{AX($,{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(`
|
|
358
|
+
`)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let Y=Q[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let G=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(G){let W=G[1];return{file:this.getRelativePath(W),line:parseInt(G[2],10)}}}}return null}getRelativePath($){return c9($)}formatMessage($,J,Q){let X=new Date,Y=X.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).replace(/\//g,"-")+"."+String(X.getMilliseconds()).padStart(3,"0"),G=this.prefix?`[${this.prefix}]`:"",W="";try{let V=O2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)W=`[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=`${Y} [${$.toUpperCase()}]${W}${q}${G} ${J}`;if(Q!==void 0)if(typeof Q==="object")H+=" "+JSON.stringify(Q).replace(/\n/g,"");else H+=" "+String(Q);let B=p9();if(B&&B>0&&H.length>B)H=H.substring(0,B)+" [TRUNCATED]";return H}writeToFile($){try{let J=SX(),Q=EX(),X=bX(J),Y=wX(X)?X:D2(process.cwd(),X);this.ensureLogDirectory(Y);let G=D2(Y,Q);LX(G,$+`
|
|
359
|
+
`,"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),!jX())if(fX)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 n($){if(!D6.has($))D6.set($,new Z7($));return D6.get($)}var w0=null,CX=!1,fX=!1;var m9,D6,a=r(()=>{n9(),m9={debug:0,info:1,warn:2,error:3},D6=new Map}),IX={};o0(IX,{setTracerProvider:()=>vX,resetTracerProvider:()=>TX,getTracerProvider:()=>O2,OTelTracerProvider:()=>i9});function d9(){if(!g9)g9=n("otel-tracer");return g9}function P7(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function w7($,...J){d9().info($,...J)}function L7($,...J){d9().warn($,...J)}function R7($,...J){d9().error($,...J)}class u9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,Y){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=Y}setAttribute($,J){this.attributes[$]=J}addEvent($,J){let Q=this.attributes._events||[];Q.push({name:$,attributes:J}),this.attributes._events=Q}end($,J){if(this.endTime=Date.now(),J)this.error=J.message;let Q=this.endTime-(this.startTime||0);if(P7())w7(`[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)L7(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=O2().getStorage();if(X){if(!(X.db||X.initialized))L7(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((G)=>{R7("[OTelSpan] Failed to initialize storage:",G)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:J?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:$,error:this.error})}else R7(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class b7{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext($){this.provider.setTracerCurrentContext(this.instanceId,$)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor($,J,Q,X){this.name=$,this.version=J,this.storage=Q,this.provider=X,this.instanceId=`${$}@${X.instanceId}`}setOnSpanEndCallback($){this.onSpanEndCallback=$}getActiveSpanCount(){return this.activeSpans.size}startSpan($,J){let Q=J?.parent,X=J&&"parent"in J,Y=J&&"context"in J,G=this.provider.getGlobalContext(),W,q,H,B,U;if(Y&&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 F=new u9($,U,this.storage,V,()=>this.handleSpanEnd(U.spanId,V.spanId));if(J?.attributes)for(let[O,D]of Object.entries(J.attributes))F.setAttribute(O,D);return this.activeSpans.set(H,F),F}if(X)W=Q;else if(this.currentContext)W=this.currentContext;else if(G)W=G;if(q=W?.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 u9($,U,this.storage,W,()=>this.handleSpanEnd(U.spanId,W?.spanId));if(J?.attributes)for(let[V,F]of Object.entries(J.attributes))z.setAttribute(V,F);if(this.activeSpans.set(H,z),P7())w7(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${q} spanId=${H} parentSpanId=${B||"-"}`);return z}injectToEnv($){if(this.currentContext)l9.inject($,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}findStackParentSpan($){for(let[,J]of this.activeSpans)if(J.spanContext.parentSpanId===$)return J;return}endSpan($){let J=$.spanContext;this.activeSpans.delete(J.spanId);let Q=this.currentContext?.traceId;if(J.parentSpanId){let Y=this.activeSpans.get(J.parentSpanId);if(Y){let G={traceId:J.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=G,G}if(Q){let G={traceId:Q,spanId:J.parentSpanId,parentSpanId:void 0};return this.currentContext=G,G}}let X=this.findStackParentSpan(J.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let $=Date.now().toString(16).padStart(12,"0"),J=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return($+J).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd($,J){if(this.activeSpans.delete($),J){let X=this.activeSpans.get(J);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:J,parentSpanId:void 0};return}}let Q=this.findStackParentSpan($);if(Q){this.currentContext={traceId:Q.spanContext.traceId,spanId:Q.spanContext.spanId,parentSpanId:Q.spanContext.parentSpanId};return}this.currentContext=void 0}}class i9{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new _7;tracerContexts=new Map;tracerContextScope=new _7;instanceId;constructor($,J){A7++,this.instanceId=`Provider#${A7}`,this.storage=$||new x9(J||xX())}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 b7($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=l9.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 O2(){if(!l0)l0=new i9;return l0}function TX(){if(l0)l0.shutdown(),l0=null}function vX($){if(l0)l0.shutdown();l0=$}function xX(){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 g9=null,l0=null,A7=0,n9=r(()=>{F7(),MX(),_X(),a()});import{AsyncLocalStorage as hX}from"async_hooks";a();var O6=n("process-tree-killer");function C7(){return e("child_process")}var E7;function yX($,J,Q){if(E7)return E7($,J,Q);return C7().spawn($,J,Q)}var S7;function gX($,J,Q){if(S7)return S7($,J,Q);let X=C7();if(typeof X.spawnSync!=="function")return;return X.spawnSync($,J,Q)}var kX;function mX(){return kX??process.platform}function uX($){try{return process.kill($,0),!0}catch(J){if(J.code==="ESRCH")return!1;return!0}}function lX($){try{let J=gX("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 cX($){return new Promise((J)=>setTimeout(J,$))}async function pX($,J){if(!Number.isInteger($)||$<=0)throw Error(`Invalid PID: ${$} (must be a positive integer)`);let Q=mX(),X=J?.signal??"SIGKILL",Y=J?.retry??3,G=J?.retryDelayMs??500;O6.info(`[bg-process:kill-begin] pid=${$} signal=${X} retry=${Y} delayMs=${G}`);for(let W=1;W<=Y;W++){let q=Q==="win32"?dX($):iX($,X,Q);if(await cX(G),!(Q==="win32"?lX($):uX($)))return O6.info(`[bg-process:kill-done] pid=${$} attempts=${W} stillAlive=false`),{pid:$,platform:Q,signal:q.signal,success:!0,attempts:W,stillAlive:!1};if(W<Y)O6.warn(`[bg-process:kill-retry] pid=${$} attempt=${W}/${Y}`)}return O6.error(`[bg-process:kill-failed] pid=${$} attempts=${Y} stillAlive=true`),{pid:$,platform:Q,signal:Q==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function dX($){try{return yX("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 iX($,J,Q){try{return process.kill(-$,J),{pid:$,platform:Q,signal:J,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:$,platform:Q,signal:J,success:!0};return{pid:$,platform:Q,signal:J,success:!1}}}a();var r9=n("task:process-registry");class a9{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);r9.info(`[bg-process:killAll-begin] count=${$.length} pids=[${$.join(",")}]`);for(let J of $)try{let Q=await pX(J,{retry:3,retryDelayMs:500});if(Q.stillAlive)r9.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{}r9.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var nX=new hX;function f7($,J){return nX.run($,J)}function rX(){if(M6!==void 0)return M6;let $=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return M6=$==="1"||$==="true"||$==="yes",M6}var M6;var aX=()=>{};function sX($){let J=()=>({recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!1,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter,errorIf:$?.errorIf});return function(Q,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let q=Y.value,H=$?.name||String(X);return Y.value=U0(q,H,J()),Y}let G=Q,W=X||{};if(typeof G==="function"){let q=$?.name||(W?.name?String(W.name):"anonymous");return U0(G,q,J())}return G}}function u($,J){return sX({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},Y=X.log,G=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let O=p9();return O!==void 0?O:500},W=(O)=>{if(O===void 0)return;if(O===null)return null;let D=G(),M;try{M=typeof O==="string"?O:JSON.stringify(O,null,0).replace(/\n/g,"")}catch(_){M=`[Object with circular reference: ${_ instanceof Error?_.message:String(_)}]`}if(D>0&&M.length>D)return M.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(M)}catch{return M}},q=(O)=>{if(O===void 0)return"undefined";if(O===null)return"null";let D=G(),M;try{M=typeof O==="string"?O:JSON.stringify(O,null,0).replace(/\n/g,"")}catch(_){M=`[Object with circular reference: ${_ instanceof Error?_.message:String(_)}]`}return D>0&&M.length>D?M.slice(0,D)+" [TRUNCATED]":M},H=(O)=>{if(O===void 0)return;if(O===null)return null;if(typeof O==="string")return O;try{return JSON.parse(JSON.stringify(O))}catch(D){return`[Object with circular reference: ${D instanceof Error?D.message:String(D)}]`}},B="[TRACE]",U=(O)=>{try{return O()}catch(D){try{n("traced:"+J).warn(`[trace] filter threw, ignoring: ${D instanceof Error?D.message:String(D)}`)}catch{}return}},z=(O,D)=>{if(X.recordResultToDb===!0)return{value:O,store:!0};if(rX())return{value:O,store:!0};if(X.resultFilter){let M=D?.ran?D.value:U(()=>X.resultFilter(O));if(M&&typeof M==="object"&&!Array.isArray(M))return{value:M,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:O,store:!0}},V=()=>{let O=Error.stackTraceLimit;Error.stackTraceLimit=15;let D=Error();Error.captureStackTrace(D,V);let M=D.stack?.split(`
|
|
360
|
+
`)||[];Error.stackTraceLimit=O;for(let _=1;_<M.length;_++){let L=M[_];if(L.includes("decorator.ts")||L.includes("decorator.js")||L.includes("logFn")||L.includes("getCallerLocation"))continue;let A=L.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||L.match(/at\s+(.+):(\d+):\d+/);if(A){let Z=A[1];if(!Z||Z==="native")continue;return`${c9(Z)}:${A[2]}`}}return""},F=(O,D,M)=>{if(!Y)return;let _=n("traced:"+J),A=`[TRACE] ${O==="enter"?">>>":O==="quit"?"<<<":"!!!"} ${J}`,Z=M||V(),b=(P,f)=>{if(f!==void 0)_.info(`${A} ${P}: ${q(f)}`,{callerLocation:Z});else _.info(`${A} ${P}`,{callerLocation:Z})};if(O==="enter")b("enter",D);else if(O==="quit")b("quit",X.logResult??X.recordResult?D:void 0);else b("error",D)};return function(...O){let D=O2().getTracer("roy-tracer"),M={};if(X.recordParams!==!1)if(X.paramFilter){let A=U(()=>X.paramFilter(O));if(M.params=H(A),X.flattenParamFilter&&A&&typeof A==="object"&&!Array.isArray(A)){for(let[Z,b]of Object.entries(A))if(!(Z in M))M[Z]=H(b)}}else M.params=H(O);let _=V(),L;try{L=D.startSpan(J,{attributes:M})}catch{}F("enter",O,_);try{let A=$.call(this,...O);if(A&&typeof A==="object"&&typeof A.then==="function")return A.then((Z)=>{if(L){let b=X.resultFilter!==void 0,P=X.resultFilter?U(()=>X.resultFilter(Z)):void 0;if(P&&typeof P==="object"&&!Array.isArray(P))for(let[S,x]of Object.entries(P))L.setAttribute(S,H(x));let f=z(Z,{ran:b,value:P});if(f.store)L.setAttribute("result",JSON.stringify(H(f.value)));let j=X.errorIf?U(()=>X.errorIf(Z)):void 0;if(j){let S=j instanceof Error?j:Error(String(j));L.setAttribute("error",S.message),L.end(void 0,S)}else L.end(f.store?f.value:void 0)}return F("quit",X.logResult??X.recordResult?Z:void 0,_),Z},(Z)=>{if(L)L.setAttribute("error",String(Z)),L.end(void 0,Z instanceof Error?Z:Error(String(Z)));throw F("error",Z.message,_),Z});if(L){let Z=X.resultFilter!==void 0,b=X.resultFilter?U(()=>X.resultFilter(A)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[j,S]of Object.entries(b))L.setAttribute(j,H(S));let P=z(A,{ran:Z,value:b});if(P.store)L.setAttribute("result",JSON.stringify(H(P.value)));let f=X.errorIf?U(()=>X.errorIf(A)):void 0;if(f){let j=f instanceof Error?f:Error(String(f));L.setAttribute("error",j.message),L.end(void 0,j)}else L.end(P.store?P.value:void 0)}return F("quit",X.logResult??X.recordResult?A:void 0,_),A}catch(A){if(L)L.setAttribute("error",String(A)),L.end(void 0,A instanceof Error?A:Error(String(A)));throw F("error",A.message,_),A}}}var z0=r(()=>{n9(),a(),aX()});import{randomUUID as oX}from"crypto";z0();function tX(){if(typeof Bun<"u"){let{Database:$}=e("bun:sqlite");return $}else return e("better-sqlite3")}function eX($){let Q=new(tX())($);if(typeof Q.run!=="function")Q.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return Q}class s9{db;insertStmt;getByIdStmt;recentStmt;constructor($){this.db=eX($.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 (
|
|
310
361
|
event_id TEXT PRIMARY KEY,
|
|
311
362
|
es_type TEXT NOT NULL,
|
|
312
363
|
sender_id TEXT NOT NULL,
|
|
@@ -321,7 +372,7 @@ Parameters:
|
|
|
321
372
|
FROM event_store
|
|
322
373
|
WHERE es_type = ? AND sender_id = ?
|
|
323
374
|
ORDER BY created_at DESC
|
|
324
|
-
LIMIT ?`)}async insertTriggerEvent(
|
|
375
|
+
LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${oX()}`,X=Date.now(),Y=JSON.stringify($.metadata??{}),G=$.rawEvent===void 0?null:$Y($.rawEvent);return this.insertStmt.run(Q,J,$.senderId,$.text??null,Y,G,X),Q}async getEventById($){let J=this.getByIdStmt.get($);if(!J)return null;return I7(J)}async getRecentEvents($,J,Q){return this.recentStmt.all($,J,Q).map((Y)=>I7(Y))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],s9.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],s9.prototype,"getEventById",null);function I7($){let J;try{J=$.metadata?JSON.parse($.metadata):{}}catch{J={}}let Q;if($.raw_event)try{Q=JSON.parse($.raw_event)}catch{Q=null}else Q=null;return{eventId:$.event_id,esType:$.es_type,senderId:$.sender_id,text:$.text??null,metadata:J,rawEvent:Q,createdAt:typeof $.created_at==="bigint"?Number($.created_at):$.created_at}}function $Y($){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 JY=null;function T7(){return JY}var Q0={BEFORE_CREATE:"task:before.create",AFTER_CREATE:"task:after.create",BEFORE_UPDATE:"task:before.update",AFTER_UPDATE:"task:after.update",BEFORE_DELETE:"task:before.delete",AFTER_DELETE:"task:after.delete",AFTER_COMPLETE:"task:after.complete",DELEGATE_BEFORE:"task:delegate:before",DELEGATE_AFTER:"task:delegate:after",OPERATION_BEFORE_CREATE:"task:operation:before.create",OPERATION_AFTER_CREATE:"task:operation:after.create"};var M2="\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536",l$="TASK_COMPLETION_HINT",F2="\u6838\u5B9E\u4E49\u52A1";var o9={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
|
|
325
376
|
|
|
326
377
|
## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
|
|
327
378
|
|
|
@@ -446,7 +497,7 @@ Parameters:
|
|
|
446
497
|
- \u2705 \u529F\u80FD\u5F00\u53D1\u3001bug \u4FEE\u590D\u3001\u91CD\u6784\u3001\u6587\u6863\u751F\u6210
|
|
447
498
|
- \u2705 \u7F51\u7EDC\u641C\u7D22\u548C\u7814\u7A76
|
|
448
499
|
|
|
449
|
-
**roy** \u7684\u63D0\u793A\u8BCD\u4E2D\u5185\u7F6E\u4E86\u4EFB\u52A1\u751F\u547D\u5468\u671F\u2014\u2014\u5B83\u77E5\u9053\u5982\u4F55\u4F7F\u7528 \`task_create\`\u3001\`task_update\`\u3001\`task_operation_create\` \u548C \`task_complete\` \u6765\u8DDF\u8E2A\u6BCF\u9879\u5DE5\u4F5C\u3002
|
|
500
|
+
**roy** \u7684\u63D0\u793A\u8BCD\u4E2D\u5185\u7F6E\u4E86\u4EFB\u52A1\u751F\u547D\u5468\u671F\u2014\u2014\u5B83\u77E5\u9053\u5982\u4F55\u4F7F\u7528 \`task_create\`\u3001\`task_update\`\u3001\`task_operation_create\` \u548C \`task_complete\` \u6765\u8DDF\u8E2A\u6BCF\u9879\u5DE5\u4F5C\u3002task_complete \u65F6\u4F1A${F2}\uFF1A\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536\uFF08${M2}\uFF09\uFF0C\u82E5\u6536\u5230 [${l$}] \u5FC5\u987B\u6838\u5B9E\u5E76\u4E8C\u9009\u4E00\uFF08\u91CD\u5F00 / \u843D decision \u8BF4\u660E\u7406\u7531\uFF09\u3002
|
|
450
501
|
|
|
451
502
|
\u63A8\u8350\u4F7F\u7528\uFF1A
|
|
452
503
|
\`\`\`
|
|
@@ -1128,7 +1179,7 @@ roy-agent <command> <subcmd> --help
|
|
|
1128
1179
|
| \`task_list\` | List tasks with optional filters for status/priority |
|
|
1129
1180
|
| \`task_complete\` | Mark a task as completed (progress=100, status=completed). Creates an operation record. |
|
|
1130
1181
|
| \`task_delete\` | Delete a task and all its operation records |
|
|
1131
|
-
| \`task_operation_create\` | Create operation records \u2014 **\u53CC\u7EF4\u5EA6**: milestone_* (\u72B6\u6001/\u91CC\u7A0B\u7891) + process_description (\u8FC7\u7A0B, 100-
|
|
1182
|
+
| \`task_operation_create\` | Create operation records \u2014 **\u53CC\u7EF4\u5EA6**: milestone_* (\u72B6\u6001/\u91CC\u7A0B\u7891) + process_description (\u8FC7\u7A0B, 100-500 \u5B57\u7B26) |
|
|
1132
1183
|
| \`task_operation_list\` | List operation records for a task |
|
|
1133
1184
|
|
|
1134
1185
|
### \u274C \u7981\u6B62\u4F7F\u7528\u7684\u5DE5\u5177\uFF08\u4F60\u4E0D\u80FD\u8C03\u7528\u4EE5\u4E0B\u5DE5\u5177\uFF09
|
|
@@ -1202,7 +1253,7 @@ Follow this lifecycle for every task:
|
|
|
1202
1253
|
\u2502 5. RECORD (task_operation_create) \u2014 **\u53CC\u7EF4\u5EA6\u5206\u5DE5** \u2502
|
|
1203
1254
|
\u2502 - **\u72B6\u6001/\u91CC\u7A0B\u7891\u7EF4\u5EA6**\uFF1A\u7528 milestone_type / milestone_title / \u2502
|
|
1204
1255
|
\u2502 milestone_description \u63CF\u8FF0"\u8FBE\u6210\u7684\u72B6\u6001/\u91CC\u7A0B\u7891"\u3002 \u2502
|
|
1205
|
-
\u2502 - **\u8FC7\u7A0B\u7EF4\u5EA6**\uFF1A\u7528 process_description\uFF08100-
|
|
1256
|
+
\u2502 - **\u8FC7\u7A0B\u7EF4\u5EA6**\uFF1A\u7528 process_description\uFF08100-500 \u5B57\u7B26\uFF09 \u2502
|
|
1206
1257
|
\u2502 \u7B80\u8981\u8BB0\u5F55"\u5982\u4F55\u8FBE\u5230"\u2014\u2014\u91C7\u53D6\u4E86\u4EC0\u4E48\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981\u3002 \u2502
|
|
1207
1258
|
\u2502 - \u26A0\uFE0F **\u4E0D\u8981\u628A action \u5F53\u72B6\u6001**\uFF0C\u4E5F\u4E0D\u8981\u8BA9 process_description \u4E0E \u2502
|
|
1208
1259
|
\u2502 milestone_description \u91CD\u590D\u3002 \u2502
|
|
@@ -1213,8 +1264,13 @@ Follow this lifecycle for every task:
|
|
|
1213
1264
|
\u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2510
|
|
1214
1265
|
\u2502 6. COMPLETE (task_complete) \u2502
|
|
1215
1266
|
\u2502 - Mark task as completed (progress=100%, status=completed) \u2502
|
|
1216
|
-
\u2502 -
|
|
1217
|
-
\u2502
|
|
1267
|
+
\u2502 - ${M2}: check each goal sub-item \u2502
|
|
1268
|
+
\u2502 against the operation-record chain + deliverable evidence \u2502
|
|
1269
|
+
\u2502 - If a [${l$}] appears in task \u2502
|
|
1270
|
+
\u2502 context, you MUST ${F2}: reopen \u2502
|
|
1271
|
+
\u2502 (task_update status=todo) or record why it is met \u2502
|
|
1272
|
+
\u2502 (task_operation_create decision). Never ignore it. \u2502
|
|
1273
|
+
\u2502 - Create completion operation record \u2502
|
|
1218
1274
|
\u2514\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2518
|
|
1219
1275
|
\`\`\`
|
|
1220
1276
|
|
|
@@ -1251,7 +1307,7 @@ When reusing an existing task, you MUST follow these rules:
|
|
|
1251
1307
|
|
|
1252
1308
|
#### \u7EF4\u5EA6 2\uFF1A\u8FC7\u7A0B\uFF08"\u5982\u4F55\u8FBE\u5230"\uFF09\u2014 \u53EF\u9009\u4F46\u63A8\u8350\u7EF4\u5EA6
|
|
1253
1309
|
\u4F7F\u7528 \`task_operation_create\` \u7684 \`process_description\` \u5B57\u6BB5\uFF1A
|
|
1254
|
-
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-
|
|
1310
|
+
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-500 \u5B57\u7B26
|
|
1255
1311
|
- \u5185\u5BB9\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981
|
|
1256
1312
|
- \u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session
|
|
1257
1313
|
|
|
@@ -1857,7 +1913,7 @@ task_operation_create( \\
|
|
|
1857
1913
|
milestone_type="progress", \\
|
|
1858
1914
|
milestone_title="\u5EFA\u7ACB self-task \u8DDF\u8E2A (Task #$SELF_TASK_ID)", \\
|
|
1859
1915
|
milestone_description="\u4EFB\u52A1\u6574\u7406\u5F00\u59CB\uFF0C\u5EFA\u7ACB self-task \u8DDF\u8E2A\u672C\u6B21 reparent/upgrade \u64CD\u4F5C\u94FE", \\
|
|
1860
|
-
process_description="\u901A\u8FC7 task_create \u5EFA tracking task + task_operation_create \u7559\u75D5\u8D77\u6B65 100-
|
|
1916
|
+
process_description="\u901A\u8FC7 task_create \u5EFA tracking task + task_operation_create \u7559\u75D5\u8D77\u6B65 100-500 \u5B57\u7B26" \\
|
|
1861
1917
|
)
|
|
1862
1918
|
|
|
1863
1919
|
# 3. \u81EA\u6B64\u6240\u6709 reparent / \u5347\u7EA7 type \u64CD\u4F5C\u90FD\u5FC5\u987B task_update \u5173\u8054\u5230 $SELF_TASK_ID
|
|
@@ -2045,7 +2101,7 @@ task_operation_create({
|
|
|
2045
2101
|
- **milestone_type**: \`decision\`\uFF08"\u4E3A\u4EC0\u4E48\u6302\u8FD9\u91CC"\uFF09\u6216 \`milestone\`\uFF08"\u8FBE\u6210\u4E86\u4EC0\u4E48"\uFF09
|
|
2046
2102
|
- **milestone_title**: \u4E00\u53E5\u8BDD\u6807\u9898\uFF08\u5982 "Reparent #X \u2192 #Y\uFF08longterm \u951A\u70B9\uFF09"\uFF09
|
|
2047
2103
|
- **milestone_description**: \u8BE6\u7EC6\u63CF\u8FF0\uFF08\u51B3\u7B56\u4F9D\u636E\u3001\u5F3A\u5EA6\u3001\u9879\u76EE\u8DEF\u5F84\uFF09
|
|
2048
|
-
- **process_description**: 100-
|
|
2104
|
+
- **process_description**: 100-500 \u5B57\u7B26\u7B80\u8981\u8FC7\u7A0B
|
|
2049
2105
|
|
|
2050
2106
|
---
|
|
2051
2107
|
|
|
@@ -2058,8 +2114,8 @@ task_operation_create({
|
|
|
2058
2114
|
\u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
|
|
2059
2115
|
|
|
2060
2116
|
> \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
|
|
2061
|
-
`},eV=d2["workflow-extract"];import K4 from"os";import z_ from"path";var B1="roy-agent";function c7(){let _=K4.homedir();try{let w=e("xdg-basedir");return{config:w.xdgConfig||z_.join(_,".config"),state:w.xdgState||z_.join(_,".local","state"),data:w.xdgData||z_.join(_,".local","share"),cache:w.xdgCache||z_.join(_,".cache")}}catch{return{config:z_.join(_,".config"),state:z_.join(_,".local","state"),data:z_.join(_,".local","share"),cache:z_.join(_,".cache")}}}function d7(){let _=K4.homedir(),w=c7();return{home:_,config:z_.join(w.config,B1),state:z_.join(w.state,B1),data:z_.join(w.data,B1),cache:z_.join(w.cache,B1)}}class N4{_paths;get paths(){if(!this._paths)this._paths=d7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return z_.join(this.paths[_],w)}reset(){this._paths=void 0}}var p7=new N4;function b4(_){return p7.getPath(_)}import*as pB from"fs/promises";import*as iB from"fs";import{join as tw}from"path";var X$=KX(g5(),1);a();V_();var __=n("agent:registry"),$$=A.object({name:A.string(),type:A.enum(["primary","sub","workflow"]),workflow:A.string().optional(),entryAgent:A.string().optional(),description:A.string().optional(),systemPromptRef:A.string().optional(),systemPrompt:A.string().optional(),model:A.string().optional(),maxIterations:A.number().optional(),maxErrorRetries:A.number().optional(),allowedTools:A.array(A.string()).optional(),deniedTools:A.array(A.string()).optional(),toolTimeout:A.number().optional(),toolRetries:A.number().optional(),doomLoopThreshold:A.number().optional(),filterHistory:A.boolean().optional()}).refine((_)=>_.type!=="workflow"||_.workflow&&_.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class M_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||iB,this.fsPromises=_.fsPromises||pB;let w=this.configComponent?.get?.("agent.configDir");if(w&&typeof w==="string"&&w.length>0)this.configDir=w;else if(_.baseDir)this.configDir=tw(_.baseDir,"agents");else this.configDir=tw(b4("data"),"agents");__.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=$$.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),__.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)__.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),__.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt(_){let w=this.agents.get(_);if(!w)return;let $=this.getActivePromptComponent();if(w.systemPromptRef)try{if($?.getPrompt){let Y=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(Y)return __.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return __.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return __.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return __.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${w.systemPromptRef}`,{error:X}),w.systemPrompt}return w.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt(_){let w=this.agents.get(_);if(!w)return;return w.systemPrompt}getWorkflowName(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.workflow}getEntryAgent(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let w={name:"workflow-runner",type:"sub",description:"Workflow runner \u2014 \u63A5\u53D7\u5E26 workflow_name\uFF08\u5FC5\u586B\uFF09\u7684\u59D4\u6258\uFF0C\u6216\u6307\u793A\u5176\u6309 search-first \u6D41\u7A0B\u81EA\u884C\u9009\u5B9A\uFF08workflow_tag_list + workflow_search + workflow_list + workflow_get\uFF09\uFF0C\u7136\u540E\u901A\u8FC7 workflow_run \u6267\u884C workflow\uFF1B\u652F\u6301 session resume \u548C stop\uFF1B\u5931\u8D25\u63A5\u7BA1\u7531 prompt \u63A8\u7406\u89E6\u53D1 (Task #2251)\u3002**\u8C03\u7528\u65B9\u5FC5\u987B\u5728 prompt \u4E2D\u660E\u786E\u6307\u5B9A workflow \u540D\uFF0C\u6216\u6307\u793A sub-agent \u81EA\u884C\u641C\u7D22\u9009\u62E9\uFF1B\u7981\u6B62\u76F2\u731C/\u7ED5\u8FC7/\u8DF3\u8FC7 schema \u9A8C\u8BC1** (Task #2486)\u3002",systemPromptRef:"workflow-runner",deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("workflow-runner",w)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let w={name:"task-organizer",type:"sub",description:"\u4EFB\u52A1\u6811\u6574\u7406\u5B50\u667A\u80FD\u4F53 \u2014 \u628A\u975E longterm \u7C7B\u578B\u7684\u6839\u4EFB\u52A1\u91CD\u65B0\u6302\u8F7D\u5230 longterm \u7236\u4EFB\u52A1\u4E0B\uFF0C\u6839\u4EFB\u52A1\u6536\u655B\u5230 10-20 \u4E2A\uFF1B\u7EF4\u62A4\u4EFB\u52A1\u6811\u5F62\u6001\u5065\u5EB7\uFF08re-parent / merge / archive / delete\uFF09\u3002Task #2348\u3002",systemPromptRef:"task-organizer",allowedTools:["task_create","task_get","task_list","task_update","task_delete","task_complete","task_tree","task_search","task_batch_archive","task_batch_delete","task_operation_create","task_operation_get","task_operation_list","task_operation_update","task_operation_delete"],deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("task-organizer",w)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let w={name:"json-extract",type:"sub",description:"JSON \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u5BF9\u8BDD\u5386\u53F2\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 JSON\uFF0C\u901A\u8FC7 workflow_submit_output \u5DE5\u5177\u63D0\u4EA4",systemPromptRef:"json-extract",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:5,filterHistory:!1};this.agents.set("json-extract",w)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let w={name:"workflow-extract",type:"sub",description:"Workflow \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 task \u7684\u5BF9\u8BDD\u5386\u53F2\u4E2D\u5206\u6790\u9700\u6C42\uFF0C\u8FED\u4EE3\u5F0F\u751F\u6210\u5E76\u9A8C\u8BC1 Workflow YAML",systemPromptRef:"workflow-extract",allowedTools:["workflow_get","workflow_list","workflow_add","workflow_validate"],deniedTools:[],maxIterations:10,filterHistory:!1};this.agents.set("workflow-extract",w)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let w={name:"workflow-creator",type:"sub",description:"Workflow \u6784\u5EFA\u5B50\u667A\u80FD\u4F53 \u2014 \u4E0E\u7528\u6237\u591A\u8F6E\u4EA4\u4E92\u5F0F\u534F\u4F5C\u8BBE\u8BA1\u3001\u9A8C\u8BC1\u5E76\u6CE8\u518C workflow",systemPromptRef:"workflow-creator",allowedTools:["workflow_list","workflow_get","workflow_search","workflow_tag_list","workflow_validate","workflow_add","bash","read_file","workflow_run","workflow_run_status"],deniedTools:["delegate_task","stop_task"],maxIterations:60};this.agents.set("workflow-creator",w)}registerCompactAgent(){if(this.agents.has("compact"))return;let w={name:"compact",type:"sub",description:"\u538B\u7F29\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 session \u7684\u5386\u53F2\u6D88\u606F\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 checkpoint JSON",systemPromptRef:"compact",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",w)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;let w={name:"compact-hint",type:"sub",description:"\u538B\u7F29\u63D0\u793A\u5B50\u667A\u80FD\u4F53 \u2014 \u5206\u6790\u7236 session \u5386\u53F2\uFF0C\u751F\u6210\u573A\u666F\u5316\u538B\u7F29\u6307\u5BFC\u63D0\u793A",systemPromptRef:"compact-hint",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact-hint",w)}registerRoyAgent(){if(this.agents.has("roy"))return;let w={name:"roy",type:"sub",description:"Roy \u2014 versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.",systemPromptRef:"roy",deniedTools:["delegate_task","stop_task"]};this.agents.set("roy",w)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch(_){return __.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return __.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let Y=tw(_,X.name);if(X.isDirectory())continue;if(!nB(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),D=this.parseAgentConfig(J,Y);if(D)this.agents.set(D.name,D),__.info(`[AgentRegistry] Loaded agent: ${D.name} from ${X.name}`),w++}catch(J){__.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}__.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){__.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=X$.default.parse(_),X=$$.safeParse($);if(!X.success)return __.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return __.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=$$.safeParse(_);if(!w.success)return __.error(`[AgentRegistry] Invalid agent config for "${_.name}": ${w.error.message}`),!1;await this.ensureConfigDir();let $=this.agentToYaml(_),X=tw(this.configDir,`${_.name}.yaml`);return await this.fsPromises.writeFile(X,$,"utf-8"),this.agents.set(_.name,_),__.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return __.error(`[AgentRegistry] Failed to save agent: ${_.name}`,{error:w}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),__.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml(_){let w={name:_.name,type:_.type,..._.description!==void 0?{description:_.description}:{},..._.systemPromptRef!==void 0?{systemPromptRef:_.systemPromptRef}:{},..._.systemPrompt!==void 0?{systemPrompt:_.systemPrompt}:{},..._.model!==void 0?{model:_.model}:{},..._.maxIterations!==void 0?{maxIterations:_.maxIterations}:{},..._.maxErrorRetries!==void 0?{maxErrorRetries:_.maxErrorRetries}:{},..._.allowedTools!==void 0?{allowedTools:_.allowedTools}:{},..._.deniedTools!==void 0?{deniedTools:_.deniedTools}:{},..._.toolTimeout!==void 0?{toolTimeout:_.toolTimeout}:{},..._.toolRetries!==void 0?{toolRetries:_.toolRetries}:{},..._.doomLoopThreshold!==void 0?{doomLoopThreshold:_.doomLoopThreshold}:{},..._.filterHistory!==void 0?{filterHistory:_.filterHistory}:{},..._.workflow!==void 0?{workflow:_.workflow}:{},..._.entryAgent!==void 0?{entryAgent:_.entryAgent}:{}};return X$.default.stringify(w).trimEnd()+`
|
|
2062
|
-
`}async deleteAgent(
|
|
2117
|
+
`},IF=o9["workflow-extract"];import v7 from"os";import F0 from"path";var F6="roy-agent";function QY(){let $=v7.homedir();try{let J=e("xdg-basedir");return{config:J.xdgConfig||F0.join($,".config"),state:J.xdgState||F0.join($,".local","state"),data:J.xdgData||F0.join($,".local","share"),cache:J.xdgCache||F0.join($,".cache")}}catch{return{config:F0.join($,".config"),state:F0.join($,".local","state"),data:F0.join($,".local","share"),cache:F0.join($,".cache")}}}function XY(){let $=v7.homedir(),J=QY();return{home:$,config:F0.join(J.config,F6),state:F0.join(J.state,F6),data:F0.join(J.data,F6),cache:F0.join(J.cache,F6)}}class x7{_paths;get paths(){if(!this._paths)this._paths=XY();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return F0.join(this.paths[$],J)}reset(){this._paths=void 0}}var YY=new x7;function h7($){return YY.getPath($)}import*as YD from"fs/promises";import*as GD from"fs";import{join as $2}from"path";var U8=h1(iJ(),1);a();z0();var $0=n("agent:registry"),B8=K.object({name:K.string(),type:K.enum(["primary","sub","workflow"]),workflow:K.string().optional(),entryAgent:K.string().optional(),description:K.string().optional(),systemPromptRef:K.string().optional(),systemPrompt:K.string().optional(),model:K.string().optional(),maxIterations:K.number().optional(),maxErrorRetries:K.number().optional(),allowedTools:K.array(K.string()).optional(),deniedTools:K.array(K.string()).optional(),toolTimeout:K.number().optional(),toolRetries:K.number().optional(),doomLoopThreshold:K.number().optional(),filterHistory:K.boolean().optional()}).refine(($)=>$.type!=="workflow"||$.workflow&&$.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class L0{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor($){this.configComponent=$.configComponent,this.promptComponent=$.promptComponent??null,this.resolvePromptComponent=$.resolvePromptComponent,this.fs=$.fs||GD,this.fsPromises=$.fsPromises||YD;let J=this.configComponent?.get?.("agent.configDir");if(J&&typeof J==="string"&&J.length>0)this.configDir=J;else if($.baseDir)this.configDir=$2($.baseDir,"agents");else this.configDir=$2(h7("data"),"agents");$0.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=B8.safeParse($);if(!J.success)throw Error(`Invalid agent config for "${$.name}": ${J.error.issues.map((Q)=>Q.message).join("; ")}`);this.agents.set($.name,{...$}),$0.info(`[AgentRegistry] Registered agent: ${$.name}`,{type:$.type})}unregister($){let J=this.agents.delete($);if(J)$0.info(`[AgentRegistry] Unregistered agent: ${$}`);return J}clear(){this.agents.clear(),$0.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt($){let J=this.agents.get($);if(!J)return;let Q=this.getActivePromptComponent();if(J.systemPromptRef)try{if(Q?.getPrompt){let Y=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(Y)return $0.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),Y}let X=Q?.get?.(J.systemPromptRef);if(X)return $0.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${J.systemPromptRef}`),X;if(J.systemPrompt)return $0.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),J.systemPrompt;return}catch(X){return $0.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(){if(this.agents.has("compact"))return;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:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",J)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;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:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};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"]};this.agents.set("roy",J)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch($){return $0.warn(`[AgentRegistry] Failed to load agents: ${$}`),0}}async loadFromDirectory($){let J=0;try{if(!this.fs.existsSync($))return $0.debug(`[AgentRegistry] Config directory does not exist: ${$}`),0;let Q=await this.fsPromises.readdir($,{withFileTypes:!0});for(let X of Q){let Y=$2($,X.name);if(X.isDirectory())continue;if(!WD(X.name))continue;try{let G=await this.fsPromises.readFile(Y,"utf-8"),W=this.parseAgentConfig(G,Y);if(W)this.agents.set(W.name,W),$0.info(`[AgentRegistry] Loaded agent: ${W.name} from ${X.name}`),J++}catch(G){$0.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${G}`)}}$0.info(`[AgentRegistry] Loaded ${J} agents from ${$}`)}catch(Q){$0.warn(`[AgentRegistry] Error reading config directory: ${Q}`)}return J}parseAgentConfig($,J){try{let Q=U8.default.parse($),X=B8.safeParse(Q);if(!X.success)return $0.warn(`[AgentRegistry] Invalid agent config: ${J}`,{errors:X.error.errors}),null;return X.data}catch(Q){return $0.error(`[AgentRegistry] Failed to parse agent config: ${J}`,{error:Q}),null}}async saveAgent($){try{let J=B8.safeParse($);if(!J.success)return $0.error(`[AgentRegistry] Invalid agent config for "${$.name}": ${J.error.message}`),!1;await this.ensureConfigDir();let Q=this.agentToYaml($),X=$2(this.configDir,`${$.name}.yaml`);return await this.fsPromises.writeFile(X,Q,"utf-8"),this.agents.set($.name,$),$0.info(`[AgentRegistry] Saved agent: ${$.name} to ${X}`),!0}catch(J){return $0.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}),$0.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 U8.default.stringify(J).trimEnd()+`
|
|
2118
|
+
`}async deleteAgent($){if(!this.agents.get($))return $0.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=$2(this.configDir,`${$}.yaml`);if(this.fs.existsSync(Q))await this.fsPromises.unlink(Q),$0.info(`[AgentRegistry] Deleted agent file: ${Q}`);return this.agents.delete($),!0}catch(Q){return $0.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 $2(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 WD($){return $.endsWith(".yaml")||$.endsWith(".yml")}var V8=`You are a subagent created by the main agent to handle a specific task.
|
|
2063
2119
|
|
|
2064
2120
|
## Your Role
|
|
2065
2121
|
- You were created to handle: {task_description}
|
|
@@ -2076,14 +2132,14 @@ task_operation_create({
|
|
|
2076
2132
|
## Execution
|
|
2077
2133
|
- Use the available tools to complete the task
|
|
2078
2134
|
- If you need more information, ask the main agent through the result
|
|
2079
|
-
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as
|
|
2135
|
+
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as qD}from"async_hooks";var HD=new qD;function z8($,J){return HD.run($,J)}import{AsyncLocalStorage as BD}from"async_hooks";var D8=()=>{};function J2(){return m2.getStore()}function W9(){return m2.getStore()||{}}function u2(){return m2.getStore()?.agentContext?.currentTaskId}function nJ($){return typeof $==="number"&&Number.isInteger($)&&$>0?$:void 0}var rJ,m2,UD,l2,q$=r(()=>{a(),z0(),D8(),rJ=n("env:context:env-context"),m2=new BD,UD=U0(function(J,Q){return nJ(J?.metadata?.parentTaskId)??nJ(Q?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:($)=>({parentTaskId:$??null})}),l2=U0(function(J){let Q=u2(),X=m2.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=J}rJ.info(`[setCurrentTaskId] taskId=${J??"undefined"} (was: ${Q??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var q9=r(()=>{q$(),D8()});class H9{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor($={}){this.componentName=$.componentName??"unknown",this.componentVersion=$.componentVersion??"0.0.0",this.defaultPriority=$.defaultPriority??0}register($,J){this.getOrCreateHooks($).push(J)}registerMany($,J){this.getOrCreateHooks($).push(...J)}unregister($,J){let Q=this._hooks.get($);if(!Q)return!1;let X=Q.findIndex((Y)=>Y.name===J);if(X===-1)return!1;return Q.splice(X,1),!0}unregisterAll($){this._hooks.delete($)}async execute($,J,Q={}){let X=this._hooks.get($),Y=process.env.ROY_HOOK_DEBUG==="1";if(Y)console.error(`[DEBUG hook-manager.execute] hookPoint=${$}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${$})`);return}let G=J2();if(Y){if(console.error(`[DEBUG hook-manager.execute] envContext=${G?"present":"absent"}`),G)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(G.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${G.sourceId}`)}if(G){if(Q.envContext=G,!Q.pluginEnabled&&G.pluginEnabled)Q.pluginEnabled=G.pluginEnabled}let W=this.sortHooks(X),q=this.createContext($,J,Q,"before"),H=Q.pluginEnabled||{};if(Y){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(H)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${W.length}:`);for(let B of W)console.error(`[DEBUG hook-manager.execute] - name=${B.name} pluginName=${B.pluginName} sourceId=${B.sourceId}`)}for(let B of W){if(B.pluginName&&B.sourceId){let U=`${B.sourceId}:${B.pluginName}`,z=H[U];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${B.name} (${U}) enabled=${z}`);if(z!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${U}] !== true, got ${JSON.stringify(z)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${B.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)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 Y=this.sortHooks(X),G=this.createContext($,J,Q,"before"),W=[];for(let q of Y){let H=await this.safeExecuteAndReturn(q,G);if(H!==void 0)W.push(H)}return W}count($){return this._hooks.get($)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks($){return this.count($)>0}setComponentInfo($,J){this.componentName=$,this.componentVersion=J}get hooks(){return this._hooks}async executeWithIntervention($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return{stopped:!1,results:[]};let Y=this.sortHooks(X),G=this.createContext($,J,Q,"before"),W=[],q=!1,H;for(let B of Y){if(q)break;let U=await this.safeExecuteAndReturn(B,G);if(W.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:W}}getOrCreateHooks($){let J=this._hooks.get($);if(!J)J=[],this._hooks.set($,J);return J}sortHooks($){return[...$].sort((J,Q)=>{let X=J.priority??this.defaultPriority,Y=Q.priority??this.defaultPriority;return X-Y})}createContext($,J,Q,X){return{component:{name:this.componentName,version:this.componentVersion},data:J,metadata:Q,phase:X,hookPoint:$}}async safeExecute($,J){try{let Q=$.execute(J);if(Q&&typeof Q==="object"&&typeof Q.then==="function")await Q}catch(Q){console.error(`Hook "${$.name}" failed:`,Q)}}async safeExecuteAndReturn($,J){try{return await $.execute(J)}catch(Q){console.error(`Hook "${$.name}" failed:`,Q);return}}}var O8=r(()=>{q9()});function VD(){let $=S0.register.bind(S0);S0.register=function(J,Q){$(J,Q);let X=aJ[J];if(X)$(X,Q)}}var S0,zD,DD,OD,aJ,Q2=r(()=>{O8(),S0=new H9,zD={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"},DD={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},OD={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"},aJ={"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"},VD()});a();z0();q9();function MD($,J){if(_8($))return!0;return J?.hasAgent($)??!1}async function FD($,J={}){let X=(J.getBuiltIn??_8)($),Y=J.registry?.get($);if(!X&&!Y)return;if(Y)return KD($,Y,X,J.registry);return{subagentType:$,description:X.description,basePrompt:X.promptOverride||V8,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function KD($,J,Q,X){let Y=X?await X.getSystemPrompt($):J.systemPrompt;return{subagentType:$,description:J.description||Q?.description||"Custom agent",basePrompt:Y||Q?.promptOverride||V8,allowedTools:J.allowedTools??Q?.allowedTools,deniedTools:J.deniedTools??Q?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function _D($){return`
|
|
2080
2136
|
## Agent Selection Guide
|
|
2081
2137
|
|
|
2082
2138
|
- Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
|
|
2083
|
-
${
|
|
2084
|
-
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function
|
|
2085
|
-
`)+J}_0();var WU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function GU(_){let w=_;for(let $ of WU)w=w.replace($,"<redacted>");return w}function QU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function x5(_,w){return QU(GU(_),w)}class q${maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor(_={}){this.maxEntries=_.maxEntries??500,this.ttlMs=_.ttlMs??86400000,this.maxDescriptionChars=_.maxDescriptionChars??240}record(_,w={}){let $=new Date().toISOString(),X=this.toRecord(_,w,$);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update(_,w){let $=this.records.get(_.id);if(!$)return;let X=new Date().toISOString();this.records.delete(_.id);let Y={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove(_){let w=this.records.get(_);if(!w)return!1;if(this.records.delete(_),w.parentTaskId!==void 0){let $=this.childrenIndex.get(w.parentTaskId);if($?.delete(_),$&&$.size===0)this.childrenIndex.delete(w.parentTaskId)}return!0}getById(_){let w=this.records.get(_);if(!w)return;if(Date.now()-Date.parse(w.updatedAt)>this.ttlMs){this.remove(_);return}return w}peekById(_){return this.records.get(_)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent(_={}){let w=_.limit??10,$=_.statuses,X=new Set(_.excludeIds??[]),Y=_.excludeAncestorOf??_.excludeSelfOrDescendant,J=Y?this.collectSubtree(Y):new Set,D=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,W=Date.now(),G=new Set([...X,...J]),Q=[];for(let q of this.records.values()){if(W-Date.parse(q.updatedAt)>this.ttlMs)continue;if(D>0&&Date.parse(q.updatedAt)<D)continue;if(G.has(q.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&q.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&q.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&q.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(q.status))continue}else if(q.status==="archived")continue;Q.push(q)}if(_.activeChildFirst){let q=new Map;for(let H of Q)q.set(H.taskId,this.hasActiveChild(H.taskId));Q.sort((H,B)=>{let O=q.get(H.taskId)?1:0,z=q.get(B.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(U!==0)return U;return B.taskId-H.taskId})}else Q.sort((q,H)=>{let B=Date.parse(H.updatedAt)-Date.parse(q.updatedAt);if(B!==0)return B;return H.taskId-q.taskId});return Q.slice(0,w)}getSubtreeSummary(_,w={}){let $=w.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has(_)&&!this.childrenIndex.has(_))return X;let Y=this.childrenIndex.get(_),J=Y?Array.from(Y):[],D=J.length>0?1:0;X.maxDepth=D;let W=J;while(W.length>0){let G=[];for(let Q of W){let q=this.records.get(Q);if(!q)continue;if(!$&&q.status==="archived")continue;if(X.descendantCount++,q.status==="active")X.activeCount++;else if(q.status==="completed")X.completedCount++;let H=this.childrenIndex.get(Q);if(H&&H.size>0)for(let B of H)G.push(B)}if(G.length>0)D++,X.maxDepth=D;W=G}return X}hasActiveChild(_){let w=this.childrenIndex.get(_);if(!w)return!1;for(let $ of w){let X=this.records.get($);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord(_,w,$){let X=this.safeParseContext(_.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:x5(_.description||"",this.maxDescriptionChars),goals:x5(_.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:_.tags??[],status:_.status,priority:_.priority,type:_.type,parentTaskId:_.parent_task_id,source:w,createdAt:_.createdAt||$,updatedAt:_.updatedAt||$,operationCount:0,project_path:_.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext(_){if(!_||!_.trim())return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}pickString(_,w){if(!_)return;let $=_[w];return typeof $==="string"?$:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>this.stripSensitiveKeys(X));if(typeof _!=="object")return _;let w={},$=q$.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((D)=>J.includes(D)))continue;w[X]=this.stripSensitiveKeys(Y)}return w}upsert(_){this.records.set(_.taskId,_)}indexParentChild(_){if(_.parentTaskId===void 0||_.parentTaskId===null)return;let w=_.parentTaskId,$=this.childrenIndex.get(w);if(!$)$=new Set,this.childrenIndex.set(w,$);$.add(_.taskId)}collectSubtree(_){let w=new Set([_]),$=[_];while($.length>0){let X=$.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let J of Y)if(!w.has(J))w.add(J),$.push(J)}return w}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let _=this.records.size-this.maxEntries,w=Array.from(this.records.keys()).slice(0,_);for(let $ of w)this.remove($)}}a();var J2=n("registry-hook-installer");function qU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,J=$.priority??100,D=!1,W=(U,V)=>{try{w.record(U,V)}catch(M){J2.warn(`[registry-hook-installer] record failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(M){J2.warn(`[registry-hook-installer] update failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},Q=(U)=>{try{w.remove(U)}catch(V){J2.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},q=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),H={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)W(V.task,q())}},B={name:`${Y}:after-update`,priority:J,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,q());else W(V.task,q())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,q())}},z={name:`${Y}:after-delete`,priority:J,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")Q(V.id)}};return _.registerHook($_.AFTER_CREATE,H),_.registerHook($_.AFTER_UPDATE,B),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(D)return;D=!0,_.unregisterHook($_.AFTER_CREATE,H.name),_.unregisterHook($_.AFTER_UPDATE,B.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),J2.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var G$=n("task-reuse-registry"),HU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},m5=new WeakMap;function BU(_){let w=m5.get(_);if(w)return w.registry;let $=new q$(HU),X={uninstall:()=>{}};try{let J=_.getComponent?.("task");if(J?.registerHook)X=qU(J,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),G$.debug("[task-reuse-registry] hook installed");else G$.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){G$.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return m5.set(_,Y),$}var UU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function zU(_){let w=_;for(let $ of UU)w=w.replace($,"<redacted>");return w}function u5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function VU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,Y=_.heading??"Recent task context (reuse candidates)",J=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(J.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let D=[];D.push(`## ${Y}`),D.push(""),D.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),D.push("");for(let G of J){if(D.push(`### Task #${G.taskId}: ${G.title}`),D.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)D.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)D.push(`- Created by: ${G.source.subagentType}`);if(D.push(`- Updated: ${G.updatedAt}`),G.project_path)D.push(`- Project: ${G.project_path}`);if(G.worktree_path)D.push(`- Worktree: ${G.worktree_path}`);if(G.branch)D.push(`- Branch: ${G.branch}`);if(G.parentBranch)D.push(`- Parent branch: ${G.parentBranch}`);let Q;try{Q=_.registry.getSubtreeSummary(G.taskId)}catch{Q=void 0}if(Q&&Q.descendantCount>0)D.push(`- Children: ${Q.descendantCount} (active: ${Q.activeCount}, completed: ${Q.completedCount}, max depth: ${Q.maxDepth})`);let q=Q!==void 0&&Q.activeCount>0;if(G.status==="completed"&&q)D.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let H=zU(u5(G.description,X));if(H)D.push(`- Description: ${H}`);if(G.tags&&G.tags.length>0)D.push(`- Tags: ${G.tags.join(", ")}`);D.push("")}D.push("---"),D.push(""),D.push("### Reuse instructions"),D.push(""),D.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),D.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),D.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),D.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),D.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),D.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),D.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),D.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),D.push(""),D.push("### Decision matrix \u2014 three legal paths"),D.push(""),D.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),D.push("remains the default, but the matrix adds two new paths for independent work."),D.push(""),D.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),D.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),D.push("append description/goals. Do **not** create a new task id."),D.push(""),D.push("```"),D.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),D.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),D.push(' milestone_title: "Reopened for <new-scope>",'),D.push(' milestone_description: "<why this is the same work>" })'),D.push("```"),D.push(""),D.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),D.push("distinct: an independent bug fix, optimization, parallel delivery or"),D.push("independent acceptance item under the same feature. Create a child task so"),D.push("the audit trail is preserved. Always pair with an audit operation."),D.push(""),D.push("```");for(let G of J){let Q=G.project_path??"<project_path>";D.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${Q}", context=<inherit or override>)`);break}D.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),D.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),D.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),D.push("```"),D.push(""),D.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),D.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),D.push("should stay \u2264 ~10 to keep the tree readable."),D.push(""),D.push("```"),D.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),D.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),D.push(' milestone_title: "New root: <topic>",'),D.push(' milestone_description: "<why this is not a child of any existing task>" })'),D.push("```"),D.push(""),D.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),D.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),D.push("chosen. Use the appropriate `milestone_type`:"),D.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),D.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),D.push(" - new root \u2192 `create` (then `progress` per phase)"),D.push(""),D.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),D.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),D.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),D.push("tokens, secrets) are stripped automatically. Use the helper:"),D.push(""),D.push("```"),D.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),D.push("```"),D.push("");let W=D.join(`
|
|
2086
|
-
`);if(
|
|
2139
|
+
${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
|
|
2140
|
+
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function LD($){let J=F8.map((W)=>`- ${W.id}: ${W.description}`),X=($?.list()??[]).filter((W)=>!F8.some((q)=>q.id===W.name)).map((W)=>{if(W.type==="workflow"){let q=W.workflow?` (workflow: ${W.workflow})`:"";return`- ${W.name}: ${W.description||"Workflow agent"}${q}`}return`- ${W.name}: ${W.description||"Custom agent"}`}),Y=[...J,...X],G=_D({hasCustomAgents:X.length>0});return Y.join(`
|
|
2141
|
+
`)+G}Q2();var RD=[/\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 AD($){let J=$;for(let Q of RD)J=J.replace(Q,"<redacted>");return J}function ND($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function sJ($,J){return ND(AD($),J)}class K8{maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor($={}){this.maxEntries=$.maxEntries??500,this.ttlMs=$.ttlMs??86400000,this.maxDescriptionChars=$.maxDescriptionChars??240}record($,J={}){let Q=new Date().toISOString(),X=this.toRecord($,J,Q);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update($,J){let Q=this.records.get($.id);if(!Q)return;let X=new Date().toISOString();this.records.delete($.id);let Y={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove($){let J=this.records.get($);if(!J)return!1;if(this.records.delete($),J.parentTaskId!==void 0){let Q=this.childrenIndex.get(J.parentTaskId);if(Q?.delete($),Q&&Q.size===0)this.childrenIndex.delete(J.parentTaskId)}return!0}getById($){let J=this.records.get($);if(!J)return;if(Date.now()-Date.parse(J.updatedAt)>this.ttlMs){this.remove($);return}return J}peekById($){return this.records.get($)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent($={}){let J=$.limit??10,Q=$.statuses,X=new Set($.excludeIds??[]),Y=$.excludeAncestorOf??$.excludeSelfOrDescendant,G=Y?this.collectSubtree(Y):new Set,W=$.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(W>0&&Date.parse(U.updatedAt)<W)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 F=U.get(z.taskId)?1:0,O=U.get(V.taskId)?1:0;if(F!==O)return O-F;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 Y=this.childrenIndex.get($),G=Y?Array.from(Y):[],W=G.length>0?1:0;X.maxDepth=W;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)W++,X.maxDepth=W;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),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:sJ($.description||"",this.maxDescriptionChars),goals:sJ($.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:$.tags??[],status:$.status,priority:$.priority,type:$.type,parentTaskId:$.parent_task_id,source:J,createdAt:$.createdAt||Q,updatedAt:$.updatedAt||Q,operationCount:0,project_path:$.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext($){if(!$||!$.trim())return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}pickString($,J){if(!$)return;let Q=$[J];return typeof Q==="string"?Q:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map((X)=>this.stripSensitiveKeys(X));if(typeof $!=="object")return $;let J={},Q=K8.STRIPPED_KEYS;for(let[X,Y]of Object.entries($)){let G=X.toLowerCase();if(Q.some((W)=>G.includes(W)))continue;J[X]=this.stripSensitiveKeys(Y)}return J}upsert($){this.records.set($.taskId,$)}indexParentChild($){if($.parentTaskId===void 0||$.parentTaskId===null)return;let J=$.parentTaskId,Q=this.childrenIndex.get(J);if(!Q)Q=new Set,this.childrenIndex.set(J,Q);Q.add($.taskId)}collectSubtree($){let J=new Set([$]),Q=[$];while(Q.length>0){let X=Q.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let G of Y)if(!J.has(G))J.add(G),Q.push(G)}return J}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let $=this.records.size-this.maxEntries,J=Array.from(this.records.keys()).slice(0,$);for(let Q of J)this.remove(Q)}}a();var B9=n("registry-hook-installer");function jD($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,G=Q.priority??100,W=!1,q=(D,M)=>{try{J.record(D,M)}catch(_){B9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${_ instanceof Error?_.message:String(_)}`)}},H=(D,M)=>{try{J.update(D,M)}catch(_){B9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${_ instanceof Error?_.message:String(_)}`)}},B=(D)=>{try{J.remove(D)}catch(M){B9.warn(`[registry-hook-installer] remove failed for task #${D}: ${M instanceof Error?M.message:String(M)}`)}},U=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),z={name:`${Y}:after-create`,priority:G,execute:async(D)=>{let M=D.data;if(M?.task)q(M.task,U())}},V={name:`${Y}:after-update`,priority:G,execute:async(D)=>{let M=D.data;if(!M?.task)return;if(J.peekById(M.task.id))H(M.task,U());else q(M.task,U())}},F={name:`${Y}:after-complete`,priority:G,execute:async(D)=>{let M=D.data;if(M?.task)H(M.task,U())}},O={name:`${Y}:after-delete`,priority:G,execute:async(D)=>{let M=D.data;if(typeof M?.id==="number")B(M.id)}};return $.registerHook(Q0.AFTER_CREATE,z),$.registerHook(Q0.AFTER_UPDATE,V),$.registerHook(Q0.AFTER_COMPLETE,F),$.registerHook(Q0.AFTER_DELETE,O),{uninstall(){if(W)return;W=!0,$.unregisterHook(Q0.AFTER_CREATE,z.name),$.unregisterHook(Q0.AFTER_UPDATE,V.name),$.unregisterHook(Q0.AFTER_COMPLETE,F.name),$.unregisterHook(Q0.AFTER_DELETE,O.name),B9.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var M8=n("task-reuse-registry"),ZD={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},oJ=new WeakMap;function PD($){let J=oJ.get($);if(J)return J.registry;let Q=new K8(ZD),X={uninstall:()=>{}};try{let G=$.getComponent?.("task");if(G?.registerHook)X=jD(G,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),M8.debug("[task-reuse-registry] hook installed");else M8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(G){M8.warn(`[task-reuse-registry] hook install failed: ${G instanceof Error?G.message:String(G)}`)}let Y={registry:Q,installHandle:X};return oJ.set($,Y),Q}var wD=[/\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 bD($){let J=$;for(let Q of wD)J=J.replace(Q,"<redacted>");return J}function tJ($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function ED($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,Y=$.heading??"Recent task context (reuse candidates)",G=$.registry.recent({scope:$.scope,limit:J,statuses:$.statuses,excludeIds:$.similarTaskIds??[],excludeAncestorOf:$.excludeAncestorOf});if(G.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let W=[];W.push(`## ${Y}`),W.push(""),W.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),W.push("");for(let H of G){if(W.push(`### Task #${H.taskId}: ${H.title}`),W.push(`- Status: ${H.status}`),H.parentTaskId!==void 0&&H.parentTaskId!==null)W.push(`- Parent: #${H.parentTaskId}`);if(H.source.subagentType)W.push(`- Created by: ${H.source.subagentType}`);if(W.push(`- Updated: ${H.updatedAt}`),H.project_path)W.push(`- Project: ${H.project_path}`);if(H.worktree_path)W.push(`- Worktree: ${H.worktree_path}`);if(H.branch)W.push(`- Branch: ${H.branch}`);if(H.parentBranch)W.push(`- Parent branch: ${H.parentBranch}`);let B;try{B=$.registry.getSubtreeSummary(H.taskId)}catch{B=void 0}if(B&&B.descendantCount>0)W.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)W.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let z=bD(tJ(H.description,X));if(z)W.push(`- Description: ${z}`);if(H.tags&&H.tags.length>0)W.push(`- Tags: ${H.tags.join(", ")}`);W.push("")}W.push("---"),W.push(""),W.push("### Reuse instructions"),W.push(""),W.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),W.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),W.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),W.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),W.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),W.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),W.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),W.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),W.push(""),W.push("### Decision matrix \u2014 three legal paths"),W.push(""),W.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),W.push("remains the default, but the matrix adds two new paths for independent work."),W.push(""),W.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),W.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),W.push("append description/goals. Do **not** create a new task id."),W.push(""),W.push("```"),W.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),W.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),W.push(' milestone_title: "Reopened for <new-scope>",'),W.push(' milestone_description: "<why this is the same work>" })'),W.push("```"),W.push(""),W.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),W.push("distinct: an independent bug fix, optimization, parallel delivery or"),W.push("independent acceptance item under the same feature. Create a child task so"),W.push("the audit trail is preserved. Always pair with an audit operation."),W.push(""),W.push("```");for(let H of G){let B=H.project_path??"<project_path>";W.push(`task_create(parent_task_id=${H.taskId}, title="<distinguishing title>", project_path="${B}", context=<inherit or override>)`);break}W.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),W.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),W.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),W.push("```"),W.push(""),W.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),W.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),W.push("should stay \u2264 ~10 to keep the tree readable."),W.push(""),W.push("```"),W.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),W.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),W.push(' milestone_title: "New root: <topic>",'),W.push(' milestone_description: "<why this is not a child of any existing task>" })'),W.push("```"),W.push(""),W.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),W.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),W.push("chosen. Use the appropriate `milestone_type`:"),W.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),W.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),W.push(" - new root \u2192 `create` (then `progress` per phase)"),W.push(""),W.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),W.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),W.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),W.push("tokens, secrets) are stripped automatically. Use the helper:"),W.push(""),W.push("```"),W.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),W.push("```"),W.push("");let q=W.join(`
|
|
2142
|
+
`);if(q.length>Q)q=tJ(q,Q);return{markdown:q,candidateIds:G.map((H)=>H.taskId),isEmpty:!1}}var y=n("task:delegate"),d0={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"},F8=[{id:"general",name:"general",mode:"subagent",description:"General-purpose agent for researching complex questions and executing multi-step tasks.",promptOverride:`You are a subagent created by the main agent to handle a specific task.
|
|
2087
2143
|
|
|
2088
2144
|
## Your Role
|
|
2089
2145
|
- You were created to handle: {task_description}
|
|
@@ -2134,42 +2190,42 @@ ${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
|
|
|
2134
2190
|
## Execution
|
|
2135
2191
|
- Use the available tools to complete the task
|
|
2136
2192
|
- If you need more information, ask the main agent through the result
|
|
2137
|
-
- Return a clear summary of what you did and the results`,deniedTools:["delegate_task","stop_task"]},{id:"explore",name:"explore",mode:"subagent",description:"Fast agent specialized for exploring codebases, finding files, and searching for patterns.",allowedTools:["read_file","glob","grep","bash"],deniedTools:["delegate_task","stop_task"]},{id:"roy",name:"Roy",mode:"subagent",description:"Versatile AI assistant inspired by Jarvis \u2014 intelligent, proactive, and capable. Use for general-purpose tasks, coding, research, and complex multi-step work. Always available (built-in) without `agent add roy`.",promptOverride:
|
|
2193
|
+
- 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:o9.roy,deniedTools:["delegate_task","stop_task"]}];function _8($){return F8.find((J)=>J.id===$)}function SD($,J,Q,X,Y){let G=$.getRegistry?.();if(G){if(G.get(J)?.type==="workflow")return y.debug(`[delegate] Skipping registration for workflow agent: ${J}`),null}let W=$.getAgent(J);if(!W){let q={type:"sub",systemPrompt:Q};if(X?.allowedTools&&X.allowedTools.length>0)q.allowedTools=X.allowedTools;if(Y.length>0)q.deniedTools=Y;W=$.registerAgent(J,q),y.debug(`[delegate] Registered subagent: ${J}`)}return W}var eJ=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 CD($){let{workflowName:J,originalPrompt:Q,description:X}=$;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
|
|
2138
2194
|
|
|
2139
|
-
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${
|
|
2195
|
+
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${J}**\u3002
|
|
2140
2196
|
\u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
|
|
2141
2197
|
|
|
2142
|
-
<workflow_name>${
|
|
2198
|
+
<workflow_name>${J}</workflow_name>
|
|
2143
2199
|
|
|
2144
2200
|
## \u8C03\u5EA6\u76EE\u6807
|
|
2145
2201
|
|
|
2146
|
-
- **Workflow \u540D\u79F0**: \`${
|
|
2202
|
+
- **Workflow \u540D\u79F0**: \`${J}\` (\u6743\u5A01\u6765\u6E90: \`<workflow_name>\` \u6807\u7B7E, \u4E0D\u8981\u4ECE\u4E0A\u4E0B\u6587\u731C\u6D4B)
|
|
2147
2203
|
- **\u4EFB\u52A1\u63CF\u8FF0**: ${X}
|
|
2148
2204
|
|
|
2149
2205
|
## \u539F\u59CB\u7528\u6237\u8BF7\u6C42
|
|
2150
2206
|
|
|
2151
|
-
${
|
|
2207
|
+
${Q}
|
|
2152
2208
|
|
|
2153
2209
|
## \u4F60\u7684\u884C\u52A8
|
|
2154
2210
|
|
|
2155
|
-
1. \`workflow_get(${
|
|
2211
|
+
1. \`workflow_get(${J})\` \u53D6 workflow \u5165\u53C2 schema
|
|
2156
2212
|
2. \u4ECE"\u539F\u59CB\u7528\u6237\u8BF7\u6C42"\u63D0\u53D6\u7B26\u5408 schema \u7684 input \u5B57\u6BB5
|
|
2157
|
-
3. \`workflow_run(${
|
|
2213
|
+
3. \`workflow_run(${J}, input)\` \u89E6\u53D1 workflow
|
|
2158
2214
|
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2159
2215
|
|
|
2160
2216
|
\u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
|
|
2161
|
-
`}var MU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),D2=1800000,RU=1200000;class w_{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor(_){this.env=_}setWorkflowService(_){this.workflowService=_}attachWorkflowRun(_,w){if(!_||!w)return;let $=this.workflowRunRegistries.get(_);if(!$)$=new Set,this.workflowRunRegistries.set(_,$);$.add(w)}detachWorkflowRun(_,w){this.workflowRunRegistries.get(_)?.delete(w)}replaceWorkflowRun(_,w,$){if(!_)return;let X=this.workflowRunRegistries.get(_);if(!X)return;if(w)X.delete(w);if($)X.add($)}async propagateStopToWorkflowRuns(_,w){let $=this.workflowRunRegistries.get(_);if(!$||$.size===0)return{runIds:[],stopResults:[]};let X=Array.from($);h.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${_}`);let Y=[];for(let J of X){if(typeof this.workflowService?.stopRun!=="function"){h.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${J}`),Y.push({runId:J,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(J,w),Y.push({runId:J,success:!0})}catch(D){let W=D instanceof Error?D.message:String(D);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${W}`),Y.push({runId:J,success:!1,error:W})}}return $.clear(),{runIds:X,stopResults:Y}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let J=this.terminalTasks.keys().next().value;if(J!==void 0)this.terminalTasks.delete(J)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let Y=this.processRegistries.get(_);if(Y&&Y.size()>0)h.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${Y.size()}, reason=${w})`);h.debug(`[BackgroundTaskManager] finalizeTask taskId=${_} reason=${w}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let _=0;for(let[w,$]of this.processRegistries)if($.size()===0)this.processRegistries.delete(w),_++;return _}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent(_){try{if(w_.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${w_.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),w_.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??w_.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=I_((_)=>MU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return w_._detectWorkflowShortcutWrapped(_)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession(_){if(!_)return;try{let $=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.(_);return typeof $==="number"&&$>0?$:void 0}catch(w){h.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${_}: ${w instanceof Error?w.message:String(w)}`);return}}publishBackgroundEvent(_,w,$,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),h.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,Y){this.publishBackgroundEvent(_,w,$,X,Y)}static parseAskUserErrorFromMessage(_){let w=_ instanceof Error?_.message:String(_);if(_&&typeof _==="object"&&_.name==="AskUserError"&&_.query){let X=_;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:w}}let $="__ASK_USER_ERROR__:";if(w.includes($))try{let X=w.substring(w.indexOf($)+$.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:w}}catch(X){return h.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask(_){let{parentSessionId:w,description:$,prompt:X,subagentType:Y,timeout:J,similarTaskIds:D,existingSubSessionId:W,triggerEventId:G,model:Q,fallbackModel:q}=_,H=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,B=this.getSessionComponent();if(!B)throw Error("SessionComponent not found");if(!await B.get(w))throw Error(`Parent session not found: ${w}`);let z;if(W){let f=await B.get(W);if(!f)throw Error(`Sub session not found for resume: ${W}`);let Z=f?.metadata?.created_by;if(Z&&Z!=="subagent")h.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${Z}); reusing anyway`);z=f;try{let L=f?.metadata??{};await B.update(W,{metadata:{...L,reused_sub_session:!0,reused_at:Date.now()}})}catch(L){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:L instanceof Error?L.message:String(L)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${H}`)}else{let f={subagent_type:Y,created_by:"subagent",task_description:$},Z=ew();if(Z){if(Z.messageId)f.messageId=Z.messageId;let L=Z.replyChannel;if(L?.messageId)f.larkMessageId=L.messageId;if(L?.chatId)f.chatId=L.chatId;if(L?.userId)f.larkUserId=L.userId;let C=L?.profile;if(C)f.larkProfile=C}if(G)f.triggerEventId=G;if(z=await B.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:f}),!z)throw Error("Failed to create sub-session")}let U=KU(),V=new AbortController;if(this.processRegistries.size>=this.maxProcessRegistries){if(this.cleanupEmptyProcessRegistries(),this.processRegistries.size>=this.maxProcessRegistries)throw Error(`BackgroundTaskManager.processRegistries \u8FBE\u5230\u4E0A\u9650 ${this.maxProcessRegistries}\uFF08\u542B\u6B8B\u7559 PID\uFF09\uFF0C\u62D2\u7EDD\u521B\u5EFA\u65B0 task\uFF08taskId=${H}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let M=new l2;this.processRegistries.set(H,M);let R=Date.now(),N=`${Y}:bg_${H}`,b={id:H,runId:N,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:R,lastUpdatedAt:R,timeoutMs:J||D2,abortController:V,similarTaskIds:D,triggerEventId:G,model:Q,fallbackModel:q,replyChannel:U};this.tasks.set(H,b),this.abortControllers.set(H,V);let E={backgroundTaskId:H,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,startedAt:R,timeoutMs:J||D2};return this.publishBackgroundEvent(c_.STARTED,E,w,G,U),this.executeTask(H,X,J,w).catch((f)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:H,error:f instanceof Error?f.message:String(f)})}),{taskId:H,subSessionId:z.id}}async executeTask(_,w,$,X){let Y=this.tasks.get(_);if(!Y){h.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let J=Date.now();Y.status="running",Y.startedAt=J,Y.lastUpdatedAt=J;let D=$||D2,W=this.abortControllers.get(_);this.startProgressReporter(_,X||Y.parentSessionId);try{let Q=await this.getSessionComponent().get(Y.subSessionId);if(!Q)throw Error(`Sub session not found: ${Y.subSessionId}`);let q=this.processRegistries.get(_),H=await this.executeWithAbort(Q,w,D,_,W?.signal,Y.similarTaskIds,q,()=>W?.abort(),Y.subagentType);if(W?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let B=Date.now();Y.status="completed",Y.completedAt=B,Y.lastUpdatedAt=B,Y.result=H;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:O,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.COMPLETED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:O})}catch(G){let Q=G instanceof Error?G.message:String(G),q=w_.parseAskUserErrorFromMessage(G),H=Q.toLowerCase().includes("stopped")||Q.toLowerCase().includes("aborted"),B=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(q){Y.status="awaiting-user",Y.error=q.rawErrorMessage,Y.pendingAskUserQuery=q.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:q.query,sessionId:q.sessionId,nodeId:q.nodeId,nodeType:q.nodeType,agentSessionId:q.agentSessionId,error:q.rawErrorMessage,executionTimeMs:B,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.ASK_USER,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:Y.subSessionId,nodeId:q.nodeId,queryPreview:q.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(H){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(Q.startsWith("Task execution timeout after")){Y.status="timeout";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.TIMEOUT,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.FAILED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=Q,h.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:Y.status,error:Q})}finally{this.finalizeTask(_,Y.status);let G=Y?._preserveSubSessionOnExit===!0,Q=this.getSessionComponent();if(!G&&Q?.endSessionCleanup&&Y?.subSessionId)try{await Q.endSessionCleanup(Y.subSessionId)}catch(q){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:q instanceof Error?q.message:String(q)})}else if(G)h.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let Y=y0();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let J={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(c_.PROGRESS,J,w,X.triggerEventId,X.replyChannel)},RU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,D,W,G){let Q=_?.metadata??{},q=Q.task_id,H=Q.task_description||"",B=_.id,O=Q.subagent_type,z=O||G||"general";if(!O&&!G)h.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${B}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),M=await XU(z,{registry:V}),R=H$(z),N=M?.basePrompt||R?.promptOverride||"You are a subagent. Complete this task: {task_description}",b=M?.deniedTools||R?.deniedTools||[],E=M?.allowedTools||R?.allowedTools,f=N.replace(/{task_description}/g,H||"N/A");if(f+=`
|
|
2217
|
+
`}var fD=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),U9=1800000,ID=600000;class J0{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor($){this.env=$}setWorkflowService($){this.workflowService=$}attachWorkflowRun($,J){if(!$||!J)return;let Q=this.workflowRunRegistries.get($);if(!Q)Q=new Set,this.workflowRunRegistries.set($,Q);Q.add(J)}detachWorkflowRun($,J){this.workflowRunRegistries.get($)?.delete(J)}replaceWorkflowRun($,J,Q){if(!$)return;let X=this.workflowRunRegistries.get($);if(!X)return;if(J)X.delete(J);if(Q)X.add(Q)}async propagateStopToWorkflowRuns($,J){let Q=this.workflowRunRegistries.get($);if(!Q||Q.size===0)return{runIds:[],stopResults:[]};let X=Array.from(Q);y.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${$}`);let Y=[];for(let G of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${G}`),Y.push({runId:G,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(G,J),Y.push({runId:G,success:!0})}catch(W){let q=W instanceof Error?W.message:String(W);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${G}) failed (likely already terminal): ${q}`),Y.push({runId:G,success:!1,error:q})}}return Q.clear(),{runIds:X,stopResults:Y}}finalizeTask($,J){if(!$)return;this.stopProgressReporter($),this.progressTimers.delete($);let Q=this.tasks.get($);if(Q){if(this.tasks.delete($),this.terminalTasks.size>=this.maxTerminalTasks){let G=this.terminalTasks.keys().next().value;if(G!==void 0)this.terminalTasks.delete(G)}this.terminalTasks.set($,Q)}let X=this.abortControllers.get($);if(X&&J!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete($),this.workflowRunRegistries.delete($);let Y=this.processRegistries.get($);if(Y&&Y.size()>0)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${Y.size()}, reason=${J})`);y.debug(`[BackgroundTaskManager] finalizeTask taskId=${$} reason=${J}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let $=0;for(let[J,Q]of this.processRegistries)if(Q.size()===0)this.processRegistries.delete(J),$++;return $}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent($){try{if(J0.detectWorkflowShortcutCompat($))return y.info(`[BackgroundTaskManager] Compat rewrite: '${$}' \u2192 '${J0.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),J0.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.($);if(!X||X.type!=="workflow")return;return X.entryAgent??J0.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(J){y.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${$}: ${J}`);return}}static _detectWorkflowShortcutWrapped=U0(($)=>fD.has($),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat($){return J0._detectWorkflowShortcutWrapped($)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession($){if(!$)return;try{let Q=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.($);return typeof Q==="number"&&Q>0?Q:void 0}catch(J){y.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${$}: ${J instanceof Error?J.message:String(J)}`);return}}publishBackgroundEvent($,J,Q,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,Y){this.publishBackgroundEvent($,J,Q,X,Y)}static parseAskUserErrorFromMessage($){let J=$ instanceof Error?$.message:String($);if($&&typeof $==="object"&&$.name==="AskUserError"&&$.query){let X=$;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:J}}let Q="__ASK_USER_ERROR__:";if(J.includes(Q))try{let X=J.substring(J.indexOf(Q)+Q.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:J}}catch(X){return y.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask($){let{parentSessionId:J,description:Q,prompt:X,subagentType:Y,timeout:G,similarTaskIds:W,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z}=$,V=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,F=this.getSessionComponent();if(!F)throw Error("SessionComponent not found");if(!await F.get(J))throw Error(`Parent session not found: ${J}`);let D;if(q){let f=await F.get(q);if(!f)throw Error(`Sub session not found for resume: ${q}`);let j=f?.metadata?.created_by;if(j&&j!=="subagent")y.warn(`[BackgroundTaskManager] Session ${q} was not created by a sub-agent (created_by=${j}); reusing anyway`);D=f;try{let S=f?.metadata??{};await F.update(q,{metadata:{...S,reused_sub_session:!0,reused_at:Date.now()}})}catch(S){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:q,error:S instanceof Error?S.message:String(S)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${q} for task ${V}`)}else{let f={subagent_type:Y,created_by:"subagent",task_description:Q},j=J2();if(j){if(j.messageId)f.messageId=j.messageId;let S=j.replyChannel;if(S?.messageId)f.larkMessageId=S.messageId;if(S?.chatId)f.chatId=S.chatId;if(S?.userId)f.larkUserId=S.userId;let x=S?.profile;if(x)f.larkProfile=x}if(H)f.triggerEventId=H;if(D=await F.create({title:`${Q} (@${Y} subagent)`,parentSessionId:J,metadata:f}),!D)throw Error("Failed to create sub-session")}let M=hD(),_=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 a9;this.processRegistries.set(V,L);let A=Date.now(),Z=`${Y}:bg_${V}`,b={id:V,runId:Z,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:Y,status:"pending",createdAt:A,lastUpdatedAt:A,timeoutMs:G||U9,abortController:_,similarTaskIds:W,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z,replyChannel:M};this.tasks.set(V,b),this.abortControllers.set(V,_);let P={backgroundTaskId:V,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:Y,startedAt:A,timeoutMs:G||U9};return this.publishBackgroundEvent(d0.STARTED,P,J,H,M),this.executeTask(V,X,G,J).catch((f)=>{y.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:V,error:f instanceof Error?f.message:String(f)})}),{taskId:V,subSessionId:D.id}}async executeTask($,J,Q,X){let Y=this.tasks.get($);if(!Y){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let G=Date.now();Y.status="running",Y.startedAt=G,Y.lastUpdatedAt=G;let W=Q||U9,q=this.abortControllers.get($);this.startProgressReporter($,X||Y.parentSessionId);try{let B=await this.getSessionComponent().get(Y.subSessionId);if(!B)throw Error(`Sub session not found: ${Y.subSessionId}`);let U=this.processRegistries.get($),z=await this.executeWithAbort(B,J,W,$,q?.signal,Y.similarTaskIds,U,()=>q?.abort(),Y.subagentType);if(q?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();Y.status="completed",Y.completedAt=V,Y.lastUpdatedAt=V,Y.result=z;let F=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=u2(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let O={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:F,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.COMPLETED,O,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:F})}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=Y.startedAt?Date.now()-Y.startedAt:0,F=Date.now();if(Y.completedAt=F,Y.lastUpdatedAt=F,Y.associatedTaskId=u2(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(U){Y.status="awaiting-user",Y.error=U.rawErrorMessage,Y.pendingAskUserQuery=U.query;let O={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:U.query,sessionId:U.sessionId,nodeId:U.nodeId,nodeType:U.nodeType,agentSessionId:U.agentSessionId,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="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.ASK_USER,O,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:Y.subSessionId,nodeId:U.nodeId,queryPreview:U.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(z){Y.status="stopped";let O={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:B,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.STOPPED,O,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(B.startsWith("Task execution timeout after")){Y.status="timeout";let O={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:B,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.TIMEOUT,O,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let O={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:B,executionTimeMs:V,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.FAILED,O,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=B,y.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:Y.status,error:B})}finally{this.finalizeTask($,Y.status);let H=Y?._preserveSubSessionOnExit===!0,B=this.getSessionComponent();if(!H&&B?.endSessionCleanup&&Y?.subSessionId)try{await B.endSessionCleanup(Y.subSessionId)}catch(U){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:U instanceof Error?U.message:String(U)})}else if(H)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let Y=u2();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let G={backgroundTaskId:$,subSessionId:X.subSessionId,parentSessionId:J,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(d0.PROGRESS,G,J,X.triggerEventId,X.replyChannel)},ID);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,Y,G,W,q,H){let B=$?.metadata??{},U=B.task_id,z=B.task_description||"",V=$.id,F=B.subagent_type,O=F||H||"general";if(!F&&!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"),M=D?.getRegistry?.(),_=await FD(O,{registry:M}),L=_8(O),A=_?.basePrompt||L?.promptOverride||"You are a subagent. Complete this task: {task_description}",Z=_?.deniedTools||L?.deniedTools||[],b=_?.allowedTools||L?.allowedTools,P=A.replace(/{task_description}/g,z||"N/A");if(P+=`
|
|
2162
2218
|
|
|
2163
2219
|
---
|
|
2164
2220
|
|
|
2165
2221
|
# Session Info
|
|
2166
|
-
- task_id: ${
|
|
2167
|
-
- session_id: ${
|
|
2222
|
+
- task_id: ${U||"N/A"}
|
|
2223
|
+
- session_id: ${V}
|
|
2168
2224
|
|
|
2169
2225
|
---
|
|
2170
2226
|
|
|
2171
2227
|
## \u7528\u6237\u6307\u4EE4
|
|
2172
|
-
${
|
|
2228
|
+
${J}
|
|
2173
2229
|
|
|
2174
2230
|
---
|
|
2175
2231
|
|
|
@@ -2177,13 +2233,13 @@ ${w}
|
|
|
2177
2233
|
- \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
|
|
2178
2234
|
- \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
|
|
2179
2235
|
- \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
|
|
2180
|
-
- \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,
|
|
2181
|
-
`;if(
|
|
2182
|
-
`,c.description)
|
|
2183
|
-
`;if(c.goals_and_expected_deliverables)
|
|
2184
|
-
`;if(
|
|
2185
|
-
`;for(let
|
|
2186
|
-
`}i.push(
|
|
2236
|
+
- \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,G&&G.length>0)try{let x=this.env?.getComponent?.("task");if(x){let i=[];for(let g of G)try{let c=await x.getTask(g);if(!c){y.warn(`[delegate] Similar task #${g} not found, skipping`);continue}let O0=await x.listOperations({taskId:g,limit:10}),M0=`### Task #${c.id}: ${c.title}
|
|
2237
|
+
`;if(M0+=`- Status: ${c.status}
|
|
2238
|
+
`,c.description)M0+=`- Description: ${c.description}
|
|
2239
|
+
`;if(c.goals_and_expected_deliverables)M0+=`- Goals: ${c.goals_and_expected_deliverables}
|
|
2240
|
+
`;if(O0&&O0.length>0){M0+=`- Recent Operations:
|
|
2241
|
+
`;for(let g0 of O0)M0+=` - [${g0.actionType}] ${g0.actionTitle}: ${g0.actionDescription||""}
|
|
2242
|
+
`}i.push(M0)}catch(c){y.warn(`[delegate] Failed to fetch similar task #${g}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)P+=`
|
|
2187
2243
|
|
|
2188
2244
|
---
|
|
2189
2245
|
|
|
@@ -2191,19 +2247,19 @@ ${w}
|
|
|
2191
2247
|
|
|
2192
2248
|
The following similar tasks and their operation records can serve as reference:
|
|
2193
2249
|
|
|
2194
|
-
`,
|
|
2195
|
-
`),
|
|
2250
|
+
`,P+=i.join(`
|
|
2251
|
+
`),P+=`
|
|
2196
2252
|
|
|
2197
2253
|
---
|
|
2198
2254
|
|
|
2199
|
-
Use these as guidance to improve task execution efficiency.`}}catch(
|
|
2255
|
+
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=PD(this.env),i=ED({registry:x,similarTaskIds:G??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)P+=`
|
|
2200
2256
|
|
|
2201
2257
|
---
|
|
2202
2258
|
|
|
2203
|
-
${i.markdown}`}}catch(
|
|
2259
|
+
${i.markdown}`}}catch(x){y.warn("[delegate] Failed to inject reuse candidate section",{error:x instanceof Error?x.message:String(x)})}let f=L?{...L,allowedTools:b}:b?{id:O,name:O,mode:"subagent",description:_?.description||"Custom agent",allowedTools:b,deniedTools:Z}:void 0;SD(D,O,A,f,Z);let S=M?.get(O)?.type==="workflow"?J:P;return new Promise((x,i)=>{let g=async()=>{try{await W?.killAll()}catch(H0){y.warn("[delegate] ProcessRegistry.killAll failed",{error:H0 instanceof Error?H0.message:String(H0)})}},c=!1,O0,M0,g0=this.tasks.get(X);if(g0?.runId)M0=g0.runId;let Y6=()=>{if(Y&&G6)try{Y.removeEventListener("abort",G6)}catch{}},G6;if(G6=()=>{if(c)return;if(c=!0,O0)clearTimeout(O0);Y6();try{let H0=this.env?.getComponent?.("agent");if(H0?.abortRun&&M0)H0.abortRun(M0,"task_signal_abort")}catch{}g().catch(()=>{}).then(()=>{i(Error("Task execution stopped"))})},O0=setTimeout(()=>{if(c)return;if(c=!0,O0)clearTimeout(O0);Y6();try{q?.()}catch{}try{let H0=this.env?.getComponent?.("agent");if(H0?.abortRun&&M0)H0.abortRun(M0,"task_timeout")}catch{}g().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${Q}ms`))})},Q),Y)Y.addEventListener("abort",G6);let r8=()=>{let H0=g0?.model,a8=g0?.fallbackModel,s8=g0?.fallbackModels;return this.env.handle_query?.(S,{sessionId:V,deniedTools:Z.length>0?Z:void 0,agentType:O,abort:Y,runId:M0,...H0?{model:H0}:{},...a8?{fallbackModel:a8}:{},...Array.isArray(s8)?{fallbackModels:s8}:{}})};(W?f7(W,()=>z8(X,()=>r8())):z8(X,()=>r8()))?.then((H0)=>{if(c)return;if(c=!0,O0)clearTimeout(O0);Y6(),x(H0)}).catch((H0)=>{if(c)return;if(c=!0,O0)clearTimeout(O0);Y6(),i(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(W){y.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:$,runId:J.runId,error:W instanceof Error?W.message:String(W)})}J.completedAt=Q,J.lastUpdatedAt=Q;try{await this.processRegistries.get($)?.killAll()}catch(W){y.warn("[delegate] stopTask killAll failed",{taskId:$,error:W instanceof Error?W.message:String(W)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns($,"Task stopped by user"),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(d0.STOPPED,G,J.parentSessionId,J.triggerEventId,J.replyChannel),this.finalizeTask($,"stopped"),{success:!0,task:J,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:Y}}getTask($){return this.tasks.get($)??this.terminalTasks.get($)}async getSubSessionActivity($){let J=this.getTask($);if(!J)return;let Q=this.getSessionComponent();if(!Q?.get)return;try{let X=await Q.get(J.subSessionId);if(!X)return;return{messageCount:X.messageCount??0,updatedAt:X.updatedAt??J.lastUpdatedAt??J.createdAt}}catch{return}}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent($){if(!$)return!1;for(let J of this.tasks.values())if(J.parentSessionId===$&&(J.status==="pending"||J.status==="running"))return!0;return!1}async stopAllForParent($){if(!$)return{stoppedTaskIds:[]};let J=[];for(let[Q,X]of this.tasks)if(X.parentSessionId===$&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask(Q))?.success)J.push(Q)}catch(Y){y.warn(`[BackgroundTaskManager] stopAllForParent failed for ${Q}: ${Y instanceof Error?Y.message:String(Y)}`)}return{stoppedTaskIds:J}}async forceStopAllAcrossParents(){let $=new Set,J=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let Q of J){if($.has(Q))continue;$.add(Q);let Y=this.tasks.get(Q)??this.terminalTasks.get(Q);try{await this.processRegistries.get(Q)?.killAll()}catch(W){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${Q}: ${W instanceof Error?W.message:String(W)}`)}try{await this.propagateStopToWorkflowRuns(Q,"force stop all")}catch(W){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${Q}: ${W instanceof Error?W.message:String(W)}`)}let G=!1;if(Y&&(Y.status==="running"||Y.status==="pending"))try{Y.status="stopped",Y.completedAt=Date.now(),Y.lastUpdatedAt=Y.completedAt,Y.abortController?.abort(),G=!0}catch(W){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${Q}: ${W instanceof Error?W.message:String(W)}`)}if(G&&Y){let W={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:Y.parentSessionId,status:"stopped",description:Y.description,error:"force stop all",executionTimeMs:Y.startedAt&&Y.completedAt?Y.completedAt-Y.startedAt:0,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(d0.STOPPED,W,Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose($){for(let[,X]of this.progressTimers)try{clearInterval(X)}catch{}this.progressTimers.clear();let J=$?.skipAbortRunningTasks===!0;if($?.waitForRunningTasks===!0&&J){let X=Date.now(),Y=600000;while(Date.now()-X<600000){let G=0;for(let[,W]of this.tasks)if(W.status==="running"||W.status==="pending")G++;if(G===0)break;y.info(`[BackgroundTaskManager] dispose waiting for ${G} running task(s)`),await new Promise((W)=>setTimeout(W,200))}}for(let[,X]of this.abortControllers){if(J)break;try{X.abort()}catch{}}this.abortControllers.clear();for(let[,X]of this.processRegistries)try{await X.killAll()}catch(Y){y.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:Y instanceof Error?Y.message:String(Y)})}this.processRegistries.clear();for(let X of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(X,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),y.info("[BackgroundTaskManager] Disposed")}}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 $3($){return $.env?.getComponent?.("agent")?.getRegistry?.()}function J3($){let J=$.env,X=$.backgroundTaskManager??new J0(J),Y=$3($);$._backgroundTaskManager=X;let G={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
|
|
2204
2260
|
|
|
2205
2261
|
Available agent types:
|
|
2206
|
-
${
|
|
2262
|
+
${LD(Y)}
|
|
2207
2263
|
|
|
2208
2264
|
When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
2209
2265
|
|
|
@@ -2232,8 +2288,14 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2232
2288
|
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2233
2289
|
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2234
2290
|
- **reason**: Brief reason for calling this tool (optional)
|
|
2235
|
-
- **similar_task_ids**: Similar task IDs (max 3) to reference for improving sub-agent execution efficiency. Search for similar tasks using \`task_search\` or \`task_list\` before calling this tool.`,parameters:
|
|
2236
|
-
`),metadata:{execution_time_ms:Date.now()-
|
|
2291
|
+
- **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:eJ,execute:async(W,q)=>{let H=Date.now(),B=eJ.parse(W),{description:U,prompt:z,subagent_type:V="general",timeout:F,reason:O,similar_task_ids:D}=B,M=q.session_id||"default",_=B.triggerEventId??vD();if(_&&_!==B.triggerEventId)y.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${_}`);if(y.info(`[delegate_task] Called: description=${U}, subagent_type=${V}, triggerEventId=${_??"(none)"}`),_){let f=T7();if(f)try{if(!await f.getEventById(_))return{success:!1,output:"",error:`Unknown triggerEventId: ${_} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-H}}}catch(j){return{success:!1,output:"",error:`Failed to verify triggerEventId ${_}: ${j instanceof Error?j.message:String(j)}`,metadata:{execution_time_ms:Date.now()-H}}}else y.warn(`[delegate_task] triggerEventId=${_} supplied but no shared EventStore registered; skipping verification`)}let L=$3($);if(!MD(V,L))return{success:!1,output:"",error:`Unknown subagent type: ${V}`,metadata:{execution_time_ms:Date.now()-H}};let A=$.getTagService(),Z=z,b={prompt:Z,subagentType:V,timeout:F,reason:O,tagService:A},P={component:{name:"task",version:"1.0.0"},data:b,metadata:{sessionId:M},phase:"before",hookPoint:Q0.DELEGATE_BEFORE};return await S0.execute(Q0.DELEGATE_BEFORE,b,{sessionId:M}),Z=b.prompt,await yD(X,M,U,Z,b.subagentType,b.timeout,D,B.sub_session_id,_,q.model,q.fallbackModel,q.fallbackModels)}};return G.execute=U0(G.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),G}function TD(){let $=J2();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 vD=U0(TD,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function xD(){let $=J2()?.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 hD=U0(xD,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function yD($,J,Q,X,Y,G,W,q,H,B,U,z){let V=Date.now();try{let F=Y,O=X,D,M=$.resolveEntryAgent(Y);if(M)D=Y,F=M,O=CD({workflowName:D,originalPrompt:X,description:Q}),y.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${M}'`);let{taskId:_,subSessionId:L}=await $.createTask({parentSessionId:J,description:Q,prompt:O,subagentType:F,timeout:G,similarTaskIds:W,originalWorkflowName:D,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${_}`,`\uD83D\uDCDD Description: ${Q}`,`\uD83E\uDD16 Sub-agent: ${F}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(G||U9)/1000}s`,"",`Use stop_task with task_id="${_}" to cancel this task.`].join(`
|
|
2292
|
+
`),metadata:{execution_time_ms:Date.now()-V,sessionId:L,background:!0,status:"accepted",bgProcessId:_}}}catch(F){return{success:!1,output:"",error:F instanceof Error?F.message:String(F),metadata:{execution_time_ms:Date.now()-V}}}}var A$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};z0();var gD=20;var kD=["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 mD($){if(!$)return[];let J;try{J=JSON.parse($)}catch{return[]}if(!J||typeof J!=="object"||Array.isArray(J))return[];let Q=J.similar_task_ids;if(!Array.isArray(Q))return[];let X=[],Y=new Set;for(let G of Q){if(typeof G!=="number")continue;if(!Number.isInteger(G)||G<=0)continue;if(Y.has(G))continue;if(Y.add(G),X.push(G),X.length>=gD)break}return X}function uD($){switch($){case"completed":case"cancelled":case"paused":case"archived":return"reopen";case"todo":case"active":default:return"enhance"}}function Q3($){return $==="paused"?"active":"todo"}var R8="__NEW_TASK_ID__",A8="#__NEW_TASK_ID__";function lD($){switch($.scenario){case"reuse":return cD($);case"reopen":return pD($);case"reopen_enhance":return dD($);case"remount":return iD($);case"soft_reuse":return nD($)}}function L8($){return $.newTaskId>0?String($.newTaskId):R8}function R0($){return $.newTaskId>0?`#${$.newTaskId}`:A8}function z9($){let J=$.targetTask;if(!J)return"";return`#${$.targetTaskId} [${J.type}] ${J.title}
|
|
2293
|
+
\u72B6\u6001\uFF1A${J.status}`}function cD($){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","",z9($),"\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 ${R0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${R0($)}\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 ${R0($)}\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(`
|
|
2294
|
+
`)}function pD($){let J=$.targetTask?.status??"completed",Q=Q3(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","",z9($),`\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 ${R0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${R0($)}\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 ${R0($)}\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(`
|
|
2295
|
+
`)}function dD($){let J=$.targetTask?.status??"completed",Q=Q3(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","",z9($),`\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 ${R0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${R0($)}\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 ${R0($)}\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(`
|
|
2296
|
+
`)}function iD($){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=${L8($)}, parent_task_id=${$.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${R0($)}\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(${L8($)}) \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=${L8($)}, 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(`
|
|
2297
|
+
`)}function nD($){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","",z9($),"","\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 ${R0($)}\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 ${R0($)}\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(`
|
|
2298
|
+
`)}function rD($){let J=$.toLowerCase();return kD.some((Q)=>Q.endsWith("_")||Q.endsWith("*")?J.startsWith(Q.slice(0,-1)):J===Q)}function aD($,J){let Q=(X,Y)=>{if(Array.isArray(X)){X.forEach((G,W)=>Q(G,`${Y}[${W}]`));return}if(!X||typeof X!=="object")return;for(let[G,W]of Object.entries(X)){let q=Y?`${Y}.${G}`:G;if(rD(G))throw Error(`[assertNoLeakage] leakage key detected at ${q}: "${G}"`);Q(W,q)}};Q($,"state"),Q(J,"questions")}function sD($,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 k_=U0(mD,"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(",")})}),m_=U0(uD,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),u_=U0(lD,"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($)})}),l_=U0(aD,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:($)=>({stateKeys:V9($[0]),questionKeys:V9($[1])})}),c_=U0(sD,"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 V9($,J=[],Q=0){if(J.length>=40||Q>4)return J;if(Array.isArray($)){for(let X of $.slice(0,3))V9(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);V9($[X],J,Q+1)}return J}import{execSync as $O}from"child_process";var X3="unknown",oD='{"type":"unknown"}';function tD(){return{task_id:K.number().describe("Task ID")}}function eD($){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 j8($){return K.preprocess(eD,K.object({...tD(),...$}))}var Y3=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
|
|
2237
2299
|
`+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
|
|
2238
2300
|
`+`**\u8C03\u7528\u524D\u5FC5\u987B\u5148\u8C03\u7528 task_tree(depth=2)** \u67E5\u770B\u73B0\u6709\u4EFB\u52A1\u6811\u7ED3\u6784\uFF0C\u907F\u514D\u91CD\u590D\u521B\u5EFA\u6839\u4EFB\u52A1\u3001\u907F\u514D\u5B64\u513F\u4EFB\u52A1\u3002
|
|
2239
2301
|
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
@@ -2241,7 +2303,7 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2241
2303
|
`+` B. \u5F52\u5C5E\u5230\u73B0\u6709\u4E3B\u9898\u805A\u7C7B\uFF08\u975E longterm \u6839\uFF0C\u4F46\u540C\u4E3B\u9898\uFF09\u2192 parent_task_id = \u8BE5\u6839 ID
|
|
2242
2304
|
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
2243
2305
|
`+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
|
|
2244
|
-
`+"\u6839\u636E\u8282\u70B9 id \u9009\u62E9\u5408\u9002\u7684\u7236\u4EFB\u52A1 ID\uFF08\u6765\u81EA tree \u8F93\u51FA\uFF0C**\u4E0D\u8981\u786C\u7F16\u7801**\u6570\u5B57\uFF09\u3002"),context:
|
|
2306
|
+
`+"\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]}')}),G3=j8({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.")}),W3=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")}),q3=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")}),H3=j8({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)")}),B3=K.object({task_id:K.number().describe("Task ID")}),U3=j8({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")}),V3=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")}),z3=K.object({task_ids:K.array(K.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),D3=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$();a();a();var JO=n("task-child-context"),QO=["commit","token","secret","password","api_key"];function N8($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map(N8);if(typeof $!=="object")return $;let J={};for(let[Q,X]of Object.entries($)){let Y=Q.toLowerCase();if(QO.some((G)=>Y.includes(G)))continue;J[Q]=N8(X)}return J}function XO($){let{parent:J,overrides:Q={}}=$,X=Q.contextInherit!==!1,Y=Q.inheritTags===!0,G=Q.projectPath??J.projectPath??"unknown",W={};if(J.contextJson&&J.contextJson.trim().length>0)try{let U=JSON.parse(J.contextJson);if(U&&typeof U==="object"&&!Array.isArray(U))W=U}catch(U){JO.debug(`[task-child-context] parent #${J.taskId} context is malformed JSON; continuing with empty inherited context (${U instanceof Error?U.message:String(U)})`),W={}}let q={};if(X){if(W.worktree_path!==void 0&&Q.worktreePath===void 0)q.worktree_path=W.worktree_path;if(W.branch!==void 0&&Q.branch===void 0)q.branch=W.branch;if(W.parent_branch!==void 0)q.parent_branch=W.parent_branch;if(W.type!==void 0)q.type=W.type;if(W.prior_context&&typeof W.prior_context==="object"){let z=W.prior_context,V={};for(let[F,O]of Object.entries(z)){if(F.toLowerCase()==="commit")continue;V[F]=O}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(W)){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=N8(q);return{project_path:G,context:JSON.stringify(B),inheritedTags:Y?J.tags??[]:[]}}var O3=n("task:tools:create");function YO($){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 GO(){try{let $=$O("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 c2($){return{name:"task_create",description:`
|
|
2245
2307
|
Create a new task for tracking work.
|
|
2246
2308
|
|
|
2247
2309
|
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
@@ -2259,6 +2321,30 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2259
2321
|
step 2: read the tree, then decide per "Decision Tree" below
|
|
2260
2322
|
step 3: task_create({...})
|
|
2261
2323
|
|
|
2324
|
+
## \u26A0\uFE0F STEP 1 \u2014 FIND SIMILAR TASKS FIRST (Task #4467)
|
|
2325
|
+
|
|
2326
|
+
Before creating a task, you **MUST** first look for existing tasks
|
|
2327
|
+
that cover the same ground, and record them in
|
|
2328
|
+
\`context.similar_task_ids\`. This lets the decision model detect
|
|
2329
|
+
duplicates and suggest reusing / reopening an existing task instead
|
|
2330
|
+
of piling up another root.
|
|
2331
|
+
|
|
2332
|
+
Workflow:
|
|
2333
|
+
step 1: task_search({keywords: [...]}) or task_get(...) to find
|
|
2334
|
+
existing tasks related to this request
|
|
2335
|
+
step 2: collect the relevant task ids (0 or more)
|
|
2336
|
+
step 3: task_create({..., context: {..., similar_task_ids: [id1, id2]}})
|
|
2337
|
+
|
|
2338
|
+
\`context.similar_task_ids\` is **required** (may be an empty array \`[]\`
|
|
2339
|
+
if you searched and found nothing related). It is an array of task ids.
|
|
2340
|
+
|
|
2341
|
+
The decision check runs on \`task:before.create\` and only **advises** \u2014
|
|
2342
|
+
the task is always created. If the output contains a
|
|
2343
|
+
\`[TASK_CREATE_HINT]\` section, you **MUST** read and verify it:
|
|
2344
|
+
verify with \`task_get\`, then either execute the suggested
|
|
2345
|
+
\`task_update\` (reusing / reopening / re-parenting) or explicitly
|
|
2346
|
+
state why it was not adopted. Never ignore it.
|
|
2347
|
+
|
|
2262
2348
|
## Decision Tree \u2014 How to choose parent_task_id
|
|
2263
2349
|
|
|
2264
2350
|
Walk these paths in order:
|
|
@@ -2287,6 +2373,37 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2287
2373
|
- Same-theme tasks cluster under one parent
|
|
2288
2374
|
- Long-tail/stranded tasks should be archived or merged
|
|
2289
2375
|
|
|
2376
|
+
## \u26A0\uFE0F Goals \u5B50\u9879\u62C6\u5206\u89C4\u5219 (Task #4791)
|
|
2377
|
+
|
|
2378
|
+
\`goals_and_expected_deliverables\` **MUST** be written as
|
|
2379
|
+
**numbered sub-items** (\u7F16\u53F7\u5B50\u9879) that can each be verified
|
|
2380
|
+
one by one (\u9010\u6761\u9A8C\u6536) \u2014 for \`type=normal\` tasks:
|
|
2381
|
+
|
|
2382
|
+
1. \u5B9E\u73B0 X\uFF08\u542B\u6587\u4EF6\u8DEF\u5F84\uFF09
|
|
2383
|
+
2. \u6D4B\u8BD5 Y \u8986\u76D6 Z \u573A\u666F\uFF08pass/fail \u8BA1\u6570\uFF09
|
|
2384
|
+
3. \u6587\u6863 W \u843D\u76D8\u5230 <path>
|
|
2385
|
+
|
|
2386
|
+
\u26A0\uFE0F For \`type=longterm\` / \`type=cycle\` tasks there is no
|
|
2387
|
+
per-item completion acceptance\uFF08\u4E0D\u8D70\u9010\u6761 complete \u9A8C\u6536\uFF09, so the
|
|
2388
|
+
MUST above does not apply; for those, it is **strongly recommended**
|
|
2389
|
+
(\u5EFA\u8BAE) to split goals into staged, individually checkable sub-items
|
|
2390
|
+
(\u9636\u6BB5\u6027\u53EF\u5224\u5B50\u9879) instead of one vague sentence.
|
|
2391
|
+
|
|
2392
|
+
Why: when the task is completed, the completion hook
|
|
2393
|
+
(task:after.complete) judges the whole goal against the
|
|
2394
|
+
operation-record chain, using each sub-item as fine-grained
|
|
2395
|
+
evidence (\u9010\u6761\u5BF9\u7167\u7684\u4F9D\u636E). Vague one-line goals (\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF0C
|
|
2396
|
+
\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D) give the judge nothing to check and
|
|
2397
|
+
make a completion hint much more likely.
|
|
2398
|
+
|
|
2399
|
+
Reference the four atomic assertion forms (Task #4768
|
|
2400
|
+
\u56DB\u539F\u5B50\u5F62\u6001) when writing each sub-item:
|
|
2401
|
+
|
|
2402
|
+
- \u6587\u4EF6\u65AD\u8A00 (file assertion): file exists / size / content grep
|
|
2403
|
+
- \u8FDB\u7A0B\u65AD\u8A00 (process assertion): command exit code / stdout match
|
|
2404
|
+
- \u6D4B\u8BD5\u65AD\u8A00 (test assertion): pass/fail counts, no NEW fail
|
|
2405
|
+
- \u72B6\u6001\u65AD\u8A00 (state assertion): version number / HTTP 200 / status field
|
|
2406
|
+
|
|
2290
2407
|
## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
|
|
2291
2408
|
|
|
2292
2409
|
A task MUST carry spatio-temporal context so it survives task-handoff
|
|
@@ -2381,28 +2498,50 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2381
2498
|
env-injected value is 0 / negative / non-integer, it's treated as
|
|
2382
2499
|
missing \u2014 only positive integers are honored.
|
|
2383
2500
|
|
|
2384
|
-
`,parameters:
|
|
2385
|
-
|
|
2501
|
+
`,parameters:Y3,execute:async(J,Q)=>{let X=Y3.parse(J),Y=Q.session_id||"unknown",G=GO(),W=X.context,q=W9().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!==X3,z=U?B:void 0,V=X.tags,F;if(H!==void 0)try{let O=await $.getTask(H);if(O){let D=XO({parent:{taskId:O.id,projectPath:O.project_path,contextJson:O.context??"",tags:O.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;F=D.context}}catch(O){O3.debug(`[task_create] failed to pre-load parent #${H} for context inheritance: ${O instanceof Error?O.message:String(O)}`)}try{let O=X.context===oD?void 0:X.context,D=O?JSON.parse(O):{},M=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(F)try{let _=JSON.parse(F);if(_&&typeof _==="object"&&!Array.isArray(_)){for(let[L,A]of Object.entries(_))if(M[L]===void 0)M[L]=A}}catch{}if(!M.created_at)M.created_at=new Date().toISOString();if(!M.worktree_path&&G)M.worktree_path=G;W=JSON.stringify(M)}catch{W=X.context}try{let O=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:Y,project_path:z??(U?B:X3),context:W});l2(O.id),O3.info(`[createTask] Trace: Task #${O.id} created, currentTaskId=${O.id} set in EnvContext`);let D=YO(O.context),M=D?D.replaceAll(A8,`#${O.id}`).replaceAll(R8,String(O.id)):"";return{success:!0,output:`Task created successfully: #${O.id} - ${O.title}`+(M?`
|
|
2502
|
+
|
|
2503
|
+
${M}`:""),metadata:{execution_time_ms:0,task_id:O.id,status:O.status,createdAt:O.createdAt}}}catch(O){return{success:!1,output:"",error:O instanceof Error?O.message:String(O),metadata:{execution_time_ms:0}}}}}}function p2($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:G3,execute:async(J,Q)=>{let X=G3.parse(J);try{if(X.include_operations){let Y=await $.getTaskWithOperations(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let G=Y.task,W=G&&typeof G==="object"?{...G,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}else{let Y=await $.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function d2($){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
|
|
2504
|
+
`+"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:W3,execute:async(J,Q)=>{let X=W3.parse(J);try{let Y=await $.listTasks({status:X.status,priority:X.priority,type:X.type,limit:X.limit,offset:X.offset,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({total:Y.total,count:Y.tasks.length,truncated:Y.total>Y.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:Y.tasks}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function i2($){return{name:"task_search",description:"Search tasks by keywords across title, description, goals, tags, and operation records. Use this when you need to find tasks related to a "+"topic, feature, bug, or area of work \u2014 even when the keyword is only "+`in description / goals / tags / past operation logs.
|
|
2386
2505
|
|
|
2387
2506
|
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
2388
2507
|
|
|
2389
|
-
If \`keywords\` is empty, returns no results.`,parameters:
|
|
2508
|
+
If \`keywords\` is empty, returns no results.`,parameters:q3,execute:async(J,Q)=>{let X=q3.parse(J);try{let Y=await $.searchTasksByKeywords(X.keywords,{limit:X.limit,offset:X.offset,excludeTaskId:X.exclude_task_id,status:X.status,priority:X.priority,type:X.type,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({tasks:Y.tasks,total:Y.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function Z8($){return{name:"task_batch_archive",description:`Batch archive multiple tasks at once. Sets all specified tasks to 'archived' status and creates operation records for each.
|
|
2390
2509
|
|
|
2391
2510
|
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
2392
2511
|
|
|
2393
|
-
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:
|
|
2512
|
+
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:V3,execute:async(J,Q)=>{let X=V3.parse(J),Y=X.task_ids,G=Q.session_id||"batch-archive";if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let W=[],q=0;for(let B of Y)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++,W.push({id:B,success:!0});else W.push({id:B,success:!1,error:"Task not found"})}catch(U){W.push({id:B,success:!1,error:U instanceof Error?U.message:String(U)})}return{success:!W.some((B)=>!B.success),output:JSON.stringify({archived_count:q,total:Y.length,errors:W.filter((B)=>!B.success).map((B)=>({id:B.id,error:B.error})),results:W},null,2),metadata:{execution_time_ms:0}}}}}function P8($){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
2394
2513
|
|
|
2395
2514
|
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
2396
2515
|
|
|
2397
|
-
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:
|
|
2516
|
+
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:z3,execute:async(J,Q)=>{let Y=z3.parse(J).task_ids;if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let G=[],W=0;for(let H of Y)try{if(await $.deleteTask(H))W++,G.push({id:H,success:!0});else G.push({id:H,success:!1,error:"Task not found"})}catch(B){G.push({id:H,success:!1,error:B instanceof Error?B.message:String(B)})}return{success:!G.some((H)=>!H.success),output:JSON.stringify({deleted_count:W,total:Y.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$();a();var WO=n("tool:update-task");async function qO($,J,Q){let X=new Set,Y=Q;while(Y!==null&&Y!==void 0){if(Y===J)return!0;if(X.has(Y))break;X.add(Y);let G=await $.getTask(Y);if(!G)break;Y=G.parent_task_id}return!1}function n2($){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:H3,execute:async(J,Q)=>{let X=H3.parse(J),Y=Q.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await qO($,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=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(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await $.createOperation({taskId:X.task_id,sessionId:Y,actionType:"progress",actionTitle:X.current_status||`Updated: ${X.status||`${X.progress}%`}`,actionDescription:JSON.stringify({status:X.status,progress:X.progress,current_status:X.current_status})});return l2(G.id),WO.info(`[updateTask] Trace: Task #${G.id} updated, currentTaskId=${G.id} set in EnvContext`),{success:!0,output:`Task updated: #${G.id} - ${G.title}`,metadata:{execution_time_ms:0,task:G}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function w8($){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:B3,execute:async(J,Q)=>{let X=B3.parse(J);try{if(!await $.deleteTask(X.task_id))return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Task deleted: #${X.task_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}q$();a();var HO=n("task:tools:complete"),BO=`
|
|
2398
2517
|
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
2399
2518
|
|
|
2400
2519
|
**Before calling this tool**, you MUST:
|
|
2401
2520
|
|
|
2402
2521
|
1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
|
|
2403
2522
|
- Use \`task_get(task_id=<id>)\` to fetch the full task record.
|
|
2404
|
-
2. **Validate
|
|
2405
|
-
-
|
|
2523
|
+
2. **Validate whether each goal sub-item was achieved** (${M2}).
|
|
2524
|
+
- Goals should be numbered sub-items (\u7F16\u53F7\u5B50\u9879, see task_create rules). Check
|
|
2525
|
+
each sub-item against the operation-record chain (\u64CD\u4F5C\u8BB0\u5F55\u94FE) and the
|
|
2526
|
+
deliverable evidence (context.deliverable_storage_path).
|
|
2527
|
+
- The completion hook (task:after.complete) judges the whole goal vs.
|
|
2528
|
+
deliverables; numbered sub-items give it finer-grained evidence to
|
|
2529
|
+
reason with (\u9010\u6761\u5BF9\u7167\u7684\u8BC1\u636E\u7C92\u5EA6). If it detects that the goal or
|
|
2530
|
+
deliverables appear unmet, the task context will carry a
|
|
2531
|
+
\`[${l$}]\`.
|
|
2532
|
+
- **If you receive a [${l$}]**, you MUST verify it
|
|
2533
|
+
(${F2}): re-read the task via \`task_get\`, then do exactly one of:
|
|
2534
|
+
(a) \u786E\u8BA4\u672A\u5B8C\u6210 \u2192 \`task_update(task_id=<id>, status=todo)\` reopen and continue; or
|
|
2535
|
+
(b) \u786E\u8BA4\u5DF2\u5B8C\u6210 \u2192 \`task_operation_create\` (milestone_type=decision,
|
|
2536
|
+
milestone_title=<\u4E00\u884C\u7ED3\u8BBA>) state why the sub-items are actually
|
|
2537
|
+
met (\u8BF4\u660E\u7406\u7531).
|
|
2538
|
+
Never ignore it (\u4E0D\u5141\u8BB8\u65E0\u89C6).
|
|
2539
|
+
- If the goal and delivery mismatch **without** a hint, either:
|
|
2540
|
+
(a) extend the task via \`task_update\`, or
|
|
2541
|
+
(b) record the discrepancy via \`task_operation_create\`
|
|
2542
|
+
(milestone_type=decision) \u2014 the reason **must** land in the
|
|
2543
|
+
operation record (\u5FC5\u987B\u843D\u5230\u64CD\u4F5C\u8BB0\u5F55\u91CC), not merely a line in
|
|
2544
|
+
your final report (\u4E0D\u80FD\u53EA\u5728\u62A5\u544A\u91CC\u5E26\u4E00\u53E5).
|
|
2406
2545
|
3. **Provide \`deliverable_storage_path\`** parameter with the deliverable's address:
|
|
2407
2546
|
- Feishu doc URL (e.g., https://my.feishu.cn/docx/abc)
|
|
2408
2547
|
- Local file path (e.g., /tmp/report.md)
|
|
@@ -2418,23 +2557,22 @@ The \`deliverable_storage_path\` will be persisted to the task's \`context.deliv
|
|
|
2418
2557
|
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
2419
2558
|
|
|
2420
2559
|
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
2421
|
-
`.trim();function
|
|
2422
|
-
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${
|
|
2423
|
-
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:
|
|
2560
|
+
`.trim();function r2($){return{name:"task_complete",description:BO,parameters:U3,execute:async(J,Q)=>{let X=U3.parse(J),Y=Q.session_id||"unknown";try{let G=await $.getTask(X.task_id);if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(G.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let W=await $.completeTask(X.task_id,Y,X.deliverable_storage_path);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return l2(void 0),HO.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${W.id} - ${W.title}
|
|
2561
|
+
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${W.id} - ${W.title}
|
|
2562
|
+
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:W}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function M3($,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 F3($,J){if(J<0)return $;if(J===0)return $.map((Q)=>({...Q,children:[]}));return $.map((Q)=>({...Q,children:F3(Q.children,J-1)}))}function K3($){let J=0;for(let Q of $)J+=1+K3(Q.children);return J}function UO($){let J=new Map,Q=new Map,X=[];for(let Y of $)J.set(Y.id,{id:Y.id,title:Y.title,status:Y.status,type:Y.type,priority:Y.priority,progress:Y.progress,children:[]});for(let Y of $){let G=Y.parent_task_id;if(G!==void 0&&G!==null&&J.has(G)){let W=Q.get(G)||[];W.push(Y),Q.set(G,W)}else X.push(Y)}for(let[Y,G]of Q.entries()){let W=J.get(Y);G.sort(M3),W.children=G.map((q)=>J.get(q.id))}return X.sort(M3),X.map((Y)=>J.get(Y.id))}function a2($){return{name:"task_tree",description:"View the task tree (forest) with optional filters. Use this BEFORE task_create to decide whether to create a root task (omit parent_task_id) or attach to an existing parent. "+"depth: 0=\u53EA\u6839\u4EFB\u52A1, 1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1, 2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1 (default), "+"-1 or omitted as -1=\u65E0\u9650\u5C42\u7EA7. "+`Returns { total, truncated, depth, parent_task_id, nodes } where:
|
|
2424
2563
|
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
2425
2564
|
- truncated: always false for now (no pagination cap on tree)
|
|
2426
2565
|
- depth: the resolved depth value
|
|
2427
2566
|
- parent_task_id: the root's id, or null for forest mode
|
|
2428
2567
|
- nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
|
|
2429
|
-
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:
|
|
2568
|
+
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:D3,execute:async(J,Q)=>{let X=D3.parse(J);try{let Y=[],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)Y=[];else{let B=await $.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[H,...B]}}else Y=(await $.listTasks({status:X.status,priority:X.priority,type:X.type,include_archived:X.include_archived,limit:9999,offset:0})).tasks;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(X.status)Y=Y.filter((H)=>H.status===X.status);if(X.priority)Y=Y.filter((H)=>H.priority===X.priority);if(X.type)Y=Y.filter((H)=>H.type===X.type);if(!X.include_archived)Y=Y.filter((H)=>H.status!=="archived")}let W=UO(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)W=F3(W,X.depth);let q=K3(W);return{success:!0,output:JSON.stringify({total:q,truncated:!1,depth:X.depth,parent_task_id:G,nodes:W}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}var D9=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),b8=100,E8=500,O9=5000,VO=1,M9=200,j3=K.string().min(b8,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${b8} \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(E8,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${E8} \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 ${b8}-${E8} \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"),Z3=K.string().min(VO,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(M9,{message:`milestone_title \u8D85\u8FC7 ${M9} \u5B57\u7B26\uFF0C\u5EFA\u8BAE\u7CBE\u7B80\uFF08\u4E00\u884C\u6807\u9898\u5373\u53EF\uFF09\u3002`}).describe("\u91CC\u7A0B\u7891\u6807\u9898\uFF08milestone_title\uFF09\uFF1A\u8FBE\u6210\u7684\u91CC\u7A0B\u7891/\u72B6\u6001\u7684\u4E00\u53E5\u8BDD\u6807\u9898\uFF1B"+"\u5FC5\u586B\uFF0C1-200 \u5B57\u7B26\u3002"),P3=K.string().max(O9,{message:`milestone_description \u8D85\u8FC7 ${O9} \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"),zO=K.object({task_id:K.number().describe("Task ID"),milestone_type:D9.optional(),milestone_title:Z3.optional(),milestone_description:P3,process_description:j3.optional(),action_type:D9.optional(),action_title:K.string().min(1).max(M9).optional(),action_description:K.string().max(O9).optional(),md_path:K.string().optional().describe("Path to detailed markdown documentation")}),_3=zO.transform(($)=>{let J=[],Q=$.milestone_type,X=$.milestone_title,Y=$.milestone_description;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");if(!X&&$.action_title)X=$.action_title,J.push("action_title");if(Y===void 0&&$.action_description!==void 0)Y=$.action_description,J.push("action_description");return{task_id:$.task_id,milestone_type:Q,milestone_title:X,milestone_description:Y,process_description:$.process_description,md_path:$.md_path,_deprecated_fields_used:J}}),L3=K.object({operation_id:K.number().describe("Operation ID")}),R3=K.object({task_id:K.number().describe("Task ID"),milestone_type:D9.optional(),action_type:D9.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}}),DO=K.object({operation_id:K.number().describe("Operation ID"),milestone_title:Z3.optional(),milestone_description:P3,process_description:j3.optional(),action_title:K.string().min(1).max(M9).optional(),action_description:K.string().max(O9).optional()}),A3=DO.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}}),N3=K.object({operation_id:K.number().describe("Operation ID")});function OO($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function MO($){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 s2($){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:_3,execute:async(J,Q)=>{let X;try{X=_3.parse(J)}catch(W){if(W instanceof W0)return{success:!1,output:"",error:OO(W),metadata:{execution_time_ms:0}};throw W}let Y=MO(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let G=Q.session_id||"unknown";try{let W=await $.createOperation({taskId:X.task_id,sessionId:G,milestoneType:Y.milestoneType,milestoneTitle:Y.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),q=`Operation created: #${W.id} for task #${W.taskId} [milestone=${W.milestoneType}] ${W.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+=`
|
|
2430
2569
|
|
|
2431
|
-
`+
|
|
2432
|
-
`);return{success:!0,output:
|
|
2570
|
+
`+H.join(`
|
|
2571
|
+
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:W.id,task_id:W.taskId,session_id:W.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function S8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:L3,execute:async(J,Q)=>{let X=L3.parse(J);try{let Y=await $.getOperation(X.operation_id);if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function o2($){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:R3,execute:async(J,Q)=>{let X=R3.parse(J);try{let Y=await $.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),G=JSON.stringify({operations:Y,count:Y.length});if(X._deprecated_fields_used.length>0)G=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
|
|
2433
2572
|
|
|
2434
|
-
`+
|
|
2573
|
+
`+G;return{success:!0,output:G,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function FO($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function C8($){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:A3,execute:async(J,Q)=>{let X;try{X=A3.parse(J)}catch(Y){if(Y instanceof W0)return{success:!1,output:"",error:FO(Y),metadata:{execution_time_ms:0}};throw Y}try{let Y=await $.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let G=`Operation updated: #${Y.id}`;if(X._deprecated_fields_used.length>0)G+=`
|
|
2435
2574
|
|
|
2436
|
-
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:
|
|
2437
|
-
`)}var r0=()=>{},z6={};o_(z6,{runMigration:()=>dU});function dU(_){o(`[Migration 001] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw $}try{w.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw $}o("[Migration 001] Migration completed successfully")}finally{w.close()}}var pU=r(()=>{Ww(),r0()}),V6={};o_(V6,{runMigration:()=>iU});function iU(_){o(`[Migration 002] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw $}o("[Migration 002] Migration completed successfully")}finally{w.close()}}var nU=r(()=>{Ww(),r0()}),O6={};o_(O6,{runMigration:()=>rU});function rU(_){o(`[Migration 003] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw $}o("[Migration 003] Migration completed successfully")}finally{w.close()}}var aU=r(()=>{Ww(),r0()}),A6={};o_(A6,{runMigration:()=>oU});function oU(_){o(`[Migration 004] Starting migration for: ${_}`);let w=w0(_);try{let $=new Set,X=w.query("PRAGMA table_info(task_operation)").all();for(let Y of X)$.add(Y.name);for(let{oldName:Y,newName:J}of M6){let D=$.has(Y),W=$.has(J);if(D&&!W)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(W)o(`[Migration 004] ${J} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${J}`)}o("[Migration 004] Migration completed successfully")}finally{w.close()}}var M6,sU=r(()=>{Ww(),r0(),M6=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),R6={};o_(R6,{runMigration:()=>tU});function tU(_){o(`[Migration 005] Starting migration for: ${_}`);let w=w0(_),$={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(w.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return o("[Migration 005] task table does not exist, skipping"),$;let Y=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if($.blobCountBefore=Y[0]?.cnt??0,$.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),$;w.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),$.ran=!0;let J=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();$.blobCountAfter=J[0]?.cnt??0,o(`[Migration 005] Converted ${$.blobCountBefore-$.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{w.close()}return $}var eU=r(()=>{Ww(),r0()});function _z(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function w0(_){let w=_z();return wz(new w(_))}function wz(_){if(typeof _.run!=="function")_.run=function(w,...$){if($.length>0)return this.prepare(w).run(...$);else return this.exec(w)};return _.query=function(w,...$){if($.length===0){let Y=this.prepare(w);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(w);return{all:(...Y)=>X.all(...$,...Y),get:(...Y)=>X.get(...$,...Y),run:(...Y)=>X.run(...$,...Y)}},_}function $z(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return f6(_,".local","share")}function q2(){return f6($z(),"roy-agent","tasks.db")}var Lw,Fw,Ww=r(()=>{a(),V_(),Lw=n("task:store"),Fw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||q2()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=e("fs"),X=e("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=w0(this.dbPath),this.db.run(`
|
|
2575
|
+
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:G,metadata:{execution_time_ms:0,operation:Y,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function f8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:N3,execute:async(J,Q)=>{let X=N3.parse(J);try{if(!await $.deleteOperation(X.operation_id))return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Operation deleted: #${X.operation_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}import{join as T3}from"path";function s($){w3.warn($)}var w3,t2=r(()=>{a(),w3=n("task:migration")}),b3={};o0(b3,{runMigration:()=>KO});function KO($){s(`[Migration 001] Starting migration for: ${$}`);let J=X2($);try{try{J.run("ALTER TABLE task ADD COLUMN project_path TEXT"),s("[Migration 001] Added project_path column")}catch(Q){if(Q.message?.includes("duplicate column name"))s("[Migration 001] project_path column already exists, skipping");else throw Q}try{J.run("ALTER TABLE task ADD COLUMN context TEXT"),s("[Migration 001] Added context column")}catch(Q){if(Q.message?.includes("duplicate column name"))s("[Migration 001] context column already exists, skipping");else throw Q}s("[Migration 001] Migration completed successfully")}finally{J.close()}}var _O=r(()=>{H$(),t2()}),E3={};o0(E3,{runMigration:()=>LO});function LO($){s(`[Migration 002] Starting migration for: ${$}`);let J=X2($);try{try{J.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),s("[Migration 002] Added type column")}catch(Q){if(Q.message?.includes("duplicate column name"))s("[Migration 002] type column already exists, skipping");else throw Q}s("[Migration 002] Migration completed successfully")}finally{J.close()}}var RO=r(()=>{H$(),t2()}),S3={};o0(S3,{runMigration:()=>AO});function AO($){s(`[Migration 003] Starting migration for: ${$}`);let J=X2($);try{try{J.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),s("[Migration 003] Added process_description column")}catch(Q){if(Q.message?.includes("duplicate column name"))s("[Migration 003] process_description column already exists, skipping");else throw Q}s("[Migration 003] Migration completed successfully")}finally{J.close()}}var NO=r(()=>{H$(),t2()}),C3={};o0(C3,{runMigration:()=>jO});function jO($){s(`[Migration 004] Starting migration for: ${$}`);let J=X2($);try{let Q=new Set,X=J.query("PRAGMA table_info(task_operation)").all();for(let Y of X)Q.add(Y.name);for(let{oldName:Y,newName:G}of f3){let W=Q.has(Y),q=Q.has(G);if(W&&!q)J.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${G}`),s(`[Migration 004] Renamed ${Y} -> ${G}`);else if(q)s(`[Migration 004] ${G} already exists, skipping rename of ${Y}`);else s(`[Migration 004] ${Y} not present, skipping rename to ${G}`)}s("[Migration 004] Migration completed successfully")}finally{J.close()}}var f3,ZO=r(()=>{H$(),t2(),f3=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),I3={};o0(I3,{runMigration:()=>PO});function PO($){s(`[Migration 005] Starting migration for: ${$}`);let J=X2($),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 s("[Migration 005] task table does not exist, skipping"),Q;let Y=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if(Q.blobCountBefore=Y[0]?.cnt??0,Q.blobCountBefore===0)return s("[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,s(`[Migration 005] Converted ${Q.blobCountBefore-Q.blobCountAfter} BLOB description(s) to TEXT`),s("[Migration 005] Migration completed successfully")}finally{J.close()}return Q}var wO=r(()=>{H$(),t2()});function bO(){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 X2($){let J=bO();return EO(new J($))}function EO($){if(typeof $.run!=="function")$.run=function(J,...Q){if(Q.length>0)return this.prepare(J).run(...Q);else return this.exec(J)};return $.query=function(J,...Q){if(Q.length===0){let Y=this.prepare(J);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(J);return{all:(...Y)=>X.all(...Q,...Y),get:(...Y)=>X.get(...Q,...Y),run:(...Y)=>X.run(...Q,...Y)}},$}function SO(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";return T3($,".local","share")}function F9(){return T3(SO(),"roy-agent","tasks.db")}var N$,j$,H$=r(()=>{a(),z0(),N$=n("task:store"),j$=class ${db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(J){this.dbPath=J||F9()}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=X2(this.dbPath),this.db.run(`
|
|
2438
2576
|
CREATE TABLE IF NOT EXISTS task (
|
|
2439
2577
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2440
2578
|
title TEXT NOT NULL,
|
|
@@ -2482,45 +2620,45 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2482
2620
|
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
2483
2621
|
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
2484
2622
|
)
|
|
2485
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)"),this.dbPath!==":memory:"){try{let{runMigration:
|
|
2623
|
+
`),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}=(_O(),u$(b3));J(this.dbPath)}catch(J){N$.warn(`[Migration 001] Failed to run: ${J.message}`)}try{let{runMigration:J}=(RO(),u$(E3));J(this.dbPath)}catch(J){N$.warn(`[Migration 002] Failed to run: ${J.message}`)}try{let{runMigration:J}=(NO(),u$(S3));J(this.dbPath)}catch(J){N$.warn(`[Migration 003] Failed to run: ${J.message}`)}try{let{runMigration:J}=(ZO(),u$(C3));J(this.dbPath)}catch(J){N$.warn(`[Migration 004] Failed to run: ${J.message}`)}try{let{runMigration:J}=(wO(),u$(I3));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(),Y=this.db.prepare(`
|
|
2486
2624
|
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
2487
2625
|
goals_and_expected_deliverables, due_date, tags, status,
|
|
2488
2626
|
current_status, created_at, updated_at, project_path, context)
|
|
2489
2627
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
|
|
2490
|
-
`).run(
|
|
2628
|
+
`).run(J.title,J.description||"",J.priority||"medium",J.type||"normal",J.parent_task_id||null,J.goals_and_expected_deliverables||"",J.due_date||null,J.tags?JSON.stringify(J.tags):null,Q,Q,J.project_path,J.context),G=await this.getTask(Y.lastInsertRowid);if(G)return this.tasksCache.set(G.id,G),G;throw Error("Failed to create task")}async getTask(J){if(await this.initialize(),this.tasksCache.has(J))return this.tasksCache.get(J);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(J);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(J,Y),Y}async updateTask(J,Q){await this.initialize();let X=await this.getTask(J);if(!X)return;let Y=[],G=[];if(Q.title!==void 0)Y.push("title = ?"),G.push(Q.title);if(Q.description!==void 0)Y.push("description = ?"),G.push(Q.description);if(Q.status!==void 0)Y.push("status = ?"),G.push(Q.status);if(Q.priority!==void 0)Y.push("priority = ?"),G.push(Q.priority);if(Q.type!==void 0)Y.push("type = ?"),G.push(Q.type);if(Q.progress!==void 0)Y.push("progress = ?"),G.push(Q.progress);if(Q.current_status!==void 0)Y.push("current_status = ?"),G.push(Q.current_status);if(Q.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),G.push(Q.goals_and_expected_deliverables);if(Q.due_date!==void 0)Y.push("due_date = ?"),G.push(Q.due_date);if(Q.tags!==void 0)Y.push("tags = ?"),G.push(JSON.stringify(Q.tags));if(Q.project_path!==void 0)Y.push("project_path = ?"),G.push(Q.project_path);if(Q.context!==void 0)Y.push("context = ?"),G.push(Q.context);if(Q.parent_task_id!==void 0)Y.push("parent_task_id = ?"),G.push(Q.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),G.push(Date.now()),G.push(J),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...G),this.tasksCache.delete(J),this.getTask(J)}async deleteTask(J){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(J);if(X.changes>0)this.tasksCache.delete(J),this.operationsCache.delete(J);return X.changes>0}async listTasks(J){if(await this.initialize(),J?.depth!==void 0&&J.depth>=0&&J.parent_task_id===void 0)return this.listTasksByDepth(J);let Q=["1=1"],X=[];if(J?.status)Q.push("status = ?"),X.push(J.status);if(J?.priority)Q.push("priority = ?"),X.push(J.priority);if(J?.type)Q.push("type = ?"),X.push(J.type);if(J?.parent_task_id!==void 0)Q.push("parent_task_id = ?"),X.push(J.parent_task_id);if(!J?.include_archived&&J?.status!=="archived")Q.push("status != 'archived'");let Y=Q.join(" AND "),G=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,q=this.db.prepare(G).get(...X)?.total??0,H=`SELECT * FROM task WHERE ${Y}`,B=[...X];if(H+=" ORDER BY updated_at DESC",J?.limit)H+=" LIMIT ?",B.push(J.limit);if(J?.offset)H+=" OFFSET ?",B.push(J.offset);return{tasks:this.db.prepare(H).all(...B).map((F)=>{let O=this.rowToTask(F);return this.tasksCache.set(O.id,O),O}),total:q}}async listTasksByDepth(J){let Q=J.depth??0,X=["1=1"],Y=[];if(J.status)X.push("status = ?"),Y.push(J.status);if(J.priority)X.push("priority = ?"),Y.push(J.priority);if(J.type)X.push("type = ?"),Y.push(J.type);if(!J?.include_archived&&J?.status!=="archived")X.push("status != 'archived'");let G=X.join(" AND "),W=[];if(Q===0){let z=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${G} ORDER BY updated_at DESC`,V=this.db.prepare(z).all(...Y);for(let F of V){let O=this.rowToTask(F);this.tasksCache.set(O.id,O),W.push(O)}}else{let V=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${G} ORDER BY updated_at DESC`).all(...Y).map((F)=>{let O=this.rowToTask(F);return this.tasksCache.set(O.id,O),O});W.push(...V);for(let F=1;F<=Q;F++){if(V.length===0)break;let O=V.map((A)=>A.id),M=`SELECT * FROM task WHERE parent_task_id IN (${O.map(()=>"?").join(",")}) AND ${G} ORDER BY updated_at DESC`,L=this.db.prepare(M).all(...O,...Y).map((A)=>{let Z=this.rowToTask(A);return this.tasksCache.set(Z.id,Z),Z});W.push(...L),V=L}}let q=W.length,H=J.offset??0,B=J.limit??q;return{tasks:W.slice(H,H+B),total:q}}async getTaskTree(J,Q=-1){await this.initialize();let X=[],Y=[J],G=0;while(Y.length>0){if(Q!==-1&&G>=Q)break;let W=Y.map(()=>"?").join(","),q=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${W}) ORDER BY updated_at DESC`).all(...Y),H=[];for(let B of q){let U=this.rowToTask(B);this.tasksCache.set(U.id,U),X.push(U),H.push(U.id)}Y=H,G++}return X}async getChildTasks(J,Q={}){return this.listTasks({...Q,parent_task_id:J})}async createOperation(J){await this.initialize();let Q=J.milestoneType??J.actionType,X=J.milestoneTitle??J.actionTitle,Y=J.milestoneDescription??J.actionDescription;if(!Q||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let G=Date.now(),q=this.db.prepare(`
|
|
2491
2629
|
INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
|
|
2492
2630
|
milestone_description, process_description, timestamp, md_path)
|
|
2493
2631
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
2494
|
-
`).run(
|
|
2632
|
+
`).run(J.taskId,J.sessionId,Q,X,Y||"",J.processDescription||"",G,J.mdPath||null);this.operationsCache.delete(J.taskId);let H=await this.getOperation(q.lastInsertRowid);if(!H)throw Error("Failed to create operation");return H}async getOperation(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(J);if(!X)return;return this.rowToOperation(X)}async updateOperation(J,Q){await this.initialize();let X=await this.getOperation(J);if(!X)return;let Y=Q.milestoneTitle??Q.actionTitle,G=Q.milestoneDescription??Q.actionDescription,W=[],q=[];if(Y!==void 0)W.push("milestone_title = ?"),q.push(Y);if(G!==void 0)W.push("milestone_description = ?"),q.push(G);if(Q.processDescription!==void 0)W.push("process_description = ?"),q.push(Q.processDescription);if(W.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${W.join(", ")} WHERE id = ?`).run(...q,J),this.operationsCache.delete(X.taskId),this.getOperation(J)}async deleteOperation(J){await this.initialize();let Q=await this.getOperation(J);if(!Q)return!1;let Y=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(J);if(Y.changes>0)this.operationsCache.delete(Q.taskId);return Y.changes>0}async listOperations(J){await this.initialize();let Q=J.taskId;if(!this.operationsCache.has(Q)){let H=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(J.taskId);this.operationsCache.set(Q,H.map((B)=>this.rowToOperation(B)))}let X=this.operationsCache.get(Q),Y=J.milestoneType??J.actionType;if(Y)X=X.filter((q)=>q.milestoneType===Y);let G=J.offset||0,W=J.limit||20;return X.slice(G,G+W)}async getTaskIdBySessionId(J){if(await this.initialize(),!J)return;let Q=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(J);return typeof Q?.task_id==="number"?Q.task_id:void 0}rowToTask(J){return{id:J.id,title:String(J.title??""),description:String(J.description??""),status:String(J.status??"todo"),priority:String(J.priority??"medium"),type:String(J.type??"normal"),progress:J.progress,current_status:String(J.current_status??""),goals_and_expected_deliverables:String(J.goals_and_expected_deliverables??""),parent_task_id:J.parent_task_id||void 0,createdAt:new Date(J.created_at).toISOString(),updatedAt:new Date(J.updated_at).toISOString(),due_date:J.due_date?String(J.due_date):void 0,tags:$.parseTagsSafely(J.tags),project_path:String(J.project_path??"unknown"),context:J.context}}static parseTagsSafely(J){if(J===null||J===void 0||J==="")return;let Q=typeof J==="string"?J:String(J);try{let X=JSON.parse(Q);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[Q]}}rowToOperation(J){let Q=J.milestone_type??J.action_type,X=J.milestone_title??J.action_title,Y=J.milestone_description??J.action_description??"";return{id:J.id,taskId:J.task_id,sessionId:J.session_id,milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:J.process_description??"",timestamp:new Date(J.timestamp).toISOString(),mdPath:J.md_path||void 0,actionType:Q,actionTitle:X,actionDescription:Y}}async createTag(J){await this.initialize();let Q=Date.now(),X=await this.getTagByName(J);if(X)return X;return{id:this.db.prepare(`
|
|
2495
2633
|
INSERT INTO task_tag (name, created_at, task_count)
|
|
2496
2634
|
VALUES (?, ?, 0)
|
|
2497
|
-
`).run(
|
|
2635
|
+
`).run(J,Q).lastInsertRowid,name:J,createdAt:new Date(Q).toISOString(),taskCount:0}}async getTag(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(J);if(!X)return;return this.rowToTag(X)}async getTagByName(J){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(J);if(!X)return;return this.rowToTag(X)}async listTags(J){await this.initialize();let Q="SELECT * FROM task_tag",X=[],Y=J?.orderBy||"count";if(Y==="count")Q+=" ORDER BY task_count DESC";else if(Y==="name")Q+=" ORDER BY name ASC";else Q+=" ORDER BY created_at DESC";if(J?.limit)Q+=" LIMIT ?",X.push(J.limit);if(J?.offset)Q+=" OFFSET ?",X.push(J.offset);return this.db.prepare(Q).all(...X).map((q)=>this.rowToTag(q))}async searchTags(J){await this.initialize();let Q=`
|
|
2498
2636
|
SELECT * FROM task_tag
|
|
2499
2637
|
WHERE name LIKE ?
|
|
2500
2638
|
ORDER BY task_count DESC
|
|
2501
2639
|
LIMIT ?
|
|
2502
|
-
`;return this.db.prepare(
|
|
2640
|
+
`;return this.db.prepare(Q).all(`%${J.query}%`,J.limit||20).map((G)=>this.rowToTag(G))}async deleteTag(J){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(J).changes>0}async addTagsToTask(J,Q){await this.initialize();let X=Date.now(),Y=this.db.prepare(`
|
|
2503
2641
|
INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
|
|
2504
2642
|
VALUES (?, ?, ?)
|
|
2505
|
-
`);for(let
|
|
2643
|
+
`);for(let G of Q)Y.run(J,G,X),this.db.run(`
|
|
2506
2644
|
UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
|
|
2507
|
-
`,
|
|
2645
|
+
`,G);await this.syncTaskTagsJson(J)}async removeTagsFromTask(J,Q){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let Y of Q)X.run(J,Y),this.db.run(`
|
|
2508
2646
|
UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
|
|
2509
|
-
`,Y);await this.syncTaskTagsJson(
|
|
2647
|
+
`,Y);await this.syncTaskTagsJson(J)}async getTagsForTask(J){await this.initialize();let Q=`
|
|
2510
2648
|
SELECT t.* FROM task_tag t
|
|
2511
2649
|
INNER JOIN task_tag_relation r ON t.id = r.tag_id
|
|
2512
2650
|
WHERE r.task_id = ?
|
|
2513
2651
|
ORDER BY t.name ASC
|
|
2514
|
-
`;return this.db.prepare(
|
|
2652
|
+
`;return this.db.prepare(Q).all(J).map((G)=>this.rowToTag(G))}async getTaskIdsByTags(J){if(await this.initialize(),J.length===0)return[];let X=`
|
|
2515
2653
|
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
2516
2654
|
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
2517
|
-
WHERE t.name IN (${
|
|
2518
|
-
`;return this.db.prepare(X).all(...
|
|
2655
|
+
WHERE t.name IN (${J.map(()=>"?").join(", ")})
|
|
2656
|
+
`;return this.db.prepare(X).all(...J).map((W)=>W.task_id)}async updateTaskTags(J,Q){await this.initialize();let X=await this.getTagsForTask(J);if(X.length>0)await this.removeTagsFromTask(J,X.map((G)=>G.id));let Y=[];for(let G of Q){let W=await this.getTagByName(G);if(!W)W=await this.createTag(G);Y.push(W.id)}if(Y.length>0)await this.addTagsToTask(J,Y)}async searchTasksByKeywords(J,Q={}){if(await this.initialize(),!J||J.length===0)return{tasks:[],total:0};let{limit:X=20,offset:Y=0,excludeTaskId:G,status:W,priority:q,type:H,depth:B}=Q,U=null;if(B!==void 0&&B>=0)U=await this.collectTaskIdsByDepth(B);let z=new Map,V="SELECT * FROM task WHERE 1=1",F=[];if(G)V+=" AND id != ?",F.push(G);if(W)V+=" AND status = ?",F.push(W);if(q)V+=" AND priority = ?",F.push(q);if(H)V+=" AND type = ?",F.push(H);if(!Q?.include_archived&&Q?.status!=="archived")V+=" AND status != 'archived'";let O=Math.max(X*5,200);V+=" ORDER BY updated_at DESC LIMIT ?",F.push(O);let D=this.db.prepare(V).all(...F);for(let b of D){let P=this.rowToTask(b),f=new Set,j=0;if(typeof P.title==="string"&&P.title){let S=P.title.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))j++,f.add(x)}if(P.tags&&Array.isArray(P.tags))for(let S of J){let x=S.toLowerCase();if(P.tags.some((i)=>i.toLowerCase().includes(x)))j+=2,f.add(S)}if(typeof P.description==="string"&&P.description){let S=P.description.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))j++,f.add(x)}if(typeof P.goals_and_expected_deliverables==="string"&&P.goals_and_expected_deliverables){let S=P.goals_and_expected_deliverables.toLowerCase();for(let x of J)if(S.includes(x.toLowerCase()))j++,f.add(x)}if(f.size===J.length)z.set(P.id,{task:P,matchCount:j})}let M=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let b of M){let f=new Set;for(let i of J){let g=`%${i}%`;if(this.db.prepare(`
|
|
2519
2657
|
SELECT * FROM task_operation
|
|
2520
2658
|
WHERE task_id = ?
|
|
2521
2659
|
AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
|
|
2522
2660
|
LIMIT 10
|
|
2523
|
-
`).all(
|
|
2661
|
+
`).all(b.task_id,g,g,g).length>0)f.add(i)}if(f.size===0)continue;let j=this.db.prepare("SELECT * FROM task WHERE id = ?").get(b.task_id);if(!j)continue;let S=this.rowToTask(j);if(G&&S.id===G)continue;if(W&&S.status!==W)continue;if(q&&S.priority!==q)continue;if(H&&S.type!==H)continue;if(!Q?.include_archived&&S.status==="archived")continue;let x=z.get(S.id);if(x)x.matchCount+=2;else{let i=new Set(f);if(typeof S.title==="string"&&S.title){let g=S.title.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(typeof S.description==="string"&&S.description){let g=S.description.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(typeof S.goals_and_expected_deliverables==="string"&&S.goals_and_expected_deliverables){let g=S.goals_and_expected_deliverables.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(S.tags&&Array.isArray(S.tags)){for(let g of J)if(S.tags.some((c)=>c.toLowerCase().includes(g.toLowerCase())))i.add(g)}if(i.size===J.length)z.set(S.id,{task:S,matchCount:2})}}let _=Array.from(z.values()).sort((b,P)=>P.matchCount-b.matchCount);if(U!==null)_=_.filter((b)=>U.has(b.task.id));let L=_.length;return{tasks:_.slice(Y,Y+X).map((b)=>b.task),total:L}}async collectTaskIdsByDepth(J){let Q=new Set,Y=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((G)=>G.id);for(let G of Y)Q.add(G);if(J===0)return Q;for(let G=1;G<=J;G++){if(Y.length===0)break;let W=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${W})`).all(...Y).map((H)=>H.id);for(let H of Y)Q.add(H)}return Q}async findSimilarTasksByKeywords(J,Q={}){let X={...Q,limit:Q.limit??5};return(await this.searchTasksByKeywords(J,X)).tasks}async findSimilarTasks(J,Q=5){await this.initialize();let X=await this.getTagsForTask(J);if(X.length===0)return[];let Y=X.map((B)=>B.id),W=`
|
|
2524
2662
|
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
2525
2663
|
FROM task t
|
|
2526
2664
|
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
@@ -2530,21 +2668,21 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2530
2668
|
GROUP BY t.id
|
|
2531
2669
|
ORDER BY match_count DESC, t.updated_at DESC
|
|
2532
2670
|
LIMIT ?
|
|
2533
|
-
`;return this.db.prepare(
|
|
2671
|
+
`;return this.db.prepare(W).all(...Y,J,Q).map((B)=>this.rowToTask(B))}async searchTasks(J,Q=20){await this.initialize();let X=`
|
|
2534
2672
|
SELECT * FROM task
|
|
2535
2673
|
WHERE title LIKE ? OR description LIKE ?
|
|
2536
2674
|
ORDER BY updated_at DESC
|
|
2537
2675
|
LIMIT ?
|
|
2538
|
-
`;return this.db.prepare(X).all(`%${
|
|
2676
|
+
`;return this.db.prepare(X).all(`%${J}%`,`%${J}%`,Q).map((W)=>this.rowToTask(W))}async findTasksByContextValue(J,Q=50){if(await this.initialize(),!J)return[];let X=`
|
|
2539
2677
|
SELECT * FROM task
|
|
2540
2678
|
WHERE context LIKE ?
|
|
2541
2679
|
ORDER BY updated_at DESC
|
|
2542
2680
|
LIMIT ?
|
|
2543
|
-
`;return this.db.prepare(X).all(`%${w}%`,$).map((J)=>this.rowToTask(J))}rowToTag(w){return{id:w.id,name:w.name,createdAt:new Date(w.created_at).toISOString(),taskCount:w.task_count}}async syncTaskTagsJson(w){let X=(await this.getTagsForTask(w)).map((J)=>J.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,w),this.tasksCache.delete(w)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"searchTasksByKeywords",null)});function L6(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let Y=$.replace(/-/g,"_").toUpperCase(),J=_.slice(X.length);if(J.startsWith("_"))J=J.slice(1);if(!J)return;let D=J.indexOf("_"),W;if(D===-1)W=J;else{let Q=J.slice(0,D),q=J.slice(D+1);if(Q===Y)W=q;else W=J}if(!W)return;let G=W.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function F6(_,w){return{..._,execute:w}}var Xz=()=>{},K6=r(()=>{Xz(),W$(),_0()});K6();class F${_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new Y2}getStatus(){return this._status}getConfig(){return{name:this.name,version:this.version,enabled:this._enabled,env:this.env}}isEnvInitialized(){return this._status!=="created"}setStatus(_){this._status=_}getEnv(){return this.env}async init(_){if(_?.env)this.env=_.env;this.setStatus("initializing");try{if(_?.name)Object.defineProperty(this,"name",{value:_.name,writable:!1});if(_?.version)Object.defineProperty(this,"version",{value:_.version,writable:!1})}catch{}if(_?.enabled!==void 0)this._enabled=_.enabled;this.hookManager.setComponentInfo(this.name,this.version),await this.onInit(),this.setStatus("running")}async start(){if(this._started)return;this._started=!0,await this.onStart(),this.setStatus("running")}async stop(){this.setStatus("stopping"),this.hookManager.clear(),await this.onStop(),this.setStatus("stopped")}async onInit(){}async onStart(){}async onStop(){}registerHook(_,w){this.hookManager.register(_,w)}addHook(_,w,$,X){this.hookManager.register(_,F6({name:w,priority:X},$))}removeHook(_,w){return this.hookManager.unregister(_,w)}async executeHooks(_,w,$){await this.hookManager.execute(_,w,$)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig(_,w){let $=this.getConfigComponent();if($){let X=$.get(_);if(X!==void 0)return X}return w}}a();var Yz={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Jz={name:"task",sources:[{type:"env",envPrefix:"TASK",priority:20,watch:!1}],keys:[{key:"task.storage.type",sources:["env","file"]},{key:"task.storage.dbPath",sources:["env","file"]}]};_0();var Dz=["completed","failed","cancelled","timeout"];Dw();a();var a0=n("task:tag");class N6{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return a0.debug(`[TagService] Created tag: ${w.name} (id=${w.id})`),w}async getTag(_){return this.store.getTag(_)}async getTagByName(_){return this.store.getTagByName(_)}async listTags(_){return this.store.listTags(_)}async searchTags(_){return this.store.searchTags(_)}async deleteTag(_){let w=await this.store.deleteTag(_);if(w)a0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),a0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),a0.debug(`[TagService] Removed ${w.length} tags from task ${_}`)}async getTagsForTask(_){return this.store.getTagsForTask(_)}async getTaskIdsByTags(_){return this.store.getTaskIdsByTags(_)}async findSimilarTasks(_,w=5){return this.store.findSimilarTasks(_,w)}async searchTasks(_,w=20){return this.store.searchTasks(_,w)}async searchTasksByKeywords(_,w){return(await this.store.searchTasksByKeywords(_,w)).tasks}async findSimilarTasksByKeywords(_,w){return this.store.findSimilarTasksByKeywords(_,w)}async syncTagsToTask(_,w){let $=[];for(let G of w){let Q=await this.store.getTagByName(G);if(!Q)Q=await this.store.createTag(G);$.push(Q.id)}let X=await this.store.getTagsForTask(_),Y=new Set(X.map((G)=>G.id)),J=new Set($),D=$.filter((G)=>!Y.has(G)),W=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(W.length>0)await this.store.removeTagsFromTask(_,W);if(D.length>0)await this.store.addTagsToTask(_,D);await this.store.updateTaskTags(_,w),a0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}V_();var J_=n("task"),Wz="Deliverable: ";function Gz(_){if(!_)return;return`${Wz}${_}`}class Kw extends F${name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent(_,w,$){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.component",trigger_session_id:$}}),J_.info(`[TaskComponent] Event published: ${_}`)}constructor(){super()}async init(_){await super.init(_);let w=_?.options;if(!w?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=w.configComponent,await this.registerConfig(w),this.setStatus("running"),J_.info("[TaskComponent] Initialized")}async registerConfig(_){let w=this.configComponent;if(!w)return;let{configPath:$,envPrefix:X,config:Y}=_,J=X??"TASK";if(w.registerComponent(Jz),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:J,priority:20,watch:!1}),await w.load("task");for(let D of Object.keys(process.env)){let W=L6(D,J,"task");if(!W)continue;let G=process.env[D];if(G!==void 0)await w.set(W,G)}for(let[D,W]of Object.entries(Yz))if(w.get(D)===void 0)await w.set(D,W);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",q2());if(Y){let D=this.flattenConfig(Y);for(let[W,G]of Object.entries(D))await w.set(W,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new N6(this.store)}async initStore(){let _=this.configComponent;if(!_)return;let w=_.get("task.storage.type")??"sqlite",$=_.get("task.storage.dbPath");if(w==="sqlite")this.store=new Fw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Fw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,Y]of Object.entries(_)){let J=`${w}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign($,this.flattenConfig(Y,J));else $[J]=Y}return $}registerConfigWatcher(_){if(typeof _.watch!=="function")return;this.configWatcher=_.watch("task.*",(w)=>{this.onConfigChange(w)})}onConfigChange(_){if(J_.info(`[TaskComponent] Config changed: ${_.key}`,{oldValue:_.oldValue,newValue:_.newValue}),_.key==="task.storage.type"||_.key==="task.storage.dbPath")this.initStore()}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new w_(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(G1(this.backgroundTaskManager),"built-in"),J_.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else J_.warn("[TaskComponent] ToolComponent not found, skipping tool registration")}async stop(){if(this.configWatcher)this.configWatcher(),this.configWatcher=void 0;if(this.toolComponent)try{this.toolComponent.register(G1(null),"built-in"),J_.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch(_){J_.warn(`[TaskComponent] Failed to reset query_background_process tool: ${_.message}`)}if(this.backgroundTaskManager)this.backgroundTaskManager.dispose(),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let _=[x0(this),m0(this),u0(this),p0(this),l0(this),z$(this),V$(this),c0(this),O$(this),d0(this)],w=[i0(this),R$(this),n0(this),f$(this),L$(this)],$=[d5(this),$4(this.backgroundTaskManager)];for(let X of[..._,...w,...$])this.toolComponent.register(X),J_.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook(_,w,$={}){let X={component:{name:this.name,version:this.version},data:w,metadata:$,phase:_.includes("before")?"before":"after",hookPoint:_};await E_.execute(_,w,$)}async createTask(_){let w=_.sessionId;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){if(!await this.store.getTask(_.parent_task_id))throw Error(`Parent task #${_.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let $={options:{..._},sessionId:w,tagService:this.tagService};await this.executeHook($_.BEFORE_CREATE,$);let X=await this.store.createTask($.options);await this.store.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook($_.AFTER_CREATE,Y),this.publishEvent(fw.CREATED,{task:X,sessionId:w},w),J_.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask(_){return this.store.getTask(_)}async getTaskIdBySessionId(_){return this.store.getTaskIdBySessionId(_)}async getTaskWithOperations(_){let w=await this.store.getTask(_);if(!w)return;let $=await this.store.listOperations({taskId:_});return{...w,operations:$,task:w}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook($_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let Y={task:X,changes:w,tagService:this.tagService};if(await this.executeHook($_.AFTER_UPDATE,Y),this.publishEvent(fw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Dz.includes(w.status)){let J=$2(),D={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,D),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook($_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook($_.AFTER_DELETE,X),$)this.publishEvent(fw.DELETED,{taskId:_,sessionId:""},""),J_.info(`[TaskComponent] Task deleted: ${_}`);return $}async listTasks(_){return this.store.listTasks(_)}async searchTasksByKeywords(_,w){return this.store.searchTasksByKeywords(_,w||{})}async getTaskTree(_,w=-1){return this.store.getTaskTree(_,w)}async getChildTasks(_,w){return this.store.getChildTasks(_,w)}async completeTask(_,w,$){let X=await this.store.getTask(_);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${_} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($){let D={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))D=W}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}D.deliverable_storage_path=$,Y.context=JSON.stringify(D)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Gz($)}),this.publishEvent(fw.COMPLETED,{task:J,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return J}async createOperation(_){let w={options:{..._}};await this.executeHook($_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),Y={operation:$};return await this.executeHook($_.OPERATION_AFTER_CREATE,Y,{task:X,operation:$}),this.publishEvent(fw.OPERATION_ADDED,{operation:$,taskId:$.taskId},$.sessionId),J_.info(`[TaskComponent] Operation created: ${$.id} for task ${$.taskId}`),$}async getOperation(_){return this.store.getOperation(_)}async updateOperation(_,w){return this.store.updateOperation(_,w)}async deleteOperation(_){return this.store.deleteOperation(_)}async listOperations(_){return this.store.listOperations(_)}getTagService(){return this.tagService}registerHook(_,w){E_.register(_,w),this.plugins.set(this.makePluginKey(_,w.name),w),J_.debug(`[TaskComponent] Registered hook: ${w.name} at ${_}`)}registerHooks(_){for(let{hookPoint:w,hook:$}of _)this.registerHook(w,$)}unregisterHook(_,w){let $=E_.unregister(_,w);if($)this.plugins.delete(this.makePluginKey(_,w)),J_.info(`[TaskComponent] Unregistered hook: ${w} from ${_}`);return $}listHooks(){return Array.from(this.plugins.values())}makePluginKey(_,w){return`${_}::${w}`}countHooks(_){return E_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],Kw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createOperation",null);var K$=A.enum(["todo","active","completed","paused","cancelled","archived"]),N$=A.enum(["low","medium","high"]),b$=A.enum(["normal","cycle","longterm"]),j$=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Qz=A.object({storage:A.object({type:A.enum(["memory","sqlite"]).default("sqlite"),dbPath:A.string().optional()}).default({})}).default({});Ww();Ww();var qz="Deliverable: ";function Hz(_){if(!_)return;return`${qz}${_}`}var H2=1e6;class E${port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=Bz(_);if(w!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(w);return(await this.scanAllTasks()).find(($)=>$.id===w)??null}return await this.port.getTask(String(_))}toTask(_){let{nativeId:w,...$}=_;return $}toOperation(_){let{nativeId:w,...$}=_;return $}async scanAllTasks(){return(await this.port.listTasks({limit:H2,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let Y=await this.resolve(_.parent_task_id);if(!Y)throw Error(`Parent task #${_.parent_task_id} not found.`);$=Y.id}let X=await this.port.createTask({title:_.title,description:_.description,priority:_.priority,type:_.type,goals_and_expected_deliverables:_.goals_and_expected_deliverables,...$!==void 0?{parent_task_id:$}:{},due_date:_.due_date,tags:_.tags,project_path:_.project_path,context:_.context,sessionId:w});return await this.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask(_){let w=await this.resolve(_);return w?this.toTask(w):null}async getTaskWithOperations(_){let w=await this.getTask(_);if(!w)return null;let $=await this.listOperations({taskId:w.id,limit:H2,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,_),{tasks:X.slice($,$+w),total:X.length}}async updateTask(_,w){let $=await this.resolve(_);if(!$)return null;let X;if(w.parent_task_id!==void 0)if(w.parent_task_id===null)X=null;else{let J=await this.resolve(w.parent_task_id);if(!J)throw Error(`Parent task #${w.parent_task_id} not found.`);X=J.id}let Y=await this.port.updateTask($.nativeId,{title:w.title,description:w.description,status:w.status,priority:w.priority,type:w.type,progress:w.progress,current_status:w.current_status,goals_and_expected_deliverables:w.goals_and_expected_deliverables,due_date:w.due_date,tags:w.tags,project_path:w.project_path,context:w.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask(_){let w=await this.resolve(_);if(!w)return!1;return await this.port.deleteTask(w.nativeId)}async completeTask(_,w,$){let X=await this.resolve(_);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($)Y.context=zz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let D=Hz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:D??"Task completed",...$?{mdPath:$}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??J)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((Q)=>this.toTask(Q)),Y=new Map;for(let Q of X){if(Q.parent_task_id===void 0)continue;let q=Y.get(Q.parent_task_id)??[];q.push(Q),Y.set(Q.parent_task_id,q)}let J=[],D=new Set([$.id]),W=[$.id],G=0;while(W.length>0){if(w!==-1&&G>=w)break;let Q=[];for(let q of W)for(let H of Y.get(q)??[]){if(D.has(H.id))continue;D.add(H.id),J.push(H),Q.push(H.id)}W=Q,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((W)=>W.id!==w.excludeTaskId);let J=_.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),D=J.length===0?Y:Y.filter((W)=>{let G=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return J.every((Q)=>G.includes(Q))});return{tasks:D.slice(X,X+$),total:D.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",Y=_.milestoneDescription??_.actionDescription??"",J=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(J)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let Y=await this.resolve(_.taskId);if(!Y)return[];let D=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?H2:w,offset:X?0:$})).operations.map((W)=>this.toOperation(W));if(X)D=D.filter((W)=>W.milestoneType===X),D=D.slice($,$+w);return D}async getOperation(_){if(typeof this.port.getOperationByNum==="function"){let $=await this.port.getOperationByNum(_);return $?this.toOperation($):null}let w=await this.scanAllTasks();for(let $ of w){let Y=(await this.port.listOperations({taskNativeId:$.nativeId,limit:H2})).operations.find((J)=>J.id===_);if(Y)return this.toOperation(Y)}return null}async updateOperation(_,w){let $=await this.getOperation(_);if(!$)return null;if(typeof this.port.updateOperationByNum!=="function")return $;let X=await this.port.updateOperationByNum(_,{sessionId:w.sessionId??$.sessionId,milestoneType:w.milestoneType??w.actionType??$.milestoneType,milestoneTitle:w.milestoneTitle??w.actionTitle??$.milestoneTitle,milestoneDescription:w.milestoneDescription??w.actionDescription??$.milestoneDescription,processDescription:w.processDescription??$.processDescription,...w.mdPath!==void 0?{mdPath:w.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation(_){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum(_)}applyFilters(_,w){let $=_;if(w.include_archived!==!0&&w.status!=="archived")$=$.filter((Y)=>Y.status!=="archived");if(w.status!==void 0)$=$.filter((Y)=>Y.status===w.status);if(w.priority!==void 0)$=$.filter((Y)=>Y.priority===w.priority);if(w.type!==void 0)$=$.filter((Y)=>Y.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((Y)=>Y.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let Y=Uz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function Bz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function Uz(_,w){if(w<0)return new Set(_.map((D)=>D.id));let $=new Set(_.map((D)=>D.id)),X=new Map;for(let D of _){let W=D.parent_task_id;if(W===void 0||!$.has(W))continue;let G=X.get(W)??[];G.push(D),X.set(W,G)}let Y=new Set,J=_.filter((D)=>D.parent_task_id===void 0||!$.has(D.parent_task_id));for(let D of J)Y.add(D.id);for(let D=1;D<=w;D++){let W=[];for(let G of J)for(let Q of X.get(G.id)??[]){if(Y.has(Q.id))continue;Y.add(Q.id),W.push(Q)}if(W.length===0)break;J=W}return Y}function zz(_,w){let $={};if(typeof _==="string"&&_.trim().length>0)try{let X=JSON.parse(_);if(X&&typeof X==="object"&&!Array.isArray(X))$=X}catch{}return $.deliverable_storage_path=w,JSON.stringify($)}var Vz=1e6;function Oz(_){let w={};if(_.type!==void 0)w.type=_.type;if(_.progress!==void 0)w.progress=_.progress;if(_.current_status!==void 0)w.current_status=_.current_status;if(_.goals_and_expected_deliverables!==void 0)w.goals_and_expected_deliverables=_.goals_and_expected_deliverables;if(_.project_path!==void 0)w.project_path=_.project_path;if(_.context!==void 0)w.context=_.context;if(_.due_date!==void 0)w.due_date=_.due_date;return w}function o0(_,w,$){if(typeof _.num!=="number")throw Error(`store did not expose a numeric handle for task ${_.id}`);let X=_.roy??{};return{id:_.num,nativeId:_.id,title:_.title,description:_.description??"",status:w.toRoyStatus(_.status),priority:w.toRoyPriority(_.priority),type:X.type??"normal",progress:typeof X.progress==="number"?X.progress:_.status==="done"?100:0,current_status:X.current_status??"",goals_and_expected_deliverables:X.goals_and_expected_deliverables??"",...$!==void 0?{parent_task_id:$}:{},createdAt:_.created_at,updatedAt:_.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:w.toRoyTags(_.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function s0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),Y=String(w.milestoneDescription??w.actionDescription??""),J=w.taskId??_.task_id,D=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:D,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:Y}}function b6(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??Vz;async function D(){let Q=await _.listTasks({limit:J});return new Map(Q.tasks.filter((q)=>typeof q.num==="number").map((q)=>[q.id,q.num]))}async function W(Q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(Q);return(await _.listTasks({limit:J})).tasks.find((H)=>H.num===Q)??null}async function G(Q){let H=[...(await D()).entries()].find(([,B])=>B===Q);if(!H)throw Error(`parent task not found: ${Q}`);return H[0]}return{async createTask(Q){let q=Q.parent_task_id!==void 0?await G(Q.parent_task_id):null,H={type:Q.type??"normal",progress:Q.progress??0,current_status:Q.current_status??"",goals_and_expected_deliverables:Q.goals_and_expected_deliverables??"",project_path:Q.project_path,context:Q.context,...Q.due_date?{due_date:Q.due_date}:{}},B=await _.createTask({title:Q.title,description:Q.description,priority:w.toStorePriority(Q.priority),owner:Y,tags:w.toStoreTags(Q.tags),parent_id:q,session_id:Q.sessionId??"unknown",roy:H});return o0(B,w,Q.parent_task_id)},async getTask(Q){let q=await _.getTask(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async getTaskByNum(Q){let q=await W(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async listTasks(Q){let q=await _.listTasks({limit:Q?.limit??20,offset:Q?.offset??0}),H=await D();return{tasks:q.tasks.map((B)=>o0(B,w,B.parent_id?H.get(B.parent_id):void 0)),total:q.total}},async updateTask(Q,q){let H=Oz(q),B=await _.updateTask(Q,{...q.title!==void 0?{title:q.title}:{},...q.description!==void 0?{description:q.description}:{},...q.status!==void 0?{status:w.toStoreStatus(q.status)}:{},...q.priority!==void 0?{priority:w.toStorePriority(q.priority)}:{},...q.tags!==void 0?{tags:w.toStoreTags(q.tags)}:{},...Object.keys(H).length>0?{roy:H}:{}});if(!B)return null;let O;if(q.parent_task_id!==void 0){let U=q.parent_task_id===null?null:await G(q.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(Q,U);O=q.parent_task_id===null?void 0:q.parent_task_id}let z=await _.getTask(Q)??B;if(O===void 0&&z.parent_id)O=(await D()).get(z.parent_id);return o0(z,w,O)},async deleteTask(Q){return await _.deleteTask(Q)},async createOperation(Q){let q=await _.appendOperation({task_id:Q.taskNativeId??String(Q.taskId),type:X,data:{taskId:Q.taskId,sessionId:Q.sessionId,milestoneType:Q.milestoneType,milestoneTitle:Q.milestoneTitle,milestoneDescription:Q.milestoneDescription,processDescription:Q.processDescription,...Q.mdPath?{mdPath:Q.mdPath}:{}}});return s0(q)},async listOperations(Q){let q=await _.listOperations({...Q?.taskNativeId?{task_id:Q.taskNativeId}:{},type:X,limit:Q?.limit??J,offset:Q?.offset??0});return{operations:q.operations.map(s0),total:q.total}},async getOperationByNum(Q){if(typeof _.getOperationByNum!=="function")return null;let q=await _.getOperationByNum(Q);return q?s0(q):null},async updateOperationByNum(Q,q){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(Q);if(!H)return null;let B=s0(H),O=await _.updateOperation(Q,{data:{taskId:B.taskId,sessionId:q.sessionId??B.sessionId,milestoneType:q.milestoneType??B.milestoneType,milestoneTitle:q.milestoneTitle??B.milestoneTitle,milestoneDescription:q.milestoneDescription??B.milestoneDescription,processDescription:q.processDescription??B.processDescription,...q.mdPath??B.mdPath?{mdPath:q.mdPath??B.mdPath}:{}}});return O?s0(O):null},async deleteOperationByNum(Q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(Q)}}}var Az="roy.milestone",Mz={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Rz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function j6(_){return Mz[_]??"pending"}function E6(_){return Rz[_]??"todo"}function S6(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function P6(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function Z6(_){if(!_||_.length===0)return;return _.join(",")}function C6(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var fz={toRoyStatus:(_)=>E6(_),toStoreStatus:(_)=>j6(_),toRoyPriority:(_)=>P6(_),toStorePriority:(_)=>S6(_),toRoyTags:(_)=>C6(_),toStoreTags:(_)=>Z6(_)};function T6(_,w={}){return new E$(b6(_,fz,{operationType:Az,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var FR=K$.options,KR=N$.options,NR=b$.options,bR=j$.options;var k6=Symbol("Let zodToJsonSchema decide on which parser to use");var I6={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},g6=(_)=>typeof _==="string"?{...I6,name:_}:{...I6,..._};var h6=(_)=>{let w=g6(_),$=w.name!==void 0?[...w.basePath,w.definitionPath,w.name]:w.basePath;return{...w,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(w.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...w.basePath,w.definitionPath,X],jsonSchema:void 0}]))}};function S$(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,S$(_,w,X,Y)}var B2=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function s(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?B2(w,_.currentPath):w.join("/")}}function y6(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==K.ZodAny)$.items=k(_.type._def,{...w,currentPath:[...w.currentPath,"items"]});if(_.minLength)d($,"minItems",_.minLength.value,_.minLength.message,w);if(_.maxLength)d($,"maxItems",_.maxLength.value,_.maxLength.message,w);if(_.exactLength)d($,"minItems",_.exactLength.value,_.exactLength.message,w),d($,"maxItems",_.exactLength.value,_.exactLength.message,w);return $}function v6(_,w){let $={type:"integer",format:"int64"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function x6(){return{type:"boolean"}}function U2(_,w){return k(_.type._def,w)}var m6=(_,w)=>{return k(_.innerType._def,w)};function P$(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>P$(_,w,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Lz(_,w)}}var Lz=(_,w)=>{let $={type:"integer",format:"unix-time"};if(w.target==="openApi3")return $;for(let X of _.checks)switch(X.kind){case"min":d($,"minimum",X.value,X.message,w);break;case"max":d($,"maximum",X.value,X.message,w);break}return $};function u6(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function l6(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function c6(_){return{type:"string",enum:Array.from(_.values)}}var Fz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function d6(_,w){let $=[k(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),k(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((J)=>!!J),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((J)=>{if(Fz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let D=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...G}=J;D=G}else X=void 0;Y.push(D)}}),Y.length?{allOf:Y,...X}:void 0}function p6(_,w){let $=typeof _.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(_.value)?"array":"object"};if(w.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[_.value]};return{type:$==="bigint"?"integer":$,const:_.value}}var Z$=void 0,S_={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Z$===void 0)Z$=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z$},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function z2(_,w){let $={type:"string"};if(_.checks)for(let X of _.checks)switch(X.kind){case"min":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w);break;case"max":d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"email":switch(w.emailStrategy){case"format:email":P_($,"email",X.message,w);break;case"format:idn-email":P_($,"idn-email",X.message,w);break;case"pattern:zod":q_($,S_.email,X.message,w);break}break;case"url":P_($,"uri",X.message,w);break;case"uuid":P_($,"uuid",X.message,w);break;case"regex":q_($,X.regex,X.message,w);break;case"cuid":q_($,S_.cuid,X.message,w);break;case"cuid2":q_($,S_.cuid2,X.message,w);break;case"startsWith":q_($,RegExp(`^${C$(X.value,w)}`),X.message,w);break;case"endsWith":q_($,RegExp(`${C$(X.value,w)}$`),X.message,w);break;case"datetime":P_($,"date-time",X.message,w);break;case"date":P_($,"date",X.message,w);break;case"time":P_($,"time",X.message,w);break;case"duration":P_($,"duration",X.message,w);break;case"length":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w),d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"includes":{q_($,RegExp(C$(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")P_($,"ipv4",X.message,w);if(X.version!=="v4")P_($,"ipv6",X.message,w);break}case"base64url":q_($,S_.base64url,X.message,w);break;case"jwt":q_($,S_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")q_($,S_.ipv4Cidr,X.message,w);if(X.version!=="v4")q_($,S_.ipv6Cidr,X.message,w);break}case"emoji":q_($,S_.emoji(),X.message,w);break;case"ulid":{q_($,S_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{P_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{q_($,S_.base64,X.message,w);break}}break}case"nanoid":q_($,S_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return $}function C$(_,w){return w.patternStrategy==="escape"?Nz(_):_}var Kz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nz(_){let w="";for(let $=0;$<_.length;$++){if(!Kz.has(_[$]))w+="\\";w+=_[$]}return w}function P_(_,w,$,X){if(_.format||_.anyOf?.some((Y)=>Y.format)){if(!_.anyOf)_.anyOf=[];if(_.format){if(_.anyOf.push({format:_.format,..._.errorMessage&&X.errorMessages&&{errorMessage:{format:_.errorMessage.format}}}),delete _.format,_.errorMessage){if(delete _.errorMessage.format,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.anyOf.push({format:w,...$&&X.errorMessages&&{errorMessage:{format:$}}})}else d(_,"format",w,$,X)}function q_(_,w,$,X){if(_.pattern||_.allOf?.some((Y)=>Y.pattern)){if(!_.allOf)_.allOf=[];if(_.pattern){if(_.allOf.push({pattern:_.pattern,..._.errorMessage&&X.errorMessages&&{errorMessage:{pattern:_.errorMessage.pattern}}}),delete _.pattern,_.errorMessage){if(delete _.errorMessage.pattern,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.allOf.push({pattern:i6(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",i6(w,X),$,X)}function i6(_,w){if(!w.applyRegexFlags||!_.flags)return _.source;let $={i:_.flags.includes("i"),m:_.flags.includes("m"),s:_.flags.includes("s")},X=$.i?_.source.toLowerCase():_.source,Y="",J=!1,D=!1,W=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(D){if(X[G].match(/[a-z]/)){if(W)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),W=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],W=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
|
|
2544
|
-
]))`;continue}else if(X[
|
|
2545
|
-
]))`;continue}}if(
|
|
2546
|
-
`:`[${X[
|
|
2547
|
-
]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(D&&X[G]==="]")D=!1;else if(!D&&X[G]==="[")D=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${w.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),_.source}return Y}function V2(_,w){if(w.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(w.target==="openApi3"&&_.keyType?._def.typeName===K.ZodEnum)return{type:"object",required:_.keyType._def.values,properties:_.keyType._def.values.reduce((X,Y)=>({...X,[Y]:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",Y]})??s(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]})??w.allowedAdditionalProperties};if(w.target==="openApi3")return $;if(_.keyType?._def.typeName===K.ZodString&&_.keyType._def.checks?.length){let{type:X,...Y}=z2(_.keyType._def,w);return{...$,propertyNames:Y}}else if(_.keyType?._def.typeName===K.ZodEnum)return{...$,propertyNames:{enum:_.keyType._def.values}};else if(_.keyType?._def.typeName===K.ZodBranded&&_.keyType._def.type._def.typeName===K.ZodString&&_.keyType._def.type._def.checks?.length){let{type:X,...Y}=U2(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function n6(_,w){if(w.mapStrategy==="record")return V2(_,w);let $=k(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||s(w),X=k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||s(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function r6(_){let w=_.values,X=Object.keys(_.values).filter((J)=>{return typeof w[w[J]]!=="number"}).map((J)=>w[J]),Y=Array.from(new Set(X.map((J)=>typeof J)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function a6(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function o6(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function t6(_,w){if(w.target==="openApi3")return s6(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in t0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((Y,J)=>{let D=t0[J._def.typeName];return D&&!Y.includes(D)?[...Y,D]:Y},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((Y,J)=>{let D=typeof J._def.value;switch(D){case"string":case"number":case"boolean":return[...Y,D];case"bigint":return[...Y,"integer"];case"object":if(J._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===$.length){let Y=X.filter((J,D,W)=>W.indexOf(J)===D);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,D)=>{return J.includes(D._def.value)?J:[...J,D._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,Y)=>[...X,...Y._def.values.filter((J)=>!X.includes(J))],[])};return s6(_,w)}var s6=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,Y)=>k(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function e6(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:t0[_.innerType._def.typeName],nullable:!0};return{type:[t0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=k(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function _X(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",S$($,"type",X.message,w);break;case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function wX(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let W in J){let G=J[W];if(G===void 0||G._def===void 0)continue;let Q=jz(G);if(Q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();Q=!1}let q=k(G._def,{...w,currentPath:[...w.currentPath,"properties",W],propertyPath:[...w.currentPath,"properties",W]});if(q===void 0)continue;if(X.properties[W]=q,!Q)Y.push(W)}if(Y.length)X.required=Y;let D=bz(_,w);if(D!==void 0)X.additionalProperties=D;return X}function bz(_,w){if(_.catchall._def.typeName!=="ZodNever")return k(_.catchall._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]});switch(_.unknownKeys){case"passthrough":return w.allowedAdditionalProperties;case"strict":return w.rejectedAdditionalProperties;case"strip":return w.removeAdditionalStrategy==="strict"?w.allowedAdditionalProperties:w.rejectedAdditionalProperties}}function jz(_){try{return _.isOptional()}catch{return!0}}var $X=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return k(_.innerType._def,w);let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:s(w)},$]}:s(w)};var XX=(_,w)=>{if(w.pipeStrategy==="input")return k(_.in._def,w);else if(w.pipeStrategy==="output")return k(_.out._def,w);let $=k(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=k(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((Y)=>Y!==void 0)}};function YX(_,w){return k(_.type._def,w)}function JX(_,w){let X={type:"array",uniqueItems:!0,items:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items"]})};if(_.minSize)d(X,"minItems",_.minSize.value,_.minSize.message,w);if(_.maxSize)d(X,"maxItems",_.maxSize.value,_.maxSize.message,w);return X}function DX(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:k(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function WX(_){return{not:s(_)}}function GX(_){return s(_)}var QX=(_,w)=>{return k(_.innerType._def,w)};var qX=(_,w,$)=>{switch(w){case K.ZodString:return z2(_,$);case K.ZodNumber:return _X(_,$);case K.ZodObject:return wX(_,$);case K.ZodBigInt:return v6(_,$);case K.ZodBoolean:return x6();case K.ZodDate:return P$(_,$);case K.ZodUndefined:return WX($);case K.ZodNull:return o6($);case K.ZodArray:return y6(_,$);case K.ZodUnion:case K.ZodDiscriminatedUnion:return t6(_,$);case K.ZodIntersection:return d6(_,$);case K.ZodTuple:return DX(_,$);case K.ZodRecord:return V2(_,$);case K.ZodLiteral:return p6(_,$);case K.ZodEnum:return c6(_);case K.ZodNativeEnum:return r6(_);case K.ZodNullable:return e6(_,$);case K.ZodOptional:return $X(_,$);case K.ZodMap:return n6(_,$);case K.ZodSet:return JX(_,$);case K.ZodLazy:return()=>_.getter()._def;case K.ZodPromise:return YX(_,$);case K.ZodNaN:case K.ZodNever:return a6($);case K.ZodEffects:return l6(_,$);case K.ZodAny:return s($);case K.ZodUnknown:return GX($);case K.ZodDefault:return u6(_,$);case K.ZodBranded:return U2(_,$);case K.ZodReadonly:return QX(_,$);case K.ZodCatch:return m6(_,$);case K.ZodPipeline:return XX(_,$);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return((X)=>{return})(w)}};function k(_,w,$=!1){let X=w.seen.get(_);if(w.override){let W=w.override?.(_,w,X,$);if(W!==k6)return W}if(X&&!$){let W=Ez(X,w);if(W!==void 0)return W}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=qX(_,_.typeName,w),D=typeof J==="function"?k(J(),w):J;if(D)Sz(_,w,D);if(w.postProcess){let W=w.postProcess(D,_,w);return Y.jsonSchema=D,W}return Y.jsonSchema=D,D}var Ez=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:B2(w.currentPath,_.path)};case"none":case"seen":{if(_.path.length<w.currentPath.length&&_.path.every(($,X)=>w.currentPath[X]===$))return console.warn(`Recursive reference detected at ${w.currentPath.join("/")}! Defaulting to any`),s(w);return w.$refStrategy==="seen"?s(w):void 0}}},Sz=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var T$=(_,w)=>{let $=h6(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[Q,q])=>({...G,[Q]:k(q._def,{...$,currentPath:[...$.basePath,$.definitionPath,Q]},!0)??s($)}),{}):void 0,Y=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,J=k(_._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??s($),D=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(D!==void 0)J.title=D;if($.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[$.openAiAnyTypeName])X[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let W=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in W)||("oneOf"in W)||("allOf"in W)||("type"in W)&&Array.isArray(W.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return W};var Pz=[x0,p0,m0,u0,l0,c0,d0,i0,n0];function Zz(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=T$($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function HX(_,w={}){let $=T6(_,w);return Pz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:Zz(Y.parameters),options:{codemode:!1},execute:async(J,D)=>{let W={session_id:D?.sessionID??w.sessionId??"unknown",workdir:D?.directory};try{let G=await Y.execute(J??{},W),Q=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?Q:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:Y.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function BX(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function UX(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let Y=_??{},J=w.agent??X0;if(typeof Y.agent?.transform==="function")try{let W=await Y.agent.transform((G)=>{L2(G)});BX(W,X.disposers),X.agentId=J}catch(W){X.errors.push(`roy agent registration failed: ${I$(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let D=[];try{D=HX(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${I$(W)}`),X}if(typeof Y.tool?.transform==="function")try{let W=await Y.tool.transform((G)=>{for(let Q of D)G.add(Q)});BX(W,X.disposers),X.toolNames=D.map((G)=>G.name)}catch(W){X.errors.push(`roy tool registration failed: ${I$(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function I$(_){return _ instanceof Error?_.message:String(_)}import{join as h$}from"path";import{homedir as vz}from"os";import{mkdirSync as xz}from"fs";import{Database as Cz}from"bun:sqlite";import{createHash as Tz,randomUUID as Iz}from"crypto";var kz=`
|
|
2681
|
+
`;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})],j$.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],j$.prototype,"searchTasksByKeywords",null)});function v3($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let Y=Q.replace(/-/g,"_").toUpperCase(),G=$.slice(X.length);if(G.startsWith("_"))G=G.slice(1);if(!G)return;let W=G.indexOf("_"),q;if(W===-1)q=G;else{let B=G.slice(0,W),U=G.slice(W+1);if(B===Y)q=U;else q=G}if(!q)return;let H=q.replace(/_/g,".");return`${Q}.${H.toLowerCase()}`}function x3($,J){return{...$,execute:J}}var CO=()=>{},h3=r(()=>{CO(),O8(),Q2()});h3();class I8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new H9}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($,x3({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}}a();var fO={"task.storage.type":"sqlite","task.storage.dbPath":void 0},IO={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"]}]};Q2();var TO=["completed","failed","cancelled","timeout"];q$();a();var e2=n("task:tag");class y3{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return e2.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)e2.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),e2.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),e2.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($),Y=new Set(X.map((H)=>H.id)),G=new Set(Q),W=Q.filter((H)=>!Y.has(H)),q=X.filter((H)=>!G.has(H.id)).map((H)=>H.id);if(q.length>0)await this.store.removeTagsFromTask($,q);if(W.length>0)await this.store.addTagsToTask($,W);await this.store.updateTaskTags($,J),e2.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}z0();var G0=n("task"),vO="Deliverable: ";function xO($){if(!$)return;return`${vO}${$}`}class Z$ extends I8{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}}),G0.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"),G0.info("[TaskComponent] Initialized")}async registerConfig($){let J=this.configComponent;if(!J)return;let{configPath:Q,envPrefix:X,config:Y}=$,G=X??"TASK";if(J.registerComponent(IO),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 W of Object.keys(process.env)){let q=v3(W,G,"task");if(!q)continue;let H=process.env[W];if(H!==void 0)await J.set(q,H)}for(let[W,q]of Object.entries(fO))if(J.get(W)===void 0)await J.set(W,q);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",F9());if(Y){let W=this.flattenConfig(Y);for(let[q,H]of Object.entries(W))await J.set(q,H)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new y3(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 j$(Q),G0.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`);else this.store=new j$,G0.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig($,J="task"){let Q={};for(let[X,Y]of Object.entries($)){let G=`${J}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign(Q,this.flattenConfig(Y,G));else Q[G]=Y}return Q}registerConfigWatcher($){if(typeof $.watch!=="function")return;this.configWatcher=$.watch("task.*",(J)=>{this.onConfigChange(J)})}onConfigChange($){if(G0.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(z6(this.backgroundTaskManager),"built-in"),G0.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else G0.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(z6(null),"built-in"),G0.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch($){G0.warn(`[TaskComponent] Failed to reset query_background_process 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 $=[c2(this),p2(this),d2(this),a2(this),i2(this),Z8(this),P8(this),n2(this),w8(this),r2(this)],J=[s2(this),S8(this),o2(this),C8(this),f8(this)],Q=[J3(this),D7(this.backgroundTaskManager)];for(let X of[...$,...J,...Q])this.toolComponent.register(X),G0.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook($,J,Q={}){let X={component:{name:this.name,version:this.version},data:J,metadata:Q,phase:$.includes("before")?"before":"after",hookPoint:$};await S0.execute($,J,Q)}async createTask($){let J=$.sessionId;if($.parent_task_id!==void 0&&$.parent_task_id!==null){if(!await this.store.getTask($.parent_task_id))throw Error(`Parent task #${$.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let Q={options:{...$},sessionId:J,tagService:this.tagService,taskComponent:this};await this.executeHook(Q0.BEFORE_CREATE,Q);let X=await this.store.createTask(Q.options);await this.store.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(Q0.AFTER_CREATE,Y),this.publishEvent(A$.CREATED,{task:X,sessionId:J},J),G0.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(Q0.BEFORE_UPDATE,Q);let X=await this.store.updateTask($,Q.options);if(X){let Y={task:X,changes:J,tagService:this.tagService};if(await this.executeHook(Q0.AFTER_UPDATE,Y),this.publishEvent(A$.UPDATED,{task:X,changes:J,sessionId:""},""),G0.info(`[TaskComponent] Task updated: ${$}`),J.status&&TO.includes(J.status)){let G=W9(),W={task:X,changes:J,terminalStatus:J.status,sessionId:G.sessionId??"",tagService:this.tagService};await this.executeHook(Q0.AFTER_COMPLETE,W),G0.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${$} -> ${J.status}`)}}return X}async deleteTask($){let J={id:$};await this.executeHook(Q0.BEFORE_DELETE,J);let Q=await this.store.deleteTask($),X={id:$,deleted:Q};if(await this.executeHook(Q0.AFTER_DELETE,X),Q)this.publishEvent(A$.DELETED,{taskId:$,sessionId:""},""),G0.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 Y={status:"completed",progress:100};if(Q){let W={};if(X?.context)try{let q=JSON.parse(X.context);if(q&&typeof q==="object"&&!Array.isArray(q))W=q}catch{G0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}W.deliverable_storage_path=Q,Y.context=JSON.stringify(W)}let G=await this.updateTask($,Y);if(G)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:xO(Q)}),this.publishEvent(A$.COMPLETED,{task:G,sessionId:J},J),G0.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(Q0.OPERATION_BEFORE_CREATE,J);let Q=await this.store.createOperation(J.options),X=await this.store.getTask(Q.taskId),Y={operation:Q};return await this.executeHook(Q0.OPERATION_AFTER_CREATE,Y,{task:X,operation:Q}),this.publishEvent(A$.OPERATION_ADDED,{operation:Q,taskId:Q.taskId},Q.sessionId),G0.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){S0.register($,J),this.plugins.set(this.makePluginKey($,J.name),J),G0.debug(`[TaskComponent] Registered hook: ${J.name} at ${$}`)}registerHooks($){for(let{hookPoint:J,hook:Q}of $)this.registerHook(J,Q)}unregisterHook($,J){let Q=S0.unregister($,J);if(Q)this.plugins.delete(this.makePluginKey($,J)),G0.info(`[TaskComponent] Unregistered hook: ${J} from ${$}`);return Q}listHooks(){return Array.from(this.plugins.values())}makePluginKey($,J){return`${$}::${J}`}countHooks($){return S0.count($)}}m([u("task.component.executeHook",{recordParams:!0})],Z$.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"createOperation",null);var T8=K.enum(["todo","active","completed","paused","cancelled","archived"]),v8=K.enum(["low","medium","high"]),x8=K.enum(["normal","cycle","longterm"]),h8=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),hO=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});H$();H$();var yO="Deliverable: ";function gO($){if(!$)return;return`${yO}${$}`}var K9=1e6;class y8{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=kO($);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:K9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;if($.parent_task_id!==void 0&&$.parent_task_id!==null){let Y=await this.resolve($.parent_task_id);if(!Y)throw Error(`Parent task #${$.parent_task_id} not found.`);Q=Y.id}let X=await this.port.createTask({title:$.title,description:$.description,priority:$.priority,type:$.type,goals_and_expected_deliverables:$.goals_and_expected_deliverables,...Q!==void 0?{parent_task_id:Q}:{},due_date:$.due_date,tags:$.tags,project_path:$.project_path,context:$.context,sessionId:J});return await this.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask($){let J=await this.resolve($);return J?this.toTask(J):null}async getTaskWithOperations($){let J=await this.getTask($);if(!J)return null;let Q=await this.listOperations({taskId:J.id,limit:K9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,$),{tasks:X.slice(Q,Q+J),total:X.length}}async updateTask($,J){let Q=await this.resolve($);if(!Q)return null;let X;if(J.parent_task_id!==void 0)if(J.parent_task_id===null)X=null;else{let G=await this.resolve(J.parent_task_id);if(!G)throw Error(`Parent task #${J.parent_task_id} not found.`);X=G.id}let Y=await this.port.updateTask(Q.nativeId,{title:J.title,description:J.description,status:J.status,priority:J.priority,type:J.type,progress:J.progress,current_status:J.current_status,goals_and_expected_deliverables:J.goals_and_expected_deliverables,due_date:J.due_date,tags:J.tags,project_path:J.project_path,context:J.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask($){let J=await this.resolve($);if(!J)return!1;return await this.port.deleteTask(J.nativeId)}async completeTask($,J,Q){let X=await this.resolve($);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if(Q)Y.context=uO(X.context,Q);let G=await this.port.updateTask(X.nativeId,Y);if(!G)return null;let W=gO(Q);await this.createOperation({taskId:G.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${G.title}`,milestoneDescription:W??"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)),Y=new Map;for(let B of X){if(B.parent_task_id===void 0)continue;let U=Y.get(B.parent_task_id)??[];U.push(B),Y.set(B.parent_task_id,U)}let G=[],W=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 Y.get(U)??[]){if(W.has(z.id))continue;W.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,Y=(await this.scanAllTasks()).map((q)=>this.toTask(q));if(Y=this.applyFilters(Y,J),J.excludeTaskId!==void 0)Y=Y.filter((q)=>q.id!==J.excludeTaskId);let G=$.map((q)=>q.toLowerCase()).filter((q)=>q.length>0),W=G.length===0?Y:Y.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:W.slice(X,X+Q),total:W.length}}async createOperation($){let J=await this.resolve($.taskId);if(!J)throw Error(`Task not found: ${$.taskId}`);let Q=$.milestoneType??$.actionType??"progress",X=$.milestoneTitle??$.actionTitle??"",Y=$.milestoneDescription??$.actionDescription??"",G=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:$.processDescription??"",...$.mdPath?{mdPath:$.mdPath}:{}});return this.toOperation(G)}async listOperations($={}){let J=$.limit??100,Q=$.offset??0,X=$.milestoneType??$.actionType;if($.taskId===void 0)return[];let Y=await this.resolve($.taskId);if(!Y)return[];let W=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?K9:J,offset:X?0:Q})).operations.map((q)=>this.toOperation(q));if(X)W=W.filter((q)=>q.milestoneType===X),W=W.slice(Q,Q+J);return W}async getOperation($){if(typeof this.port.getOperationByNum==="function"){let Q=await this.port.getOperationByNum($);return Q?this.toOperation(Q):null}let J=await this.scanAllTasks();for(let Q of J){let Y=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:K9})).operations.find((G)=>G.id===$);if(Y)return this.toOperation(Y)}return null}async updateOperation($,J){let Q=await this.getOperation($);if(!Q)return null;if(typeof this.port.updateOperationByNum!=="function")return Q;let X=await this.port.updateOperationByNum($,{sessionId:J.sessionId??Q.sessionId,milestoneType:J.milestoneType??J.actionType??Q.milestoneType,milestoneTitle:J.milestoneTitle??J.actionTitle??Q.milestoneTitle,milestoneDescription:J.milestoneDescription??J.actionDescription??Q.milestoneDescription,processDescription:J.processDescription??Q.processDescription,...J.mdPath!==void 0?{mdPath:J.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation($){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum($)}applyFilters($,J){let Q=$;if(J.include_archived!==!0&&J.status!=="archived")Q=Q.filter((Y)=>Y.status!=="archived");if(J.status!==void 0)Q=Q.filter((Y)=>Y.status===J.status);if(J.priority!==void 0)Q=Q.filter((Y)=>Y.priority===J.priority);if(J.type!==void 0)Q=Q.filter((Y)=>Y.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((Y)=>Y.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let Y=mO(Q,J.depth);Q=Q.filter((G)=>Y.has(G.id))}return Q}}function kO($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function mO($,J){if(J<0)return new Set($.map((W)=>W.id));let Q=new Set($.map((W)=>W.id)),X=new Map;for(let W of $){let q=W.parent_task_id;if(q===void 0||!Q.has(q))continue;let H=X.get(q)??[];H.push(W),X.set(q,H)}let Y=new Set,G=$.filter((W)=>W.parent_task_id===void 0||!Q.has(W.parent_task_id));for(let W of G)Y.add(W.id);for(let W=1;W<=J;W++){let q=[];for(let H of G)for(let B of X.get(H.id)??[]){if(Y.has(B.id))continue;Y.add(B.id),q.push(B)}if(q.length===0)break;G=q}return Y}function uO($,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 lO=1e6;function cO($){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 $6($,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 J6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),Y=String(J.milestoneDescription??J.actionDescription??""),G=J.taskId??$.task_id,W=typeof G==="number"?G:typeof G==="string"&&/^\d+$/.test(G)?Number(G):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:W,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:Y,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:Y}}function g3($,J,Q={}){let X=Q.operationType??"roy.milestone",Y=Q.agent??"roy",G=Q.scanLimit??lO;async function W(){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 W()).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:Y,tags:J.toStoreTags(B.tags),parent_id:U,session_id:B.sessionId??"unknown",roy:z});return $6(V,J,B.parent_task_id)},async getTask(B){let U=await $.getTask(B);if(!U)return null;let z=await W();return $6(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 W();return $6(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 W();return{tasks:U.tasks.map((V)=>$6(V,J,V.parent_id?z.get(V.parent_id):void 0)),total:U.total}},async updateTask(B,U){let z=cO(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 F;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);F=U.parent_task_id===null?void 0:U.parent_task_id}let O=await $.getTask(B)??V;if(F===void 0&&O.parent_id)F=(await W()).get(O.parent_id);return $6(O,J,F)},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 J6(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(J6),total:U.total}},async getOperationByNum(B){if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(B);return U?J6(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=J6(z),F=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 F?J6(F):null},async deleteOperationByNum(B){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(B)}}}var pO="roy.milestone",dO={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},iO={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function k3($){return dO[$]??"pending"}function m3($){return iO[$]??"todo"}function u3($){if($==="high")return 1;if($==="low")return 5;return 3}function l3($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function c3($){if(!$||$.length===0)return;return $.join(",")}function p3($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var nO={toRoyStatus:($)=>m3($),toStoreStatus:($)=>k3($),toRoyPriority:($)=>l3($),toStorePriority:($)=>u3($),toRoyTags:($)=>p3($),toStoreTags:($)=>c3($)};function d3($,J={}){return new y8(g3($,nO,{operationType:pO,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var zR=T8.options,DR=v8.options,OR=x8.options,MR=h8.options;var n3=Symbol("Let zodToJsonSchema decide on which parser to use");var i3={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"},r3=($)=>typeof $==="string"?{...i3,name:$}:{...i3,...$};var a3=($)=>{let J=r3($),Q=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function g8($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function p($,J,Q,X,Y){$[J]=Q,g8($,J,X,Y)}var _9=($,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 o($){if($.target!=="openAi")return{};let J=[...$.basePath,$.definitionPath,$.openAiAnyTypeName];return $.flags.hasReferencedOpenAiAnyType=!0,{$ref:$.$refStrategy==="relative"?_9(J,$.currentPath):J.join("/")}}function s3($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==N.ZodAny)Q.items=v($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)p(Q,"minItems",$.minLength.value,$.minLength.message,J);if($.maxLength)p(Q,"maxItems",$.maxLength.value,$.maxLength.message,J);if($.exactLength)p(Q,"minItems",$.exactLength.value,$.exactLength.message,J),p(Q,"maxItems",$.exactLength.value,$.exactLength.message,J);return Q}function o3($,J){let Q={type:"integer",format:"int64"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"min":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"minimum",X.value,X.message,J);else p(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;p(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"maximum",X.value,X.message,J);else p(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;p(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":p(Q,"multipleOf",X.value,X.message,J);break}return Q}function t3(){return{type:"boolean"}}function L9($,J){return v($.type._def,J)}var e3=($,J)=>{return v($.innerType._def,J)};function k8($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,G)=>k8($,J,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return rO($,J)}}var rO=($,J)=>{let Q={type:"integer",format:"unix-time"};if(J.target==="openApi3")return Q;for(let X of $.checks)switch(X.kind){case"min":p(Q,"minimum",X.value,X.message,J);break;case"max":p(Q,"maximum",X.value,X.message,J);break}return Q};function $1($,J){return{...v($.innerType._def,J),default:$.defaultValue()}}function J1($,J){return J.effectStrategy==="input"?v($.schema._def,J):o(J)}function Q1($){return{type:"string",enum:Array.from($.values)}}var aO=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function X1($,J){let Q=[v($.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),v($.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((G)=>!!G),X=J.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return Q.forEach((G)=>{if(aO(G)){if(Y.push(...G.allOf),G.unevaluatedProperties===void 0)X=void 0}else{let W=G;if("additionalProperties"in G&&G.additionalProperties===!1){let{additionalProperties:q,...H}=G;W=H}else X=void 0;Y.push(W)}}),Y.length?{allOf:Y,...X}:void 0}function Y1($,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 m8=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(m8===void 0)m8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return m8},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 R9($,J){let Q={type:"string"};if($.checks)for(let X of $.checks)switch(X.kind){case"min":p(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J);break;case"max":p(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"email":switch(J.emailStrategy){case"format:email":f0(Q,"email",X.message,J);break;case"format:idn-email":f0(Q,"idn-email",X.message,J);break;case"pattern:zod":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(`^${u8(X.value,J)}`),X.message,J);break;case"endsWith":V0(Q,RegExp(`${u8(X.value,J)}$`),X.message,J);break;case"datetime":f0(Q,"date-time",X.message,J);break;case"date":f0(Q,"date",X.message,J);break;case"time":f0(Q,"time",X.message,J);break;case"duration":f0(Q,"duration",X.message,J);break;case"length":p(Q,"minLength",typeof Q.minLength==="number"?Math.max(Q.minLength,X.value):X.value,X.message,J),p(Q,"maxLength",typeof Q.maxLength==="number"?Math.min(Q.maxLength,X.value):X.value,X.message,J);break;case"includes":{V0(Q,RegExp(u8(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":{p(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:((Y)=>{})(X)}return Q}function u8($,J){return J.patternStrategy==="escape"?oO($):$}var sO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function oO($){let J="";for(let Q=0;Q<$.length;Q++){if(!sO.has($[Q]))J+="\\";J+=$[Q]}return J}function f0($,J,Q,X){if($.format||$.anyOf?.some((Y)=>Y.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&X.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:J,...Q&&X.errorMessages&&{errorMessage:{format:Q}}})}else p($,"format",J,Q,X)}function V0($,J,Q,X){if($.pattern||$.allOf?.some((Y)=>Y.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&X.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:G1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else p($,"pattern",G1(J,X),Q,X)}function G1($,J){if(!J.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},X=Q.i?$.source.toLowerCase():$.source,Y="",G=!1,W=!1,q=!1;for(let H=0;H<X.length;H++){if(G){Y+=X[H],G=!1;continue}if(Q.i){if(W){if(X[H].match(/[a-z]/)){if(q)Y+=X[H],Y+=`${X[H-2]}-${X[H]}`.toUpperCase(),q=!1;else if(X[H+1]==="-"&&X[H+2]?.match(/[a-z]/))Y+=X[H],q=!0;else Y+=`${X[H]}${X[H].toUpperCase()}`;continue}}else if(X[H].match(/[a-z]/)){Y+=`[${X[H]}${X[H].toUpperCase()}]`;continue}}if(Q.m){if(X[H]==="^"){Y+=`(^|(?<=[\r
|
|
2682
|
+
]))`;continue}else if(X[H]==="$"){Y+=`($|(?=[\r
|
|
2683
|
+
]))`;continue}}if(Q.s&&X[H]==="."){Y+=W?`${X[H]}\r
|
|
2684
|
+
`:`[${X[H]}\r
|
|
2685
|
+
]`;continue}if(Y+=X[H],X[H]==="\\")G=!0;else if(W&&X[H]==="]")W=!1;else if(!W&&X[H]==="[")W=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return Y}function A9($,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===N.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,Y)=>({...X,[Y]:v($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",Y]})??o(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===N.ZodString&&$.keyType._def.checks?.length){let{type:X,...Y}=R9($.keyType._def,J);return{...Q,propertyNames:Y}}else if($.keyType?._def.typeName===N.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===N.ZodBranded&&$.keyType._def.type._def.typeName===N.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...Y}=L9($.keyType._def,J);return{...Q,propertyNames:Y}}return Q}function W1($,J){if(J.mapStrategy==="record")return A9($,J);let Q=v($.keyType._def,{...J,currentPath:[...J.currentPath,"items","items","0"]})||o(J),X=v($.valueType._def,{...J,currentPath:[...J.currentPath,"items","items","1"]})||o(J);return{type:"array",maxItems:125,items:{type:"array",items:[Q,X],minItems:2,maxItems:2}}}function q1($){let J=$.values,X=Object.keys($.values).filter((G)=>{return typeof J[J[G]]!=="number"}).map((G)=>J[G]),Y=Array.from(new Set(X.map((G)=>typeof G)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function H1($){return $.target==="openAi"?void 0:{not:o({...$,currentPath:[...$.currentPath,"not"]})}}function B1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Q6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function V1($,J){if(J.target==="openApi3")return U1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in Q6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((Y,G)=>{let W=Q6[G._def.typeName];return W&&!Y.includes(W)?[...Y,W]:Y},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((Y,G)=>{let W=typeof G._def.value;switch(W){case"string":case"number":case"boolean":return[...Y,W];case"bigint":return[...Y,"integer"];case"object":if(G._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===Q.length){let Y=X.filter((G,W,q)=>q.indexOf(G)===W);return{type:Y.length>1?Y:Y[0],enum:Q.reduce((G,W)=>{return G.includes(W._def.value)?G:[...G,W._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,Y)=>[...X,...Y._def.values.filter((G)=>!X.includes(G))],[])};return U1($,J)}var U1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,Y)=>v(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function 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:Q6[$.innerType._def.typeName],nullable:!0};return{type:[Q6[$.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 D1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",g8(Q,"type",X.message,J);break;case"min":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"minimum",X.value,X.message,J);else p(Q,"exclusiveMinimum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMinimum=!0;p(Q,"minimum",X.value,X.message,J)}break;case"max":if(J.target==="jsonSchema7")if(X.inclusive)p(Q,"maximum",X.value,X.message,J);else p(Q,"exclusiveMaximum",X.value,X.message,J);else{if(!X.inclusive)Q.exclusiveMaximum=!0;p(Q,"maximum",X.value,X.message,J)}break;case"multipleOf":p(Q,"multipleOf",X.value,X.message,J);break}return Q}function O1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},Y=[],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)Y.push(q)}if(Y.length)X.required=Y;let W=tO($,J);if(W!==void 0)X.additionalProperties=W;return X}function tO($,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 M1=($,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:o(J)},Q]}:o(J)};var F1=($,J)=>{if(J.pipeStrategy==="input")return v($.in._def,J);else if(J.pipeStrategy==="output")return v($.out._def,J);let Q=v($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),X=v($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,X].filter((Y)=>Y!==void 0)}};function K1($,J){return v($.type._def,J)}function _1($,J){let X={type:"array",uniqueItems:!0,items:v($.valueType._def,{...J,currentPath:[...J.currentPath,"items"]})};if($.minSize)p(X,"minItems",$.minSize.value,$.minSize.message,J);if($.maxSize)p(X,"maxItems",$.maxSize.value,$.maxSize.message,J);return X}function L1($,J){if($.rest)return{type:"array",minItems:$.items.length,items:$.items.map((Q,X)=>v(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[]),additionalItems:v($.rest._def,{...J,currentPath:[...J.currentPath,"additionalItems"]})};else return{type:"array",minItems:$.items.length,maxItems:$.items.length,items:$.items.map((Q,X)=>v(Q._def,{...J,currentPath:[...J.currentPath,"items",`${X}`]})).reduce((Q,X)=>X===void 0?Q:[...Q,X],[])}}function R1($){return{not:o($)}}function A1($){return o($)}var N1=($,J)=>{return v($.innerType._def,J)};var j1=($,J,Q)=>{switch(J){case N.ZodString:return R9($,Q);case N.ZodNumber:return D1($,Q);case N.ZodObject:return O1($,Q);case N.ZodBigInt:return o3($,Q);case N.ZodBoolean:return t3();case N.ZodDate:return k8($,Q);case N.ZodUndefined:return R1(Q);case N.ZodNull:return B1(Q);case N.ZodArray:return s3($,Q);case N.ZodUnion:case N.ZodDiscriminatedUnion:return V1($,Q);case N.ZodIntersection:return X1($,Q);case N.ZodTuple:return L1($,Q);case N.ZodRecord:return A9($,Q);case N.ZodLiteral:return Y1($,Q);case N.ZodEnum:return Q1($);case N.ZodNativeEnum:return q1($);case N.ZodNullable:return z1($,Q);case N.ZodOptional:return M1($,Q);case N.ZodMap:return W1($,Q);case N.ZodSet:return _1($,Q);case N.ZodLazy:return()=>$.getter()._def;case N.ZodPromise:return K1($,Q);case N.ZodNaN:case N.ZodNever:return H1(Q);case N.ZodEffects:return J1($,Q);case N.ZodAny:return o(Q);case N.ZodUnknown:return A1(Q);case N.ZodDefault:return $1($,Q);case N.ZodBranded:return L9($,Q);case N.ZodReadonly:return N1($,Q);case N.ZodCatch:return e3($,Q);case N.ZodPipeline:return F1($,Q);case N.ZodFunction:case N.ZodVoid:case N.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!==n3)return q}if(X&&!Q){let q=$M(X,J);if(q!==void 0)return q}let Y={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,Y);let G=j1($,$.typeName,J),W=typeof G==="function"?v(G(),J):G;if(W)JM($,J,W);if(J.postProcess){let q=J.postProcess(W,$,J);return Y.jsonSchema=W,q}return Y.jsonSchema=W,W}var $M=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:_9(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`),o(J);return J.$refStrategy==="seen"?o(J):void 0}}},JM=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var l8=($,J)=>{let Q=a3(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)??o(Q)}),{}):void 0,Y=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,G=v($._def,Y===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,Y]},!1)??o(Q),W=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(W!==void 0)G.title=W;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=Y===void 0?X?{...G,[Q.definitionPath]:X}:G:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,Y].join("/"),[Q.definitionPath]:{...X,[Y]:G}};if(Q.target==="jsonSchema7")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 QM=[c2,a2,p2,d2,i2,n2,r2,s2,o2];function XM($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=l8(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...G}=X;return G}catch{return{}}}function Z1($,J={}){let Q=d3($,J);return QM.map((X)=>{let Y=X(Q);return{name:Y.name,description:Y.description,input:XM(Y.parameters),options:{codemode:!1},execute:async(G,W)=>{let q={session_id:W?.sessionID??J.sessionId??"unknown",workdir:W?.directory};try{let H=await Y.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:Y.name,ok:H.success}}}catch(H){return{content:`ERROR: ${H instanceof Error?H.message:String(H)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function P1($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function w1($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let Y=$??{},G=J.agent??G2;if(typeof Y.agent?.transform==="function")try{let q=await Y.agent.transform((H)=>{E9(H)});P1(q,X.disposers),X.agentId=G}catch(q){X.errors.push(`roy agent registration failed: ${c8(q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let W=[];try{W=Z1(J.store,{agent:G,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(q){return X.errors.push(`roy tool construction failed: ${c8(q)}`),X}if(typeof Y.tool?.transform==="function")try{let q=await Y.tool.transform((H)=>{for(let B of W)H.add(B)});P1(q,X.disposers),X.toolNames=W.map((H)=>H.name)}catch(q){X.errors.push(`roy tool registration failed: ${c8(q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function c8($){return $ instanceof Error?$.message:String($)}import{join as i8}from"path";import{homedir as VM}from"os";import{mkdirSync as zM}from"fs";import{Database as YM}from"bun:sqlite";import{createHash as GM,randomUUID as WM}from"crypto";var qM=`
|
|
2548
2686
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
2549
2687
|
id TEXT PRIMARY KEY,
|
|
2550
2688
|
title TEXT NOT NULL,
|
|
@@ -2599,13 +2737,13 @@ CREATE TABLE IF NOT EXISTS bounties (
|
|
|
2599
2737
|
done_at TEXT
|
|
2600
2738
|
);
|
|
2601
2739
|
CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
|
|
2602
|
-
`;function
|
|
2740
|
+
`;function P$(){return new Date().toISOString()}function p8(){return WM()}function HM($){return GM("sha256").update($).digest("hex")}function b1($){let J=JSON.stringify({id:$.id,type:$.type,data:$.data,prev_hash:$.prev_hash,created_at:$.created_at});return HM(J)}function d8($){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:BM($.roy),created_at:$.created_at,updated_at:$.updated_at}}function BM($){if($===null||$===void 0||$==="")return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}function UM($){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 E1($){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 N9($){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 j9{db;closedFlag=!1;constructor($){this.db=$}static async create($){let J=new YM($);return J.exec(qM),UM(J),new j9(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 W=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(J);if(W){let q=await this.getTask(W.task_id);if(q)return q}}let Q=p8(),X=P$(),Y=$.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
|
|
2603
2741
|
parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
|
|
2604
|
-
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(
|
|
2605
|
-
VALUES (?, ?, ?)`).run(
|
|
2606
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X
|
|
2607
|
-
VALUES (?, ?, ?, ?, 'open', ?)`).run(
|
|
2608
|
-
WHERE id = ? AND status = 'claimed'`).run(
|
|
2742
|
+
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.title,$.description??null,Y,$.owner??null,$.tags??null,$.parent_id??null,JSON.stringify($.blocked_by??[]),$.retry_of??null,$.session_id??null,$.roy===void 0?null:JSON.stringify($.roy),X,X),J)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
|
|
2743
|
+
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?d8(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?d8(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],Y=[];if(J.title!==void 0)X.push("title = ?"),Y.push(J.title);if(J.description!==void 0)X.push("description = ?"),Y.push(J.description);if(J.status!==void 0)X.push("status = ?"),Y.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),Y.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),Y.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),Y.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),Y.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let G={...Q.roy??{},...J.roy};X.push("roy = ?"),Y.push(JSON.stringify(G))}if(X.push("updated_at = ?"),Y.push(P$()),Y.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...Y),J.status!==void 0&&J.status!==Q.status)await this.appendOperation({task_id:$,type:"task.status_changed",data:{from:Q.status,to:J.status}});else await this.appendOperation({task_id:$,type:"task.updated",data:{keys:Object.keys(J)}});return await this.getTask($)}async listTasks($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)if(Array.isArray($.status))J.push(`status IN (${$.status.map(()=>"?").join(",")})`),Q.push(...$.status);else J.push("status = ?"),Q.push($.status);if($.parent_id!==void 0)if($.parent_id===null)J.push("parent_id IS NULL");else J.push("parent_id = ?"),Q.push($.parent_id);if($.session_id!==void 0)J.push("session_id = ?"),Q.push($.session_id);if($.owner!==void 0)J.push("owner = ?"),Q.push($.owner);if($.tags!==void 0)J.push("tags LIKE ?"),Q.push(`%${$.tags}%`);if($.search!==void 0)J.push("(title LIKE ? OR description LIKE ?)"),Q.push(`%${$.search}%`,`%${$.search}%`);let X=$.limit??100,Y=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",W=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${G}`).get(...Q).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${G} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...Q,X,Y).map(d8),total:W}}async deleteTask($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run($).changes>0}async setParentId($,J){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(J,P$(),$)}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=p8(),Y=P$(),G=b1({id:X,type:$.type,data:$.data,prev_hash:Q,created_at:Y});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
|
|
2744
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),Y,Q,G);let W=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:W,task_id:$.task_id,type:$.type,data:$.data,created_at:Y,prev_hash: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?E1(J):null}async updateOperation($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getOperationByNum($);if(!Q)return null;let X=[],Y=[];if(J.type!==void 0)X.push("type = ?"),Y.push(J.type);if(J.data!==void 0)X.push("data = ?"),Y.push(JSON.stringify(J.data));if(X.length===0)return Q;return Y.push($),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...Y),await this.getOperationByNum($)}async deleteOperation($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM operations WHERE rowid = ?").run($).changes>0}async listOperations($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.task_id!==void 0)J.push("task_id = ?"),Q.push($.task_id);if($.type!==void 0)J.push("type = ?"),Q.push($.type);let X=$.limit??100,Y=$.offset??0,G=J.length?`WHERE ${J.join(" AND ")}`:"",W=this.db.query(`SELECT COUNT(*) AS n FROM operations ${G}`).get(...Q).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${G} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...Q,X,Y).map(E1),total:W}}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=b1({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=p8(),Q=P$();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
|
|
2745
|
+
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 N9(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=P$();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 N9(X)}async completeBounty($,J){if(this.closedFlag)throw Error("store closed");let Q=P$();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
|
|
2746
|
+
WHERE id = ? AND status = 'claimed'`).run(J,Q,$).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:$,task_id:J}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return N9(Y)}async listBounties($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.to!==void 0)J.push("to_ = ?"),Q.push($.to);let X=J.length?`WHERE ${J.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...Q).map(N9)}}var DM=i8(VM(),".roy-task-plugin"),OM=i8(DM,"tasks.db");class Y2{inner;constructor($){this.inner=$}static async create($){let J=$??OM;if(J!==":memory:")zM(i8(J,".."),{recursive:!0});let Q=await j9.create(J);return new Y2(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 n8{baseUrl;headers;closedFlag=!1;constructor($){this.baseUrl=$.baseUrl.replace(/\/+$/,""),this.headers={"content-type":"application/json",...$.authToken?{authorization:`Bearer ${$.authToken}`}:{},...$.headers??{}}}async close(){this.closedFlag=!0}async request($,J,Q){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if(Q?.idempotencyKey)X["idempotency-key"]=Q.idempotencyKey;let Y=await fetch(`${this.baseUrl}${J}`,{method:$,headers:X,body:Q?.body!==void 0?JSON.stringify(Q.body):void 0});if(Y.status===204)return null;let G=await Y.text(),W=null;try{W=G?JSON.parse(G):null}catch{W=G}if(!Y.ok)throw new y0(Y.status,`HTTP ${Y.status}`,W);return W}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 X6{inner;constructor($){this.inner=new n8($)}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 sj($={}){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 X6({baseUrl:$.remoteUrl,authToken:$.remoteAuthToken})}else Q=await Y2.create($.localDbPath);let X={store:Q,agent:$.agent??"opencode-default"};return{handlers:q6(X),store:Q,async close(){await Q.close()}}}var MM={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 X6({baseUrl:J.remoteUrl,authToken:J.remoteAuthToken})}else X=await Y2.create(J.localDbPath);let Y={store:X,agent:J.agent??"opencode-default"},G=q6(Y),W=await w1($,{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??""),F=`
|
|
2609
2747
|
|
|
2610
2748
|
# Roy Task Plugin (auto-injected by roy-task-plugin v2)
|
|
2611
2749
|
|
|
@@ -2613,14 +2751,14 @@ When you start a non-trivial task (more than one tool call), create a tracked ta
|
|
|
2613
2751
|
|
|
2614
2752
|
task-create <title> [body]
|
|
2615
2753
|
|
|
2616
|
-
The plugin persists each invocation to ${
|
|
2754
|
+
The plugin persists each invocation to ${Q==="local"?"SQLite at ~/.roy-task-plugin/tasks.db":`remote service at ${J.remoteUrl}`}. Use \`task-list\` and \`task-status\` to retrieve.
|
|
2617
2755
|
|
|
2618
2756
|
Mark progress on long tasks via \`task-update <id> --status <status>\`.
|
|
2619
2757
|
|
|
2620
2758
|
For task-first-class-citizen work (task tree, milestones, deliverables), switch
|
|
2621
2759
|
to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
|
|
2622
2760
|
lifecycle as native tools.
|
|
2623
|
-
`;
|
|
2624
|
-
`)[0]?.trim()||`task-${Date.now()}`;await
|
|
2761
|
+
`;B.update("build",(O)=>{if(typeof O.system==="string"||O.system===void 0)O.system=V+F})}),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(`
|
|
2762
|
+
`)[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 W.disposers)try{await B()}catch{}await q.dispose(),await H.dispose(),await X.close()}}}},tj=MM;export{tj as default,sj as createRoyTaskPlugin,q6 as createHandlers,X6 as RemoteTaskStore,Y2 as LocalTaskStore};
|
|
2625
2763
|
|
|
2626
|
-
//# debugId=
|
|
2764
|
+
//# debugId=D9C9B43706B816DD64756E2164756E21
|