@ai-setting/roy-task-plugin 0.7.7 → 0.7.9
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 +171 -94
- package/dist/cli.js +126 -154
- package/dist/index.js +329 -482
- package/dist/index.js.map +10 -10
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,244 +1,269 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};
|
|
4
|
-
`)?
|
|
2
|
+
var v1=Object.create;var{getPrototypeOf:x1,defineProperty:S9,getOwnPropertyNames:h1}=Object;var y1=Object.prototype.hasOwnProperty;function g1($){return this[$]}var k1,m1,u1=($,J,Q)=>{var X=$!=null&&typeof $==="object";if(X){var W=J?k1??=new WeakMap:m1??=new WeakMap,Y=W.get($);if(Y)return Y}Q=$!=null?v1(x1($)):{};let G=J||!$||!$.__esModule?S9(Q,"default",{value:$,enumerable:!0}):Q;for(let q of h1($))if(!y1.call(G,q))S9(G,q,{get:g1.bind($,q),enumerable:!0});if(X)W.set($,G);return G};var C=($,J)=>()=>(J||$((J={exports:{}}).exports,J),J.exports);var l1=($)=>$;function c1($,J){this[$]=l1.bind(null,J)}var p1=($,J)=>{for(var Q in J)S9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:c1.bind(J,Q)})};var q6=import.meta.require;var d=C((KW)=>{var X4=Symbol.for("yaml.alias"),l7=Symbol.for("yaml.document"),A6=Symbol.for("yaml.map"),c7=Symbol.for("yaml.pair"),W4=Symbol.for("yaml.scalar"),j6=Symbol.for("yaml.seq"),c0=Symbol.for("yaml.node.type"),UW=($)=>!!$&&typeof $==="object"&&$[c0]===X4,VW=($)=>!!$&&typeof $==="object"&&$[c0]===l7,zW=($)=>!!$&&typeof $==="object"&&$[c0]===A6,DW=($)=>!!$&&typeof $==="object"&&$[c0]===c7,p7=($)=>!!$&&typeof $==="object"&&$[c0]===W4,OW=($)=>!!$&&typeof $==="object"&&$[c0]===j6;function d7($){if($&&typeof $==="object")switch($[c0]){case A6:case j6:return!0}return!1}function FW($){if($&&typeof $==="object")switch($[c0]){case X4:case A6:case W4:case j6:return!0}return!1}var MW=($)=>(p7($)||d7($))&&!!$.anchor;KW.ALIAS=X4;KW.DOC=l7;KW.MAP=A6;KW.NODE_TYPE=c0;KW.PAIR=c7;KW.SCALAR=W4;KW.SEQ=j6;KW.hasAnchor=MW;KW.isAlias=UW;KW.isCollection=d7;KW.isDocument=VW;KW.isMap=zW;KW.isNode=FW;KW.isPair=DW;KW.isScalar=p7;KW.isSeq=OW});var R2=C((vW)=>{var W0=d(),D0=Symbol("break visit"),i7=Symbol("skip children"),x0=Symbol("remove node");function N6($,J){let Q=n7(J);if(W0.isDocument($)){if(p$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else p$(null,$,Q,Object.freeze([]))}N6.BREAK=D0;N6.SKIP=i7;N6.REMOVE=x0;function p$($,J,Q,X){let W=r7($,J,Q,X);if(W0.isNode(W)||W0.isPair(W))return a7($,X,W),p$($,W,Q,X);if(typeof W!=="symbol"){if(W0.isCollection(J)){X=Object.freeze(X.concat(J));for(let Y=0;Y<J.items.length;++Y){let G=p$(Y,J.items[Y],Q,X);if(typeof G==="number")Y=G-1;else if(G===D0)return D0;else if(G===x0)J.items.splice(Y,1),Y-=1}}else if(W0.isPair(J)){X=Object.freeze(X.concat(J));let Y=p$("key",J.key,Q,X);if(Y===D0)return D0;else if(Y===x0)J.key=null;let G=p$("value",J.value,Q,X);if(G===D0)return D0;else if(G===x0)J.value=null}}return W}async function Z6($,J){let Q=n7(J);if(W0.isDocument($)){if(await d$(null,$.contents,Q,Object.freeze([$]))===x0)$.contents=null}else await d$(null,$,Q,Object.freeze([]))}Z6.BREAK=D0;Z6.SKIP=i7;Z6.REMOVE=x0;async function d$($,J,Q,X){let W=await r7($,J,Q,X);if(W0.isNode(W)||W0.isPair(W))return a7($,X,W),d$($,W,Q,X);if(typeof W!=="symbol"){if(W0.isCollection(J)){X=Object.freeze(X.concat(J));for(let Y=0;Y<J.items.length;++Y){let G=await d$(Y,J.items[Y],Q,X);if(typeof G==="number")Y=G-1;else if(G===D0)return D0;else if(G===x0)J.items.splice(Y,1),Y-=1}}else if(W0.isPair(J)){X=Object.freeze(X.concat(J));let Y=await d$("key",J.key,Q,X);if(Y===D0)return D0;else if(Y===x0)J.key=null;let G=await d$("value",J.value,Q,X);if(G===D0)return D0;else if(G===x0)J.value=null}}return W}function n7($){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 r7($,J,Q,X){if(typeof Q==="function")return Q($,J,X);if(W0.isMap(J))return Q.Map?.($,J,X);if(W0.isSeq(J))return Q.Seq?.($,J,X);if(W0.isPair(J))return Q.Pair?.($,J,X);if(W0.isScalar(J))return Q.Scalar?.($,J,X);if(W0.isAlias(J))return Q.Alias?.($,J,X);return}function a7($,J,Q){let X=J[J.length-1];if(W0.isCollection(X))X.items[$]=Q;else if(W0.isPair(X))if($==="key")X.key=Q;else X.value=Q;else if(W0.isDocument(X))X.contents=Q;else{let W=W0.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${W} parent`)}}vW.visit=N6;vW.visitAsync=Z6});var Y4=C((mW)=>{var s7=d(),yW=R2(),gW={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},kW=($)=>$.replace(/[!,[\]{}]/g,(J)=>gW[J]);class K0{constructor($,J){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},K0.defaultYaml,$),this.tags=Object.assign({},K0.defaultTags,J)}clone(){let $=new K0(this.yaml,this.tags);return $.docStart=this.docStart,$}atDocument(){let $=new K0(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:K0.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},K0.defaultTags);break}return $}add($,J){if(this.atNextDocument)this.yaml={explicit:K0.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},K0.defaultTags),this.atNextDocument=!1;let Q=$.trim().split(/[ \t]+/),X=Q.shift();switch(X){case"%TAG":{if(Q.length!==2){if(J(0,"%TAG directive should contain exactly two parts"),Q.length<2)return!1}let[W,Y]=Q;return this.tags[W]=Y,!0}case"%YAML":{if(this.yaml.explicit=!0,Q.length!==1)return J(0,"%YAML directive should contain exactly one part"),!1;let[W]=Q;if(W==="1.1"||W==="1.2")return this.yaml.version=W,!0;else{let Y=/^\d+\.\d+$/.test(W);return J(6,`Unsupported YAML version ${W}`,Y),!1}}default:return J(0,`Unknown directive ${X}`,!0),!1}}tagName($,J){if($==="!")return"!";if($[0]!=="!")return J(`Not a valid tag: ${$}`),null;if($[1]==="<"){let Y=$.slice(2,-1);if(Y==="!"||Y==="!!")return J(`Verbatim tags aren't resolved, so ${$} is invalid.`),null;if($[$.length-1]!==">")J("Verbatim tags must end with a >");return Y}let[,Q,X]=$.match(/^(.*!)([^!]*)$/s);if(!X)J(`The ${$} tag has no suffix`);let W=this.tags[Q];if(W)try{return W+decodeURIComponent(X)}catch(Y){return J(String(Y)),null}if(Q==="!")return $;return J(`Could not resolve tag: ${$}`),null}tagString($){for(let[J,Q]of Object.entries(this.tags))if($.startsWith(Q))return J+kW($.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&&s7.isNode($.contents)){let W={};yW.visit($.contents,(Y,G)=>{if(s7.isNode(G)&&G.tag)W[G.tag]=!0}),X=Object.keys(W)}else X=[];for(let[W,Y]of Q){if(W==="!!"&&Y==="tag:yaml.org,2002:")continue;if(!$||X.some((G)=>G.startsWith(Y)))J.push(`%TAG ${W} ${Y}`)}return J.join(`
|
|
3
|
+
`)}}K0.defaultYaml={explicit:!1,version:"1.2"};K0.defaultTags={"!!":"tag:yaml.org,2002:"};mW.Directives=K0});var w6=C((dW)=>{var o7=d(),lW=R2();function cW($){if(/[\x00-\x19\s,[\]{}]/.test($)){let Q=`Anchor must not contain whitespace or control characters: ${JSON.stringify($)}`;throw Error(Q)}return!0}function t7($){let J=new Set;return lW.visit($,{Value(Q,X){if(X.anchor)J.add(X.anchor)}}),J}function e7($,J){for(let Q=1;;++Q){let X=`${$}${Q}`;if(!J.has(X))return X}}function pW($,J){let Q=[],X=new Map,W=null;return{onAnchor:(Y)=>{Q.push(Y),W??(W=t7($));let G=e7(J,W);return W.add(G),G},setAnchors:()=>{for(let Y of Q){let G=X.get(Y);if(typeof G==="object"&&G.anchor&&(o7.isScalar(G.node)||o7.isCollection(G.node)))G.node.anchor=G.anchor;else{let q=Error("Failed to resolve repeated object (this should not happen)");throw q.source=Y,q}}},sourceObjects:X}}dW.anchorIsValid=cW;dW.anchorNames=t7;dW.createNodeAnchors=pW;dW.findNewAnchor=e7});var G4=C((sW)=>{function _2($,J,Q,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let W=0,Y=X.length;W<Y;++W){let G=X[W],q=_2($,X,String(W),G);if(q===void 0)delete X[W];else if(q!==G)X[W]=q}else if(X instanceof Map)for(let W of Array.from(X.keys())){let Y=X.get(W),G=_2($,X,W,Y);if(G===void 0)X.delete(W);else if(G!==Y)X.set(W,G)}else if(X instanceof Set)for(let W of Array.from(X)){let Y=_2($,X,W,W);if(Y===void 0)X.delete(W);else if(Y!==W)X.delete(W),X.add(Y)}else for(let[W,Y]of Object.entries(X)){let G=_2($,X,W,Y);if(G===void 0)delete X[W];else if(G!==Y)X[W]=G}return $.call(J,Q,X)}sW.applyReviver=_2});var t0=C((eW)=>{var tW=d();function $5($,J,Q){if(Array.isArray($))return $.map((X,W)=>$5(X,String(W),Q));if($&&typeof $.toJSON==="function"){if(!Q||!tW.hasAnchor($))return $.toJSON(J,Q);let X={aliasCount:0,count:1,res:void 0};Q.anchors.set($,X),Q.onCreate=(Y)=>{X.res=Y,delete Q.onCreate};let W=$.toJSON(J,Q);if(Q.onCreate)Q.onCreate(W);return W}if(typeof $==="bigint"&&!Q?.keep)return Number($);return $}eW.toJS=$5});var b6=C((XY)=>{var JY=G4(),J5=d(),QY=t0();class Q5{constructor($){Object.defineProperty(this,J5.NODE_TYPE,{value:$})}clone(){let $=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)$.range=this.range.slice();return $}toJS($,{mapAsMap:J,maxAliasCount:Q,onAnchor:X,reviver:W}={}){if(!J5.isDocument($))throw TypeError("A document argument is required");let Y={anchors:new Map,doc:$,keep:!0,mapAsMap:J===!0,mapKeyWarned:!1,maxAliasCount:typeof Q==="number"?Q:100},G=QY.toJS(this,"",Y);if(typeof X==="function")for(let{count:q,res:H}of Y.anchors.values())X(H,q);return typeof W==="function"?JY.applyReviver(W,{"":G},"",G):G}}XY.NodeBase=Q5});var L2=C((BY)=>{var YY=w6(),GY=R2(),i$=d(),qY=b6(),HY=t0();class X5 extends qY.NodeBase{constructor($){super(i$.ALIAS);this.source=$,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve($,J){if(J?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let Q;if(J?.aliasResolveCache)Q=J.aliasResolveCache;else if(Q=[],GY.visit($,{Node:(W,Y)=>{if(i$.isAlias(Y)||i$.hasAnchor(Y))Q.push(Y)}}),J)J.aliasResolveCache=Q;let X=void 0;for(let W of Q){if(W===this)break;if(W.anchor===this.source)X=W}if(X&&J){let{anchors:W,doc:Y,maxAliasCount:G}=J,q=W.get(X);if(!q)HY.toJS(X,null,J),q=W.get(X);if(q?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(G>=0){if(q.count+=1,q.aliasCount===0)q.aliasCount=P6(Y,X,W);if(q.count*q.aliasCount>G)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON($,J){if(!J)return{source:this.source};let Q=this.resolve(J.doc,J);if(!Q){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return J.anchors.get(Q).res}toString($,J,Q){let X=`*${this.source}`;if($){if(YY.anchorIsValid(this.source),$.options.verifyAliasOrder&&!$.anchors.has(this.source)){let W=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(W)}if($.implicitKey)return`${X} `}return X}}function P6($,J,Q){if(i$.isAlias(J)){let X=J.resolve($),W=Q&&X&&Q.get(X);return W?W.count*W.aliasCount:0}else if(i$.isCollection(J)){let X=0;for(let W of J.items){let Y=P6($,W,Q);if(Y>X)X=Y}return X}else if(i$.isPair(J)){let X=P6($,J.key,Q),W=P6($,J.value,Q);return Math.max(X,W)}return 1}BY.Alias=X5});var X0=C((FY)=>{var VY=d(),zY=b6(),DY=t0(),OY=($)=>!$||typeof $!=="function"&&typeof $!=="object";class F$ extends zY.NodeBase{constructor($){super(VY.SCALAR);this.value=$}toJSON($,J){return J?.keep?this.value:DY.toJS(this.value,$,J)}toString(){return String(this.value)}}F$.BLOCK_FOLDED="BLOCK_FOLDED";F$.BLOCK_LITERAL="BLOCK_LITERAL";F$.PLAIN="PLAIN";F$.QUOTE_DOUBLE="QUOTE_DOUBLE";F$.QUOTE_SINGLE="QUOTE_SINGLE";FY.Scalar=F$;FY.isScalarValue=OY});var A2=C((jY)=>{var RY=L2(),M$=d(),W5=X0(),_Y="tag:yaml.org,2002:";function LY($,J,Q){if(J){let X=Q.filter((Y)=>Y.tag===J),W=X.find((Y)=>!Y.format)??X[0];if(!W)throw Error(`Tag ${J} not found`);return W}return Q.find((X)=>X.identify?.($)&&!X.format)}function AY($,J,Q){if(M$.isDocument($))$=$.contents;if(M$.isNode($))return $;if(M$.isPair($)){let z=Q.schema[M$.MAP].createNode?.(Q.schema,null,Q);return z.items.push($),z}if($ instanceof String||$ instanceof Number||$ instanceof Boolean||typeof BigInt<"u"&&$ instanceof BigInt)$=$.valueOf();let{aliasDuplicateObjects:X,onAnchor:W,onTagObj:Y,schema:G,sourceObjects:q}=Q,H=void 0;if(X&&$&&typeof $==="object")if(H=q.get($),H)return H.anchor??(H.anchor=W($)),new RY.Alias(H.anchor);else H={anchor:null,node:null},q.set($,H);if(J?.startsWith("!!"))J=_Y+J.slice(2);let B=LY($,J,G.tags);if(!B){if($&&typeof $.toJSON==="function")$=$.toJSON();if(!$||typeof $!=="object"){let z=new W5.Scalar($);if(H)H.node=z;return z}B=$ instanceof Map?G[M$.MAP]:(Symbol.iterator in Object($))?G[M$.SEQ]:G[M$.MAP]}if(Y)Y(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 W5.Scalar($);if(J)U.tag=J;else if(!B.default)U.tag=B.tag;if(H)H.node=U;return U}jY.createNode=AY});var S6=C((bY)=>{var ZY=A2(),h0=d(),wY=b6();function q4($,J,Q){let X=Q;for(let W=J.length-1;W>=0;--W){let Y=J[W];if(typeof Y==="number"&&Number.isInteger(Y)&&Y>=0){let G=[];G[Y]=X,X=G}else X=new Map([[Y,X]])}return ZY.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:$,sourceObjects:new Map})}var Y5=($)=>$==null||typeof $==="object"&&!!$[Symbol.iterator]().next().done;class G5 extends wY.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(Y5($))this.add(J);else{let[Q,...X]=$,W=this.get(Q,!0);if(h0.isCollection(W))W.addIn(X,J);else if(W===void 0&&this.schema)this.set(Q,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]=$,W=this.get(Q,!0);if(X.length===0)return!J&&h0.isScalar(W)?W.value:W;else return h0.isCollection(W)?W.getIn(X,J):void 0}hasAllNullValues($){return this.items.every((J)=>{if(!h0.isPair(J))return!1;let Q=J.value;return Q==null||$&&h0.isScalar(Q)&&Q.value==null&&!Q.commentBefore&&!Q.comment&&!Q.tag})}hasIn($){let[J,...Q]=$;if(Q.length===0)return this.has(J);let X=this.get(J,!0);return h0.isCollection(X)?X.hasIn(Q):!1}setIn($,J){let[Q,...X]=$;if(X.length===0)this.set(Q,J);else{let W=this.get(Q,!0);if(h0.isCollection(W))W.setIn(X,J);else if(W===void 0&&this.schema)this.set(Q,q4(this.schema,X,J));else throw Error(`Expected YAML collection at ${Q}. Remaining path: ${X}`)}}}bY.Collection=G5;bY.collectionFromPath=q4;bY.isEmptyPath=Y5});var j2=C((TY)=>{var CY=($)=>$.replace(/^(?!$)(?: $)?/gm,"#");function H4($,J){if(/^\n+$/.test($))return $.substring(1);return J?$.replace(/^(?! *$)/gm,J):$}var fY=($,J,Q)=>$.endsWith(`
|
|
4
|
+
`)?H4(Q,J):Q.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
`+
|
|
7
|
-
`){if(Q==="block")D=
|
|
8
|
-
`&&
|
|
9
|
-
`&&Z!=="\t")V=D}if(D>=z)if(V)B.push(V),z=V+H,V=void 0;else if(Q==="quoted"){while(
|
|
10
|
-
${J}${$.slice(0,
|
|
11
|
-
${J}${$.slice(Z+1,
|
|
12
|
-
`);X=J,
|
|
13
|
-
`){if(G
|
|
14
|
-
|
|
15
|
-
`;while(Q[H+2]==="\\"&&Q[H+3]==="n"&&Q[H+4]!=='"')
|
|
16
|
-
`,H+=2;if(
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test($))return N2($,J);let Q=J.indent||(
|
|
18
|
-
${Q}`)+"'";return J.implicitKey?X:e0.foldFlowLines(X,Q,e0.FOLD_FLOW,
|
|
6
|
+
`+H4(Q,J):($.endsWith(" ")?"":" ")+Q;TY.indentComment=H4;TY.lineComment=fY;TY.stringifyComment=CY});var H5=C((yY)=>{function hY($,J,Q="flow",{indentAtStart:X,lineWidth:W=80,minContentWidth:Y=20,onFold:G,onOverflow:q}={}){if(!W||W<0)return $;if(W<Y)Y=0;let H=Math.max(1+Y,1+W-J.length);if($.length<=H)return $;let B=[],U={},z=W-J.length;if(typeof X==="number")if(X>W-Math.max(2,Y))B.push(0);else z=W-X;let V=void 0,M=void 0,O=!1,D=-1,F=-1,R=-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(F=D,$[D+1]){case"x":D+=3;break;case"u":D+=5;break;case"U":D+=9;break;default:D+=1}R=D}if(A===`
|
|
7
|
+
`){if(Q==="block")D=q5($,D,J.length);z=D+J.length+H,V=void 0}else{if(A===" "&&M&&M!==" "&&M!==`
|
|
8
|
+
`&&M!=="\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(M===" "||M==="\t")M=A,A=$[D+=1],O=!0;let Z=D>R+1?D-2:F-1;if(U[Z])return $;B.push(Z),U[Z]=!0,z=Z+H,V=void 0}else O=!0}M=A}if(O&&q)q();if(B.length===0)return $;if(G)G();let _=$.slice(0,B[0]);for(let A=0;A<B.length;++A){let Z=B[A],P=B[A+1]||$.length;if(Z===0)_=`
|
|
10
|
+
${J}${$.slice(0,P)}`;else{if(Q==="quoted"&&U[Z])_+=`${$[Z]}\\`;_+=`
|
|
11
|
+
${J}${$.slice(Z+1,P)}`}}return _}function q5($,J,Q){let X=J,W=J+1,Y=$[W];while(Y===" "||Y==="\t")if(J<W+Q)Y=$[++J];else{do Y=$[++J];while(Y&&Y!==`
|
|
12
|
+
`);X=J,W=J+1,Y=$[W]}return X}yY.FOLD_BLOCK="block";yY.FOLD_FLOW="flow";yY.FOLD_QUOTED="quoted";yY.foldFlowLines=hY});var Z2=C((dY)=>{var P0=X0(),e0=H5(),C6=($,J)=>({indentAtStart:J?$.indent.length:$.indentAtStart,lineWidth:$.options.lineWidth,minContentWidth:$.options.minContentWidth}),f6=($)=>/^(%|---|\.\.\.)/m.test($);function lY($,J,Q){if(!J||J<0)return!1;let X=J-Q,W=$.length;if(W<=X)return!1;for(let Y=0,G=0;Y<W;++Y)if($[Y]===`
|
|
13
|
+
`){if(Y-G>X)return!0;if(G=Y+1,W-G<=X)return!1}return!0}function N2($,J){let Q=JSON.stringify($);if(J.options.doubleQuotedAsJSON)return Q;let{implicitKey:X}=J,W=J.options.doubleQuotedMinMultiLineLength,Y=J.indent||(f6($)?" ":""),G="",q=0;for(let H=0,B=Q[H];B;B=Q[++H]){if(B===" "&&Q[H+1]==="\\"&&Q[H+2]==="n")G+=Q.slice(q,H)+"\\ ",H+=1,q=H,B="\\";if(B==="\\")switch(Q[H+1]){case"u":{G+=Q.slice(q,H);let U=Q.substr(H+2,4);switch(U){case"0000":G+="\\0";break;case"0007":G+="\\a";break;case"000b":G+="\\v";break;case"001b":G+="\\e";break;case"0085":G+="\\N";break;case"00a0":G+="\\_";break;case"2028":G+="\\L";break;case"2029":G+="\\P";break;default:if(U.substr(0,2)==="00")G+="\\x"+U.substr(2);else G+=Q.substr(H,6)}H+=5,q=H+1}break;case"n":if(X||Q[H+2]==='"'||Q.length<W)H+=1;else{G+=Q.slice(q,H)+`
|
|
14
|
+
|
|
15
|
+
`;while(Q[H+2]==="\\"&&Q[H+3]==="n"&&Q[H+4]!=='"')G+=`
|
|
16
|
+
`,H+=2;if(G+=Y,Q[H+2]===" ")G+="\\";H+=1,q=H+1}break;default:H+=1}}return G=q?G+Q.slice(q):Q,X?G:e0.foldFlowLines(G,Y,e0.FOLD_QUOTED,C6(J,!1))}function B4($,J){if(J.options.singleQuote===!1||J.implicitKey&&$.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test($))return N2($,J);let Q=J.indent||(f6($)?" ":""),X="'"+$.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${Q}`)+"'";return J.implicitKey?X:e0.foldFlowLines(X,Q,e0.FOLD_FLOW,C6(J,!1))}function n$($,J){let{singleQuote:Q}=J.options,X;if(Q===!1)X=N2;else{let W=$.includes('"'),Y=$.includes("'");if(W&&!Y)X=B4;else if(Y&&!W)X=N2;else X=Q?B4:N2}return X($,J)}var U4;try{U4=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{U4=/\n+(?!\n|$)/g}function E6({comment:$,type:J,value:Q},X,W,Y){let{blockQuote:G,commentString:q,lineWidth:H}=X.options;if(!G||/\n[\t ]+$/.test(Q))return n$(Q,X);let B=X.indent||(X.forceBlockIndent||f6(Q)?" ":""),U=G==="literal"?!0:G==="folded"||J===P0.Scalar.BLOCK_FOLDED?!1:J===P0.Scalar.BLOCK_LITERAL?!0:!lY(Q,H,B.length);if(!Q)return U?`|
|
|
22
22
|
`:`>
|
|
23
|
-
`;let z,V;for(V=Q.length;V>0;--V){let
|
|
24
|
-
`&&
|
|
25
|
-
`);if(O===-1)z="-";else if(Q===
|
|
26
|
-
`)
|
|
27
|
-
`)
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${B}`),
|
|
29
|
-
${B}${
|
|
30
|
-
${B}${
|
|
31
|
-
`)||U&&/[[\]{},]/.test(
|
|
32
|
-
`)?
|
|
33
|
-
`))return
|
|
34
|
-
${H}`);if(
|
|
35
|
-
${J.indent}${q}`}
|
|
36
|
-
${q}:`}else if(
|
|
37
|
-
`:"",
|
|
38
|
-
${
|
|
39
|
-
`&&A)
|
|
40
|
-
|
|
41
|
-
`}else
|
|
42
|
-
${Q.indent}`}else if(!
|
|
43
|
-
`),
|
|
44
|
-
${Q.indent}`}}else if(
|
|
45
|
-
`)
|
|
23
|
+
`;let z,V;for(V=Q.length;V>0;--V){let P=Q[V-1];if(P!==`
|
|
24
|
+
`&&P!=="\t"&&P!==" ")break}let M=Q.substring(V),O=M.indexOf(`
|
|
25
|
+
`);if(O===-1)z="-";else if(Q===M||O!==M.length-1){if(z="+",Y)Y()}else z="";if(M){if(Q=Q.slice(0,-M.length),M[M.length-1]===`
|
|
26
|
+
`)M=M.slice(0,-1);M=M.replace(U4,`$&${B}`)}let D=!1,F,R=-1;for(F=0;F<Q.length;++F){let P=Q[F];if(P===" ")D=!0;else if(P===`
|
|
27
|
+
`)R=F;else break}let _=Q.substring(0,R<F?R+1:F);if(_)Q=Q.substring(_.length),_=_.replace(/\n+/g,`$&${B}`);let Z=(D?B?"2":"1":"")+z;if($){if(Z+=" "+q($.replace(/ ?[\r\n]+/g," ")),W)W()}if(!U){let P=Q.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${B}`),w=!1,f=C6(X,!0);if(G!=="folded"&&J!==P0.Scalar.BLOCK_FOLDED)f.onOverflow=()=>{w=!0};let N=e0.foldFlowLines(`${_}${P}${M}`,B,e0.FOLD_BLOCK,f);if(!w)return`>${Z}
|
|
29
|
+
${B}${N}`}return Q=Q.replace(/\n+/g,`$&${B}`),`|${Z}
|
|
30
|
+
${B}${_}${Q}${M}`}function cY($,J,Q,X){let{type:W,value:Y}=$,{actualString:G,implicitKey:q,indent:H,indentStep:B,inFlow:U}=J;if(q&&Y.includes(`
|
|
31
|
+
`)||U&&/[[\]{},]/.test(Y))return n$(Y,J);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(Y))return q||U||!Y.includes(`
|
|
32
|
+
`)?n$(Y,J):E6($,J,Q,X);if(!q&&!U&&W!==P0.Scalar.PLAIN&&Y.includes(`
|
|
33
|
+
`))return E6($,J,Q,X);if(f6(Y)){if(H==="")return J.forceBlockIndent=!0,E6($,J,Q,X);else if(q&&H===B)return n$(Y,J)}let z=Y.replace(/\n+/g,`$&
|
|
34
|
+
${H}`);if(G){let V=(D)=>D.default&&D.tag!=="tag:yaml.org,2002:str"&&D.test?.test(z),{compat:M,tags:O}=J.doc.schema;if(O.some(V)||M?.some(V))return n$(Y,J)}return q?z:e0.foldFlowLines(z,H,e0.FOLD_FLOW,C6(J,!1))}function pY($,J,Q,X){let{implicitKey:W,inFlow:Y}=J,G=typeof $.value==="string"?$:Object.assign({},$,{value:String($.value)}),{type:q}=$;if(q!==P0.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(G.value))q=P0.Scalar.QUOTE_DOUBLE}let H=(U)=>{switch(U){case P0.Scalar.BLOCK_FOLDED:case P0.Scalar.BLOCK_LITERAL:return W||Y?n$(G.value,J):E6(G,J,Q,X);case P0.Scalar.QUOTE_DOUBLE:return N2(G.value,J);case P0.Scalar.QUOTE_SINGLE:return B4(G.value,J);case P0.Scalar.PLAIN:return cY(G,J,Q,X);default:return null}},B=H(q);if(B===null){let{defaultKeyType:U,defaultStringType:z}=J.options,V=W&&U||z;if(B=H(V),B===null)throw Error(`Unsupported default string type ${V}`)}return B}dY.stringifyString=pY});var w2=C(($G)=>{var nY=w6(),$$=d(),rY=j2(),aY=Z2();function sY($,J){let Q=Object.assign({blockQuote:!0,commentString:rY.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 oY($,J){if(J.tag){let W=$.filter((Y)=>Y.tag===J.tag);if(W.length>0)return W.find((Y)=>Y.format===J.format)??W[0]}let Q=void 0,X;if($$.isScalar(J)){X=J.value;let W=$.filter((Y)=>Y.identify?.(X));if(W.length>1){let Y=W.filter((G)=>G.test);if(Y.length>0)W=Y}Q=W.find((Y)=>Y.format===J.format)??W.find((Y)=>!Y.format)}else X=J,Q=$.find((W)=>W.nodeClass&&X instanceof W.nodeClass);if(!Q){let W=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${W} value`)}return Q}function tY($,J,{anchors:Q,doc:X}){if(!X.directives)return"";let W=[],Y=($$.isScalar($)||$$.isCollection($))&&$.anchor;if(Y&&nY.anchorIsValid(Y))Q.add(Y),W.push(`&${Y}`);let G=$.tag??(J.default?null:J.tag);if(G)W.push(X.directives.tagString(G));return W.join(" ")}function eY($,J,Q,X){if($$.isPair($))return $.toString(J,Q,X);if($$.isAlias($)){if(J.doc.directives)return $.toString(J);if(J.resolvedAliases?.has($))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(J.resolvedAliases)J.resolvedAliases.add($);else J.resolvedAliases=new Set([$]);$=$.resolve(J.doc)}}let W=void 0,Y=$$.isNode($)?$:J.doc.createNode($,{onTagObj:(H)=>W=H});W??(W=oY(J.doc.schema.tags,Y));let G=tY(Y,W,J);if(G.length>0)J.indentAtStart=(J.indentAtStart??0)+G.length+1;let q=typeof W.stringify==="function"?W.stringify(Y,J,Q,X):$$.isScalar(Y)?aY.stringifyString(Y,J,Q,X):Y.toString(J,Q,X);if(!G)return q;return $$.isScalar(Y)||q[0]==="{"||q[0]==="["?`${G} ${q}`:`${G}
|
|
35
|
+
${J.indent}${q}`}$G.createStringifyContext=sY;$G.stringify=eY});var V5=C((WG)=>{var p0=d(),B5=X0(),U5=w2(),b2=j2();function XG({key:$,value:J},Q,X,W){let{allNullValues:Y,doc:G,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 M=!z&&(!$||V&&J==null&&!Q.inFlow||p0.isCollection($)||(p0.isScalar($)?$.type===B5.Scalar.BLOCK_FOLDED||$.type===B5.Scalar.BLOCK_LITERAL:typeof $==="object"));Q=Object.assign({},Q,{allNullValues:!1,implicitKey:!M&&(z||!Y),indent:q+H});let O=!1,D=!1,F=U5.stringify($,Q,()=>O=!0,()=>D=!0);if(!M&&!Q.inFlow&&F.length>1024){if(z)throw Error("With simple keys, single line scalar must not span more than 1024 characters");M=!0}if(Q.inFlow){if(Y||J==null){if(O&&X)X();return F===""?"?":M?`? ${F}`:F}}else if(Y&&!z||J==null&&M){if(F=`? ${F}`,V&&!O)F+=b2.lineComment(F,Q.indent,B(V));else if(D&&W)W();return F}if(O)V=null;if(M){if(V)F+=b2.lineComment(F,Q.indent,B(V));F=`? ${F}
|
|
36
|
+
${q}:`}else if(F=`${F}:`,V)F+=b2.lineComment(F,Q.indent,B(V));let R,_,A;if(p0.isNode(J))R=!!J.spaceBefore,_=J.commentBefore,A=J.comment;else if(R=!1,_=null,A=null,J&&typeof J==="object")J=G.createNode(J);if(Q.implicitKey=!1,!M&&!V&&p0.isScalar(J))Q.indentAtStart=F.length+1;if(D=!1,!U&&H.length>=2&&!Q.inFlow&&!M&&p0.isSeq(J)&&!J.flow&&!J.tag&&!J.anchor)Q.indent=Q.indent.substring(2);let Z=!1,P=U5.stringify(J,Q,()=>Z=!0,()=>D=!0),w=" ";if(V||R||_){if(w=R?`
|
|
37
|
+
`:"",_){let f=B(_);w+=`
|
|
38
|
+
${b2.indentComment(f,Q.indent)}`}if(P===""&&!Q.inFlow){if(w===`
|
|
39
|
+
`&&A)w=`
|
|
40
|
+
|
|
41
|
+
`}else w+=`
|
|
42
|
+
${Q.indent}`}else if(!M&&p0.isCollection(J)){let f=P[0],N=P.indexOf(`
|
|
43
|
+
`),E=N!==-1,x=Q.inFlow??J.flow??J.items.length===0;if(E||!x){let i=!1;if(E&&(f==="&"||f==="!")){let g=P.indexOf(" ");if(f==="&"&&g!==-1&&g<N&&P[g+1]==="!")g=P.indexOf(" ",g+1);if(g===-1||N<g)i=!0}if(!i)w=`
|
|
44
|
+
${Q.indent}`}}else if(P===""||P[0]===`
|
|
45
|
+
`)w="";if(F+=w+P,Q.inFlow){if(Z&&X)X()}else if(A&&!Z)F+=b2.lineComment(F,Q.indent,B(A));else if(D&&W)W();return F}WG.stringifyPair=XG});var V4=C((HG)=>{var z5=q6("process");function GG($,...J){if($==="debug")console.log(...J)}function qG($,J){if($==="debug"||$==="warn")if(typeof z5.emitWarning==="function")z5.emitWarning(J);else console.warn(J)}HG.debug=GG;HG.warn=qG});var x6=C((zG)=>{var v6=d(),D5=X0(),T6="<<",I6={identify:($)=>$===T6||typeof $==="symbol"&&$.description===T6,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new D5.Scalar(Symbol(T6)),{addToJSMap:O5}),stringify:()=>T6},VG=($,J)=>(I6.identify(J)||v6.isScalar(J)&&(!J.type||J.type===D5.Scalar.PLAIN)&&I6.identify(J.value))&&$?.doc.schema.tags.some((Q)=>Q.tag===I6.tag&&Q.default);function O5($,J,Q){let X=F5($,Q);if(v6.isSeq(X))for(let W of X.items)z4($,J,W);else if(Array.isArray(X))for(let W of X)z4($,J,W);else z4($,J,X)}function z4($,J,Q){let X=F5($,Q);if(!v6.isMap(X))throw Error("Merge sources must be maps or map aliases");let W=X.toJSON(null,$,Map);for(let[Y,G]of W)if(J instanceof Map){if(!J.has(Y))J.set(Y,G)}else if(J instanceof Set)J.add(Y);else if(!Object.prototype.hasOwnProperty.call(J,Y))Object.defineProperty(J,Y,{value:G,writable:!0,enumerable:!0,configurable:!0});return J}function F5($,J){return $&&v6.isAlias(J)?J.resolve($.doc,$):J}zG.addMergeToJSMap=O5;zG.isMergeKey=VG;zG.merge=I6});var O4=C((LG)=>{var MG=V4(),M5=x6(),KG=w2(),K5=d(),D4=t0();function RG($,J,{key:Q,value:X}){if(K5.isNode(Q)&&Q.addToJSMap)Q.addToJSMap($,J,X);else if(M5.isMergeKey($,Q))M5.addMergeToJSMap($,J,X);else{let W=D4.toJS(Q,"",$);if(J instanceof Map)J.set(W,D4.toJS(X,W,$));else if(J instanceof Set)J.add(W);else{let Y=_G(Q,W,$),G=D4.toJS(X,Y,$);if(Y in J)Object.defineProperty(J,Y,{value:G,writable:!0,enumerable:!0,configurable:!0});else J[Y]=G}}return J}function _G($,J,Q){if(J===null)return"";if(typeof J!=="object")return String(J);if(K5.isNode($)&&Q?.doc){let X=KG.createStringifyContext(Q.doc,{});X.anchors=new Set;for(let Y of Q.anchors.keys())X.anchors.add(Y.anchor);X.inFlow=!0,X.inStringifyKey=!0;let W=$.toString(X);if(!Q.mapKeyWarned){let Y=JSON.stringify(W);if(Y.length>40)Y=Y.substring(0,36)+'..."';MG.warn(Q.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${Y}. Set mapAsMap: true to use object keys.`),Q.mapKeyWarned=!0}return W}return JSON.stringify(J)}LG.addPairToJSMap=RG});var J$=C((wG)=>{var R5=A2(),jG=V5(),NG=O4(),h6=d();function ZG($,J,Q){let X=R5.createNode($,void 0,Q),W=R5.createNode(J,void 0,Q);return new y6(X,W)}class y6{constructor($,J=null){Object.defineProperty(this,h6.NODE_TYPE,{value:h6.PAIR}),this.key=$,this.value=J}clone($){let{key:J,value:Q}=this;if(h6.isNode(J))J=J.clone($);if(h6.isNode(Q))Q=Q.clone($);return new y6(J,Q)}toJSON($,J){let Q=J?.mapAsMap?new Map:{};return NG.addPairToJSMap(J,Q,this)}toString($,J,Q){return $?.doc?jG.stringifyPair(this,$,J,Q):JSON.stringify(this)}}wG.Pair=y6;wG.createPair=ZG});var F4=C((fG)=>{var K$=d(),_5=w2(),g6=j2();function SG($,J,Q){return(J.inFlow??$.flow?CG:EG)($,J,Q)}function EG({comment:$,items:J},Q,{blockItemPrefix:X,flowChars:W,itemIndent:Y,onChompKeep:G,onComment:q}){let{indent:H,options:{commentString:B}}=Q,U=Object.assign({},Q,{indent:Y,type:null}),z=!1,V=[];for(let O=0;O<J.length;++O){let D=J[O],F=null;if(K$.isNode(D)){if(!z&&D.spaceBefore)V.push("");if(k6(Q,V,D.commentBefore,z),D.comment)F=D.comment}else if(K$.isPair(D)){let _=K$.isNode(D.key)?D.key:null;if(_){if(!z&&_.spaceBefore)V.push("");k6(Q,V,_.commentBefore,z)}}z=!1;let R=_5.stringify(D,U,()=>F=null,()=>z=!0);if(F)R+=g6.lineComment(R,Y,B(F));if(z&&F)z=!1;V.push(X+R)}let M;if(V.length===0)M=W.start+W.end;else{M=V[0];for(let O=1;O<V.length;++O){let D=V[O];M+=D?`
|
|
46
46
|
${H}${D}`:`
|
|
47
|
-
`}}if($){if(
|
|
48
|
-
`+
|
|
49
|
-
`)),O<$.length-1)
|
|
50
|
-
${
|
|
47
|
+
`}}if($){if(M+=`
|
|
48
|
+
`+g6.indentComment(B($),H),q)q()}else if(z&&G)G();return M}function CG({items:$},J,{flowChars:Q,itemIndent:X}){let{indent:W,indentStep:Y,flowCollectionPadding:G,options:{commentString:q}}=J;X+=Y;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],F=null;if(K$.isNode(D)){if(D.spaceBefore)z.push("");if(k6(J,z,D.commentBefore,!1),D.comment)F=D.comment}else if(K$.isPair(D)){let _=K$.isNode(D.key)?D.key:null;if(_){if(_.spaceBefore)z.push("");if(k6(J,z,_.commentBefore,!1),_.comment)B=!0}let A=K$.isNode(D.value)?D.value:null;if(A){if(A.comment)F=A.comment;if(A.commentBefore)B=!0}else if(D.value==null&&_?.comment)F=_.comment}if(F)B=!0;let R=_5.stringify(D,H,()=>F=null);if(B||(B=z.length>U||R.includes(`
|
|
49
|
+
`)),O<$.length-1)R+=",";else if(J.options.trailingComma){if(J.options.lineWidth>0)B||(B=z.reduce((_,A)=>_+A.length+2,2)+(R.length+2)>J.options.lineWidth);if(B)R+=","}if(F)R+=g6.lineComment(R,X,q(F));z.push(R),U=z.length}let{start:V,end:M}=Q;if(z.length===0)return V+M;else{if(!B){let O=z.reduce((D,F)=>D+F.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
|
+
${Y}${W}${D}`:`
|
|
51
51
|
`;return`${O}
|
|
52
|
-
${
|
|
53
|
-
`:" ")}return
|
|
54
|
-
${
|
|
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&&
|
|
52
|
+
${W}${M}`}else return`${V}${G}${z.join(" ")}${G}${M}`}}function k6({indent:$,options:{commentString:J}},Q,X,W){if(X&&W)X=X.replace(/^\n+/,"");if(X){let Y=g6.indentComment(J(X),$);Q.push(Y.trimStart())}}fG.stringifyCollection=SG});var X$=C((yG)=>{var IG=F4(),vG=O4(),xG=S6(),Q$=d(),m6=J$(),hG=X0();function P2($,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 L5 extends xG.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor($){super(Q$.MAP,$);this.items=[]}static from($,J,Q){let{keepUndefined:X,replacer:W}=Q,Y=new this($),G=(q,H)=>{if(typeof W==="function")H=W.call(J,q,H);else if(Array.isArray(W)&&!W.includes(q))return;if(H!==void 0||X)Y.items.push(m6.createPair(q,H,Q))};if(J instanceof Map)for(let[q,H]of J)G(q,H);else if(J&&typeof J==="object")for(let q of Object.keys(J))G(q,J[q]);if(typeof $.sortMapEntries==="function")Y.items.sort($.sortMapEntries);return Y}add($,J){let Q;if(Q$.isPair($))Q=$;else if(!$||typeof $!=="object"||!("key"in $))Q=new m6.Pair($,$?.value);else Q=new m6.Pair($.key,$.value);let X=P2(this.items,Q.key),W=this.schema?.sortMapEntries;if(X){if(!J)throw Error(`Key ${Q.key} already set`);if(Q$.isScalar(X.value)&&hG.isScalarValue(Q.value))X.value.value=Q.value;else X.value=Q.value}else if(W){let Y=this.items.findIndex((G)=>W(Q,G)<0);if(Y===-1)this.items.push(Q);else this.items.splice(Y,0,Q)}else this.items.push(Q)}delete($){let J=P2(this.items,$);if(!J)return!1;return this.items.splice(this.items.indexOf(J),1).length>0}get($,J){let X=P2(this.items,$)?.value;return(!J&&Q$.isScalar(X)?X.value:X)??void 0}has($){return!!P2(this.items,$)}set($,J){this.add(new m6.Pair($,J),!0)}toJSON($,J,Q){let X=Q?new Q:J?.mapAsMap?new Map:{};if(J?.onCreate)J.onCreate(X);for(let W of this.items)vG.addPairToJSMap(J,X,W);return X}toString($,J,Q){if(!$)return JSON.stringify(this);for(let X of this.items)if(!Q$.isPair(X))throw Error(`Map items must all be pairs; found ${JSON.stringify(X)} instead`);if(!$.allNullValues&&this.hasAllNullValues(!1))$=Object.assign({},$,{allNullValues:!0});return IG.stringifyCollection(this,$,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:$.indent||"",onChompKeep:Q,onComment:J})}}yG.YAMLMap=L5;yG.findPair=P2});var r$=C((lG)=>{var mG=d(),A5=X$(),uG={collection:"map",default:!0,nodeClass:A5.YAMLMap,tag:"tag:yaml.org,2002:map",resolve($,J){if(!mG.isMap($))J("Expected a mapping for this tag");return $},createNode:($,J,Q)=>A5.YAMLMap.from($,J,Q)};lG.map=uG});var W$=C((aG)=>{var pG=A2(),dG=F4(),iG=S6(),l6=d(),nG=X0(),rG=t0();class j5 extends iG.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor($){super(l6.SEQ,$);this.items=[]}add($){this.items.push($)}delete($){let J=u6($);if(typeof J!=="number")return!1;return this.items.splice(J,1).length>0}get($,J){let Q=u6($);if(typeof Q!=="number")return;let X=this.items[Q];return!J&&l6.isScalar(X)?X.value:X}has($){let J=u6($);return typeof J==="number"&&J<this.items.length}set($,J){let Q=u6($);if(typeof Q!=="number")throw Error(`Expected a valid index, not ${$}.`);let X=this.items[Q];if(l6.isScalar(X)&&nG.isScalarValue(J))X.value=J;else this.items[Q]=J}toJSON($,J){let Q=[];if(J?.onCreate)J.onCreate(Q);let X=0;for(let W of this.items)Q.push(rG.toJS(W,String(X++),J));return Q}toString($,J,Q){if(!$)return JSON.stringify(this);return dG.stringifyCollection(this,$,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:($.indent||"")+" ",onChompKeep:Q,onComment:J})}static from($,J,Q){let{replacer:X}=Q,W=new this($);if(J&&Symbol.iterator in Object(J)){let Y=0;for(let G of J){if(typeof X==="function"){let q=J instanceof Set?G:String(Y++);G=X.call(J,q,G)}W.items.push(pG.createNode(G,void 0,Q))}}return W}}function u6($){let J=l6.isScalar($)?$.value:$;if(J&&typeof J==="string")J=Number(J);return typeof J==="number"&&Number.isInteger(J)&&J>=0?J:null}aG.YAMLSeq=j5});var a$=C((eG)=>{var oG=d(),N5=W$(),tG={collection:"seq",default:!0,nodeClass:N5.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve($,J){if(!oG.isSeq($))J("Expected a sequence for this tag");return $},createNode:($,J,Q)=>N5.YAMLSeq.from($,J,Q)};eG.seq=tG});var S2=C((Xq)=>{var Jq=Z2(),Qq={identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify($,J,Q,X){return J=Object.assign({actualString:!0},J),Jq.stringifyString($,J,Q,X)}};Xq.string=Qq});var c6=C((Yq)=>{var Z5=X0(),w5={identify:($)=>$==null,createNode:()=>new Z5.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Z5.Scalar(null),stringify:({source:$},J)=>typeof $==="string"&&w5.test.test($)?$:J.options.nullStr};Yq.nullTag=w5});var M4=C((Hq)=>{var qq=X0(),b5={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($&&b5.test.test($)){let X=$[0]==="t"||$[0]==="T";if(J===X)return $}return J?Q.options.trueStr:Q.options.falseStr}};Hq.boolTag=b5});var s$=C((Vq)=>{function Uq({format:$,minFractionDigits:J,tag:Q,value:X}){if(typeof X==="bigint")return String(X);let W=typeof X==="number"?X:Number(X);if(!isFinite(W))return isNaN(W)?".nan":W<0?"-.inf":".inf";let Y=Object.is(X,-0)?"-0":JSON.stringify(X);if(!$&&J&&(!Q||Q==="tag:yaml.org,2002:float")&&/^-?\d/.test(Y)&&!Y.includes("e")){let G=Y.indexOf(".");if(G<0)G=Y.length,Y+=".";let q=J-(Y.length-G-1);while(q-- >0)Y+="0"}return Y}Vq.stringifyNumber=Uq});var R4=C((Kq)=>{var Dq=X0(),K4=s$(),Oq={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:K4.stringifyNumber},Fq={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():K4.stringifyNumber($)}},Mq={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve($){let J=new Dq.Scalar(parseFloat($)),Q=$.indexOf(".");if(Q!==-1&&$[$.length-1]==="0")J.minFractionDigits=$.length-Q-1;return J},stringify:K4.stringifyNumber};Kq.float=Mq;Kq.floatExp=Fq;Kq.floatNaN=Oq});var L4=C((Zq)=>{var P5=s$(),p6=($)=>typeof $==="bigint"||Number.isInteger($),_4=($,J,Q,{intAsBigInt:X})=>X?BigInt($):parseInt($.substring(J),Q);function S5($,J,Q){let{value:X}=$;if(p6(X)&&X>=0)return Q+X.toString(J);return P5.stringifyNumber($)}var Aq={identify:($)=>p6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:($,J,Q)=>_4($,2,8,Q),stringify:($)=>S5($,8,"0o")},jq={identify:p6,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:($,J,Q)=>_4($,0,10,Q),stringify:P5.stringifyNumber},Nq={identify:($)=>p6($)&&$>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:($,J,Q)=>_4($,2,16,Q),stringify:($)=>S5($,16,"0x")};Zq.int=jq;Zq.intHex=Nq;Zq.intOct=Aq});var E5=C((vq)=>{var Sq=r$(),Eq=c6(),Cq=a$(),fq=S2(),Tq=M4(),A4=R4(),j4=L4(),Iq=[Sq.map,Cq.seq,fq.string,Eq.nullTag,Tq.boolTag,j4.intOct,j4.int,j4.intHex,A4.floatNaN,A4.floatExp,A4.float];vq.schema=Iq});var f5=C((lq)=>{var hq=X0(),yq=r$(),gq=a$();function C5($){return typeof $==="bigint"||Number.isInteger($)}var d6=({value:$})=>JSON.stringify($),kq=[{identify:($)=>typeof $==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:($)=>$,stringify:d6},{identify:($)=>$==null,createNode:()=>new hq.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:d6},{identify:($)=>typeof $==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:($)=>$==="true",stringify:d6},{identify:C5,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:($,J,{intAsBigInt:Q})=>Q?BigInt($):parseInt($,10),stringify:({value:$})=>C5($)?$.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:d6}],mq={default:!0,tag:"",test:/^/,resolve($,J){return J(`Unresolved plain scalar ${JSON.stringify($)}`),$}},uq=[yq.map,gq.seq].concat(kq,mq);lq.schema=uq});var Z4=C((iq)=>{var E2=q6("buffer"),N4=X0(),pq=Z2(),dq={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 W=0;W<Q.length;++W)X[W]=Q.charCodeAt(W);return X}else return J("This environment does not support reading binary tags; either Buffer or atob is required"),$},stringify({comment:$,type:J,value:Q},X,W,Y){if(!Q)return"";let G=Q,q;if(typeof E2.Buffer==="function")q=G instanceof E2.Buffer?G.toString("base64"):E2.Buffer.from(G.buffer).toString("base64");else if(typeof btoa==="function"){let H="";for(let B=0;B<G.length;++B)H+=String.fromCharCode(G[B]);q=btoa(H)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(J??(J=N4.Scalar.BLOCK_LITERAL),J!==N4.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===N4.Scalar.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return pq.stringifyString({comment:$,type:J,value:q},X,W,Y)}};iq.binary=dq});var n6=C((oq)=>{var i6=d(),w4=J$(),rq=X0(),aq=W$();function T5($,J){if(i6.isSeq($))for(let Q=0;Q<$.items.length;++Q){let X=$.items[Q];if(i6.isPair(X))continue;else if(i6.isMap(X)){if(X.items.length>1)J("Each pair must have its own sequence indicator");let W=X.items[0]||new w4.Pair(new rq.Scalar(null));if(X.commentBefore)W.key.commentBefore=W.key.commentBefore?`${X.commentBefore}
|
|
54
|
+
${W.key.commentBefore}`:X.commentBefore;if(X.comment){let Y=W.value??W.key;Y.comment=Y.comment?`${X.comment}
|
|
55
|
+
${Y.comment}`:X.comment}X=W}$.items[Q]=i6.isPair(X)?X:new w4.Pair(X)}else J("Expected a sequence for this tag");return $}function I5($,J,Q){let{replacer:X}=Q,W=new aq.YAMLSeq($);W.tag="tag:yaml.org,2002:pairs";let Y=0;if(J&&Symbol.iterator in Object(J))for(let G of J){if(typeof X==="function")G=X.call(J,String(Y++),G);let q,H;if(Array.isArray(G))if(G.length===2)q=G[0],H=G[1];else throw TypeError(`Expected [key, value] tuple: ${G}`);else if(G&&G instanceof Object){let B=Object.keys(G);if(B.length===1)q=B[0],H=G[q];else throw TypeError(`Expected tuple with one key, not ${B.length} keys`)}else q=G;W.items.push(w4.createPair(q,H,Q))}return W}var sq={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:T5,createNode:I5};oq.createPairs=I5;oq.pairs=sq;oq.resolvePairs=T5});var P4=C((XH)=>{var v5=d(),b4=t0(),C2=X$(),JH=W$(),x5=n6();class R$ extends JH.YAMLSeq{constructor(){super();this.add=C2.YAMLMap.prototype.add.bind(this),this.delete=C2.YAMLMap.prototype.delete.bind(this),this.get=C2.YAMLMap.prototype.get.bind(this),this.has=C2.YAMLMap.prototype.has.bind(this),this.set=C2.YAMLMap.prototype.set.bind(this),this.tag=R$.tag}toJSON($,J){if(!J)return super.toJSON($);let Q=new Map;if(J?.onCreate)J.onCreate(Q);for(let X of this.items){let W,Y;if(v5.isPair(X))W=b4.toJS(X.key,"",J),Y=b4.toJS(X.value,W,J);else W=b4.toJS(X,"",J);if(Q.has(W))throw Error("Ordered maps must not include duplicate keys");Q.set(W,Y)}return Q}static from($,J,Q){let X=x5.createPairs($,J,Q),W=new this;return W.items=X.items,W}}R$.tag="tag:yaml.org,2002:omap";var QH={collection:"seq",identify:($)=>$ instanceof Map,nodeClass:R$,default:!1,tag:"tag:yaml.org,2002:omap",resolve($,J){let Q=x5.resolvePairs($,J),X=[];for(let{key:W}of Q.items)if(v5.isScalar(W))if(X.includes(W.value))J(`Ordered maps must not include duplicate keys: ${W.value}`);else X.push(W.value);return Object.assign(new R$,Q)},createNode:($,J,Q)=>R$.from($,J,Q)};XH.YAMLOMap=R$;XH.omap=QH});var m5=C((GH)=>{var h5=X0();function y5({value:$,source:J},Q){if(J&&($?g5:k5).test.test(J))return J;return $?Q.options.trueStr:Q.options.falseStr}var g5={identify:($)=>$===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new h5.Scalar(!0),stringify:y5},k5={identify:($)=>$===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new h5.Scalar(!1),stringify:y5};GH.falseTag=k5;GH.trueTag=g5});var u5=C((DH)=>{var BH=X0(),S4=s$(),UH={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:S4.stringifyNumber},VH={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():S4.stringifyNumber($)}},zH={identify:($)=>typeof $==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve($){let J=new BH.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:S4.stringifyNumber};DH.float=zH;DH.floatExp=VH;DH.floatNaN=UH});var c5=C((AH)=>{var l5=s$(),f2=($)=>typeof $==="bigint"||Number.isInteger($);function r6($,J,Q,{intAsBigInt:X}){let W=$[0];if(W==="-"||W==="+")J+=1;if($=$.substring(J).replace(/_/g,""),X){switch(Q){case 2:$=`0b${$}`;break;case 8:$=`0o${$}`;break;case 16:$=`0x${$}`;break}let G=BigInt($);return W==="-"?BigInt(-1)*G:G}let Y=parseInt($,Q);return W==="-"?-1*Y:Y}function E4($,J,Q){let{value:X}=$;if(f2(X)){let W=X.toString(J);return X<0?"-"+Q+W.substr(1):Q+W}return l5.stringifyNumber($)}var KH={identify:f2,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:($,J,Q)=>r6($,2,2,Q),stringify:($)=>E4($,2,"0b")},RH={identify:f2,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:($,J,Q)=>r6($,1,8,Q),stringify:($)=>E4($,8,"0")},_H={identify:f2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:($,J,Q)=>r6($,0,10,Q),stringify:l5.stringifyNumber},LH={identify:f2,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:($,J,Q)=>r6($,2,16,Q),stringify:($)=>E4($,16,"0x")};AH.int=_H;AH.intBin=KH;AH.intHex=LH;AH.intOct=RH});var C4=C((PH)=>{var o6=d(),a6=J$(),s6=X$();class _$ extends s6.YAMLMap{constructor($){super($);this.tag=_$.tag}add($){let J;if(o6.isPair($))J=$;else if($&&typeof $==="object"&&"key"in $&&"value"in $&&$.value===null)J=new a6.Pair($.key,null);else J=new a6.Pair($,null);if(!s6.findPair(this.items,J.key))this.items.push(J)}get($,J){let Q=s6.findPair(this.items,$);return!J&&o6.isPair(Q)?o6.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=s6.findPair(this.items,$);if(Q&&!J)this.items.splice(this.items.indexOf(Q),1);else if(!Q&&J)this.items.push(new a6.Pair($))}toJSON($,J){return super.toJSON($,J,Set)}toString($,J,Q){if(!$)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},$,{allNullValues:!0}),J,Q);else throw Error("Set items must all have null values")}static from($,J,Q){let{replacer:X}=Q,W=new this($);if(J&&Symbol.iterator in Object(J))for(let Y of J){if(typeof X==="function")Y=X.call(J,Y,Y);W.items.push(a6.createPair(Y,null,Q))}return W}}_$.tag="tag:yaml.org,2002:set";var bH={collection:"map",identify:($)=>$ instanceof Set,nodeClass:_$,default:!1,tag:"tag:yaml.org,2002:set",createNode:($,J,Q)=>_$.from($,J,Q),resolve($,J){if(o6.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 $}};PH.YAMLSet=_$;PH.set=bH});var T4=C((IH)=>{var CH=s$();function f4($,J){let Q=$[0],X=Q==="-"||Q==="+"?$.substring(1):$,W=(G)=>J?BigInt(G):Number(G),Y=X.replace(/_/g,"").split(":").reduce((G,q)=>G*W(60)+W(q),W(0));return Q==="-"?W(-1)*Y:Y}function p5($){let{value:J}=$,Q=(G)=>G;if(typeof J==="bigint")Q=(G)=>BigInt(G);else if(isNaN(J)||!isFinite(J))return CH.stringifyNumber($);let X="";if(J<0)X="-",J*=Q(-1);let W=Q(60),Y=[J%W];if(J<60)Y.unshift(0);else if(J=(J-Y[0])/W,Y.unshift(J%W),J>=60)J=(J-Y[0])/W,Y.unshift(J);return X+Y.map((G)=>String(G).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var fH={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})=>f4($,Q),stringify:p5},TH={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:($)=>f4($,!1),stringify:p5},d5={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(d5.test);if(!J)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,Q,X,W,Y,G,q]=J.map(Number),H=J[7]?Number((J[7]+"00").substr(1,3)):0,B=Date.UTC(Q,X-1,W,Y||0,G||0,q||0,H),U=J[8];if(U&&U!=="Z"){let z=f4(U,!1);if(Math.abs(z)<30)z*=60;B-=60000*z}return new Date(B)},stringify:({value:$})=>$?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};IH.floatTime=TH;IH.intTime=fH;IH.timestamp=d5});var n5=C((nH)=>{var yH=r$(),gH=c6(),kH=a$(),mH=S2(),uH=Z4(),i5=m5(),I4=u5(),t6=c5(),lH=x6(),cH=P4(),pH=n6(),dH=C4(),v4=T4(),iH=[yH.map,kH.seq,mH.string,gH.nullTag,i5.trueTag,i5.falseTag,t6.intBin,t6.intOct,t6.int,t6.intHex,I4.floatNaN,I4.floatExp,I4.float,uH.binary,lH.merge,cH.omap,pH.pairs,dH.set,v4.intTime,v4.floatTime,v4.timestamp];nH.schema=iH});var XJ=C((QB)=>{var o5=r$(),aH=c6(),t5=a$(),sH=S2(),oH=M4(),x4=R4(),h4=L4(),tH=E5(),eH=f5(),e5=Z4(),T2=x6(),$J=P4(),JJ=n6(),r5=n5(),QJ=C4(),e6=T4(),a5=new Map([["core",tH.schema],["failsafe",[o5.map,t5.seq,sH.string]],["json",eH.schema],["yaml11",r5.schema],["yaml-1.1",r5.schema]]),s5={binary:e5.binary,bool:oH.boolTag,float:x4.float,floatExp:x4.floatExp,floatNaN:x4.floatNaN,floatTime:e6.floatTime,int:h4.int,intHex:h4.intHex,intOct:h4.intOct,intTime:e6.intTime,map:o5.map,merge:T2.merge,null:aH.nullTag,omap:$J.omap,pairs:JJ.pairs,seq:t5.seq,set:QJ.set,timestamp:e6.timestamp},$B={"tag:yaml.org,2002:binary":e5.binary,"tag:yaml.org,2002:merge":T2.merge,"tag:yaml.org,2002:omap":$J.omap,"tag:yaml.org,2002:pairs":JJ.pairs,"tag:yaml.org,2002:set":QJ.set,"tag:yaml.org,2002:timestamp":e6.timestamp};function JB($,J,Q){let X=a5.get(J);if(X&&!$)return Q&&!X.includes(T2.merge)?X.concat(T2.merge):X.slice();let W=X;if(!W)if(Array.isArray($))W=[];else{let Y=Array.from(a5.keys()).filter((G)=>G!=="yaml11").map((G)=>JSON.stringify(G)).join(", ");throw Error(`Unknown schema "${J}"; use one of ${Y} or define customTags array`)}if(Array.isArray($))for(let Y of $)W=W.concat(Y);else if(typeof $==="function")W=$(W.slice());if(Q)W=W.concat(T2.merge);return W.reduce((Y,G)=>{let q=typeof G==="string"?s5[G]:G;if(!q){let H=JSON.stringify(G),B=Object.keys(s5).map((U)=>JSON.stringify(U)).join(", ");throw Error(`Unknown custom tag ${H}; use one of ${B}`)}if(!Y.includes(q))Y.push(q);return Y},[])}QB.coreKnownTags=$B;QB.getTags=JB});var k4=C((BB)=>{var y4=d(),YB=r$(),GB=a$(),qB=S2(),$9=XJ(),HB=($,J)=>$.key<J.key?-1:$.key>J.key?1:0;class g4{constructor({compat:$,customTags:J,merge:Q,resolveKnownTags:X,schema:W,sortMapEntries:Y,toStringDefaults:G}){this.compat=Array.isArray($)?$9.getTags($,"compat"):$?$9.getTags(null,$):null,this.name=typeof W==="string"&&W||"core",this.knownTags=X?$9.coreKnownTags:{},this.tags=$9.getTags(J,this.name,Q),this.toStringOptions=G??null,Object.defineProperty(this,y4.MAP,{value:YB.map}),Object.defineProperty(this,y4.SCALAR,{value:qB.string}),Object.defineProperty(this,y4.SEQ,{value:GB.seq}),this.sortMapEntries=typeof Y==="function"?Y:Y===!0?HB:null}clone(){let $=Object.create(g4.prototype,Object.getOwnPropertyDescriptors(this));return $.tags=this.tags.slice(),$}}BB.Schema=g4});var WJ=C((DB)=>{var VB=d(),m4=w2(),I2=j2();function zB($,J){let Q=[],X=J.directives===!0;if(J.directives!==!1&&$.directives){let H=$.directives.toString($);if(H)Q.push(H),X=!0;else if($.directives.docStart)X=!0}if(X)Q.push("---");let W=m4.createStringifyContext($,J),{commentString:Y}=W.options;if($.commentBefore){if(Q.length!==1)Q.unshift("");let H=Y($.commentBefore);Q.unshift(I2.indentComment(H,""))}let G=!1,q=null;if($.contents){if(VB.isNode($.contents)){if($.contents.spaceBefore&&X)Q.push("");if($.contents.commentBefore){let U=Y($.contents.commentBefore);Q.push(I2.indentComment(U,""))}W.forceBlockIndent=!!$.comment,q=$.contents.comment}let H=q?void 0:()=>G=!0,B=m4.stringify($.contents,W,()=>q=null,H);if(q)B+=I2.lineComment(B,"",Y(q));if((B[0]==="|"||B[0]===">")&&Q[Q.length-1]==="---")Q[Q.length-1]=`--- ${B}`;else Q.push(B)}else Q.push(m4.stringify($.contents,W));if($.directives?.docEnd)if($.comment){let H=Y($.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&&G)H=H.replace(/^\n+/,"");if(H){if((!G||q)&&Q[Q.length-1]!=="")Q.push("");Q.push(I2.indentComment(Y(H),""))}}return Q.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
59
|
-
`;
|
|
58
|
+
`}DB.stringifyDocument=zB});var v2=C((jB)=>{var FB=L2(),o$=S6(),R0=d(),MB=J$(),KB=t0(),RB=k4(),_B=WJ(),u4=w6(),LB=G4(),AB=A2(),l4=Y4();class c4{constructor($,J,Q){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,R0.NODE_TYPE,{value:R0.DOC});let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J,J=void 0;let W=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},Q);this.options=W;let{version:Y}=W;if(Q?._directives){if(this.directives=Q._directives.atDocument(),this.directives.yaml.explicit)Y=this.directives.yaml.version}else this.directives=new l4.Directives({version:Y});this.setSchema(Y,Q),this.contents=$===void 0?null:this.createNode($,X,Q)}clone(){let $=Object.create(c4.prototype,{[R0.NODE_TYPE]:{value:R0.DOC}});if($.commentBefore=this.commentBefore,$.comment=this.comment,$.errors=this.errors.slice(),$.warnings=this.warnings.slice(),$.options=Object.assign({},this.options),this.directives)$.directives=this.directives.clone();if($.schema=this.schema.clone(),$.contents=R0.isNode(this.contents)?this.contents.clone($.schema):this.contents,this.range)$.range=this.range.slice();return $}add($){if(t$(this.contents))this.contents.add($)}addIn($,J){if(t$(this.contents))this.contents.addIn($,J)}createAlias($,J){if(!$.anchor){let Q=u4.anchorNames(this);$.anchor=!J||Q.has(J)?u4.findNewAnchor(J||"a",Q):J}return new FB.Alias($.anchor)}createNode($,J,Q){let X=void 0;if(typeof J==="function")$=J.call({"":$},"",$),X=J;else if(Array.isArray(J)){let D=(R)=>typeof R==="number"||R instanceof String||R instanceof Number,F=J.filter(D).map(String);if(F.length>0)J=J.concat(F);X=J}else if(Q===void 0&&J)Q=J,J=void 0;let{aliasDuplicateObjects:W,anchorPrefix:Y,flow:G,keepUndefined:q,onTagObj:H,tag:B}=Q??{},{onAnchor:U,setAnchors:z,sourceObjects:V}=u4.createNodeAnchors(this,Y||"a"),M={aliasDuplicateObjects:W??!0,keepUndefined:q??!1,onAnchor:U,onTagObj:H,replacer:X,schema:this.schema,sourceObjects:V},O=AB.createNode($,B,M);if(G&&R0.isCollection(O))O.flow=!0;return z(),O}createPair($,J,Q={}){let X=this.createNode($,null,Q),W=this.createNode(J,null,Q);return new MB.Pair(X,W)}delete($){return t$(this.contents)?this.contents.delete($):!1}deleteIn($){if(o$.isEmptyPath($)){if(this.contents==null)return!1;return this.contents=null,!0}return t$(this.contents)?this.contents.deleteIn($):!1}get($,J){return R0.isCollection(this.contents)?this.contents.get($,J):void 0}getIn($,J){if(o$.isEmptyPath($))return!J&&R0.isScalar(this.contents)?this.contents.value:this.contents;return R0.isCollection(this.contents)?this.contents.getIn($,J):void 0}has($){return R0.isCollection(this.contents)?this.contents.has($):!1}hasIn($){if(o$.isEmptyPath($))return this.contents!==void 0;return R0.isCollection(this.contents)?this.contents.hasIn($):!1}set($,J){if(this.contents==null)this.contents=o$.collectionFromPath(this.schema,[$],J);else if(t$(this.contents))this.contents.set($,J)}setIn($,J){if(o$.isEmptyPath($))this.contents=J;else if(this.contents==null)this.contents=o$.collectionFromPath(this.schema,Array.from($),J);else if(t$(this.contents))this.contents.setIn($,J)}setSchema($,J={}){if(typeof $==="number")$=String($);let Q;switch($){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new l4.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 l4.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 RB.Schema(Object.assign(Q,J));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:$,jsonArg:J,mapAsMap:Q,maxAliasCount:X,onAnchor:W,reviver:Y}={}){let G={anchors:new Map,doc:this,keep:!$,mapAsMap:Q===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},q=KB.toJS(this.contents,J??"",G);if(typeof W==="function")for(let{count:H,res:B}of G.anchors.values())W(B,H);return typeof Y==="function"?LB.applyReviver(Y,{"":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 _B.stringifyDocument(this,$)}}function t$($){if(R0.isCollection($))return!0;throw Error("Expected a YAML collection as document contents")}jB.Document=c4});var x2=C((wB)=>{class J9 extends Error{constructor($,J,Q,X){super();this.name=$,this.code=Q,this.message=X,this.pos=J}}class YJ extends J9{constructor($,J,Q){super("YAMLParseError",$,J,Q)}}class GJ extends J9{constructor($,J,Q){super("YAMLWarning",$,J,Q)}}var ZB=($,J)=>(Q)=>{if(Q.pos[0]===-1)return;Q.linePos=Q.pos.map((q)=>J.linePos(q));let{line:X,col:W}=Q.linePos[0];Q.message+=` at line ${X}, column ${W}`;let Y=W-1,G=$.substring(J.lineStarts[X-1],J.lineStarts[X]).replace(/[\n\r]+$/,"");if(Y>=60&&G.length>80){let q=Math.min(Y-39,G.length-79);G="\u2026"+G.substring(q),Y-=q-1}if(G.length>80)G=G.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(G.substring(0,Y))){let q=$.substring(J.lineStarts[X-2],J.lineStarts[X-1]);if(q.length>80)q=q.substring(0,79)+`\u2026
|
|
59
|
+
`;G=q+G}if(/[^ ]/.test(G)){let q=1,H=Q.linePos[1];if(H?.line===X&&H.col>W)q=Math.max(1,Math.min(H.col-W,80-Y));let B=" ".repeat(Y)+"^".repeat(q);Q.message+=`:
|
|
60
60
|
|
|
61
|
-
${
|
|
61
|
+
${G}
|
|
62
62
|
${B}
|
|
63
|
-
`}};
|
|
64
|
-
`))return!0;if($.end){for(let J of $.end)if(J.type==="newline")return!0}return!1;case"flow-collection":for(let J of $.items){for(let Q of J.start)if(Q.type==="newline")return!0;if(J.sep){for(let Q of J.sep)if(Q.type==="newline")return!0}if(
|
|
65
|
-
`+D.comment;else q.comment=D.comment;continue}if(D.newlineAfterProp||
|
|
66
|
-
`+A.comment;else
|
|
67
|
-
`+
|
|
68
|
-
`+f;else
|
|
69
|
-
`+
|
|
70
|
-
`+
|
|
71
|
-
`.repeat(Math.max(1,
|
|
72
|
-
`;for(let D=U;D<q;++D){let[
|
|
73
|
-
`;else if(
|
|
74
|
-
`;else if(!
|
|
63
|
+
`}};wB.YAMLError=J9;wB.YAMLParseError=YJ;wB.YAMLWarning=GJ;wB.prettifyError=ZB});var h2=C((fB)=>{function CB($,{flow:J,indicator:Q,next:X,offset:W,onError:Y,parentIndent:G,startOnNewline:q}){let H=!1,B=q,U=q,z="",V="",M=!1,O=!1,D=null,F=null,R=null,_=null,A=null,Z=null,P=null;for(let N of $){if(O){if(N.type!=="space"&&N.type!=="newline"&&N.type!=="comma")Y(N.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");O=!1}if(D){if(B&&N.type!=="comment"&&N.type!=="newline")Y(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");D=null}switch(N.type){case"space":if(!J&&(Q!=="doc-start"||X?.type!=="flow-collection")&&N.source.includes("\t"))D=N;U=!0;break;case"comment":{if(!U)Y(N,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=N.source.substring(1)||" ";if(!z)z=E;else z+=V+E;V="",B=!1;break}case"newline":if(B){if(z)z+=N.source;else if(!Z||Q!=="seq-item-ind")H=!0}else V+=N.source;if(B=!0,M=!0,F||R)_=N;U=!0;break;case"anchor":if(F)Y(N,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(N.source.endsWith(":"))Y(N.offset+N.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);F=N,P??(P=N.offset),B=!1,U=!1,O=!0;break;case"tag":{if(R)Y(N,"MULTIPLE_TAGS","A node can have at most one tag");R=N,P??(P=N.offset),B=!1,U=!1,O=!0;break}case Q:if(F||R)Y(N,"BAD_PROP_ORDER",`Anchors and tags must be after the ${N.source} indicator`);if(Z)Y(N,"UNEXPECTED_TOKEN",`Unexpected ${N.source} in ${J??"collection"}`);Z=N,B=Q==="seq-item-ind"||Q==="explicit-key-ind",U=!1;break;case"comma":if(J){if(A)Y(N,"UNEXPECTED_TOKEN",`Unexpected , in ${J}`);A=N,B=!1,U=!1;break}default:Y(N,"UNEXPECTED_TOKEN",`Unexpected ${N.type} token`),B=!1,U=!1}}let w=$[$.length-1],f=w?w.offset+w.source.length:W;if(O&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))Y(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(D&&(B&&D.indent<=G||X?.type==="block-map"||X?.type==="block-seq"))Y(D,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:A,found:Z,spaceBefore:H,comment:z,hasNewline:M,anchor:F,tag:R,newlineAfterProp:_,end:f,start:P??f}}fB.resolveProps=CB});var Q9=C((IB)=>{function p4($){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(p4(J.key)||p4(J.value))return!0}return!1;default:return!0}}IB.containsNewline=p4});var d4=C((yB)=>{var xB=Q9();function hB($,J,Q){if(J?.type==="flow-collection"){let X=J.end[0];if(X.indent===$&&(X.source==="]"||X.source==="}")&&xB.containsNewline(J))Q(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}yB.flowIndentCheck=hB});var i4=C((mB)=>{var qJ=d();function kB($,J,Q){let{uniqueKeys:X}=$.options;if(X===!1)return!1;let W=typeof X==="function"?X:(Y,G)=>Y===G||qJ.isScalar(Y)&&qJ.isScalar(G)&&Y.value===G.value;return J.some((Y)=>W(Y.key,Q))}mB.mapIncludes=kB});var zJ=C((iB)=>{var HJ=J$(),lB=X$(),BJ=h2(),cB=Q9(),UJ=d4(),pB=i4(),VJ="All mapping items must start at the same column";function dB({composeNode:$,composeEmptyNode:J},Q,X,W,Y){let q=new(Y?.nodeClass??lB.YAMLMap)(Q.schema);if(Q.atRoot)Q.atRoot=!1;let H=X.offset,B=null;for(let U of X.items){let{start:z,key:V,sep:M,value:O}=U,D=BJ.resolveProps(z,{indicator:"explicit-key-ind",next:V??M?.[0],offset:H,onError:W,parentIndent:X.indent,startOnNewline:!0}),F=!D.found;if(F){if(V){if(V.type==="block-seq")W(H,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in V&&V.indent!==X.indent)W(H,"BAD_INDENT",VJ)}if(!D.anchor&&!D.tag&&!M){if(B=D.end,D.comment)if(q.comment)q.comment+=`
|
|
65
|
+
`+D.comment;else q.comment=D.comment;continue}if(D.newlineAfterProp||cB.containsNewline(V))W(V??z[z.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(D.found?.indent!==X.indent)W(H,"BAD_INDENT",VJ);Q.atKey=!0;let R=D.end,_=V?$(Q,V,D,W):J(Q,R,z,null,D,W);if(Q.schema.compat)UJ.flowIndentCheck(X.indent,V,W);if(Q.atKey=!1,pB.mapIncludes(Q,q.items,_))W(R,"DUPLICATE_KEY","Map keys must be unique");let A=BJ.resolveProps(M??[],{indicator:"map-value-ind",next:O,offset:_.range[2],onError:W,parentIndent:X.indent,startOnNewline:!V||V.type==="block-scalar"});if(H=A.end,A.found){if(F){if(O?.type==="block-map"&&!A.hasNewline)W(H,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if(Q.options.strict&&D.start<A.found.offset-1024)W(_.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,W):J(Q,H,M,null,A,W);if(Q.schema.compat)UJ.flowIndentCheck(X.indent,O,W);H=Z.range[2];let P=new HJ.Pair(_,Z);if(Q.options.keepSourceTokens)P.srcToken=U;q.items.push(P)}else{if(F)W(_.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(A.comment)if(_.comment)_.comment+=`
|
|
66
|
+
`+A.comment;else _.comment=A.comment;let Z=new HJ.Pair(_);if(Q.options.keepSourceTokens)Z.srcToken=U;q.items.push(Z)}}if(B&&B<H)W(B,"IMPOSSIBLE","Map comment with trailing content");return q.range=[X.offset,H,B??H],q}iB.resolveBlockMap=dB});var DJ=C((tB)=>{var rB=W$(),aB=h2(),sB=d4();function oB({composeNode:$,composeEmptyNode:J},Q,X,W,Y){let q=new(Y?.nodeClass??rB.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=aB.resolveProps(U,{indicator:"seq-item-ind",next:z,offset:H,onError:W,parentIndent:X.indent,startOnNewline:!0});if(!V.found)if(V.anchor||V.tag||z)if(z?.type==="block-seq")W(V.end,"BAD_INDENT","All sequence items must start at the same column");else W(H,"MISSING_CHAR","Sequence item without - indicator");else{if(B=V.end,V.comment)q.comment=V.comment;continue}let M=z?$(Q,z,V,W):J(Q,V.end,U,null,V,W);if(Q.schema.compat)sB.flowIndentCheck(X.indent,z,W);H=M.range[2],q.items.push(M)}return q.range=[X.offset,H,B??H],q}tB.resolveBlockSeq=oB});var e$=C((JU)=>{function $U($,J,Q,X){let W="";if($){let Y=!1,G="";for(let q of $){let{source:H,type:B}=q;switch(B){case"space":Y=!0;break;case"comment":{if(Q&&!Y)X(q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let U=H.substring(1)||" ";if(!W)W=U;else W+=G+U;G="";break}case"newline":if(W)G+=H;Y=!0;break;default:X(q,"UNEXPECTED_TOKEN",`Unexpected ${B} at node end`)}J+=H.length}}return{comment:W,offset:J}}JU.resolveEnd=$U});var MJ=C((UU)=>{var XU=d(),WU=J$(),OJ=X$(),YU=W$(),GU=e$(),FJ=h2(),qU=Q9(),HU=i4(),n4="Block collections are not allowed within flow collections",r4=($)=>$&&($.type==="block-map"||$.type==="block-seq");function BU({composeNode:$,composeEmptyNode:J},Q,X,W,Y){let G=X.start.source==="{",q=G?"flow map":"flow sequence",B=new(Y?.nodeClass??(G?OJ.YAMLMap:YU.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 F=0;F<X.items.length;++F){let R=X.items[F],{start:_,key:A,sep:Z,value:P}=R,w=FJ.resolveProps(_,{flow:q,indicator:"explicit-key-ind",next:A??Z?.[0],offset:z,onError:W,parentIndent:X.indent,startOnNewline:!1});if(!w.found){if(!w.anchor&&!w.tag&&!Z&&!P){if(F===0&&w.comma)W(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`);else if(F<X.items.length-1)W(w.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${q}`);if(w.comment)if(B.comment)B.comment+=`
|
|
67
|
+
`+w.comment;else B.comment=w.comment;z=w.end;continue}if(!G&&Q.options.strict&&qU.containsNewline(A))W(A,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(F===0){if(w.comma)W(w.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${q}`)}else{if(!w.comma)W(w.start,"MISSING_CHAR",`Missing , between ${q} items`);if(w.comment){let f="";$:for(let N of _)switch(N.type){case"comma":case"space":break;case"comment":f=N.source.substring(1);break $;default:break $}if(f){let N=B.items[B.items.length-1];if(XU.isPair(N))N=N.value??N.key;if(N.comment)N.comment+=`
|
|
68
|
+
`+f;else N.comment=f;w.comment=w.comment.substring(f.length+1)}}}if(!G&&!Z&&!w.found){let f=P?$(Q,P,w,W):J(Q,w.end,Z,null,w,W);if(B.items.push(f),z=f.range[2],r4(P))W(f.range,"BLOCK_IN_FLOW",n4)}else{Q.atKey=!0;let f=w.end,N=A?$(Q,A,w,W):J(Q,f,_,null,w,W);if(r4(A))W(N.range,"BLOCK_IN_FLOW",n4);Q.atKey=!1;let E=FJ.resolveProps(Z??[],{flow:q,indicator:"map-value-ind",next:P,offset:N.range[2],onError:W,parentIndent:X.indent,startOnNewline:!1});if(E.found){if(!G&&!w.found&&Q.options.strict){if(Z)for(let g of Z){if(g===E.found)break;if(g.type==="newline"){W(g,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(w.start<E.found.offset-1024)W(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(P)if("source"in P&&P.source?.[0]===":")W(P,"MISSING_CHAR",`Missing space after : in ${q}`);else W(E.start,"MISSING_CHAR",`Missing , or : between ${q} items`);let x=P?$(Q,P,E,W):E.found?J(Q,E.end,Z,null,E,W):null;if(x){if(r4(P))W(x.range,"BLOCK_IN_FLOW",n4)}else if(E.comment)if(N.comment)N.comment+=`
|
|
69
|
+
`+E.comment;else N.comment=E.comment;let i=new WU.Pair(N,x);if(Q.options.keepSourceTokens)i.srcToken=R;if(G){let g=B;if(HU.mapIncludes(Q,g.items,N))W(f,"DUPLICATE_KEY","Map keys must be unique");g.items.push(i)}else{let g=new OJ.YAMLMap(Q.schema);g.flow=!0,g.items.push(i);let c=(x??N).range;g.range=[N.range[0],c[1],c[2]],B.items.push(g)}z=x?x.range[2]:E.end}}let V=G?"}":"]",[M,...O]=X.end,D=z;if(M?.source===V)D=M.offset+M.source.length;else{let F=q[0].toUpperCase()+q.substring(1),R=U?`${F} must end with a ${V}`:`${F} in block collection must be sufficiently indented and end with a ${V}`;if(W(z,U?"MISSING_CHAR":"BAD_INDENT",R),M&&M.source.length!==1)O.unshift(M)}if(O.length>0){let F=GU.resolveEnd(O,D,Q.options.strict,W);if(F.comment)if(B.comment)B.comment+=`
|
|
70
|
+
`+F.comment;else B.comment=F.comment;B.range=[X.offset,D,F.offset]}else B.range=[X.offset,D,D];return B}UU.resolveFlowCollection=BU});var KJ=C((LU)=>{var zU=d(),DU=X0(),OU=X$(),FU=W$(),MU=zJ(),KU=DJ(),RU=MJ();function a4($,J,Q,X,W,Y){let G=Q.type==="block-map"?MU.resolveBlockMap($,J,Q,X,Y):Q.type==="block-seq"?KU.resolveBlockSeq($,J,Q,X,Y):RU.resolveFlowCollection($,J,Q,X,Y),q=G.constructor;if(W==="!"||W===q.tagName)return G.tag=q.tagName,G;if(W)G.tag=W;return G}function _U($,J,Q,X,W){let Y=X.tag,G=!Y?null:J.directives.tagName(Y.source,(V)=>W(Y,"TAG_RESOLVE_FAILED",V));if(Q.type==="block-seq"){let{anchor:V,newlineAfterProp:M}=X,O=V&&Y?V.offset>Y.offset?V:Y:V??Y;if(O&&(!M||M.offset<O.offset))W(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(!Y||!G||G==="!"||G===OU.YAMLMap.tagName&&q==="map"||G===FU.YAMLSeq.tagName&&q==="seq")return a4($,J,Q,W,G);let H=J.schema.tags.find((V)=>V.tag===G&&V.collection===q);if(!H){let V=J.schema.knownTags[G];if(V?.collection===q)J.schema.tags.push(Object.assign({},V,{default:!1})),H=V;else{if(V)W(Y,"BAD_COLLECTION_TYPE",`${V.tag} used for ${q} collection, but expects ${V.collection??"scalar"}`,!0);else W(Y,"TAG_RESOLVE_FAILED",`Unresolved tag: ${G}`,!0);return a4($,J,Q,W,G)}}let B=a4($,J,Q,W,G,H),U=H.resolve?.(B,(V)=>W(Y,"TAG_RESOLVE_FAILED",V),J.options)??B,z=zU.isNode(U)?U:new DU.Scalar(U);if(z.range=B.range,z.tag=G,H?.format)z.format=H.format;return z}LU.composeCollection=_U});var o4=C((wU)=>{var s4=X0();function jU($,J,Q){let X=J.offset,W=NU(J,$.options.strict,Q);if(!W)return{value:"",type:null,comment:"",range:[X,X,X]};let Y=W.mode===">"?s4.Scalar.BLOCK_FOLDED:s4.Scalar.BLOCK_LITERAL,G=J.source?ZU(J.source):[],q=G.length;for(let D=G.length-1;D>=0;--D){let F=G[D][1];if(F===""||F==="\r")q=D;else break}if(q===0){let D=W.chomp==="+"&&G.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,G.length-1)):"",F=X+W.length;if(J.source)F+=J.source.length;return{value:D,type:Y,comment:W.comment,range:[X,F,F]}}let H=J.indent+W.indent,B=J.offset+W.length,U=0;for(let D=0;D<q;++D){let[F,R]=G[D];if(R===""||R==="\r"){if(W.indent===0&&F.length>H)H=F.length}else{if(F.length<H)Q(B+F.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(W.indent===0)H=F.length;if(U=D,H===0&&!$.atRoot)Q(B,"BAD_INDENT","Block scalar values in collections must be indented");break}B+=F.length+R.length+1}for(let D=G.length-1;D>=q;--D)if(G[D][0].length>H)q=D+1;let z="",V="",M=!1;for(let D=0;D<U;++D)z+=G[D][0].slice(H)+`
|
|
72
|
+
`;for(let D=U;D<q;++D){let[F,R]=G[D];B+=F.length+R.length+1;let _=R[R.length-1]==="\r";if(_)R=R.slice(0,-1);if(R&&F.length<H){let Z=`Block scalar lines must not be less indented than their ${W.indent?"explicit indentation indicator":"first line"}`;Q(B-R.length-(_?2:1),"BAD_INDENT",Z),F=""}if(Y===s4.Scalar.BLOCK_LITERAL)z+=V+F.slice(H)+R,V=`
|
|
73
|
+
`;else if(F.length>H||R[0]==="\t"){if(V===" ")V=`
|
|
74
|
+
`;else if(!M&&V===`
|
|
75
75
|
`)V=`
|
|
76
76
|
|
|
77
|
-
`;z+=V+
|
|
78
|
-
`,
|
|
77
|
+
`;z+=V+F.slice(H)+R,V=`
|
|
78
|
+
`,M=!0}else if(R==="")if(V===`
|
|
79
79
|
`)z+=`
|
|
80
80
|
`;else V=`
|
|
81
|
-
`;else z+=V+
|
|
82
|
-
`+
|
|
81
|
+
`;else z+=V+R,V=" ",M=!1}switch(W.chomp){case"-":break;case"+":for(let D=q;D<G.length;++D)z+=`
|
|
82
|
+
`+G[D][0].slice(H);if(z[z.length-1]!==`
|
|
83
83
|
`)z+=`
|
|
84
84
|
`;break;default:z+=`
|
|
85
|
-
`}let O=X+
|
|
86
|
-
`)G
|
|
87
|
-
`;else G
|
|
88
|
-
`)continue;if(
|
|
89
|
-
`){let{fold:
|
|
90
|
-
`){
|
|
91
|
-
`){
|
|
92
|
-
`&&!(
|
|
93
|
-
`))Q+=X>
|
|
85
|
+
`}let O=X+W.length+J.source.length;return{value:z,type:Y,comment:W.comment,range:[X,O,O]}}function NU({offset:$,props:J},Q,X){if(J[0].type!=="block-scalar-header")return X(J[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:W}=J[0],Y=W[0],G=0,q="",H=-1;for(let V=1;V<W.length;++V){let M=W[V];if(!q&&(M==="-"||M==="+"))q=M;else{let O=Number(M);if(!G&&O)G=O;else if(H===-1)H=$+V}}if(H!==-1)X(H,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${W}`);let B=!1,U="",z=W.length;for(let V=1;V<J.length;++V){let M=J[V];switch(M.type){case"space":B=!0;case"newline":z+=M.source.length;break;case"comment":if(Q&&!B)X(M,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");z+=M.source.length,U=M.source.substring(1);break;case"error":X(M,"UNEXPECTED_TOKEN",M.message),z+=M.source.length;break;default:{let O=`Unexpected token in block scalar header: ${M.type}`;X(M,"UNEXPECTED_TOKEN",O);let D=M.source;if(D&&typeof D==="string")z+=D.length}}}return{mode:Y,indent:G,chomp:q,comment:U,length:z}}function ZU($){let J=$.split(/\n( *)/),Q=J[0],X=Q.match(/^( *)/),Y=[X?.[1]?[X[1],Q.slice(X[1].length)]:["",Q]];for(let G=1;G<J.length;G+=2)Y.push([J[G],J[G+1]]);return Y}wU.resolveBlockScalar=jU});var e4=C((xU)=>{var t4=X0(),PU=e$();function SU($,J,Q){let{offset:X,type:W,source:Y,end:G}=$,q,H,B=(V,M,O)=>Q(X+V,M,O);switch(W){case"scalar":q=t4.Scalar.PLAIN,H=EU(Y,B);break;case"single-quoted-scalar":q=t4.Scalar.QUOTE_SINGLE,H=CU(Y,B);break;case"double-quoted-scalar":q=t4.Scalar.QUOTE_DOUBLE,H=fU(Y,B);break;default:return Q($,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${W}`),{value:"",type:null,comment:"",range:[X,X+Y.length,X+Y.length]}}let U=X+Y.length,z=PU.resolveEnd(G,U,J,Q);return{value:H,type:q,comment:z.comment,range:[X,U,z.offset]}}function EU($,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 RJ($)}function CU($,J){if($[$.length-1]!=="'"||$.length===1)J($.length,"MISSING_CHAR","Missing closing 'quote");return RJ($.slice(1,-1)).replace(/''/g,"'")}function RJ($){let J=/(.*?)\r?\n/sy,Q=J.exec($);if(!Q)return $;let X,W;try{X=new RegExp("(?<![ \t])[ \t]+$"),W=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,W=/^[ \t]+|[ \t]+$/g}let Y=Q[1].replace(X,""),G=" ",q=J.lastIndex;while(Q=J.exec($)){let B=Q[1].replace(W,"");if(B==="")if(G===`
|
|
86
|
+
`)Y+=G;else G=`
|
|
87
|
+
`;else Y+=G+B,G=" ";q=J.lastIndex}let H=/[ \t]*(.*)/sy;return H.lastIndex=q,Q=H.exec($),Y+G+(Q?.[1]??"")}function fU($,J){let Q="";for(let X=1;X<$.length-1;++X){let W=$[X];if(W==="\r"&&$[X+1]===`
|
|
88
|
+
`)continue;if(W===`
|
|
89
|
+
`){let{fold:Y,offset:G}=TU($,X);Q+=Y,X=G}else if(W==="\\"){let Y=$[++X],G=IU[Y];if(G)Q+=G;else if(Y===`
|
|
90
|
+
`){Y=$[X+1];while(Y===" "||Y==="\t")Y=$[++X+1]}else if(Y==="\r"&&$[X+1]===`
|
|
91
|
+
`){Y=$[++X+1];while(Y===" "||Y==="\t")Y=$[++X+1]}else if(Y==="x"||Y==="u"||Y==="U"){let q=Y==="x"?2:Y==="u"?4:8;Q+=vU($,X+1,q,J),X+=q}else{let q=$.substr(X-1,2);J(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${q}`),Q+=q}}else if(W===" "||W==="\t"){let Y=X,G=$[X+1];while(G===" "||G==="\t")G=$[++X+1];if(G!==`
|
|
92
|
+
`&&!(G==="\r"&&$[X+2]===`
|
|
93
|
+
`))Q+=X>Y?$.slice(Y,X+1):W}else Q+=W}if($[$.length-1]!=='"'||$.length===1)J($.length,"MISSING_CHAR",'Missing closing "quote');return Q}function TU($,J){let Q="",X=$[J+1];while(X===" "||X==="\t"||X===`
|
|
94
94
|
`||X==="\r"){if(X==="\r"&&$[J+2]!==`
|
|
95
95
|
`)break;if(X===`
|
|
96
96
|
`)Q+=`
|
|
97
|
-
`;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var
|
|
98
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
97
|
+
`;J+=1,X=$[J+1]}if(!Q)Q=" ";return{fold:Q,offset:J}}var IU={"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 vU($,J,Q,X){let W=$.substr(J,Q),G=W.length===Q&&/^[0-9a-fA-F]+$/.test(W)?parseInt(W,16):NaN;try{return String.fromCodePoint(G)}catch{let q=$.substr(J-2,Q+2);return X(J-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${q}`),q}}xU.resolveFlowScalar=SU});var LJ=C((lU)=>{var L$=d(),_J=X0(),yU=o4(),gU=e4();function kU($,J,Q,X){let{value:W,type:Y,comment:G,range:q}=J.type==="block-scalar"?yU.resolveBlockScalar($,J,X):gU.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=mU($.schema,W,H,Q,X);else if(J.type==="scalar")B=uU($,W,J,X);else B=$.schema[L$.SCALAR];let U;try{let z=B.resolve(W,(V)=>X(Q??J,"TAG_RESOLVE_FAILED",V),$.options);U=L$.isScalar(z)?z:new _J.Scalar(z)}catch(z){let V=z instanceof Error?z.message:String(z);X(Q??J,"TAG_RESOLVE_FAILED",V),U=new _J.Scalar(W)}if(U.range=q,U.source=W,Y)U.type=Y;if(H)U.tag=H;if(B.format)U.format=B.format;if(G)U.comment=G;return U}function mU($,J,Q,X,W){if(Q==="!")return $[L$.SCALAR];let Y=[];for(let q of $.tags)if(!q.collection&&q.tag===Q)if(q.default&&q.test)Y.push(q);else return q;for(let q of Y)if(q.test?.test(J))return q;let G=$.knownTags[Q];if(G&&!G.collection)return $.tags.push(Object.assign({},G,{default:!1,test:void 0})),G;return W(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,Q!=="tag:yaml.org,2002:str"),$[L$.SCALAR]}function uU({atKey:$,directives:J,schema:Q},X,W,Y){let G=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(G.tag!==q.tag){let H=J.tagString(G.tag),B=J.tagString(q.tag),U=`Value may be parsed as either ${H} or ${B}`;Y(W,"TAG_RESOLVE_FAILED",U,!0)}}return G}lU.composeScalar=kU});var AJ=C((dU)=>{function pU($,J,Q){if(J){Q??(Q=J.length);for(let X=Q-1;X>=0;--X){let W=J[X];switch(W.type){case"space":case"comment":case"newline":$-=W.source.length;continue}W=J[++X];while(W?.type==="space")$+=W.source.length,W=J[++X];break}}return $}dU.emptyScalarPosition=pU});var ZJ=C(($V)=>{var nU=L2(),rU=d(),aU=KJ(),jJ=LJ(),sU=e$(),oU=AJ(),tU={composeNode:NJ,composeEmptyNode:$8};function NJ($,J,Q,X){let W=$.atKey,{spaceBefore:Y,comment:G,anchor:q,tag:H}=Q,B,U=!0;switch(J.type){case"alias":if(B=eU($,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=jJ.composeScalar($,J,H,X),q)B.anchor=q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(B=aU.composeCollection(tU,$,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=$8($,J.offset,void 0,null,Q,X)),q&&B.anchor==="")X(q,"BAD_ALIAS","Anchor cannot be an empty string");if(W&&$.options.stringKeys&&(!rU.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(Y)B.spaceBefore=!0;if(G)if(J.type==="scalar"&&J.source==="")B.comment=G;else B.commentBefore=G;if($.options.keepSourceTokens&&U)B.srcToken=J;return B}function $8($,J,Q,X,{spaceBefore:W,comment:Y,anchor:G,tag:q,end:H},B){let U={type:"scalar",offset:oU.emptyScalarPosition(J,Q,X),indent:-1,source:""},z=jJ.composeScalar($,U,q,B);if(G){if(z.anchor=G.source.substring(1),z.anchor==="")B(G,"BAD_ALIAS","Anchor cannot be an empty string")}if(W)z.spaceBefore=!0;if(Y)z.comment=Y,z.range[2]=H;return z}function eU({options:$},{offset:J,source:Q,end:X},W){let Y=new nU.Alias(Q.substring(1));if(Y.source==="")W(J,"BAD_ALIAS","Alias cannot be an empty string");if(Y.source.endsWith(":"))W(J+Q.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let G=J+Q.length,q=sU.resolveEnd(X,G,$.strict,W);if(Y.range=[J,G,q.offset],q.comment)Y.comment=q.comment;return Y}$V.composeEmptyNode=$8;$V.composeNode=NJ});var bJ=C((qV)=>{var XV=v2(),wJ=ZJ(),WV=e$(),YV=h2();function GV($,J,{offset:Q,start:X,value:W,end:Y},G){let q=Object.assign({_directives:J},$),H=new XV.Document(void 0,q),B={atKey:!1,atRoot:!0,directives:H.directives,options:H.options,schema:H.schema},U=YV.resolveProps(X,{indicator:"doc-start",next:W??Y?.[0],offset:Q,onError:G,parentIndent:0,startOnNewline:!0});if(U.found){if(H.directives.docStart=!0,W&&(W.type==="block-map"||W.type==="block-seq")&&!U.hasNewline)G(U.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}H.contents=W?wJ.composeNode(B,W,U,G):wJ.composeEmptyNode(B,U.end,X,null,U,G);let z=H.contents.range[2],V=WV.resolveEnd(Y,z,!1,G);if(V.comment)H.comment=V.comment;return H.range=[Q,z,V.offset],H}qV.composeDoc=GV});var J8=C((OV)=>{var BV=q6("process"),UV=Y4(),VV=v2(),y2=x2(),PJ=d(),zV=bJ(),DV=e$();function g2($){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 SJ($){let J="",Q=!1,X=!1;for(let W=0;W<$.length;++W){let Y=$[W];switch(Y[0]){case"#":J+=(J===""?"":X?`
|
|
99
99
|
|
|
100
100
|
`:`
|
|
101
|
-
`)+(
|
|
102
|
-
${Q}`:Q;else if(X||$.directives.docStart||!
|
|
103
|
-
${
|
|
104
|
-
${
|
|
105
|
-
${J.comment}`:J.comment}this.doc.range[2]=J.offset;break}default:this.errors.push(new
|
|
101
|
+
`)+(Y.substring(1)||" "),Q=!0,X=!1;break;case"%":if($[W+1]?.[0]!=="#")W+=1;Q=!1;break;default:if(!Q)X=!0;Q=!1}}return{comment:J,afterEmptyLine:X}}class EJ{constructor($={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(J,Q,X,W)=>{let Y=g2(J);if(W)this.warnings.push(new y2.YAMLWarning(Y,Q,X));else this.errors.push(new y2.YAMLParseError(Y,Q,X))},this.directives=new UV.Directives({version:$.version||"1.2"}),this.options=$}decorate($,J){let{comment:Q,afterEmptyLine:X}=SJ(this.prelude);if(Q){let W=$.contents;if(J)$.comment=$.comment?`${$.comment}
|
|
102
|
+
${Q}`:Q;else if(X||$.directives.docStart||!W)$.commentBefore=Q;else if(PJ.isCollection(W)&&!W.flow&&W.items.length>0){let Y=W.items[0];if(PJ.isPair(Y))Y=Y.key;let G=Y.commentBefore;Y.commentBefore=G?`${Q}
|
|
103
|
+
${G}`:Q}else{let Y=W.commentBefore;W.commentBefore=Y?`${Q}
|
|
104
|
+
${Y}`:Q}}if(J){for(let W=0;W<this.errors.length;++W)$.errors.push(this.errors[W]);for(let W=0;W<this.warnings.length;++W)$.warnings.push(this.warnings[W])}else $.errors=this.errors,$.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:SJ(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(BV.env.LOG_STREAM)console.dir($,{depth:null});switch($.type){case"directive":this.directives.add($.source,(J,Q,X)=>{let W=g2($);W[0]+=J,this.onError(W,"BAD_DIRECTIVE",Q,X)}),this.prelude.push($.source),this.atDirectives=!0;break;case"document":{let J=zV.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 y2.YAMLParseError(g2($),"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 y2.YAMLParseError(g2($),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let J=DV.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 y2.YAMLParseError(g2($),"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 VV.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}}}OV.Composer=EJ});var TJ=C((NV)=>{var MV=o4(),KV=e4(),RV=x2(),CJ=Z2();function _V($,J=!0,Q){if($){let X=(W,Y,G)=>{let q=typeof W==="number"?W:Array.isArray(W)?W[0]:W.offset;if(Q)Q(q,Y,G);else throw new RV.YAMLParseError([q,q+1],Y,G)};switch($.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return KV.resolveFlowScalar($,J,X);case"block-scalar":return MV.resolveBlockScalar({options:{strict:J}},$,X)}}return null}function LV($,J){let{implicitKey:Q=!1,indent:X,inFlow:W=!1,offset:Y=-1,type:G="PLAIN"}=J,q=CJ.stringifyString({type:G,value:$},{implicitKey:Q,indent:X>0?" ".repeat(X):"",inFlow:W,options:{blockQuote:!0,lineWidth:-1}}),H=J.end??[{type:"newline",offset:-1,indent:X,source:`
|
|
106
106
|
`}];switch(q[0]){case"|":case">":{let B=q.indexOf(`
|
|
107
107
|
`),U=q.substring(0,B),z=q.substring(B+1)+`
|
|
108
|
-
`,V=[{type:"block-scalar-header",offset:
|
|
109
|
-
`});return{type:"block-scalar",offset:
|
|
110
|
-
`),X=J.substring(0,Q),
|
|
111
|
-
`;if($.type==="block-scalar"){let
|
|
112
|
-
`});for(let H of Object.keys($))if(H!=="type"&&H!=="offset")delete $[H];Object.assign($,{type:"block-scalar",indent:
|
|
113
|
-
`};delete $.items,Object.assign($,{type:Q,source:J,end:[
|
|
108
|
+
`,V=[{type:"block-scalar-header",offset:Y,indent:X,source:U}];if(!fJ(V,H))V.push({type:"newline",offset:-1,indent:X,source:`
|
|
109
|
+
`});return{type:"block-scalar",offset:Y,indent:X,props:V,source:z}}case'"':return{type:"double-quoted-scalar",offset:Y,indent:X,source:q,end:H};case"'":return{type:"single-quoted-scalar",offset:Y,indent:X,source:q,end:H};default:return{type:"scalar",offset:Y,indent:X,source:q,end:H}}}function AV($,J,Q={}){let{afterKey:X=!1,implicitKey:W=!1,inFlow:Y=!1,type:G}=Q,q="indent"in $?$.indent:null;if(X&&typeof q==="number")q+=2;if(!G)switch($.type){case"single-quoted-scalar":G="QUOTE_SINGLE";break;case"double-quoted-scalar":G="QUOTE_DOUBLE";break;case"block-scalar":{let B=$.props[0];if(B.type!=="block-scalar-header")throw Error("Invalid block scalar header");G=B.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:G="PLAIN"}let H=CJ.stringifyString({type:G,value:J},{implicitKey:W||q===null,indent:q!==null&&q>0?" ".repeat(q):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}});switch(H[0]){case"|":case">":jV($,H);break;case'"':Q8($,H,"double-quoted-scalar");break;case"'":Q8($,H,"single-quoted-scalar");break;default:Q8($,H,"scalar")}}function jV($,J){let Q=J.indexOf(`
|
|
110
|
+
`),X=J.substring(0,Q),W=J.substring(Q+1)+`
|
|
111
|
+
`;if($.type==="block-scalar"){let Y=$.props[0];if(Y.type!=="block-scalar-header")throw Error("Invalid block scalar header");Y.source=X,$.source=W}else{let{offset:Y}=$,G="indent"in $?$.indent:-1,q=[{type:"block-scalar-header",offset:Y,indent:G,source:X}];if(!fJ(q,"end"in $?$.end:void 0))q.push({type:"newline",offset:-1,indent:G,source:`
|
|
112
|
+
`});for(let H of Object.keys($))if(H!=="type"&&H!=="offset")delete $[H];Object.assign($,{type:"block-scalar",indent:G,props:q,source:W})}}function fJ($,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 Q8($,J,Q){switch($.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":$.type=Q,$.source=J;break;case"block-scalar":{let X=$.props.slice(1),W=J.length;if($.props[0].type==="block-scalar-header")W-=$.props[0].source.length;for(let Y of X)Y.offset+=W;delete $.props,Object.assign($,{type:Q,source:J,end:X});break}case"block-map":case"block-seq":{let W={type:"newline",offset:$.offset+J.length,indent:$.indent,source:`
|
|
113
|
+
`};delete $.items,Object.assign($,{type:Q,source:J,end:[W]});break}default:{let X="indent"in $?$.indent:-1,W="end"in $&&Array.isArray($.end)?$.end.filter((Y)=>Y.type==="space"||Y.type==="comment"||Y.type==="newline"):[];for(let Y of Object.keys($))if(Y!=="type"&&Y!=="offset")delete $[Y];Object.assign($,{type:Q,indent:X,source:J,end:W})}}}NV.createScalarToken=LV;NV.resolveAsScalar=_V;NV.setScalarValue=AV});var IJ=C((SV)=>{var PV=($)=>("type"in $)?W9($):X9($);function W9($){switch($.type){case"block-scalar":{let J="";for(let Q of $.props)J+=W9(Q);return J+$.source}case"block-map":case"block-seq":{let J="";for(let Q of $.items)J+=X9(Q);return J}case"flow-collection":{let J=$.start.source;for(let Q of $.items)J+=X9(Q);for(let Q of $.end)J+=Q.source;return J}case"document":{let J=X9($);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 X9({start:$,key:J,sep:Q,value:X}){let W="";for(let Y of $)W+=Y.source;if(J)W+=W9(J);if(Q)for(let Y of Q)W+=Y.source;if(X)W+=W9(X);return W}SV.stringify=PV});var hJ=C((fV)=>{var X8=Symbol("break visit"),CV=Symbol("skip children"),vJ=Symbol("remove item");function A$($,J){if("type"in $&&$.type==="document")$={start:$.start,value:$.value};xJ(Object.freeze([]),$,J)}A$.BREAK=X8;A$.SKIP=CV;A$.REMOVE=vJ;A$.itemAtPath=($,J)=>{let Q=$;for(let[X,W]of J){let Y=Q?.[X];if(Y&&"items"in Y)Q=Y.items[W];else return}return Q};A$.parentCollection=($,J)=>{let Q=A$.itemAtPath($,J.slice(0,-1)),X=J[J.length-1][0],W=Q?.[X];if(W&&"items"in W)return W;throw Error("Parent collection not found")};function xJ($,J,Q){let X=Q(J,$);if(typeof X==="symbol")return X;for(let W of["key","value"]){let Y=J[W];if(Y&&"items"in Y){for(let G=0;G<Y.items.length;++G){let q=xJ(Object.freeze($.concat([[W,G]])),Y.items[G],Q);if(typeof q==="number")G=q-1;else if(q===X8)return X8;else if(q===vJ)Y.items.splice(G,1),G-=1}if(typeof X==="function"&&W==="key")X=X(J,$)}}return typeof X==="function"?X(J,$):X}fV.visit=A$});var Y9=C((kV)=>{var W8=TJ(),IV=IJ(),vV=hJ(),Y8="\uFEFF",G8="\x02",q8="\x18",H8="\x1F",xV=($)=>!!$&&("items"in $),hV=($)=>!!$&&($.type==="scalar"||$.type==="single-quoted-scalar"||$.type==="double-quoted-scalar"||$.type==="block-scalar");function yV($){switch($){case Y8:return"<BOM>";case G8:return"<DOC>";case q8:return"<FLOW_END>";case H8:return"<SCALAR>";default:return JSON.stringify($)}}function gV($){switch($){case Y8:return"byte-order-mark";case G8:return"doc-mode";case q8:return"flow-error-end";case H8:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
|
|
114
114
|
`:case`\r
|
|
115
|
-
`:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch($[0]){case" ":case"\t":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}
|
|
116
|
-
`:case"\r":case"\t":return!0;default:return!1}}var
|
|
117
|
-
\r `),
|
|
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}kV.createScalarToken=W8.createScalarToken;kV.resolveAsScalar=W8.resolveAsScalar;kV.setScalarValue=W8.setScalarValue;kV.stringify=IV.stringify;kV.visit=vV.visit;kV.BOM=Y8;kV.DOCUMENT=G8;kV.FLOW_END=q8;kV.SCALAR=H8;kV.isCollection=xV;kV.isScalar=hV;kV.prettyToken=yV;kV.tokenType=gV});var U8=C((Jz)=>{var k2=Y9();function S0($){switch($){case void 0:case" ":case`
|
|
116
|
+
`:case"\r":case"\t":return!0;default:return!1}}var yJ=new Set("0123456789ABCDEFabcdef"),eV=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),G9=new Set(",[]{}"),$z=new Set(` ,[]{}
|
|
117
|
+
\r `),B8=($)=>!$||$z.has($);class gJ{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex($,J=!1){if($){if(typeof $!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+$:$,this.lineEndPos=null}this.atEnd=!J;let Q=this.next??"stream";while(Q&&(J||this.hasChars(1)))Q=yield*this.parseNext(Q)}atLineEnd(){let $=this.pos,J=this.buffer[$];while(J===" "||J==="\t")J=this.buffer[++$];if(!J||J==="#"||J===`
|
|
118
118
|
`)return!0;if(J==="\r")return this.buffer[$+1]===`
|
|
119
119
|
`;return!1}charAt($){return this.buffer[this.pos+$]}continueScalar($){let J=this.buffer[$];if(this.indentNext>0){let Q=0;while(J===" ")J=this.buffer[++Q+$];if(J==="\r"){let X=this.buffer[Q+$+1];if(X===`
|
|
120
120
|
`||!X&&!this.atEnd)return $+Q+1}return J===`
|
|
121
|
-
`||Q>=this.indentNext||!J&&!this.atEnd?$+Q:-1}if(J==="-"||J==="."){let Q=this.buffer.substr($,3);if((Q==="---"||Q==="...")&&
|
|
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]===
|
|
123
|
-
`,this.pos);if(X!==-1){while(X!==-1){let
|
|
124
|
-
`,
|
|
125
|
-
`:$=
|
|
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
|
|
127
|
-
`,
|
|
128
|
-
`)Q=this.buffer[++X];$=X-1}else if(!this.blockScalarKeep)do{let
|
|
129
|
-
`&&
|
|
121
|
+
`||Q>=this.indentNext||!J&&!this.atEnd?$+Q:-1}if(J==="-"||J==="."){let Q=this.buffer.substr($,3);if((Q==="---"||Q==="...")&&S0(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]===k2.BOM)yield*this.pushCount(1),$=$.substring(1);if($[0]==="%"){let J=$.length,Q=$.indexOf("#");while(Q!==-1){let W=$[Q-1];if(W===" "||W==="\t"){J=Q-1;break}else Q=$.indexOf("#",Q+1)}while(!0){let W=$[J-1];if(W===" "||W==="\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 k2.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==="...")&&S0(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&&!S0(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(($==="-"||$==="?"||$===":")&&S0(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(B8),"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("..."))&&S0(X[3])){if(!(Q===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield k2.FLOW_END,yield*this.parseLineStart()}let W=0;while(X[W]===",")W+=yield*this.pushCount(1),W+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(W+=yield*this.pushIndicators(),X[W]){case void 0:return"flow";case"#":return yield*this.pushCount(X.length-W),"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(B8),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let Y=this.charAt(1);if(this.flowKey||S0(Y)||Y===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let $=this.charAt(0),J=this.buffer.indexOf($,this.pos+1);if($==="'")while(J!==-1&&this.buffer[J+1]==="'")J=this.buffer.indexOf("'",J+2);else while(J!==-1){let W=0;while(this.buffer[J-1-W]==="\\")W+=1;if(W%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 W=this.continueScalar(X+1);if(W===-1)break;X=Q.indexOf(`
|
|
124
|
+
`,W)}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)=>S0(J)||J==="#")}*parseBlockScalar(){let $=this.pos-1,J=0,Q;$:for(let W=this.pos;Q=this.buffer[W];++W)switch(Q){case" ":J+=1;break;case`
|
|
125
|
+
`:$=W,J=0;break;case"\r":{let Y=this.buffer[W+1];if(!Y&&!this.atEnd)return this.setNext("block-scalar");if(Y===`
|
|
126
|
+
`)break}default:break $}if(!Q&&!this.atEnd)return this.setNext("block-scalar");if(J>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=J;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let W=this.continueScalar($+1);if(W===-1)break;$=this.buffer.indexOf(`
|
|
127
|
+
`,W)}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 W=$-1,Y=this.buffer[W];if(Y==="\r")Y=this.buffer[--W];let G=W;while(Y===" ")Y=this.buffer[--W];if(Y===`
|
|
129
|
+
`&&W>=this.pos&&W+1+J>G)$=W;else break}while(!0);return yield k2.SCALAR,yield*this.pushToIndex($+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let $=this.flowLevel>0,J=this.pos-1,Q=this.pos-1,X;while(X=this.buffer[++Q])if(X===":"){let W=this.buffer[Q+1];if(S0(W)||$&&G9.has(W))break;J=Q}else if(S0(X)){let W=this.buffer[Q+1];if(X==="\r")if(W===`
|
|
130
130
|
`)Q+=1,X=`
|
|
131
|
-
`,
|
|
132
|
-
`){let
|
|
131
|
+
`,W=this.buffer[Q+1];else J=Q;if(W==="#"||$&&G9.has(W))break;if(X===`
|
|
132
|
+
`){let Y=this.continueScalar(Q+1);if(Y===-1)break;Q=Math.max(Q,Y-2)}}else{if($&&G9.has(X))break;J=Q}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield k2.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(B8),$+=yield*this.pushSpaces(!0);continue $;case"-":case"?":case":":{let J=this.flowLevel>0,Q=this.charAt(1);if(S0(Q)||J&&G9.has(Q)){if(!J)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;$+=yield*this.pushCount(1),$+=yield*this.pushSpaces(!0);continue $}}}break $}return $}*pushTag(){if(this.charAt(1)==="<"){let $=this.pos+2,J=this.buffer[$];while(!S0(J)&&J!==">")J=this.buffer[++$];return yield*this.pushToIndex(J===">"?$+1:$,!1)}else{let $=this.pos+1,J=this.buffer[$];while(J)if(eV.has(J))J=this.buffer[++$];else if(J==="%"&&yJ.has(this.buffer[$+1])&&yJ.has(this.buffer[$+2]))J=this.buffer[$+=3];else break;return yield*this.pushToIndex($,!1)}}*pushNewline(){let $=this.buffer[this.pos];if($===`
|
|
133
133
|
`)return yield*this.pushCount(1);else if($==="\r"&&this.charAt(1)===`
|
|
134
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces($){let J=this.pos-1,Q;do Q=this.buffer[++J];while(Q===" "||$&&Q==="\t");let X=J-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=J;return X}*pushUntil($){let J=this.pos,Q=this.buffer[J];while(!$(Q))Q=this.buffer[++J];return yield*this.pushToIndex(J,!1)}}
|
|
134
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces($){let J=this.pos-1,Q;do Q=this.buffer[++J];while(Q===" "||$&&Q==="\t");let X=J-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=J;return X}*pushUntil($){let J=this.pos,Q=this.buffer[J];while(!$(Q))Q=this.buffer[++J];return yield*this.pushToIndex(J,!1)}}Jz.Lexer=gJ});var V8=C((Xz)=>{class kJ{constructor(){this.lineStarts=[],this.addNewLine=($)=>this.lineStarts.push($),this.linePos=($)=>{let J=0,Q=this.lineStarts.length;while(J<Q){let W=J+Q>>1;if(this.lineStarts[W]<$)J=W+1;else Q=W}if(this.lineStarts[J]===$)return{line:J+1,col:1};if(J===0)return{line:0,col:$};let X=this.lineStarts[J-1];return{line:J,col:$-X+1}}}}Xz.LineCounter=kJ});var z8=C((qz)=>{var Yz=q6("process"),mJ=Y9(),Gz=U8();function Y$($,J){for(let Q=0;Q<$.length;++Q)if($[Q].type===J)return!0;return!1}function uJ($){for(let J=0;J<$.length;++J)switch($[J].type){case"space":case"comment":case"newline":break;default:return J}return-1}function cJ($){switch($?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function q9($){switch($.type){case"document":return $.start;case"block-map":{let J=$.items[$.items.length-1];return J.sep??J.start}case"block-seq":return $.items[$.items.length-1].start;default:return[]}}function $2($){if($.length===0)return[];let J=$.length;$:while(--J>=0)switch($[J].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break $}while($[++J]?.type==="space");return $.splice(J,$.length)}function H9($,J){if(J.length<1e5)Array.prototype.push.apply($,J);else for(let Q=0;Q<J.length;++Q)$.push(J[Q])}function lJ($){if($.start.type==="flow-seq-start"){for(let J of $.items)if(J.sep&&!J.value&&!Y$(J.start,"explicit-key-ind")&&!Y$(J.sep,"map-value-ind")){if(J.key)J.value=J.key;if(delete J.key,cJ(J.value))if(J.value.end)H9(J.value.end,J.sep);else J.value.end=J.sep;else H9(J.start,J.sep);delete J.sep}}}class pJ{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 Gz.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=$,Yz.env.LOG_TOKENS)console.log("|",mJ.prettyToken($));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=$.length;return}let J=mJ.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")lJ(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&&uJ(X.start)===-1&&(J.indent===0||X.start.every((W)=>W.type!=="comment"||W.indent<J.indent))){if(Q.type==="document")Q.end=X.start;else Q.items.push({start:X.start});J.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let $={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")$.start.push(this.sourceToken);this.stack.push($);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document($){if($.value)return yield*this.lineEnd($);switch(this.type){case"doc-start":{if(uJ($.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=q9(this.peek(2)),Q=$2(J),X;if($.end)X=$.end,X.push(this.sourceToken),delete $.end;else X=[this.sourceToken];let W={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:Q,key:$,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}else yield*this.lineEnd($)}*blockScalar($){switch(this.type){case"space":case"comment":case"newline":$.props.push(this.sourceToken);return;case"scalar":if($.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let J=this.source.indexOf(`
|
|
135
135
|
`)+1;while(J!==0)this.onNewLine(this.offset+J),J=this.source.indexOf(`
|
|
136
|
-
`,J)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else if(J.sep)J.sep.push(this.sourceToken);else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){
|
|
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)){H9(X,J.start),X.push(this.sourceToken),$.items.pop();return}}J.start.push(this.sourceToken)}return}if(this.indent>=$.indent){let Q=!this.onKeyLine&&this.indent===$.indent,X=Q&&(J.sep||J.explicitKey)&&this.type!=="seq-item-ind",W=[];if(X&&J.sep&&!J.value){let Y=[];for(let G=0;G<J.sep.length;++G){let q=J.sep[G];switch(q.type){case"newline":Y.push(G);break;case"space":break;case"comment":if(q.indent>$.indent)Y.length=0;break;default:Y.length=0}}if(Y.length>=2)W=J.sep.splice(Y[1])}switch(this.type){case"anchor":case"tag":if(X||J.value)W.push(this.sourceToken),$.items.push({start:W}),this.onKeyLine=!0;else if(J.sep)J.sep.push(this.sourceToken);else J.start.push(this.sourceToken);return;case"explicit-key-ind":if(!J.sep&&!J.explicitKey)J.start.push(this.sourceToken),J.explicitKey=!0;else if(X||J.value)W.push(this.sourceToken),$.items.push({start:W,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(J.explicitKey)if(!J.sep)if(Y$(J.start,"newline"))Object.assign(J,{key:null,sep:[this.sourceToken]});else{let Y=$2(J.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]})}else if(J.value)$.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Y$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:W,key:null,sep:[this.sourceToken]}]});else if(cJ(J.key)&&!Y$(J.sep,"newline")){let Y=$2(J.start),G=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:Y,key:G,sep:q}]})}else if(W.length>0)J.sep=J.sep.concat(W,this.sourceToken);else J.sep.push(this.sourceToken);else if(!J.sep)Object.assign(J,{key:null,sep:[this.sourceToken]});else if(J.value||X)$.items.push({start:W,key:null,sep:[this.sourceToken]});else if(Y$(J.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else J.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let Y=this.flowScalar(this.type);if(X||J.value)$.items.push({start:W,key:Y,sep:[]}),this.onKeyLine=!0;else if(J.sep)this.stack.push(Y);else Object.assign(J,{key:Y,sep:[]}),this.onKeyLine=!0;return}default:{let Y=this.startBlockValue($);if(Y){if(Y.type==="block-seq"){if(!J.explicitKey&&J.sep&&!Y$(J.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if(Q)$.items.push({start:W});this.stack.push(Y);return}}}}yield*this.pop(),yield*this.step()}*blockSequence($){let J=$.items[$.items.length-1];switch(this.type){case"newline":if(J.value){let Q="end"in J.value?J.value.end:void 0;if((Array.isArray(Q)?Q[Q.length-1]:void 0)?.type==="comment")Q?.push(this.sourceToken);else $.items.push({start:[this.sourceToken]})}else J.start.push(this.sourceToken);return;case"space":case"comment":if(J.value)$.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(J.start,$.indent)){let X=$.items[$.items.length-2]?.value?.end;if(Array.isArray(X)){H9(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||Y$(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=q9(Q),W=$2(X);lJ($);let Y=$.end.splice(1,$.end.length);Y.push(this.sourceToken);let G={type:"block-map",offset:$.offset,indent:$.indent,items:[{start:W,key:$,sep:Y}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=G}else yield*this.lineEnd($)}}flowScalar($){if(this.onNewLine){let J=this.source.indexOf(`
|
|
137
137
|
`)+1;while(J!==0)this.onNewLine(this.offset+J),J=this.source.indexOf(`
|
|
138
|
-
`,J)+1}return{type:$,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue($){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let J=
|
|
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=q9($),Q=$2(J);return Q.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let J=q9($),Q=$2(J);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Q,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment($,J){if(this.type!=="comment")return!1;if(this.indent<=J)return!1;return $.every((Q)=>Q.type==="newline"||Q.type==="space")}*documentEnd($){if(this.type!=="doc-mode"){if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd($){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if($.end)$.end.push(this.sourceToken);else $.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}qz.Parser=pJ});var aJ=C((Mz)=>{var dJ=J8(),Bz=v2(),m2=x2(),Uz=V4(),Vz=d(),zz=V8(),iJ=z8();function nJ($){let J=$.prettyErrors!==!1;return{lineCounter:$.lineCounter||J&&new zz.LineCounter||null,prettyErrors:J}}function Dz($,J={}){let{lineCounter:Q,prettyErrors:X}=nJ(J),W=new iJ.Parser(Q?.addNewLine),Y=new dJ.Composer(J),G=Array.from(Y.compose(W.parse($)));if(X&&Q)for(let q of G)q.errors.forEach(m2.prettifyError($,Q)),q.warnings.forEach(m2.prettifyError($,Q));if(G.length>0)return G;return Object.assign([],{empty:!0},Y.streamInfo())}function rJ($,J={}){let{lineCounter:Q,prettyErrors:X}=nJ(J),W=new iJ.Parser(Q?.addNewLine),Y=new dJ.Composer(J),G=null;for(let q of Y.compose(W.parse($),!0,$.length))if(!G)G=q;else if(G.options.logLevel!=="silent"){G.errors.push(new m2.YAMLParseError(q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&Q)G.errors.forEach(m2.prettifyError($,Q)),G.warnings.forEach(m2.prettifyError($,Q));return G}function Oz($,J,Q){let X=void 0;if(typeof J==="function")X=J;else if(Q===void 0&&J&&typeof J==="object")Q=J;let W=rJ($,Q);if(!W)return null;if(W.warnings.forEach((Y)=>Uz.warn(W.options.logLevel,Y)),W.errors.length>0)if(W.options.logLevel!=="silent")throw W.errors[0];else W.errors=[];return W.toJS(Object.assign({reviver:X},Q))}function Fz($,J,Q){let X=null;if(typeof J==="function"||Array.isArray(J))X=J;else if(Q===void 0&&J)Q=J;if(typeof Q==="string")Q=Q.length;if(typeof Q==="number"){let W=Math.round(Q);Q=W<1?void 0:W>8?{indent:8}:{indent:W}}if($===void 0){let{keepUndefined:W}=Q??J??{};if(!W)return}if(Vz.isDocument($)&&!X)return $.toString(Q);return new Bz.Document($,X,Q).toString(Q)}Mz.parse=Oz;Mz.parseAllDocuments=Dz;Mz.parseDocument=rJ;Mz.stringify=Fz});var oJ=C((Iz)=>{var Az=J8(),jz=v2(),Nz=k4(),D8=x2(),Zz=L2(),G$=d(),wz=J$(),bz=X0(),Pz=X$(),Sz=W$(),Ez=Y9(),Cz=U8(),fz=V8(),Tz=z8(),B9=aJ(),sJ=R2();Iz.Composer=Az.Composer;Iz.Document=jz.Document;Iz.Schema=Nz.Schema;Iz.YAMLError=D8.YAMLError;Iz.YAMLParseError=D8.YAMLParseError;Iz.YAMLWarning=D8.YAMLWarning;Iz.Alias=Zz.Alias;Iz.isAlias=G$.isAlias;Iz.isCollection=G$.isCollection;Iz.isDocument=G$.isDocument;Iz.isMap=G$.isMap;Iz.isNode=G$.isNode;Iz.isPair=G$.isPair;Iz.isScalar=G$.isScalar;Iz.isSeq=G$.isSeq;Iz.Pair=wz.Pair;Iz.Scalar=bz.Scalar;Iz.YAMLMap=Pz.YAMLMap;Iz.YAMLSeq=Sz.YAMLSeq;Iz.CST=Ez;Iz.Lexer=Cz.Lexer;Iz.LineCounter=fz.LineCounter;Iz.Parser=Tz.Parser;Iz.parse=B9.parse;Iz.parseAllDocuments=B9.parseAllDocuments;Iz.parseDocument=B9.parseDocument;Iz.stringify=B9.stringify;Iz.visit=sJ.visit;Iz.visitAsync=sJ.visitAsync});var d1=($)=>$.payload.title?.trim()||`session:${$.payload.id}`;function H6($){let{store:J,agent:Q}=$;return{async session(X){let W=X.payload.id,Y=await Q7(J,W);switch(X.type){case"session.created":{if(Y)return{task_id:Y.id};let G=d1(X);return{task_id:(await J.createTask({title:G,session_id:W,owner:Q,priority:3})).id}}case"session.idle":{if(!Y)return null;if(Y.status==="pending"){let G=await J.updateTask(Y.id,{status:"in_progress"});return G?{task_id:G.id}:null}return null}case"session.deleted":{if(!Y)return null;return await J.updateTask(Y.id,{status:"cancelled"}),{task_id:Y.id}}case"session.error":case"session.compacted":return await J.appendOperation({task_id:Y?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:W,agent:Q}}),null;default:return null}},async tool(X){let W=X.payload.sessionID,Y=await Q7(J,W);if(!Y)return await J.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:W,tool:X.payload.tool}}),{task_id:(await J.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:Q,priority:3})).id};let G=i1(X),H=(await J.listTasks({parent_id:Y.id,limit:20})).tasks.find((U)=>U.title===G&&Date.now()-new Date(U.created_at).getTime()<60000);if(H)return{task_id:H.id};let B=await J.createTask({title:G,parent_id:Y.id,session_id:W,owner:Q,priority:3});return await J.updateTask(B.id,{status:"in_progress"}),{task_id:B.id}},async catchAll(X){try{await J.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:Q}})}catch{}}}}async function Q7($,J){return(await $.listTasks({session_id:J,limit:1})).tasks[0]??null}function i1($){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 G2="\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536",B$="TASK_COMPLETION_HINT",q2="\u6838\u5B9E\u4E49\u52A1",B6="### Task Lifecycle (7 steps, 0-6)\n\n> Tasks are the **first-class citizen**. Follow this lifecycle for every task:\n\n0. CHECK TASK CONTEXT OR SEARCH\n - If `[\u5F53\u524D Task #N]` is in the context \u2192 use `task_get #N` directly, skip searching.\n - Otherwise use `task_list` / `task_search` to find related tasks.\n - If found \u2192 reuse, extend, and update (see the reuse rules in step 1).\n If not found \u2192 proceed to step 1.\n - **Orient before creating**: read the existing tree with\n `task_tree(depth=1)` (`depth=2` for bigger trees) and decide whether the\n work belongs to an existing root (attach via `parent_task_id`) or is\n genuinely new. Keep **root tasks \u2264 10**; prefer attaching to an existing\n thematic root over spawning a new root. Never hardcode ids \u2014 read them\n from `task_tree`.\n\n1. CREATE or REUSE\n - No existing task \u2192 create a new one with title, description, goals.\n - Existing task \u2192 reuse via `task_get`, then `task_update`:\n * Append new context to description and goals (preserve the old content)\n * Add / extend `goals_and_expected_deliverables`\n * Create an operation record documenting the continuation\n * Set priority and due date if any\n * If the original task was completed \u2192 reset status to `active`\n and reset progress to a reasonable value\n\n2. GATHER CONTEXT (never skip)\n - Read description, goals, current_status\n - Check `parent_task_id` for sub-tasks\n - Read the operation history: `task_operation_list` (~20 recent records)\n - Review recent operations for history and decisions\n - Working without context risks: outdated goals, missed decisions,\n duplicated work, misalignment with the parent task\n\n3. EXECUTE\n - Use the available tools, skills and workflows to satisfy the task\n description and goals.\n - Long-running work: for work longer than 5 minutes, record a milestone\n with `task_operation_create` as you go, so the user can see progress.\n - Several independent sub-tasks may run in parallel (background `bash &`\n or parallel ReAct steps).\n - **\u8FB9\u5E72\u8FB9\u8BB0** \u2014 milestones are recorded **while working**;\n **\u7981\u6B62\u4E8B\u540E\u6279\u91CF\u8865**\uFF08do not defer them to one batch at the end\uFF09.\n - Note: `task_create` / `task_update` already create operation records\n automatically \u2014 do not create duplicates by hand.\n\n4. TRACK\n - Update progress (0-100%) as the work advances\n - Update status: todo \u2192 active \u2192 completed\n - Record `current_status` with human-readable progress\n\n5. RECORD \u2014 operation records (see Operation Discipline below)\n\n6. COMPLETE \u2014 `task_complete` after item-by-item verification\n (see Complete Discipline below)",U6=`### Operation Record \u2014 \u53CC\u7EF4\u5EA6\u5206\u5DE5\u89C4\u8303
|
|
139
|
+
|
|
140
|
+
**Record milestones as you work** \u2014 call \`task_operation_create\` the moment a
|
|
141
|
+
stage is reached, **not after the fact** (not in a batch at the end).
|
|
142
|
+
|
|
143
|
+
**\u64CD\u4F5C\u8BB0\u5F55\u5FC5\u987B\u4E25\u683C\u533A\u5206\u4E24\u4E2A\u7EF4\u5EA6\uFF0C\u4E8C\u8005\u914D\u5957\u8BB0\u5F55\u3001\u5404\u53F8\u5176\u804C**\uFF1A
|
|
144
|
+
|
|
145
|
+
#### \u7EF4\u5EA6 1\uFF1A\u72B6\u6001/\u91CC\u7A0B\u7891\uFF08"\u8FBE\u5230\u4EC0\u4E48"\uFF09\u2014 \u5FC5\u586B\u7EF4\u5EA6
|
|
146
|
+
\u4F7F\u7528 \`task_operation_create\` \u7684 milestone_* \u4E3B\u5B57\u6BB5\uFF1A
|
|
147
|
+
- **milestone_type**\uFF1A\u91CC\u7A0B\u7891\u7C7B\u578B\uFF08create / progress / milestone / problem / solution / decision / review / completed / workflow_extracted\uFF09
|
|
148
|
+
- **milestone_title**\uFF1A\u91CC\u7A0B\u7891\u6807\u9898\uFF08\u4E00\u884C\uFF09
|
|
149
|
+
- **milestone_description**\uFF1A\u8FBE\u6210\u7684\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\uFF08\u53EF\u957F\u53EF\u77ED\uFF09
|
|
150
|
+
|
|
151
|
+
#### \u7EF4\u5EA6 2\uFF1A\u8FC7\u7A0B\uFF08"\u5982\u4F55\u8FBE\u5230"\uFF09\u2014 \u53EF\u9009\u4F46\u63A8\u8350\u7EF4\u5EA6
|
|
152
|
+
\u4F7F\u7528 \`task_operation_create\` \u7684 \`process_description\` \u5B57\u6BB5\uFF1A
|
|
153
|
+
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-500 \u5B57\u7B26 (100\u2013500 characters)
|
|
154
|
+
- \u5185\u5BB9\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981
|
|
155
|
+
- \u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session
|
|
156
|
+
|
|
157
|
+
#### \u53CC\u7EF4\u5EA6\u914D\u5408\u94C1\u5F8B
|
|
158
|
+
- \u274C **\u4E0D\u8981\u628A action \u5F53\u72B6\u6001**\uFF1A\u65E7 \`action_*\` \u547D\u540D\u504F\u52A8\u4F5C/\u884C\u4E3A\u5C42\uFF0C\u4E0D\u80FD\u8868\u8FBE"\u6B64\u523B\u8FBE\u5230\u4EC0\u4E48"\uFF1B\u73B0\u5728\u7EDF\u4E00\u6539\u7528 \`milestone_*\`\u3002
|
|
159
|
+
- \u274C **\u4E0D\u8981\u8BA9 process_description \u4E0E milestone_description \u91CD\u590D**\uFF1Aprocess \u662F"\u5982\u4F55\u8FBE\u5230"\uFF0Cmilestone \u662F"\u8FBE\u5230\u4EC0\u4E48\u72B6\u6001"\u3002
|
|
160
|
+
- \u2705 **\u914D\u5957\u8BB0\u5F55**\uFF1A\u6BCF\u4E2A\u6709\u610F\u4E49\u7684 operation \u90FD\u5E94\u540C\u65F6\u5305\u542B\u4E24\u8005\uFF1B\u4E0D\u5199 process \u65F6\uFF0Cdetail \u5E94\u901A\u8FC7 sessionId \u56DE\u67E5\u3002
|
|
161
|
+
- \u26A0\uFE0F **\u517C\u5BB9\u7A97\u53E3\u671F**\uFF1A\u65E7 \`action_type\` / \`action_title\` / \`action_description\` \u4ECD\u88AB tool \u63A5\u53D7\uFF08\u6807\u8BB0 @deprecated\uFF09\uFF0C\u4F1A\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5E76\u8FD4\u56DE deprecation warning\u3002
|
|
162
|
+
|
|
163
|
+
#### \u8303\u4F8B\uFF08\u53CC\u7EF4\u5EA6\u9F50\u5168\u7684 operation \u8BB0\u5F55\uFF09
|
|
164
|
+
\`\`\`json
|
|
165
|
+
{
|
|
166
|
+
"task_id": 123,
|
|
167
|
+
"milestone_type": "milestone",
|
|
168
|
+
"milestone_title": "GREEN \u901A\u8FC7\uFF1Amilestone_* schema/storage/tool \u5168\u94FE\u8DEF",
|
|
169
|
+
"milestone_description": "21/21 \u6D4B\u8BD5\u901A\u8FC7\uFF0C\u5305\u542B 4 \u4E2A action_* alias \u517C\u5BB9\u6D4B\u8BD5",
|
|
170
|
+
"process_description": "TDD RED \u5199 4 \u4E2A\u5931\u8D25\u6D4B\u8BD5\u8986\u76D6 storage/tool\uFF1B\u8FC1\u79FB 004 rename \u5217\uFF1BrowToOperation \u540C\u65F6\u8F93\u51FA\u53CC\u5B57\u6BB5\u517C\u5BB9\uFF1Btool zod preprocess \u81EA\u52A8\u6620\u5C04 action_*"
|
|
171
|
+
}
|
|
172
|
+
\`\`\``,P$=`### Goals \u5B50\u9879\u62C6\u5206\u89C4\u5219
|
|
173
|
+
|
|
174
|
+
\`goals_and_expected_deliverables\` **MUST** be written as
|
|
175
|
+
**numbered sub-items** (\u7F16\u53F7\u5B50\u9879) that can each be verified
|
|
176
|
+
one by one (\u9010\u6761\u9A8C\u6536) \u2014 for \`type=normal\` tasks:
|
|
177
|
+
|
|
178
|
+
1. \u5B9E\u73B0 X\uFF08\u542B\u6587\u4EF6\u8DEF\u5F84\uFF09
|
|
179
|
+
2. \u6D4B\u8BD5 Y \u8986\u76D6 Z \u573A\u666F\uFF08pass/fail \u8BA1\u6570\uFF09
|
|
180
|
+
3. \u6587\u6863 W \u843D\u76D8\u5230 <path>
|
|
181
|
+
|
|
182
|
+
\u26A0\uFE0F For \`type=longterm\` / \`type=cycle\` tasks there is no
|
|
183
|
+
per-item completion acceptance\uFF08\u4E0D\u8D70\u9010\u6761 complete \u9A8C\u6536\uFF09, so the
|
|
184
|
+
MUST above does not apply; for those, it is **strongly recommended**
|
|
185
|
+
(\u5EFA\u8BAE) to split goals into staged, individually checkable sub-items
|
|
186
|
+
(\u9636\u6BB5\u6027\u53EF\u5224\u5B50\u9879) instead of one vague sentence.
|
|
187
|
+
|
|
188
|
+
Why: when the task is completed, the completion hook
|
|
189
|
+
(task:after.complete) judges the whole goal against the
|
|
190
|
+
operation-record chain, using each sub-item as fine-grained
|
|
191
|
+
evidence (\u9010\u6761\u5BF9\u7167\u7684\u4F9D\u636E). Vague one-line goals (\u4E00\u53E5\u8BDD\u6A21\u7CCA\u76EE\u6807\uFF0C
|
|
192
|
+
\u5982\u300C\u505A\u597D X\u300D\u300C\u5B8C\u6210\u8C03\u7814\u300D) give the judge nothing to check
|
|
193
|
+
and make a completion hint much more likely.
|
|
194
|
+
|
|
195
|
+
Reference the four atomic assertion forms (Task #4768
|
|
196
|
+
\u56DB\u539F\u5B50\u5F62\u6001) when writing each sub-item:
|
|
197
|
+
|
|
198
|
+
- \u6587\u4EF6\u65AD\u8A00 (file assertion): file exists / size / content grep
|
|
199
|
+
- \u8FDB\u7A0B\u65AD\u8A00 (process assertion): command exit code / stdout match
|
|
200
|
+
- \u6D4B\u8BD5\u65AD\u8A00 (test assertion): pass/fail counts, no NEW fail
|
|
201
|
+
- \u72B6\u6001\u65AD\u8A00 (state assertion): version number / HTTP 200 / status field`,V6=`### Task Complete \u2014 \u6838\u5B9E\u4E49\u52A1
|
|
202
|
+
|
|
203
|
+
Before calling \`task_complete\`, you MUST:
|
|
204
|
+
|
|
205
|
+
1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
|
|
206
|
+
- Use \`task_get(task_id=<id>)\` to fetch the full task record.
|
|
207
|
+
2. **Validate whether each goal sub-item was achieved** \u2014 accept the goal
|
|
208
|
+
**item-by-item** (${G2}).
|
|
209
|
+
- Goals should be numbered sub-items (\u7F16\u53F7\u5B50\u9879). Check
|
|
210
|
+
each sub-item against the operation-record chain (\u64CD\u4F5C\u8BB0\u5F55\u94FE) and the
|
|
211
|
+
deliverable evidence (context.deliverable_storage_path).
|
|
212
|
+
- The completion hook (task:after.complete) judges the whole goal vs.
|
|
213
|
+
deliverables; numbered sub-items give it finer-grained evidence to
|
|
214
|
+
reason with (\u9010\u6761\u5BF9\u7167\u7684\u8BC1\u636E\u7C92\u5EA6). If it detects that the goal or
|
|
215
|
+
deliverables appear unmet, the task context will carry a
|
|
216
|
+
\`[${B$}]\`.
|
|
217
|
+
- **If you receive a [${B$}]**, you MUST verify it
|
|
218
|
+
(${q2}): re-read the task via \`task_get\`, then do exactly one of:
|
|
219
|
+
(a) \u786E\u8BA4\u672A\u5B8C\u6210 \u2192 \`task_update(task_id=<id>, status=todo)\` to **reopen**
|
|
220
|
+
the task and continue the work; or
|
|
221
|
+
(b) \u786E\u8BA4\u5DF2\u5B8C\u6210 \u2192 \`task_operation_create\` (milestone_type=decision,
|
|
222
|
+
milestone_title=<\u4E00\u884C\u7ED3\u8BBA>) **state why** the sub-items are actually
|
|
223
|
+
met (\u8BF4\u660E\u7406\u7531).
|
|
224
|
+
Never ignore it (\u4E0D\u5141\u8BB8\u65E0\u89C6).
|
|
225
|
+
- If the goal and delivery mismatch **without** a hint, either:
|
|
226
|
+
(a) extend the task via \`task_update\`, or
|
|
227
|
+
(b) record the discrepancy via \`task_operation_create\`
|
|
228
|
+
(milestone_type=decision) \u2014 the reason **must** land in the
|
|
229
|
+
operation record (\u5FC5\u987B\u843D\u5230\u64CD\u4F5C\u8BB0\u5F55\u91CC), not merely a line in
|
|
230
|
+
your final report (\u4E0D\u80FD\u53EA\u5728\u62A5\u544A\u91CC\u5E26\u4E00\u53E5).
|
|
231
|
+
3. **Provide \`deliverable_storage_path\`** parameter with the deliverable's address.
|
|
232
|
+
It may name **multiple paths** (multiple deliverables), space-separated
|
|
233
|
+
(\`/tmp/report.md /tmp/diff.patch\`) \u2014 the judge splits on whitespace as
|
|
234
|
+
well as \`,\` \`;\` \`\u3001\` and \` + \`. A local path may also be written in its
|
|
235
|
+
\`file://\` form (\`file:///tmp/report.md\`) \u2014 the scheme is stripped and the
|
|
236
|
+
path kept. Declare **every** artefact you produced: a path left out reads
|
|
237
|
+
as "not produced".
|
|
238
|
+
- Feishu doc URL (e.g., https://my.feishu.cn/docx/abc)
|
|
239
|
+
- Local file path (e.g., /tmp/report.md)
|
|
240
|
+
- Git branch or worktree path (e.g., feature/my-feature)
|
|
241
|
+
- GitHub commit URL or PR URL
|
|
242
|
+
- Cloud drive URL (e.g., https://my.feishu.cn/file/abc)
|
|
243
|
+
- Or any other locator that points to where the work product lives
|
|
244
|
+
|
|
245
|
+
The \`deliverable_storage_path\` will be persisted to the task's
|
|
246
|
+
\`context.deliverable_storage_path\` for future reference and traceability.`,E9=[B6,U6,P$,V6].join(`
|
|
247
|
+
|
|
248
|
+
`);import{createRequire as n1}from"module";var{defineProperty:C9,getOwnPropertyNames:r1,getOwnPropertyDescriptor:a1}=Object,s1=Object.prototype.hasOwnProperty;function o1($){return this[$]}var S$=($)=>{var J=(X7??=new WeakMap).get($),Q;if(J)return J;if(J=C9({},"__esModule",{value:!0}),$&&typeof $==="object"||typeof $==="function"){for(var X of r1($))if(!s1.call(J,X))C9(J,X,{get:o1.bind($,X),enumerable:!(Q=a1($,X))||Q.enumerable})}return X7.set($,J),J},X7,t1=($)=>$;function e1($,J){this[$]=t1.bind(null,J)}var i0=($,J)=>{for(var Q in J)C9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:e1.bind(J,Q)})},m=function($,J,Q,X){var W=arguments.length,Y=W<3?J:X===null?X=Object.getOwnPropertyDescriptor(J,Q):X,G;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")Y=Reflect.decorate($,J,Q,X);else for(var q=$.length-1;q>=0;q--)if(G=$[q])Y=(W<3?G(Y):W>3?G(J,Q,Y):G(J,Q))||Y;return W>3&&Y&&Object.defineProperty(J,Q,Y),Y},r=($,J)=>()=>($&&(J=$($=0)),J),t=n1(import.meta.url);var f9=`# Roy \u2014 task-first-class-citizen agent
|
|
139
249
|
|
|
140
250
|
You are **Roy**, an agent whose defining rule is simple:
|
|
141
251
|
|
|
142
252
|
> **Task is a first-class citizen. No task, no work.**
|
|
143
253
|
|
|
144
|
-
You are
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
## The lifecycle (non-negotiable)
|
|
151
|
-
|
|
152
|
-
### 1. Orient \u2014 \`task_tree(depth=1)\` (or \`depth=2\` for bigger trees)
|
|
153
|
-
Before creating anything, look at the existing tree. Decide:
|
|
154
|
-
- does this work belong to an existing root (attach via \`parent_task_id\`)?
|
|
155
|
-
- or is it genuinely new?
|
|
156
|
-
|
|
157
|
-
Keep **root tasks \u2264 10**. Prefer attaching to an existing thematic root over
|
|
158
|
-
spawning a new root. Never hardcode ids \u2014 read them from \`task_tree\`.
|
|
159
|
-
|
|
160
|
-
### 2. Create \u2014 \`task_create\`
|
|
161
|
-
Create the task **before** doing the work. Pass:
|
|
162
|
-
- \`title\` (imperative, specific), \`description\`, \`goals_and_expected_deliverables\`
|
|
163
|
-
- \`priority\` (low / medium / high), \`type\` (normal / cycle / longterm)
|
|
164
|
-
- \`project_path\`, \`context\` (JSON string: worktree_path / branch / type \u2026)
|
|
165
|
-
- \`parent_task_id\` when the tree said so
|
|
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.
|
|
254
|
+
You are a worker agent: you act through the tools, and your output is what
|
|
255
|
+
the user sees.
|
|
256
|
+
|
|
257
|
+
${B6}
|
|
258
|
+
|
|
259
|
+
${P$}
|
|
190
260
|
|
|
191
261
|
The tool returns a **numeric task id** \u2014 that number is your handle for the
|
|
192
262
|
rest of the conversation.
|
|
193
263
|
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
- \`progress\`: 0\u2013100
|
|
198
|
-
- \`current_status\`: one human sentence about where you are right now
|
|
199
|
-
|
|
200
|
-
If the scope changes, \`task_update\` the description/goals instead of silently
|
|
201
|
-
doing something else.
|
|
202
|
-
|
|
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
|
-
|
|
210
|
-
This tool has **two orthogonal dimensions** and you must keep them distinct:
|
|
211
|
-
- **state / milestone dimension** \u2014 \`milestone_type\` + \`milestone_title\` +
|
|
212
|
-
\`milestone_description\`: *what* was reached (e.g. "GREEN: all tests pass").
|
|
213
|
-
- **process dimension** \u2014 \`process_description\`: *how* you got there \u2014
|
|
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).
|
|
217
|
-
|
|
218
|
-
Rules: do **not** use the process field to restate the milestone, and do not
|
|
219
|
-
use milestones as a substitute for progress. Milestones mark *state
|
|
220
|
-
transitions*: RED\u2192GREEN, blocker found, decision made, review passed.
|
|
221
|
-
|
|
222
|
-
### 5. Close \u2014 \`task_complete\`
|
|
223
|
-
Before completing:
|
|
224
|
-
1. \`task_get(task_id)\` and re-read goal + delivery.
|
|
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.
|
|
229
|
-
3. Call \`task_complete\` with \`deliverable_storage_path\` \u2014 a locator for the
|
|
230
|
-
work product: a file path, a git branch/worktree, a doc URL, a commit URL.
|
|
231
|
-
The path is persisted into the task context and as an operation record.
|
|
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").
|
|
264
|
+
${U6}
|
|
265
|
+
|
|
266
|
+
${V6}
|
|
242
267
|
|
|
243
268
|
#### Several deliverables in one field
|
|
244
269
|
\`deliverable_storage_path\` may name **multiple paths**, space-separated
|
|
@@ -273,7 +298,7 @@ if it is not in the task store, it is not tracked.
|
|
|
273
298
|
- Be direct and concrete; the user is reading task titles and milestones.
|
|
274
299
|
- Report the task id and its state whenever you finish a step.
|
|
275
300
|
- If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
|
|
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.
|
|
301
|
+
\`problem\` milestone explaining the blocker instead of going silent.`;var T9="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.",I9=f9;var H2="roy",W7={action:"execute",resource:"*",effect:"deny"};function Y7(){return{id:H2,mode:"primary",description:T9,system:I9,permissions:[{...W7}]}}function $Q($,J){if(!Array.isArray($.permissions))$.permissions=[];for(let Q of J)if(!$.permissions.some((W)=>W.action===Q.action&&W.resource===Q.resource&&W.effect===Q.effect))$.permissions.push({...Q})}function v9($){let J=Y7();return $.update(H2,(Q)=>{if(Q.mode=J.mode,Q.description=J.description,Q.system=J.system,Q.hidden===void 0)Q.hidden=!1;$Q(Q,J.permissions)}),J}var K={};p1(K,{void:()=>gQ,util:()=>l,unknown:()=>hQ,union:()=>lQ,undefined:()=>IQ,tuple:()=>dQ,transformer:()=>JX,symbol:()=>TQ,string:()=>O7,strictObject:()=>uQ,setErrorMap:()=>XQ,set:()=>rQ,record:()=>iQ,quotelessJson:()=>JQ,promise:()=>$X,preprocess:()=>WX,pipeline:()=>YX,ostring:()=>GX,optional:()=>QX,onumber:()=>qX,oboolean:()=>HX,objectUtil:()=>x9,object:()=>mQ,number:()=>F7,nullable:()=>XX,null:()=>vQ,never:()=>yQ,nativeEnum:()=>eQ,nan:()=>EQ,map:()=>nQ,makeIssue:()=>B2,literal:()=>oQ,lazy:()=>sQ,late:()=>PQ,isValid:()=>n0,isDirty:()=>D6,isAsync:()=>C$,isAborted:()=>z6,intersection:()=>pQ,instanceof:()=>SQ,getParsedType:()=>T0,getErrorMap:()=>E$,function:()=>aQ,enum:()=>tQ,effect:()=>JX,discriminatedUnion:()=>cQ,defaultErrorMap:()=>k0,datetimeRegex:()=>V7,date:()=>fQ,custom:()=>D7,coerce:()=>BX,boolean:()=>M7,bigint:()=>CQ,array:()=>kQ,any:()=>xQ,addIssueToContext:()=>S,ZodVoid:()=>V2,ZodUnknown:()=>r0,ZodUnion:()=>h$,ZodUndefined:()=>v$,ZodType:()=>k,ZodTuple:()=>v0,ZodTransformer:()=>w0,ZodSymbol:()=>U2,ZodString:()=>A0,ZodSet:()=>D$,ZodSchema:()=>k,ZodRecord:()=>z2,ZodReadonly:()=>c$,ZodPromise:()=>O$,ZodPipeline:()=>F2,ZodParsedType:()=>b,ZodOptional:()=>N0,ZodObject:()=>e,ZodNumber:()=>a0,ZodNullable:()=>u0,ZodNull:()=>x$,ZodNever:()=>I0,ZodNativeEnum:()=>m$,ZodNaN:()=>O2,ZodMap:()=>D2,ZodLiteral:()=>k$,ZodLazy:()=>g$,ZodIssueCode:()=>L,ZodIntersection:()=>y$,ZodFunction:()=>T$,ZodFirstPartyTypeKind:()=>j,ZodError:()=>G0,ZodEnum:()=>o0,ZodEffects:()=>w0,ZodDiscriminatedUnion:()=>O6,ZodDefault:()=>u$,ZodDate:()=>V$,ZodCatch:()=>l$,ZodBranded:()=>F6,ZodBoolean:()=>I$,ZodBigInt:()=>s0,ZodArray:()=>j0,ZodAny:()=>z$,Schema:()=>k,ParseStatus:()=>q0,OK:()=>B0,NEVER:()=>UX,INVALID:()=>I,EMPTY_PATH:()=>WQ,DIRTY:()=>U$,BRAND:()=>bQ});var l;(function($){$.assertEqual=(W)=>{};function J(W){}$.assertIs=J;function Q(W){throw Error()}$.assertNever=Q,$.arrayToEnum=(W)=>{let Y={};for(let G of W)Y[G]=G;return Y},$.getValidEnumValues=(W)=>{let Y=$.objectKeys(W).filter((q)=>typeof W[W[q]]!=="number"),G={};for(let q of Y)G[q]=W[q];return $.objectValues(G)},$.objectValues=(W)=>{return $.objectKeys(W).map(function(Y){return W[Y]})},$.objectKeys=typeof Object.keys==="function"?(W)=>Object.keys(W):(W)=>{let Y=[];for(let G in W)if(Object.prototype.hasOwnProperty.call(W,G))Y.push(G);return Y},$.find=(W,Y)=>{for(let G of W)if(Y(G))return G;return},$.isInteger=typeof Number.isInteger==="function"?(W)=>Number.isInteger(W):(W)=>typeof W==="number"&&Number.isFinite(W)&&Math.floor(W)===W;function X(W,Y=" | "){return W.map((G)=>typeof G==="string"?`'${G}'`:G).join(Y)}$.joinValues=X,$.jsonStringifyReplacer=(W,Y)=>{if(typeof Y==="bigint")return Y.toString();return Y}})(l||(l={}));var x9;(function($){$.mergeShapes=(J,Q)=>{return{...J,...Q}}})(x9||(x9={}));var b=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),T0=($)=>{switch(typeof $){case"undefined":return b.undefined;case"string":return b.string;case"number":return Number.isNaN($)?b.nan:b.number;case"boolean":return b.boolean;case"function":return b.function;case"bigint":return b.bigint;case"symbol":return b.symbol;case"object":if(Array.isArray($))return b.array;if($===null)return b.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return b.promise;if(typeof Map<"u"&&$ instanceof Map)return b.map;if(typeof Set<"u"&&$ instanceof Set)return b.set;if(typeof Date<"u"&&$ instanceof Date)return b.date;return b.object;default:return b.unknown}};var L=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),JQ=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class G0 extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(Q)=>{this.issues=[...this.issues,Q]},this.addIssues=(Q=[])=>{this.issues=[...this.issues,...Q]};let J=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,J);else this.__proto__=J;this.name="ZodError",this.issues=$}format($){let J=$||function(W){return W.message},Q={_errors:[]},X=(W)=>{for(let Y of W.issues)if(Y.code==="invalid_union")Y.unionErrors.map(X);else if(Y.code==="invalid_return_type")X(Y.returnTypeError);else if(Y.code==="invalid_arguments")X(Y.argumentsError);else if(Y.path.length===0)Q._errors.push(J(Y));else{let G=Q,q=0;while(q<Y.path.length){let H=Y.path[q];if(q!==Y.path.length-1)G[H]=G[H]||{_errors:[]};else G[H]=G[H]||{_errors:[]},G[H]._errors.push(J(Y));G=G[H],q++}}};return X(this),Q}static assert($){if(!($ instanceof G0))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(J)=>J.message){let J={},Q=[];for(let X of this.issues)if(X.path.length>0){let W=X.path[0];J[W]=J[W]||[],J[W].push($(X))}else Q.push($(X));return{formErrors:Q,fieldErrors:J}}get formErrors(){return this.flatten()}}G0.create=($)=>{return new G0($)};var QQ=($,J)=>{let Q;switch($.code){case L.invalid_type:if($.received===b.undefined)Q="Required";else Q=`Expected ${$.expected}, received ${$.received}`;break;case L.invalid_literal:Q=`Invalid literal value, expected ${JSON.stringify($.expected,l.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:Q=`Unrecognized key(s) in object: ${l.joinValues($.keys,", ")}`;break;case L.invalid_union:Q="Invalid input";break;case L.invalid_union_discriminator:Q=`Invalid discriminator value. Expected ${l.joinValues($.options)}`;break;case L.invalid_enum_value:Q=`Invalid enum value. Expected ${l.joinValues($.options)}, received '${$.received}'`;break;case L.invalid_arguments:Q="Invalid function arguments";break;case L.invalid_return_type:Q="Invalid function return type";break;case L.invalid_date:Q="Invalid date";break;case L.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 L.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 L.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 L.custom:Q="Invalid input";break;case L.invalid_intersection_types:Q="Intersection results could not be merged";break;case L.not_multiple_of:Q=`Number must be a multiple of ${$.multipleOf}`;break;case L.not_finite:Q="Number must be finite";break;default:Q=J.defaultError,l.assertNever($)}return{message:Q}},k0=QQ;var G7=k0;function XQ($){G7=$}function E$(){return G7}var B2=($)=>{let{data:J,path:Q,errorMaps:X,issueData:W}=$,Y=[...Q,...W.path||[]],G={...W,path:Y};if(W.message!==void 0)return{...W,path:Y,message:W.message};let q="",H=X.filter((B)=>!!B).slice().reverse();for(let B of H)q=B(G,{data:J,defaultError:q}).message;return{...W,path:Y,message:q}},WQ=[];function S($,J){let Q=E$(),X=B2({issueData:J,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,Q,Q===k0?void 0:k0].filter((W)=>!!W)});$.common.issues.push(X)}class q0{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,J){let Q=[];for(let X of J){if(X.status==="aborted")return I;if(X.status==="dirty")$.dirty();Q.push(X.value)}return{status:$.value,value:Q}}static async mergeObjectAsync($,J){let Q=[];for(let X of J){let W=await X.key,Y=await X.value;Q.push({key:W,value:Y})}return q0.mergeObjectSync($,Q)}static mergeObjectSync($,J){let Q={};for(let X of J){let{key:W,value:Y}=X;if(W.status==="aborted")return I;if(Y.status==="aborted")return I;if(W.status==="dirty")$.dirty();if(Y.status==="dirty")$.dirty();if(W.value!=="__proto__"&&(typeof Y.value<"u"||X.alwaysSet))Q[W.value]=Y.value}return{status:$.value,value:Q}}}var I=Object.freeze({status:"aborted"}),U$=($)=>({status:"dirty",value:$}),B0=($)=>({status:"valid",value:$}),z6=($)=>$.status==="aborted",D6=($)=>$.status==="dirty",n0=($)=>$.status==="valid",C$=($)=>typeof Promise<"u"&&$ instanceof Promise;var T;(function($){$.errToObj=(J)=>typeof J==="string"?{message:J}:J||{},$.toString=(J)=>typeof J==="string"?J:J?.message})(T||(T={}));class 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 q7=($,J)=>{if(n0(J))return{success:!0,data:J.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let Q=new G0($.common.issues);return this._error=Q,this._error}}}};function h($){if(!$)return{};let{errorMap:J,invalid_type_error:Q,required_error:X,description:W}=$;if(J&&(Q||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(J)return{errorMap:J,description:W};return{errorMap:(G,q)=>{let{message:H}=$;if(G.code==="invalid_enum_value")return{message:H??q.defaultError};if(typeof q.data>"u")return{message:H??X??q.defaultError};if(G.code!=="invalid_type")return{message:q.defaultError};return{message:H??Q??q.defaultError}},description:W}}class k{get description(){return this._def.description}_getType($){return T0($.data)}_getOrReturnCtx($,J){return J||{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new q0,ctx:{common:$.parent.common,data:$.data,parsedType:T0($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let J=this._parse($);if(C$(J))throw Error("Synchronous parse encountered promise.");return J}_parseAsync($){let J=this._parse($);return Promise.resolve(J)}parse($,J){let Q=this.safeParse($,J);if(Q.success)return Q.data;throw Q.error}safeParse($,J){let Q={common:{issues:[],async:J?.async??!1,contextualErrorMap:J?.errorMap},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T0($)},X=this._parseSync({data:$,path:Q.path,parent:Q});return q7(Q,X)}"~validate"($){let J={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T0($)};if(!this["~standard"].async)try{let Q=this._parseSync({data:$,path:[],parent:J});return n0(Q)?{value:Q.value}:{issues:J.common.issues}}catch(Q){if(Q?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;J.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:J}).then((Q)=>n0(Q)?{value:Q.value}:{issues:J.common.issues})}async parseAsync($,J){let Q=await this.safeParseAsync($,J);if(Q.success)return Q.data;throw Q.error}async safeParseAsync($,J){let Q={common:{issues:[],contextualErrorMap:J?.errorMap,async:!0},path:J?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:T0($)},X=this._parse({data:$,path:Q.path,parent:Q}),W=await(C$(X)?X:Promise.resolve(X));return q7(Q,W)}refine($,J){let Q=(X)=>{if(typeof J==="string"||typeof J>"u")return{message:J};else if(typeof J==="function")return J(X);else return J};return this._refinement((X,W)=>{let Y=$(X),G=()=>W.addIssue({code:L.custom,...Q(X)});if(typeof Promise<"u"&&Y instanceof Promise)return Y.then((q)=>{if(!q)return G(),!1;else return!0});if(!Y)return G(),!1;else return!0})}refinement($,J){return this._refinement((Q,X)=>{if(!$(Q))return X.addIssue(typeof J==="function"?J(Q,X):J),!1;else return!0})}_refinement($){return new w0({schema:this,typeName:j.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(J)=>this["~validate"](J)}}optional(){return N0.create(this,this._def)}nullable(){return u0.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return j0.create(this)}promise(){return O$.create(this,this._def)}or($){return h$.create([this,$],this._def)}and($){return y$.create(this,$,this._def)}transform($){return new w0({...h(this._def),schema:this,typeName:j.ZodEffects,effect:{type:"transform",transform:$}})}default($){let J=typeof $==="function"?$:()=>$;return new u$({...h(this._def),innerType:this,defaultValue:J,typeName:j.ZodDefault})}brand(){return new F6({typeName:j.ZodBranded,type:this,...h(this._def)})}catch($){let J=typeof $==="function"?$:()=>$;return new l$({...h(this._def),innerType:this,catchValue:J,typeName:j.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return F2.create(this,$)}readonly(){return c$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var YQ=/^c[^\s-]{8,}$/i,GQ=/^[0-9a-z]+$/,qQ=/^[0-9A-HJKMNP-TV-Z]{26}$/i,HQ=/^[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,BQ=/^[a-z0-9_-]{21}$/i,UQ=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,VQ=/^[-+]?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)?)??$/,zQ=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,DQ="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",h9,OQ=/^(?:(?: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])$/,FQ=/^(?:(?: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])$/,MQ=/^(([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]))$/,KQ=/^(([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])$/,RQ=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,_Q=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,B7="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",LQ=new RegExp(`^${B7}$`);function U7($){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 AQ($){return new RegExp(`^${U7($)}$`)}function V7($){let J=`${B7}T${U7($)}`,Q=[];if(Q.push($.local?"Z?":"Z"),$.offset)Q.push("([+-]\\d{2}:?\\d{2})");return J=`${J}(${Q.join("|")})`,new RegExp(`^${J}$`)}function jQ($,J){if((J==="v4"||!J)&&OQ.test($))return!0;if((J==="v6"||!J)&&MQ.test($))return!0;return!1}function NQ($,J){if(!UQ.test($))return!1;try{let[Q]=$.split(".");if(!Q)return!1;let X=Q.replace(/-/g,"+").replace(/_/g,"/").padEnd(Q.length+(4-Q.length%4)%4,"="),W=JSON.parse(atob(X));if(typeof W!=="object"||W===null)return!1;if("typ"in W&&W?.typ!=="JWT")return!1;if(!W.alg)return!1;if(J&&W.alg!==J)return!1;return!0}catch{return!1}}function ZQ($,J){if((J==="v4"||!J)&&FQ.test($))return!0;if((J==="v6"||!J)&&KQ.test($))return!0;return!1}class A0 extends k{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==b.string){let W=this._getOrReturnCtx($);return S(W,{code:L.invalid_type,expected:b.string,received:W.parsedType}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.length<W.value)X=this._getOrReturnCtx($,X),S(X,{code:L.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="max"){if($.data.length>W.value)X=this._getOrReturnCtx($,X),S(X,{code:L.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!1,message:W.message}),Q.dirty()}else if(W.kind==="length"){let Y=$.data.length>W.value,G=$.data.length<W.value;if(Y||G){if(X=this._getOrReturnCtx($,X),Y)S(X,{code:L.too_big,maximum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});else if(G)S(X,{code:L.too_small,minimum:W.value,type:"string",inclusive:!0,exact:!0,message:W.message});Q.dirty()}}else if(W.kind==="email"){if(!zQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"email",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="emoji"){if(!h9)h9=new RegExp(DQ,"u");if(!h9.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"emoji",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="uuid"){if(!HQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"uuid",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="nanoid"){if(!BQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"nanoid",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid"){if(!YQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cuid2"){if(!GQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"cuid2",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ulid"){if(!qQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"ulid",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="url")try{new URL($.data)}catch{X=this._getOrReturnCtx($,X),S(X,{validation:"url",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="regex"){if(W.regex.lastIndex=0,!W.regex.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"regex",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="trim")$.data=$.data.trim();else if(W.kind==="includes"){if(!$.data.includes(W.value,W.position))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:{includes:W.value,position:W.position},message:W.message}),Q.dirty()}else if(W.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(W.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(W.kind==="startsWith"){if(!$.data.startsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:{startsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="endsWith"){if(!$.data.endsWith(W.value))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:{endsWith:W.value},message:W.message}),Q.dirty()}else if(W.kind==="datetime"){if(!V7(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:"datetime",message:W.message}),Q.dirty()}else if(W.kind==="date"){if(!LQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:"date",message:W.message}),Q.dirty()}else if(W.kind==="time"){if(!AQ(W).test($.data))X=this._getOrReturnCtx($,X),S(X,{code:L.invalid_string,validation:"time",message:W.message}),Q.dirty()}else if(W.kind==="duration"){if(!VQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"duration",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="ip"){if(!jQ($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"ip",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="jwt"){if(!NQ($.data,W.alg))X=this._getOrReturnCtx($,X),S(X,{validation:"jwt",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="cidr"){if(!ZQ($.data,W.version))X=this._getOrReturnCtx($,X),S(X,{validation:"cidr",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64"){if(!RQ.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64",code:L.invalid_string,message:W.message}),Q.dirty()}else if(W.kind==="base64url"){if(!_Q.test($.data))X=this._getOrReturnCtx($,X),S(X,{validation:"base64url",code:L.invalid_string,message:W.message}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:$.data}}_regex($,J,Q){return this.refinement((X)=>$.test(X),{validation:J,code:L.invalid_string,...T.errToObj(Q)})}_addCheck($){return new A0({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...T.errToObj($)})}url($){return this._addCheck({kind:"url",...T.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...T.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...T.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...T.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...T.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...T.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...T.errToObj($)})}base64($){return this._addCheck({kind:"base64",...T.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...T.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...T.errToObj($)})}ip($){return this._addCheck({kind:"ip",...T.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...T.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...T.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...T.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...T.errToObj($)})}regex($,J){return this._addCheck({kind:"regex",regex:$,...T.errToObj(J)})}includes($,J){return this._addCheck({kind:"includes",value:$,position:J?.position,...T.errToObj(J?.message)})}startsWith($,J){return this._addCheck({kind:"startsWith",value:$,...T.errToObj(J)})}endsWith($,J){return this._addCheck({kind:"endsWith",value:$,...T.errToObj(J)})}min($,J){return this._addCheck({kind:"min",value:$,...T.errToObj(J)})}max($,J){return this._addCheck({kind:"max",value:$,...T.errToObj(J)})}length($,J){return this._addCheck({kind:"length",value:$,...T.errToObj(J)})}nonempty($){return this.min(1,T.errToObj($))}trim(){return new 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:j.ZodString,coerce:$?.coerce??!1,...h($)})};function wQ($,J){let Q=($.toString().split(".")[1]||"").length,X=(J.toString().split(".")[1]||"").length,W=Q>X?Q:X,Y=Number.parseInt($.toFixed(W).replace(".","")),G=Number.parseInt(J.toFixed(W).replace(".",""));return Y%G/10**W}class a0 extends k{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==b.number){let W=this._getOrReturnCtx($);return S(W,{code:L.invalid_type,expected:b.number,received:W.parsedType}),I}let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="int"){if(!l.isInteger($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:L.invalid_type,expected:"integer",received:"float",message:W.message}),X.dirty()}else if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:L.too_small,minimum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:L.too_big,maximum:W.value,type:"number",inclusive:W.inclusive,exact:!1,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if(wQ($.data,W.value)!==0)Q=this._getOrReturnCtx($,Q),S(Q,{code:L.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else if(W.kind==="finite"){if(!Number.isFinite($.data))Q=this._getOrReturnCtx($,Q),S(Q,{code:L.not_finite,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new a0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new a0({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:T.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.toString(J)})}finite($){return this._addCheck({kind:"finite",message:T.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString($)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&l.isInteger($.value))}get isFinite(){let $=null,J=null;for(let Q of this._def.checks)if(Q.kind==="finite"||Q.kind==="int"||Q.kind==="multipleOf")return!0;else if(Q.kind==="min"){if(J===null||Q.value>J)J=Q.value}else if(Q.kind==="max"){if($===null||Q.value<$)$=Q.value}return Number.isFinite(J)&&Number.isFinite($)}}a0.create=($)=>{return new a0({checks:[],typeName:j.ZodNumber,coerce:$?.coerce||!1,...h($)})};class s0 extends k{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==b.bigint)return this._getInvalidInput($);let Q=void 0,X=new q0;for(let W of this._def.checks)if(W.kind==="min"){if(W.inclusive?$.data<W.value:$.data<=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:L.too_small,type:"bigint",minimum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="max"){if(W.inclusive?$.data>W.value:$.data>=W.value)Q=this._getOrReturnCtx($,Q),S(Q,{code:L.too_big,type:"bigint",maximum:W.value,inclusive:W.inclusive,message:W.message}),X.dirty()}else if(W.kind==="multipleOf"){if($.data%W.value!==BigInt(0))Q=this._getOrReturnCtx($,Q),S(Q,{code:L.not_multiple_of,multipleOf:W.value,message:W.message}),X.dirty()}else l.assertNever(W);return{status:X.value,value:$.data}}_getInvalidInput($){let J=this._getOrReturnCtx($);return S(J,{code:L.invalid_type,expected:b.bigint,received:J.parsedType}),I}gte($,J){return this.setLimit("min",$,!0,T.toString(J))}gt($,J){return this.setLimit("min",$,!1,T.toString(J))}lte($,J){return this.setLimit("max",$,!0,T.toString(J))}lt($,J){return this.setLimit("max",$,!1,T.toString(J))}setLimit($,J,Q,X){return new s0({...this._def,checks:[...this._def.checks,{kind:$,value:J,inclusive:Q,message:T.toString(X)}]})}_addCheck($){return new s0({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString($)})}multipleOf($,J){return this._addCheck({kind:"multipleOf",value:$,message:T.toString(J)})}get minValue(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $}get maxValue(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $}}s0.create=($)=>{return new s0({checks:[],typeName:j.ZodBigInt,coerce:$?.coerce??!1,...h($)})};class I$ extends k{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==b.boolean){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.boolean,received:Q.parsedType}),I}return B0($.data)}}I$.create=($)=>{return new I$({typeName:j.ZodBoolean,coerce:$?.coerce||!1,...h($)})};class V$ extends k{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==b.date){let W=this._getOrReturnCtx($);return S(W,{code:L.invalid_type,expected:b.date,received:W.parsedType}),I}if(Number.isNaN($.data.getTime())){let W=this._getOrReturnCtx($);return S(W,{code:L.invalid_date}),I}let Q=new q0,X=void 0;for(let W of this._def.checks)if(W.kind==="min"){if($.data.getTime()<W.value)X=this._getOrReturnCtx($,X),S(X,{code:L.too_small,message:W.message,inclusive:!0,exact:!1,minimum:W.value,type:"date"}),Q.dirty()}else if(W.kind==="max"){if($.data.getTime()>W.value)X=this._getOrReturnCtx($,X),S(X,{code:L.too_big,message:W.message,inclusive:!0,exact:!1,maximum:W.value,type:"date"}),Q.dirty()}else l.assertNever(W);return{status:Q.value,value:new Date($.data.getTime())}}_addCheck($){return new V$({...this._def,checks:[...this._def.checks,$]})}min($,J){return this._addCheck({kind:"min",value:$.getTime(),message:T.toString(J)})}max($,J){return this._addCheck({kind:"max",value:$.getTime(),message:T.toString(J)})}get minDate(){let $=null;for(let J of this._def.checks)if(J.kind==="min"){if($===null||J.value>$)$=J.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let J of this._def.checks)if(J.kind==="max"){if($===null||J.value<$)$=J.value}return $!=null?new Date($):null}}V$.create=($)=>{return new V$({checks:[],coerce:$?.coerce||!1,typeName:j.ZodDate,...h($)})};class U2 extends k{_parse($){if(this._getType($)!==b.symbol){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.symbol,received:Q.parsedType}),I}return B0($.data)}}U2.create=($)=>{return new U2({typeName:j.ZodSymbol,...h($)})};class v$ extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.undefined,received:Q.parsedType}),I}return B0($.data)}}v$.create=($)=>{return new v$({typeName:j.ZodUndefined,...h($)})};class x$ extends k{_parse($){if(this._getType($)!==b.null){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.null,received:Q.parsedType}),I}return B0($.data)}}x$.create=($)=>{return new x$({typeName:j.ZodNull,...h($)})};class z$ extends k{constructor(){super(...arguments);this._any=!0}_parse($){return B0($.data)}}z$.create=($)=>{return new z$({typeName:j.ZodAny,...h($)})};class r0 extends k{constructor(){super(...arguments);this._unknown=!0}_parse($){return B0($.data)}}r0.create=($)=>{return new r0({typeName:j.ZodUnknown,...h($)})};class I0 extends k{_parse($){let J=this._getOrReturnCtx($);return S(J,{code:L.invalid_type,expected:b.never,received:J.parsedType}),I}}I0.create=($)=>{return new I0({typeName:j.ZodNever,...h($)})};class V2 extends k{_parse($){if(this._getType($)!==b.undefined){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.void,received:Q.parsedType}),I}return B0($.data)}}V2.create=($)=>{return new V2({typeName:j.ZodVoid,...h($)})};class j0 extends k{_parse($){let{ctx:J,status:Q}=this._processInputParams($),X=this._def;if(J.parsedType!==b.array)return S(J,{code:L.invalid_type,expected:b.array,received:J.parsedType}),I;if(X.exactLength!==null){let Y=J.data.length>X.exactLength.value,G=J.data.length<X.exactLength.value;if(Y||G)S(J,{code:Y?L.too_big:L.too_small,minimum:G?X.exactLength.value:void 0,maximum:Y?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),Q.dirty()}if(X.minLength!==null){if(J.data.length<X.minLength.value)S(J,{code:L.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),Q.dirty()}if(X.maxLength!==null){if(J.data.length>X.maxLength.value)S(J,{code:L.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),Q.dirty()}if(J.common.async)return Promise.all([...J.data].map((Y,G)=>{return X.type._parseAsync(new Z0(J,Y,J.path,G))})).then((Y)=>{return q0.mergeArray(Q,Y)});let W=[...J.data].map((Y,G)=>{return X.type._parseSync(new Z0(J,Y,J.path,G))});return q0.mergeArray(Q,W)}get element(){return this._def.type}min($,J){return new j0({...this._def,minLength:{value:$,message:T.toString(J)}})}max($,J){return new j0({...this._def,maxLength:{value:$,message:T.toString(J)}})}length($,J){return new j0({...this._def,exactLength:{value:$,message:T.toString(J)}})}nonempty($){return this.min(1,$)}}j0.create=($,J)=>{return new j0({type:$,minLength:null,maxLength:null,exactLength:null,typeName:j.ZodArray,...h(J)})};function f$($){if($ instanceof e){let J={};for(let Q in $.shape){let X=$.shape[Q];J[Q]=N0.create(f$(X))}return new e({...$._def,shape:()=>J})}else if($ instanceof j0)return new j0({...$._def,type:f$($.element)});else if($ instanceof N0)return N0.create(f$($.unwrap()));else if($ instanceof u0)return u0.create(f$($.unwrap()));else if($ instanceof v0)return v0.create($.items.map((J)=>f$(J)));else return $}class e extends k{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),J=l.objectKeys($);return this._cached={shape:$,keys:J},this._cached}_parse($){if(this._getType($)!==b.object){let H=this._getOrReturnCtx($);return S(H,{code:L.invalid_type,expected:b.object,received:H.parsedType}),I}let{status:Q,ctx:X}=this._processInputParams($),{shape:W,keys:Y}=this._getCached(),G=[];if(!(this._def.catchall instanceof I0&&this._def.unknownKeys==="strip")){for(let H in X.data)if(!Y.includes(H))G.push(H)}let q=[];for(let H of Y){let B=W[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 I0){let H=this._def.unknownKeys;if(H==="passthrough")for(let B of G)q.push({key:{status:"valid",value:B},value:{status:"valid",value:X.data[B]}});else if(H==="strict"){if(G.length>0)S(X,{code:L.unrecognized_keys,keys:G}),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 G){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 T.errToObj,new e({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(J,Q)=>{let X=this._def.errorMap?.(J,Q).message??Q.defaultError;if(J.code==="unrecognized_keys")return{message:T.errToObj($).message??X};return{message:X}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend($){return new e({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new e({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:j.ZodObject})}setKey($,J){return this.augment({[$]:J})}catchall($){return new e({...this._def,catchall:$})}pick($){let J={};for(let Q of l.objectKeys($))if($[Q]&&this.shape[Q])J[Q]=this.shape[Q];return new e({...this._def,shape:()=>J})}omit($){let J={};for(let Q of l.objectKeys(this.shape))if(!$[Q])J[Q]=this.shape[Q];return new e({...this._def,shape:()=>J})}deepPartial(){return f$(this)}partial($){let J={};for(let Q of l.objectKeys(this.shape)){let X=this.shape[Q];if($&&!$[Q])J[Q]=X;else J[Q]=X.optional()}return new e({...this._def,shape:()=>J})}required($){let J={};for(let Q of l.objectKeys(this.shape))if($&&!$[Q])J[Q]=this.shape[Q];else{let W=this.shape[Q];while(W instanceof N0)W=W._def.innerType;J[Q]=W}return new e({...this._def,shape:()=>J})}keyof(){return z7(l.objectKeys(this.shape))}}e.create=($,J)=>{return new e({shape:()=>$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};e.strictCreate=($,J)=>{return new e({shape:()=>$,unknownKeys:"strict",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};e.lazycreate=($,J)=>{return new e({shape:$,unknownKeys:"strip",catchall:I0.create(),typeName:j.ZodObject,...h(J)})};class h$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=this._def.options;function X(W){for(let G of W)if(G.result.status==="valid")return G.result;for(let G of W)if(G.result.status==="dirty")return J.common.issues.push(...G.ctx.common.issues),G.result;let Y=W.map((G)=>new G0(G.ctx.common.issues));return S(J,{code:L.invalid_union,unionErrors:Y}),I}if(J.common.async)return Promise.all(Q.map(async(W)=>{let Y={...J,common:{...J.common,issues:[]},parent:null};return{result:await W._parseAsync({data:J.data,path:J.path,parent:Y}),ctx:Y}})).then(X);else{let W=void 0,Y=[];for(let q of Q){let H={...J,common:{...J.common,issues:[]},parent:null},B=q._parseSync({data:J.data,path:J.path,parent:H});if(B.status==="valid")return B;else if(B.status==="dirty"&&!W)W={result:B,ctx:H};if(H.common.issues.length)Y.push(H.common.issues)}if(W)return J.common.issues.push(...W.ctx.common.issues),W.result;let G=Y.map((q)=>new G0(q));return S(J,{code:L.invalid_union,unionErrors:G}),I}}get options(){return this._def.options}}h$.create=($,J)=>{return new h$({options:$,typeName:j.ZodUnion,...h(J)})};var m0=($)=>{if($ instanceof g$)return m0($.schema);else if($ instanceof w0)return m0($.innerType());else if($ instanceof k$)return[$.value];else if($ instanceof o0)return $.options;else if($ instanceof m$)return l.objectValues($.enum);else if($ instanceof u$)return m0($._def.innerType);else if($ instanceof v$)return[void 0];else if($ instanceof x$)return[null];else if($ instanceof N0)return[void 0,...m0($.unwrap())];else if($ instanceof u0)return[null,...m0($.unwrap())];else if($ instanceof F6)return m0($.unwrap());else if($ instanceof c$)return m0($.unwrap());else if($ instanceof l$)return m0($._def.innerType);else return[]};class O6 extends k{_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.object)return S(J,{code:L.invalid_type,expected:b.object,received:J.parsedType}),I;let Q=this.discriminator,X=J.data[Q],W=this.optionsMap.get(X);if(!W)return S(J,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[Q]}),I;if(J.common.async)return W._parseAsync({data:J.data,path:J.path,parent:J});else return W._parseSync({data:J.data,path:J.path,parent:J})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,J,Q){let X=new Map;for(let W of J){let Y=m0(W.shape[$]);if(!Y.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let G of Y){if(X.has(G))throw Error(`Discriminator property ${String($)} has duplicate value ${String(G)}`);X.set(G,W)}}return new O6({typeName:j.ZodDiscriminatedUnion,discriminator:$,options:J,optionsMap:X,...h(Q)})}}function y9($,J){let Q=T0($),X=T0(J);if($===J)return{valid:!0,data:$};else if(Q===b.object&&X===b.object){let W=l.objectKeys(J),Y=l.objectKeys($).filter((q)=>W.indexOf(q)!==-1),G={...$,...J};for(let q of Y){let H=y9($[q],J[q]);if(!H.valid)return{valid:!1};G[q]=H.data}return{valid:!0,data:G}}else if(Q===b.array&&X===b.array){if($.length!==J.length)return{valid:!1};let W=[];for(let Y=0;Y<$.length;Y++){let G=$[Y],q=J[Y],H=y9(G,q);if(!H.valid)return{valid:!1};W.push(H.data)}return{valid:!0,data:W}}else if(Q===b.date&&X===b.date&&+$===+J)return{valid:!0,data:$};else return{valid:!1}}class y$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=(W,Y)=>{if(z6(W)||z6(Y))return I;let G=y9(W.value,Y.value);if(!G.valid)return S(Q,{code:L.invalid_intersection_types}),I;if(D6(W)||D6(Y))J.dirty();return{status:J.value,value:G.data}};if(Q.common.async)return Promise.all([this._def.left._parseAsync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseAsync({data:Q.data,path:Q.path,parent:Q})]).then(([W,Y])=>X(W,Y));else return X(this._def.left._parseSync({data:Q.data,path:Q.path,parent:Q}),this._def.right._parseSync({data:Q.data,path:Q.path,parent:Q}))}}y$.create=($,J,Q)=>{return new y$({left:$,right:J,typeName:j.ZodIntersection,...h(Q)})};class v0 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.array)return S(Q,{code:L.invalid_type,expected:b.array,received:Q.parsedType}),I;if(Q.data.length<this._def.items.length)return S(Q,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&Q.data.length>this._def.items.length)S(Q,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J.dirty();let W=[...Q.data].map((Y,G)=>{let q=this._def.items[G]||this._def.rest;if(!q)return null;return q._parse(new Z0(Q,Y,Q.path,G))}).filter((Y)=>!!Y);if(Q.common.async)return Promise.all(W).then((Y)=>{return q0.mergeArray(J,Y)});else return q0.mergeArray(J,W)}get items(){return this._def.items}rest($){return new v0({...this._def,rest:$})}}v0.create=($,J)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new v0({items:$,typeName:j.ZodTuple,rest:null,...h(J)})};class z2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.object)return S(Q,{code:L.invalid_type,expected:b.object,received:Q.parsedType}),I;let X=[],W=this._def.keyType,Y=this._def.valueType;for(let G in Q.data)X.push({key:W._parse(new Z0(Q,G,Q.path,G)),value:Y._parse(new Z0(Q,Q.data[G],Q.path,G)),alwaysSet:G 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 z2({keyType:$,valueType:J,typeName:j.ZodRecord,...h(Q)});return new z2({keyType:A0.create(),valueType:$,typeName:j.ZodRecord,...h(J)})}}class D2 extends k{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.map)return S(Q,{code:L.invalid_type,expected:b.map,received:Q.parsedType}),I;let X=this._def.keyType,W=this._def.valueType,Y=[...Q.data.entries()].map(([G,q],H)=>{return{key:X._parse(new Z0(Q,G,Q.path,[H,"key"])),value:W._parse(new Z0(Q,q,Q.path,[H,"value"]))}});if(Q.common.async){let G=new Map;return Promise.resolve().then(async()=>{for(let q of Y){let H=await q.key,B=await q.value;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();G.set(H.value,B.value)}return{status:J.value,value:G}})}else{let G=new Map;for(let q of Y){let{key:H,value:B}=q;if(H.status==="aborted"||B.status==="aborted")return I;if(H.status==="dirty"||B.status==="dirty")J.dirty();G.set(H.value,B.value)}return{status:J.value,value:G}}}}D2.create=($,J,Q)=>{return new D2({valueType:J,keyType:$,typeName:j.ZodMap,...h(Q)})};class D$ extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.parsedType!==b.set)return S(Q,{code:L.invalid_type,expected:b.set,received:Q.parsedType}),I;let X=this._def;if(X.minSize!==null){if(Q.data.size<X.minSize.value)S(Q,{code:L.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),J.dirty()}if(X.maxSize!==null){if(Q.data.size>X.maxSize.value)S(Q,{code:L.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),J.dirty()}let W=this._def.valueType;function Y(q){let H=new Set;for(let B of q){if(B.status==="aborted")return I;if(B.status==="dirty")J.dirty();H.add(B.value)}return{status:J.value,value:H}}let G=[...Q.data.values()].map((q,H)=>W._parse(new Z0(Q,q,Q.path,H)));if(Q.common.async)return Promise.all(G).then((q)=>Y(q));else return Y(G)}min($,J){return new D$({...this._def,minSize:{value:$,message:T.toString(J)}})}max($,J){return new D$({...this._def,maxSize:{value:$,message:T.toString(J)}})}size($,J){return this.min($,J).max($,J)}nonempty($){return this.min(1,$)}}D$.create=($,J)=>{return new D$({valueType:$,minSize:null,maxSize:null,typeName:j.ZodSet,...h(J)})};class T$ extends k{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.function)return S(J,{code:L.invalid_type,expected:b.function,received:J.parsedType}),I;function Q(G,q){return B2({data:G,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),k0].filter((H)=>!!H),issueData:{code:L.invalid_arguments,argumentsError:q}})}function X(G,q){return B2({data:G,path:J.path,errorMaps:[J.common.contextualErrorMap,J.schemaErrorMap,E$(),k0].filter((H)=>!!H),issueData:{code:L.invalid_return_type,returnTypeError:q}})}let W={errorMap:J.common.contextualErrorMap},Y=J.data;if(this._def.returns instanceof O$){let G=this;return B0(async function(...q){let H=new G0([]),B=await G._def.args.parseAsync(q,W).catch((V)=>{throw H.addIssue(Q(q,V)),H}),U=await Reflect.apply(Y,this,B);return await G._def.returns._def.type.parseAsync(U,W).catch((V)=>{throw H.addIssue(X(U,V)),H})})}else{let G=this;return B0(function(...q){let H=G._def.args.safeParse(q,W);if(!H.success)throw new G0([Q(q,H.error)]);let B=Reflect.apply(Y,this,H.data),U=G._def.returns.safeParse(B,W);if(!U.success)throw new G0([X(B,U.error)]);return U.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new T$({...this._def,args:v0.create($).rest(r0.create())})}returns($){return new T$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,J,Q){return new T$({args:$?$:v0.create([]).rest(r0.create()),returns:J||r0.create(),typeName:j.ZodFunction,...h(Q)})}}class g$ extends k{get schema(){return this._def.getter()}_parse($){let{ctx:J}=this._processInputParams($);return this._def.getter()._parse({data:J.data,path:J.path,parent:J})}}g$.create=($,J)=>{return new g$({getter:$,typeName:j.ZodLazy,...h(J)})};class k$ extends k{_parse($){if($.data!==this._def.value){let J=this._getOrReturnCtx($);return S(J,{received:J.data,code:L.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:$.data}}get value(){return this._def.value}}k$.create=($,J)=>{return new k$({value:$,typeName:j.ZodLiteral,...h(J)})};function z7($,J){return new o0({values:$,typeName:j.ZodEnum,...h(J)})}class o0 extends k{_parse($){if(typeof $.data!=="string"){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{expected:l.joinValues(Q),received:J.parsedType,code:L.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let J=this._getOrReturnCtx($),Q=this._def.values;return S(J,{received:J.data,code:L.invalid_enum_value,options:Q}),I}return B0($.data)}get options(){return this._def.values}get enum(){let $={};for(let J of this._def.values)$[J]=J;return $}get Values(){let $={};for(let J of this._def.values)$[J]=J;return $}get Enum(){let $={};for(let J of this._def.values)$[J]=J;return $}extract($,J=this._def){return o0.create($,{...this._def,...J})}exclude($,J=this._def){return o0.create(this.options.filter((Q)=>!$.includes(Q)),{...this._def,...J})}}o0.create=z7;class m$ extends k{_parse($){let J=l.getValidEnumValues(this._def.values),Q=this._getOrReturnCtx($);if(Q.parsedType!==b.string&&Q.parsedType!==b.number){let X=l.objectValues(J);return S(Q,{expected:l.joinValues(X),received:Q.parsedType,code:L.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let X=l.objectValues(J);return S(Q,{received:Q.data,code:L.invalid_enum_value,options:X}),I}return B0($.data)}get enum(){return this._def.values}}m$.create=($,J)=>{return new m$({values:$,typeName:j.ZodNativeEnum,...h(J)})};class O$ extends k{unwrap(){return this._def.type}_parse($){let{ctx:J}=this._processInputParams($);if(J.parsedType!==b.promise&&J.common.async===!1)return S(J,{code:L.invalid_type,expected:b.promise,received:J.parsedType}),I;let Q=J.parsedType===b.promise?J.data:Promise.resolve(J.data);return B0(Q.then((X)=>{return this._def.type.parseAsync(X,{path:J.path,errorMap:J.common.contextualErrorMap})}))}}O$.create=($,J)=>{return new O$({type:$,typeName:j.ZodPromise,...h(J)})};class w0 extends k{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===j.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:J,ctx:Q}=this._processInputParams($),X=this._def.effect||null,W={addIssue:(Y)=>{if(S(Q,Y),Y.fatal)J.abort();else J.dirty()},get path(){return Q.path}};if(W.addIssue=W.addIssue.bind(W),X.type==="preprocess"){let Y=X.transform(Q.data,W);if(Q.common.async)return Promise.resolve(Y).then(async(G)=>{if(J.value==="aborted")return I;let q=await this._def.schema._parseAsync({data:G,path:Q.path,parent:Q});if(q.status==="aborted")return I;if(q.status==="dirty")return U$(q.value);if(J.value==="dirty")return U$(q.value);return q});else{if(J.value==="aborted")return I;let G=this._def.schema._parseSync({data:Y,path:Q.path,parent:Q});if(G.status==="aborted")return I;if(G.status==="dirty")return U$(G.value);if(J.value==="dirty")return U$(G.value);return G}}if(X.type==="refinement"){let Y=(G)=>{let q=X.refinement(G,W);if(Q.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return G};if(Q.common.async===!1){let G=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(G.status==="aborted")return I;if(G.status==="dirty")J.dirty();return Y(G.value),{status:J.value,value:G.value}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((G)=>{if(G.status==="aborted")return I;if(G.status==="dirty")J.dirty();return Y(G.value).then(()=>{return{status:J.value,value:G.value}})})}if(X.type==="transform")if(Q.common.async===!1){let Y=this._def.schema._parseSync({data:Q.data,path:Q.path,parent:Q});if(!n0(Y))return I;let G=X.transform(Y.value,W);if(G instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:J.value,value:G}}else return this._def.schema._parseAsync({data:Q.data,path:Q.path,parent:Q}).then((Y)=>{if(!n0(Y))return I;return Promise.resolve(X.transform(Y.value,W)).then((G)=>({status:J.value,value:G}))});l.assertNever(X)}}w0.create=($,J,Q)=>{return new w0({schema:$,typeName:j.ZodEffects,effect:J,...h(Q)})};w0.createWithPreprocess=($,J,Q)=>{return new w0({schema:J,effect:{type:"preprocess",transform:$},typeName:j.ZodEffects,...h(Q)})};class N0 extends k{_parse($){if(this._getType($)===b.undefined)return B0(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}N0.create=($,J)=>{return new N0({innerType:$,typeName:j.ZodOptional,...h(J)})};class u0 extends k{_parse($){if(this._getType($)===b.null)return B0(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}u0.create=($,J)=>{return new u0({innerType:$,typeName:j.ZodNullable,...h(J)})};class u$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q=J.data;if(J.parsedType===b.undefined)Q=this._def.defaultValue();return this._def.innerType._parse({data:Q,path:J.path,parent:J})}removeDefault(){return this._def.innerType}}u$.create=($,J)=>{return new u$({innerType:$,typeName:j.ZodDefault,defaultValue:typeof J.default==="function"?J.default:()=>J.default,...h(J)})};class l$ extends k{_parse($){let{ctx:J}=this._processInputParams($),Q={...J,common:{...J.common,issues:[]}},X=this._def.innerType._parse({data:Q.data,path:Q.path,parent:{...Q}});if(C$(X))return X.then((W)=>{return{status:"valid",value:W.status==="valid"?W.value:this._def.catchValue({get error(){return new G0(Q.common.issues)},input:Q.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new G0(Q.common.issues)},input:Q.data})}}removeCatch(){return this._def.innerType}}l$.create=($,J)=>{return new l$({innerType:$,typeName:j.ZodCatch,catchValue:typeof J.catch==="function"?J.catch:()=>J.catch,...h(J)})};class O2 extends k{_parse($){if(this._getType($)!==b.nan){let Q=this._getOrReturnCtx($);return S(Q,{code:L.invalid_type,expected:b.nan,received:Q.parsedType}),I}return{status:"valid",value:$.data}}}O2.create=($)=>{return new O2({typeName:j.ZodNaN,...h($)})};var bQ=Symbol("zod_brand");class F6 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 F2 extends k{_parse($){let{status:J,ctx:Q}=this._processInputParams($);if(Q.common.async)return(async()=>{let W=await this._def.in._parseAsync({data:Q.data,path:Q.path,parent:Q});if(W.status==="aborted")return I;if(W.status==="dirty")return J.dirty(),U$(W.value);else return this._def.out._parseAsync({data:W.value,path:Q.path,parent:Q})})();else{let X=this._def.in._parseSync({data:Q.data,path:Q.path,parent:Q});if(X.status==="aborted")return I;if(X.status==="dirty")return J.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:Q.path,parent:Q})}}static create($,J){return new F2({in:$,out:J,typeName:j.ZodPipeline})}}class c$ extends k{_parse($){let J=this._def.innerType._parse($),Q=(X)=>{if(n0(X))X.value=Object.freeze(X.value);return X};return C$(J)?J.then((X)=>Q(X)):Q(J)}unwrap(){return this._def.innerType}}c$.create=($,J)=>{return new c$({innerType:$,typeName:j.ZodReadonly,...h(J)})};function H7($,J){let Q=typeof $==="function"?$(J):typeof $==="string"?{message:$}:$;return typeof Q==="string"?{message:Q}:Q}function D7($,J={},Q){if($)return z$.create().superRefine((X,W)=>{let Y=$(X);if(Y instanceof Promise)return Y.then((G)=>{if(!G){let q=H7(J,X),H=q.fatal??Q??!0;W.addIssue({code:"custom",...q,fatal:H})}});if(!Y){let G=H7(J,X),q=G.fatal??Q??!0;W.addIssue({code:"custom",...G,fatal:q})}return});return z$.create()}var PQ={object:e.lazycreate},j;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(j||(j={}));var SQ=($,J={message:`Input not instance of ${$.name}`})=>D7((Q)=>Q instanceof $,J),O7=A0.create,F7=a0.create,EQ=O2.create,CQ=s0.create,M7=I$.create,fQ=V$.create,TQ=U2.create,IQ=v$.create,vQ=x$.create,xQ=z$.create,hQ=r0.create,yQ=I0.create,gQ=V2.create,kQ=j0.create,mQ=e.create,uQ=e.strictCreate,lQ=h$.create,cQ=O6.create,pQ=y$.create,dQ=v0.create,iQ=z2.create,nQ=D2.create,rQ=D$.create,aQ=T$.create,sQ=g$.create,oQ=k$.create,tQ=o0.create,eQ=m$.create,$X=O$.create,JX=w0.create,QX=N0.create,XX=u0.create,WX=w0.createWithPreprocess,YX=F2.create,GX=()=>O7().optional(),qX=()=>F7().optional(),HX=()=>M7().optional(),BX={string:($)=>A0.create({...$,coerce:!0}),number:($)=>a0.create({...$,coerce:!0}),boolean:($)=>I$.create({...$,coerce:!0}),bigint:($)=>s0.create({...$,coerce:!0}),date:($)=>V$.create({...$,coerce:!0})};var UX=I;var g9=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 VX($){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 K7($){let J=Date.now();return{alive:!1,status:"not_found",createdAt:J,lastUpdatedAt:J,description:`No background process found with id '${$}'.`}}var LM={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
277
302
|
|
|
278
303
|
Use this tool when:
|
|
279
304
|
- 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.
|
|
@@ -290,7 +315,7 @@ Use this tool when:
|
|
|
290
315
|
- result: present when status is 'completed'
|
|
291
316
|
- error: present when status is 'failed'
|
|
292
317
|
|
|
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:
|
|
318
|
+
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:g9,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async($,J)=>M6(null).execute($,J)};function M6($=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
294
319
|
|
|
295
320
|
Use this tool when:
|
|
296
321
|
- 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.
|
|
@@ -307,7 +332,7 @@ Use this tool when:
|
|
|
307
332
|
- result: present when status is 'completed'
|
|
308
333
|
- error: present when status is 'failed'
|
|
309
334
|
|
|
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:
|
|
335
|
+
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:g9,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(J,Q)=>{let X=Date.now(),W=g9.parse(J),{bgProcessId:Y}=W;if(!$)return{success:!1,output:"",error:"query_background_process is not initialized: no BackgroundTaskManager has been bound. TaskComponent should call createQueryBackgroundProcessTool(manager) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-X}};let G;try{G=$.getTask(Y)}catch(H){return{success:!1,output:"",error:`failed to query background task: ${H.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(G){let H=Q.session_id;if(!H||G.parentSessionId!==H)return{success:!0,output:JSON.stringify(K7(Y),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:Y,status:"not_found",alive:!1}}}let q=G?VX(G):K7(Y);if(q.alive)try{let H=await $.getSubSessionActivity?.(Y);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:Y,status:q.status,alive:q.alive}}}}}var R7=K.object({task_id:K.string().describe("The ID of the background task to stop")}),zX=`Stop a running background task.
|
|
311
336
|
|
|
312
337
|
Use this tool to stop a background task that is currently running. This is useful when:
|
|
313
338
|
- The user wants to cancel a long-running task
|
|
@@ -317,10 +342,10 @@ Use this tool to stop a background task that is currently running. This is usefu
|
|
|
317
342
|
When stopped, the task will be terminated immediately and you will receive a confirmation.
|
|
318
343
|
|
|
319
344
|
Parameters:
|
|
320
|
-
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function
|
|
321
|
-
`),metadata:{execution_time_ms:Date.now()-X,task_id:
|
|
322
|
-
`);else H=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${
|
|
323
|
-
`);return{success:!1,output:H,error:
|
|
345
|
+
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function DX($){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 _7($){return{name:"stop_task",description:zX,parameters:R7,execute:async(J,Q)=>{let X=Date.now(),W=R7.parse(J),{task_id:Y}=W,G=await $.stopTask(Y);if(G.success){let q=G.task,H=q.startedAt?Date.now()-q.startedAt:Date.now()-q.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${Y}`,`\uD83D\uDCDD Description: ${q.description}`,`\uD83D\uDD04 Status: ${q.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${DX(H)}`,"",G.message].join(`
|
|
346
|
+
`),metadata:{execution_time_ms:Date.now()-X,task_id:Y,previous_status:q.status}}}else{let q=G.task,H;if(q)H=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${Y}`,`\uD83D\uDCDD Description: ${q.description}`,`\uD83D\uDD04 Current Status: ${q.status}`,"",G.message].join(`
|
|
347
|
+
`);else H=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${Y}`,"",G.message].join(`
|
|
348
|
+
`);return{success:!1,output:H,error:G.message,metadata:{execution_time_ms:Date.now()-X,task_id:Y}}}}}}function k9(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function L7($){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 OX(){if(typeof Bun<"u"){let{Database:$}=t("bun:sqlite");return $}try{let{DatabaseSync:$}=t("node:sqlite");if(typeof $==="function")return $}catch{}return t("better-sqlite3")}function FX($){let Q=new(OX())($);if(typeof Q.run!=="function")Q.run=function(X,...W){if(W.length>0)return this.prepare(X).run(...W);else return this.exec(X)};return Q}class m9{db=null;dbPath;initialized=!1;constructor($){if(!$)throw Error("SQLiteSpanStorage requires a valid dbPath parameter");if($===":memory:")throw Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");this.dbPath=$}async initialize(){if(this.initialized)return;let $=t("fs"),Q=t("path").dirname(this.dbPath);if(!$.existsSync(Q))$.mkdirSync(Q,{recursive:!0});this.db=FX(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(`
|
|
324
349
|
CREATE TABLE IF NOT EXISTS span (
|
|
325
350
|
span_id TEXT PRIMARY KEY,
|
|
326
351
|
trace_id TEXT NOT NULL,
|
|
@@ -335,11 +360,11 @@ Parameters:
|
|
|
335
360
|
error TEXT,
|
|
336
361
|
time_created INTEGER NOT NULL
|
|
337
362
|
)
|
|
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(
|
|
363
|
+
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save($){if(!this.db){if(k9())console.log(`[SpanStorage] save() skipped: db not initialized for span "${$.name}" traceId=${$.traceId}`);return}let J=this.db.prepare(`
|
|
339
364
|
INSERT OR REPLACE INTO span
|
|
340
365
|
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
341
366
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
342
|
-
`),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:
|
|
367
|
+
`),Q=$.result!==void 0&&$.result!==null?typeof $.result==="string"?$.result:L7($.result):null;if(k9())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${$.name}" traceId=${$.traceId} spanId=${$.spanId} status=${$.status}`);try{let X=J.run($.spanId,$.traceId,$.parentSpanId||null,$.name,$.kind,$.status,$.startTime,$.endTime||null,L7($.attributes),Q,$.error||null,Date.now());if(k9())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch($){for(let J of $)this.save(J)}findByTraceId($){if(!this.db)return[];let J=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all($);return this.buildTree(J.map(this.rowToSpan))}findBySpanId($){if(!this.db)return;let J=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get($);return J?this.rowToSpan(J):void 0}listTraces($=10){if(!this.db)return[];return this.db.prepare(`
|
|
343
368
|
SELECT trace_id,
|
|
344
369
|
MIN(start_time) as start_time,
|
|
345
370
|
MAX(end_time) as end_time,
|
|
@@ -354,10 +379,10 @@ Parameters:
|
|
|
354
379
|
GROUP BY trace_id
|
|
355
380
|
ORDER BY start_time DESC
|
|
356
381
|
LIMIT ?
|
|
357
|
-
`).all($).map((Q)=>{let X=Number(Q.span_count)||0,
|
|
358
|
-
`)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let
|
|
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
|
|
382
|
+
`).all($).map((Q)=>{let X=Number(Q.span_count)||0,W=Number(Q.error_count)||0,Y=Q.end_time??void 0,G=W===0?"ok":W>=X?"error":"mixed";return{traceId:Q.trace_id,rootSpanName:Q.root_name??"unknown",startTime:Q.start_time,endTime:Y,duration:Y!==void 0?Y-Q.start_time:void 0,spanCount:X,status:G}})}deleteByTraceId($){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run($)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan($){return{traceId:$.trace_id,spanId:$.span_id,parentSpanId:$.parent_span_id,name:$.name,kind:$.kind,status:$.status,startTime:$.start_time,endTime:$.end_time,attributes:$.attributes?JSON.parse($.attributes):{},result:$.result||void 0,error:$.error||void 0}}buildTree($){let J=new Map,Q=[];for(let X of $)J.set(X.spanId,{...X,children:[]});for(let X of J.values())if(X.parentSpanId){let W=J.get(X.parentSpanId);if(W)W.children.push(X);else Q.push(X)}else Q.push(X);return Q}}var A7=()=>{};import{appendFileSync as ZX,existsSync as wX,mkdirSync as bX}from"fs";import{join as M2}from"path";import{AsyncLocalStorage as N7}from"async_hooks";function j7($,J){return $.padStart(J,"0")}function u9($){return/^[0-9a-f]+$/i.test($)}function MX($){let J=j7($.traceId.toLowerCase(),P7),Q=j7($.spanId.toLowerCase(),S7);return[p9,J,Q,RX].join("-")}function KX($){if(!$||typeof $!=="string")return;let Q=$.trim().split("-");if(Q.length!==4)return;let[X,W,Y,G]=Q;if(X!==p9){if(X>p9)return}if(W.length!==P7||!u9(W))return;if(Y.length!==S7||!u9(Y))return;if(G.length!==_X||!u9(G))return;return{traceId:W.toLowerCase(),spanId:Y.toLowerCase()}}var p9="00",RX="01",l9="TRACEPARENT",P7=32,S7=16,_X=2,n9,LX=r(()=>{n9={inject($,J){$[l9]=MX(J)},extract($){let J=$[l9];if(!J)return;return KX(J)},getTraceparentHeader(){return l9}}}),AX,jX,NX=r(()=>{(($)=>{$.CLIENT="client",$.SERVER="server",$.INTERNAL="internal"})(AX||={}),(($)=>{$.OK="ok",$.ERROR="error"})(jX||={})});function r9($){let J=$.replace(/\\/g,"/"),Q=J.match(/\/\$bunfs\/root\/(.+)$/);if(Q){let G=Q[1],q=G.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(q)return q[1];return G}let X=J.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let G=X[1].replace(/\+/g,"/"),q=X[2],H=G,B=q.startsWith("src/")?q:`src/${q}`;return`${H}/${B}`}let W=J.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];let Y=["packages/core/src","packages/core","packages"];for(let G of Y){let q=J.indexOf(G);if(q!==-1)return J.substring(q)}return J}function PX(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let J=t("xdg-basedir");if(J.xdgData)return M2(J.xdgData,"roy-agent","logs")}catch{}return M2($,".local","share","roy-agent","logs")}function SX(){return xX}function EX(){if(b0){let J=b0.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 CX($){if(b0){let X=b0.get("log_trace.logging.levels");if(X&&typeof X==="object"){let Y=X[$];if(Y&&["debug","info","warn","error"].includes(Y))return Y}let W=b0.get(`log_trace.logging.levels.${$}`);if(W&&["debug","info","warn","error"].includes(W))return W}let J=`LOG_LEVEL_${$.toUpperCase().replace(/:/g,"_")}`,Q=process.env[J];if(Q&&["debug","info","warn","error"].includes(Q))return Q;return EX()}function fX($){if($.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test($))return!0;return!1}function TX($){if($.startsWith("~")){let J=process.env.HOME||process.env.USERPROFILE||"/tmp";return M2(J,$.slice(1))}return $}function IX(){if(b0){let $=b0.get("log-trace.logging.file");if($)return $}return"app.log"}function vX(){if(b0){let $=b0.get("log-trace.logging.dir");if($)return $}return PX()}function a9(){if(b0){let $=b0.get("log-trace.logging.maxOutput");if(typeof $==="number")return $}return}class E7{prefix;constructor($){this.prefix=$}shouldLog($){let J=CX(this.prefix);return d9[$]>=d9[J]}ensureLogDirectory($){if(!wX($))try{bX($,{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(`
|
|
383
|
+
`)||[];Error.stackTraceLimit=$;for(let X=1;X<Q.length;X++){let W=Q[X];if(W.includes("at ")&&!W.includes("logger.ts")&&!W.includes("formatMessage")){let Y=W.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||W.match(/at\s+(.+):(\d+):\d+/);if(Y){let G=Y[1];return{file:this.getRelativePath(G),line:parseInt(Y[2],10)}}}}return null}getRelativePath($){return r9($)}formatMessage($,J,Q){let X=new Date,W=X.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).replace(/\//g,"-")+"."+String(X.getMilliseconds()).padStart(3,"0"),Y=this.prefix?`[${this.prefix}]`:"",G="";try{let V=K2().getTracer("roy-tracer").getCurrentContext();if(V?.traceId)G=`[traceId=${V.traceId}]`}catch{}let q="";if(Q&&typeof Q==="object"&&"callerLocation"in Q){let U=Q;q=U.callerLocation?` [${U.callerLocation}]`:"";let{callerLocation:z,...V}=U;Q=Object.keys(V).length>0?V:void 0}else{let U=this.getCallerLocation();if(U)q=` [${U.file}:${U.line}]`}let H=`${W} [${$.toUpperCase()}]${G}${q}${Y} ${J}`;if(Q!==void 0)if(typeof Q==="object")H+=" "+JSON.stringify(Q).replace(/\n/g,"");else H+=" "+String(Q);let B=a9();if(B&&B>0&&H.length>B)H=H.substring(0,B)+" [TRUNCATED]";return H}writeToFile($){try{let J=vX(),Q=IX(),X=TX(J),W=fX(X)?X:M2(process.cwd(),X);this.ensureLogDirectory(W);let Y=M2(W,Q);ZX(Y,$+`
|
|
384
|
+
`,"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),!SX())if(hX)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(!K6.has($))K6.set($,new E7($));return K6.get($)}var b0=null,xX=!1,hX=!1;var d9,K6,a=r(()=>{t9(),d9={debug:0,info:1,warn:2,error:3},K6=new Map}),yX={};i0(yX,{setTracerProvider:()=>kX,resetTracerProvider:()=>gX,getTracerProvider:()=>K2,OTelTracerProvider:()=>o9});function s9(){if(!c9)c9=n("otel-tracer");return c9}function C7(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function f7($,...J){s9().info($,...J)}function Z7($,...J){s9().warn($,...J)}function w7($,...J){s9().error($,...J)}class i9{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor($,J,Q,X,W){this.name=$,this.kind="internal",this.spanContext=J,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=Q,this.onEnd=W}setAttribute($,J){this.attributes[$]=J}addEvent($,J){let Q=this.attributes._events||[];Q.push({name:$,attributes:J}),this.attributes._events=Q}end($,J){if(this.endTime=Date.now(),J)this.error=J.message;let Q=this.endTime-(this.startTime||0);if(C7())f7(`[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)Z7(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=K2().getStorage();if(X){if(!(X.db||X.initialized))Z7(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((Y)=>{w7("[OTelSpan] Failed to initialize storage:",Y)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:J?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:$,error:this.error})}else w7(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class T7{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext($){this.provider.setTracerCurrentContext(this.instanceId,$)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor($,J,Q,X){this.name=$,this.version=J,this.storage=Q,this.provider=X,this.instanceId=`${$}@${X.instanceId}`}setOnSpanEndCallback($){this.onSpanEndCallback=$}getActiveSpanCount(){return this.activeSpans.size}startSpan($,J){let Q=J?.parent,X=J&&"parent"in J,W=J&&"context"in J,Y=this.provider.getGlobalContext(),G,q,H,B,U;if(W&&J?.context){let V=J.context;q=V.traceId,H=this.generateSpanId(),B=V.spanId,U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let M=new i9($,U,this.storage,V,()=>this.handleSpanEnd(U.spanId,V.spanId));if(J?.attributes)for(let[O,D]of Object.entries(J.attributes))M.setAttribute(O,D);return this.activeSpans.set(H,M),M}if(X)G=Q;else if(this.currentContext)G=this.currentContext;else if(Y)G=Y;if(q=G?.traceId||this.generateTraceId(),H=this.generateSpanId(),X&&Q)B=Q.parentSpanId||Q.spanId;else if(this.currentContext)B=this.currentContext.spanId;else if(Y)B=Y.spanId;U={traceId:q,spanId:H,parentSpanId:B},this.currentContext={traceId:q,spanId:H,parentSpanId:B};let z=new i9($,U,this.storage,G,()=>this.handleSpanEnd(U.spanId,G?.spanId));if(J?.attributes)for(let[V,M]of Object.entries(J.attributes))z.setAttribute(V,M);if(this.activeSpans.set(H,z),C7())f7(`[OTelTracer] \u2713 Span created: name="${$}" traceId=${q} spanId=${H} parentSpanId=${B||"-"}`);return z}injectToEnv($){if(this.currentContext)n9.inject($,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext($){this.currentContext=$}findStackParentSpan($){for(let[,J]of this.activeSpans)if(J.spanContext.parentSpanId===$)return J;return}endSpan($){let J=$.spanContext;this.activeSpans.delete(J.spanId);let Q=this.currentContext?.traceId;if(J.parentSpanId){let W=this.activeSpans.get(J.parentSpanId);if(W){let Y={traceId:J.traceId,spanId:W.spanContext.spanId,parentSpanId:W.spanContext.parentSpanId};return this.currentContext=Y,Y}if(Q){let Y={traceId:Q,spanId:J.parentSpanId,parentSpanId:void 0};return this.currentContext=Y,Y}}let X=this.findStackParentSpan(J.spanId);if(X){let W={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=W,W}this.currentContext=void 0;return}generateTraceId(){let $=Date.now().toString(16).padStart(12,"0"),J=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return($+J).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd($,J){if(this.activeSpans.delete($),J){let X=this.activeSpans.get(J);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:J,parentSpanId:void 0};return}}let Q=this.findStackParentSpan($);if(Q){this.currentContext={traceId:Q.spanContext.traceId,spanId:Q.spanContext.spanId,parentSpanId:Q.spanContext.parentSpanId};return}this.currentContext=void 0}}class o9{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new N7;tracerContexts=new Map;tracerContextScope=new N7;instanceId;constructor($,J){b7++,this.instanceId=`Provider#${b7}`,this.storage=$||new m9(J||mX())}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 T7($,J,this.storage,this),this.tracers.set(Q,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv($){let J=n9.extract(process.env);if(J)$.setCurrentContext({traceId:J.traceId,spanId:J.spanId,parentSpanId:void 0})}shutdown(){for(let $ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function K2(){if(!l0)l0=new o9;return l0}function gX(){if(l0)l0.shutdown(),l0=null}function kX($){if(l0)l0.shutdown();l0=$}function mX(){let $=t("os"),J=t("path"),Q=$.homedir(),X=process.env.XDG_DATA_HOME||J.join(Q,".local","share");return J.join(X,"roy-agent","traces.db")}var c9=null,l0=null,b7=0,t9=r(()=>{A7(),LX(),NX(),a()});import{AsyncLocalStorage as uX}from"async_hooks";a();var R6=n("process-tree-killer");function x7(){return t("child_process")}var I7;function lX($,J,Q){if(I7)return I7($,J,Q);return x7().spawn($,J,Q)}var v7;function cX($,J,Q){if(v7)return v7($,J,Q);let X=x7();if(typeof X.spawnSync!=="function")return;return X.spawnSync($,J,Q)}var pX;function dX(){return pX??process.platform}function iX($){try{return process.kill($,0),!0}catch(J){if(J.code==="ESRCH")return!1;return!0}}function nX($){try{let J=cX("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 rX($){return new Promise((J)=>setTimeout(J,$))}async function aX($,J){if(!Number.isInteger($)||$<=0)throw Error(`Invalid PID: ${$} (must be a positive integer)`);let Q=dX(),X=J?.signal??"SIGKILL",W=J?.retry??3,Y=J?.retryDelayMs??500;R6.info(`[bg-process:kill-begin] pid=${$} signal=${X} retry=${W} delayMs=${Y}`);for(let G=1;G<=W;G++){let q=Q==="win32"?sX($):oX($,X,Q);if(await rX(Y),!(Q==="win32"?nX($):iX($)))return R6.info(`[bg-process:kill-done] pid=${$} attempts=${G} stillAlive=false`),{pid:$,platform:Q,signal:q.signal,success:!0,attempts:G,stillAlive:!1};if(G<W)R6.warn(`[bg-process:kill-retry] pid=${$} attempt=${G}/${W}`)}return R6.error(`[bg-process:kill-failed] pid=${$} attempts=${W} stillAlive=true`),{pid:$,platform:Q,signal:Q==="win32"?"taskkill /f /t":X,success:!1,attempts:W,stillAlive:!0}}function sX($){try{return lX("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 oX($,J,Q){try{return process.kill(-$,J),{pid:$,platform:Q,signal:J,success:!0}}catch(X){let W=X.code;if(W==="ESRCH"||W==="EPERM")return{pid:$,platform:Q,signal:J,success:!0};return{pid:$,platform:Q,signal:J,success:!1}}}a();var e9=n("task:process-registry");class $4{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);e9.info(`[bg-process:killAll-begin] count=${$.length} pids=[${$.join(",")}]`);for(let J of $)try{let Q=await aX(J,{retry:3,retryDelayMs:500});if(Q.stillAlive)e9.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{}e9.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var tX=new uX;function h7($,J){return tX.run($,J)}function eX(){if(_6!==void 0)return _6;let $=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return _6=$==="1"||$==="true"||$==="yes",_6}var _6;var $W=()=>{};function JW($){let J=()=>({recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!1,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter,errorIf:$?.errorIf});return function(Q,X,W){if(W!==void 0&&W!==null&&typeof W==="object"&&"value"in W){let q=W.value,H=$?.name||String(X);return W.value=U0(q,H,J()),W}let Y=Q,G=X||{};if(typeof Y==="function"){let q=$?.name||(G?.name?String(G.name):"anonymous");return U0(Y,q,J())}return Y}}function u($,J){return JW({name:$,...J})}function U0($,J,Q){let X={recordParams:Q?.recordParams??!0,recordResult:Q?.recordResult??!0,recordResultToDb:Q?.recordResultToDb??!1,logResult:Q?.logResult,recordError:Q?.recordError??!0,log:Q?.log??!1,maxLogSize:Q?.maxLogSize,paramFilter:Q?.paramFilter,resultFilter:Q?.resultFilter,flattenParamFilter:Q?.flattenParamFilter??!1,errorIf:Q?.errorIf},W=X.log,Y=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let O=a9();return O!==void 0?O:500},G=(O)=>{if(O===void 0)return;if(O===null)return null;let D=Y(),F;try{F=typeof O==="string"?O:JSON.stringify(O,null,0).replace(/\n/g,"")}catch(R){F=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}if(D>0&&F.length>D)return F.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(F)}catch{return F}},q=(O)=>{if(O===void 0)return"undefined";if(O===null)return"null";let D=Y(),F;try{F=typeof O==="string"?O:JSON.stringify(O,null,0).replace(/\n/g,"")}catch(R){F=`[Object with circular reference: ${R instanceof Error?R.message:String(R)}]`}return D>0&&F.length>D?F.slice(0,D)+" [TRUNCATED]":F},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(eX())return{value:O,store:!0};if(X.resultFilter){let F=D?.ran?D.value:U(()=>X.resultFilter(O));if(F&&typeof F==="object"&&!Array.isArray(F))return{value:F,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 F=D.stack?.split(`
|
|
385
|
+
`)||[];Error.stackTraceLimit=O;for(let R=1;R<F.length;R++){let _=F[R];if(_.includes("decorator.ts")||_.includes("decorator.js")||_.includes("logFn")||_.includes("getCallerLocation"))continue;let A=_.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||_.match(/at\s+(.+):(\d+):\d+/);if(A){let Z=A[1];if(!Z||Z==="native")continue;return`${r9(Z)}:${A[2]}`}}return""},M=(O,D,F)=>{if(!W)return;let R=n("traced:"+J),A=`[TRACE] ${O==="enter"?">>>":O==="quit"?"<<<":"!!!"} ${J}`,Z=F||V(),P=(w,f)=>{if(f!==void 0)R.info(`${A} ${w}: ${q(f)}`,{callerLocation:Z});else R.info(`${A} ${w}`,{callerLocation:Z})};if(O==="enter")P("enter",D);else if(O==="quit")P("quit",X.logResult??X.recordResult?D:void 0);else P("error",D)};return function(...O){let D=K2().getTracer("roy-tracer"),F={};if(X.recordParams!==!1)if(X.paramFilter){let A=U(()=>X.paramFilter(O));if(F.params=H(A),X.flattenParamFilter&&A&&typeof A==="object"&&!Array.isArray(A)){for(let[Z,P]of Object.entries(A))if(!(Z in F))F[Z]=H(P)}}else F.params=H(O);let R=V(),_;try{_=D.startSpan(J,{attributes:F})}catch{}M("enter",O,R);try{let A=$.call(this,...O);if(A&&typeof A==="object"&&typeof A.then==="function")return A.then((Z)=>{if(_){let P=X.resultFilter!==void 0,w=X.resultFilter?U(()=>X.resultFilter(Z)):void 0;if(w&&typeof w==="object"&&!Array.isArray(w))for(let[E,x]of Object.entries(w))_.setAttribute(E,H(x));let f=z(Z,{ran:P,value:w});if(f.store)_.setAttribute("result",JSON.stringify(H(f.value)));let N=X.errorIf?U(()=>X.errorIf(Z)):void 0;if(N){let E=N instanceof Error?N:Error(String(N));_.setAttribute("error",E.message),_.end(void 0,E)}else _.end(f.store?f.value:void 0)}return M("quit",X.logResult??X.recordResult?Z:void 0,R),Z},(Z)=>{if(_)_.setAttribute("error",String(Z)),_.end(void 0,Z instanceof Error?Z:Error(String(Z)));throw M("error",Z.message,R),Z});if(_){let Z=X.resultFilter!==void 0,P=X.resultFilter?U(()=>X.resultFilter(A)):void 0;if(P&&typeof P==="object"&&!Array.isArray(P))for(let[N,E]of Object.entries(P))_.setAttribute(N,H(E));let w=z(A,{ran:Z,value:P});if(w.store)_.setAttribute("result",JSON.stringify(H(w.value)));let f=X.errorIf?U(()=>X.errorIf(A)):void 0;if(f){let N=f instanceof Error?f:Error(String(f));_.setAttribute("error",N.message),_.end(void 0,N)}else _.end(w.store?w.value:void 0)}return M("quit",X.logResult??X.recordResult?A:void 0,R),A}catch(A){if(_)_.setAttribute("error",String(A)),_.end(void 0,A instanceof Error?A:Error(String(A)));throw M("error",A.message,R),A}}}var z0=r(()=>{t9(),a(),$W()});import{randomUUID as QW}from"crypto";z0();function XW(){if(typeof Bun<"u"){let{Database:$}=t("bun:sqlite");return $}else return t("better-sqlite3")}function WW($){let Q=new(XW())($);if(typeof Q.run!=="function")Q.run=function(X,...W){if(W.length>0)return this.prepare(X).run(...W);else return this.exec(X)};return Q}class J4{db;insertStmt;getByIdStmt;recentStmt;constructor($){this.db=WW($.dbPath);try{this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA synchronous=NORMAL"),this.db.exec("PRAGMA busy_timeout=5000")}catch{}this.db.exec(`CREATE TABLE IF NOT EXISTS event_store (
|
|
361
386
|
event_id TEXT PRIMARY KEY,
|
|
362
387
|
es_type TEXT NOT NULL,
|
|
363
388
|
sender_id TEXT NOT NULL,
|
|
@@ -372,7 +397,7 @@ Parameters:
|
|
|
372
397
|
FROM event_store
|
|
373
398
|
WHERE es_type = ? AND sender_id = ?
|
|
374
399
|
ORDER BY created_at DESC
|
|
375
|
-
LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${
|
|
400
|
+
LIMIT ?`)}async insertTriggerEvent($,J){let Q=`evt_${Date.now()}_${QW()}`,X=Date.now(),W=JSON.stringify($.metadata??{}),Y=$.rawEvent===void 0?null:YW($.rawEvent);return this.insertStmt.run(Q,J,$.senderId,$.text??null,W,Y,X),Q}async getEventById($){let J=this.getByIdStmt.get($);if(!J)return null;return y7(J)}async getRecentEvents($,J,Q){return this.recentStmt.all($,J,Q).map((W)=>y7(W))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],J4.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],J4.prototype,"getEventById",null);function y7($){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 YW($){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 GW=null;function g7(){return GW}var Q4={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
|
|
376
401
|
|
|
377
402
|
## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
|
|
378
403
|
|
|
@@ -497,7 +522,7 @@ Parameters:
|
|
|
497
522
|
- \u2705 \u529F\u80FD\u5F00\u53D1\u3001bug \u4FEE\u590D\u3001\u91CD\u6784\u3001\u6587\u6863\u751F\u6210
|
|
498
523
|
- \u2705 \u7F51\u7EDC\u641C\u7D22\u548C\u7814\u7A76
|
|
499
524
|
|
|
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${
|
|
525
|
+
**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${q2}\uFF1A\u6309\u5B50\u9879\u9010\u6761\u9A8C\u6536\uFF08${G2}\uFF09\uFF0C\u82E5\u6536\u5230 [${B$}] \u5FC5\u987B\u6838\u5B9E\u5E76\u4E8C\u9009\u4E00\uFF08\u91CD\u5F00 / \u843D decision \u8BF4\u660E\u7406\u7531\uFF09\u3002
|
|
501
526
|
|
|
502
527
|
\u63A8\u8350\u4F7F\u7528\uFF1A
|
|
503
528
|
\`\`\`
|
|
@@ -715,7 +740,7 @@ delegate_task({
|
|
|
715
740
|
#### \u4F55\u65F6\u4F7F\u7528 query_background_process
|
|
716
741
|
|
|
717
742
|
\u2705 **\u5E94\u8BE5\u7528**\uFF1A
|
|
718
|
-
- \u59D4\u6258\u4E86\u4E00\u4E2A**\u957F\u4EFB\u52A1**\uFF08timeout \u2265 5 \u5206\u949F\uFF09\uFF0C\u8FC7\u53BB
|
|
743
|
+
- \u59D4\u6258\u4E86\u4E00\u4E2A**\u957F\u4EFB\u52A1**\uFF08timeout \u2265 5 \u5206\u949F\uFF09\uFF0C\u8FC7\u53BB 20+ \u5206\u949F\u8FD8\u6CA1\u6536\u5230\u4EFB\u4F55\u901A\u77E5\uFF0C\u4E3B\u52A8\u786E\u8BA4\u662F\u5426\u8FD8\u6D3B\u7740
|
|
719
744
|
- \u7528\u6237**\u4E3B\u52A8\u95EE**"\u90A3\u4E2A\u4EFB\u52A1\u8FDB\u5C55\u600E\u4E48\u6837\u4E86\uFF1F"\u2014\u2014\u9700\u8981\u6700\u65B0\u5FEB\u7167\u800C\u4E0D\u662F\u7B49\u901A\u77E5
|
|
720
745
|
- \u6000\u7591\u540E\u53F0\u4EFB\u52A1**\u5361\u4F4F**\uFF08\u6700\u540E\u4E00\u6761 progress \u901A\u77E5\u662F\u8F83\u4E45\u4EE5\u524D\u3001\u5B50\u4EFB\u52A1\u660E\u663E\u5E94\u8BE5\u63A8\u8FDB\u4F46\u6CA1\u52A8\u9759\uFF09
|
|
721
746
|
- \u6536\u5230 timeout / failed \u901A\u77E5\uFF0C\u4F46\u9700\u8981\u786E\u8BA4**\u771F\u5B9E\u72B6\u6001**\uFF08\u907F\u514D\u8BEF\u5224 timeout \u540E\u53C8\u88AB\u901A\u77E5\u8BF4\u5B8C\u6210\u4E86\uFF09
|
|
@@ -728,11 +753,15 @@ delegate_task({
|
|
|
728
753
|
|
|
729
754
|
#### \u67E5\u8BE2\u9891\u7387\u5EFA\u8BAE
|
|
730
755
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
-
|
|
756
|
+
> \u6821\u51C6\u4F9D\u636E\uFF1Aprogress \u5FC3\u8DF3\u95F4\u9694\u662F **20 \u5206\u949F**\uFF08\`PROGRESS_INTERVAL\`\uFF09\u3002\u9996\u6761\u5FC3\u8DF3\u5728\u59D4\u6258\u540E\u7B2C 20 \u5206\u949F\u624D\u5230\uFF0C\u6240\u4EE5\u300C20 \u5206\u949F\u5185\u6CA1\u901A\u77E5\u300D\u662F**\u5B8C\u5168\u6B63\u5E38**\u7684\uFF0C\u4E0D\u9700\u8981\u67E5\u3002
|
|
757
|
+
|
|
758
|
+
- **\u59D4\u6258\u540E 20 \u5206\u949F\u5185**\uFF1A\u5B8C\u5168\u4E0D\u9700\u8981\u67E5\uFF0C\u7B49\u901A\u77E5
|
|
759
|
+
- **20-40 \u5206\u949F\u65E0\u901A\u77E5**\uFF1A\u53EF\u4EE5\u67E5\u4E00\u6B21\u786E\u8BA4 alive \u72B6\u6001\uFF0C\u7136\u540E\u7EE7\u7EED\u7B49
|
|
760
|
+
- **40+ \u5206\u949F\u65E0\u901A\u77E5**\uFF08\u4EC5\u5BF9 timeout > 40 \u5206\u949F\u7684\u957F\u4EFB\u52A1\u53EF\u8FBE\uFF1B\u9ED8\u8BA4 30 \u5206\u949F timeout \u65E9\u8BE5\u6536\u5230 timeout \u901A\u77E5\u4E86\uFF09\uFF1A\u53EF\u4EE5\u6BCF 10 \u5206\u949F\u67E5\u4E00\u6B21\uFF0C\u5173\u6CE8 status \u662F\u5426\u4ECD\u4E3A "running"
|
|
734
761
|
- **\u6536\u5230 timeout \u901A\u77E5\u540E**\uFF1A\u7ACB\u523B\u67E5\u4E00\u6B21\uFF0C\u786E\u8BA4\u6700\u7EC8\u72B6\u6001\u518D\u51B3\u5B9A\u4E0B\u4E00\u6B65
|
|
735
762
|
|
|
763
|
+
> \uD83D\uDCA1 \u67E5\u56DE\u6765\u82E5 \`alive: true\`\uFF0C\u91CD\u70B9\u770B \`messageCount\` / \`subSessionUpdatedAt\`\uFF08\u771F\u5B9E liveness \u4FE1\u53F7\uFF09\uFF1A\`messageCount\` \u5728\u6DA8\u8BF4\u660E sub-agent \u786E\u5B9E\u5728\u5E72\u6D3B\uFF0C\`lastUpdatedAt\` \u505C\u6EDE\u624D\u8BF4\u660E\u53EF\u80FD\u5361\u4F4F \u2014\u2014 \u4E0D\u8981\u53EA\u770B \`lastUpdatedAt\`\uFF08\u5B83\u6700\u7EC6\u4E5F\u53EA\u6709 20 \u5206\u949F\u7C92\u5EA6\uFF09\u3002
|
|
764
|
+
|
|
736
765
|
#### \u8FD4\u56DE\u503C\u7ED3\u6784
|
|
737
766
|
|
|
738
767
|
\u5DE5\u5177\u8FD4\u56DE JSON \u5B57\u7B26\u4E32\uFF1A
|
|
@@ -743,6 +772,8 @@ delegate_task({
|
|
|
743
772
|
"status": "running", // pending | running | completed | failed | stopped | timeout | not_found
|
|
744
773
|
"createdAt": 1721000000000, // \u542F\u52A8\u65F6\u95F4\u6233\uFF08ms\uFF09
|
|
745
774
|
"lastUpdatedAt": 1721000060000, // \u6700\u540E\u72B6\u6001\u66F4\u65B0\u65F6\u95F4\u6233\uFF08ms\uFF09
|
|
775
|
+
"messageCount": 42, // \u4EC5 alive \u65F6\u63D0\u4F9B\uFF1Asub-session \u6D88\u606F\u6570\uFF08\u771F\u5B9E\u6D3B\u8DC3\u5EA6\uFF09
|
|
776
|
+
"subSessionUpdatedAt": 1721001234000, // \u4EC5 alive \u65F6\u63D0\u4F9B\uFF1Asub-session \u6700\u540E\u5199\u5165\u65F6\u523B
|
|
746
777
|
"description": "\u5B9E\u73B0\u52A0\u6CD5\u51FD\u6570", // delegate_task \u4F20\u5165\u7684 description
|
|
747
778
|
"result": "\u5DF2\u5B8C\u6210\uFF0C\u5B9E\u73B0\u4EE3\u7801\u5728 ...", // \u4EC5 completed \u72B6\u6001\u6709
|
|
748
779
|
"error": "..." // \u4EC5 failed \u72B6\u6001\u6709
|
|
@@ -761,7 +792,7 @@ const result = await delegate_task({
|
|
|
761
792
|
});
|
|
762
793
|
// result.bgProcessId \u5F62\u5982 "process_1721000000000_abc12345"
|
|
763
794
|
|
|
764
|
-
// ...\u7B49
|
|
795
|
+
// ...\u7B49 20 \u5206\u949F\u6CA1\u6536\u5230\u901A\u77E5\uFF0C\u4E3B\u52A8\u67E5\u8BE2
|
|
765
796
|
const status = await query_background_process({ bgProcessId: result.bgProcessId });
|
|
766
797
|
// status.alive === true \u2192 \u8FD8\u5728\u8DD1\uFF0C\u7EE7\u7EED\u7B49
|
|
767
798
|
// status.alive === false && status.status === "completed" \u2192 \u4EFB\u52A1\u5DF2\u5B8C\u6210\uFF0C\u770B status.result
|
|
@@ -1191,163 +1222,7 @@ roy-agent <command> <subcmd> --help
|
|
|
1191
1222
|
| \`delegate_task\` | \u5B50 agent \u59D4\u6258\u5165\u53E3\uFF0C\u7531 \`default\` \u63A5\u5F85\u5458\u72EC\u5360 | \u76F4\u63A5\u7528 \`bash\` / \`read_file\` / \`edit_file\` \u7B49\u5DE5\u5177\u81EA\u5DF1\u5B8C\u6210\u4EFB\u52A1\uFF1B\u82E5\u662F\u771F\u6B63\u7684\u590D\u6742\u591A\u6B65\u4EFB\u52A1\uFF0C\u5EFA\u8BAE\u7528\u6237\u5207\u6362\u5230 \`default\` agent |
|
|
1192
1223
|
| \`stop_task\` | \u540E\u53F0\u8FDB\u7A0B\u7BA1\u7406\u5165\u53E3\uFF0C\u7531 \`default\` \u63A5\u5F85\u5458\u72EC\u5360 | \u4F60\u65E0\u6CD5\u542F\u52A8\u540E\u53F0\u8FDB\u7A0B\uFF0C\u81EA\u7136\u4E0D\u9700\u8981 \`stop_task\` |
|
|
1193
1224
|
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
Follow this lifecycle for every task:
|
|
1197
|
-
|
|
1198
|
-
\`\`\`text
|
|
1199
|
-
\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
|
|
1200
|
-
\u2502 0. CHECK TASK CONTEXT OR SEARCH \u2502
|
|
1201
|
-
\u2502 - First: Check if [\u5F53\u524D Task #N] is in the context \u2502
|
|
1202
|
-
\u2502 If yes \u2192 use \`task_get #N\` directly, skip to step 1 \u2502
|
|
1203
|
-
\u2502 - If no taskId in context: \u2502
|
|
1204
|
-
\u2502 Use \`task_list\` to search for existing related tasks \u2502
|
|
1205
|
-
\u2502 - If found \u2192 reuse, extend, and update (see rules below) \u2502
|
|
1206
|
-
\u2502 - If not found \u2192 proceed to step 1 \u2502
|
|
1207
|
-
\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
|
|
1208
|
-
\u2193
|
|
1209
|
-
\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
|
|
1210
|
-
\u2502 1. CREATE (task_create) OR REUSE (task_get + task_update) \u2502
|
|
1211
|
-
\u2502 - No existing task \u2192 Create new with title, desc, goals \u2502
|
|
1212
|
-
\u2502 - Existing task \u2192 Reuse via task_get, then task_update: \u2502
|
|
1213
|
-
\u2502 * Append new context to description (preserve old) \u2502
|
|
1214
|
-
\u2502 * Add/extend goals_and_expected_deliverables \u2502
|
|
1215
|
-
\u2502 * Create operation record documenting the continuation \u2502
|
|
1216
|
-
\u2502 - Set priority (low/medium/high) and due date (if any) \u2502
|
|
1217
|
-
\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
|
|
1218
|
-
\u2193
|
|
1219
|
-
\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
|
|
1220
|
-
\u2502 2. GATHER CONTEXT (task_get + task_operation_list) \u2502
|
|
1221
|
-
\u2502 - Read description, goals, current_status \u2502
|
|
1222
|
-
\u2502 - Check parent_task_id for sub-tasks \u2502
|
|
1223
|
-
\u2502 - Review recent operations for history and decisions \u2502
|
|
1224
|
-
\u2502 \u2502
|
|
1225
|
-
\u2502 \u26A0\uFE0F REQUIRED: Never skip this step. Working without context \u2502
|
|
1226
|
-
\u2502 risks: outdated goals, missed decisions, duplicated work \u2502
|
|
1227
|
-
\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
|
|
1228
|
-
\u2193
|
|
1229
|
-
\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
|
|
1230
|
-
\u2502 3. EXECUTE \u2502
|
|
1231
|
-
\u2502 - \u5229\u7528\u5404\u79CD\u5DE5\u5177\u548C\u80FD\u529B\uFF0Cskill\uFF0Cworkflow\u7B49\u6765\u89E3\u51B3\u4EFB\u52A1\u8FBE\u5230\u4EFB\u52A1\u63CF\u8FF0 \u2502
|
|
1232
|
-
\u2502 \u548C\u4EFB\u52A1\u76EE\u6807\u8981\u6C42 \u2502
|
|
1233
|
-
\u2502 \u2502
|
|
1234
|
-
\u2502 Long-running work guidance: \u2502
|
|
1235
|
-
\u2502 - \u8D85\u8FC7 5 \u5206\u949F\u7684\u590D\u6742\u4EFB\u52A1\uFF1A\u7528 \`task_operation_create\` \u2502
|
|
1236
|
-
\u2502 \u8BB0\u5F55\u91CC\u7A0B\u7891\uFF0C\u8BA9\u7528\u6237\u80FD\u770B\u5230\u5B9E\u65F6\u8FDB\u5C55 \u2502
|
|
1237
|
-
\u2502 - \u591A\u4E2A\u72EC\u7ACB\u5B50\u4EFB\u52A1\u53EF\u5E76\u884C\uFF1A\u7528 \`bash &\` \u540E\u53F0\u542F\u52A8\u6216 \u2502
|
|
1238
|
-
\u2502 \u62C6\u5206\u6210\u591A\u4E2A\u5E76\u884C ReAct \u6B65\u9AA4 \u2502
|
|
1239
|
-
\u2502 \u2502
|
|
1240
|
-
\u2502 \u26A0\uFE0F Note: \u4E0D\u9700\u8981\u624B\u52A8\u8C03\u7528 \`task_operation_create\` \u8DDF\u8E2A \u2502
|
|
1241
|
-
\u2502 task_create / task_update \u7B49\u64CD\u4F5C\u4E5F\u4F1A\u81EA\u52A8\u521B\u5EFA\u8BB0\u5F55\u3002 \u2502
|
|
1242
|
-
\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
|
|
1243
|
-
\u2193
|
|
1244
|
-
\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
|
|
1245
|
-
\u2502 4. TRACK (task_update) \u2502
|
|
1246
|
-
\u2502 - Update progress (0-100%) as work advances \u2502
|
|
1247
|
-
\u2502 - Update status: todo \u2192 active \u2192 completed \u2502
|
|
1248
|
-
\u2502 - Can also set paused or cancelled status \u2502
|
|
1249
|
-
\u2502 - Record current_status with human-readable progress \u2502
|
|
1250
|
-
\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
|
|
1251
|
-
\u2193
|
|
1252
|
-
\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
|
|
1253
|
-
\u2502 5. RECORD (task_operation_create) \u2014 **\u53CC\u7EF4\u5EA6\u5206\u5DE5** \u2502
|
|
1254
|
-
\u2502 - **\u72B6\u6001/\u91CC\u7A0B\u7891\u7EF4\u5EA6**\uFF1A\u7528 milestone_type / milestone_title / \u2502
|
|
1255
|
-
\u2502 milestone_description \u63CF\u8FF0"\u8FBE\u6210\u7684\u72B6\u6001/\u91CC\u7A0B\u7891"\u3002 \u2502
|
|
1256
|
-
\u2502 - **\u8FC7\u7A0B\u7EF4\u5EA6**\uFF1A\u7528 process_description\uFF08100-500 \u5B57\u7B26\uFF09 \u2502
|
|
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
|
|
1258
|
-
\u2502 - \u26A0\uFE0F **\u4E0D\u8981\u628A action \u5F53\u72B6\u6001**\uFF0C\u4E5F\u4E0D\u8981\u8BA9 process_description \u4E0E \u2502
|
|
1259
|
-
\u2502 milestone_description \u91CD\u590D\u3002 \u2502
|
|
1260
|
-
\u2502 - \u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session \u5386\u53F2\u3002 \u2502
|
|
1261
|
-
\u2502 - \u8FD9\u4E9B\u8BB0\u5F55\u5F62\u6210\u4EFB\u52A1\u7684\u5386\u53F2\u4E0E\u4E0A\u4E0B\u6587\u3002 \u2502
|
|
1262
|
-
\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
|
|
1263
|
-
\u2193
|
|
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
|
|
1265
|
-
\u2502 6. COMPLETE (task_complete) \u2502
|
|
1266
|
-
\u2502 - Mark task as completed (progress=100%, status=completed) \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
|
|
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
|
|
1275
|
-
\`\`\`
|
|
1276
|
-
|
|
1277
|
-
### Task Update Rules
|
|
1278
|
-
|
|
1279
|
-
When reusing an existing task, you MUST follow these rules:
|
|
1280
|
-
|
|
1281
|
-
1. **Append, don't replace** \u2014 When using \`task_update\`, the \`description\` and \`goals\` fields MUST **preserve existing content** and append new content after it.
|
|
1282
|
-
2. **Document the continuation** \u2014 Use \`task_operation_create\` to create an operation record explaining why the task is being continued and what new scope has been added.
|
|
1283
|
-
3. **Reset the status** \u2014 If the original task was completed, change status to \`active\` and reset progress to a reasonable value.
|
|
1284
|
-
|
|
1285
|
-
### Task Properties
|
|
1286
|
-
|
|
1287
|
-
| Property | Description |
|
|
1288
|
-
|----------|-------------|
|
|
1289
|
-
| **title** | Brief task title |
|
|
1290
|
-
| **description** | Detailed description of what needs to be done |
|
|
1291
|
-
| **goals_and_expected_deliverables** | Clear success criteria and expected outputs |
|
|
1292
|
-
| **status** | todo \u2192 active \u2192 completed (or paused, cancelled) |
|
|
1293
|
-
| **progress** | 0-100 percentage of completion |
|
|
1294
|
-
| **current_status** | Human-readable status describing current work |
|
|
1295
|
-
| **priority** | low, medium, high |
|
|
1296
|
-
| **parent_task_id** | Parent task ID (if this is a sub-task) |
|
|
1297
|
-
|
|
1298
|
-
### Task Operation Record \u2014 \u53CC\u7EF4\u5EA6\u5206\u5DE5\u89C4\u8303 (Task #2211)
|
|
1299
|
-
|
|
1300
|
-
**\u64CD\u4F5C\u8BB0\u5F55\u5FC5\u987B\u4E25\u683C\u533A\u5206\u4E24\u4E2A\u7EF4\u5EA6\uFF0C\u4E8C\u8005\u914D\u5957\u8BB0\u5F55\u3001\u5404\u53F8\u5176\u804C**\uFF1A
|
|
1301
|
-
|
|
1302
|
-
#### \u7EF4\u5EA6 1\uFF1A\u72B6\u6001/\u91CC\u7A0B\u7891\uFF08"\u8FBE\u5230\u4EC0\u4E48"\uFF09\u2014 \u5FC5\u586B\u7EF4\u5EA6
|
|
1303
|
-
\u4F7F\u7528 \`task_operation_create\` \u7684 milestone_* \u4E3B\u5B57\u6BB5\uFF1A
|
|
1304
|
-
- **milestone_type**\uFF1A\u91CC\u7A0B\u7891\u7C7B\u578B\uFF08create / progress / milestone / problem / solution / decision / review / completed\uFF09
|
|
1305
|
-
- **milestone_title**\uFF1A\u91CC\u7A0B\u7891\u6807\u9898\uFF08\u4E00\u884C\uFF09
|
|
1306
|
-
- **milestone_description**\uFF1A\u8FBE\u6210\u7684\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\uFF08\u53EF\u957F\u53EF\u77ED\uFF09
|
|
1307
|
-
|
|
1308
|
-
#### \u7EF4\u5EA6 2\uFF1A\u8FC7\u7A0B\uFF08"\u5982\u4F55\u8FBE\u5230"\uFF09\u2014 \u53EF\u9009\u4F46\u63A8\u8350\u7EF4\u5EA6
|
|
1309
|
-
\u4F7F\u7528 \`task_operation_create\` \u7684 \`process_description\` \u5B57\u6BB5\uFF1A
|
|
1310
|
-
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-500 \u5B57\u7B26
|
|
1311
|
-
- \u5185\u5BB9\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981
|
|
1312
|
-
- \u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session
|
|
1313
|
-
|
|
1314
|
-
#### \u53CC\u7EF4\u5EA6\u914D\u5408\u94C1\u5F8B
|
|
1315
|
-
- \u274C **\u4E0D\u8981\u628A action \u5F53\u72B6\u6001**\uFF1A\u65E7 \`action_*\` \u547D\u540D\u504F\u52A8\u4F5C/\u884C\u4E3A\u5C42\uFF0C\u4E0D\u80FD\u8868\u8FBE"\u6B64\u523B\u8FBE\u5230\u4EC0\u4E48"\uFF1B\u73B0\u5728\u7EDF\u4E00\u6539\u7528 \`milestone_*\`\u3002
|
|
1316
|
-
- \u274C **\u4E0D\u8981\u8BA9 process_description \u4E0E milestone_description \u91CD\u590D**\uFF1Aprocess \u662F"\u5982\u4F55\u8FBE\u5230"\uFF0Cmilestone \u662F"\u8FBE\u5230\u4EC0\u4E48\u72B6\u6001"\u3002
|
|
1317
|
-
- \u2705 **\u914D\u5957\u8BB0\u5F55**\uFF1A\u6BCF\u4E2A\u6709\u610F\u4E49\u7684 operation \u90FD\u5E94\u540C\u65F6\u5305\u542B\u4E24\u8005\uFF1B\u4E0D\u5199 process \u65F6\uFF0Cdetail \u5E94\u901A\u8FC7 sessionId \u56DE\u67E5\u3002
|
|
1318
|
-
- \u26A0\uFE0F **\u517C\u5BB9\u7A97\u53E3\u671F**\uFF1A\u65E7 \`action_type\` / \`action_title\` / \`action_description\` \u4ECD\u88AB tool \u63A5\u53D7\uFF08\u6807\u8BB0 @deprecated\uFF09\uFF0C\u4F1A\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5E76\u8FD4\u56DE deprecation warning\u3002
|
|
1319
|
-
|
|
1320
|
-
#### \u8303\u4F8B\uFF08\u53CC\u7EF4\u5EA6\u9F50\u5168\u7684 operation \u8BB0\u5F55\uFF09
|
|
1321
|
-
\`\`\`json
|
|
1322
|
-
{
|
|
1323
|
-
"task_id": 123,
|
|
1324
|
-
"milestone_type": "milestone",
|
|
1325
|
-
"milestone_title": "GREEN \u901A\u8FC7\uFF1Amilestone_* schema/storage/tool \u5168\u94FE\u8DEF",
|
|
1326
|
-
"milestone_description": "21/21 \u6D4B\u8BD5\u901A\u8FC7\uFF0C\u5305\u542B 4 \u4E2A action_* alias \u517C\u5BB9\u6D4B\u8BD5",
|
|
1327
|
-
"process_description": "TDD RED \u5199 4 \u4E2A\u5931\u8D25\u6D4B\u8BD5\u8986\u76D6 storage/tool\uFF1B\u8FC1\u79FB 004 rename \u5217\uFF1BrowToOperation \u540C\u65F6\u8F93\u51FA\u53CC\u5B57\u6BB5\u517C\u5BB9\uFF1Btool zod preprocess \u81EA\u52A8\u6620\u5C04 action_*"
|
|
1328
|
-
}
|
|
1329
|
-
\`\`\`
|
|
1330
|
-
|
|
1331
|
-
### Task Context Awareness
|
|
1332
|
-
|
|
1333
|
-
**Before starting any task-related work, you MUST gather context:**
|
|
1334
|
-
|
|
1335
|
-
**Step 0: Check for Task ID in Context**
|
|
1336
|
-
- If the system provides \`[\u5F53\u524D Task #N]\` in the context messages:
|
|
1337
|
-
Use \`task_get #N\` directly \u2014 this is your confirmed task. **Skip searching.**
|
|
1338
|
-
- If no taskId is provided, use \`task_list\` to search for existing related tasks.
|
|
1339
|
-
|
|
1340
|
-
**Then gather full context:**
|
|
1341
|
-
1. **Read task details**: Use \`task_get\` to read description, goals, status
|
|
1342
|
-
2. **Read operation history**: Use \`task_operation_list\` to get the last ~20 operation records
|
|
1343
|
-
3. **Read parent context** (if \`parent_task_id\` exists): Understand overall goal
|
|
1344
|
-
|
|
1345
|
-
**Why context matters**: Without it, you risk:
|
|
1346
|
-
- Working on outdated or wrong goals
|
|
1347
|
-
- Missing critical decisions made in operations
|
|
1348
|
-
- Losing parent task alignment
|
|
1349
|
-
- Duplicating or conflicting work
|
|
1350
|
-
|
|
1225
|
+
${E9}
|
|
1351
1226
|
### {{memory}}`,coding:`You are an expert coding assistant.
|
|
1352
1227
|
|
|
1353
1228
|
## Your Approach
|
|
@@ -2114,8 +1989,8 @@ task_operation_create({
|
|
|
2114
1989
|
\u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
|
|
2115
1990
|
|
|
2116
1991
|
> \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
|
|
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
|
|
1992
|
+
`},pM=Q4["workflow-extract"];var Q0={BEFORE_CREATE:"task:before.create",AFTER_CREATE:"task:after.create",BEFORE_UPDATE:"task:before.update",AFTER_UPDATE:"task:after.update",BEFORE_DELETE:"task:before.delete",AFTER_DELETE:"task:after.delete",AFTER_COMPLETE:"task:after.complete",DELEGATE_BEFORE:"task:delegate:before",DELEGATE_AFTER:"task:delegate:after",OPERATION_BEFORE_CREATE:"task:operation:before.create",OPERATION_AFTER_CREATE:"task:operation:after.create"};import k7 from"os";import M0 from"path";var L6="roy-agent";function qW(){let $=k7.homedir();try{let J=t("xdg-basedir");return{config:J.xdgConfig||M0.join($,".config"),state:J.xdgState||M0.join($,".local","state"),data:J.xdgData||M0.join($,".local","share"),cache:J.xdgCache||M0.join($,".cache")}}catch{return{config:M0.join($,".config"),state:M0.join($,".local","state"),data:M0.join($,".local","share"),cache:M0.join($,".cache")}}}function HW(){let $=k7.homedir(),J=qW();return{home:$,config:M0.join(J.config,L6),state:M0.join(J.state,L6),data:M0.join(J.data,L6),cache:M0.join(J.cache,L6)}}class m7{_paths;get paths(){if(!this._paths)this._paths=HW();return this._paths}getPath($){return this.paths[$]}getComponentPath($,J){return M0.join(this.paths[$],J)}reset(){this._paths=void 0}}var BW=new m7;function u7($){return BW.getPath($)}import*as BD from"fs/promises";import*as UD from"fs";import{join as J2}from"path";var F8=u1(oJ(),1);a();z0();var $0=n("agent:registry"),O8=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 _0{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor($){this.configComponent=$.configComponent,this.promptComponent=$.promptComponent??null,this.resolvePromptComponent=$.resolvePromptComponent,this.fs=$.fs||UD,this.fsPromises=$.fsPromises||BD;let J=this.configComponent?.get?.("agent.configDir");if(J&&typeof J==="string"&&J.length>0)this.configDir=J;else if($.baseDir)this.configDir=J2($.baseDir,"agents");else this.configDir=J2(u7("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=O8.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 W=await Q.getPrompt(J.systemPromptRef,{},{agentType:J.type});if(W)return $0.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${J.systemPromptRef}`),W}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 W=J2($,X.name);if(X.isDirectory())continue;if(!VD(X.name))continue;try{let Y=await this.fsPromises.readFile(W,"utf-8"),G=this.parseAgentConfig(Y,W);if(G)this.agents.set(G.name,G),$0.info(`[AgentRegistry] Loaded agent: ${G.name} from ${X.name}`),J++}catch(Y){$0.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${Y}`)}}$0.info(`[AgentRegistry] Loaded ${J} agents from ${$}`)}catch(Q){$0.warn(`[AgentRegistry] Error reading config directory: ${Q}`)}return J}parseAgentConfig($,J){try{let Q=F8.default.parse($),X=O8.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=O8.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=J2(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 F8.default.stringify(J).trimEnd()+`
|
|
1993
|
+
`}async deleteAgent($){if(!this.agents.get($))return $0.warn(`[AgentRegistry] Agent not found: ${$}`),!1;try{let Q=J2(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 J2(this.configDir,`${$}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],_0.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],_0.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],_0.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],_0.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],_0.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],_0.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],_0.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],_0.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],_0.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],_0.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],_0.prototype,"loadFromDirectory",null);function VD($){return $.endsWith(".yaml")||$.endsWith(".yml")}var M8=`You are a subagent created by the main agent to handle a specific task.
|
|
2119
1994
|
|
|
2120
1995
|
## Your Role
|
|
2121
1996
|
- You were created to handle: {task_description}
|
|
@@ -2132,14 +2007,14 @@ task_operation_create({
|
|
|
2132
2007
|
## Execution
|
|
2133
2008
|
- Use the available tools to complete the task
|
|
2134
2009
|
- If you need more information, ask the main agent through the result
|
|
2135
|
-
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as
|
|
2010
|
+
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as zD}from"async_hooks";var DD=new zD;function K8($,J){return DD.run($,J)}import{AsyncLocalStorage as OD}from"async_hooks";var R8=()=>{};function Q2(){return u2.getStore()}function U9(){return u2.getStore()||{}}function l2(){return u2.getStore()?.agentContext?.currentTaskId}function tJ($){return typeof $==="number"&&Number.isInteger($)&&$>0?$:void 0}var eJ,u2,FD,c2,q$=r(()=>{a(),z0(),R8(),eJ=n("env:context:env-context"),u2=new OD,FD=U0(function(J,Q){return tJ(J?.metadata?.parentTaskId)??tJ(Q?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:($)=>({parentTaskId:$??null})}),c2=U0(function(J){let Q=l2(),X=u2.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=J}eJ.info(`[setCurrentTaskId] taskId=${J??"undefined"} (was: ${Q??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var V9=r(()=>{q$(),R8()});class z9{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor($={}){this.componentName=$.componentName??"unknown",this.componentVersion=$.componentVersion??"0.0.0",this.defaultPriority=$.defaultPriority??0}register($,J){this.getOrCreateHooks($).push(J)}registerMany($,J){this.getOrCreateHooks($).push(...J)}unregister($,J){let Q=this._hooks.get($);if(!Q)return!1;let X=Q.findIndex((W)=>W.name===J);if(X===-1)return!1;return Q.splice(X,1),!0}unregisterAll($){this._hooks.delete($)}async execute($,J,Q={}){let X=this._hooks.get($),W=process.env.ROY_HOOK_DEBUG==="1";if(W)console.error(`[DEBUG hook-manager.execute] hookPoint=${$}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(W)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${$})`);return}let Y=Q2();if(W){if(console.error(`[DEBUG hook-manager.execute] envContext=${Y?"present":"absent"}`),Y)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(Y.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${Y.sourceId}`)}if(Y){if(Q.envContext=Y,!Q.pluginEnabled&&Y.pluginEnabled)Q.pluginEnabled=Y.pluginEnabled}let G=this.sortHooks(X),q=this.createContext($,J,Q,"before"),H=Q.pluginEnabled||{};if(W){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(H)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${G.length}:`);for(let B of G)console.error(`[DEBUG hook-manager.execute] - name=${B.name} pluginName=${B.pluginName} sourceId=${B.sourceId}`)}for(let B of G){if(B.pluginName&&B.sourceId){let U=`${B.sourceId}:${B.pluginName}`,z=H[U];if(W)console.error(`[DEBUG hook-manager.execute] hook ${B.name} (${U}) enabled=${z}`);if(z!==!0){if(W)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${U}] !== true, got ${JSON.stringify(z)})`);continue}}else if(W)console.error(`[DEBUG hook-manager.execute] hook ${B.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(W)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${B.name}`);await this.safeExecute(B,q)}}async executeAndCollect($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return[];let W=this.sortHooks(X),Y=this.createContext($,J,Q,"before"),G=[];for(let q of W){let H=await this.safeExecuteAndReturn(q,Y);if(H!==void 0)G.push(H)}return G}count($){return this._hooks.get($)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks($){return this.count($)>0}setComponentInfo($,J){this.componentName=$,this.componentVersion=J}get hooks(){return this._hooks}async executeWithIntervention($,J,Q={}){let X=this._hooks.get($);if(!X||X.length===0)return{stopped:!1,results:[]};let W=this.sortHooks(X),Y=this.createContext($,J,Q,"before"),G=[],q=!1,H;for(let B of W){if(q)break;let U=await this.safeExecuteAndReturn(B,Y);if(G.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:G}}getOrCreateHooks($){let J=this._hooks.get($);if(!J)J=[],this._hooks.set($,J);return J}sortHooks($){return[...$].sort((J,Q)=>{let X=J.priority??this.defaultPriority,W=Q.priority??this.defaultPriority;return X-W})}createContext($,J,Q,X){return{component:{name:this.componentName,version:this.componentVersion},data:J,metadata:Q,phase:X,hookPoint:$}}async safeExecute($,J){try{let Q=$.execute(J);if(Q&&typeof Q==="object"&&typeof Q.then==="function")await Q}catch(Q){console.error(`Hook "${$.name}" failed:`,Q)}}async safeExecuteAndReturn($,J){try{return await $.execute(J)}catch(Q){console.error(`Hook "${$.name}" failed:`,Q);return}}}var _8=r(()=>{V9()});function MD(){let $=E0.register.bind(E0);E0.register=function(J,Q){$(J,Q);let X=$3[J];if(X)$(X,Q)}}var E0,KD,RD,_D,$3,X2=r(()=>{_8(),E0=new z9,KD={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"},RD={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},_D={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"},$3={"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"},MD()});a();z0();V9();function LD($,J){if(N8($))return!0;return J?.hasAgent($)??!1}async function AD($,J={}){let X=(J.getBuiltIn??N8)($),W=J.registry?.get($);if(!X&&!W)return;if(W)return jD($,W,X,J.registry);return{subagentType:$,description:X.description,basePrompt:X.promptOverride||M8,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function jD($,J,Q,X){let W=X?await X.getSystemPrompt($):J.systemPrompt;return{subagentType:$,description:J.description||Q?.description||"Custom agent",basePrompt:W||Q?.promptOverride||M8,allowedTools:J.allowedTools??Q?.allowedTools,deniedTools:J.deniedTools??Q?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function ND($){return`
|
|
2136
2011
|
## Agent Selection Guide
|
|
2137
2012
|
|
|
2138
2013
|
- Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
|
|
2139
2014
|
${$.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
|
|
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=
|
|
2015
|
+
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function ZD($){let J=A8.map((G)=>`- ${G.id}: ${G.description}`),X=($?.list()??[]).filter((G)=>!A8.some((q)=>q.id===G.name)).map((G)=>{if(G.type==="workflow"){let q=G.workflow?` (workflow: ${G.workflow})`:"";return`- ${G.name}: ${G.description||"Workflow agent"}${q}`}return`- ${G.name}: ${G.description||"Custom agent"}`}),W=[...J,...X],Y=ND({hasCustomAgents:X.length>0});return W.join(`
|
|
2016
|
+
`)+Y}X2();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 PD($,J){if($.length<=J)return $;if(J<=3)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function J3($,J){return PD(bD($),J)}class j8{maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor($={}){this.maxEntries=$.maxEntries??500,this.ttlMs=$.ttlMs??86400000,this.maxDescriptionChars=$.maxDescriptionChars??240}record($,J={}){let Q=new Date().toISOString(),X=this.toRecord($,J,Q);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update($,J){let Q=this.records.get($.id);if(!Q)return;let X=new Date().toISOString();this.records.delete($.id);let W={...Q,...this.toRecord($,J??Q.source,X),createdAt:Q.createdAt,source:J??Q.source};return this.records.set($.id,W),this.childrenIndex.delete(W.taskId),this.indexParentChild(W),this.evictIfNeeded(),W}remove($){let J=this.records.get($);if(!J)return!1;if(this.records.delete($),J.parentTaskId!==void 0){let Q=this.childrenIndex.get(J.parentTaskId);if(Q?.delete($),Q&&Q.size===0)this.childrenIndex.delete(J.parentTaskId)}return!0}getById($){let J=this.records.get($);if(!J)return;if(Date.now()-Date.parse(J.updatedAt)>this.ttlMs){this.remove($);return}return J}peekById($){return this.records.get($)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent($={}){let J=$.limit??10,Q=$.statuses,X=new Set($.excludeIds??[]),W=$.excludeAncestorOf??$.excludeSelfOrDescendant,Y=W?this.collectSubtree(W):new Set,G=$.sinceHours?Date.now()-$.sinceHours*60*60*1000:0,q=Date.now(),H=new Set([...X,...Y]),B=[];for(let U of this.records.values()){if(q-Date.parse(U.updatedAt)>this.ttlMs)continue;if(G>0&&Date.parse(U.updatedAt)<G)continue;if(H.has(U.taskId))continue;if($.scope){if($.scope.sessionId!==void 0&&U.source.sessionId!==$.scope.sessionId)continue;if($.scope.parentSessionId!==void 0&&U.source.parentSessionId!==$.scope.parentSessionId)continue;if($.scope.subagentType!==void 0&&U.source.subagentType!==$.scope.subagentType)continue}if(Q){if(!Q.includes(U.status))continue}else if(U.status==="archived")continue;B.push(U)}if($.activeChildFirst){let U=new Map;for(let z of B)U.set(z.taskId,this.hasActiveChild(z.taskId));B.sort((z,V)=>{let M=U.get(z.taskId)?1:0,O=U.get(V.taskId)?1:0;if(M!==O)return O-M;let D=Date.parse(V.updatedAt)-Date.parse(z.updatedAt);if(D!==0)return D;return V.taskId-z.taskId})}else B.sort((U,z)=>{let V=Date.parse(z.updatedAt)-Date.parse(U.updatedAt);if(V!==0)return V;return z.taskId-U.taskId});return B.slice(0,J)}getSubtreeSummary($,J={}){let Q=J.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has($)&&!this.childrenIndex.has($))return X;let W=this.childrenIndex.get($),Y=W?Array.from(W):[],G=Y.length>0?1:0;X.maxDepth=G;let q=Y;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)G++,X.maxDepth=G;q=H}return X}hasActiveChild($){let J=this.childrenIndex.get($);if(!J)return!1;for(let Q of J){let X=this.records.get(Q);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord($,J,Q){let X=this.safeParseContext($.context),W=X?this.stripSensitiveKeys(X):void 0;return{taskId:$.id,title:$.title,description:J3($.description||"",this.maxDescriptionChars),goals:J3($.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:$.tags??[],status:$.status,priority:$.priority,type:$.type,parentTaskId:$.parent_task_id,source:J,createdAt:$.createdAt||Q,updatedAt:$.updatedAt||Q,operationCount:0,project_path:$.project_path,branch:this.pickString(W,"branch"),worktree_path:this.pickString(W,"worktree_path"),parentBranch:this.pickString(W,"parent_branch"),context:W}}safeParseContext($){if(!$||!$.trim())return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}pickString($,J){if(!$)return;let Q=$[J];return typeof Q==="string"?Q:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map((X)=>this.stripSensitiveKeys(X));if(typeof $!=="object")return $;let J={},Q=j8.STRIPPED_KEYS;for(let[X,W]of Object.entries($)){let Y=X.toLowerCase();if(Q.some((G)=>Y.includes(G)))continue;J[X]=this.stripSensitiveKeys(W)}return J}upsert($){this.records.set($.taskId,$)}indexParentChild($){if($.parentTaskId===void 0||$.parentTaskId===null)return;let J=$.parentTaskId,Q=this.childrenIndex.get(J);if(!Q)Q=new Set,this.childrenIndex.set(J,Q);Q.add($.taskId)}collectSubtree($){let J=new Set([$]),Q=[$];while(Q.length>0){let X=Q.shift(),W=this.childrenIndex.get(X);if(!W)continue;for(let Y of W)if(!J.has(Y))J.add(Y),Q.push(Y)}return J}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let $=this.records.size-this.maxEntries,J=Array.from(this.records.keys()).slice(0,$);for(let Q of J)this.remove(Q)}}a();var D9=n("registry-hook-installer");function SD($,J,Q={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,W=Q.hookName?`${Q.hookName}:${X}`:`registry-hook-installer:${X}`,Y=Q.priority??100,G=!1,q=(D,F)=>{try{J.record(D,F)}catch(R){D9.warn(`[registry-hook-installer] record failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},H=(D,F)=>{try{J.update(D,F)}catch(R){D9.warn(`[registry-hook-installer] update failed for task #${D.id}: ${R instanceof Error?R.message:String(R)}`)}},B=(D)=>{try{J.remove(D)}catch(F){D9.warn(`[registry-hook-installer] remove failed for task #${D}: ${F instanceof Error?F.message:String(F)}`)}},U=()=>({sessionId:Q.sessionIdProvider?.(),...Q.staticSource??{}}),z={name:`${W}:after-create`,priority:Y,execute:async(D)=>{let F=D.data;if(F?.task)q(F.task,U())}},V={name:`${W}:after-update`,priority:Y,execute:async(D)=>{let F=D.data;if(!F?.task)return;if(J.peekById(F.task.id))H(F.task,U());else q(F.task,U())}},M={name:`${W}:after-complete`,priority:Y,execute:async(D)=>{let F=D.data;if(F?.task)H(F.task,U())}},O={name:`${W}:after-delete`,priority:Y,execute:async(D)=>{let F=D.data;if(typeof F?.id==="number")B(F.id)}};return $.registerHook(Q0.AFTER_CREATE,z),$.registerHook(Q0.AFTER_UPDATE,V),$.registerHook(Q0.AFTER_COMPLETE,M),$.registerHook(Q0.AFTER_DELETE,O),{uninstall(){if(G)return;G=!0,$.unregisterHook(Q0.AFTER_CREATE,z.name),$.unregisterHook(Q0.AFTER_UPDATE,V.name),$.unregisterHook(Q0.AFTER_COMPLETE,M.name),$.unregisterHook(Q0.AFTER_DELETE,O.name),D9.debug(`[registry-hook-installer] uninstalled hooks (name=${W})`)}}}a();var L8=n("task-reuse-registry"),ED={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},Q3=new WeakMap;function CD($){let J=Q3.get($);if(J)return J.registry;let Q=new j8(ED),X={uninstall:()=>{}};try{let Y=$.getComponent?.("task");if(Y?.registerHook)X=SD(Y,Q,{sessionIdProvider:()=>{try{return $.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),L8.debug("[task-reuse-registry] hook installed");else L8.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(Y){L8.warn(`[task-reuse-registry] hook install failed: ${Y instanceof Error?Y.message:String(Y)}`)}let W={registry:Q,installHandle:X};return Q3.set($,W),Q}var fD=[/\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 TD($){let J=$;for(let Q of fD)J=J.replace(Q,"<redacted>");return J}function X3($,J){if($.length<=J)return $;if(J<=1)return $.slice(0,J);return $.slice(0,J-1)+"\u2026"}function ID($){let J=$.limit??5,Q=$.maxChars??2000,X=$.maxDescriptionChars??240,W=$.heading??"Recent task context (reuse candidates)",Y=$.registry.recent({scope:$.scope,limit:J,statuses:$.statuses,excludeIds:$.similarTaskIds??[],excludeAncestorOf:$.excludeAncestorOf});if(Y.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let G=[];G.push(`## ${W}`),G.push(""),G.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),G.push("");for(let H of Y){if(G.push(`### Task #${H.taskId}: ${H.title}`),G.push(`- Status: ${H.status}`),H.parentTaskId!==void 0&&H.parentTaskId!==null)G.push(`- Parent: #${H.parentTaskId}`);if(H.source.subagentType)G.push(`- Created by: ${H.source.subagentType}`);if(G.push(`- Updated: ${H.updatedAt}`),H.project_path)G.push(`- Project: ${H.project_path}`);if(H.worktree_path)G.push(`- Worktree: ${H.worktree_path}`);if(H.branch)G.push(`- Branch: ${H.branch}`);if(H.parentBranch)G.push(`- Parent branch: ${H.parentBranch}`);let B;try{B=$.registry.getSubtreeSummary(H.taskId)}catch{B=void 0}if(B&&B.descendantCount>0)G.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)G.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let z=TD(X3(H.description,X));if(z)G.push(`- Description: ${z}`);if(H.tags&&H.tags.length>0)G.push(`- Tags: ${H.tags.join(", ")}`);G.push("")}G.push("---"),G.push(""),G.push("### Reuse instructions"),G.push(""),G.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),G.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),G.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),G.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),G.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),G.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),G.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),G.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),G.push(""),G.push("### Decision matrix \u2014 three legal paths"),G.push(""),G.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),G.push("remains the default, but the matrix adds two new paths for independent work."),G.push(""),G.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),G.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),G.push("append description/goals. Do **not** create a new task id."),G.push(""),G.push("```"),G.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),G.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),G.push(' milestone_title: "Reopened for <new-scope>",'),G.push(' milestone_description: "<why this is the same work>" })'),G.push("```"),G.push(""),G.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),G.push("distinct: an independent bug fix, optimization, parallel delivery or"),G.push("independent acceptance item under the same feature. Create a child task so"),G.push("the audit trail is preserved. Always pair with an audit operation."),G.push(""),G.push("```");for(let H of Y){let B=H.project_path??"<project_path>";G.push(`task_create(parent_task_id=${H.taskId}, title="<distinguishing title>", project_path="${B}", context=<inherit or override>)`);break}G.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),G.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),G.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),G.push("```"),G.push(""),G.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),G.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),G.push("should stay \u2264 ~10 to keep the tree readable."),G.push(""),G.push("```"),G.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),G.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),G.push(' milestone_title: "New root: <topic>",'),G.push(' milestone_description: "<why this is not a child of any existing task>" })'),G.push("```"),G.push(""),G.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),G.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),G.push("chosen. Use the appropriate `milestone_type`:"),G.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),G.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),G.push(" - new root \u2192 `create` (then `progress` per phase)"),G.push(""),G.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),G.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),G.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),G.push("tokens, secrets) are stripped automatically. Use the helper:"),G.push(""),G.push("```"),G.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),G.push("```"),G.push("");let q=G.join(`
|
|
2017
|
+
`);if(q.length>Q)q=X3(q,Q);return{markdown:q,candidateIds:Y.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"},A8=[{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.
|
|
2143
2018
|
|
|
2144
2019
|
## Your Role
|
|
2145
2020
|
- You were created to handle: {task_description}
|
|
@@ -2190,7 +2065,7 @@ ${$.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
|
|
|
2190
2065
|
## Execution
|
|
2191
2066
|
- Use the available tools to complete the task
|
|
2192
2067
|
- If you need more information, ask the main agent through the result
|
|
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:
|
|
2068
|
+
- 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:Q4.roy,deniedTools:["delegate_task","stop_task"]}];function N8($){return A8.find((J)=>J.id===$)}function vD($,J,Q,X,W){let Y=$.getRegistry?.();if(Y){if(Y.get(J)?.type==="workflow")return y.debug(`[delegate] Skipping registration for workflow agent: ${J}`),null}let G=$.getAgent(J);if(!G){let q={type:"sub",systemPrompt:Q};if(X?.allowedTools&&X.allowedTools.length>0)q.allowedTools=X.allowedTools;if(W.length>0)q.deniedTools=W;G=$.registerAgent(J,q),y.debug(`[delegate] Registered subagent: ${J}`)}return G}var W3=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 xD($){let{workflowName:J,originalPrompt:Q,description:X}=$;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
|
|
2194
2069
|
|
|
2195
2070
|
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${J}**\u3002
|
|
2196
2071
|
\u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
|
|
@@ -2214,7 +2089,7 @@ ${Q}
|
|
|
2214
2089
|
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2215
2090
|
|
|
2216
2091
|
\u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
|
|
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+=`
|
|
2092
|
+
`}var hD=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),O9=1800000,yD=1200000;class J0{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor($){this.env=$}setWorkflowService($){this.workflowService=$}attachWorkflowRun($,J){if(!$||!J)return;let Q=this.workflowRunRegistries.get($);if(!Q)Q=new Set,this.workflowRunRegistries.set($,Q);Q.add(J)}detachWorkflowRun($,J){this.workflowRunRegistries.get($)?.delete(J)}replaceWorkflowRun($,J,Q){if(!$)return;let X=this.workflowRunRegistries.get($);if(!X)return;if(J)X.delete(J);if(Q)X.add(Q)}async propagateStopToWorkflowRuns($,J){let Q=this.workflowRunRegistries.get($);if(!Q||Q.size===0)return{runIds:[],stopResults:[]};let X=Array.from(Q);y.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${$}`);let W=[];for(let Y of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${Y}`),W.push({runId:Y,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(Y,J),W.push({runId:Y,success:!0})}catch(G){let q=G instanceof Error?G.message:String(G);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${Y}) failed (likely already terminal): ${q}`),W.push({runId:Y,success:!1,error:q})}}return Q.clear(),{runIds:X,stopResults:W}}finalizeTask($,J){if(!$)return;this.stopProgressReporter($),this.progressTimers.delete($);let Q=this.tasks.get($);if(Q){if(this.tasks.delete($),this.terminalTasks.size>=this.maxTerminalTasks){let Y=this.terminalTasks.keys().next().value;if(Y!==void 0)this.terminalTasks.delete(Y)}this.terminalTasks.set($,Q)}let X=this.abortControllers.get($);if(X&&J!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete($),this.workflowRunRegistries.delete($);let W=this.processRegistries.get($);if(W&&W.size()>0)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${$} (residualPIDs=${W.size()}, reason=${J})`);y.debug(`[BackgroundTaskManager] finalizeTask taskId=${$} reason=${J}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let $=0;for(let[J,Q]of this.processRegistries)if(Q.size()===0)this.processRegistries.delete(J),$++;return $}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent($){try{if(J0.detectWorkflowShortcutCompat($))return y.info(`[BackgroundTaskManager] Compat rewrite: '${$}' \u2192 '${J0.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),J0.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.($);if(!X||X.type!=="workflow")return;return X.entryAgent??J0.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(J){y.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${$}: ${J}`);return}}static _detectWorkflowShortcutWrapped=U0(($)=>hD.has($),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat($){return J0._detectWorkflowShortcutWrapped($)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession($){if(!$)return;try{let Q=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.($);return typeof Q==="number"&&Q>0?Q:void 0}catch(J){y.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${$}: ${J instanceof Error?J.message:String(J)}`);return}}publishBackgroundEvent($,J,Q,X,W){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:$,payload:J,metadata:{source:"task.background",trigger_session_id:Q,...X?{triggerEventId:X}:{},...W?{replyChannel:W}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${$}`,{triggerEventId:X,replyChannelChatId:W?.chatId})}publishBackgroundEventWithTrigger($,J,Q,X,W){this.publishBackgroundEvent($,J,Q,X,W)}static parseAskUserErrorFromMessage($){let J=$ instanceof Error?$.message:String($);if($&&typeof $==="object"&&$.name==="AskUserError"&&$.query){let X=$;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:J}}let Q="__ASK_USER_ERROR__:";if(J.includes(Q))try{let X=J.substring(J.indexOf(Q)+Q.length),W=JSON.parse(X);return{query:W.query,sessionId:W.sessionId,nodeId:W.nodeId,nodeType:W.nodeType||"agent",agentSessionId:W.agentSessionId,rawErrorMessage:J}}catch(X){return y.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask($){let{parentSessionId:J,description:Q,prompt:X,subagentType:W,timeout:Y,similarTaskIds:G,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z}=$,V=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,M=this.getSessionComponent();if(!M)throw Error("SessionComponent not found");if(!await M.get(J))throw Error(`Parent session not found: ${J}`);let D;if(q){let f=await M.get(q);if(!f)throw Error(`Sub session not found for resume: ${q}`);let N=f?.metadata?.created_by;if(N&&N!=="subagent")y.warn(`[BackgroundTaskManager] Session ${q} was not created by a sub-agent (created_by=${N}); reusing anyway`);D=f;try{let E=f?.metadata??{};await M.update(q,{metadata:{...E,reused_sub_session:!0,reused_at:Date.now()}})}catch(E){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:q,error:E instanceof Error?E.message:String(E)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${q} for task ${V}`)}else{let f={subagent_type:W,created_by:"subagent",task_description:Q},N=Q2();if(N){if(N.messageId)f.messageId=N.messageId;let E=N.replyChannel;if(E?.messageId)f.larkMessageId=E.messageId;if(E?.chatId)f.chatId=E.chatId;if(E?.userId)f.larkUserId=E.userId;let x=E?.profile;if(x)f.larkProfile=x}if(H)f.triggerEventId=H;if(D=await M.create({title:`${Q} (@${W} subagent)`,parentSessionId:J,metadata:f}),!D)throw Error("Failed to create sub-session")}let F=uD(),R=new AbortController;if(this.processRegistries.size>=this.maxProcessRegistries){if(this.cleanupEmptyProcessRegistries(),this.processRegistries.size>=this.maxProcessRegistries)throw Error(`BackgroundTaskManager.processRegistries \u8FBE\u5230\u4E0A\u9650 ${this.maxProcessRegistries}\uFF08\u542B\u6B8B\u7559 PID\uFF09\uFF0C\u62D2\u7EDD\u521B\u5EFA\u65B0 task\uFF08taskId=${V}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let _=new $4;this.processRegistries.set(V,_);let A=Date.now(),Z=`${W}:bg_${V}`,P={id:V,runId:Z,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,status:"pending",createdAt:A,lastUpdatedAt:A,timeoutMs:Y||O9,abortController:R,similarTaskIds:G,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z,replyChannel:F};this.tasks.set(V,P),this.abortControllers.set(V,R);let w={backgroundTaskId:V,subSessionId:D.id,parentSessionId:J,description:Q,subagentType:W,startedAt:A,timeoutMs:Y||O9};return this.publishBackgroundEvent(d0.STARTED,w,J,H,F),this.executeTask(V,X,Y,J).catch((f)=>{y.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:V,error:f instanceof Error?f.message:String(f)})}),{taskId:V,subSessionId:D.id}}async executeTask($,J,Q,X){let W=this.tasks.get($);if(!W){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:$});return}let Y=Date.now();W.status="running",W.startedAt=Y,W.lastUpdatedAt=Y;let G=Q||O9,q=this.abortControllers.get($);this.startProgressReporter($,X||W.parentSessionId);try{let B=await this.getSessionComponent().get(W.subSessionId);if(!B)throw Error(`Sub session not found: ${W.subSessionId}`);let U=this.processRegistries.get($),z=await this.executeWithAbort(B,J,G,$,q?.signal,W.similarTaskIds,U,()=>q?.abort(),W.subagentType);if(q?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:$});return}let V=Date.now();W.status="completed",W.completedAt=V,W.lastUpdatedAt=V,W.result=z;let M=W.completedAt-W.startedAt;if(W.associatedTaskId=l2(),W.associatedTaskId===void 0)W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId);let O={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"completed",result:W.result,description:W.description,executionTimeMs:M,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.COMPLETED,O,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:$,executionTimeMs:M})}catch(H){let B=H instanceof Error?H.message:String(H),U=J0.parseAskUserErrorFromMessage(H),z=B.toLowerCase().includes("stopped")||B.toLowerCase().includes("aborted"),V=W.startedAt?Date.now()-W.startedAt:0,M=Date.now();if(W.completedAt=M,W.lastUpdatedAt=M,W.associatedTaskId=l2(),W.associatedTaskId===void 0)W.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(W.subSessionId);if(U){W.status="awaiting-user",W.error=U.rawErrorMessage,W.pendingAskUserQuery=U.query;let O={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,subagentType:W.subagentType,description:W.description,query:U.query,sessionId:U.sessionId,nodeId:U.nodeId,nodeType:U.nodeType,agentSessionId:U.agentSessionId,error:U.rawErrorMessage,executionTimeMs:V,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${W.subagentType}", existingSubSessionId="${W.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.ASK_USER,O,X||W.parentSessionId,W.triggerEventId,W.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:$,subSessionId:W.subSessionId,nodeId:U.nodeId,queryPreview:U.query.substring(0,80)}),W._preserveSubSessionOnExit=!0;return}if(z){W.status="stopped";let O={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"stopped",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.STOPPED,O,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else if(B.startsWith("Task execution timeout after")){W.status="timeout";let O={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"timeout",description:W.description,error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.TIMEOUT,O,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}else{W.status="failed";let O={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:X||W.parentSessionId,status:"failed",error:B,executionTimeMs:V,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.FAILED,O,X||W.parentSessionId,W.triggerEventId,W.replyChannel)}W.error=B,y.error("[BackgroundTaskManager] Task execution error",{taskId:$,status:W.status,error:B})}finally{this.finalizeTask($,W.status);let H=W?._preserveSubSessionOnExit===!0,B=this.getSessionComponent();if(!H&&B?.endSessionCleanup&&W?.subSessionId)try{await B.endSessionCleanup(W.subSessionId)}catch(U){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${W.subSessionId}`,{error:U instanceof Error?U.message:String(U)})}else if(H)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${W.subSessionId}`)}}startProgressReporter($,J){let Q=setInterval(()=>{let X=this.tasks.get($);if(!X||X.status!=="running"){this.stopProgressReporter($);return}let W=l2();if(W!==void 0)X.associatedTaskId=W;X.lastUpdatedAt=Date.now();let Y={backgroundTaskId:$,subSessionId:X.subSessionId,parentSessionId:J,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(d0.PROGRESS,Y,J,X.triggerEventId,X.replyChannel)},yD);this.progressTimers.set($,Q)}stopProgressReporter($){let J=this.progressTimers.get($);if(J)clearInterval(J),this.progressTimers.delete($)}async executeWithAbort($,J,Q,X,W,Y,G,q,H){let B=$?.metadata??{},U=B.task_id,z=B.task_description||"",V=$.id,M=B.subagent_type,O=M||H||"general";if(!M&&!H)y.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${V}`);let D=this.env?.getComponent?.("agent"),F=D?.getRegistry?.(),R=await AD(O,{registry:F}),_=N8(O),A=R?.basePrompt||_?.promptOverride||"You are a subagent. Complete this task: {task_description}",Z=R?.deniedTools||_?.deniedTools||[],P=R?.allowedTools||_?.allowedTools,w=A.replace(/{task_description}/g,z||"N/A");if(w+=`
|
|
2218
2093
|
|
|
2219
2094
|
---
|
|
2220
2095
|
|
|
@@ -2233,13 +2108,13 @@ ${J}
|
|
|
2233
2108
|
- \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
|
|
2234
2109
|
- \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
|
|
2235
2110
|
- \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
|
|
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`,
|
|
2237
|
-
`;if(
|
|
2238
|
-
`,c.description)
|
|
2239
|
-
`;if(c.goals_and_expected_deliverables)
|
|
2240
|
-
`;if(O0&&O0.length>0){
|
|
2241
|
-
`;for(let g0 of O0)
|
|
2242
|
-
`}i.push(
|
|
2111
|
+
- \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`,Y&&Y.length>0)try{let x=this.env?.getComponent?.("task");if(x){let i=[];for(let g of Y)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}),F0=`### Task #${c.id}: ${c.title}
|
|
2112
|
+
`;if(F0+=`- Status: ${c.status}
|
|
2113
|
+
`,c.description)F0+=`- Description: ${c.description}
|
|
2114
|
+
`;if(c.goals_and_expected_deliverables)F0+=`- Goals: ${c.goals_and_expected_deliverables}
|
|
2115
|
+
`;if(O0&&O0.length>0){F0+=`- Recent Operations:
|
|
2116
|
+
`;for(let g0 of O0)F0+=` - [${g0.actionType}] ${g0.actionTitle}: ${g0.actionDescription||""}
|
|
2117
|
+
`}i.push(F0)}catch(c){y.warn(`[delegate] Failed to fetch similar task #${g}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)w+=`
|
|
2243
2118
|
|
|
2244
2119
|
---
|
|
2245
2120
|
|
|
@@ -2247,19 +2122,19 @@ ${J}
|
|
|
2247
2122
|
|
|
2248
2123
|
The following similar tasks and their operation records can serve as reference:
|
|
2249
2124
|
|
|
2250
|
-
`,
|
|
2251
|
-
`),
|
|
2125
|
+
`,w+=i.join(`
|
|
2126
|
+
`),w+=`
|
|
2252
2127
|
|
|
2253
2128
|
---
|
|
2254
2129
|
|
|
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=
|
|
2130
|
+
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=CD(this.env),i=ID({registry:x,similarTaskIds:Y??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)w+=`
|
|
2256
2131
|
|
|
2257
2132
|
---
|
|
2258
2133
|
|
|
2259
|
-
${i.markdown}`}}catch(x){y.warn("[delegate] Failed to inject reuse candidate section",{error:x instanceof Error?x.message:String(x)})}let f=
|
|
2134
|
+
${i.markdown}`}}catch(x){y.warn("[delegate] Failed to inject reuse candidate section",{error:x instanceof Error?x.message:String(x)})}let f=_?{..._,allowedTools:P}:P?{id:O,name:O,mode:"subagent",description:R?.description||"Custom agent",allowedTools:P,deniedTools:Z}:void 0;vD(D,O,A,f,Z);let E=F?.get(O)?.type==="workflow"?J:w;return new Promise((x,i)=>{let g=async()=>{try{await G?.killAll()}catch(H0){y.warn("[delegate] ProcessRegistry.killAll failed",{error:H0 instanceof Error?H0.message:String(H0)})}},c=!1,O0,F0,g0=this.tasks.get(X);if(g0?.runId)F0=g0.runId;let Y6=()=>{if(W&&G6)try{W.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&&F0)H0.abortRun(F0,"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&&F0)H0.abortRun(F0,"task_timeout")}catch{}g().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${Q}ms`))})},Q),W)W.addEventListener("abort",G6);let e8=()=>{let H0=g0?.model,$7=g0?.fallbackModel,J7=g0?.fallbackModels;return this.env.handle_query?.(E,{sessionId:V,deniedTools:Z.length>0?Z:void 0,agentType:O,abort:W,runId:F0,...H0?{model:H0}:{},...$7?{fallbackModel:$7}:{},...Array.isArray(J7)?{fallbackModels:J7}:{}})};(G?h7(G,()=>K8(X,()=>e8())):K8(X,()=>e8()))?.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(G){y.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:$,runId:J.runId,error:G instanceof Error?G.message:String(G)})}J.completedAt=Q,J.lastUpdatedAt=Q;try{await this.processRegistries.get($)?.killAll()}catch(G){y.warn("[delegate] stopTask killAll failed",{taskId:$,error:G instanceof Error?G.message:String(G)})}let{runIds:X,stopResults:W}=await this.propagateStopToWorkflowRuns($,"Task stopped by user"),Y={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:J.parentSessionId,status:"stopped",description:J.description,error:"Task stopped by user",executionTimeMs:J.startedAt?J.completedAt-J.startedAt:0,associatedTaskId:J.associatedTaskId};return this.publishBackgroundEvent(d0.STOPPED,Y,J.parentSessionId,J.triggerEventId,J.replyChannel),this.finalizeTask($,"stopped"),{success:!0,task:J,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:W}}getTask($){return this.tasks.get($)??this.terminalTasks.get($)}async getSubSessionActivity($){let J=this.getTask($);if(!J)return;let Q=this.getSessionComponent();if(!Q?.get)return;try{let X=await Q.get(J.subSessionId);if(!X)return;return{messageCount:X.messageCount??0,updatedAt:X.updatedAt??J.lastUpdatedAt??J.createdAt}}catch{return}}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent($){if(!$)return!1;for(let J of this.tasks.values())if(J.parentSessionId===$&&(J.status==="pending"||J.status==="running"))return!0;return!1}async stopAllForParent($){if(!$)return{stoppedTaskIds:[]};let J=[];for(let[Q,X]of this.tasks)if(X.parentSessionId===$&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask(Q))?.success)J.push(Q)}catch(W){y.warn(`[BackgroundTaskManager] stopAllForParent failed for ${Q}: ${W instanceof Error?W.message:String(W)}`)}return{stoppedTaskIds:J}}async forceStopAllAcrossParents(){let $=new Set,J=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let Q of J){if($.has(Q))continue;$.add(Q);let W=this.tasks.get(Q)??this.terminalTasks.get(Q);try{await this.processRegistries.get(Q)?.killAll()}catch(G){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}try{await this.propagateStopToWorkflowRuns(Q,"force stop all")}catch(G){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}let Y=!1;if(W&&(W.status==="running"||W.status==="pending"))try{W.status="stopped",W.completedAt=Date.now(),W.lastUpdatedAt=W.completedAt,W.abortController?.abort(),Y=!0}catch(G){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${Q}: ${G instanceof Error?G.message:String(G)}`)}if(Y&&W){let G={backgroundTaskId:W.id,subSessionId:W.subSessionId,parentSessionId:W.parentSessionId,status:"stopped",description:W.description,error:"force stop all",executionTimeMs:W.startedAt&&W.completedAt?W.completedAt-W.startedAt:0,associatedTaskId:W.associatedTaskId};this.publishBackgroundEvent(d0.STOPPED,G,W.parentSessionId,W.triggerEventId,W.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose($){for(let[,X]of this.progressTimers)try{clearInterval(X)}catch{}this.progressTimers.clear();let J=$?.skipAbortRunningTasks===!0;if($?.waitForRunningTasks===!0&&J){let X=Date.now(),W=600000;while(Date.now()-X<600000){let Y=0;for(let[,G]of this.tasks)if(G.status==="running"||G.status==="pending")Y++;if(Y===0)break;y.info(`[BackgroundTaskManager] dispose waiting for ${Y} running task(s)`),await new Promise((G)=>setTimeout(G,200))}}for(let[,X]of this.abortControllers){if(J)break;try{X.abort()}catch{}}this.abortControllers.clear();for(let[,X]of this.processRegistries)try{await X.killAll()}catch(W){y.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:W instanceof Error?W.message:String(W)})}this.processRegistries.clear();for(let X of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(X,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),y.info("[BackgroundTaskManager] Disposed")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],J0.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],J0.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],J0.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],J0.prototype,"forceStopAllAcrossParents",null);function Y3($){return $.env?.getComponent?.("agent")?.getRegistry?.()}function G3($){let J=$.env,X=$.backgroundTaskManager??new J0(J),W=Y3($);$._backgroundTaskManager=X;let Y={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
|
|
2260
2135
|
|
|
2261
2136
|
Available agent types:
|
|
2262
|
-
${
|
|
2137
|
+
${ZD(W)}
|
|
2263
2138
|
|
|
2264
2139
|
When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
2265
2140
|
|
|
@@ -2288,14 +2163,14 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2288
2163
|
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2289
2164
|
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2290
2165
|
- **reason**: Brief reason for calling this tool (optional)
|
|
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:
|
|
2292
|
-
`),metadata:{execution_time_ms:Date.now()-V,sessionId:
|
|
2293
|
-
\u72B6\u6001\uFF1A${J.status}`}function
|
|
2294
|
-
`)}function
|
|
2295
|
-
`)}function
|
|
2296
|
-
`)}function
|
|
2297
|
-
`)}function
|
|
2298
|
-
`)}function
|
|
2166
|
+
- **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:W3,execute:async(G,q)=>{let H=Date.now(),B=W3.parse(G),{description:U,prompt:z,subagent_type:V="general",timeout:M,reason:O,similar_task_ids:D}=B,F=q.session_id||"default",R=B.triggerEventId??kD();if(R&&R!==B.triggerEventId)y.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${R}`);if(y.info(`[delegate_task] Called: description=${U}, subagent_type=${V}, triggerEventId=${R??"(none)"}`),R){let f=g7();if(f)try{if(!await f.getEventById(R))return{success:!1,output:"",error:`Unknown triggerEventId: ${R} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-H}}}catch(N){return{success:!1,output:"",error:`Failed to verify triggerEventId ${R}: ${N instanceof Error?N.message:String(N)}`,metadata:{execution_time_ms:Date.now()-H}}}else y.warn(`[delegate_task] triggerEventId=${R} supplied but no shared EventStore registered; skipping verification`)}let _=Y3($);if(!LD(V,_))return{success:!1,output:"",error:`Unknown subagent type: ${V}`,metadata:{execution_time_ms:Date.now()-H}};let A=$.getTagService(),Z=z,P={prompt:Z,subagentType:V,timeout:M,reason:O,tagService:A},w={component:{name:"task",version:"1.0.0"},data:P,metadata:{sessionId:F},phase:"before",hookPoint:Q0.DELEGATE_BEFORE};return await E0.execute(Q0.DELEGATE_BEFORE,P,{sessionId:F}),Z=P.prompt,await lD(X,F,U,Z,P.subagentType,P.timeout,D,B.sub_session_id,R,q.model,q.fallbackModel,q.fallbackModels)}};return Y.execute=U0(Y.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),Y}function gD(){let $=Q2();if(!$)return;let J=$.envEvent,Q=J?.metadata?.triggerEventId;if(typeof Q==="string"&&Q.length>0)return Q;let X=J?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var kD=U0(gD,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function mD(){let $=Q2()?.replyChannel;if(!$)return;if(!$.chatId&&!$.messageId)return;let J={...$.params??{}};if($.userId&&J.userId===void 0)J.userId=$.userId;return{type:$.type,appId:$.appId,chatId:$.chatId,messageId:$.messageId,profile:$.profile,params:Object.keys(J).length>0?J:void 0}}var uD=U0(mD,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function lD($,J,Q,X,W,Y,G,q,H,B,U,z){let V=Date.now();try{let M=W,O=X,D,F=$.resolveEntryAgent(W);if(F)D=W,M=F,O=xD({workflowName:D,originalPrompt:X,description:Q}),y.info(`[delegate_task] Routing workflow subagent '${W}' \u2192 entry-agent '${F}'`);let{taskId:R,subSessionId:_}=await $.createTask({parentSessionId:J,description:Q,prompt:O,subagentType:M,timeout:Y,similarTaskIds:G,originalWorkflowName:D,existingSubSessionId:q,triggerEventId:H,model:B,fallbackModel:U,fallbackModels:z});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${R}`,`\uD83D\uDCDD Description: ${Q}`,`\uD83E\uDD16 Sub-agent: ${M}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(Y||O9)/1000}s`,"",`Use stop_task with task_id="${R}" to cancel this task.`].join(`
|
|
2167
|
+
`),metadata:{execution_time_ms:Date.now()-V,sessionId:_,background:!0,status:"accepted",bgProcessId:R}}}catch(M){return{success:!1,output:"",error:M instanceof Error?M.message:String(M),metadata:{execution_time_ms:Date.now()-V}}}}var j$={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};z0();var cD=20;var pD=["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 dD($){if(!$)return[];let J;try{J=JSON.parse($)}catch{return[]}if(!J||typeof J!=="object"||Array.isArray(J))return[];let Q=J.similar_task_ids;if(!Array.isArray(Q))return[];let X=[],W=new Set;for(let Y of Q){if(typeof Y!=="number")continue;if(!Number.isInteger(Y)||Y<=0)continue;if(W.has(Y))continue;if(W.add(Y),X.push(Y),X.length>=cD)break}return X}function iD($){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 w8="__NEW_TASK_ID__",b8="#__NEW_TASK_ID__";function nD($){switch($.scenario){case"reuse":return rD($);case"reopen":return aD($);case"reopen_enhance":return sD($);case"remount":return oD($);case"soft_reuse":return tD($)}}function Z8($){return $.newTaskId>0?String($.newTaskId):w8}function L0($){return $.newTaskId>0?`#${$.newTaskId}`:b8}function M9($){let J=$.targetTask;if(!J)return"";return`#${$.targetTaskId} [${J.type}] ${J.title}
|
|
2168
|
+
\u72B6\u6001\uFF1A${J.status}`}function rD($){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","",M9($),"\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 ${L0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${L0($)}\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 ${L0($)}\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(`
|
|
2169
|
+
`)}function aD($){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","",M9($),`\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 ${L0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${L0($)}\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 ${L0($)}\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(`
|
|
2170
|
+
`)}function sD($){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","",M9($),`\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 ${L0($)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${$.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${L0($)}\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 ${L0($)}\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(`
|
|
2171
|
+
`)}function oD($){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=${Z8($)}, parent_task_id=${$.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${L0($)}\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(${Z8($)}) \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=${Z8($)}, 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(`
|
|
2172
|
+
`)}function tD($){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","",M9($),"","\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 ${L0($)}\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 ${L0($)}\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(`
|
|
2173
|
+
`)}function eD($){let J=$.toLowerCase();return pD.some((Q)=>Q.endsWith("_")||Q.endsWith("*")?J.startsWith(Q.slice(0,-1)):J===Q)}function $O($,J){let Q=(X,W)=>{if(Array.isArray(X)){X.forEach((Y,G)=>Q(Y,`${W}[${G}]`));return}if(!X||typeof X!=="object")return;for(let[Y,G]of Object.entries(X)){let q=W?`${W}.${Y}`:Y;if(eD(Y))throw Error(`[assertNoLeakage] leakage key detected at ${q}: "${Y}"`);Q(G,q)}};Q($,"state"),Q(J,"questions")}function JO($,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 tR=U0(dD,"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(",")})}),eR=U0(iD,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),$_=U0(nD,"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($)})}),J_=U0($O,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:($)=>({stateKeys:F9($[0]),questionKeys:F9($[1])})}),Q_=U0(JO,"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 F9($,J=[],Q=0){if(J.length>=40||Q>4)return J;if(Array.isArray($)){for(let X of $.slice(0,3))F9(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);F9($[X],J,Q+1)}return J}import{execSync as YO}from"child_process";var H3="unknown",QO='{"type":"unknown"}';function XO(){return{task_id:K.number().describe("Task ID")}}function WO($){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 S8($){return K.preprocess(WO,K.object({...XO(),...$}))}var B3=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
|
|
2299
2174
|
`+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
|
|
2300
2175
|
`+`**\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
|
|
2301
2176
|
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
@@ -2303,7 +2178,9 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2303
2178
|
`+` 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
|
|
2304
2179
|
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
2305
2180
|
`+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
|
|
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]}')}),
|
|
2181
|
+
`+"\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]}')}),U3=S8({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.")}),V3=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")}),z3=K.object({keywords:K.array(K.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:K.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:K.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:K.enum(["todo","active","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")}),D3=S8({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)")}),O3=K.object({task_id:K.number().describe("Task ID")}),F3=S8({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")}),M3=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")}),K3=K.object({task_ids:K.array(K.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),R3=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 GO=n("task-child-context"),qO=["commit","token","secret","password","api_key"];function P8($){if($===null||$===void 0)return $;if(Array.isArray($))return $.map(P8);if(typeof $!=="object")return $;let J={};for(let[Q,X]of Object.entries($)){let W=Q.toLowerCase();if(qO.some((Y)=>W.includes(Y)))continue;J[Q]=P8(X)}return J}function HO($){let{parent:J,overrides:Q={}}=$,X=Q.contextInherit!==!1,W=Q.inheritTags===!0,Y=Q.projectPath??J.projectPath??"unknown",G={};if(J.contextJson&&J.contextJson.trim().length>0)try{let U=JSON.parse(J.contextJson);if(U&&typeof U==="object"&&!Array.isArray(U))G=U}catch(U){GO.debug(`[task-child-context] parent #${J.taskId} context is malformed JSON; continuing with empty inherited context (${U instanceof Error?U.message:String(U)})`),G={}}let q={};if(X){if(G.worktree_path!==void 0&&Q.worktreePath===void 0)q.worktree_path=G.worktree_path;if(G.branch!==void 0&&Q.branch===void 0)q.branch=G.branch;if(G.parent_branch!==void 0)q.parent_branch=G.parent_branch;if(G.type!==void 0)q.type=G.type;if(G.prior_context&&typeof G.prior_context==="object"){let z=G.prior_context,V={};for(let[M,O]of Object.entries(z)){if(M.toLowerCase()==="commit")continue;V[M]=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(G)){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=P8(q);return{project_path:Y,context:JSON.stringify(B),inheritedTags:W?J.tags??[]:[]}}var _3=n("task:tools:create"),BO=P$.split(`
|
|
2182
|
+
`).map(($)=>$.trim()?" "+$:$).join(`
|
|
2183
|
+
`);function UO($){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 VO(){try{let $=YO("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 p2($){return{name:"task_create",description:`
|
|
2307
2184
|
Create a new task for tracking work.
|
|
2308
2185
|
|
|
2309
2186
|
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
@@ -2372,37 +2249,7 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2372
2249
|
- Depth \u2264 5 (avoid deep nesting)
|
|
2373
2250
|
- Same-theme tasks cluster under one parent
|
|
2374
2251
|
- Long-tail/stranded tasks should be archived or merged
|
|
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
|
|
2252
|
+
${BO}
|
|
2406
2253
|
|
|
2407
2254
|
## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
|
|
2408
2255
|
|
|
@@ -2498,29 +2345,29 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2498
2345
|
env-injected value is 0 / negative / non-integer, it's treated as
|
|
2499
2346
|
missing \u2014 only positive integers are honored.
|
|
2500
2347
|
|
|
2501
|
-
`,parameters:
|
|
2348
|
+
`,parameters:B3,execute:async(J,Q)=>{let X=B3.parse(J),W=Q.session_id||"unknown",Y=VO(),G=X.context,q=U9().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!==H3,z=U?B:void 0,V=X.tags,M;if(H!==void 0)try{let O=await $.getTask(H);if(O){let D=HO({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;M=D.context}}catch(O){_3.debug(`[task_create] failed to pre-load parent #${H} for context inheritance: ${O instanceof Error?O.message:String(O)}`)}try{let O=X.context===QO?void 0:X.context,D=O?JSON.parse(O):{},F=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(M)try{let R=JSON.parse(M);if(R&&typeof R==="object"&&!Array.isArray(R)){for(let[_,A]of Object.entries(R))if(F[_]===void 0)F[_]=A}}catch{}if(!F.created_at)F.created_at=new Date().toISOString();if(!F.worktree_path&&Y)F.worktree_path=Y;G=JSON.stringify(F)}catch{G=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:W,project_path:z??(U?B:H3),context:G});c2(O.id),_3.info(`[createTask] Trace: Task #${O.id} created, currentTaskId=${O.id} set in EnvContext`);let D=UO(O.context),F=D?D.replaceAll(b8,`#${O.id}`).replaceAll(w8,String(O.id)):"";return{success:!0,output:`Task created successfully: #${O.id} - ${O.title}`+(F?`
|
|
2502
2349
|
|
|
2503
|
-
${
|
|
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:
|
|
2350
|
+
${F}`:""),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 d2($){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:U3,execute:async(J,Q)=>{let X=U3.parse(J);try{if(X.include_operations){let W=await $.getTaskWithOperations(X.task_id);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let Y=W.task,G=Y&&typeof Y==="object"?{...Y,operations:W.operations}:W;return{success:!0,output:JSON.stringify(G,null,2),metadata:{execution_time_ms:0}}}else{let W=await $.getTask(X.task_id);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function i2($){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
|
|
2351
|
+
`+"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:V3,execute:async(J,Q)=>{let X=V3.parse(J);try{let W=await $.listTasks({status:X.status,priority:X.priority,type:X.type,limit:X.limit,offset:X.offset,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({total:W.total,count:W.tasks.length,truncated:W.total>W.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:W.tasks}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function n2($){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.
|
|
2505
2352
|
|
|
2506
2353
|
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
2507
2354
|
|
|
2508
|
-
If \`keywords\` is empty, returns no results.`,parameters:
|
|
2355
|
+
If \`keywords\` is empty, returns no results.`,parameters:z3,execute:async(J,Q)=>{let X=z3.parse(J);try{let W=await $.searchTasksByKeywords(X.keywords,{limit:X.limit,offset:X.offset,excludeTaskId:X.exclude_task_id,status:X.status,priority:X.priority,type:X.type,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({tasks:W.tasks,total:W.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function E8($){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.
|
|
2509
2356
|
|
|
2510
2357
|
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
2511
2358
|
|
|
2512
|
-
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:
|
|
2359
|
+
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:M3,execute:async(J,Q)=>{let X=M3.parse(J),W=X.task_ids,Y=Q.session_id||"batch-archive";if(!W||W.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let G=[],q=0;for(let B of W)try{if(await $.updateTask(B,{status:"archived"}))await $.createOperation({taskId:B,sessionId:Y,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),q++,G.push({id:B,success:!0});else G.push({id:B,success:!1,error:"Task not found"})}catch(U){G.push({id:B,success:!1,error:U instanceof Error?U.message:String(U)})}return{success:!G.some((B)=>!B.success),output:JSON.stringify({archived_count:q,total:W.length,errors:G.filter((B)=>!B.success).map((B)=>({id:B.id,error:B.error})),results:G},null,2),metadata:{execution_time_ms:0}}}}}function C8($){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
2513
2360
|
|
|
2514
2361
|
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
2515
2362
|
|
|
2516
|
-
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:
|
|
2363
|
+
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:K3,execute:async(J,Q)=>{let W=K3.parse(J).task_ids;if(!W||W.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let Y=[],G=0;for(let H of W)try{if(await $.deleteTask(H))G++,Y.push({id:H,success:!0});else Y.push({id:H,success:!1,error:"Task not found"})}catch(B){Y.push({id:H,success:!1,error:B instanceof Error?B.message:String(B)})}return{success:!Y.some((H)=>!H.success),output:JSON.stringify({deleted_count:G,total:W.length,errors:Y.filter((H)=>!H.success).map((H)=>({id:H.id,error:H.error})),results:Y},null,2),metadata:{execution_time_ms:0}}}}}q$();a();var zO=n("tool:update-task");async function DO($,J,Q){let X=new Set,W=Q;while(W!==null&&W!==void 0){if(W===J)return!0;if(X.has(W))break;X.add(W);let Y=await $.getTask(W);if(!Y)break;W=Y.parent_task_id}return!1}function r2($){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:D3,execute:async(J,Q)=>{let X=D3.parse(J),W=Q.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await DO($,X.task_id,X.parent_task_id))return{success:!1,output:"",error:`Circular reference detected: setting parent_task_id to ${X.parent_task_id} for task #${X.task_id} would create a cycle`,metadata:{execution_time_ms:0}}}let Y=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(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await $.createOperation({taskId:X.task_id,sessionId:W,actionType:"progress",actionTitle:X.current_status||`Updated: ${X.status||`${X.progress}%`}`,actionDescription:JSON.stringify({status:X.status,progress:X.progress,current_status:X.current_status})});return c2(Y.id),zO.info(`[updateTask] Trace: Task #${Y.id} updated, currentTaskId=${Y.id} set in EnvContext`),{success:!0,output:`Task updated: #${Y.id} - ${Y.title}`,metadata:{execution_time_ms:0,task:Y}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function f8($){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:O3,execute:async(J,Q)=>{let X=O3.parse(J);try{if(!await $.deleteTask(X.task_id))return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Task deleted: #${X.task_id}`,metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}q$();a();var OO=n("task:tools:complete"),FO=`
|
|
2517
2364
|
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
2518
2365
|
|
|
2519
2366
|
**Before calling this tool**, you MUST:
|
|
2520
2367
|
|
|
2521
2368
|
1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
|
|
2522
2369
|
- Use \`task_get(task_id=<id>)\` to fetch the full task record.
|
|
2523
|
-
2. **Validate whether each goal sub-item was achieved** (${
|
|
2370
|
+
2. **Validate whether each goal sub-item was achieved** (${G2}).
|
|
2524
2371
|
- Goals should be numbered sub-items (\u7F16\u53F7\u5B50\u9879, see task_create rules). Check
|
|
2525
2372
|
each sub-item against the operation-record chain (\u64CD\u4F5C\u8BB0\u5F55\u94FE) and the
|
|
2526
2373
|
deliverable evidence (context.deliverable_storage_path).
|
|
@@ -2528,9 +2375,9 @@ Mark a task as completed (progress=100, status=completed). Creates an operation
|
|
|
2528
2375
|
deliverables; numbered sub-items give it finer-grained evidence to
|
|
2529
2376
|
reason with (\u9010\u6761\u5BF9\u7167\u7684\u8BC1\u636E\u7C92\u5EA6). If it detects that the goal or
|
|
2530
2377
|
deliverables appear unmet, the task context will carry a
|
|
2531
|
-
\`[${
|
|
2532
|
-
- **If you receive a [${
|
|
2533
|
-
(${
|
|
2378
|
+
\`[${B$}]\`.
|
|
2379
|
+
- **If you receive a [${B$}]**, you MUST verify it
|
|
2380
|
+
(${q2}): re-read the task via \`task_get\`, then do exactly one of:
|
|
2534
2381
|
(a) \u786E\u8BA4\u672A\u5B8C\u6210 \u2192 \`task_update(task_id=<id>, status=todo)\` reopen and continue; or
|
|
2535
2382
|
(b) \u786E\u8BA4\u5DF2\u5B8C\u6210 \u2192 \`task_operation_create\` (milestone_type=decision,
|
|
2536
2383
|
milestone_title=<\u4E00\u884C\u7ED3\u8BBA>) state why the sub-items are actually
|
|
@@ -2557,22 +2404,22 @@ The \`deliverable_storage_path\` will be persisted to the task's \`context.deliv
|
|
|
2557
2404
|
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
2558
2405
|
|
|
2559
2406
|
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
2560
|
-
`.trim();function
|
|
2561
|
-
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${
|
|
2562
|
-
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:
|
|
2407
|
+
`.trim();function a2($){return{name:"task_complete",description:FO,parameters:F3,execute:async(J,Q)=>{let X=F3.parse(J),W=Q.session_id||"unknown";try{let Y=await $.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(Y.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let G=await $.completeTask(X.task_id,W,X.deliverable_storage_path);if(!G)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return c2(void 0),OO.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: #${G.id} - ${G.title}
|
|
2408
|
+
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${G.id} - ${G.title}
|
|
2409
|
+
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:G}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function L3($,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 A3($,J){if(J<0)return $;if(J===0)return $.map((Q)=>({...Q,children:[]}));return $.map((Q)=>({...Q,children:A3(Q.children,J-1)}))}function j3($){let J=0;for(let Q of $)J+=1+j3(Q.children);return J}function MO($){let J=new Map,Q=new Map,X=[];for(let W of $)J.set(W.id,{id:W.id,title:W.title,status:W.status,type:W.type,priority:W.priority,progress:W.progress,children:[]});for(let W of $){let Y=W.parent_task_id;if(Y!==void 0&&Y!==null&&J.has(Y)){let G=Q.get(Y)||[];G.push(W),Q.set(Y,G)}else X.push(W)}for(let[W,Y]of Q.entries()){let G=J.get(W);Y.sort(L3),G.children=Y.map((q)=>J.get(q.id))}return X.sort(L3),X.map((W)=>J.get(W.id))}function s2($){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:
|
|
2563
2410
|
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
2564
2411
|
- truncated: always false for now (no pagination cap on tree)
|
|
2565
2412
|
- depth: the resolved depth value
|
|
2566
2413
|
- parent_task_id: the root's id, or null for forest mode
|
|
2567
2414
|
- nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
|
|
2568
|
-
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:
|
|
2415
|
+
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:R3,execute:async(J,Q)=>{let X=R3.parse(J);try{let W=[],Y=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let H=await $.getTask(X.parent_task_id);if(!H)W=[];else{let B=await $.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));W=[H,...B]}}else W=(await $.listTasks({status:X.status,priority:X.priority,type:X.type,include_archived:X.include_archived,limit:9999,offset:0})).tasks;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(X.status)W=W.filter((H)=>H.status===X.status);if(X.priority)W=W.filter((H)=>H.priority===X.priority);if(X.type)W=W.filter((H)=>H.type===X.type);if(!X.include_archived)W=W.filter((H)=>H.status!=="archived")}let G=MO(W);if(X.parent_task_id===void 0||X.parent_task_id===null)G=A3(G,X.depth);let q=j3(G);return{success:!0,output:JSON.stringify({total:q,truncated:!1,depth:X.depth,parent_task_id:Y,nodes:G}),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}var K9=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),T8=100,I8=500,R9=5000,KO=1,_9=200,S3=K.string().min(T8,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${T8} \u5B57\u7B26\uFF09\uFF0C\u65E0\u6CD5\u8868\u8FBE\u8FC7\u7A0B\u6982\u8981\uFF1B\u5982\u65E0\u8FC7\u7A0B\u4FE1\u606F\u8BF7\u7701\u7565\u8BE5\u5B57\u6BB5\uFF0C\u7EC6\u8282\u8BF7\u56DE\u67E5 sessionId\u3002`}).max(I8,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${I8} \u5B57\u7B26\uFF09\uFF0C\u4F1A\u9000\u5316\u4E3A\u65E5\u5FD7\u7EC6\u8282\uFF1B\u64CD\u4F5C\u8BB0\u5F55\u53EA\u627F\u62C5 milestone \u6982\u8981\uFF0C\u5B8C\u6574\u7EC6\u8282\u8BF7\u901A\u8FC7 sessionId \u56DE\u67E5 session\u3002`}).describe("\u8FC7\u7A0B\u6982\u8981\uFF08process_description\uFF09\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981\uFF1B"+`\u4E25\u683C\u63A7\u5236 ${T8}-${I8} \u5B57\u7B26\u3002`+"\u64CD\u4F5C\u8BB0\u5F55\u662F\u8282\u70B9\u9636\u6BB5 milestone \u6458\u8981\uFF0C\u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session\uFF1B"+"milestone_description \u624D\u662F\u8FBE\u6210\u7684\u72B6\u6001/\u7ED3\u679C\u63CF\u8FF0\u3002"),E3=K.string().min(KO,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(_9,{message:`milestone_title \u8D85\u8FC7 ${_9} \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"),C3=K.string().max(R9,{message:`milestone_description \u8D85\u8FC7 ${R9} \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"),RO=K.object({task_id:K.number().describe("Task ID"),milestone_type:K9.optional(),milestone_title:E3.optional(),milestone_description:C3,process_description:S3.optional(),action_type:K9.optional(),action_title:K.string().min(1).max(_9).optional(),action_description:K.string().max(R9).optional(),md_path:K.string().optional().describe("Path to detailed markdown documentation")}),N3=RO.transform(($)=>{let J=[],Q=$.milestone_type,X=$.milestone_title,W=$.milestone_description;if(!Q&&$.action_type)Q=$.action_type,J.push("action_type");if(!X&&$.action_title)X=$.action_title,J.push("action_title");if(W===void 0&&$.action_description!==void 0)W=$.action_description,J.push("action_description");return{task_id:$.task_id,milestone_type:Q,milestone_title:X,milestone_description:W,process_description:$.process_description,md_path:$.md_path,_deprecated_fields_used:J}}),Z3=K.object({operation_id:K.number().describe("Operation ID")}),w3=K.object({task_id:K.number().describe("Task ID"),milestone_type:K9.optional(),action_type:K9.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}}),_O=K.object({operation_id:K.number().describe("Operation ID"),milestone_title:E3.optional(),milestone_description:C3,process_description:S3.optional(),action_title:K.string().min(1).max(_9).optional(),action_description:K.string().max(R9).optional()}),b3=_O.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}}),P3=K.object({operation_id:K.number().describe("Operation ID")});function LO($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function AO($){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 o2($){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:N3,execute:async(J,Q)=>{let X;try{X=N3.parse(J)}catch(G){if(G instanceof G0)return{success:!1,output:"",error:LO(G),metadata:{execution_time_ms:0}};throw G}let W=AO(X);if(!W.ok)return{success:!1,output:"",error:W.error,metadata:{execution_time_ms:0}};let Y=Q.session_id||"unknown";try{let G=await $.createOperation({taskId:X.task_id,sessionId:Y,milestoneType:W.milestoneType,milestoneTitle:W.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),q=`Operation created: #${G.id} for task #${G.taskId} [milestone=${G.milestoneType}] ${G.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+=`
|
|
2569
2416
|
|
|
2570
2417
|
`+H.join(`
|
|
2571
|
-
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:
|
|
2418
|
+
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:G.id,task_id:G.taskId,session_id:G.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(G){return{success:!1,output:"",error:G instanceof Error?G.message:String(G),metadata:{execution_time_ms:0}}}}}}function v8($){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:Z3,execute:async(J,Q)=>{let X=Z3.parse(J);try{let W=await $.getOperation(X.operation_id);if(!W)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function t2($){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:w3,execute:async(J,Q)=>{let X=w3.parse(J);try{let W=await $.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),Y=JSON.stringify({operations:W,count:W.length});if(X._deprecated_fields_used.length>0)Y=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
|
|
2572
2419
|
|
|
2573
|
-
`+
|
|
2420
|
+
`+Y;return{success:!0,output:Y,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function jO($){return`Invalid parameters: ${$.issues.map((Q)=>`${Q.path.join(".")||"<root>"}: ${Q.message}`).join("; ")}`}function x8($){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:b3,execute:async(J,Q)=>{let X;try{X=b3.parse(J)}catch(W){if(W instanceof G0)return{success:!1,output:"",error:jO(W),metadata:{execution_time_ms:0}};throw W}try{let W=await $.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!W)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let Y=`Operation updated: #${W.id}`;if(X._deprecated_fields_used.length>0)Y+=`
|
|
2574
2421
|
|
|
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:
|
|
2422
|
+
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:Y,metadata:{execution_time_ms:0,operation:W,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function h8($){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:P3,execute:async(J,Q)=>{let X=P3.parse(J);try{if(!await $.deleteOperation(X.operation_id))return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Operation deleted: #${X.operation_id}`,metadata:{execution_time_ms:0}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}import{join as g3}from"path";function s($){f3.warn($)}var f3,e2=r(()=>{a(),f3=n("task:migration")}),T3={};i0(T3,{runMigration:()=>NO});function NO($){s(`[Migration 001] Starting migration for: ${$}`);let J=W2($);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 ZO=r(()=>{H$(),e2()}),I3={};i0(I3,{runMigration:()=>wO});function wO($){s(`[Migration 002] Starting migration for: ${$}`);let J=W2($);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 bO=r(()=>{H$(),e2()}),v3={};i0(v3,{runMigration:()=>PO});function PO($){s(`[Migration 003] Starting migration for: ${$}`);let J=W2($);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 SO=r(()=>{H$(),e2()}),x3={};i0(x3,{runMigration:()=>EO});function EO($){s(`[Migration 004] Starting migration for: ${$}`);let J=W2($);try{let Q=new Set,X=J.query("PRAGMA table_info(task_operation)").all();for(let W of X)Q.add(W.name);for(let{oldName:W,newName:Y}of h3){let G=Q.has(W),q=Q.has(Y);if(G&&!q)J.run(`ALTER TABLE task_operation RENAME COLUMN ${W} TO ${Y}`),s(`[Migration 004] Renamed ${W} -> ${Y}`);else if(q)s(`[Migration 004] ${Y} already exists, skipping rename of ${W}`);else s(`[Migration 004] ${W} not present, skipping rename to ${Y}`)}s("[Migration 004] Migration completed successfully")}finally{J.close()}}var h3,CO=r(()=>{H$(),e2(),h3=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),y3={};i0(y3,{runMigration:()=>fO});function fO($){s(`[Migration 005] Starting migration for: ${$}`);let J=W2($),Q={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(J.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return s("[Migration 005] task table does not exist, skipping"),Q;let W=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if(Q.blobCountBefore=W[0]?.cnt??0,Q.blobCountBefore===0)return 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 Y=J.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();Q.blobCountAfter=Y[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 TO=r(()=>{H$(),e2()});function IO(){if(typeof Bun<"u"){let{Database:$}=t("bun:sqlite");return $}try{let{DatabaseSync:$}=t("node:sqlite");if(typeof $==="function")return $}catch{}return t("better-sqlite3")}function W2($){let J=IO();return vO(new J($))}function vO($){if(typeof $.run!=="function")$.run=function(J,...Q){if(Q.length>0)return this.prepare(J).run(...Q);else return this.exec(J)};return $.query=function(J,...Q){if(Q.length===0){let W=this.prepare(J);return{all:()=>W.all(),get:()=>W.get(),run:()=>W.run()}}let X=this.prepare(J);return{all:(...W)=>X.all(...Q,...W),get:(...W)=>X.get(...Q,...W),run:(...W)=>X.run(...Q,...W)}},$}function xO(){let $=process.env.HOME||process.env.USERPROFILE||"/tmp";return g3($,".local","share")}function L9(){return g3(xO(),"roy-agent","tasks.db")}var N$,Z$,H$=r(()=>{a(),z0(),N$=n("task:store"),Z$=class ${db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(J){this.dbPath=J||L9()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let J=t("fs"),X=t("path").dirname(this.dbPath);if(!J.existsSync(X))J.mkdirSync(X,{recursive:!0})}if(this.db=W2(this.dbPath),this.db.run(`
|
|
2576
2423
|
CREATE TABLE IF NOT EXISTS task (
|
|
2577
2424
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2578
2425
|
title TEXT NOT NULL,
|
|
@@ -2620,69 +2467,69 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2620
2467
|
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
2621
2468
|
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
2622
2469
|
)
|
|
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}=(
|
|
2470
|
+
`),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}=(ZO(),S$(T3));J(this.dbPath)}catch(J){N$.warn(`[Migration 001] Failed to run: ${J.message}`)}try{let{runMigration:J}=(bO(),S$(I3));J(this.dbPath)}catch(J){N$.warn(`[Migration 002] Failed to run: ${J.message}`)}try{let{runMigration:J}=(SO(),S$(v3));J(this.dbPath)}catch(J){N$.warn(`[Migration 003] Failed to run: ${J.message}`)}try{let{runMigration:J}=(CO(),S$(x3));J(this.dbPath)}catch(J){N$.warn(`[Migration 004] Failed to run: ${J.message}`)}try{let{runMigration:J}=(TO(),S$(y3));J(this.dbPath)}catch(J){N$.warn(`[Migration 005] Failed to run: ${J.message}`)}}this.initialized=!0,N$.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(J){await this.initialize();let Q=Date.now(),W=this.db.prepare(`
|
|
2624
2471
|
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
2625
2472
|
goals_and_expected_deliverables, due_date, tags, status,
|
|
2626
2473
|
current_status, created_at, updated_at, project_path, context)
|
|
2627
2474
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
|
|
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),
|
|
2475
|
+
`).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),Y=await this.getTask(W.lastInsertRowid);if(Y)return this.tasksCache.set(Y.id,Y),Y;throw Error("Failed to create task")}async getTask(J){if(await this.initialize(),this.tasksCache.has(J))return this.tasksCache.get(J);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(J);if(!X)return;let W=this.rowToTask(X);return this.tasksCache.set(J,W),W}async updateTask(J,Q){await this.initialize();let X=await this.getTask(J);if(!X)return;let W=[],Y=[];if(Q.title!==void 0)W.push("title = ?"),Y.push(Q.title);if(Q.description!==void 0)W.push("description = ?"),Y.push(Q.description);if(Q.status!==void 0)W.push("status = ?"),Y.push(Q.status);if(Q.priority!==void 0)W.push("priority = ?"),Y.push(Q.priority);if(Q.type!==void 0)W.push("type = ?"),Y.push(Q.type);if(Q.progress!==void 0)W.push("progress = ?"),Y.push(Q.progress);if(Q.current_status!==void 0)W.push("current_status = ?"),Y.push(Q.current_status);if(Q.goals_and_expected_deliverables!==void 0)W.push("goals_and_expected_deliverables = ?"),Y.push(Q.goals_and_expected_deliverables);if(Q.due_date!==void 0)W.push("due_date = ?"),Y.push(Q.due_date);if(Q.tags!==void 0)W.push("tags = ?"),Y.push(JSON.stringify(Q.tags));if(Q.project_path!==void 0)W.push("project_path = ?"),Y.push(Q.project_path);if(Q.context!==void 0)W.push("context = ?"),Y.push(Q.context);if(Q.parent_task_id!==void 0)W.push("parent_task_id = ?"),Y.push(Q.parent_task_id);if(W.length===0)return X;return W.push("updated_at = ?"),Y.push(Date.now()),Y.push(J),this.db.prepare(`UPDATE task SET ${W.join(", ")} WHERE id = ?`).run(...Y),this.tasksCache.delete(J),this.getTask(J)}async deleteTask(J){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(J);if(X.changes>0)this.tasksCache.delete(J),this.operationsCache.delete(J);return X.changes>0}async listTasks(J){if(await this.initialize(),J?.depth!==void 0&&J.depth>=0&&J.parent_task_id===void 0)return this.listTasksByDepth(J);let Q=["1=1"],X=[];if(J?.status)Q.push("status = ?"),X.push(J.status);if(J?.priority)Q.push("priority = ?"),X.push(J.priority);if(J?.type)Q.push("type = ?"),X.push(J.type);if(J?.parent_task_id!==void 0)Q.push("parent_task_id = ?"),X.push(J.parent_task_id);if(!J?.include_archived&&J?.status!=="archived")Q.push("status != 'archived'");let W=Q.join(" AND "),Y=`SELECT COUNT(*) as total FROM task WHERE ${W}`,q=this.db.prepare(Y).get(...X)?.total??0,H=`SELECT * FROM task WHERE ${W}`,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((M)=>{let O=this.rowToTask(M);return this.tasksCache.set(O.id,O),O}),total:q}}async listTasksByDepth(J){let Q=J.depth??0,X=["1=1"],W=[];if(J.status)X.push("status = ?"),W.push(J.status);if(J.priority)X.push("priority = ?"),W.push(J.priority);if(J.type)X.push("type = ?"),W.push(J.type);if(!J?.include_archived&&J?.status!=="archived")X.push("status != 'archived'");let Y=X.join(" AND "),G=[];if(Q===0){let z=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`,V=this.db.prepare(z).all(...W);for(let M of V){let O=this.rowToTask(M);this.tasksCache.set(O.id,O),G.push(O)}}else{let V=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`).all(...W).map((M)=>{let O=this.rowToTask(M);return this.tasksCache.set(O.id,O),O});G.push(...V);for(let M=1;M<=Q;M++){if(V.length===0)break;let O=V.map((A)=>A.id),F=`SELECT * FROM task WHERE parent_task_id IN (${O.map(()=>"?").join(",")}) AND ${Y} ORDER BY updated_at DESC`,_=this.db.prepare(F).all(...O,...W).map((A)=>{let Z=this.rowToTask(A);return this.tasksCache.set(Z.id,Z),Z});G.push(..._),V=_}}let q=G.length,H=J.offset??0,B=J.limit??q;return{tasks:G.slice(H,H+B),total:q}}async getTaskTree(J,Q=-1){await this.initialize();let X=[],W=[J],Y=0;while(W.length>0){if(Q!==-1&&Y>=Q)break;let G=W.map(()=>"?").join(","),q=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${G}) ORDER BY updated_at DESC`).all(...W),H=[];for(let B of q){let U=this.rowToTask(B);this.tasksCache.set(U.id,U),X.push(U),H.push(U.id)}W=H,Y++}return X}async getChildTasks(J,Q={}){return this.listTasks({...Q,parent_task_id:J})}async createOperation(J){await this.initialize();let Q=J.milestoneType??J.actionType,X=J.milestoneTitle??J.actionTitle,W=J.milestoneDescription??J.actionDescription;if(!Q||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let Y=Date.now(),q=this.db.prepare(`
|
|
2629
2476
|
INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
|
|
2630
2477
|
milestone_description, process_description, timestamp, md_path)
|
|
2631
2478
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
2632
|
-
`).run(J.taskId,J.sessionId,Q,X,
|
|
2479
|
+
`).run(J.taskId,J.sessionId,Q,X,W||"",J.processDescription||"",Y,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 W=Q.milestoneTitle??Q.actionTitle,Y=Q.milestoneDescription??Q.actionDescription,G=[],q=[];if(W!==void 0)G.push("milestone_title = ?"),q.push(W);if(Y!==void 0)G.push("milestone_description = ?"),q.push(Y);if(Q.processDescription!==void 0)G.push("process_description = ?"),q.push(Q.processDescription);if(G.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${G.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 W=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(J);if(W.changes>0)this.operationsCache.delete(Q.taskId);return W.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),W=J.milestoneType??J.actionType;if(W)X=X.filter((q)=>q.milestoneType===W);let Y=J.offset||0,G=J.limit||20;return X.slice(Y,Y+G)}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,W=J.milestone_description??J.action_description??"";return{id:J.id,taskId:J.task_id,sessionId:J.session_id,milestoneType:Q,milestoneTitle:X,milestoneDescription:W,processDescription:J.process_description??"",timestamp:new Date(J.timestamp).toISOString(),mdPath:J.md_path||void 0,actionType:Q,actionTitle:X,actionDescription:W}}async createTag(J){await this.initialize();let Q=Date.now(),X=await this.getTagByName(J);if(X)return X;return{id:this.db.prepare(`
|
|
2633
2480
|
INSERT INTO task_tag (name, created_at, task_count)
|
|
2634
2481
|
VALUES (?, ?, 0)
|
|
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=[],
|
|
2482
|
+
`).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=[],W=J?.orderBy||"count";if(W==="count")Q+=" ORDER BY task_count DESC";else if(W==="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=`
|
|
2636
2483
|
SELECT * FROM task_tag
|
|
2637
2484
|
WHERE name LIKE ?
|
|
2638
2485
|
ORDER BY task_count DESC
|
|
2639
2486
|
LIMIT ?
|
|
2640
|
-
`;return this.db.prepare(Q).all(`%${J.query}%`,J.limit||20).map((
|
|
2487
|
+
`;return this.db.prepare(Q).all(`%${J.query}%`,J.limit||20).map((Y)=>this.rowToTag(Y))}async deleteTag(J){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(J).changes>0}async addTagsToTask(J,Q){await this.initialize();let X=Date.now(),W=this.db.prepare(`
|
|
2641
2488
|
INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
|
|
2642
2489
|
VALUES (?, ?, ?)
|
|
2643
|
-
`);for(let
|
|
2490
|
+
`);for(let Y of Q)W.run(J,Y,X),this.db.run(`
|
|
2644
2491
|
UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
|
|
2645
|
-
`,
|
|
2492
|
+
`,Y);await this.syncTaskTagsJson(J)}async removeTagsFromTask(J,Q){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let W of Q)X.run(J,W),this.db.run(`
|
|
2646
2493
|
UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
|
|
2647
|
-
`,
|
|
2494
|
+
`,W);await this.syncTaskTagsJson(J)}async getTagsForTask(J){await this.initialize();let Q=`
|
|
2648
2495
|
SELECT t.* FROM task_tag t
|
|
2649
2496
|
INNER JOIN task_tag_relation r ON t.id = r.tag_id
|
|
2650
2497
|
WHERE r.task_id = ?
|
|
2651
2498
|
ORDER BY t.name ASC
|
|
2652
|
-
`;return this.db.prepare(Q).all(J).map((
|
|
2499
|
+
`;return this.db.prepare(Q).all(J).map((Y)=>this.rowToTag(Y))}async getTaskIdsByTags(J){if(await this.initialize(),J.length===0)return[];let X=`
|
|
2653
2500
|
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
2654
2501
|
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
2655
2502
|
WHERE t.name IN (${J.map(()=>"?").join(", ")})
|
|
2656
|
-
`;return this.db.prepare(X).all(...J).map((
|
|
2503
|
+
`;return this.db.prepare(X).all(...J).map((G)=>G.task_id)}async updateTaskTags(J,Q){await this.initialize();let X=await this.getTagsForTask(J);if(X.length>0)await this.removeTagsFromTask(J,X.map((Y)=>Y.id));let W=[];for(let Y of Q){let G=await this.getTagByName(Y);if(!G)G=await this.createTag(Y);W.push(G.id)}if(W.length>0)await this.addTagsToTask(J,W)}async searchTasksByKeywords(J,Q={}){if(await this.initialize(),!J||J.length===0)return{tasks:[],total:0};let{limit:X=20,offset:W=0,excludeTaskId:Y,status:G,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",M=[];if(Y)V+=" AND id != ?",M.push(Y);if(G)V+=" AND status = ?",M.push(G);if(q)V+=" AND priority = ?",M.push(q);if(H)V+=" AND type = ?",M.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 ?",M.push(O);let D=this.db.prepare(V).all(...M);for(let P of D){let w=this.rowToTask(P),f=new Set,N=0;if(typeof w.title==="string"&&w.title){let E=w.title.toLowerCase();for(let x of J)if(E.includes(x.toLowerCase()))N++,f.add(x)}if(w.tags&&Array.isArray(w.tags))for(let E of J){let x=E.toLowerCase();if(w.tags.some((i)=>i.toLowerCase().includes(x)))N+=2,f.add(E)}if(typeof w.description==="string"&&w.description){let E=w.description.toLowerCase();for(let x of J)if(E.includes(x.toLowerCase()))N++,f.add(x)}if(typeof w.goals_and_expected_deliverables==="string"&&w.goals_and_expected_deliverables){let E=w.goals_and_expected_deliverables.toLowerCase();for(let x of J)if(E.includes(x.toLowerCase()))N++,f.add(x)}if(f.size===J.length)z.set(w.id,{task:w,matchCount:N})}let F=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let P of F){let f=new Set;for(let i of J){let g=`%${i}%`;if(this.db.prepare(`
|
|
2657
2504
|
SELECT * FROM task_operation
|
|
2658
2505
|
WHERE task_id = ?
|
|
2659
2506
|
AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
|
|
2660
2507
|
LIMIT 10
|
|
2661
|
-
`).all(
|
|
2508
|
+
`).all(P.task_id,g,g,g).length>0)f.add(i)}if(f.size===0)continue;let N=this.db.prepare("SELECT * FROM task WHERE id = ?").get(P.task_id);if(!N)continue;let E=this.rowToTask(N);if(Y&&E.id===Y)continue;if(G&&E.status!==G)continue;if(q&&E.priority!==q)continue;if(H&&E.type!==H)continue;if(!Q?.include_archived&&E.status==="archived")continue;let x=z.get(E.id);if(x)x.matchCount+=2;else{let i=new Set(f);if(typeof E.title==="string"&&E.title){let g=E.title.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(typeof E.description==="string"&&E.description){let g=E.description.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(typeof E.goals_and_expected_deliverables==="string"&&E.goals_and_expected_deliverables){let g=E.goals_and_expected_deliverables.toLowerCase();for(let c of J)if(g.includes(c.toLowerCase()))i.add(c)}if(E.tags&&Array.isArray(E.tags)){for(let g of J)if(E.tags.some((c)=>c.toLowerCase().includes(g.toLowerCase())))i.add(g)}if(i.size===J.length)z.set(E.id,{task:E,matchCount:2})}}let R=Array.from(z.values()).sort((P,w)=>w.matchCount-P.matchCount);if(U!==null)R=R.filter((P)=>U.has(P.task.id));let _=R.length;return{tasks:R.slice(W,W+X).map((P)=>P.task),total:_}}async collectTaskIdsByDepth(J){let Q=new Set,W=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((Y)=>Y.id);for(let Y of W)Q.add(Y);if(J===0)return Q;for(let Y=1;Y<=J;Y++){if(W.length===0)break;let G=W.map(()=>"?").join(",");W=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${G})`).all(...W).map((H)=>H.id);for(let H of W)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 W=X.map((B)=>B.id),G=`
|
|
2662
2509
|
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
2663
2510
|
FROM task t
|
|
2664
2511
|
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
2665
2512
|
INNER JOIN task_tag_relation r2 ON t.id = r2.task_id
|
|
2666
|
-
WHERE r.tag_id IN (${
|
|
2513
|
+
WHERE r.tag_id IN (${W.map(()=>"?").join(", ")})
|
|
2667
2514
|
AND t.id != ?
|
|
2668
2515
|
GROUP BY t.id
|
|
2669
2516
|
ORDER BY match_count DESC, t.updated_at DESC
|
|
2670
2517
|
LIMIT ?
|
|
2671
|
-
`;return this.db.prepare(
|
|
2518
|
+
`;return this.db.prepare(G).all(...W,J,Q).map((B)=>this.rowToTask(B))}async searchTasks(J,Q=20){await this.initialize();let X=`
|
|
2672
2519
|
SELECT * FROM task
|
|
2673
2520
|
WHERE title LIKE ? OR description LIKE ?
|
|
2674
2521
|
ORDER BY updated_at DESC
|
|
2675
2522
|
LIMIT ?
|
|
2676
|
-
`;return this.db.prepare(X).all(`%${J}%`,`%${J}%`,Q).map((
|
|
2523
|
+
`;return this.db.prepare(X).all(`%${J}%`,`%${J}%`,Q).map((G)=>this.rowToTask(G))}async findTasksByContextValue(J,Q=50){if(await this.initialize(),!J)return[];let X=`
|
|
2677
2524
|
SELECT * FROM task
|
|
2678
2525
|
WHERE context LIKE ?
|
|
2679
2526
|
ORDER BY updated_at DESC
|
|
2680
2527
|
LIMIT ?
|
|
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]==="$"){
|
|
2683
|
-
]))`;continue}}if(Q.s&&X[H]==="."){
|
|
2528
|
+
`;return this.db.prepare(X).all(`%${J}%`,Q).map((Y)=>this.rowToTask(Y))}rowToTag(J){return{id:J.id,name:J.name,createdAt:new Date(J.created_at).toISOString(),taskCount:J.task_count}}async syncTaskTagsJson(J){let X=(await this.getTagsForTask(J)).map((Y)=>Y.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,J),this.tasksCache.delete(J)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Z$.prototype,"searchTasksByKeywords",null)});function k3($,J,Q){let X=J.toUpperCase();if(!$.startsWith(X))return;let W=Q.replace(/-/g,"_").toUpperCase(),Y=$.slice(X.length);if(Y.startsWith("_"))Y=Y.slice(1);if(!Y)return;let G=Y.indexOf("_"),q;if(G===-1)q=Y;else{let B=Y.slice(0,G),U=Y.slice(G+1);if(B===W)q=U;else q=Y}if(!q)return;let H=q.replace(/_/g,".");return`${Q}.${H.toLowerCase()}`}function m3($,J){return{...$,execute:J}}var hO=()=>{},u3=r(()=>{hO(),_8(),X2()});u3();class y8{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new z9}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($,m3({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 yO={"task.storage.type":"sqlite","task.storage.dbPath":void 0},gO={name:"task",sources:[{type:"env",envPrefix:"TASK",priority:20,watch:!1}],keys:[{key:"task.storage.type",sources:["env","file"]},{key:"task.storage.dbPath",sources:["env","file"]}]};X2();var kO=["completed","failed","cancelled","timeout"];q$();a();var $6=n("task:tag");class l3{store;constructor($){this.store=$}async createTag($){let J=await this.store.createTag($);return $6.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)$6.debug(`[TagService] Deleted tag id=${$}`);return J}async addTagsToTask($,J){await this.store.addTagsToTask($,J),$6.debug(`[TagService] Added ${J.length} tags to task ${$}`)}async removeTagsFromTask($,J){await this.store.removeTagsFromTask($,J),$6.debug(`[TagService] Removed ${J.length} tags from task ${$}`)}async getTagsForTask($){return this.store.getTagsForTask($)}async getTaskIdsByTags($){return this.store.getTaskIdsByTags($)}async findSimilarTasks($,J=5){return this.store.findSimilarTasks($,J)}async searchTasks($,J=20){return this.store.searchTasks($,J)}async searchTasksByKeywords($,J){return(await this.store.searchTasksByKeywords($,J)).tasks}async findSimilarTasksByKeywords($,J){return this.store.findSimilarTasksByKeywords($,J)}async syncTagsToTask($,J){let Q=[];for(let H of J){let B=await this.store.getTagByName(H);if(!B)B=await this.store.createTag(H);Q.push(B.id)}let X=await this.store.getTagsForTask($),W=new Set(X.map((H)=>H.id)),Y=new Set(Q),G=Q.filter((H)=>!W.has(H)),q=X.filter((H)=>!Y.has(H.id)).map((H)=>H.id);if(q.length>0)await this.store.removeTagsFromTask($,q);if(G.length>0)await this.store.addTagsToTask($,G);await this.store.updateTaskTags($,J),$6.info(`[TagService] Synced tags for task ${$}: ${J.join(", ")}`)}}z0();var Y0=n("task"),mO="Deliverable: ";function uO($){if(!$)return;return`${mO}${$}`}class w$ extends y8{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}}),Y0.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"),Y0.info("[TaskComponent] Initialized")}async registerConfig($){let J=this.configComponent;if(!J)return;let{configPath:Q,envPrefix:X,config:W}=$,Y=X??"TASK";if(J.registerComponent(gO),Q)J.registerSource({type:"file",relativePath:Q,optional:!0,watch:!1});J.registerSource({type:"env",envPrefix:Y,priority:20,watch:!1}),await J.load("task");for(let G of Object.keys(process.env)){let q=k3(G,Y,"task");if(!q)continue;let H=process.env[G];if(H!==void 0)await J.set(q,H)}for(let[G,q]of Object.entries(yO))if(J.get(G)===void 0)await J.set(G,q);if(J.get("task.storage.dbPath")===void 0)await J.set("task.storage.dbPath",L9());if(W){let G=this.flattenConfig(W);for(let[q,H]of Object.entries(G))await J.set(q,H)}this.registerConfigWatcher(J),await this.initStore(),this.tagService=new l3(this.store)}async initStore(){let $=this.configComponent;if(!$)return;let J=$.get("task.storage.type")??"sqlite",Q=$.get("task.storage.dbPath");if(J==="sqlite")this.store=new Z$(Q),Y0.info(`[TaskComponent] Using SQLite storage: ${Q||"default path"}`);else this.store=new Z$,Y0.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig($,J="task"){let Q={};for(let[X,W]of Object.entries($)){let Y=`${J}.${X}`;if(W&&typeof W==="object"&&!Array.isArray(W))Object.assign(Q,this.flattenConfig(W,Y));else Q[Y]=W}return Q}registerConfigWatcher($){if(typeof $.watch!=="function")return;this.configWatcher=$.watch("task.*",(J)=>{this.onConfigChange(J)})}onConfigChange($){if(Y0.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(M6(this.backgroundTaskManager),"built-in"),Y0.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else Y0.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(M6(null),"built-in"),Y0.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch($){Y0.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 $=[p2(this),d2(this),i2(this),s2(this),n2(this),E8(this),C8(this),r2(this),f8(this),a2(this)],J=[o2(this),v8(this),t2(this),x8(this),h8(this)],Q=[G3(this),_7(this.backgroundTaskManager)];for(let X of[...$,...J,...Q])this.toolComponent.register(X),Y0.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook($,J,Q={}){let X={component:{name:this.name,version:this.version},data:J,metadata:Q,phase:$.includes("before")?"before":"after",hookPoint:$};await E0.execute($,J,Q)}async createTask($){let J=$.sessionId;if($.parent_task_id!==void 0&&$.parent_task_id!==null){if(!await this.store.getTask($.parent_task_id))throw Error(`Parent task #${$.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let Q={options:{...$},sessionId:J,tagService:this.tagService,taskComponent:this};await this.executeHook(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 W={task:X,sessionId:J,tagService:this.tagService};return await this.executeHook(Q0.AFTER_CREATE,W),this.publishEvent(j$.CREATED,{task:X,sessionId:J},J),Y0.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 W={task:X,changes:J,tagService:this.tagService};if(await this.executeHook(Q0.AFTER_UPDATE,W),this.publishEvent(j$.UPDATED,{task:X,changes:J,sessionId:""},""),Y0.info(`[TaskComponent] Task updated: ${$}`),J.status&&kO.includes(J.status)){let Y=U9(),G={task:X,changes:J,terminalStatus:J.status,sessionId:Y.sessionId??"",tagService:this.tagService};await this.executeHook(Q0.AFTER_COMPLETE,G),Y0.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(j$.DELETED,{taskId:$,sessionId:""},""),Y0.info(`[TaskComponent] Task deleted: ${$}`);return Q}async listTasks($){return this.store.listTasks($)}async searchTasksByKeywords($,J){return this.store.searchTasksByKeywords($,J||{})}async getTaskTree($,J=-1){return this.store.getTaskTree($,J)}async getChildTasks($,J){return this.store.getChildTasks($,J)}async completeTask($,J,Q){let X=await this.store.getTask($);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${$} - ${X.title}. Cycle tasks are not meant to be completed.`);let W={status:"completed",progress:100};if(Q){let G={};if(X?.context)try{let q=JSON.parse(X.context);if(q&&typeof q==="object"&&!Array.isArray(q))G=q}catch{Y0.warn(`[TaskComponent] Task #${$} context is not valid JSON, ignoring when merging deliverable`)}G.deliverable_storage_path=Q,W.context=JSON.stringify(G)}let Y=await this.updateTask($,W);if(Y)await this.createOperation({taskId:$,sessionId:J,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:uO(Q)}),this.publishEvent(j$.COMPLETED,{task:Y,sessionId:J},J),Y0.info(`[TaskComponent] Task completed: ${$}, deliverable=${Q||"(none)"}`);return Y}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),W={operation:Q};return await this.executeHook(Q0.OPERATION_AFTER_CREATE,W,{task:X,operation:Q}),this.publishEvent(j$.OPERATION_ADDED,{operation:Q,taskId:Q.taskId},Q.sessionId),Y0.info(`[TaskComponent] Operation created: ${Q.id} for task ${Q.taskId}`),Q}async getOperation($){return this.store.getOperation($)}async updateOperation($,J){return this.store.updateOperation($,J)}async deleteOperation($){return this.store.deleteOperation($)}async listOperations($){return this.store.listOperations($)}getTagService(){return this.tagService}registerHook($,J){E0.register($,J),this.plugins.set(this.makePluginKey($,J.name),J),Y0.debug(`[TaskComponent] Registered hook: ${J.name} at ${$}`)}registerHooks($){for(let{hookPoint:J,hook:Q}of $)this.registerHook(J,Q)}unregisterHook($,J){let Q=E0.unregister($,J);if(Q)this.plugins.delete(this.makePluginKey($,J)),Y0.info(`[TaskComponent] Unregistered hook: ${J} from ${$}`);return Q}listHooks(){return Array.from(this.plugins.values())}makePluginKey($,J){return`${$}::${J}`}countHooks($){return E0.count($)}}m([u("task.component.executeHook",{recordParams:!0})],w$.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],w$.prototype,"createOperation",null);var g8=K.enum(["todo","active","completed","paused","cancelled","archived"]),k8=K.enum(["low","medium","high"]),m8=K.enum(["normal","cycle","longterm"]),u8=K.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),lO=K.object({storage:K.object({type:K.enum(["memory","sqlite"]).default("sqlite"),dbPath:K.string().optional()}).default({})}).default({});H$();H$();var cO="Deliverable: ";function pO($){if(!$)return;return`${cO}${$}`}var A9=1e6;class l8{port;options;constructor($,J={}){this.port=$,this.options=J}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve($){let J=dO($);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:A9,offset:0,includeArchived:!0})).tasks}async createTask($){let J=$.sessionId??this.defaultSessionId,Q;if($.parent_task_id!==void 0&&$.parent_task_id!==null){let W=await this.resolve($.parent_task_id);if(!W)throw Error(`Parent task #${$.parent_task_id} not found.`);Q=W.id}let X=await this.port.createTask({title:$.title,description:$.description,priority:$.priority,type:$.type,goals_and_expected_deliverables:$.goals_and_expected_deliverables,...Q!==void 0?{parent_task_id:Q}:{},due_date:$.due_date,tags:$.tags,project_path:$.project_path,context:$.context,sessionId:J});return await this.createOperation({taskId:X.id,sessionId:J,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask($){let J=await this.resolve($);return J?this.toTask(J):null}async getTaskWithOperations($){let J=await this.getTask($);if(!J)return null;let Q=await this.listOperations({taskId:J.id,limit:A9,offset:0});return{...J,operations:Q}}async listTasks($={}){let J=$.limit??20,Q=$.offset??0,X=(await this.scanAllTasks()).map((W)=>this.toTask(W));return X=this.applyFilters(X,$),{tasks:X.slice(Q,Q+J),total:X.length}}async updateTask($,J){let Q=await this.resolve($);if(!Q)return null;let X;if(J.parent_task_id!==void 0)if(J.parent_task_id===null)X=null;else{let Y=await this.resolve(J.parent_task_id);if(!Y)throw Error(`Parent task #${J.parent_task_id} not found.`);X=Y.id}let W=await this.port.updateTask(Q.nativeId,{title:J.title,description:J.description,status:J.status,priority:J.priority,type:J.type,progress:J.progress,current_status:J.current_status,goals_and_expected_deliverables:J.goals_and_expected_deliverables,due_date:J.due_date,tags:J.tags,project_path:J.project_path,context:J.context,...X!==void 0?{parent_task_id:X}:{}});return W?this.toTask(W):null}async deleteTask($){let J=await this.resolve($);if(!J)return!1;return await this.port.deleteTask(J.nativeId)}async completeTask($,J,Q){let X=await this.resolve($);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let W={status:"completed",progress:100};if(Q)W.context=nO(X.context,Q);let Y=await this.port.updateTask(X.nativeId,W);if(!Y)return null;let G=pO(Q);await this.createOperation({taskId:Y.id,sessionId:J??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${Y.title}`,milestoneDescription:G??"Task completed",...Q?{mdPath:Q}:{}});let q=await this.resolve(X.nativeId);return this.toTask(q??Y)}async getTaskTree($,J=-1){let Q=await this.resolve($);if(!Q)return[];if(J===0)return[];let X=(await this.scanAllTasks()).map((B)=>this.toTask(B)),W=new Map;for(let B of X){if(B.parent_task_id===void 0)continue;let U=W.get(B.parent_task_id)??[];U.push(B),W.set(B.parent_task_id,U)}let Y=[],G=new Set([Q.id]),q=[Q.id],H=0;while(q.length>0){if(J!==-1&&H>=J)break;let B=[];for(let U of q)for(let z of W.get(U)??[]){if(G.has(z.id))continue;G.add(z.id),Y.push(z),B.push(z.id)}q=B,H++}return Y}async searchTasksByKeywords($,J={}){let Q=J.limit??20,X=J.offset??0,W=(await this.scanAllTasks()).map((q)=>this.toTask(q));if(W=this.applyFilters(W,J),J.excludeTaskId!==void 0)W=W.filter((q)=>q.id!==J.excludeTaskId);let Y=$.map((q)=>q.toLowerCase()).filter((q)=>q.length>0),G=Y.length===0?W:W.filter((q)=>{let H=[q.title,q.description,q.goals_and_expected_deliverables,q.current_status,(q.tags??[]).join(" "),q.project_path].join(" ").toLowerCase();return Y.every((B)=>H.includes(B))});return{tasks:G.slice(X,X+Q),total:G.length}}async createOperation($){let J=await this.resolve($.taskId);if(!J)throw Error(`Task not found: ${$.taskId}`);let Q=$.milestoneType??$.actionType??"progress",X=$.milestoneTitle??$.actionTitle??"",W=$.milestoneDescription??$.actionDescription??"",Y=await this.port.createOperation({taskId:J.id,taskNativeId:J.nativeId,sessionId:$.sessionId??this.defaultSessionId,milestoneType:Q,milestoneTitle:X,milestoneDescription:W,processDescription:$.processDescription??"",...$.mdPath?{mdPath:$.mdPath}:{}});return this.toOperation(Y)}async listOperations($={}){let J=$.limit??100,Q=$.offset??0,X=$.milestoneType??$.actionType;if($.taskId===void 0)return[];let W=await this.resolve($.taskId);if(!W)return[];let G=(await this.port.listOperations({taskNativeId:W.nativeId,limit:X?A9:J,offset:X?0:Q})).operations.map((q)=>this.toOperation(q));if(X)G=G.filter((q)=>q.milestoneType===X),G=G.slice(Q,Q+J);return G}async getOperation($){if(typeof this.port.getOperationByNum==="function"){let Q=await this.port.getOperationByNum($);return Q?this.toOperation(Q):null}let J=await this.scanAllTasks();for(let Q of J){let W=(await this.port.listOperations({taskNativeId:Q.nativeId,limit:A9})).operations.find((Y)=>Y.id===$);if(W)return this.toOperation(W)}return null}async updateOperation($,J){let Q=await this.getOperation($);if(!Q)return null;if(typeof this.port.updateOperationByNum!=="function")return Q;let X=await this.port.updateOperationByNum($,{sessionId:J.sessionId??Q.sessionId,milestoneType:J.milestoneType??J.actionType??Q.milestoneType,milestoneTitle:J.milestoneTitle??J.actionTitle??Q.milestoneTitle,milestoneDescription:J.milestoneDescription??J.actionDescription??Q.milestoneDescription,processDescription:J.processDescription??Q.processDescription,...J.mdPath!==void 0?{mdPath:J.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation($){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum($)}applyFilters($,J){let Q=$;if(J.include_archived!==!0&&J.status!=="archived")Q=Q.filter((W)=>W.status!=="archived");if(J.status!==void 0)Q=Q.filter((W)=>W.status===J.status);if(J.priority!==void 0)Q=Q.filter((W)=>W.priority===J.priority);if(J.type!==void 0)Q=Q.filter((W)=>W.type===J.type);if(J.parent_task_id!==void 0)Q=Q.filter((W)=>W.parent_task_id===J.parent_task_id);if(J.depth!==void 0&&J.depth>=0){let W=iO(Q,J.depth);Q=Q.filter((Y)=>W.has(Y.id))}return Q}}function dO($){if(typeof $==="number")return Number.isFinite($)?$:void 0;return/^\d+$/.test($)?Number($):void 0}function iO($,J){if(J<0)return new Set($.map((G)=>G.id));let Q=new Set($.map((G)=>G.id)),X=new Map;for(let G of $){let q=G.parent_task_id;if(q===void 0||!Q.has(q))continue;let H=X.get(q)??[];H.push(G),X.set(q,H)}let W=new Set,Y=$.filter((G)=>G.parent_task_id===void 0||!Q.has(G.parent_task_id));for(let G of Y)W.add(G.id);for(let G=1;G<=J;G++){let q=[];for(let H of Y)for(let B of X.get(H.id)??[]){if(W.has(B.id))continue;W.add(B.id),q.push(B)}if(q.length===0)break;Y=q}return W}function nO($,J){let Q={};if(typeof $==="string"&&$.trim().length>0)try{let X=JSON.parse($);if(X&&typeof X==="object"&&!Array.isArray(X))Q=X}catch{}return Q.deliverable_storage_path=J,JSON.stringify(Q)}var rO=1e6;function aO($){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 J6($,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 Q6($){let J=$.data??{},Q=String(J.milestoneType??J.actionType??"progress"),X=String(J.milestoneTitle??J.actionTitle??""),W=String(J.milestoneDescription??J.actionDescription??""),Y=J.taskId??$.task_id,G=typeof Y==="number"?Y:typeof Y==="string"&&/^\d+$/.test(Y)?Number(Y):0;return{id:typeof $.num==="number"?$.num:0,nativeId:$.id,taskId:G,sessionId:String(J.sessionId??$.task_id??"unknown"),milestoneType:Q,milestoneTitle:X,milestoneDescription:W,processDescription:String(J.processDescription??""),timestamp:$.created_at,...J.mdPath?{mdPath:String(J.mdPath)}:{},actionType:Q,actionTitle:X,actionDescription:W}}function c3($,J,Q={}){let X=Q.operationType??"roy.milestone",W=Q.agent??"roy",Y=Q.scanLimit??rO;async function G(){let B=await $.listTasks({limit:Y});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:Y})).tasks.find((z)=>z.num===B)??null}async function H(B){let z=[...(await G()).entries()].find(([,V])=>V===B);if(!z)throw Error(`parent task not found: ${B}`);return z[0]}return{async createTask(B){let U=B.parent_task_id!==void 0?await H(B.parent_task_id):null,z={type:B.type??"normal",progress:B.progress??0,current_status:B.current_status??"",goals_and_expected_deliverables:B.goals_and_expected_deliverables??"",project_path:B.project_path,context:B.context,...B.due_date?{due_date:B.due_date}:{}},V=await $.createTask({title:B.title,description:B.description,priority:J.toStorePriority(B.priority),owner:W,tags:J.toStoreTags(B.tags),parent_id:U,session_id:B.sessionId??"unknown",roy:z});return J6(V,J,B.parent_task_id)},async getTask(B){let U=await $.getTask(B);if(!U)return null;let z=await G();return J6(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 G();return J6(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 G();return{tasks:U.tasks.map((V)=>J6(V,J,V.parent_id?z.get(V.parent_id):void 0)),total:U.total}},async updateTask(B,U){let z=aO(U),V=await $.updateTask(B,{...U.title!==void 0?{title:U.title}:{},...U.description!==void 0?{description:U.description}:{},...U.status!==void 0?{status:J.toStoreStatus(U.status)}:{},...U.priority!==void 0?{priority:J.toStorePriority(U.priority)}:{},...U.tags!==void 0?{tags:J.toStoreTags(U.tags)}:{},...Object.keys(z).length>0?{roy:z}:{}});if(!V)return null;let M;if(U.parent_task_id!==void 0){let D=U.parent_task_id===null?null:await H(U.parent_task_id);if(typeof $.setParentId==="function")await $.setParentId(B,D);M=U.parent_task_id===null?void 0:U.parent_task_id}let O=await $.getTask(B)??V;if(M===void 0&&O.parent_id)M=(await G()).get(O.parent_id);return J6(O,J,M)},async deleteTask(B){return await $.deleteTask(B)},async createOperation(B){let U=await $.appendOperation({task_id:B.taskNativeId??String(B.taskId),type:X,data:{taskId:B.taskId,sessionId:B.sessionId,milestoneType:B.milestoneType,milestoneTitle:B.milestoneTitle,milestoneDescription:B.milestoneDescription,processDescription:B.processDescription,...B.mdPath?{mdPath:B.mdPath}:{}}});return Q6(U)},async listOperations(B){let U=await $.listOperations({...B?.taskNativeId?{task_id:B.taskNativeId}:{},type:X,limit:B?.limit??Y,offset:B?.offset??0});return{operations:U.operations.map(Q6),total:U.total}},async getOperationByNum(B){if(typeof $.getOperationByNum!=="function")return null;let U=await $.getOperationByNum(B);return U?Q6(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=Q6(z),M=await $.updateOperation(B,{data:{taskId:V.taskId,sessionId:U.sessionId??V.sessionId,milestoneType:U.milestoneType??V.milestoneType,milestoneTitle:U.milestoneTitle??V.milestoneTitle,milestoneDescription:U.milestoneDescription??V.milestoneDescription,processDescription:U.processDescription??V.processDescription,...U.mdPath??V.mdPath?{mdPath:U.mdPath??V.mdPath}:{}}});return M?Q6(M):null},async deleteOperationByNum(B){if(typeof $.deleteOperation!=="function")return!1;return await $.deleteOperation(B)}}}var sO="roy.milestone",oO={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},tO={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function p3($){return oO[$]??"pending"}function d3($){return tO[$]??"todo"}function i3($){if($==="high")return 1;if($==="low")return 5;return 3}function n3($){if($===void 0)return"medium";if($<=2)return"high";return $===3?"medium":"low"}function r3($){if(!$||$.length===0)return;return $.join(",")}function a3($){if(!$)return[];return $.split(",").map((J)=>J.trim()).filter((J)=>J.length>0)}var eO={toRoyStatus:($)=>d3($),toStoreStatus:($)=>p3($),toRoyPriority:($)=>n3($),toStorePriority:($)=>i3($),toRoyTags:($)=>a3($),toStoreTags:($)=>r3($)};function s3($,J={}){return new l8(c3($,eO,{operationType:sO,agent:J.agent??"roy"}),{sessionId:J.sessionId})}var wL=g8.options,bL=k8.options,PL=m8.options,SL=u8.options;var t3=Symbol("Let zodToJsonSchema decide on which parser to use");var o3={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"},e3=($)=>typeof $==="string"?{...o3,name:$}:{...o3,...$};var $1=($)=>{let J=e3($),Q=J.name!==void 0?[...J.basePath,J.definitionPath,J.name]:J.basePath;return{...J,flags:{hasReferencedOpenAiAnyType:!1},currentPath:Q,propertyPath:void 0,seen:new Map(Object.entries(J.definitions).map(([X,W])=>[W._def,{def:W._def,path:[...J.basePath,J.definitionPath,X],jsonSchema:void 0}]))}};function c8($,J,Q,X){if(!X?.errorMessages)return;if(Q)$.errorMessage={...$.errorMessage,[J]:Q}}function p($,J,Q,X,W){$[J]=Q,c8($,J,X,W)}var j9=($,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"?j9(J,$.currentPath):J.join("/")}}function J1($,J){let Q={type:"array"};if($.type?._def&&$.type?._def?.typeName!==j.ZodAny)Q.items=v($.type._def,{...J,currentPath:[...J.currentPath,"items"]});if($.minLength)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 Q1($,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 X1(){return{type:"boolean"}}function N9($,J){return v($.type._def,J)}var W1=($,J)=>{return v($.innerType._def,J)};function p8($,J,Q){let X=Q??J.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((W,Y)=>p8($,J,W))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return $F($,J)}}var $F=($,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 Y1($,J){return{...v($.innerType._def,J),default:$.defaultValue()}}function G1($,J){return J.effectStrategy==="input"?v($.schema._def,J):o(J)}function q1($){return{type:"string",enum:Array.from($.values)}}var JF=($)=>{if("type"in $&&$.type==="string")return!1;return"allOf"in $};function H1($,J){let Q=[v($.left._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),v($.right._def,{...J,currentPath:[...J.currentPath,"allOf","1"]})].filter((Y)=>!!Y),X=J.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,W=[];return Q.forEach((Y)=>{if(JF(Y)){if(W.push(...Y.allOf),Y.unevaluatedProperties===void 0)X=void 0}else{let G=Y;if("additionalProperties"in Y&&Y.additionalProperties===!1){let{additionalProperties:q,...H}=Y;G=H}else X=void 0;W.push(G)}}),W.length?{allOf:W,...X}:void 0}function B1($,J){let Q=typeof $.value;if(Q!=="bigint"&&Q!=="number"&&Q!=="boolean"&&Q!=="string")return{type:Array.isArray($.value)?"array":"object"};if(J.target==="openApi3")return{type:Q==="bigint"?"integer":Q,enum:[$.value]};return{type:Q==="bigint"?"integer":Q,const:$.value}}var d8=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(d8===void 0)d8=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return d8},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 Z9($,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(`^${i8(X.value,J)}`),X.message,J);break;case"endsWith":V0(Q,RegExp(`${i8(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(i8(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:((W)=>{})(X)}return Q}function i8($,J){return J.patternStrategy==="escape"?XF($):$}var QF=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function XF($){let J="";for(let Q=0;Q<$.length;Q++){if(!QF.has($[Q]))J+="\\";J+=$[Q]}return J}function f0($,J,Q,X){if($.format||$.anyOf?.some((W)=>W.format)){if(!$.anyOf)$.anyOf=[];if($.format){if($.anyOf.push({format:$.format,...$.errorMessage&&X.errorMessages&&{errorMessage:{format:$.errorMessage.format}}}),delete $.format,$.errorMessage){if(delete $.errorMessage.format,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.anyOf.push({format:J,...Q&&X.errorMessages&&{errorMessage:{format:Q}}})}else p($,"format",J,Q,X)}function V0($,J,Q,X){if($.pattern||$.allOf?.some((W)=>W.pattern)){if(!$.allOf)$.allOf=[];if($.pattern){if($.allOf.push({pattern:$.pattern,...$.errorMessage&&X.errorMessages&&{errorMessage:{pattern:$.errorMessage.pattern}}}),delete $.pattern,$.errorMessage){if(delete $.errorMessage.pattern,Object.keys($.errorMessage).length===0)delete $.errorMessage}}$.allOf.push({pattern:U1(J,X),...Q&&X.errorMessages&&{errorMessage:{pattern:Q}}})}else p($,"pattern",U1(J,X),Q,X)}function U1($,J){if(!J.applyRegexFlags||!$.flags)return $.source;let Q={i:$.flags.includes("i"),m:$.flags.includes("m"),s:$.flags.includes("s")},X=Q.i?$.source.toLowerCase():$.source,W="",Y=!1,G=!1,q=!1;for(let H=0;H<X.length;H++){if(Y){W+=X[H],Y=!1;continue}if(Q.i){if(G){if(X[H].match(/[a-z]/)){if(q)W+=X[H],W+=`${X[H-2]}-${X[H]}`.toUpperCase(),q=!1;else if(X[H+1]==="-"&&X[H+2]?.match(/[a-z]/))W+=X[H],q=!0;else W+=`${X[H]}${X[H].toUpperCase()}`;continue}}else if(X[H].match(/[a-z]/)){W+=`[${X[H]}${X[H].toUpperCase()}]`;continue}}if(Q.m){if(X[H]==="^"){W+=`(^|(?<=[\r
|
|
2529
|
+
]))`;continue}else if(X[H]==="$"){W+=`($|(?=[\r
|
|
2530
|
+
]))`;continue}}if(Q.s&&X[H]==="."){W+=G?`${X[H]}\r
|
|
2684
2531
|
`:`[${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=`
|
|
2532
|
+
]`;continue}if(W+=X[H],X[H]==="\\")Y=!0;else if(G&&X[H]==="]")G=!1;else if(!G&&X[H]==="[")G=!0}try{new RegExp(W)}catch{return console.warn(`Could not convert regex pattern at ${J.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),$.source}return W}function w9($,J){if(J.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(J.target==="openApi3"&&$.keyType?._def.typeName===j.ZodEnum)return{type:"object",required:$.keyType._def.values,properties:$.keyType._def.values.reduce((X,W)=>({...X,[W]:v($.valueType._def,{...J,currentPath:[...J.currentPath,"properties",W]})??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===j.ZodString&&$.keyType._def.checks?.length){let{type:X,...W}=Z9($.keyType._def,J);return{...Q,propertyNames:W}}else if($.keyType?._def.typeName===j.ZodEnum)return{...Q,propertyNames:{enum:$.keyType._def.values}};else if($.keyType?._def.typeName===j.ZodBranded&&$.keyType._def.type._def.typeName===j.ZodString&&$.keyType._def.type._def.checks?.length){let{type:X,...W}=N9($.keyType._def,J);return{...Q,propertyNames:W}}return Q}function V1($,J){if(J.mapStrategy==="record")return w9($,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 z1($){let J=$.values,X=Object.keys($.values).filter((Y)=>{return typeof J[J[Y]]!=="number"}).map((Y)=>J[Y]),W=Array.from(new Set(X.map((Y)=>typeof Y)));return{type:W.length===1?W[0]==="string"?"string":"number":["string","number"],enum:X}}function D1($){return $.target==="openAi"?void 0:{not:o({...$,currentPath:[...$.currentPath,"not"]})}}function O1($){return $.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var X6={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function M1($,J){if(J.target==="openApi3")return F1($,J);let Q=$.options instanceof Map?Array.from($.options.values()):$.options;if(Q.every((X)=>(X._def.typeName in X6)&&(!X._def.checks||!X._def.checks.length))){let X=Q.reduce((W,Y)=>{let G=X6[Y._def.typeName];return G&&!W.includes(G)?[...W,G]:W},[]);return{type:X.length>1?X:X[0]}}else if(Q.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=Q.reduce((W,Y)=>{let G=typeof Y._def.value;switch(G){case"string":case"number":case"boolean":return[...W,G];case"bigint":return[...W,"integer"];case"object":if(Y._def.value===null)return[...W,"null"];case"symbol":case"undefined":case"function":default:return W}},[]);if(X.length===Q.length){let W=X.filter((Y,G,q)=>q.indexOf(Y)===G);return{type:W.length>1?W:W[0],enum:Q.reduce((Y,G)=>{return Y.includes(G._def.value)?Y:[...Y,G._def.value]},[])}}}else if(Q.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:Q.reduce((X,W)=>[...X,...W._def.values.filter((Y)=>!X.includes(Y))],[])};return F1($,J)}var F1=($,J)=>{let Q=($.options instanceof Map?Array.from($.options.values()):$.options).map((X,W)=>v(X._def,{...J,currentPath:[...J.currentPath,"anyOf",`${W}`]})).filter((X)=>!!X&&(!J.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return Q.length?{anyOf:Q}:void 0};function K1($,J){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes($.innerType._def.typeName)&&(!$.innerType._def.checks||!$.innerType._def.checks.length)){if(J.target==="openApi3")return{type:X6[$.innerType._def.typeName],nullable:!0};return{type:[X6[$.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 R1($,J){let Q={type:"number"};if(!$.checks)return Q;for(let X of $.checks)switch(X.kind){case"int":Q.type="integer",c8(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 _1($,J){let Q=J.target==="openAi",X={type:"object",properties:{}},W=[],Y=$.shape();for(let q in Y){let H=Y[q];if(H===void 0||H._def===void 0)continue;let B=YF(H);if(B&&Q){if(H._def.typeName==="ZodOptional")H=H._def.innerType;if(!H.isNullable())H=H.nullable();B=!1}let U=v(H._def,{...J,currentPath:[...J.currentPath,"properties",q],propertyPath:[...J.currentPath,"properties",q]});if(U===void 0)continue;if(X.properties[q]=U,!B)W.push(q)}if(W.length)X.required=W;let G=WF($,J);if(G!==void 0)X.additionalProperties=G;return X}function WF($,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 YF($){try{return $.isOptional()}catch{return!0}}var L1=($,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 A1=($,J)=>{if(J.pipeStrategy==="input")return v($.in._def,J);else if(J.pipeStrategy==="output")return v($.out._def,J);let Q=v($.in._def,{...J,currentPath:[...J.currentPath,"allOf","0"]}),X=v($.out._def,{...J,currentPath:[...J.currentPath,"allOf",Q?"1":"0"]});return{allOf:[Q,X].filter((W)=>W!==void 0)}};function j1($,J){return v($.type._def,J)}function N1($,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 Z1($,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 w1($){return{not:o($)}}function b1($){return o($)}var P1=($,J)=>{return v($.innerType._def,J)};var S1=($,J,Q)=>{switch(J){case j.ZodString:return Z9($,Q);case j.ZodNumber:return R1($,Q);case j.ZodObject:return _1($,Q);case j.ZodBigInt:return Q1($,Q);case j.ZodBoolean:return X1();case j.ZodDate:return p8($,Q);case j.ZodUndefined:return w1(Q);case j.ZodNull:return O1(Q);case j.ZodArray:return J1($,Q);case j.ZodUnion:case j.ZodDiscriminatedUnion:return M1($,Q);case j.ZodIntersection:return H1($,Q);case j.ZodTuple:return Z1($,Q);case j.ZodRecord:return w9($,Q);case j.ZodLiteral:return B1($,Q);case j.ZodEnum:return q1($);case j.ZodNativeEnum:return z1($);case j.ZodNullable:return K1($,Q);case j.ZodOptional:return L1($,Q);case j.ZodMap:return V1($,Q);case j.ZodSet:return N1($,Q);case j.ZodLazy:return()=>$.getter()._def;case j.ZodPromise:return j1($,Q);case j.ZodNaN:case j.ZodNever:return D1(Q);case j.ZodEffects:return G1($,Q);case j.ZodAny:return o(Q);case j.ZodUnknown:return b1(Q);case j.ZodDefault:return Y1($,Q);case j.ZodBranded:return N9($,Q);case j.ZodReadonly:return P1($,Q);case j.ZodCatch:return W1($,Q);case j.ZodPipeline:return A1($,Q);case j.ZodFunction:case j.ZodVoid:case j.ZodSymbol:return;default:return((X)=>{return})(J)}};function v($,J,Q=!1){let X=J.seen.get($);if(J.override){let q=J.override?.($,J,X,Q);if(q!==t3)return q}if(X&&!Q){let q=GF(X,J);if(q!==void 0)return q}let W={def:$,path:J.currentPath,jsonSchema:void 0};J.seen.set($,W);let Y=S1($,$.typeName,J),G=typeof Y==="function"?v(Y(),J):Y;if(G)qF($,J,G);if(J.postProcess){let q=J.postProcess(G,$,J);return W.jsonSchema=G,q}return W.jsonSchema=G,G}var GF=($,J)=>{switch(J.$refStrategy){case"root":return{$ref:$.path.join("/")};case"relative":return{$ref:j9(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}}},qF=($,J,Q)=>{if($.description){if(Q.description=$.description,J.markdownDescription)Q.markdownDescription=$.description}return Q};var n8=($,J)=>{let Q=$1(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,W=typeof J==="string"?J:J?.nameStrategy==="title"?void 0:J?.name,Y=v($._def,W===void 0?Q:{...Q,currentPath:[...Q.basePath,Q.definitionPath,W]},!1)??o(Q),G=typeof J==="object"&&J.name!==void 0&&J.nameStrategy==="title"?J.name:void 0;if(G!==void 0)Y.title=G;if(Q.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[Q.openAiAnyTypeName])X[Q.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:Q.$refStrategy==="relative"?"1":[...Q.basePath,Q.definitionPath,Q.openAiAnyTypeName].join("/")}}}let q=W===void 0?X?{...Y,[Q.definitionPath]:X}:Y:{$ref:[...Q.$refStrategy==="relative"?[]:Q.basePath,Q.definitionPath,W].join("/"),[Q.definitionPath]:{...X,[W]:Y}};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 HF=[p2,s2,d2,i2,n2,r2,a2,o2,t2];function BF($){let J=$;if(!J)return{};let Q=J.shape?J:J._def?.schema??J;try{let X=n8(Q,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:W,...Y}=X;return Y}catch{return{}}}function E1($,J={}){let Q=s3($,J);return HF.map((X)=>{let W=X(Q);return{name:W.name,description:W.description,input:BF(W.parameters),options:{codemode:!1},execute:async(Y,G)=>{let q={session_id:G?.sessionID??J.sessionId??"unknown",workdir:G?.directory};try{let H=await W.execute(Y??{},q),B=typeof H.output==="string"?H.output:JSON.stringify(H.output??"");return{content:H.success?B:`ERROR: ${H.error??"unknown error"}`,metadata:{tool:W.name,ok:H.success}}}catch(H){return{content:`ERROR: ${H instanceof Error?H.message:String(H)}`,metadata:{tool:W.name,ok:!1}}}}}})}function C1($,J){let Q=$?.dispose;if(typeof Q==="function")J.push(Q)}async function f1($,J){let Q=J.enabled!==!1,X={enabled:Q,agentId:null,toolNames:[],errors:[],disposers:[]};if(!Q)return X;let W=$??{},Y=J.agent??H2;if(typeof W.agent?.transform==="function")try{let q=await W.agent.transform((H)=>{v9(H)});C1(q,X.disposers),X.agentId=Y}catch(q){X.errors.push(`roy agent registration failed: ${r8(q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let G=[];try{G=E1(J.store,{agent:Y,...J.sessionId?{sessionId:J.sessionId}:{}})}catch(q){return X.errors.push(`roy tool construction failed: ${r8(q)}`),X}if(typeof W.tool?.transform==="function")try{let q=await W.tool.transform((H)=>{for(let B of G)H.add(B)});C1(q,X.disposers),X.toolNames=G.map((H)=>H.name)}catch(q){X.errors.push(`roy tool registration failed: ${r8(q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function r8($){return $ instanceof Error?$.message:String($)}import{join as o8}from"path";import{homedir as KF}from"os";import{mkdirSync as RF}from"fs";import{Database as UF}from"bun:sqlite";import{createHash as VF,randomUUID as zF}from"crypto";var DF=`
|
|
2686
2533
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
2687
2534
|
id TEXT PRIMARY KEY,
|
|
2688
2535
|
title TEXT NOT NULL,
|
|
@@ -2737,13 +2584,13 @@ CREATE TABLE IF NOT EXISTS bounties (
|
|
|
2737
2584
|
done_at TEXT
|
|
2738
2585
|
);
|
|
2739
2586
|
CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
|
|
2740
|
-
`;function
|
|
2587
|
+
`;function b$(){return new Date().toISOString()}function a8(){return zF()}function OF($){return VF("sha256").update($).digest("hex")}function T1($){let J=JSON.stringify({id:$.id,type:$.type,data:$.data,prev_hash:$.prev_hash,created_at:$.created_at});return OF(J)}function s8($){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:FF($.roy),created_at:$.created_at,updated_at:$.updated_at}}function FF($){if($===null||$===void 0||$==="")return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J;return}catch{return}}function MF($){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 I1($){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 b9($){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 P9{db;closedFlag=!1;constructor($){this.db=$}static async create($){let J=new UF($);return J.exec(DF),MF(J),new P9(J)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask($,J){if(this.closedFlag)throw Error("store closed");if(J){let G=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(J);if(G){let q=await this.getTask(G.task_id);if(q)return q}}let Q=a8(),X=b$(),W=$.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
|
|
2741
2588
|
parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
|
|
2742
|
-
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.title,$.description??null,
|
|
2743
|
-
VALUES (?, ?, ?)`).run(J,Q,X);await this.appendOperation({task_id:Q,type:"task.created",data:{title:$.title,parent_id:$.parent_id??null}});let
|
|
2744
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),
|
|
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
|
|
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
|
|
2589
|
+
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run(Q,$.title,$.description??null,W,$.owner??null,$.tags??null,$.parent_id??null,JSON.stringify($.blocked_by??[]),$.retry_of??null,$.session_id??null,$.roy===void 0?null:JSON.stringify($.roy),X,X),J)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
|
|
2590
|
+
VALUES (?, ?, ?)`).run(J,Q,X);await this.appendOperation({task_id:Q,type:"task.created",data:{title:$.title,parent_id:$.parent_id??null}});let Y=await this.getTask(Q);if(!Y)throw Error("internal: task vanished after insert");return Y}async getTask($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get($);return J?s8(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?s8(J):null}async updateTask($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getTask($);if(!Q)return null;let X=[],W=[];if(J.title!==void 0)X.push("title = ?"),W.push(J.title);if(J.description!==void 0)X.push("description = ?"),W.push(J.description);if(J.status!==void 0)X.push("status = ?"),W.push(J.status);if(J.priority!==void 0)X.push("priority = ?"),W.push(J.priority);if(J.owner!==void 0)X.push("owner = ?"),W.push(J.owner);if(J.tags!==void 0)X.push("tags = ?"),W.push(J.tags);if(J.blocked_by!==void 0)X.push("blocked_by = ?"),W.push(JSON.stringify(J.blocked_by));if(J.roy!==void 0){let Y={...Q.roy??{},...J.roy};X.push("roy = ?"),W.push(JSON.stringify(Y))}if(X.push("updated_at = ?"),W.push(b$()),W.push($),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...W),J.status!==void 0&&J.status!==Q.status)await this.appendOperation({task_id:$,type:"task.status_changed",data:{from:Q.status,to:J.status}});else await this.appendOperation({task_id:$,type:"task.updated",data:{keys:Object.keys(J)}});return await this.getTask($)}async listTasks($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)if(Array.isArray($.status))J.push(`status IN (${$.status.map(()=>"?").join(",")})`),Q.push(...$.status);else J.push("status = ?"),Q.push($.status);if($.parent_id!==void 0)if($.parent_id===null)J.push("parent_id IS NULL");else J.push("parent_id = ?"),Q.push($.parent_id);if($.session_id!==void 0)J.push("session_id = ?"),Q.push($.session_id);if($.owner!==void 0)J.push("owner = ?"),Q.push($.owner);if($.tags!==void 0)J.push("tags LIKE ?"),Q.push(`%${$.tags}%`);if($.search!==void 0)J.push("(title LIKE ? OR description LIKE ?)"),Q.push(`%${$.search}%`,`%${$.search}%`);let X=$.limit??100,W=$.offset??0,Y=J.length?`WHERE ${J.join(" AND ")}`:"",G=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${Y}`).get(...Q).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${Y} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...Q,X,W).map(s8),total:G}}async deleteTask($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run($).changes>0}async setParentId($,J){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(J,b$(),$)}async appendOperation($){if(this.closedFlag)throw Error("store closed");let Q=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=a8(),W=b$(),Y=T1({id:X,type:$.type,data:$.data,prev_hash:Q,created_at:W});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
|
|
2591
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,$.task_id,$.type,JSON.stringify($.data),W,Q,Y);let G=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:G,task_id:$.task_id,type:$.type,data:$.data,created_at:W,prev_hash:Q,hash:Y}}async getOperationByNum($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get($);return J?I1(J):null}async updateOperation($,J){if(this.closedFlag)throw Error("store closed");let Q=await this.getOperationByNum($);if(!Q)return null;let X=[],W=[];if(J.type!==void 0)X.push("type = ?"),W.push(J.type);if(J.data!==void 0)X.push("data = ?"),W.push(JSON.stringify(J.data));if(X.length===0)return Q;return W.push($),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...W),await this.getOperationByNum($)}async deleteOperation($){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM operations WHERE rowid = ?").run($).changes>0}async listOperations($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.task_id!==void 0)J.push("task_id = ?"),Q.push($.task_id);if($.type!==void 0)J.push("type = ?"),Q.push($.type);let X=$.limit??100,W=$.offset??0,Y=J.length?`WHERE ${J.join(" AND ")}`:"",G=this.db.query(`SELECT COUNT(*) AS n FROM operations ${Y}`).get(...Q).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${Y} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...Q,X,W).map(I1),total:G}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),J="0".repeat(64);for(let Q of $){let X=T1({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=a8(),Q=b$();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
|
|
2592
|
+
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 b9(X)}async claimBounty($){if(this.closedFlag)throw Error("store closed");let J=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!J)return null;let Q=b$();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run($,Q,J.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:J.id,by:$}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(J.id);return b9(X)}async completeBounty($,J){if(this.closedFlag)throw Error("store closed");let Q=b$();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
|
|
2593
|
+
WHERE id = ? AND status = 'claimed'`).run(J,Q,$).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:$,task_id:J}});let W=this.db.query("SELECT * FROM bounties WHERE id = ?").get($);return b9(W)}async listBounties($={}){if(this.closedFlag)throw Error("store closed");let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.to!==void 0)J.push("to_ = ?"),Q.push($.to);let X=J.length?`WHERE ${J.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...Q).map(b9)}}var _F=o8(KF(),".roy-task-plugin"),LF=o8(_F,"tasks.db");class Y2{inner;constructor($){this.inner=$}static async create($){let J=$??LF;if(J!==":memory:")RF(o8(J,".."),{recursive:!0});let Q=await P9.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 t8{baseUrl;headers;closedFlag=!1;constructor($){this.baseUrl=$.baseUrl.replace(/\/+$/,""),this.headers={"content-type":"application/json",...$.authToken?{authorization:`Bearer ${$.authToken}`}:{},...$.headers??{}}}async close(){this.closedFlag=!0}async request($,J,Q){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if(Q?.idempotencyKey)X["idempotency-key"]=Q.idempotencyKey;let W=await fetch(`${this.baseUrl}${J}`,{method:$,headers:X,body:Q?.body!==void 0?JSON.stringify(Q.body):void 0});if(W.status===204)return null;let Y=await W.text(),G=null;try{G=Y?JSON.parse(Y):null}catch{G=Y}if(!W.ok)throw new y0(W.status,`HTTP ${W.status}`,G);return G}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 W6{inner;constructor($){this.inner=new t8($)}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 BZ($={}){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 W6({baseUrl:$.remoteUrl,authToken:$.remoteAuthToken})}else Q=await Y2.create($.localDbPath);let X={store:Q,agent:$.agent??"opencode-default"};return{handlers:H6(X),store:Q,async close(){await Q.close()}}}var AF={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 W6({baseUrl:J.remoteUrl,authToken:J.remoteAuthToken})}else X=await Y2.create(J.localDbPath);let W={store:X,agent:J.agent??"opencode-default"},Y=H6(W),G=await f1($,{store:X,enabled:J.royAgent!==!1,agent:"roy"}),q=await $.agent.transform(async(B)=>{let z=B.get("build");if(!z)return;let V=String(z.system??""),M=`
|
|
2747
2594
|
|
|
2748
2595
|
# Roy Task Plugin (auto-injected by roy-task-plugin v2)
|
|
2749
2596
|
|
|
@@ -2758,7 +2605,7 @@ Mark progress on long tasks via \`task-update <id> --status <status>\`.
|
|
|
2758
2605
|
For task-first-class-citizen work (task tree, milestones, deliverables), switch
|
|
2759
2606
|
to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
|
|
2760
2607
|
lifecycle as native tools.
|
|
2761
|
-
`;B.update("build",(O)=>{if(typeof O.system==="string"||O.system===void 0)O.system=V+
|
|
2762
|
-
`)[0]?.trim()||`task-${Date.now()}`;await
|
|
2608
|
+
`;B.update("build",(O)=>{if(typeof O.system==="string"||O.system===void 0)O.system=V+M})}),H=await $.command.transform((B)=>{B.add({name:"task-create",description:"Create a tracked task in roy-task-plugin store. Persists to SQLite (~/.roy-task-plugin/tasks.db) or remote service. Args: <title> [body]",template:"task-create <title> [body]",execute:async(U)=>{let z=String(U?.prompt?.text??"").trim(),V=z.split(`
|
|
2609
|
+
`)[0]?.trim()||`task-${Date.now()}`;await Y.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 G.disposers)try{await B()}catch{}await q.dispose(),await H.dispose(),await X.close()}}}},VZ=AF;export{VZ as default,BZ as createRoyTaskPlugin,H6 as createHandlers,W6 as RemoteTaskStore,Y2 as LocalTaskStore};
|
|
2763
2610
|
|
|
2764
|
-
//# debugId=
|
|
2611
|
+
//# debugId=AD33318141E4735E64756E2164756E21
|