@ai-setting/roy-task-plugin 0.7.4 → 0.7.6
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 +10 -3
- package/dist/claude-plugin/commands/task-milestone.md +1 -1
- package/dist/cli.js +164 -124
- package/dist/index.js +208 -170
- package/dist/index.js.map +13 -12
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,141 +1,141 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}}
|
|
4
|
-
`)?
|
|
2
|
+
var b9=Object.create;var{getPrototypeOf:j9,defineProperty:L1,getOwnPropertyNames:E9}=Object;var S9=Object.prototype.hasOwnProperty;function P9(_){return this[_]}var Z9,C9,I9=(_,w,$)=>{var X=_!=null&&typeof _==="object";if(X){var Y=w?Z9??=new WeakMap:C9??=new WeakMap,J=Y.get(_);if(J)return J}$=_!=null?b9(j9(_)):{};let Q=w||!_||!_.__esModule?L1($,"default",{value:_,enumerable:!0}):$;for(let W of E9(_))if(!S9.call(Q,W))L1(Q,W,{get:P9.bind(_,W),enumerable:!0});if(X)Y.set(_,Q);return Q};var Z=(_,w)=>()=>(w||_((w={exports:{}}).exports,w),w.exports);var T9=(_)=>_;function k9(_,w){this[_]=T9.bind(null,w)}var g9=(_,w)=>{for(var $ in w)L1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:k9.bind(w,$)})};var X2=import.meta.require;var p=Z((GY)=>{var r1=Symbol.for("yaml.alias"),T4=Symbol.for("yaml.document"),z2=Symbol.for("yaml.map"),k4=Symbol.for("yaml.pair"),a1=Symbol.for("yaml.scalar"),V2=Symbol.for("yaml.seq"),c_=Symbol.for("yaml.node.type"),wY=(_)=>!!_&&typeof _==="object"&&_[c_]===r1,$Y=(_)=>!!_&&typeof _==="object"&&_[c_]===T4,XY=(_)=>!!_&&typeof _==="object"&&_[c_]===z2,YY=(_)=>!!_&&typeof _==="object"&&_[c_]===k4,g4=(_)=>!!_&&typeof _==="object"&&_[c_]===a1,JY=(_)=>!!_&&typeof _==="object"&&_[c_]===V2;function h4(_){if(_&&typeof _==="object")switch(_[c_]){case z2:case V2:return!0}return!1}function QY(_){if(_&&typeof _==="object")switch(_[c_]){case r1:case z2:case a1:case V2:return!0}return!1}var WY=(_)=>(g4(_)||h4(_))&&!!_.anchor;GY.ALIAS=r1;GY.DOC=T4;GY.MAP=z2;GY.NODE_TYPE=c_;GY.PAIR=k4;GY.SCALAR=a1;GY.SEQ=V2;GY.hasAnchor=WY;GY.isAlias=wY;GY.isCollection=h4;GY.isDocument=$Y;GY.isMap=XY;GY.isNode=QY;GY.isPair=YY;GY.isScalar=g4;GY.isSeq=JY});var z0=Z((bY)=>{var Y_=p(),U_=Symbol("break visit"),y4=Symbol("skip children"),g_=Symbol("remove node");function O2(_,w){let $=v4(w);if(Y_.isDocument(_)){if(lw(null,_.contents,$,Object.freeze([_]))===g_)_.contents=null}else lw(null,_,$,Object.freeze([]))}O2.BREAK=U_;O2.SKIP=y4;O2.REMOVE=g_;function lw(_,w,$,X){let Y=x4(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return m4(_,X,Y),lw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let Q=lw(J,w.items[J],$,X);if(typeof Q==="number")J=Q-1;else if(Q===U_)return U_;else if(Q===g_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=lw("key",w.key,$,X);if(J===U_)return U_;else if(J===g_)w.key=null;let Q=lw("value",w.value,$,X);if(Q===U_)return U_;else if(Q===g_)w.value=null}}return Y}async function M2(_,w){let $=v4(w);if(Y_.isDocument(_)){if(await cw(null,_.contents,$,Object.freeze([_]))===g_)_.contents=null}else await cw(null,_,$,Object.freeze([]))}M2.BREAK=U_;M2.SKIP=y4;M2.REMOVE=g_;async function cw(_,w,$,X){let Y=await x4(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return m4(_,X,Y),cw(_,Y,$,X);if(typeof Y!=="symbol"){if(Y_.isCollection(w)){X=Object.freeze(X.concat(w));for(let J=0;J<w.items.length;++J){let Q=await cw(J,w.items[J],$,X);if(typeof Q==="number")J=Q-1;else if(Q===U_)return U_;else if(Q===g_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=await cw("key",w.key,$,X);if(J===U_)return U_;else if(J===g_)w.key=null;let Q=await cw("value",w.value,$,X);if(Q===U_)return U_;else if(Q===g_)w.value=null}}return Y}function v4(_){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 x4(_,w,$,X){if(typeof $==="function")return $(_,w,X);if(Y_.isMap(w))return $.Map?.(_,w,X);if(Y_.isSeq(w))return $.Seq?.(_,w,X);if(Y_.isPair(w))return $.Pair?.(_,w,X);if(Y_.isScalar(w))return $.Scalar?.(_,w,X);if(Y_.isAlias(w))return $.Alias?.(_,w,X);return}function m4(_,w,$){let X=w[w.length-1];if(Y_.isCollection(X))X.items[_]=$;else if(Y_.isPair(X))if(_==="key")X.key=$;else X.value=$;else if(Y_.isDocument(X))X.contents=$;else{let Y=Y_.isAlias(X)?"alias":"scalar";throw Error(`Cannot replace node with ${Y} parent`)}}bY.visit=O2;bY.visitAsync=M2});var o1=Z((CY)=>{var u4=p(),SY=z0(),PY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},ZY=(_)=>_.replace(/[!,[\]{}]/g,(w)=>PY[w]);class M_{constructor(_,w){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},M_.defaultYaml,_),this.tags=Object.assign({},M_.defaultTags,w)}clone(){let _=new M_(this.yaml,this.tags);return _.docStart=this.docStart,_}atDocument(){let _=new M_(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:M_.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},M_.defaultTags);break}return _}add(_,w){if(this.atNextDocument)this.yaml={explicit:M_.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},M_.defaultTags),this.atNextDocument=!1;let $=_.trim().split(/[ \t]+/),X=$.shift();switch(X){case"%TAG":{if($.length!==2){if(w(0,"%TAG directive should contain exactly two parts"),$.length<2)return!1}let[Y,J]=$;return this.tags[Y]=J,!0}case"%YAML":{if(this.yaml.explicit=!0,$.length!==1)return w(0,"%YAML directive should contain exactly one part"),!1;let[Y]=$;if(Y==="1.1"||Y==="1.2")return this.yaml.version=Y,!0;else{let J=/^\d+\.\d+$/.test(Y);return w(6,`Unsupported YAML version ${Y}`,J),!1}}default:return w(0,`Unknown directive ${X}`,!0),!1}}tagName(_,w){if(_==="!")return"!";if(_[0]!=="!")return w(`Not a valid tag: ${_}`),null;if(_[1]==="<"){let J=_.slice(2,-1);if(J==="!"||J==="!!")return w(`Verbatim tags aren't resolved, so ${_} is invalid.`),null;if(_[_.length-1]!==">")w("Verbatim tags must end with a >");return J}let[,$,X]=_.match(/^(.*!)([^!]*)$/s);if(!X)w(`The ${_} tag has no suffix`);let Y=this.tags[$];if(Y)try{return Y+decodeURIComponent(X)}catch(J){return w(String(J)),null}if($==="!")return _;return w(`Could not resolve tag: ${_}`),null}tagString(_){for(let[w,$]of Object.entries(this.tags))if(_.startsWith($))return w+ZY(_.substring($.length));return _[0]==="!"?_:`!<${_}>`}toString(_){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],$=Object.entries(this.tags),X;if(_&&$.length>0&&u4.isNode(_.contents)){let Y={};SY.visit(_.contents,(J,Q)=>{if(u4.isNode(Q)&&Q.tag)Y[Q.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,J]of $){if(Y==="!!"&&J==="tag:yaml.org,2002:")continue;if(!_||X.some((Q)=>Q.startsWith(J)))w.push(`%TAG ${Y} ${J}`)}return w.join(`
|
|
3
|
+
`)}}M_.defaultYaml={explicit:!1,version:"1.2"};M_.defaultTags={"!!":"tag:yaml.org,2002:"};CY.Directives=M_});var A2=Z((hY)=>{var l4=p(),TY=z0();function kY(_){if(/[\x00-\x19\s,[\]{}]/.test(_)){let $=`Anchor must not contain whitespace or control characters: ${JSON.stringify(_)}`;throw Error($)}return!0}function c4(_){let w=new Set;return TY.visit(_,{Value($,X){if(X.anchor)w.add(X.anchor)}}),w}function d4(_,w){for(let $=1;;++$){let X=`${_}${$}`;if(!w.has(X))return X}}function gY(_,w){let $=[],X=new Map,Y=null;return{onAnchor:(J)=>{$.push(J),Y??(Y=c4(_));let Q=d4(w,Y);return Y.add(Q),Q},setAnchors:()=>{for(let J of $){let Q=X.get(J);if(typeof Q==="object"&&Q.anchor&&(l4.isScalar(Q.node)||l4.isCollection(Q.node)))Q.node.anchor=Q.anchor;else{let W=Error("Failed to resolve repeated object (this should not happen)");throw W.source=J,W}}},sourceObjects:X}}hY.anchorIsValid=kY;hY.anchorNames=c4;hY.createNodeAnchors=gY;hY.findNewAnchor=d4});var s1=Z((uY)=>{function V0(_,w,$,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,J=X.length;Y<J;++Y){let Q=X[Y],W=V0(_,X,String(Y),Q);if(W===void 0)delete X[Y];else if(W!==Q)X[Y]=W}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let J=X.get(Y),Q=V0(_,X,Y,J);if(Q===void 0)X.delete(Y);else if(Q!==J)X.set(Y,Q)}else if(X instanceof Set)for(let Y of Array.from(X)){let J=V0(_,X,Y,Y);if(J===void 0)X.delete(Y);else if(J!==Y)X.delete(Y),X.add(J)}else for(let[Y,J]of Object.entries(X)){let Q=V0(_,X,Y,J);if(Q===void 0)delete X[Y];else if(Q!==J)X[Y]=Q}return _.call(w,$,X)}uY.applyReviver=V0});var t_=Z((dY)=>{var cY=p();function p4(_,w,$){if(Array.isArray(_))return _.map((X,Y)=>p4(X,String(Y),$));if(_&&typeof _.toJSON==="function"){if(!$||!cY.hasAnchor(_))return _.toJSON(w,$);let X={aliasCount:0,count:1,res:void 0};$.anchors.set(_,X),$.onCreate=(J)=>{X.res=J,delete $.onCreate};let Y=_.toJSON(w,$);if($.onCreate)$.onCreate(Y);return Y}if(typeof _==="bigint"&&!$?.keep)return Number(_);return _}dY.toJS=p4});var R2=Z((rY)=>{var iY=s1(),i4=p(),nY=t_();class n4{constructor(_){Object.defineProperty(this,i4.NODE_TYPE,{value:_})}clone(){let _=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(this.range)_.range=this.range.slice();return _}toJS(_,{mapAsMap:w,maxAliasCount:$,onAnchor:X,reviver:Y}={}){if(!i4.isDocument(_))throw TypeError("A document argument is required");let J={anchors:new Map,doc:_,keep:!0,mapAsMap:w===!0,mapKeyWarned:!1,maxAliasCount:typeof $==="number"?$:100},Q=nY.toJS(this,"",J);if(typeof X==="function")for(let{count:W,res:G}of J.anchors.values())X(G,W);return typeof Y==="function"?iY.applyReviver(Y,{"":Q},"",Q):Q}}rY.NodeBase=n4});var O0=Z((_J)=>{var oY=A2(),sY=z0(),dw=p(),tY=R2(),eY=t_();class r4 extends tY.NodeBase{constructor(_){super(dw.ALIAS);this.source=_,Object.defineProperty(this,"tag",{set(){throw Error("Alias nodes cannot have tags")}})}resolve(_,w){if(w?.maxAliasCount===0)throw ReferenceError("Alias resolution is disabled");let $;if(w?.aliasResolveCache)$=w.aliasResolveCache;else if($=[],sY.visit(_,{Node:(Y,J)=>{if(dw.isAlias(J)||dw.hasAnchor(J))$.push(J)}}),w)w.aliasResolveCache=$;let X=void 0;for(let Y of $){if(Y===this)break;if(Y.anchor===this.source)X=Y}if(X&&w){let{anchors:Y,doc:J,maxAliasCount:Q}=w,W=Y.get(X);if(!W)eY.toJS(X,null,w),W=Y.get(X);if(W?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(Q>=0){if(W.count+=1,W.aliasCount===0)W.aliasCount=f2(J,X,Y);if(W.count*W.aliasCount>Q)throw ReferenceError("Excessive alias count indicates a resource exhaustion attack")}}return X}toJSON(_,w){if(!w)return{source:this.source};let $=this.resolve(w.doc,w);if(!$){let X=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(X)}return w.anchors.get($).res}toString(_,w,$){let X=`*${this.source}`;if(_){if(oY.anchorIsValid(this.source),_.options.verifyAliasOrder&&!_.anchors.has(this.source)){let Y=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(Y)}if(_.implicitKey)return`${X} `}return X}}function f2(_,w,$){if(dw.isAlias(w)){let X=w.resolve(_),Y=$&&X&&$.get(X);return Y?Y.count*Y.aliasCount:0}else if(dw.isCollection(w)){let X=0;for(let Y of w.items){let J=f2(_,Y,$);if(J>X)X=J}return X}else if(dw.isPair(w)){let X=f2(_,w.key,$),Y=f2(_,w.value,$);return Math.max(X,Y)}return 1}_J.Alias=r4});var X_=Z((QJ)=>{var $J=p(),XJ=R2(),YJ=t_(),JJ=(_)=>!_||typeof _!=="function"&&typeof _!=="object";class zw extends XJ.NodeBase{constructor(_){super($J.SCALAR);this.value=_}toJSON(_,w){return w?.keep?this.value:YJ.toJS(this.value,_,w)}toString(){return String(this.value)}}zw.BLOCK_FOLDED="BLOCK_FOLDED";zw.BLOCK_LITERAL="BLOCK_LITERAL";zw.PLAIN="PLAIN";zw.QUOTE_DOUBLE="QUOTE_DOUBLE";zw.QUOTE_SINGLE="QUOTE_SINGLE";QJ.Scalar=zw;QJ.isScalarValue=JJ});var M0=Z((UJ)=>{var DJ=O0(),Vw=p(),a4=X_(),qJ="tag:yaml.org,2002:";function BJ(_,w,$){if(w){let X=$.filter((J)=>J.tag===w),Y=X.find((J)=>!J.format)??X[0];if(!Y)throw Error(`Tag ${w} not found`);return Y}return $.find((X)=>X.identify?.(_)&&!X.format)}function HJ(_,w,$){if(Vw.isDocument(_))_=_.contents;if(Vw.isNode(_))return _;if(Vw.isPair(_)){let H=$.schema[Vw.MAP].createNode?.($.schema,null,$);return H.items.push(_),H}if(_ instanceof String||_ instanceof Number||_ instanceof Boolean||typeof BigInt<"u"&&_ instanceof BigInt)_=_.valueOf();let{aliasDuplicateObjects:X,onAnchor:Y,onTagObj:J,schema:Q,sourceObjects:W}=$,G=void 0;if(X&&_&&typeof _==="object")if(G=W.get(_),G)return G.anchor??(G.anchor=Y(_)),new DJ.Alias(G.anchor);else G={anchor:null,node:null},W.set(_,G);if(w?.startsWith("!!"))w=qJ+w.slice(2);let D=BJ(_,w,Q.tags);if(!D){if(_&&typeof _.toJSON==="function")_=_.toJSON();if(!_||typeof _!=="object"){let H=new a4.Scalar(_);if(G)G.node=H;return H}D=_ instanceof Map?Q[Vw.MAP]:(Symbol.iterator in Object(_))?Q[Vw.SEQ]:Q[Vw.MAP]}if(J)J(D),delete $.onTagObj;let q=D?.createNode?D.createNode($.schema,_,$):typeof D?.nodeClass?.from==="function"?D.nodeClass.from($.schema,_,$):new a4.Scalar(_);if(w)q.tag=w;else if(!D.default)q.tag=D.tag;if(G)G.node=q;return q}UJ.createNode=HJ});var L2=Z((MJ)=>{var VJ=M0(),h_=p(),OJ=R2();function t1(_,w,$){let X=$;for(let Y=w.length-1;Y>=0;--Y){let J=w[Y];if(typeof J==="number"&&Number.isInteger(J)&&J>=0){let Q=[];Q[J]=X,X=Q}else X=new Map([[J,X]])}return VJ.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:_,sourceObjects:new Map})}var o4=(_)=>_==null||typeof _==="object"&&!!_[Symbol.iterator]().next().done;class s4 extends OJ.NodeBase{constructor(_,w){super(_);Object.defineProperty(this,"schema",{value:w,configurable:!0,enumerable:!1,writable:!0})}clone(_){let w=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));if(_)w.schema=_;if(w.items=w.items.map(($)=>h_.isNode($)||h_.isPair($)?$.clone(_):$),this.range)w.range=this.range.slice();return w}addIn(_,w){if(o4(_))this.add(w);else{let[$,...X]=_,Y=this.get($,!0);if(h_.isCollection(Y))Y.addIn(X,w);else if(Y===void 0&&this.schema)this.set($,t1(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}deleteIn(_){let[w,...$]=_;if($.length===0)return this.delete(w);let X=this.get(w,!0);if(h_.isCollection(X))return X.deleteIn($);else throw Error(`Expected YAML collection at ${w}. Remaining path: ${$}`)}getIn(_,w){let[$,...X]=_,Y=this.get($,!0);if(X.length===0)return!w&&h_.isScalar(Y)?Y.value:Y;else return h_.isCollection(Y)?Y.getIn(X,w):void 0}hasAllNullValues(_){return this.items.every((w)=>{if(!h_.isPair(w))return!1;let $=w.value;return $==null||_&&h_.isScalar($)&&$.value==null&&!$.commentBefore&&!$.comment&&!$.tag})}hasIn(_){let[w,...$]=_;if($.length===0)return this.has(w);let X=this.get(w,!0);return h_.isCollection(X)?X.hasIn($):!1}setIn(_,w){let[$,...X]=_;if(X.length===0)this.set($,w);else{let Y=this.get($,!0);if(h_.isCollection(Y))Y.setIn(X,w);else if(Y===void 0&&this.schema)this.set($,t1(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}}MJ.Collection=s4;MJ.collectionFromPath=t1;MJ.isEmptyPath=o4});var A0=Z((KJ)=>{var LJ=(_)=>_.replace(/^(?!$)(?: $)?/gm,"#");function e1(_,w){if(/^\n+$/.test(_))return _.substring(1);return w?_.replace(/^(?! *$)/gm,w):_}var FJ=(_,w,$)=>_.endsWith(`
|
|
4
|
+
`)?e1($,w):$.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
`+
|
|
7
|
-
`){if($==="block")U=
|
|
8
|
-
`&&O!=="\t"){let
|
|
9
|
-
`&&
|
|
10
|
-
${w}${_.slice(0,E)}`;else{if($==="quoted"&&q[
|
|
11
|
-
${w}${_.slice(
|
|
12
|
-
`);X=w,Y=w+1,J=_[Y]}return X}
|
|
13
|
-
`){if(J-
|
|
14
|
-
|
|
15
|
-
`;while($[G+2]==="\\"&&$[G+3]==="n"&&$[G+4]!=='"')
|
|
16
|
-
`,G+=2;if(
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test(_))return
|
|
18
|
-
${$}`)+"'";return w.implicitKey?X:
|
|
6
|
+
`+e1($,w):(_.endsWith(" ")?"":" ")+$;KJ.indentComment=e1;KJ.lineComment=FJ;KJ.stringifyComment=LJ});var e4=Z((SJ)=>{function EJ(_,w,$="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:J=20,onFold:Q,onOverflow:W}={}){if(!Y||Y<0)return _;if(Y<J)J=0;let G=Math.max(1+J,1+Y-w.length);if(_.length<=G)return _;let D=[],q={},H=Y-w.length;if(typeof X==="number")if(X>Y-Math.max(2,J))D.push(0);else H=Y-X;let B=void 0,O=void 0,z=!1,U=-1,V=-1,A=-1;if($==="block"){if(U=t4(_,U,w.length),U!==-1)H=U+G}for(let L;L=_[U+=1];){if($==="quoted"&&L==="\\"){switch(V=U,_[U+1]){case"x":U+=3;break;case"u":U+=5;break;case"U":U+=9;break;default:U+=1}A=U}if(L===`
|
|
7
|
+
`){if($==="block")U=t4(_,U,w.length);H=U+w.length+G,B=void 0}else{if(L===" "&&O&&O!==" "&&O!==`
|
|
8
|
+
`&&O!=="\t"){let N=_[U+1];if(N&&N!==" "&&N!==`
|
|
9
|
+
`&&N!=="\t")B=U}if(U>=H)if(B)D.push(B),H=B+G,B=void 0;else if($==="quoted"){while(O===" "||O==="\t")O=L,L=_[U+=1],z=!0;let N=U>A+1?U-2:V-1;if(q[N])return _;D.push(N),q[N]=!0,H=N+G,B=void 0}else z=!0}O=L}if(z&&W)W();if(D.length===0)return _;if(Q)Q();let R=_.slice(0,D[0]);for(let L=0;L<D.length;++L){let N=D[L],E=D[L+1]||_.length;if(N===0)R=`
|
|
10
|
+
${w}${_.slice(0,E)}`;else{if($==="quoted"&&q[N])R+=`${_[N]}\\`;R+=`
|
|
11
|
+
${w}${_.slice(N+1,E)}`}}return R}function t4(_,w,$){let X=w,Y=w+1,J=_[Y];while(J===" "||J==="\t")if(w<Y+$)J=_[++w];else{do J=_[++w];while(J&&J!==`
|
|
12
|
+
`);X=w,Y=w+1,J=_[Y]}return X}SJ.FOLD_BLOCK="block";SJ.FOLD_FLOW="flow";SJ.FOLD_QUOTED="quoted";SJ.foldFlowLines=EJ});var f0=Z((hJ)=>{var E_=X_(),e_=e4(),K2=(_,w)=>({indentAtStart:w?_.indent.length:_.indentAtStart,lineWidth:_.options.lineWidth,minContentWidth:_.options.minContentWidth}),N2=(_)=>/^(%|---|\.\.\.)/m.test(_);function TJ(_,w,$){if(!w||w<0)return!1;let X=w-$,Y=_.length;if(Y<=X)return!1;for(let J=0,Q=0;J<Y;++J)if(_[J]===`
|
|
13
|
+
`){if(J-Q>X)return!0;if(Q=J+1,Y-Q<=X)return!1}return!0}function R0(_,w){let $=JSON.stringify(_);if(w.options.doubleQuotedAsJSON)return $;let{implicitKey:X}=w,Y=w.options.doubleQuotedMinMultiLineLength,J=w.indent||(N2(_)?" ":""),Q="",W=0;for(let G=0,D=$[G];D;D=$[++G]){if(D===" "&&$[G+1]==="\\"&&$[G+2]==="n")Q+=$.slice(W,G)+"\\ ",G+=1,W=G,D="\\";if(D==="\\")switch($[G+1]){case"u":{Q+=$.slice(W,G);let q=$.substr(G+2,4);switch(q){case"0000":Q+="\\0";break;case"0007":Q+="\\a";break;case"000b":Q+="\\v";break;case"001b":Q+="\\e";break;case"0085":Q+="\\N";break;case"00a0":Q+="\\_";break;case"2028":Q+="\\L";break;case"2029":Q+="\\P";break;default:if(q.substr(0,2)==="00")Q+="\\x"+q.substr(2);else Q+=$.substr(G,6)}G+=5,W=G+1}break;case"n":if(X||$[G+2]==='"'||$.length<Y)G+=1;else{Q+=$.slice(W,G)+`
|
|
14
|
+
|
|
15
|
+
`;while($[G+2]==="\\"&&$[G+3]==="n"&&$[G+4]!=='"')Q+=`
|
|
16
|
+
`,G+=2;if(Q+=J,$[G+2]===" ")Q+="\\";G+=1,W=G+1}break;default:G+=1}}return Q=W?Q+$.slice(W):$,X?Q:e_.foldFlowLines(Q,J,e_.FOLD_QUOTED,K2(w,!1))}function _3(_,w){if(w.options.singleQuote===!1||w.implicitKey&&_.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test(_))return R0(_,w);let $=w.indent||(N2(_)?" ":""),X="'"+_.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${$}`)+"'";return w.implicitKey?X:e_.foldFlowLines(X,$,e_.FOLD_FLOW,K2(w,!1))}function pw(_,w){let{singleQuote:$}=w.options,X;if($===!1)X=R0;else{let Y=_.includes('"'),J=_.includes("'");if(Y&&!J)X=_3;else if(J&&!Y)X=R0;else X=$?_3:R0}return X(_,w)}var w3;try{w3=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{w3=/\n+(?!\n|$)/g}function F2({comment:_,type:w,value:$},X,Y,J){let{blockQuote:Q,commentString:W,lineWidth:G}=X.options;if(!Q||/\n[\t ]+$/.test($))return pw($,X);let D=X.indent||(X.forceBlockIndent||N2($)?" ":""),q=Q==="literal"?!0:Q==="folded"||w===E_.Scalar.BLOCK_FOLDED?!1:w===E_.Scalar.BLOCK_LITERAL?!0:!TJ($,G,D.length);if(!$)return q?`|
|
|
22
22
|
`:`>
|
|
23
23
|
`;let H,B;for(B=$.length;B>0;--B){let E=$[B-1];if(E!==`
|
|
24
24
|
`&&E!=="\t"&&E!==" ")break}let O=$.substring(B),z=O.indexOf(`
|
|
25
25
|
`);if(z===-1)H="-";else if($===O||z!==O.length-1){if(H="+",J)J()}else H="";if(O){if($=$.slice(0,-O.length),O[O.length-1]===`
|
|
26
|
-
`)O=O.slice(0,-1);O=O.replace(
|
|
27
|
-
`)
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
`)||q&&/[[\]{},]/.test(J))return
|
|
32
|
-
`)?
|
|
33
|
-
`))return
|
|
34
|
-
${G}`);if(
|
|
35
|
-
${w.indent}${W}`}
|
|
36
|
-
${W}:`}else if(V=`${V}:`,B)V+=
|
|
37
|
-
`:"",R){let
|
|
38
|
-
${
|
|
39
|
-
`&&
|
|
40
|
-
|
|
41
|
-
`}else
|
|
42
|
-
${$.indent}`}else if(!O&&
|
|
43
|
-
`),
|
|
26
|
+
`)O=O.slice(0,-1);O=O.replace(w3,`$&${D}`)}let U=!1,V,A=-1;for(V=0;V<$.length;++V){let E=$[V];if(E===" ")U=!0;else if(E===`
|
|
27
|
+
`)A=V;else break}let R=$.substring(0,A<V?A+1:V);if(R)$=$.substring(R.length),R=R.replace(/\n+/g,`$&${D}`);let N=(U?D?"2":"1":"")+H;if(_){if(N+=" "+W(_.replace(/ ?[\r\n]+/g," ")),Y)Y()}if(!q){let E=$.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${D}`),b=!1,C=K2(X,!0);if(Q!=="folded"&&w!==E_.Scalar.BLOCK_FOLDED)C.onOverflow=()=>{b=!0};let K=e_.foldFlowLines(`${R}${E}${O}`,D,e_.FOLD_BLOCK,C);if(!b)return`>${N}
|
|
29
|
+
${D}${K}`}return $=$.replace(/\n+/g,`$&${D}`),`|${N}
|
|
30
|
+
${D}${R}${$}${O}`}function kJ(_,w,$,X){let{type:Y,value:J}=_,{actualString:Q,implicitKey:W,indent:G,indentStep:D,inFlow:q}=w;if(W&&J.includes(`
|
|
31
|
+
`)||q&&/[[\]{},]/.test(J))return pw(J,w);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(J))return W||q||!J.includes(`
|
|
32
|
+
`)?pw(J,w):F2(_,w,$,X);if(!W&&!q&&Y!==E_.Scalar.PLAIN&&J.includes(`
|
|
33
|
+
`))return F2(_,w,$,X);if(N2(J)){if(G==="")return w.forceBlockIndent=!0,F2(_,w,$,X);else if(W&&G===D)return pw(J,w)}let H=J.replace(/\n+/g,`$&
|
|
34
|
+
${G}`);if(Q){let B=(U)=>U.default&&U.tag!=="tag:yaml.org,2002:str"&&U.test?.test(H),{compat:O,tags:z}=w.doc.schema;if(z.some(B)||O?.some(B))return pw(J,w)}return W?H:e_.foldFlowLines(H,G,e_.FOLD_FLOW,K2(w,!1))}function gJ(_,w,$,X){let{implicitKey:Y,inFlow:J}=w,Q=typeof _.value==="string"?_:Object.assign({},_,{value:String(_.value)}),{type:W}=_;if(W!==E_.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(Q.value))W=E_.Scalar.QUOTE_DOUBLE}let G=(q)=>{switch(q){case E_.Scalar.BLOCK_FOLDED:case E_.Scalar.BLOCK_LITERAL:return Y||J?pw(Q.value,w):F2(Q,w,$,X);case E_.Scalar.QUOTE_DOUBLE:return R0(Q.value,w);case E_.Scalar.QUOTE_SINGLE:return _3(Q.value,w);case E_.Scalar.PLAIN:return kJ(Q,w,$,X);default:return null}},D=G(W);if(D===null){let{defaultKeyType:q,defaultStringType:H}=w.options,B=Y&&q||H;if(D=G(B),D===null)throw Error(`Unsupported default string type ${B}`)}return D}hJ.stringifyString=gJ});var L0=Z((pJ)=>{var vJ=A2(),_w=p(),xJ=A0(),mJ=f0();function uJ(_,w){let $=Object.assign({blockQuote:!0,commentString:xJ.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},_.schema.toStringOptions,w),X;switch($.collectionStyle){case"block":X=!1;break;case"flow":X=!0;break;default:X=null}return{anchors:new Set,doc:_,flowCollectionPadding:$.flowCollectionPadding?" ":"",indent:"",indentStep:typeof $.indent==="number"?" ".repeat($.indent):" ",inFlow:X,options:$}}function lJ(_,w){if(w.tag){let Y=_.filter((J)=>J.tag===w.tag);if(Y.length>0)return Y.find((J)=>J.format===w.format)??Y[0]}let $=void 0,X;if(_w.isScalar(w)){X=w.value;let Y=_.filter((J)=>J.identify?.(X));if(Y.length>1){let J=Y.filter((Q)=>Q.test);if(J.length>0)Y=J}$=Y.find((J)=>J.format===w.format)??Y.find((J)=>!J.format)}else X=w,$=_.find((Y)=>Y.nodeClass&&X instanceof Y.nodeClass);if(!$){let Y=X?.constructor?.name??(X===null?"null":typeof X);throw Error(`Tag not resolved for ${Y} value`)}return $}function cJ(_,w,{anchors:$,doc:X}){if(!X.directives)return"";let Y=[],J=(_w.isScalar(_)||_w.isCollection(_))&&_.anchor;if(J&&vJ.anchorIsValid(J))$.add(J),Y.push(`&${J}`);let Q=_.tag??(w.default?null:w.tag);if(Q)Y.push(X.directives.tagString(Q));return Y.join(" ")}function dJ(_,w,$,X){if(_w.isPair(_))return _.toString(w,$,X);if(_w.isAlias(_)){if(w.doc.directives)return _.toString(w);if(w.resolvedAliases?.has(_))throw TypeError("Cannot stringify circular structure without alias nodes");else{if(w.resolvedAliases)w.resolvedAliases.add(_);else w.resolvedAliases=new Set([_]);_=_.resolve(w.doc)}}let Y=void 0,J=_w.isNode(_)?_:w.doc.createNode(_,{onTagObj:(G)=>Y=G});Y??(Y=lJ(w.doc.schema.tags,J));let Q=cJ(J,Y,w);if(Q.length>0)w.indentAtStart=(w.indentAtStart??0)+Q.length+1;let W=typeof Y.stringify==="function"?Y.stringify(J,w,$,X):_w.isScalar(J)?mJ.stringifyString(J,w,$,X):J.toString(w,$,X);if(!Q)return W;return _w.isScalar(J)||W[0]==="{"||W[0]==="["?`${Q} ${W}`:`${Q}
|
|
35
|
+
${w.indent}${W}`}pJ.createStringifyContext=uJ;pJ.stringify=dJ});var $8=Z((aJ)=>{var d_=p(),_8=X_(),w8=L0(),F0=A0();function rJ({key:_,value:w},$,X,Y){let{allNullValues:J,doc:Q,indent:W,indentStep:G,options:{commentString:D,indentSeq:q,simpleKeys:H}}=$,B=d_.isNode(_)&&_.comment||null;if(H){if(B)throw Error("With simple keys, key nodes cannot have comments");if(d_.isCollection(_)||!d_.isNode(_)&&typeof _==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!H&&(!_||B&&w==null&&!$.inFlow||d_.isCollection(_)||(d_.isScalar(_)?_.type===_8.Scalar.BLOCK_FOLDED||_.type===_8.Scalar.BLOCK_LITERAL:typeof _==="object"));$=Object.assign({},$,{allNullValues:!1,implicitKey:!O&&(H||!J),indent:W+G});let z=!1,U=!1,V=w8.stringify(_,$,()=>z=!0,()=>U=!0);if(!O&&!$.inFlow&&V.length>1024){if(H)throw Error("With simple keys, single line scalar must not span more than 1024 characters");O=!0}if($.inFlow){if(J||w==null){if(z&&X)X();return V===""?"?":O?`? ${V}`:V}}else if(J&&!H||w==null&&O){if(V=`? ${V}`,B&&!z)V+=F0.lineComment(V,$.indent,D(B));else if(U&&Y)Y();return V}if(z)B=null;if(O){if(B)V+=F0.lineComment(V,$.indent,D(B));V=`? ${V}
|
|
36
|
+
${W}:`}else if(V=`${V}:`,B)V+=F0.lineComment(V,$.indent,D(B));let A,R,L;if(d_.isNode(w))A=!!w.spaceBefore,R=w.commentBefore,L=w.comment;else if(A=!1,R=null,L=null,w&&typeof w==="object")w=Q.createNode(w);if($.implicitKey=!1,!O&&!B&&d_.isScalar(w))$.indentAtStart=V.length+1;if(U=!1,!q&&G.length>=2&&!$.inFlow&&!O&&d_.isSeq(w)&&!w.flow&&!w.tag&&!w.anchor)$.indent=$.indent.substring(2);let N=!1,E=w8.stringify(w,$,()=>N=!0,()=>U=!0),b=" ";if(B||A||R){if(b=A?`
|
|
37
|
+
`:"",R){let C=D(R);b+=`
|
|
38
|
+
${F0.indentComment(C,$.indent)}`}if(E===""&&!$.inFlow){if(b===`
|
|
39
|
+
`&&L)b=`
|
|
40
|
+
|
|
41
|
+
`}else b+=`
|
|
42
|
+
${$.indent}`}else if(!O&&d_.isCollection(w)){let C=E[0],K=E.indexOf(`
|
|
43
|
+
`),P=K!==-1,g=$.inFlow??w.flow??w.items.length===0;if(P||!g){let i=!1;if(P&&(C==="&"||C==="!")){let v=E.indexOf(" ");if(C==="&"&&v!==-1&&v<K&&E[v+1]==="!")v=E.indexOf(" ",v+1);if(v===-1||K<v)i=!0}if(!i)b=`
|
|
44
44
|
${$.indent}`}}else if(E===""||E[0]===`
|
|
45
|
-
`)
|
|
45
|
+
`)b="";if(V+=b+E,$.inFlow){if(N&&X)X()}else if(L&&!N)V+=F0.lineComment(V,$.indent,D(L));else if(U&&Y)Y();return V}aJ.stringifyPair=rJ});var $3=Z((eJ)=>{var X8=X2("process");function sJ(_,...w){if(_==="debug")console.log(...w)}function tJ(_,w){if(_==="debug"||_==="warn")if(typeof X8.emitWarning==="function")X8.emitWarning(w);else console.warn(w)}eJ.debug=sJ;eJ.warn=tJ});var S2=Z((XQ)=>{var E2=p(),Y8=X_(),b2="<<",j2={identify:(_)=>_===b2||typeof _==="symbol"&&_.description===b2,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Y8.Scalar(Symbol(b2)),{addToJSMap:J8}),stringify:()=>b2},$Q=(_,w)=>(j2.identify(w)||E2.isScalar(w)&&(!w.type||w.type===Y8.Scalar.PLAIN)&&j2.identify(w.value))&&_?.doc.schema.tags.some(($)=>$.tag===j2.tag&&$.default);function J8(_,w,$){let X=Q8(_,$);if(E2.isSeq(X))for(let Y of X.items)X3(_,w,Y);else if(Array.isArray(X))for(let Y of X)X3(_,w,Y);else X3(_,w,X)}function X3(_,w,$){let X=Q8(_,$);if(!E2.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,_,Map);for(let[J,Q]of Y)if(w instanceof Map){if(!w.has(J))w.set(J,Q)}else if(w instanceof Set)w.add(J);else if(!Object.prototype.hasOwnProperty.call(w,J))Object.defineProperty(w,J,{value:Q,writable:!0,enumerable:!0,configurable:!0});return w}function Q8(_,w){return _&&E2.isAlias(w)?w.resolve(_.doc,_):w}XQ.addMergeToJSMap=J8;XQ.isMergeKey=$Q;XQ.merge=j2});var J3=Z((BQ)=>{var WQ=$3(),W8=S2(),GQ=L0(),G8=p(),Y3=t_();function DQ(_,w,{key:$,value:X}){if(G8.isNode($)&&$.addToJSMap)$.addToJSMap(_,w,X);else if(W8.isMergeKey(_,$))W8.addMergeToJSMap(_,w,X);else{let Y=Y3.toJS($,"",_);if(w instanceof Map)w.set(Y,Y3.toJS(X,Y,_));else if(w instanceof Set)w.add(Y);else{let J=qQ($,Y,_),Q=Y3.toJS(X,J,_);if(J in w)Object.defineProperty(w,J,{value:Q,writable:!0,enumerable:!0,configurable:!0});else w[J]=Q}}return w}function qQ(_,w,$){if(w===null)return"";if(typeof w!=="object")return String(w);if(G8.isNode(_)&&$?.doc){let X=GQ.createStringifyContext($.doc,{});X.anchors=new Set;for(let J of $.anchors.keys())X.anchors.add(J.anchor);X.inFlow=!0,X.inStringifyKey=!0;let Y=_.toString(X);if(!$.mapKeyWarned){let J=JSON.stringify(Y);if(J.length>40)J=J.substring(0,36)+'..."';WQ.warn($.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${J}. Set mapAsMap: true to use object keys.`),$.mapKeyWarned=!0}return Y}return JSON.stringify(w)}BQ.addPairToJSMap=DQ});var ww=Z((OQ)=>{var D8=M0(),UQ=$8(),zQ=J3(),P2=p();function VQ(_,w,$){let X=D8.createNode(_,void 0,$),Y=D8.createNode(w,void 0,$);return new Z2(X,Y)}class Z2{constructor(_,w=null){Object.defineProperty(this,P2.NODE_TYPE,{value:P2.PAIR}),this.key=_,this.value=w}clone(_){let{key:w,value:$}=this;if(P2.isNode(w))w=w.clone(_);if(P2.isNode($))$=$.clone(_);return new Z2(w,$)}toJSON(_,w){let $=w?.mapAsMap?new Map:{};return zQ.addPairToJSMap(w,$,this)}toString(_,w,$){return _?.doc?UQ.stringifyPair(this,_,w,$):JSON.stringify(this)}}OQ.Pair=Z2;OQ.createPair=VQ});var Q3=Z((FQ)=>{var Ow=p(),q8=L0(),C2=A0();function RQ(_,w,$){return(w.inFlow??_.flow?LQ:fQ)(_,w,$)}function fQ({comment:_,items:w},$,{blockItemPrefix:X,flowChars:Y,itemIndent:J,onChompKeep:Q,onComment:W}){let{indent:G,options:{commentString:D}}=$,q=Object.assign({},$,{indent:J,type:null}),H=!1,B=[];for(let z=0;z<w.length;++z){let U=w[z],V=null;if(Ow.isNode(U)){if(!H&&U.spaceBefore)B.push("");if(I2($,B,U.commentBefore,H),U.comment)V=U.comment}else if(Ow.isPair(U)){let R=Ow.isNode(U.key)?U.key:null;if(R){if(!H&&R.spaceBefore)B.push("");I2($,B,R.commentBefore,H)}}H=!1;let A=q8.stringify(U,q,()=>V=null,()=>H=!0);if(V)A+=C2.lineComment(A,J,D(V));if(H&&V)H=!1;B.push(X+A)}let O;if(B.length===0)O=Y.start+Y.end;else{O=B[0];for(let z=1;z<B.length;++z){let U=B[z];O+=U?`
|
|
46
46
|
${G}${U}`:`
|
|
47
47
|
`}}if(_){if(O+=`
|
|
48
|
-
`+
|
|
49
|
-
`)),z<_.length-1)
|
|
48
|
+
`+C2.indentComment(D(_),G),W)W()}else if(H&&Q)Q();return O}function LQ({items:_},w,{flowChars:$,itemIndent:X}){let{indent:Y,indentStep:J,flowCollectionPadding:Q,options:{commentString:W}}=w;X+=J;let G=Object.assign({},w,{indent:X,inFlow:!0,type:null}),D=!1,q=0,H=[];for(let z=0;z<_.length;++z){let U=_[z],V=null;if(Ow.isNode(U)){if(U.spaceBefore)H.push("");if(I2(w,H,U.commentBefore,!1),U.comment)V=U.comment}else if(Ow.isPair(U)){let R=Ow.isNode(U.key)?U.key:null;if(R){if(R.spaceBefore)H.push("");if(I2(w,H,R.commentBefore,!1),R.comment)D=!0}let L=Ow.isNode(U.value)?U.value:null;if(L){if(L.comment)V=L.comment;if(L.commentBefore)D=!0}else if(U.value==null&&R?.comment)V=R.comment}if(V)D=!0;let A=q8.stringify(U,G,()=>V=null);if(D||(D=H.length>q||A.includes(`
|
|
49
|
+
`)),z<_.length-1)A+=",";else if(w.options.trailingComma){if(w.options.lineWidth>0)D||(D=H.reduce((R,L)=>R+L.length+2,2)+(A.length+2)>w.options.lineWidth);if(D)A+=","}if(V)A+=C2.lineComment(A,X,W(V));H.push(A),q=H.length}let{start:B,end:O}=$;if(H.length===0)return B+O;else{if(!D){let z=H.reduce((U,V)=>U+V.length+2,2);D=w.options.lineWidth>0&&z>w.options.lineWidth}if(D){let z=B;for(let U of H)z+=U?`
|
|
50
50
|
${J}${Y}${U}`:`
|
|
51
51
|
`;return`${z}
|
|
52
|
-
${Y}${O}`}else return`${B}${
|
|
53
|
-
`:" ")}return
|
|
52
|
+
${Y}${O}`}else return`${B}${Q}${H.join(" ")}${Q}${O}`}}function I2({indent:_,options:{commentString:w}},$,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let J=C2.indentComment(w(X),_);$.push(J.trimStart())}}FQ.stringifyCollection=RQ});var Xw=Z((SQ)=>{var NQ=Q3(),bQ=J3(),jQ=L2(),$w=p(),T2=ww(),EQ=X_();function K0(_,w){let $=$w.isScalar(w)?w.value:w;for(let X of _)if($w.isPair(X)){if(X.key===w||X.key===$)return X;if($w.isScalar(X.key)&&X.key.value===$)return X}return}class B8 extends jQ.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(_){super($w.MAP,_);this.items=[]}static from(_,w,$){let{keepUndefined:X,replacer:Y}=$,J=new this(_),Q=(W,G)=>{if(typeof Y==="function")G=Y.call(w,W,G);else if(Array.isArray(Y)&&!Y.includes(W))return;if(G!==void 0||X)J.items.push(T2.createPair(W,G,$))};if(w instanceof Map)for(let[W,G]of w)Q(W,G);else if(w&&typeof w==="object")for(let W of Object.keys(w))Q(W,w[W]);if(typeof _.sortMapEntries==="function")J.items.sort(_.sortMapEntries);return J}add(_,w){let $;if($w.isPair(_))$=_;else if(!_||typeof _!=="object"||!("key"in _))$=new T2.Pair(_,_?.value);else $=new T2.Pair(_.key,_.value);let X=K0(this.items,$.key),Y=this.schema?.sortMapEntries;if(X){if(!w)throw Error(`Key ${$.key} already set`);if($w.isScalar(X.value)&&EQ.isScalarValue($.value))X.value.value=$.value;else X.value=$.value}else if(Y){let J=this.items.findIndex((Q)=>Y($,Q)<0);if(J===-1)this.items.push($);else this.items.splice(J,0,$)}else this.items.push($)}delete(_){let w=K0(this.items,_);if(!w)return!1;return this.items.splice(this.items.indexOf(w),1).length>0}get(_,w){let X=K0(this.items,_)?.value;return(!w&&$w.isScalar(X)?X.value:X)??void 0}has(_){return!!K0(this.items,_)}set(_,w){this.add(new T2.Pair(_,w),!0)}toJSON(_,w,$){let X=$?new $:w?.mapAsMap?new Map:{};if(w?.onCreate)w.onCreate(X);for(let Y of this.items)bQ.addPairToJSMap(w,X,Y);return X}toString(_,w,$){if(!_)return JSON.stringify(this);for(let X of this.items)if(!$w.isPair(X))throw Error(`Map items must all be pairs; found ${JSON.stringify(X)} instead`);if(!_.allNullValues&&this.hasAllNullValues(!1))_=Object.assign({},_,{allNullValues:!0});return NQ.stringifyCollection(this,_,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:_.indent||"",onChompKeep:$,onComment:w})}}SQ.YAMLMap=B8;SQ.findPair=K0});var iw=Z((TQ)=>{var CQ=p(),H8=Xw(),IQ={collection:"map",default:!0,nodeClass:H8.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(_,w){if(!CQ.isMap(_))w("Expected a mapping for this tag");return _},createNode:(_,w,$)=>H8.YAMLMap.from(_,w,$)};TQ.map=IQ});var Yw=Z((mQ)=>{var gQ=M0(),hQ=Q3(),yQ=L2(),g2=p(),vQ=X_(),xQ=t_();class U8 extends yQ.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(_){super(g2.SEQ,_);this.items=[]}add(_){this.items.push(_)}delete(_){let w=k2(_);if(typeof w!=="number")return!1;return this.items.splice(w,1).length>0}get(_,w){let $=k2(_);if(typeof $!=="number")return;let X=this.items[$];return!w&&g2.isScalar(X)?X.value:X}has(_){let w=k2(_);return typeof w==="number"&&w<this.items.length}set(_,w){let $=k2(_);if(typeof $!=="number")throw Error(`Expected a valid index, not ${_}.`);let X=this.items[$];if(g2.isScalar(X)&&vQ.isScalarValue(w))X.value=w;else this.items[$]=w}toJSON(_,w){let $=[];if(w?.onCreate)w.onCreate($);let X=0;for(let Y of this.items)$.push(xQ.toJS(Y,String(X++),w));return $}toString(_,w,$){if(!_)return JSON.stringify(this);return hQ.stringifyCollection(this,_,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(_.indent||"")+" ",onChompKeep:$,onComment:w})}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w)){let J=0;for(let Q of w){if(typeof X==="function"){let W=w instanceof Set?Q:String(J++);Q=X.call(w,W,Q)}Y.items.push(gQ.createNode(Q,void 0,$))}}return Y}}function k2(_){let w=g2.isScalar(_)?_.value:_;if(w&&typeof w==="string")w=Number(w);return typeof w==="number"&&Number.isInteger(w)&&w>=0?w:null}mQ.YAMLSeq=U8});var nw=Z((dQ)=>{var lQ=p(),z8=Yw(),cQ={collection:"seq",default:!0,nodeClass:z8.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(_,w){if(!lQ.isSeq(_))w("Expected a sequence for this tag");return _},createNode:(_,w,$)=>z8.YAMLSeq.from(_,w,$)};dQ.seq=cQ});var N0=Z((rQ)=>{var iQ=f0(),nQ={identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify(_,w,$,X){return w=Object.assign({actualString:!0},w),iQ.stringifyString(_,w,$,X)}};rQ.string=nQ});var h2=Z((oQ)=>{var V8=X_(),O8={identify:(_)=>_==null,createNode:()=>new V8.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new V8.Scalar(null),stringify:({source:_},w)=>typeof _==="string"&&O8.test.test(_)?_:w.options.nullStr};oQ.nullTag=O8});var W3=Z((eQ)=>{var tQ=X_(),M8={identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(_)=>new tQ.Scalar(_[0]==="t"||_[0]==="T"),stringify({source:_,value:w},$){if(_&&M8.test.test(_)){let X=_[0]==="t"||_[0]==="T";if(w===X)return _}return w?$.options.trueStr:$.options.falseStr}};eQ.boolTag=M8});var rw=Z(($W)=>{function wW({format:_,minFractionDigits:w,tag:$,value:X}){if(typeof X==="bigint")return String(X);let Y=typeof X==="number"?X:Number(X);if(!isFinite(Y))return isNaN(Y)?".nan":Y<0?"-.inf":".inf";let J=Object.is(X,-0)?"-0":JSON.stringify(X);if(!_&&w&&(!$||$==="tag:yaml.org,2002:float")&&/^-?\d/.test(J)&&!J.includes("e")){let Q=J.indexOf(".");if(Q<0)Q=J.length,J+=".";let W=w-(J.length-Q-1);while(W-- >0)J+="0"}return J}$W.stringifyNumber=wW});var D3=Z((GW)=>{var YW=X_(),G3=rw(),JW={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:G3.stringifyNumber},QW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():G3.stringifyNumber(_)}},WW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(_){let w=new YW.Scalar(parseFloat(_)),$=_.indexOf(".");if($!==-1&&_[_.length-1]==="0")w.minFractionDigits=_.length-$-1;return w},stringify:G3.stringifyNumber};GW.float=WW;GW.floatExp=QW;GW.floatNaN=JW});var B3=Z((VW)=>{var A8=rw(),y2=(_)=>typeof _==="bigint"||Number.isInteger(_),q3=(_,w,$,{intAsBigInt:X})=>X?BigInt(_):parseInt(_.substring(w),$);function R8(_,w,$){let{value:X}=_;if(y2(X)&&X>=0)return $+X.toString(w);return A8.stringifyNumber(_)}var HW={identify:(_)=>y2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(_,w,$)=>q3(_,2,8,$),stringify:(_)=>R8(_,8,"0o")},UW={identify:y2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(_,w,$)=>q3(_,0,10,$),stringify:A8.stringifyNumber},zW={identify:(_)=>y2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(_,w,$)=>q3(_,2,16,$),stringify:(_)=>R8(_,16,"0x")};VW.int=UW;VW.intHex=zW;VW.intOct=HW});var f8=Z((bW)=>{var RW=iw(),fW=h2(),LW=nw(),FW=N0(),KW=W3(),H3=D3(),U3=B3(),NW=[RW.map,LW.seq,FW.string,fW.nullTag,KW.boolTag,U3.intOct,U3.int,U3.intHex,H3.floatNaN,H3.floatExp,H3.float];bW.schema=NW});var F8=Z((TW)=>{var EW=X_(),SW=iw(),PW=nw();function L8(_){return typeof _==="bigint"||Number.isInteger(_)}var v2=({value:_})=>JSON.stringify(_),ZW=[{identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify:v2},{identify:(_)=>_==null,createNode:()=>new EW.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:v2},{identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(_)=>_==="true",stringify:v2},{identify:L8,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(_,w,{intAsBigInt:$})=>$?BigInt(_):parseInt(_,10),stringify:({value:_})=>L8(_)?_.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:v2}],CW={default:!0,tag:"",test:/^/,resolve(_,w){return w(`Unresolved plain scalar ${JSON.stringify(_)}`),_}},IW=[SW.map,PW.seq].concat(ZW,CW);TW.schema=IW});var V3=Z((yW)=>{var b0=X2("buffer"),z3=X_(),gW=f0(),hW={identify:(_)=>_ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(_,w){if(typeof b0.Buffer==="function")return b0.Buffer.from(_,"base64");else if(typeof atob==="function"){let $=atob(_.replace(/[\n\r]/g,"")),X=new Uint8Array($.length);for(let Y=0;Y<$.length;++Y)X[Y]=$.charCodeAt(Y);return X}else return w("This environment does not support reading binary tags; either Buffer or atob is required"),_},stringify({comment:_,type:w,value:$},X,Y,J){if(!$)return"";let Q=$,W;if(typeof b0.Buffer==="function")W=Q instanceof b0.Buffer?Q.toString("base64"):b0.Buffer.from(Q.buffer).toString("base64");else if(typeof btoa==="function"){let G="";for(let D=0;D<Q.length;++D)G+=String.fromCharCode(Q[D]);W=btoa(G)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(w??(w=z3.Scalar.BLOCK_LITERAL),w!==z3.Scalar.QUOTE_DOUBLE){let G=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),D=Math.ceil(W.length/G),q=Array(D);for(let H=0,B=0;H<D;++H,B+=G)q[H]=W.substr(B,G);W=q.join(w===z3.Scalar.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return gW.stringifyString({comment:_,type:w,value:W},X,Y,J)}};yW.binary=hW});var m2=Z((lW)=>{var x2=p(),O3=ww(),xW=X_(),mW=Yw();function K8(_,w){if(x2.isSeq(_))for(let $=0;$<_.items.length;++$){let X=_.items[$];if(x2.isPair(X))continue;else if(x2.isMap(X)){if(X.items.length>1)w("Each pair must have its own sequence indicator");let Y=X.items[0]||new O3.Pair(new xW.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
|
|
54
54
|
${Y.key.commentBefore}`:X.commentBefore;if(X.comment){let J=Y.value??Y.key;J.comment=J.comment?`${X.comment}
|
|
55
|
-
${J.comment}`:X.comment}X=Y}_.items[$]=v1.isPair(X)?X:new U3.Pair(X)}else w("Expected a sequence for this tag");return _}function A8(_,w,$){let{replacer:X}=$,Y=new CW.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let D of w){if(typeof X==="function")D=X.call(w,String(J++),D);let W,G;if(Array.isArray(D))if(D.length===2)W=D[0],G=D[1];else throw TypeError(`Expected [key, value] tuple: ${D}`);else if(D&&D instanceof Object){let Q=Object.keys(D);if(Q.length===1)W=Q[0],G=D[W];else throw TypeError(`Expected tuple with one key, not ${Q.length} keys`)}else W=D;Y.items.push(U3.createPair(W,G,$))}return Y}var TW={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:O8,createNode:A8};IW.createPairs=A8;IW.pairs=TW;IW.resolvePairs=O8});var V3=P((xW)=>{var M8=p(),z3=s_(),b0=$w(),yW=Xw(),R8=x1();class Ow extends yW.YAMLSeq{constructor(){super();this.add=b0.YAMLMap.prototype.add.bind(this),this.delete=b0.YAMLMap.prototype.delete.bind(this),this.get=b0.YAMLMap.prototype.get.bind(this),this.has=b0.YAMLMap.prototype.has.bind(this),this.set=b0.YAMLMap.prototype.set.bind(this),this.tag=Ow.tag}toJSON(_,w){if(!w)return super.toJSON(_);let $=new Map;if(w?.onCreate)w.onCreate($);for(let X of this.items){let Y,J;if(M8.isPair(X))Y=z3.toJS(X.key,"",w),J=z3.toJS(X.value,Y,w);else Y=z3.toJS(X,"",w);if($.has(Y))throw Error("Ordered maps must not include duplicate keys");$.set(Y,J)}return $}static from(_,w,$){let X=R8.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Ow.tag="tag:yaml.org,2002:omap";var vW={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Ow,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=R8.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(M8.isScalar(Y))if(X.includes(Y.value))w(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new Ow,$)},createNode:(_,w,$)=>Ow.from(_,w,$)};xW.YAMLOMap=Ow;xW.omap=vW});var N8=P((lW)=>{var f8=X_();function L8({value:_,source:w},$){if(w&&(_?F8:K8).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var F8={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new f8.Scalar(!0),stringify:L8},K8={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new f8.Scalar(!1),stringify:L8};lW.falseTag=K8;lW.trueTag=F8});var b8=P((aW)=>{var pW=X_(),O3=nw(),iW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:(_)=>_.slice(-3).toLowerCase()==="nan"?NaN:_[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:O3.stringifyNumber},nW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_.replace(/_/g,"")),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():O3.stringifyNumber(_)}},rW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new pW.Scalar(parseFloat(_.replace(/_/g,""))),$=_.indexOf(".");if($!==-1){let X=_.substring($+1).replace(/_/g,"");if(X[X.length-1]==="0")w.minFractionDigits=X.length}return w},stringify:O3.stringifyNumber};aW.float=rW;aW.floatExp=nW;aW.floatNaN=iW});var E8=P((XG)=>{var j8=nw(),j0=(_)=>typeof _==="bigint"||Number.isInteger(_);function m1(_,w,$,{intAsBigInt:X}){let Y=_[0];if(Y==="-"||Y==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let D=BigInt(_);return Y==="-"?BigInt(-1)*D:D}let J=parseInt(_,$);return Y==="-"?-1*J:J}function A3(_,w,$){let{value:X}=_;if(j0(X)){let Y=X.toString(w);return X<0?"-"+$+Y.substr(1):$+Y}return j8.stringifyNumber(_)}var eW={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>m1(_,2,2,$),stringify:(_)=>A3(_,2,"0b")},_G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>m1(_,1,8,$),stringify:(_)=>A3(_,8,"0")},wG={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>m1(_,0,10,$),stringify:j8.stringifyNumber},$G={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>m1(_,2,16,$),stringify:(_)=>A3(_,16,"0x")};XG.int=wG;XG.intBin=eW;XG.intHex=$G;XG.intOct=_G});var M3=P((QG)=>{var c1=p(),u1=_w(),l1=$w();class Aw extends l1.YAMLMap{constructor(_){super(_);this.tag=Aw.tag}add(_){let w;if(c1.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new u1.Pair(_.key,null);else w=new u1.Pair(_,null);if(!l1.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=l1.findPair(this.items,_);return!w&&c1.isPair($)?c1.isScalar($.key)?$.key.value:$.key:$}set(_,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let $=l1.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new u1.Pair(_))}toJSON(_,w){return super.toJSON(_,w,Set)}toString(_,w,$){if(!_)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},_,{allNullValues:!0}),w,$);else throw Error("Set items must all have null values")}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof X==="function")J=X.call(w,J,J);Y.items.push(u1.createPair(J,null,$))}return Y}}Aw.tag="tag:yaml.org,2002:set";var GG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Aw,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Aw.from(_,w,$),resolve(_,w){if(c1.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Aw,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};QG.YAMLSet=Aw;QG.set=GG});var f3=P((VG)=>{var BG=nw();function R3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(D)=>w?BigInt(D):Number(D),J=X.replace(/_/g,"").split(":").reduce((D,W)=>D*Y(60)+Y(W),Y(0));return $==="-"?Y(-1)*J:J}function S8(_){let{value:w}=_,$=(D)=>D;if(typeof w==="bigint")$=(D)=>BigInt(D);else if(isNaN(w)||!isFinite(w))return BG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let Y=$(60),J=[w%Y];if(w<60)J.unshift(0);else if(w=(w-J[0])/Y,J.unshift(w%Y),w>=60)w=(w-J[0])/Y,J.unshift(w);return X+J.map((D)=>String(D).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var UG={identify:(_)=>typeof _==="bigint"||Number.isInteger(_),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(_,w,{intAsBigInt:$})=>R3(_,$),stringify:S8},zG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:(_)=>R3(_,!1),stringify:S8},P8={identify:(_)=>_ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(_){let w=_.match(P8.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,D,W]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,Q=Date.UTC($,X-1,Y,J||0,D||0,W||0,G),q=w[8];if(q&&q!=="Z"){let H=R3(q,!1);if(Math.abs(H)<30)H*=60;Q-=60000*H}return new Date(Q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};VG.floatTime=zG;VG.intTime=UG;VG.timestamp=P8});var C8=P((PG)=>{var RG=pw(),fG=g1(),LG=iw(),FG=K0(),KG=B3(),Z8=N8(),L3=b8(),d1=E8(),NG=E1(),bG=V3(),jG=x1(),EG=M3(),F3=f3(),SG=[RG.map,LG.seq,FG.string,fG.nullTag,Z8.trueTag,Z8.falseTag,d1.intBin,d1.intOct,d1.int,d1.intHex,L3.floatNaN,L3.floatExp,L3.float,KG.binary,NG.merge,bG.omap,jG.pairs,EG.set,F3.intTime,F3.floatTime,F3.timestamp];PG.schema=SG});var u8=P((vG)=>{var g8=pw(),CG=g1(),h8=iw(),TG=K0(),IG=Y3(),K3=D3(),N3=G3(),kG=U8(),gG=V8(),y8=B3(),E0=E1(),v8=V3(),x8=x1(),T8=C8(),m8=M3(),p1=f3(),I8=new Map([["core",kG.schema],["failsafe",[g8.map,h8.seq,TG.string]],["json",gG.schema],["yaml11",T8.schema],["yaml-1.1",T8.schema]]),k8={binary:y8.binary,bool:IG.boolTag,float:K3.float,floatExp:K3.floatExp,floatNaN:K3.floatNaN,floatTime:p1.floatTime,int:N3.int,intHex:N3.intHex,intOct:N3.intOct,intTime:p1.intTime,map:g8.map,merge:E0.merge,null:CG.nullTag,omap:v8.omap,pairs:x8.pairs,seq:h8.seq,set:m8.set,timestamp:p1.timestamp},hG={"tag:yaml.org,2002:binary":y8.binary,"tag:yaml.org,2002:merge":E0.merge,"tag:yaml.org,2002:omap":v8.omap,"tag:yaml.org,2002:pairs":x8.pairs,"tag:yaml.org,2002:set":m8.set,"tag:yaml.org,2002:timestamp":p1.timestamp};function yG(_,w,$){let X=I8.get(w);if(X&&!_)return $&&!X.includes(E0.merge)?X.concat(E0.merge):X.slice();let Y=X;if(!Y)if(Array.isArray(_))Y=[];else{let J=Array.from(I8.keys()).filter((D)=>D!=="yaml11").map((D)=>JSON.stringify(D)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${J} or define customTags array`)}if(Array.isArray(_))for(let J of _)Y=Y.concat(J);else if(typeof _==="function")Y=_(Y.slice());if($)Y=Y.concat(E0.merge);return Y.reduce((J,D)=>{let W=typeof D==="string"?k8[D]:D;if(!W){let G=JSON.stringify(D),Q=Object.keys(k8).map((q)=>JSON.stringify(q)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${Q}`)}if(!J.includes(W))J.push(W);return J},[])}vG.coreKnownTags=hG;vG.getTags=yG});var E3=P((pG)=>{var b3=p(),uG=pw(),lG=iw(),cG=K0(),i1=u8(),dG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class j3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:D}){this.compat=Array.isArray(_)?i1.getTags(_,"compat"):_?i1.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?i1.coreKnownTags:{},this.tags=i1.getTags(w,this.name,$),this.toStringOptions=D??null,Object.defineProperty(this,b3.MAP,{value:uG.map}),Object.defineProperty(this,b3.SCALAR,{value:cG.string}),Object.defineProperty(this,b3.SEQ,{value:lG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?dG:null}clone(){let _=Object.create(j3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}pG.Schema=j3});var l8=P((aG)=>{var nG=p(),S3=f0(),S0=A0();function rG(_,w){let $=[],X=w.directives===!0;if(w.directives!==!1&&_.directives){let G=_.directives.toString(_);if(G)$.push(G),X=!0;else if(_.directives.docStart)X=!0}if(X)$.push("---");let Y=S3.createStringifyContext(_,w),{commentString:J}=Y.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=J(_.commentBefore);$.unshift(S0.indentComment(G,""))}let D=!1,W=null;if(_.contents){if(nG.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let q=J(_.contents.commentBefore);$.push(S0.indentComment(q,""))}Y.forceBlockIndent=!!_.comment,W=_.contents.comment}let G=W?void 0:()=>D=!0,Q=S3.stringify(_.contents,Y,()=>W=null,G);if(W)Q+=S0.lineComment(Q,"",J(W));if((Q[0]==="|"||Q[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${Q}`;else $.push(Q)}else $.push(S3.stringify(_.contents,Y));if(_.directives?.docEnd)if(_.comment){let G=J(_.comment);if(G.includes(`
|
|
56
|
-
`))$.push("..."),$.push(
|
|
55
|
+
${J.comment}`:X.comment}X=Y}_.items[$]=x2.isPair(X)?X:new O3.Pair(X)}else w("Expected a sequence for this tag");return _}function N8(_,w,$){let{replacer:X}=$,Y=new mW.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let Q of w){if(typeof X==="function")Q=X.call(w,String(J++),Q);let W,G;if(Array.isArray(Q))if(Q.length===2)W=Q[0],G=Q[1];else throw TypeError(`Expected [key, value] tuple: ${Q}`);else if(Q&&Q instanceof Object){let D=Object.keys(Q);if(D.length===1)W=D[0],G=Q[W];else throw TypeError(`Expected tuple with one key, not ${D.length} keys`)}else W=Q;Y.items.push(O3.createPair(W,G,$))}return Y}var uW={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:K8,createNode:N8};lW.createPairs=N8;lW.pairs=uW;lW.resolvePairs=K8});var A3=Z((rW)=>{var b8=p(),M3=t_(),j0=Xw(),iW=Yw(),j8=m2();class Mw extends iW.YAMLSeq{constructor(){super();this.add=j0.YAMLMap.prototype.add.bind(this),this.delete=j0.YAMLMap.prototype.delete.bind(this),this.get=j0.YAMLMap.prototype.get.bind(this),this.has=j0.YAMLMap.prototype.has.bind(this),this.set=j0.YAMLMap.prototype.set.bind(this),this.tag=Mw.tag}toJSON(_,w){if(!w)return super.toJSON(_);let $=new Map;if(w?.onCreate)w.onCreate($);for(let X of this.items){let Y,J;if(b8.isPair(X))Y=M3.toJS(X.key,"",w),J=M3.toJS(X.value,Y,w);else Y=M3.toJS(X,"",w);if($.has(Y))throw Error("Ordered maps must not include duplicate keys");$.set(Y,J)}return $}static from(_,w,$){let X=j8.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Mw.tag="tag:yaml.org,2002:omap";var nW={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Mw,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=j8.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(b8.isScalar(Y))if(X.includes(Y.value))w(`Ordered maps must not include duplicate keys: ${Y.value}`);else X.push(Y.value);return Object.assign(new Mw,$)},createNode:(_,w,$)=>Mw.from(_,w,$)};rW.YAMLOMap=Mw;rW.omap=nW});var C8=Z((sW)=>{var E8=X_();function S8({value:_,source:w},$){if(w&&(_?P8:Z8).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var P8={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new E8.Scalar(!0),stringify:S8},Z8={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new E8.Scalar(!1),stringify:S8};sW.falseTag=Z8;sW.trueTag=P8});var I8=Z((YG)=>{var _G=X_(),R3=rw(),wG={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:R3.stringifyNumber},$G={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:(_)=>parseFloat(_.replace(/_/g,"")),stringify(_){let w=Number(_.value);return isFinite(w)?w.toExponential():R3.stringifyNumber(_)}},XG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new _G.Scalar(parseFloat(_.replace(/_/g,""))),$=_.indexOf(".");if($!==-1){let X=_.substring($+1).replace(/_/g,"");if(X[X.length-1]==="0")w.minFractionDigits=X.length}return w},stringify:R3.stringifyNumber};YG.float=XG;YG.floatExp=$G;YG.floatNaN=wG});var k8=Z((HG)=>{var T8=rw(),E0=(_)=>typeof _==="bigint"||Number.isInteger(_);function u2(_,w,$,{intAsBigInt:X}){let Y=_[0];if(Y==="-"||Y==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let Q=BigInt(_);return Y==="-"?BigInt(-1)*Q:Q}let J=parseInt(_,$);return Y==="-"?-1*J:J}function f3(_,w,$){let{value:X}=_;if(E0(X)){let Y=X.toString(w);return X<0?"-"+$+Y.substr(1):$+Y}return T8.stringifyNumber(_)}var GG={identify:E0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>u2(_,2,2,$),stringify:(_)=>f3(_,2,"0b")},DG={identify:E0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>u2(_,1,8,$),stringify:(_)=>f3(_,8,"0")},qG={identify:E0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>u2(_,0,10,$),stringify:T8.stringifyNumber},BG={identify:E0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>u2(_,2,16,$),stringify:(_)=>f3(_,16,"0x")};HG.int=qG;HG.intBin=GG;HG.intHex=BG;HG.intOct=DG});var L3=Z((AG)=>{var d2=p(),l2=ww(),c2=Xw();class Aw extends c2.YAMLMap{constructor(_){super(_);this.tag=Aw.tag}add(_){let w;if(d2.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new l2.Pair(_.key,null);else w=new l2.Pair(_,null);if(!c2.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=c2.findPair(this.items,_);return!w&&d2.isPair($)?d2.isScalar($.key)?$.key.value:$.key:$}set(_,w){if(typeof w!=="boolean")throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof w}`);let $=c2.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new l2.Pair(_))}toJSON(_,w){return super.toJSON(_,w,Set)}toString(_,w,$){if(!_)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},_,{allNullValues:!0}),w,$);else throw Error("Set items must all have null values")}static from(_,w,$){let{replacer:X}=$,Y=new this(_);if(w&&Symbol.iterator in Object(w))for(let J of w){if(typeof X==="function")J=X.call(w,J,J);Y.items.push(l2.createPair(J,null,$))}return Y}}Aw.tag="tag:yaml.org,2002:set";var MG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Aw,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Aw.from(_,w,$),resolve(_,w){if(d2.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Aw,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};AG.YAMLSet=Aw;AG.set=MG});var K3=Z((NG)=>{var LG=rw();function F3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(Q)=>w?BigInt(Q):Number(Q),J=X.replace(/_/g,"").split(":").reduce((Q,W)=>Q*Y(60)+Y(W),Y(0));return $==="-"?Y(-1)*J:J}function g8(_){let{value:w}=_,$=(Q)=>Q;if(typeof w==="bigint")$=(Q)=>BigInt(Q);else if(isNaN(w)||!isFinite(w))return LG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let Y=$(60),J=[w%Y];if(w<60)J.unshift(0);else if(w=(w-J[0])/Y,J.unshift(w%Y),w>=60)w=(w-J[0])/Y,J.unshift(w);return X+J.map((Q)=>String(Q).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var FG={identify:(_)=>typeof _==="bigint"||Number.isInteger(_),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(_,w,{intAsBigInt:$})=>F3(_,$),stringify:g8},KG={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:(_)=>F3(_,!1),stringify:g8},h8={identify:(_)=>_ instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(_){let w=_.match(h8.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,Q,W]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,D=Date.UTC($,X-1,Y,J||0,Q||0,W||0,G),q=w[8];if(q&&q!=="Z"){let H=F3(q,!1);if(Math.abs(H)<30)H*=60;D-=60000*H}return new Date(D)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};NG.floatTime=KG;NG.intTime=FG;NG.timestamp=h8});var v8=Z((vG)=>{var SG=iw(),PG=h2(),ZG=nw(),CG=N0(),IG=V3(),y8=C8(),N3=I8(),p2=k8(),TG=S2(),kG=A3(),gG=m2(),hG=L3(),b3=K3(),yG=[SG.map,ZG.seq,CG.string,PG.nullTag,y8.trueTag,y8.falseTag,p2.intBin,p2.intOct,p2.int,p2.intHex,N3.floatNaN,N3.floatExp,N3.float,IG.binary,TG.merge,kG.omap,gG.pairs,hG.set,b3.intTime,b3.floatTime,b3.timestamp];vG.schema=yG});var r8=Z((nG)=>{var l8=iw(),mG=h2(),c8=nw(),uG=N0(),lG=W3(),j3=D3(),E3=B3(),cG=f8(),dG=F8(),d8=V3(),S0=S2(),p8=A3(),i8=m2(),x8=v8(),n8=L3(),i2=K3(),m8=new Map([["core",cG.schema],["failsafe",[l8.map,c8.seq,uG.string]],["json",dG.schema],["yaml11",x8.schema],["yaml-1.1",x8.schema]]),u8={binary:d8.binary,bool:lG.boolTag,float:j3.float,floatExp:j3.floatExp,floatNaN:j3.floatNaN,floatTime:i2.floatTime,int:E3.int,intHex:E3.intHex,intOct:E3.intOct,intTime:i2.intTime,map:l8.map,merge:S0.merge,null:mG.nullTag,omap:p8.omap,pairs:i8.pairs,seq:c8.seq,set:n8.set,timestamp:i2.timestamp},pG={"tag:yaml.org,2002:binary":d8.binary,"tag:yaml.org,2002:merge":S0.merge,"tag:yaml.org,2002:omap":p8.omap,"tag:yaml.org,2002:pairs":i8.pairs,"tag:yaml.org,2002:set":n8.set,"tag:yaml.org,2002:timestamp":i2.timestamp};function iG(_,w,$){let X=m8.get(w);if(X&&!_)return $&&!X.includes(S0.merge)?X.concat(S0.merge):X.slice();let Y=X;if(!Y)if(Array.isArray(_))Y=[];else{let J=Array.from(m8.keys()).filter((Q)=>Q!=="yaml11").map((Q)=>JSON.stringify(Q)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${J} or define customTags array`)}if(Array.isArray(_))for(let J of _)Y=Y.concat(J);else if(typeof _==="function")Y=_(Y.slice());if($)Y=Y.concat(S0.merge);return Y.reduce((J,Q)=>{let W=typeof Q==="string"?u8[Q]:Q;if(!W){let G=JSON.stringify(Q),D=Object.keys(u8).map((q)=>JSON.stringify(q)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${D}`)}if(!J.includes(W))J.push(W);return J},[])}nG.coreKnownTags=pG;nG.getTags=iG});var Z3=Z((_D)=>{var S3=p(),oG=iw(),sG=nw(),tG=N0(),n2=r8(),eG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class P3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:Q}){this.compat=Array.isArray(_)?n2.getTags(_,"compat"):_?n2.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?n2.coreKnownTags:{},this.tags=n2.getTags(w,this.name,$),this.toStringOptions=Q??null,Object.defineProperty(this,S3.MAP,{value:oG.map}),Object.defineProperty(this,S3.SCALAR,{value:tG.string}),Object.defineProperty(this,S3.SEQ,{value:sG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?eG:null}clone(){let _=Object.create(P3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}_D.Schema=P3});var a8=Z((YD)=>{var $D=p(),C3=L0(),P0=A0();function XD(_,w){let $=[],X=w.directives===!0;if(w.directives!==!1&&_.directives){let G=_.directives.toString(_);if(G)$.push(G),X=!0;else if(_.directives.docStart)X=!0}if(X)$.push("---");let Y=C3.createStringifyContext(_,w),{commentString:J}=Y.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=J(_.commentBefore);$.unshift(P0.indentComment(G,""))}let Q=!1,W=null;if(_.contents){if($D.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let q=J(_.contents.commentBefore);$.push(P0.indentComment(q,""))}Y.forceBlockIndent=!!_.comment,W=_.contents.comment}let G=W?void 0:()=>Q=!0,D=C3.stringify(_.contents,Y,()=>W=null,G);if(W)D+=P0.lineComment(D,"",J(W));if((D[0]==="|"||D[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${D}`;else $.push(D)}else $.push(C3.stringify(_.contents,Y));if(_.directives?.docEnd)if(_.comment){let G=J(_.comment);if(G.includes(`
|
|
56
|
+
`))$.push("..."),$.push(P0.indentComment(G,""));else $.push(`... ${G}`)}else $.push("...");else{let G=_.comment;if(G&&Q)G=G.replace(/^\n+/,"");if(G){if((!Q||W)&&$[$.length-1]!=="")$.push("");$.push(P0.indentComment(J(G),""))}}return $.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
59
|
-
`;
|
|
58
|
+
`}YD.stringifyDocument=XD});var Z0=Z((UD)=>{var QD=O0(),aw=L2(),A_=p(),WD=ww(),GD=t_(),DD=Z3(),qD=a8(),I3=A2(),BD=s1(),HD=M0(),T3=o1();class k3{constructor(_,w,$){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,A_.NODE_TYPE,{value:A_.DOC});let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w,w=void 0;let Y=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},$);this.options=Y;let{version:J}=Y;if($?._directives){if(this.directives=$._directives.atDocument(),this.directives.yaml.explicit)J=this.directives.yaml.version}else this.directives=new T3.Directives({version:J});this.setSchema(J,$),this.contents=_===void 0?null:this.createNode(_,X,$)}clone(){let _=Object.create(k3.prototype,{[A_.NODE_TYPE]:{value:A_.DOC}});if(_.commentBefore=this.commentBefore,_.comment=this.comment,_.errors=this.errors.slice(),_.warnings=this.warnings.slice(),_.options=Object.assign({},this.options),this.directives)_.directives=this.directives.clone();if(_.schema=this.schema.clone(),_.contents=A_.isNode(this.contents)?this.contents.clone(_.schema):this.contents,this.range)_.range=this.range.slice();return _}add(_){if(ow(this.contents))this.contents.add(_)}addIn(_,w){if(ow(this.contents))this.contents.addIn(_,w)}createAlias(_,w){if(!_.anchor){let $=I3.anchorNames(this);_.anchor=!w||$.has(w)?I3.findNewAnchor(w||"a",$):w}return new QD.Alias(_.anchor)}createNode(_,w,$){let X=void 0;if(typeof w==="function")_=w.call({"":_},"",_),X=w;else if(Array.isArray(w)){let U=(A)=>typeof A==="number"||A instanceof String||A instanceof Number,V=w.filter(U).map(String);if(V.length>0)w=w.concat(V);X=w}else if($===void 0&&w)$=w,w=void 0;let{aliasDuplicateObjects:Y,anchorPrefix:J,flow:Q,keepUndefined:W,onTagObj:G,tag:D}=$??{},{onAnchor:q,setAnchors:H,sourceObjects:B}=I3.createNodeAnchors(this,J||"a"),O={aliasDuplicateObjects:Y??!0,keepUndefined:W??!1,onAnchor:q,onTagObj:G,replacer:X,schema:this.schema,sourceObjects:B},z=HD.createNode(_,D,O);if(Q&&A_.isCollection(z))z.flow=!0;return H(),z}createPair(_,w,$={}){let X=this.createNode(_,null,$),Y=this.createNode(w,null,$);return new WD.Pair(X,Y)}delete(_){return ow(this.contents)?this.contents.delete(_):!1}deleteIn(_){if(aw.isEmptyPath(_)){if(this.contents==null)return!1;return this.contents=null,!0}return ow(this.contents)?this.contents.deleteIn(_):!1}get(_,w){return A_.isCollection(this.contents)?this.contents.get(_,w):void 0}getIn(_,w){if(aw.isEmptyPath(_))return!w&&A_.isScalar(this.contents)?this.contents.value:this.contents;return A_.isCollection(this.contents)?this.contents.getIn(_,w):void 0}has(_){return A_.isCollection(this.contents)?this.contents.has(_):!1}hasIn(_){if(aw.isEmptyPath(_))return this.contents!==void 0;return A_.isCollection(this.contents)?this.contents.hasIn(_):!1}set(_,w){if(this.contents==null)this.contents=aw.collectionFromPath(this.schema,[_],w);else if(ow(this.contents))this.contents.set(_,w)}setIn(_,w){if(aw.isEmptyPath(_))this.contents=w;else if(this.contents==null)this.contents=aw.collectionFromPath(this.schema,Array.from(_),w);else if(ow(this.contents))this.contents.setIn(_,w)}setSchema(_,w={}){if(typeof _==="number")_=String(_);let $;switch(_){case"1.1":if(this.directives)this.directives.yaml.version="1.1";else this.directives=new T3.Directives({version:"1.1"});$={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":if(this.directives)this.directives.yaml.version=_;else this.directives=new T3.Directives({version:_});$={resolveKnownTags:!0,schema:"core"};break;case null:if(this.directives)delete this.directives;$=null;break;default:{let X=JSON.stringify(_);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${X}`)}}if(w.schema instanceof Object)this.schema=w.schema;else if($)this.schema=new DD.Schema(Object.assign($,w));else throw Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:_,jsonArg:w,mapAsMap:$,maxAliasCount:X,onAnchor:Y,reviver:J}={}){let Q={anchors:new Map,doc:this,keep:!_,mapAsMap:$===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},W=GD.toJS(this.contents,w??"",Q);if(typeof Y==="function")for(let{count:G,res:D}of Q.anchors.values())Y(D,G);return typeof J==="function"?BD.applyReviver(J,{"":W},"",W):W}toJSON(_,w){return this.toJS({json:!0,jsonArg:_,mapAsMap:!1,onAnchor:w})}toString(_={}){if(this.errors.length>0)throw Error("Document with errors cannot be stringified");if("indent"in _&&(!Number.isInteger(_.indent)||Number(_.indent)<=0)){let w=JSON.stringify(_.indent);throw Error(`"indent" option must be a positive integer, not ${w}`)}return qD.stringifyDocument(this,_)}}function ow(_){if(A_.isCollection(_))return!0;throw Error("Expected a YAML collection as document contents")}UD.Document=k3});var C0=Z((OD)=>{class r2 extends Error{constructor(_,w,$,X){super();this.name=_,this.code=$,this.message=X,this.pos=w}}class o8 extends r2{constructor(_,w,$){super("YAMLParseError",_,w,$)}}class s8 extends r2{constructor(_,w,$){super("YAMLWarning",_,w,$)}}var VD=(_,w)=>($)=>{if($.pos[0]===-1)return;$.linePos=$.pos.map((W)=>w.linePos(W));let{line:X,col:Y}=$.linePos[0];$.message+=` at line ${X}, column ${Y}`;let J=Y-1,Q=_.substring(w.lineStarts[X-1],w.lineStarts[X]).replace(/[\n\r]+$/,"");if(J>=60&&Q.length>80){let W=Math.min(J-39,Q.length-79);Q="\u2026"+Q.substring(W),J-=W-1}if(Q.length>80)Q=Q.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(Q.substring(0,J))){let W=_.substring(w.lineStarts[X-2],w.lineStarts[X-1]);if(W.length>80)W=W.substring(0,79)+`\u2026
|
|
59
|
+
`;Q=W+Q}if(/[^ ]/.test(Q)){let W=1,G=$.linePos[1];if(G?.line===X&&G.col>Y)W=Math.max(1,Math.min(G.col-Y,80-J));let D=" ".repeat(J)+"^".repeat(W);$.message+=`:
|
|
60
60
|
|
|
61
|
-
${D}
|
|
62
61
|
${Q}
|
|
63
|
-
|
|
64
|
-
`)
|
|
65
|
-
|
|
66
|
-
`+
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+C
|
|
70
|
-
`+
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
`;
|
|
62
|
+
${D}
|
|
63
|
+
`}};OD.YAMLError=r2;OD.YAMLParseError=o8;OD.YAMLWarning=s8;OD.prettifyError=VD});var I0=Z((FD)=>{function LD(_,{flow:w,indicator:$,next:X,offset:Y,onError:J,parentIndent:Q,startOnNewline:W}){let G=!1,D=W,q=W,H="",B="",O=!1,z=!1,U=null,V=null,A=null,R=null,L=null,N=null,E=null;for(let K of _){if(z){if(K.type!=="space"&&K.type!=="newline"&&K.type!=="comma")J(K.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");z=!1}if(U){if(D&&K.type!=="comment"&&K.type!=="newline")J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");U=null}switch(K.type){case"space":if(!w&&($!=="doc-start"||X?.type!=="flow-collection")&&K.source.includes("\t"))U=K;q=!0;break;case"comment":{if(!q)J(K,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let P=K.source.substring(1)||" ";if(!H)H=P;else H+=B+P;B="",D=!1;break}case"newline":if(D){if(H)H+=K.source;else if(!N||$!=="seq-item-ind")G=!0}else B+=K.source;if(D=!0,O=!0,V||A)R=K;q=!0;break;case"anchor":if(V)J(K,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(K.source.endsWith(":"))J(K.offset+K.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);V=K,E??(E=K.offset),D=!1,q=!1,z=!0;break;case"tag":{if(A)J(K,"MULTIPLE_TAGS","A node can have at most one tag");A=K,E??(E=K.offset),D=!1,q=!1,z=!0;break}case $:if(V||A)J(K,"BAD_PROP_ORDER",`Anchors and tags must be after the ${K.source} indicator`);if(N)J(K,"UNEXPECTED_TOKEN",`Unexpected ${K.source} in ${w??"collection"}`);N=K,D=$==="seq-item-ind"||$==="explicit-key-ind",q=!1;break;case"comma":if(w){if(L)J(K,"UNEXPECTED_TOKEN",`Unexpected , in ${w}`);L=K,D=!1,q=!1;break}default:J(K,"UNEXPECTED_TOKEN",`Unexpected ${K.type} token`),D=!1,q=!1}}let b=_[_.length-1],C=b?b.offset+b.source.length:Y;if(z&&X&&X.type!=="space"&&X.type!=="newline"&&X.type!=="comma"&&(X.type!=="scalar"||X.source!==""))J(X.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");if(U&&(D&&U.indent<=Q||X?.type==="block-map"||X?.type==="block-seq"))J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:L,found:N,spaceBefore:G,comment:H,hasNewline:O,anchor:V,tag:A,newlineAfterProp:R,end:C,start:E??C}}FD.resolveProps=LD});var a2=Z((ND)=>{function g3(_){if(!_)return null;switch(_.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(_.source.includes(`
|
|
64
|
+
`))return!0;if(_.end){for(let w of _.end)if(w.type==="newline")return!0}return!1;case"flow-collection":for(let w of _.items){for(let $ of w.start)if($.type==="newline")return!0;if(w.sep){for(let $ of w.sep)if($.type==="newline")return!0}if(g3(w.key)||g3(w.value))return!0}return!1;default:return!0}}ND.containsNewline=g3});var h3=Z((SD)=>{var jD=a2();function ED(_,w,$){if(w?.type==="flow-collection"){let X=w.end[0];if(X.indent===_&&(X.source==="]"||X.source==="}")&&jD.containsNewline(w))$(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}SD.flowIndentCheck=ED});var y3=Z((CD)=>{var t8=p();function ZD(_,w,$){let{uniqueKeys:X}=_.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(J,Q)=>J===Q||t8.isScalar(J)&&t8.isScalar(Q)&&J.value===Q.value;return w.some((J)=>Y(J.key,$))}CD.mapIncludes=ZD});var X5=Z((yD)=>{var e8=ww(),TD=Xw(),_5=I0(),kD=a2(),w5=h3(),gD=y3(),$5="All mapping items must start at the same column";function hD({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=new(J?.nodeClass??TD.YAMLMap)($.schema);if($.atRoot)$.atRoot=!1;let G=X.offset,D=null;for(let q of X.items){let{start:H,key:B,sep:O,value:z}=q,U=_5.resolveProps(H,{indicator:"explicit-key-ind",next:B??O?.[0],offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0}),V=!U.found;if(V){if(B){if(B.type==="block-seq")Y(G,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key");else if("indent"in B&&B.indent!==X.indent)Y(G,"BAD_INDENT",$5)}if(!U.anchor&&!U.tag&&!O){if(D=U.end,U.comment)if(W.comment)W.comment+=`
|
|
65
|
+
`+U.comment;else W.comment=U.comment;continue}if(U.newlineAfterProp||kD.containsNewline(B))Y(B??H[H.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else if(U.found?.indent!==X.indent)Y(G,"BAD_INDENT",$5);$.atKey=!0;let A=U.end,R=B?_($,B,U,Y):w($,A,H,null,U,Y);if($.schema.compat)w5.flowIndentCheck(X.indent,B,Y);if($.atKey=!1,gD.mapIncludes($,W.items,R))Y(A,"DUPLICATE_KEY","Map keys must be unique");let L=_5.resolveProps(O??[],{indicator:"map-value-ind",next:z,offset:R.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!B||B.type==="block-scalar"});if(G=L.end,L.found){if(V){if(z?.type==="block-map"&&!L.hasNewline)Y(G,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if($.options.strict&&U.start<L.found.offset-1024)Y(R.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let N=z?_($,z,L,Y):w($,G,O,null,L,Y);if($.schema.compat)w5.flowIndentCheck(X.indent,z,Y);G=N.range[2];let E=new e8.Pair(R,N);if($.options.keepSourceTokens)E.srcToken=q;W.items.push(E)}else{if(V)Y(R.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(L.comment)if(R.comment)R.comment+=`
|
|
66
|
+
`+L.comment;else R.comment=L.comment;let N=new e8.Pair(R);if($.options.keepSourceTokens)N.srcToken=q;W.items.push(N)}}if(D&&D<G)Y(D,"IMPOSSIBLE","Map comment with trailing content");return W.range=[X.offset,G,D??G],W}yD.resolveBlockMap=hD});var Y5=Z((cD)=>{var xD=Yw(),mD=I0(),uD=h3();function lD({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=new(J?.nodeClass??xD.YAMLSeq)($.schema);if($.atRoot)$.atRoot=!1;if($.atKey)$.atKey=!1;let G=X.offset,D=null;for(let{start:q,value:H}of X.items){let B=mD.resolveProps(q,{indicator:"seq-item-ind",next:H,offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!B.found)if(B.anchor||B.tag||H)if(H?.type==="block-seq")Y(B.end,"BAD_INDENT","All sequence items must start at the same column");else Y(G,"MISSING_CHAR","Sequence item without - indicator");else{if(D=B.end,B.comment)W.comment=B.comment;continue}let O=H?_($,H,B,Y):w($,B.end,q,null,B,Y);if($.schema.compat)uD.flowIndentCheck(X.indent,H,Y);G=O.range[2],W.items.push(O)}return W.range=[X.offset,G,D??G],W}cD.resolveBlockSeq=lD});var sw=Z((iD)=>{function pD(_,w,$,X){let Y="";if(_){let J=!1,Q="";for(let W of _){let{source:G,type:D}=W;switch(D){case"space":J=!0;break;case"comment":{if($&&!J)X(W,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let q=G.substring(1)||" ";if(!Y)Y=q;else Y+=Q+q;Q="";break}case"newline":if(Y)Q+=G;J=!0;break;default:X(W,"UNEXPECTED_TOKEN",`Unexpected ${D} at node end`)}w+=G.length}}return{comment:Y,offset:w}}iD.resolveEnd=pD});var W5=Z((wq)=>{var rD=p(),aD=ww(),J5=Xw(),oD=Yw(),sD=sw(),Q5=I0(),tD=a2(),eD=y3(),v3="Block collections are not allowed within flow collections",x3=(_)=>_&&(_.type==="block-map"||_.type==="block-seq");function _q({composeNode:_,composeEmptyNode:w},$,X,Y,J){let Q=X.start.source==="{",W=Q?"flow map":"flow sequence",D=new(J?.nodeClass??(Q?J5.YAMLMap:oD.YAMLSeq))($.schema);D.flow=!0;let q=$.atRoot;if(q)$.atRoot=!1;if($.atKey)$.atKey=!1;let H=X.offset+X.start.source.length;for(let V=0;V<X.items.length;++V){let A=X.items[V],{start:R,key:L,sep:N,value:E}=A,b=Q5.resolveProps(R,{flow:W,indicator:"explicit-key-ind",next:L??N?.[0],offset:H,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!b.found){if(!b.anchor&&!b.tag&&!N&&!E){if(V===0&&b.comma)Y(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`);else if(V<X.items.length-1)Y(b.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${W}`);if(b.comment)if(D.comment)D.comment+=`
|
|
67
|
+
`+b.comment;else D.comment=b.comment;H=b.end;continue}if(!Q&&$.options.strict&&tD.containsNewline(L))Y(L,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(V===0){if(b.comma)Y(b.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${W}`)}else{if(!b.comma)Y(b.start,"MISSING_CHAR",`Missing , between ${W} items`);if(b.comment){let C="";_:for(let K of R)switch(K.type){case"comma":case"space":break;case"comment":C=K.source.substring(1);break _;default:break _}if(C){let K=D.items[D.items.length-1];if(rD.isPair(K))K=K.value??K.key;if(K.comment)K.comment+=`
|
|
68
|
+
`+C;else K.comment=C;b.comment=b.comment.substring(C.length+1)}}}if(!Q&&!N&&!b.found){let C=E?_($,E,b,Y):w($,b.end,N,null,b,Y);if(D.items.push(C),H=C.range[2],x3(E))Y(C.range,"BLOCK_IN_FLOW",v3)}else{$.atKey=!0;let C=b.end,K=L?_($,L,b,Y):w($,C,R,null,b,Y);if(x3(L))Y(K.range,"BLOCK_IN_FLOW",v3);$.atKey=!1;let P=Q5.resolveProps(N??[],{flow:W,indicator:"map-value-ind",next:E,offset:K.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(P.found){if(!Q&&!b.found&&$.options.strict){if(N)for(let v of N){if(v===P.found)break;if(v.type==="newline"){Y(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}if(b.start<P.found.offset-1024)Y(P.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(E)if("source"in E&&E.source?.[0]===":")Y(E,"MISSING_CHAR",`Missing space after : in ${W}`);else Y(P.start,"MISSING_CHAR",`Missing , or : between ${W} items`);let g=E?_($,E,P,Y):P.found?w($,P.end,N,null,P,Y):null;if(g){if(x3(E))Y(g.range,"BLOCK_IN_FLOW",v3)}else if(P.comment)if(K.comment)K.comment+=`
|
|
69
|
+
`+P.comment;else K.comment=P.comment;let i=new aD.Pair(K,g);if($.options.keepSourceTokens)i.srcToken=A;if(Q){let v=D;if(eD.mapIncludes($,v.items,K))Y(C,"DUPLICATE_KEY","Map keys must be unique");v.items.push(i)}else{let v=new J5.YAMLMap($.schema);v.flow=!0,v.items.push(i);let c=(g??K).range;v.range=[K.range[0],c[1],c[2]],D.items.push(v)}H=g?g.range[2]:P.end}}let B=Q?"}":"]",[O,...z]=X.end,U=H;if(O?.source===B)U=O.offset+O.source.length;else{let V=W[0].toUpperCase()+W.substring(1),A=q?`${V} must end with a ${B}`:`${V} in block collection must be sufficiently indented and end with a ${B}`;if(Y(H,q?"MISSING_CHAR":"BAD_INDENT",A),O&&O.source.length!==1)z.unshift(O)}if(z.length>0){let V=sD.resolveEnd(z,U,$.options.strict,Y);if(V.comment)if(D.comment)D.comment+=`
|
|
70
|
+
`+V.comment;else D.comment=V.comment;D.range=[X.offset,U,V.offset]}else D.range=[X.offset,U,U];return D}wq.resolveFlowCollection=_q});var G5=Z((Bq)=>{var Xq=p(),Yq=X_(),Jq=Xw(),Qq=Yw(),Wq=X5(),Gq=Y5(),Dq=W5();function m3(_,w,$,X,Y,J){let Q=$.type==="block-map"?Wq.resolveBlockMap(_,w,$,X,J):$.type==="block-seq"?Gq.resolveBlockSeq(_,w,$,X,J):Dq.resolveFlowCollection(_,w,$,X,J),W=Q.constructor;if(Y==="!"||Y===W.tagName)return Q.tag=W.tagName,Q;if(Y)Q.tag=Y;return Q}function qq(_,w,$,X,Y){let J=X.tag,Q=!J?null:w.directives.tagName(J.source,(B)=>Y(J,"TAG_RESOLVE_FAILED",B));if($.type==="block-seq"){let{anchor:B,newlineAfterProp:O}=X,z=B&&J?B.offset>J.offset?B:J:B??J;if(z&&(!O||O.offset<z.offset))Y(z,"MISSING_CHAR","Missing newline after block sequence props")}let W=$.type==="block-map"?"map":$.type==="block-seq"?"seq":$.start.source==="{"?"map":"seq";if(!J||!Q||Q==="!"||Q===Jq.YAMLMap.tagName&&W==="map"||Q===Qq.YAMLSeq.tagName&&W==="seq")return m3(_,w,$,Y,Q);let G=w.schema.tags.find((B)=>B.tag===Q&&B.collection===W);if(!G){let B=w.schema.knownTags[Q];if(B?.collection===W)w.schema.tags.push(Object.assign({},B,{default:!1})),G=B;else{if(B)Y(J,"BAD_COLLECTION_TYPE",`${B.tag} used for ${W} collection, but expects ${B.collection??"scalar"}`,!0);else Y(J,"TAG_RESOLVE_FAILED",`Unresolved tag: ${Q}`,!0);return m3(_,w,$,Y,Q)}}let D=m3(_,w,$,Y,Q,G),q=G.resolve?.(D,(B)=>Y(J,"TAG_RESOLVE_FAILED",B),w.options)??D,H=Xq.isNode(q)?q:new Yq.Scalar(q);if(H.range=D.range,H.tag=Q,G?.format)H.format=G.format;return H}Bq.composeCollection=qq});var l3=Z((Oq)=>{var u3=X_();function Uq(_,w,$){let X=w.offset,Y=zq(w,_.options.strict,$);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let J=Y.mode===">"?u3.Scalar.BLOCK_FOLDED:u3.Scalar.BLOCK_LITERAL,Q=w.source?Vq(w.source):[],W=Q.length;for(let U=Q.length-1;U>=0;--U){let V=Q[U][1];if(V===""||V==="\r")W=U;else break}if(W===0){let U=Y.chomp==="+"&&Q.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,Q.length-1)):"",V=X+Y.length;if(w.source)V+=w.source.length;return{value:U,type:J,comment:Y.comment,range:[X,V,V]}}let G=w.indent+Y.indent,D=w.offset+Y.length,q=0;for(let U=0;U<W;++U){let[V,A]=Q[U];if(A===""||A==="\r"){if(Y.indent===0&&V.length>G)G=V.length}else{if(V.length<G)$(D+V.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator");if(Y.indent===0)G=V.length;if(q=U,G===0&&!_.atRoot)$(D,"BAD_INDENT","Block scalar values in collections must be indented");break}D+=V.length+A.length+1}for(let U=Q.length-1;U>=W;--U)if(Q[U][0].length>G)W=U+1;let H="",B="",O=!1;for(let U=0;U<q;++U)H+=Q[U][0].slice(G)+`
|
|
72
|
+
`;for(let U=q;U<W;++U){let[V,A]=Q[U];D+=V.length+A.length+1;let R=A[A.length-1]==="\r";if(R)A=A.slice(0,-1);if(A&&V.length<G){let N=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;$(D-A.length-(R?2:1),"BAD_INDENT",N),V=""}if(J===u3.Scalar.BLOCK_LITERAL)H+=B+V.slice(G)+A,B=`
|
|
73
|
+
`;else if(V.length>G||A[0]==="\t"){if(B===" ")B=`
|
|
74
74
|
`;else if(!O&&B===`
|
|
75
75
|
`)B=`
|
|
76
76
|
|
|
77
|
-
`;H+=B+V.slice(G)+
|
|
78
|
-
`,O=!0}else if(
|
|
77
|
+
`;H+=B+V.slice(G)+A,B=`
|
|
78
|
+
`,O=!0}else if(A==="")if(B===`
|
|
79
79
|
`)H+=`
|
|
80
80
|
`;else B=`
|
|
81
|
-
`;else H+=B+
|
|
82
|
-
`+
|
|
81
|
+
`;else H+=B+A,B=" ",O=!1}switch(Y.chomp){case"-":break;case"+":for(let U=W;U<Q.length;++U)H+=`
|
|
82
|
+
`+Q[U][0].slice(G);if(H[H.length-1]!==`
|
|
83
83
|
`)H+=`
|
|
84
84
|
`;break;default:H+=`
|
|
85
|
-
`}let z=X+Y.length+w.source.length;return{value:H,type:J,comment:Y.comment,range:[X,z,z]}}function
|
|
86
|
-
`)J+=
|
|
87
|
-
`;else J+=D
|
|
85
|
+
`}let z=X+Y.length+w.source.length;return{value:H,type:J,comment:Y.comment,range:[X,z,z]}}function zq({offset:_,props:w},$,X){if(w[0].type!=="block-scalar-header")return X(w[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:Y}=w[0],J=Y[0],Q=0,W="",G=-1;for(let B=1;B<Y.length;++B){let O=Y[B];if(!W&&(O==="-"||O==="+"))W=O;else{let z=Number(O);if(!Q&&z)Q=z;else if(G===-1)G=_+B}}if(G!==-1)X(G,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let D=!1,q="",H=Y.length;for(let B=1;B<w.length;++B){let O=w[B];switch(O.type){case"space":D=!0;case"newline":H+=O.source.length;break;case"comment":if($&&!D)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");H+=O.source.length,q=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),H+=O.source.length;break;default:{let z=`Unexpected token in block scalar header: ${O.type}`;X(O,"UNEXPECTED_TOKEN",z);let U=O.source;if(U&&typeof U==="string")H+=U.length}}}return{mode:J,indent:Q,chomp:W,comment:q,length:H}}function Vq(_){let w=_.split(/\n( *)/),$=w[0],X=$.match(/^( *)/),J=[X?.[1]?[X[1],$.slice(X[1].length)]:["",$]];for(let Q=1;Q<w.length;Q+=2)J.push([w[Q],w[Q+1]]);return J}Oq.resolveBlockScalar=Uq});var d3=Z((jq)=>{var c3=X_(),Aq=sw();function Rq(_,w,$){let{offset:X,type:Y,source:J,end:Q}=_,W,G,D=(B,O,z)=>$(X+B,O,z);switch(Y){case"scalar":W=c3.Scalar.PLAIN,G=fq(J,D);break;case"single-quoted-scalar":W=c3.Scalar.QUOTE_SINGLE,G=Lq(J,D);break;case"double-quoted-scalar":W=c3.Scalar.QUOTE_DOUBLE,G=Fq(J,D);break;default:return $(_,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${Y}`),{value:"",type:null,comment:"",range:[X,X+J.length,X+J.length]}}let q=X+J.length,H=Aq.resolveEnd(Q,q,w,$);return{value:G,type:W,comment:H.comment,range:[X,q,H.offset]}}function fq(_,w){let $="";switch(_[0]){case"\t":$="a tab character";break;case",":$="flow indicator character ,";break;case"%":$="directive indicator character %";break;case"|":case">":{$=`block scalar indicator ${_[0]}`;break}case"@":case"`":{$=`reserved character ${_[0]}`;break}}if($)w(0,"BAD_SCALAR_START",`Plain value cannot start with ${$}`);return D5(_)}function Lq(_,w){if(_[_.length-1]!=="'"||_.length===1)w(_.length,"MISSING_CHAR","Missing closing 'quote");return D5(_.slice(1,-1)).replace(/''/g,"'")}function D5(_){let w=/(.*?)\r?\n/sy,$=w.exec(_);if(!$)return _;let X,Y;try{X=new RegExp("(?<![ \t])[ \t]+$"),Y=new RegExp("^[ \t]+|(?<![ \t])[ \t]+$","g")}catch{X=/[ \t]+$/,Y=/^[ \t]+|[ \t]+$/g}let J=$[1].replace(X,""),Q=" ",W=w.lastIndex;while($=w.exec(_)){let D=$[1].replace(Y,"");if(D==="")if(Q===`
|
|
86
|
+
`)J+=Q;else Q=`
|
|
87
|
+
`;else J+=Q+D,Q=" ";W=w.lastIndex}let G=/[ \t]*(.*)/sy;return G.lastIndex=W,$=G.exec(_),J+Q+($?.[1]??"")}function Fq(_,w){let $="";for(let X=1;X<_.length-1;++X){let Y=_[X];if(Y==="\r"&&_[X+1]===`
|
|
88
88
|
`)continue;if(Y===`
|
|
89
|
-
`){let{fold:J,offset:
|
|
89
|
+
`){let{fold:J,offset:Q}=Kq(_,X);$+=J,X=Q}else if(Y==="\\"){let J=_[++X],Q=Nq[J];if(Q)$+=Q;else if(J===`
|
|
90
90
|
`){J=_[X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="\r"&&_[X+1]===`
|
|
91
|
-
`){J=_[++X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="x"||J==="u"||J==="U"){let W=J==="x"?2:J==="u"?4:8;$+=
|
|
92
|
-
`&&!(
|
|
93
|
-
`))$+=X>J?_.slice(J,X+1):Y}else $+=Y}if(_[_.length-1]!=='"'||_.length===1)w(_.length,"MISSING_CHAR",'Missing closing "quote');return $}function
|
|
91
|
+
`){J=_[++X+1];while(J===" "||J==="\t")J=_[++X+1]}else if(J==="x"||J==="u"||J==="U"){let W=J==="x"?2:J==="u"?4:8;$+=bq(_,X+1,W,w),X+=W}else{let W=_.substr(X-1,2);w(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),$+=W}}else if(Y===" "||Y==="\t"){let J=X,Q=_[X+1];while(Q===" "||Q==="\t")Q=_[++X+1];if(Q!==`
|
|
92
|
+
`&&!(Q==="\r"&&_[X+2]===`
|
|
93
|
+
`))$+=X>J?_.slice(J,X+1):Y}else $+=Y}if(_[_.length-1]!=='"'||_.length===1)w(_.length,"MISSING_CHAR",'Missing closing "quote');return $}function Kq(_,w){let $="",X=_[w+1];while(X===" "||X==="\t"||X===`
|
|
94
94
|
`||X==="\r"){if(X==="\r"&&_[w+2]!==`
|
|
95
95
|
`)break;if(X===`
|
|
96
96
|
`)$+=`
|
|
97
|
-
`;w+=1,X=_[w+1]}if(!$)$=" ";return{fold:$,offset:w}}var
|
|
98
|
-
`,r:"\r",t:"\t",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\","\t":"\t"};function
|
|
97
|
+
`;w+=1,X=_[w+1]}if(!$)$=" ";return{fold:$,offset:w}}var Nq={"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 bq(_,w,$,X){let Y=_.substr(w,$),Q=Y.length===$&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(Q)}catch{let W=_.substr(w-2,$+2);return X(w-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${W}`),W}}jq.resolveFlowScalar=Rq});var B5=Z((Tq)=>{var Rw=p(),q5=X_(),Sq=l3(),Pq=d3();function Zq(_,w,$,X){let{value:Y,type:J,comment:Q,range:W}=w.type==="block-scalar"?Sq.resolveBlockScalar(_,w,X):Pq.resolveFlowScalar(w,_.options.strict,X),G=$?_.directives.tagName($.source,(H)=>X($,"TAG_RESOLVE_FAILED",H)):null,D;if(_.options.stringKeys&&_.atKey)D=_.schema[Rw.SCALAR];else if(G)D=Cq(_.schema,Y,G,$,X);else if(w.type==="scalar")D=Iq(_,Y,w,X);else D=_.schema[Rw.SCALAR];let q;try{let H=D.resolve(Y,(B)=>X($??w,"TAG_RESOLVE_FAILED",B),_.options);q=Rw.isScalar(H)?H:new q5.Scalar(H)}catch(H){let B=H instanceof Error?H.message:String(H);X($??w,"TAG_RESOLVE_FAILED",B),q=new q5.Scalar(Y)}if(q.range=W,q.source=Y,J)q.type=J;if(G)q.tag=G;if(D.format)q.format=D.format;if(Q)q.comment=Q;return q}function Cq(_,w,$,X,Y){if($==="!")return _[Rw.SCALAR];let J=[];for(let W of _.tags)if(!W.collection&&W.tag===$)if(W.default&&W.test)J.push(W);else return W;for(let W of J)if(W.test?.test(w))return W;let Q=_.knownTags[$];if(Q&&!Q.collection)return _.tags.push(Object.assign({},Q,{default:!1,test:void 0})),Q;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${$}`,$!=="tag:yaml.org,2002:str"),_[Rw.SCALAR]}function Iq({atKey:_,directives:w,schema:$},X,Y,J){let Q=$.tags.find((W)=>(W.default===!0||_&&W.default==="key")&&W.test?.test(X))||$[Rw.SCALAR];if($.compat){let W=$.compat.find((G)=>G.default&&G.test?.test(X))??$[Rw.SCALAR];if(Q.tag!==W.tag){let G=w.tagString(Q.tag),D=w.tagString(W.tag),q=`Value may be parsed as either ${G} or ${D}`;J(Y,"TAG_RESOLVE_FAILED",q,!0)}}return Q}Tq.composeScalar=Zq});var H5=Z((hq)=>{function gq(_,w,$){if(w){$??($=w.length);for(let X=$-1;X>=0;--X){let Y=w[X];switch(Y.type){case"space":case"comment":case"newline":_-=Y.source.length;continue}Y=w[++X];while(Y?.type==="space")_+=Y.source.length,Y=w[++X];break}}return _}hq.emptyScalarPosition=gq});var V5=Z((pq)=>{var vq=O0(),xq=p(),mq=G5(),U5=B5(),uq=sw(),lq=H5(),cq={composeNode:z5,composeEmptyNode:p3};function z5(_,w,$,X){let Y=_.atKey,{spaceBefore:J,comment:Q,anchor:W,tag:G}=$,D,q=!0;switch(w.type){case"alias":if(D=dq(_,w,X),W||G)X(w,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":if(D=U5.composeScalar(_,w,G,X),W)D.anchor=W.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(D=mq.composeCollection(cq,_,w,$,X),W)D.anchor=W.source.substring(1)}catch(H){let B=H instanceof Error?H.message:String(H);X(w,"RESOURCE_EXHAUSTION",B)}break;default:{let H=w.type==="error"?w.message:`Unsupported token (type: ${w.type})`;X(w,"UNEXPECTED_TOKEN",H),q=!1}}if(D??(D=p3(_,w.offset,void 0,null,$,X)),W&&D.anchor==="")X(W,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&_.options.stringKeys&&(!xq.isScalar(D)||typeof D.value!=="string"||D.tag&&D.tag!=="tag:yaml.org,2002:str"))X(G??w,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(J)D.spaceBefore=!0;if(Q)if(w.type==="scalar"&&w.source==="")D.comment=Q;else D.commentBefore=Q;if(_.options.keepSourceTokens&&q)D.srcToken=w;return D}function p3(_,w,$,X,{spaceBefore:Y,comment:J,anchor:Q,tag:W,end:G},D){let q={type:"scalar",offset:lq.emptyScalarPosition(w,$,X),indent:-1,source:""},H=U5.composeScalar(_,q,W,D);if(Q){if(H.anchor=Q.source.substring(1),H.anchor==="")D(Q,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)H.spaceBefore=!0;if(J)H.comment=J,H.range[2]=G;return H}function dq({options:_},{offset:w,source:$,end:X},Y){let J=new vq.Alias($.substring(1));if(J.source==="")Y(w,"BAD_ALIAS","Alias cannot be an empty string");if(J.source.endsWith(":"))Y(w+$.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let Q=w+$.length,W=uq.resolveEnd(X,Q,_.strict,Y);if(J.range=[w,Q,W.offset],W.comment)J.comment=W.comment;return J}pq.composeEmptyNode=p3;pq.composeNode=z5});var M5=Z((tq)=>{var rq=Z0(),O5=V5(),aq=sw(),oq=I0();function sq(_,w,{offset:$,start:X,value:Y,end:J},Q){let W=Object.assign({_directives:w},_),G=new rq.Document(void 0,W),D={atKey:!1,atRoot:!0,directives:G.directives,options:G.options,schema:G.schema},q=oq.resolveProps(X,{indicator:"doc-start",next:Y??J?.[0],offset:$,onError:Q,parentIndent:0,startOnNewline:!0});if(q.found){if(G.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!q.hasNewline)Q(q.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}G.contents=Y?O5.composeNode(D,Y,q,Q):O5.composeEmptyNode(D,q.end,X,null,q,Q);let H=G.contents.range[2],B=aq.resolveEnd(J,H,!1,Q);if(B.comment)G.comment=B.comment;return G.range=[$,H,B.offset],G}tq.composeDoc=sq});var i3=Z((JB)=>{var _B=X2("process"),wB=o1(),$B=Z0(),T0=C0(),A5=p(),XB=M5(),YB=sw();function k0(_){if(typeof _==="number")return[_,_+1];if(Array.isArray(_))return _.length===2?_:[_[0],_[1]];let{offset:w,source:$}=_;return[w,w+(typeof $==="string"?$.length:1)]}function R5(_){let w="",$=!1,X=!1;for(let Y=0;Y<_.length;++Y){let J=_[Y];switch(J[0]){case"#":w+=(w===""?"":X?`
|
|
99
99
|
|
|
100
100
|
`:`
|
|
101
|
-
`)+(J.substring(1)||" "),$=!0,X=!1;break;case"%":if(_[Y+1]?.[0]!=="#")Y+=1;$=!1;break;default:if(!$)X=!0;$=!1}}return{comment:w,afterEmptyLine:X}}class
|
|
102
|
-
${$}`:$;else if(X||_.directives.docStart||!Y)_.commentBefore=$;else if(
|
|
103
|
-
${
|
|
104
|
-
${J}`:$}}if(w){for(let Y=0;Y<this.errors.length;++Y)_.errors.push(this.errors[Y]);for(let Y=0;Y<this.warnings.length;++Y)_.warnings.push(this.warnings[Y])}else _.errors=this.errors,_.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:
|
|
105
|
-
${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new T0.YAMLParseError(
|
|
106
|
-
`}];switch(W[0]){case"|":case">":{let
|
|
107
|
-
`),q=W.substring(0,
|
|
108
|
-
`,B=[{type:"block-scalar-header",offset:J,indent:X,source:q}];if(!
|
|
109
|
-
`});return{type:"block-scalar",offset:J,indent:X,props:B,source:H}}case'"':return{type:"double-quoted-scalar",offset:J,indent:X,source:W,end:G};case"'":return{type:"single-quoted-scalar",offset:J,indent:X,source:W,end:G};default:return{type:"scalar",offset:J,indent:X,source:W,end:G}}}function
|
|
101
|
+
`)+(J.substring(1)||" "),$=!0,X=!1;break;case"%":if(_[Y+1]?.[0]!=="#")Y+=1;$=!1;break;default:if(!$)X=!0;$=!1}}return{comment:w,afterEmptyLine:X}}class f5{constructor(_={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(w,$,X,Y)=>{let J=k0(w);if(Y)this.warnings.push(new T0.YAMLWarning(J,$,X));else this.errors.push(new T0.YAMLParseError(J,$,X))},this.directives=new wB.Directives({version:_.version||"1.2"}),this.options=_}decorate(_,w){let{comment:$,afterEmptyLine:X}=R5(this.prelude);if($){let Y=_.contents;if(w)_.comment=_.comment?`${_.comment}
|
|
102
|
+
${$}`:$;else if(X||_.directives.docStart||!Y)_.commentBefore=$;else if(A5.isCollection(Y)&&!Y.flow&&Y.items.length>0){let J=Y.items[0];if(A5.isPair(J))J=J.key;let Q=J.commentBefore;J.commentBefore=Q?`${$}
|
|
103
|
+
${Q}`:$}else{let J=Y.commentBefore;Y.commentBefore=J?`${$}
|
|
104
|
+
${J}`:$}}if(w){for(let Y=0;Y<this.errors.length;++Y)_.errors.push(this.errors[Y]);for(let Y=0;Y<this.warnings.length;++Y)_.warnings.push(this.warnings[Y])}else _.errors=this.errors,_.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:R5(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(_,w=!1,$=-1){for(let X of _)yield*this.next(X);yield*this.end(w,$)}*next(_){if(_B.env.LOG_STREAM)console.dir(_,{depth:null});switch(_.type){case"directive":this.directives.add(_.source,(w,$,X)=>{let Y=k0(_);Y[0]+=w,this.onError(Y,"BAD_DIRECTIVE",$,X)}),this.prelude.push(_.source),this.atDirectives=!0;break;case"document":{let w=XB.composeDoc(this.options,this.directives,_,this.onError);if(this.atDirectives&&!w.directives.docStart)this.onError(_,"MISSING_CHAR","Missing directives-end/doc-start indicator line");if(this.decorate(w,!1),this.doc)yield this.doc;this.doc=w,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(_.source);break;case"error":{let w=_.source?`${_.message}: ${JSON.stringify(_.source)}`:_.message,$=new T0.YAMLParseError(k0(_),"UNEXPECTED_TOKEN",w);if(this.atDirectives||!this.doc)this.errors.push($);else this.doc.errors.push($);break}case"doc-end":{if(!this.doc){this.errors.push(new T0.YAMLParseError(k0(_),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let w=YB.resolveEnd(_.end,_.offset+_.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),w.comment){let $=this.doc.comment;this.doc.comment=$?`${$}
|
|
105
|
+
${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new T0.YAMLParseError(k0(_),"UNEXPECTED_TOKEN",`Unsupported token ${_.type}`))}}*end(_=!1,w=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(_){let $=Object.assign({_directives:this.directives},this.options),X=new $B.Document(void 0,$);if(this.atDirectives)this.onError(w,"MISSING_CHAR","Missing directives-end indicator line");X.range=[0,w,w],this.decorate(X,!1),yield X}}}JB.Composer=f5});var K5=Z((zB)=>{var WB=l3(),GB=d3(),DB=C0(),L5=f0();function qB(_,w=!0,$){if(_){let X=(Y,J,Q)=>{let W=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if($)$(W,J,Q);else throw new DB.YAMLParseError([W,W+1],J,Q)};switch(_.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return GB.resolveFlowScalar(_,w,X);case"block-scalar":return WB.resolveBlockScalar({options:{strict:w}},_,X)}}return null}function BB(_,w){let{implicitKey:$=!1,indent:X,inFlow:Y=!1,offset:J=-1,type:Q="PLAIN"}=w,W=L5.stringifyString({type:Q,value:_},{implicitKey:$,indent:X>0?" ".repeat(X):"",inFlow:Y,options:{blockQuote:!0,lineWidth:-1}}),G=w.end??[{type:"newline",offset:-1,indent:X,source:`
|
|
106
|
+
`}];switch(W[0]){case"|":case">":{let D=W.indexOf(`
|
|
107
|
+
`),q=W.substring(0,D),H=W.substring(D+1)+`
|
|
108
|
+
`,B=[{type:"block-scalar-header",offset:J,indent:X,source:q}];if(!F5(B,G))B.push({type:"newline",offset:-1,indent:X,source:`
|
|
109
|
+
`});return{type:"block-scalar",offset:J,indent:X,props:B,source:H}}case'"':return{type:"double-quoted-scalar",offset:J,indent:X,source:W,end:G};case"'":return{type:"single-quoted-scalar",offset:J,indent:X,source:W,end:G};default:return{type:"scalar",offset:J,indent:X,source:W,end:G}}}function HB(_,w,$={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:J=!1,type:Q}=$,W="indent"in _?_.indent:null;if(X&&typeof W==="number")W+=2;if(!Q)switch(_.type){case"single-quoted-scalar":Q="QUOTE_SINGLE";break;case"double-quoted-scalar":Q="QUOTE_DOUBLE";break;case"block-scalar":{let D=_.props[0];if(D.type!=="block-scalar-header")throw Error("Invalid block scalar header");Q=D.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:Q="PLAIN"}let G=L5.stringifyString({type:Q,value:w},{implicitKey:Y||W===null,indent:W!==null&&W>0?" ".repeat(W):"",inFlow:J,options:{blockQuote:!0,lineWidth:-1}});switch(G[0]){case"|":case">":UB(_,G);break;case'"':n3(_,G,"double-quoted-scalar");break;case"'":n3(_,G,"single-quoted-scalar");break;default:n3(_,G,"scalar")}}function UB(_,w){let $=w.indexOf(`
|
|
110
110
|
`),X=w.substring(0,$),Y=w.substring($+1)+`
|
|
111
|
-
`;if(_.type==="block-scalar"){let J=_.props[0];if(J.type!=="block-scalar-header")throw Error("Invalid block scalar header");J.source=X,_.source=Y}else{let{offset:J}=_,
|
|
112
|
-
`});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:
|
|
113
|
-
`};delete _.items,Object.assign(_,{type:$,source:w,end:[Y]});break}default:{let X="indent"in _?_.indent:-1,Y="end"in _&&Array.isArray(_.end)?_.end.filter((J)=>J.type==="space"||J.type==="comment"||J.type==="newline"):[];for(let J of Object.keys(_))if(J!=="type"&&J!=="offset")delete _[J];Object.assign(_,{type:$,indent:X,source:w,end:Y})}}}
|
|
111
|
+
`;if(_.type==="block-scalar"){let J=_.props[0];if(J.type!=="block-scalar-header")throw Error("Invalid block scalar header");J.source=X,_.source=Y}else{let{offset:J}=_,Q="indent"in _?_.indent:-1,W=[{type:"block-scalar-header",offset:J,indent:Q,source:X}];if(!F5(W,"end"in _?_.end:void 0))W.push({type:"newline",offset:-1,indent:Q,source:`
|
|
112
|
+
`});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:Q,props:W,source:Y})}}function F5(_,w){if(w)for(let $ of w)switch($.type){case"space":case"comment":_.push($);break;case"newline":return _.push($),!0}return!1}function n3(_,w,$){switch(_.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":_.type=$,_.source=w;break;case"block-scalar":{let X=_.props.slice(1),Y=w.length;if(_.props[0].type==="block-scalar-header")Y-=_.props[0].source.length;for(let J of X)J.offset+=Y;delete _.props,Object.assign(_,{type:$,source:w,end:X});break}case"block-map":case"block-seq":{let Y={type:"newline",offset:_.offset+w.length,indent:_.indent,source:`
|
|
113
|
+
`};delete _.items,Object.assign(_,{type:$,source:w,end:[Y]});break}default:{let X="indent"in _?_.indent:-1,Y="end"in _&&Array.isArray(_.end)?_.end.filter((J)=>J.type==="space"||J.type==="comment"||J.type==="newline"):[];for(let J of Object.keys(_))if(J!=="type"&&J!=="offset")delete _[J];Object.assign(_,{type:$,indent:X,source:w,end:Y})}}}zB.createScalarToken=BB;zB.resolveAsScalar=qB;zB.setScalarValue=HB});var N5=Z((RB)=>{var AB=(_)=>("type"in _)?s2(_):o2(_);function s2(_){switch(_.type){case"block-scalar":{let w="";for(let $ of _.props)w+=s2($);return w+_.source}case"block-map":case"block-seq":{let w="";for(let $ of _.items)w+=o2($);return w}case"flow-collection":{let w=_.start.source;for(let $ of _.items)w+=o2($);for(let $ of _.end)w+=$.source;return w}case"document":{let w=o2(_);if(_.end)for(let $ of _.end)w+=$.source;return w}default:{let w=_.source;if("end"in _&&_.end)for(let $ of _.end)w+=$.source;return w}}}function o2({start:_,key:w,sep:$,value:X}){let Y="";for(let J of _)Y+=J.source;if(w)Y+=s2(w);if($)for(let J of $)Y+=J.source;if(X)Y+=s2(X);return Y}RB.stringify=AB});var E5=Z((FB)=>{var r3=Symbol("break visit"),LB=Symbol("skip children"),b5=Symbol("remove item");function fw(_,w){if("type"in _&&_.type==="document")_={start:_.start,value:_.value};j5(Object.freeze([]),_,w)}fw.BREAK=r3;fw.SKIP=LB;fw.REMOVE=b5;fw.itemAtPath=(_,w)=>{let $=_;for(let[X,Y]of w){let J=$?.[X];if(J&&"items"in J)$=J.items[Y];else return}return $};fw.parentCollection=(_,w)=>{let $=fw.itemAtPath(_,w.slice(0,-1)),X=w[w.length-1][0],Y=$?.[X];if(Y&&"items"in Y)return Y;throw Error("Parent collection not found")};function j5(_,w,$){let X=$(w,_);if(typeof X==="symbol")return X;for(let Y of["key","value"]){let J=w[Y];if(J&&"items"in J){for(let Q=0;Q<J.items.length;++Q){let W=j5(Object.freeze(_.concat([[Y,Q]])),J.items[Q],$);if(typeof W==="number")Q=W-1;else if(W===r3)return r3;else if(W===b5)J.items.splice(Q,1),Q-=1}if(typeof X==="function"&&Y==="key")X=X(w,_)}}return typeof X==="function"?X(w,_):X}FB.visit=fw});var t2=Z((ZB)=>{var a3=K5(),NB=N5(),bB=E5(),o3="\uFEFF",s3="\x02",t3="\x18",e3="\x1F",jB=(_)=>!!_&&("items"in _),EB=(_)=>!!_&&(_.type==="scalar"||_.type==="single-quoted-scalar"||_.type==="double-quoted-scalar"||_.type==="block-scalar");function SB(_){switch(_){case o3:return"<BOM>";case s3:return"<DOC>";case t3:return"<FLOW_END>";case e3:return"<SCALAR>";default:return JSON.stringify(_)}}function PB(_){switch(_){case o3:return"byte-order-mark";case s3:return"doc-mode";case t3:return"flow-error-end";case e3: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}ZB.createScalarToken=a3.createScalarToken;ZB.resolveAsScalar=a3.resolveAsScalar;ZB.setScalarValue=a3.setScalarValue;ZB.stringify=NB.stringify;ZB.visit=bB.visit;ZB.BOM=o3;ZB.DOCUMENT=s3;ZB.FLOW_END=t3;ZB.SCALAR=e3;ZB.isCollection=jB;ZB.isScalar=EB;ZB.prettyToken=SB;ZB.tokenType=PB});var w$=Z((iB)=>{var g0=t2();function S_(_){switch(_){case void 0:case" ":case`
|
|
116
|
+
`:case"\r":case"\t":return!0;default:return!1}}var S5=new Set("0123456789ABCDEFabcdef"),dB=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),e2=new Set(",[]{}"),pB=new Set(` ,[]{}
|
|
117
|
+
\r `),_$=(_)=>!_||pB.has(_);class P5{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(_,w=!1){if(_){if(typeof _!=="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+_:_,this.lineEndPos=null}this.atEnd=!w;let $=this.next??"stream";while($&&(w||this.hasChars(1)))$=yield*this.parseNext($)}atLineEnd(){let _=this.pos,w=this.buffer[_];while(w===" "||w==="\t")w=this.buffer[++_];if(!w||w==="#"||w===`
|
|
118
118
|
`)return!0;if(w==="\r")return this.buffer[_+1]===`
|
|
119
119
|
`;return!1}charAt(_){return this.buffer[this.pos+_]}continueScalar(_){let w=this.buffer[_];if(this.indentNext>0){let $=0;while(w===" ")w=this.buffer[++$+_];if(w==="\r"){let X=this.buffer[$+_+1];if(X===`
|
|
120
120
|
`||!X&&!this.atEnd)return _+$+1}return w===`
|
|
121
|
-
`||$>=this.indentNext||!w&&!this.atEnd?_+$:-1}if(w==="-"||w==="."){let $=this.buffer.substr(_,3);if(($==="---"||$==="...")&&
|
|
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]===
|
|
121
|
+
`||$>=this.indentNext||!w&&!this.atEnd?_+$:-1}if(w==="-"||w==="."){let $=this.buffer.substr(_,3);if(($==="---"||$==="...")&&S_(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]===g0.BOM)yield*this.pushCount(1),_=_.substring(1);if(_[0]==="%"){let w=_.length,$=_.indexOf("#");while($!==-1){let Y=_[$-1];if(Y===" "||Y==="\t"){w=$-1;break}else $=_.indexOf("#",$+1)}while(!0){let Y=_[w-1];if(Y===" "||Y==="\t")w-=1;else break}let X=(yield*this.pushCount(w))+(yield*this.pushSpaces(!0));return yield*this.pushCount(_.length-X),this.pushNewline(),"stream"}if(this.atLineEnd()){let w=yield*this.pushSpaces(!0);return yield*this.pushCount(_.length-w),yield*this.pushNewline(),"stream"}return yield g0.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 w=this.peek(3);if((w==="---"||w==="...")&&S_(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,w==="---"?"doc":"stream"}if(this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!S_(this.charAt(1)))this.indentNext=this.indentValue;return yield*this.parseBlockStart()}*parseBlockStart(){let[_,w]=this.peek(2);if(!w&&!this.atEnd)return this.setNext("block-start");if((_==="-"||_==="?"||_===":")&&S_(w)){let $=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=$,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let _=this.getLine();if(_===null)return this.setNext("doc");let w=yield*this.pushIndicators();switch(_[w]){case"#":yield*this.pushCount(_.length-w);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(_$),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return w+=yield*this.parseBlockScalarHeader(),w+=yield*this.pushSpaces(!0),yield*this.pushCount(_.length-w),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let _,w,$=-1;do{if(_=yield*this.pushNewline(),_>0)w=yield*this.pushSpaces(!1),this.indentValue=$=w;else w=0;w+=yield*this.pushSpaces(!0)}while(_+w>0);let X=this.getLine();if(X===null)return this.setNext("flow");if($!==-1&&$<this.indentNext&&X[0]!=="#"||$===0&&(X.startsWith("---")||X.startsWith("..."))&&S_(X[3])){if(!($===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield g0.FLOW_END,yield*this.parseLineStart()}let Y=0;while(X[Y]===",")Y+=yield*this.pushCount(1),Y+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(Y+=yield*this.pushIndicators(),X[Y]){case void 0:return"flow";case"#":return yield*this.pushCount(X.length-Y),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(_$),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let J=this.charAt(1);if(this.flowKey||S_(J)||J===",")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),w=this.buffer.indexOf(_,this.pos+1);if(_==="'")while(w!==-1&&this.buffer[w+1]==="'")w=this.buffer.indexOf("'",w+2);else while(w!==-1){let Y=0;while(this.buffer[w-1-Y]==="\\")Y+=1;if(Y%2===0)break;w=this.buffer.indexOf('"',w+1)}let $=this.buffer.substring(0,w),X=$.indexOf(`
|
|
123
123
|
`,this.pos);if(X!==-1){while(X!==-1){let Y=this.continueScalar(X+1);if(Y===-1)break;X=$.indexOf(`
|
|
124
|
-
`,Y)}if(X!==-1)w=X-($[X-1]==="\r"?2:1)}if(w===-1){if(!this.atEnd)return this.setNext("quoted-scalar");w=this.buffer.length}return yield*this.pushToIndex(w+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let _=this.pos;while(!0){let w=this.buffer[++_];if(w==="+")this.blockScalarKeep=!0;else if(w>"0"&&w<="9")this.blockScalarIndent=Number(w)-1;else if(w!=="-")break}return yield*this.pushUntil((w)=>
|
|
124
|
+
`,Y)}if(X!==-1)w=X-($[X-1]==="\r"?2:1)}if(w===-1){if(!this.atEnd)return this.setNext("quoted-scalar");w=this.buffer.length}return yield*this.pushToIndex(w+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let _=this.pos;while(!0){let w=this.buffer[++_];if(w==="+")this.blockScalarKeep=!0;else if(w>"0"&&w<="9")this.blockScalarIndent=Number(w)-1;else if(w!=="-")break}return yield*this.pushUntil((w)=>S_(w)||w==="#")}*parseBlockScalar(){let _=this.pos-1,w=0,$;_:for(let Y=this.pos;$=this.buffer[Y];++Y)switch($){case" ":w+=1;break;case`
|
|
125
125
|
`:_=Y,w=0;break;case"\r":{let J=this.buffer[Y+1];if(!J&&!this.atEnd)return this.setNext("block-scalar");if(J===`
|
|
126
126
|
`)break}default:break _}if(!$&&!this.atEnd)return this.setNext("block-scalar");if(w>=this.indentNext){if(this.blockScalarIndent===-1)this.indentNext=w;else this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let Y=this.continueScalar(_+1);if(Y===-1)break;_=this.buffer.indexOf(`
|
|
127
127
|
`,Y)}while(_!==-1);if(_===-1){if(!this.atEnd)return this.setNext("block-scalar");_=this.buffer.length}}let X=_+1;$=this.buffer[X];while($===" ")$=this.buffer[++X];if($==="\t"){while($==="\t"||$===" "||$==="\r"||$===`
|
|
128
|
-
`)$=this.buffer[++X];_=X-1}else if(!this.blockScalarKeep)do{let Y=_-1,J=this.buffer[Y];if(J==="\r")J=this.buffer[--Y];let
|
|
129
|
-
`&&Y>=this.pos&&Y+1+w>
|
|
128
|
+
`)$=this.buffer[++X];_=X-1}else if(!this.blockScalarKeep)do{let Y=_-1,J=this.buffer[Y];if(J==="\r")J=this.buffer[--Y];let Q=Y;while(J===" ")J=this.buffer[--Y];if(J===`
|
|
129
|
+
`&&Y>=this.pos&&Y+1+w>Q)_=Y;else break}while(!0);return yield g0.SCALAR,yield*this.pushToIndex(_+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let _=this.flowLevel>0,w=this.pos-1,$=this.pos-1,X;while(X=this.buffer[++$])if(X===":"){let Y=this.buffer[$+1];if(S_(Y)||_&&e2.has(Y))break;w=$}else if(S_(X)){let Y=this.buffer[$+1];if(X==="\r")if(Y===`
|
|
130
130
|
`)$+=1,X=`
|
|
131
|
-
`,Y=this.buffer[$+1];else w=$;if(Y==="#"||_&&
|
|
132
|
-
`){let J=this.continueScalar($+1);if(J===-1)break;$=Math.max($,J-2)}}else{if(_&&
|
|
131
|
+
`,Y=this.buffer[$+1];else w=$;if(Y==="#"||_&&e2.has(Y))break;if(X===`
|
|
132
|
+
`){let J=this.continueScalar($+1);if(J===-1)break;$=Math.max($,J-2)}}else{if(_&&e2.has(X))break;w=$}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield g0.SCALAR,yield*this.pushToIndex(w+1,!0),_?"flow":"doc"}*pushCount(_){if(_>0)return yield this.buffer.substr(this.pos,_),this.pos+=_,_;return 0}*pushToIndex(_,w){let $=this.buffer.slice(this.pos,_);if($)return yield $,this.pos+=$.length,$.length;else if(w)yield"";return 0}*pushIndicators(){let _=0;_:while(!0){switch(this.charAt(0)){case"!":_+=yield*this.pushTag(),_+=yield*this.pushSpaces(!0);continue _;case"&":_+=yield*this.pushUntil(_$),_+=yield*this.pushSpaces(!0);continue _;case"-":case"?":case":":{let w=this.flowLevel>0,$=this.charAt(1);if(S_($)||w&&e2.has($)){if(!w)this.indentNext=this.indentValue+1;else if(this.flowKey)this.flowKey=!1;_+=yield*this.pushCount(1),_+=yield*this.pushSpaces(!0);continue _}}}break _}return _}*pushTag(){if(this.charAt(1)==="<"){let _=this.pos+2,w=this.buffer[_];while(!S_(w)&&w!==">")w=this.buffer[++_];return yield*this.pushToIndex(w===">"?_+1:_,!1)}else{let _=this.pos+1,w=this.buffer[_];while(w)if(dB.has(w))w=this.buffer[++_];else if(w==="%"&&S5.has(this.buffer[_+1])&&S5.has(this.buffer[_+2]))w=this.buffer[_+=3];else break;return yield*this.pushToIndex(_,!1)}}*pushNewline(){let _=this.buffer[this.pos];if(_===`
|
|
133
133
|
`)return yield*this.pushCount(1);else if(_==="\r"&&this.charAt(1)===`
|
|
134
|
-
`)return yield*this.pushCount(2);else return 0}*pushSpaces(_){let w=this.pos-1,$;do $=this.buffer[++w];while($===" "||_&&$==="\t");let X=w-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=w;return X}*pushUntil(_){let w=this.pos,$=this.buffer[w];while(!_($))$=this.buffer[++w];return yield*this.pushToIndex(w,!1)}}
|
|
134
|
+
`)return yield*this.pushCount(2);else return 0}*pushSpaces(_){let w=this.pos-1,$;do $=this.buffer[++w];while($===" "||_&&$==="\t");let X=w-this.pos;if(X>0)yield this.buffer.substr(this.pos,X),this.pos=w;return X}*pushUntil(_){let w=this.pos,$=this.buffer[w];while(!_($))$=this.buffer[++w];return yield*this.pushToIndex(w,!1)}}iB.Lexer=P5});var $$=Z((rB)=>{class Z5{constructor(){this.lineStarts=[],this.addNewLine=(_)=>this.lineStarts.push(_),this.linePos=(_)=>{let w=0,$=this.lineStarts.length;while(w<$){let Y=w+$>>1;if(this.lineStarts[Y]<_)w=Y+1;else $=Y}if(this.lineStarts[w]===_)return{line:w+1,col:1};if(w===0)return{line:0,col:_};let X=this.lineStarts[w-1];return{line:w,col:_-X+1}}}}rB.LineCounter=Z5});var X$=Z((tB)=>{var oB=X2("process"),C5=t2(),sB=w$();function Jw(_,w){for(let $=0;$<_.length;++$)if(_[$].type===w)return!0;return!1}function I5(_){for(let w=0;w<_.length;++w)switch(_[w].type){case"space":case"comment":case"newline":break;default:return w}return-1}function k5(_){switch(_?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function _1(_){switch(_.type){case"document":return _.start;case"block-map":{let w=_.items[_.items.length-1];return w.sep??w.start}case"block-seq":return _.items[_.items.length-1].start;default:return[]}}function tw(_){if(_.length===0)return[];let w=_.length;_:while(--w>=0)switch(_[w].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break _}while(_[++w]?.type==="space");return _.splice(w,_.length)}function w1(_,w){if(w.length<1e5)Array.prototype.push.apply(_,w);else for(let $=0;$<w.length;++$)_.push(w[$])}function T5(_){if(_.start.type==="flow-seq-start"){for(let w of _.items)if(w.sep&&!w.value&&!Jw(w.start,"explicit-key-ind")&&!Jw(w.sep,"map-value-ind")){if(w.key)w.value=w.key;if(delete w.key,k5(w.value))if(w.value.end)w1(w.value.end,w.sep);else w.value.end=w.sep;else w1(w.start,w.sep);delete w.sep}}}class g5{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 sB.Lexer,this.onNewLine=_}*parse(_,w=!1){if(this.onNewLine&&this.offset===0)this.onNewLine(0);for(let $ of this.lexer.lex(_,w))yield*this.next($);if(!w)yield*this.end()}*next(_){if(this.source=_,oB.env.LOG_TOKENS)console.log("|",C5.prettyToken(_));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=_.length;return}let w=C5.tokenType(_);if(!w){let $=`Not a YAML token: ${_}`;yield*this.pop({type:"error",offset:this.offset,message:$,source:_}),this.offset+=_.length}else if(w==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=w,yield*this.step(),w){case"newline":if(this.atNewLine=!0,this.indent=0,this.onNewLine)this.onNewLine(this.offset+_.length);break;case"space":if(this.atNewLine&&_[0]===" ")this.indent+=_.length;break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":if(this.atNewLine)this.indent+=_.length;break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=_.length}}*end(){while(this.stack.length>0)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let _=this.peek(1);if(this.type==="doc-end"&&_?.type!=="doc-end"){while(this.stack.length>0)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!_)return yield*this.stream();switch(_.type){case"document":return yield*this.document(_);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(_);case"block-scalar":return yield*this.blockScalar(_);case"block-map":return yield*this.blockMap(_);case"block-seq":return yield*this.blockSequence(_);case"flow-collection":return yield*this.flowCollection(_);case"doc-end":return yield*this.documentEnd(_)}yield*this.pop()}peek(_){return this.stack[this.stack.length-_]}*pop(_){let w=_??this.stack.pop();if(!w)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield w;else{let $=this.peek(1);if(w.type==="block-scalar")w.indent="indent"in $?$.indent:0;else if(w.type==="flow-collection"&&$.type==="document")w.indent=0;if(w.type==="flow-collection")T5(w);switch($.type){case"document":$.value=w;break;case"block-scalar":$.props.push(w);break;case"block-map":{let X=$.items[$.items.length-1];if(X.value){$.items.push({start:[],key:w,sep:[]}),this.onKeyLine=!0;return}else if(X.sep)X.value=w;else{Object.assign(X,{key:w,sep:[]}),this.onKeyLine=!X.explicitKey;return}break}case"block-seq":{let X=$.items[$.items.length-1];if(X.value)$.items.push({start:[],value:w});else X.value=w;break}case"flow-collection":{let X=$.items[$.items.length-1];if(!X||X.value)$.items.push({start:[],key:w,sep:[]});else if(X.sep)X.value=w;else Object.assign(X,{key:w,sep:[]});return}default:yield*this.pop(),yield*this.pop(w)}if(($.type==="document"||$.type==="block-map"||$.type==="block-seq")&&(w.type==="block-map"||w.type==="block-seq")){let X=w.items[w.items.length-1];if(X&&!X.sep&&!X.value&&X.start.length>0&&I5(X.start)===-1&&(w.indent===0||X.start.every((Y)=>Y.type!=="comment"||Y.indent<w.indent))){if($.type==="document")$.end=X.start;else $.items.push({start:X.start});w.items.splice(-1,1)}}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let _={type:"document",offset:this.offset,start:[]};if(this.type==="doc-start")_.start.push(this.sourceToken);this.stack.push(_);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(_){if(_.value)return yield*this.lineEnd(_);switch(this.type){case"doc-start":{if(I5(_.start)!==-1)yield*this.pop(),yield*this.step();else _.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":_.start.push(this.sourceToken);return}let w=this.startBlockValue(_);if(w)this.stack.push(w);else yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(_){if(this.type==="map-value-ind"){let w=_1(this.peek(2)),$=tw(w),X;if(_.end)X=_.end,X.push(this.sourceToken),delete _.end;else X=[this.sourceToken];let Y={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:$,key:_,sep:X}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Y}else yield*this.lineEnd(_)}*blockScalar(_){switch(this.type){case"space":case"comment":case"newline":_.props.push(this.sourceToken);return;case"scalar":if(_.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let w=this.source.indexOf(`
|
|
135
135
|
`)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
|
|
136
|
-
`,w)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){
|
|
136
|
+
`,w)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){w1(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return}if(this.indent>=_.indent){let $=!this.onKeyLine&&this.indent===_.indent,X=$&&(w.sep||w.explicitKey)&&this.type!=="seq-item-ind",Y=[];if(X&&w.sep&&!w.value){let J=[];for(let Q=0;Q<w.sep.length;++Q){let W=w.sep[Q];switch(W.type){case"newline":J.push(Q);break;case"space":break;case"comment":if(W.indent>_.indent)J.length=0;break;default:J.length=0}}if(J.length>=2)Y=w.sep.splice(J[1])}switch(this.type){case"anchor":case"tag":if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y}),this.onKeyLine=!0;else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"explicit-key-ind":if(!w.sep&&!w.explicitKey)w.start.push(this.sourceToken),w.explicitKey=!0;else if(X||w.value)Y.push(this.sourceToken),_.items.push({start:Y,explicitKey:!0});else this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]});this.onKeyLine=!0;return;case"map-value-ind":if(w.explicitKey)if(!w.sep)if(Jw(w.start,"newline"))Object.assign(w,{key:null,sep:[this.sourceToken]});else{let J=tw(w.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:null,sep:[this.sourceToken]}]})}else if(w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Jw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:Y,key:null,sep:[this.sourceToken]}]});else if(k5(w.key)&&!Jw(w.sep,"newline")){let J=tw(w.start),Q=w.key,W=w.sep;W.push(this.sourceToken),delete w.key,delete w.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:J,key:Q,sep:W}]})}else if(Y.length>0)w.sep=w.sep.concat(Y,this.sourceToken);else w.sep.push(this.sourceToken);else if(!w.sep)Object.assign(w,{key:null,sep:[this.sourceToken]});else if(w.value||X)_.items.push({start:Y,key:null,sep:[this.sourceToken]});else if(Jw(w.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]});else w.sep.push(this.sourceToken);this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let J=this.flowScalar(this.type);if(X||w.value)_.items.push({start:Y,key:J,sep:[]}),this.onKeyLine=!0;else if(w.sep)this.stack.push(J);else Object.assign(w,{key:J,sep:[]}),this.onKeyLine=!0;return}default:{let J=this.startBlockValue(_);if(J){if(J.type==="block-seq"){if(!w.explicitKey&&w.sep&&!Jw(w.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else if($)_.items.push({start:Y});this.stack.push(J);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(_){let w=_.items[_.items.length-1];switch(this.type){case"newline":if(w.value){let $="end"in w.value?w.value.end:void 0;if((Array.isArray($)?$[$.length-1]:void 0)?.type==="comment")$?.push(this.sourceToken);else _.items.push({start:[this.sourceToken]})}else w.start.push(this.sourceToken);return;case"space":case"comment":if(w.value)_.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(w.start,_.indent)){let X=_.items[_.items.length-2]?.value?.end;if(Array.isArray(X)){w1(X,w.start),X.push(this.sourceToken),_.items.pop();return}}w.start.push(this.sourceToken)}return;case"anchor":case"tag":if(w.value||this.indent<=_.indent)break;w.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==_.indent)break;if(w.value||Jw(w.start,"seq-item-ind"))_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return}if(this.indent>_.indent){let $=this.startBlockValue(_);if($){this.stack.push($);return}}yield*this.pop(),yield*this.step()}*flowCollection(_){let w=_.items[_.items.length-1];if(this.type==="flow-error-end"){let $;do yield*this.pop(),$=this.peek(1);while($?.type==="flow-collection")}else if(_.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":if(!w||w.sep)_.items.push({start:[this.sourceToken]});else w.start.push(this.sourceToken);return;case"map-value-ind":if(!w||w.value)_.items.push({start:[],key:null,sep:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else Object.assign(w,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":if(!w||w.value)_.items.push({start:[this.sourceToken]});else if(w.sep)w.sep.push(this.sourceToken);else w.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let X=this.flowScalar(this.type);if(!w||w.value)_.items.push({start:[],key:X,sep:[]});else if(w.sep)this.stack.push(X);else Object.assign(w,{key:X,sep:[]});return}case"flow-map-end":case"flow-seq-end":_.end.push(this.sourceToken);return}let $=this.startBlockValue(_);if($)this.stack.push($);else yield*this.pop(),yield*this.step()}else{let $=this.peek(2);if($.type==="block-map"&&(this.type==="map-value-ind"&&$.indent===_.indent||this.type==="newline"&&!$.items[$.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&$.type!=="flow-collection"){let X=_1($),Y=tw(X);T5(_);let J=_.end.splice(1,_.end.length);J.push(this.sourceToken);let Q={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:Y,key:_,sep:J}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=Q}else yield*this.lineEnd(_)}}flowScalar(_){if(this.onNewLine){let w=this.source.indexOf(`
|
|
137
137
|
`)+1;while(w!==0)this.onNewLine(this.offset+w),w=this.source.indexOf(`
|
|
138
|
-
`,w)+1}return{type:_,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(_){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let w=
|
|
138
|
+
`,w)+1}return{type:_,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(_){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let w=_1(_),$=tw(w);return $.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let w=_1(_),$=tw(w);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:$,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(_,w){if(this.type!=="comment")return!1;if(this.indent<=w)return!1;return _.every(($)=>$.type==="newline"||$.type==="space")}*documentEnd(_){if(this.type!=="doc-mode"){if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}*lineEnd(_){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;case"space":case"comment":default:if(_.end)_.end.push(this.sourceToken);else _.end=[this.sourceToken];if(this.type==="newline")yield*this.pop()}}}tB.Parser=g5});var m5=Z((WH)=>{var h5=i3(),_H=Z0(),h0=C0(),wH=$3(),$H=p(),XH=$$(),y5=X$();function v5(_){let w=_.prettyErrors!==!1;return{lineCounter:_.lineCounter||w&&new XH.LineCounter||null,prettyErrors:w}}function YH(_,w={}){let{lineCounter:$,prettyErrors:X}=v5(w),Y=new y5.Parser($?.addNewLine),J=new h5.Composer(w),Q=Array.from(J.compose(Y.parse(_)));if(X&&$)for(let W of Q)W.errors.forEach(h0.prettifyError(_,$)),W.warnings.forEach(h0.prettifyError(_,$));if(Q.length>0)return Q;return Object.assign([],{empty:!0},J.streamInfo())}function x5(_,w={}){let{lineCounter:$,prettyErrors:X}=v5(w),Y=new y5.Parser($?.addNewLine),J=new h5.Composer(w),Q=null;for(let W of J.compose(Y.parse(_),!0,_.length))if(!Q)Q=W;else if(Q.options.logLevel!=="silent"){Q.errors.push(new h0.YAMLParseError(W.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&$)Q.errors.forEach(h0.prettifyError(_,$)),Q.warnings.forEach(h0.prettifyError(_,$));return Q}function JH(_,w,$){let X=void 0;if(typeof w==="function")X=w;else if($===void 0&&w&&typeof w==="object")$=w;let Y=x5(_,$);if(!Y)return null;if(Y.warnings.forEach((J)=>wH.warn(Y.options.logLevel,J)),Y.errors.length>0)if(Y.options.logLevel!=="silent")throw Y.errors[0];else Y.errors=[];return Y.toJS(Object.assign({reviver:X},$))}function QH(_,w,$){let X=null;if(typeof w==="function"||Array.isArray(w))X=w;else if($===void 0&&w)$=w;if(typeof $==="string")$=$.length;if(typeof $==="number"){let Y=Math.round($);$=Y<1?void 0:Y>8?{indent:8}:{indent:Y}}if(_===void 0){let{keepUndefined:Y}=$??w??{};if(!Y)return}if($H.isDocument(_)&&!X)return _.toString($);return new _H.Document(_,X,$).toString($)}WH.parse=JH;WH.parseAllDocuments=YH;WH.parseDocument=x5;WH.stringify=QH});var l5=Z((NH)=>{var HH=i3(),UH=Z0(),zH=Z3(),Y$=C0(),VH=O0(),Qw=p(),OH=ww(),MH=X_(),AH=Xw(),RH=Yw(),fH=t2(),LH=w$(),FH=$$(),KH=X$(),$1=m5(),u5=z0();NH.Composer=HH.Composer;NH.Document=UH.Document;NH.Schema=zH.Schema;NH.YAMLError=Y$.YAMLError;NH.YAMLParseError=Y$.YAMLParseError;NH.YAMLWarning=Y$.YAMLWarning;NH.Alias=VH.Alias;NH.isAlias=Qw.isAlias;NH.isCollection=Qw.isCollection;NH.isDocument=Qw.isDocument;NH.isMap=Qw.isMap;NH.isNode=Qw.isNode;NH.isPair=Qw.isPair;NH.isScalar=Qw.isScalar;NH.isSeq=Qw.isSeq;NH.Pair=OH.Pair;NH.Scalar=MH.Scalar;NH.YAMLMap=AH.YAMLMap;NH.YAMLSeq=RH.YAMLSeq;NH.CST=fH;NH.Lexer=LH.Lexer;NH.LineCounter=FH.LineCounter;NH.Parser=KH.Parser;NH.parse=$1.parse;NH.parseAllDocuments=$1.parseAllDocuments;NH.parseDocument=$1.parseDocument;NH.stringify=$1.stringify;NH.visit=u5.visit;NH.visitAsync=u5.visitAsync});var h9=(_)=>_.payload.title?.trim()||`session:${_.payload.id}`;function Y2(_){let{store:w,agent:$}=_;return{async session(X){let Y=X.payload.id,J=await n$(w,Y);switch(X.type){case"session.created":{if(J)return{task_id:J.id};let Q=h9(X);return{task_id:(await w.createTask({title:Q,session_id:Y,owner:$,priority:3})).id}}case"session.idle":{if(!J)return null;if(J.status==="pending"){let Q=await w.updateTask(J.id,{status:"in_progress"});return Q?{task_id:Q.id}:null}return null}case"session.deleted":{if(!J)return null;return await w.updateTask(J.id,{status:"cancelled"}),{task_id:J.id}}case"session.error":case"session.compacted":return await w.appendOperation({task_id:J?.id??null,type:`session.${X.type.split(".").pop()}`,data:{session_id:Y,agent:$}}),null;default:return null}},async tool(X){let Y=X.payload.sessionID,J=await n$(w,Y);if(!J)return await w.appendOperation({task_id:null,type:"tool.orphan",data:{session_id:Y,tool:X.payload.tool}}),{task_id:(await w.createTask({title:`${X.payload.tool} (orphan)`,session_id:null,owner:$,priority:3})).id};let Q=y9(X),G=(await w.listTasks({parent_id:J.id,limit:20})).tasks.find((q)=>q.title===Q&&Date.now()-new Date(q.created_at).getTime()<60000);if(G)return{task_id:G.id};let D=await w.createTask({title:Q,parent_id:J.id,session_id:Y,owner:$,priority:3});return await w.updateTask(D.id,{status:"in_progress"}),{task_id:D.id}},async catchAll(X){try{await w.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:$}})}catch{}}}}async function n$(_,w){return(await _.listTasks({session_id:w,limit:1})).tasks[0]??null}function y9(_){let w=_.payload.tool,$=_.payload.args??{};switch(w){case"write":case"edit":return`${w} ${$.filePath??"?"}`;case"bash":case"shell":{let X=String($.command??$.cmd??"");return`${w} ${X.slice(0,40)}`}case"read":return`read ${$.filePath??"?"}`;default:return`${w} ${JSON.stringify($).slice(0,40)}`}}var F1="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.",K1=`# Roy \u2014 task-first-class-citizen agent
|
|
139
139
|
|
|
140
140
|
You are **Roy**, an agent whose defining rule is simple:
|
|
141
141
|
|
|
@@ -176,13 +176,20 @@ Report progress as you go, not only at the end:
|
|
|
176
176
|
If the scope changes, \`task_update\` the description/goals instead of silently
|
|
177
177
|
doing something else.
|
|
178
178
|
|
|
179
|
-
### 4. Record milestones \u2014 \`task_operation_create\`
|
|
179
|
+
### 4. Record milestones \u2014 \`task_operation_create\` \u2014 **as you work**
|
|
180
|
+
Call this tool the moment a stage is reached \u2014 **not after the fact**,
|
|
181
|
+
not in a batch at the end. Finished a chunk of code? A test just went
|
|
182
|
+
green? Hit a blocker? Made a decision? Record it **immediately**, then
|
|
183
|
+
keep working. The record is the running log of the work, written while
|
|
184
|
+
it happens.
|
|
185
|
+
|
|
180
186
|
This tool has **two orthogonal dimensions** and you must keep them distinct:
|
|
181
187
|
- **state / milestone dimension** \u2014 \`milestone_type\` + \`milestone_title\` +
|
|
182
188
|
\`milestone_description\`: *what* was reached (e.g. "GREEN: all tests pass").
|
|
183
189
|
- **process dimension** \u2014 \`process_description\`: *how* you got there \u2014
|
|
184
|
-
|
|
185
|
-
Too short = rejected (no value);
|
|
190
|
+
the operations just performed and why, written in the moment,
|
|
191
|
+
**100\u2013500 characters**. Too short = rejected (no value);
|
|
192
|
+
too long = rejected (that is a log, not a summary).
|
|
186
193
|
|
|
187
194
|
Rules: do **not** use the process field to restate the milestone, and do not
|
|
188
195
|
use milestones as a substitute for progress. Milestones mark *state
|
|
@@ -222,7 +229,7 @@ if it is not in the task store, it is not tracked.
|
|
|
222
229
|
- Be direct and concrete; the user is reading task titles and milestones.
|
|
223
230
|
- Report the task id and its state whenever you finish a step.
|
|
224
231
|
- If a task is blocked, mark it (\`task_update(status="paused")\`) and record a
|
|
225
|
-
\`problem\` milestone explaining the blocker instead of going silent.`;var X0="roy",u$={action:"execute",resource:"*",effect:"deny"};function l$(){return{id:X0,mode:"primary",description:R2,system:f2,permissions:[{...u$}]}}function PX(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((Y)=>Y.action===$.action&&Y.resource===$.resource&&Y.effect===$.effect))_.permissions.push({...$})}function L2(_){let w=l$();return _.update(X0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;PX($,w.permissions)}),w}var A={};jX(A,{void:()=>U9,util:()=>l,unknown:()=>H9,union:()=>A9,undefined:()=>G9,tuple:()=>f9,transformer:()=>Z9,symbol:()=>W9,string:()=>s$,strictObject:()=>O9,setErrorMap:()=>TX,set:()=>K9,record:()=>L9,quotelessJson:()=>ZX,promise:()=>P9,preprocess:()=>I9,pipeline:()=>k9,ostring:()=>g9,optional:()=>C9,onumber:()=>h9,oboolean:()=>y9,objectUtil:()=>F2,object:()=>V9,number:()=>t$,nullable:()=>T9,null:()=>Q9,never:()=>B9,nativeEnum:()=>S9,nan:()=>Y9,map:()=>F9,makeIssue:()=>Y0,literal:()=>j9,lazy:()=>b9,late:()=>$9,isValid:()=>p_,isDirty:()=>J1,isAsync:()=>jw,isAborted:()=>Y1,intersection:()=>R9,instanceof:()=>X9,getParsedType:()=>Z_,getErrorMap:()=>bw,function:()=>N9,enum:()=>E9,effect:()=>Z9,discriminatedUnion:()=>M9,defaultErrorMap:()=>y_,datetimeRegex:()=>r$,date:()=>D9,custom:()=>o$,coerce:()=>v9,boolean:()=>e$,bigint:()=>J9,array:()=>z9,any:()=>q9,addIssueToContext:()=>S,ZodVoid:()=>D0,ZodUnknown:()=>i_,ZodUnion:()=>Tw,ZodUndefined:()=>Zw,ZodType:()=>x,ZodTuple:()=>T_,ZodTransformer:()=>K_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>W0,ZodReadonly:()=>xw,ZodPromise:()=>Bw,ZodPipeline:()=>q0,ZodParsedType:()=>j,ZodOptional:()=>L_,ZodObject:()=>t,ZodNumber:()=>n_,ZodNullable:()=>x_,ZodNull:()=>Cw,ZodNever:()=>C_,ZodNativeEnum:()=>hw,ZodNaN:()=>Q0,ZodMap:()=>G0,ZodLiteral:()=>gw,ZodLazy:()=>kw,ZodIssueCode:()=>F,ZodIntersection:()=>Iw,ZodFunction:()=>Sw,ZodFirstPartyTypeKind:()=>K,ZodError:()=>D_,ZodEnum:()=>a_,ZodEffects:()=>K_,ZodDiscriminatedUnion:()=>D1,ZodDefault:()=>yw,ZodDate:()=>Qw,ZodCatch:()=>vw,ZodBranded:()=>W1,ZodBoolean:()=>Pw,ZodBigInt:()=>r_,ZodArray:()=>f_,ZodAny:()=>qw,Schema:()=>x,ParseStatus:()=>W_,OK:()=>Q_,NEVER:()=>x9,INVALID:()=>I,EMPTY_PATH:()=>IX,DIRTY:()=>Gw,BRAND:()=>w9});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let D of Y)J[D]=D;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((W)=>typeof Y[Y[W]]!=="number"),D={};for(let W of J)D[W]=Y[W];return _.objectValues(D)},_.objectValues=(Y)=>{return _.objectKeys(Y).map(function(J){return Y[J]})},_.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let J=[];for(let D in Y)if(Object.prototype.hasOwnProperty.call(Y,D))J.push(D);return J},_.find=(Y,J)=>{for(let D of Y)if(J(D))return D;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((D)=>typeof D==="string"?`'${D}'`:D).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var F2;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(F2||(F2={}));var j=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z_=(_)=>{switch(typeof _){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(_)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray(_))return j.array;if(_===null)return j.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return j.promise;if(typeof Map<"u"&&_ instanceof Map)return j.map;if(typeof Set<"u"&&_ instanceof Set)return j.set;if(typeof Date<"u"&&_ instanceof Date)return j.date;return j.object;default:return j.unknown}};var F=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZX=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class D_ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=_}format(_){let w=_||function(Y){return Y.message},$={_errors:[]},X=(Y)=>{for(let J of Y.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)$._errors.push(w(J));else{let D=$,W=0;while(W<J.path.length){let G=J.path[W];if(W!==J.path.length-1)D[G]=D[G]||{_errors:[]};else D[G]=D[G]||{_errors:[]},D[G]._errors.push(w(J));D=D[G],W++}}};return X(this),$}static assert(_){if(!(_ instanceof D_))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(w)=>w.message){let w={},$=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];w[Y]=w[Y]||[],w[Y].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}D_.create=(_)=>{return new D_(_)};var CX=(_,w)=>{let $;switch(_.code){case F.invalid_type:if(_.received===j.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case F.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case F.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case F.invalid_union:$="Invalid input";break;case F.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case F.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case F.invalid_arguments:$="Invalid function arguments";break;case F.invalid_return_type:$="Invalid function return type";break;case F.invalid_date:$="Invalid date";break;case F.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if($=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)$=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)$=`Invalid input: must end with "${_.validation.endsWith}"`;else l.assertNever(_.validation);else if(_.validation!=="regex")$=`Invalid ${_.validation}`;else $="Invalid";break;case F.too_small:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else $="Invalid input";break;case F.too_big:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")$=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else $="Invalid input";break;case F.custom:$="Invalid input";break;case F.invalid_intersection_types:$="Intersection results could not be merged";break;case F.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case F.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},y_=CX;var c$=y_;function TX(_){c$=_}function bw(){return c$}var Y0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],D={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let W="",G=X.filter((Q)=>!!Q).slice().reverse();for(let Q of G)W=Q(D,{data:w,defaultError:W}).message;return{...Y,path:J,message:W}},IX=[];function S(_,w){let $=bw(),X=Y0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===y_?void 0:y_].filter((Y)=>!!Y)});_.common.issues.push(X)}class W_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,w){let $=[];for(let X of w){if(X.status==="aborted")return I;if(X.status==="dirty")_.dirty();$.push(X.value)}return{status:_.value,value:$}}static async mergeObjectAsync(_,w){let $=[];for(let X of w){let Y=await X.key,J=await X.value;$.push({key:Y,value:J})}return W_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:Y,value:J}=X;if(Y.status==="aborted")return I;if(J.status==="aborted")return I;if(Y.status==="dirty")_.dirty();if(J.status==="dirty")_.dirty();if(Y.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))$[Y.value]=J.value}return{status:_.value,value:$}}}var I=Object.freeze({status:"aborted"}),Gw=(_)=>({status:"dirty",value:_}),Q_=(_)=>({status:"valid",value:_}),Y1=(_)=>_.status==="aborted",J1=(_)=>_.status==="dirty",p_=(_)=>_.status==="valid",jw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var T;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(T||(T={}));class F_{constructor(_,w,$,X){this._cachedPath=[],this.parent=_,this.data=w,this._path=$,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var d$=(_,w)=>{if(p_(w))return{success:!0,data:w.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new D_(_.common.issues);return this._error=$,this._error}}}};function g(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:Y}=_;if(w&&($||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:Y};return{errorMap:(D,W)=>{let{message:G}=_;if(D.code==="invalid_enum_value")return{message:G??W.defaultError};if(typeof W.data>"u")return{message:G??X??W.defaultError};if(D.code!=="invalid_type")return{message:W.defaultError};return{message:G??$??W.defaultError}},description:Y}}class x{get description(){return this._def.description}_getType(_){return Z_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new W_,ctx:{common:_.parent.common,data:_.data,parsedType:Z_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(jw(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync(_){let w=this._parse(_);return Promise.resolve(w)}parse(_,w){let $=this.safeParse(_,w);if($.success)return $.data;throw $.error}safeParse(_,w){let $={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return d$($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return p_($)?{value:$.value}:{issues:w.common.issues}}catch($){if($?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:w}).then(($)=>p_($)?{value:$.value}:{issues:w.common.issues})}async parseAsync(_,w){let $=await this.safeParseAsync(_,w);if($.success)return $.data;throw $.error}async safeParseAsync(_,w){let $={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:Z_(_)},X=this._parse({data:_,path:$.path,parent:$}),Y=await(jw(X)?X:Promise.resolve(X));return d$($,Y)}refine(_,w){let $=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,Y)=>{let J=_(X),D=()=>Y.addIssue({code:F.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((W)=>{if(!W)return D(),!1;else return!0});if(!J)return D(),!1;else return!0})}refinement(_,w){return this._refinement(($,X)=>{if(!_($))return X.addIssue(typeof w==="function"?w($,X):w),!1;else return!0})}_refinement(_){return new K_({schema:this,typeName:K.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(w)=>this["~validate"](w)}}optional(){return L_.create(this,this._def)}nullable(){return x_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return f_.create(this)}promise(){return Bw.create(this,this._def)}or(_){return Tw.create([this,_],this._def)}and(_){return Iw.create(this,_,this._def)}transform(_){return new K_({...g(this._def),schema:this,typeName:K.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new yw({...g(this._def),innerType:this,defaultValue:w,typeName:K.ZodDefault})}brand(){return new W1({typeName:K.ZodBranded,type:this,...g(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new vw({...g(this._def),innerType:this,catchValue:w,typeName:K.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return q0.create(this,_)}readonly(){return xw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var kX=/^c[^\s-]{8,}$/i,gX=/^[0-9a-z]+$/,hX=/^[0-9A-HJKMNP-TV-Z]{26}$/i,yX=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,vX=/^[a-z0-9_-]{21}$/i,xX=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mX=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,uX=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,lX="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K2,cX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,dX=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,pX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,iX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nX=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,rX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i$="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aX=new RegExp(`^${i$}$`);function n$(_){let w="[0-5]\\d";if(_.precision)w=`${w}\\.\\d{${_.precision}}`;else if(_.precision==null)w=`${w}(\\.\\d+)?`;let $=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${$}`}function oX(_){return new RegExp(`^${n$(_)}$`)}function r$(_){let w=`${i$}T${n$(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function sX(_,w){if((w==="v4"||!w)&&cX.test(_))return!0;if((w==="v6"||!w)&&pX.test(_))return!0;return!1}function tX(_,w){if(!xX.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(w&&Y.alg!==w)return!1;return!0}catch{return!1}}function eX(_,w){if((w==="v4"||!w)&&dX.test(_))return!0;if((w==="v6"||!w)&&iX.test(_))return!0;return!1}class R_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==j.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.string,received:Y.parsedType}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.length<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="max"){if(_.data.length>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="length"){let J=_.data.length>Y.value,D=_.data.length<Y.value;if(J||D){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:F.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(D)S(X,{code:F.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!uX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!K2)K2=new RegExp(lX,"u");if(!K2.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!yX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!vX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!kX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!gX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!hX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),S(X,{validation:"url",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"regex",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="trim")_.data=_.data.trim();else if(Y.kind==="includes"){if(!_.data.includes(Y.value,Y.position))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),$.dirty()}else if(Y.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(Y.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(Y.kind==="startsWith"){if(!_.data.startsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{startsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="endsWith"){if(!_.data.endsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!r$(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!aX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!oX(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:F.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!mX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!sX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!tX(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!eX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!nX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:F.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!rX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:F.invalid_string,message:Y.message}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:F.invalid_string,...T.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...T.errToObj(_)})}url(_){return this._addCheck({kind:"url",...T.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...T.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...T.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...T.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...T.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...T.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...T.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...T.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...T.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...T.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...T.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...T.errToObj(_)})}datetime(_){if(typeof _==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:_});return this._addCheck({kind:"datetime",precision:typeof _?.precision>"u"?null:_?.precision,offset:_?.offset??!1,local:_?.local??!1,...T.errToObj(_?.message)})}date(_){return this._addCheck({kind:"date",message:_})}time(_){if(typeof _==="string")return this._addCheck({kind:"time",precision:null,message:_});return this._addCheck({kind:"time",precision:typeof _?.precision>"u"?null:_?.precision,...T.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...T.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...T.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...T.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...T.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...T.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...T.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...T.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...T.errToObj(w)})}nonempty(_){return this.min(1,T.errToObj(_))}trim(){return new R_({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new R_({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxLength(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}R_.create=(_)=>{return new R_({checks:[],typeName:K.ZodString,coerce:_?.coerce??!1,...g(_)})};function _9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),D=Number.parseInt(w.toFixed(Y).replace(".",""));return J%D/10**Y}class n_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==j.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.number,received:Y.parsedType}),I}let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_9(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:F.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new n_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new n_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:T.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:T.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:T.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:T.toString(_)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&l.isInteger(_.value))}get isFinite(){let _=null,w=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(w===null||$.value>w)w=$.value}else if($.kind==="max"){if(_===null||$.value<_)_=$.value}return Number.isFinite(w)&&Number.isFinite(_)}}n_.create=(_)=>{return new n_({checks:[],typeName:K.ZodNumber,coerce:_?.coerce||!1,...g(_)})};class r_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==j.bigint)return this._getInvalidInput(_);let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:F.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_.data%Y.value!==BigInt(0))$=this._getOrReturnCtx(_,$),S($,{code:F.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.bigint,received:w.parsedType}),I}gte(_,w){return this.setLimit("min",_,!0,T.toString(w))}gt(_,w){return this.setLimit("min",_,!1,T.toString(w))}lte(_,w){return this.setLimit("max",_,!0,T.toString(w))}lt(_,w){return this.setLimit("max",_,!1,T.toString(w))}setLimit(_,w,$,X){return new r_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:T.toString(X)}]})}_addCheck(_){return new r_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:T.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:T.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:T.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:T.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:T.toString(w)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}r_.create=(_)=>{return new r_({checks:[],typeName:K.ZodBigInt,coerce:_?.coerce??!1,...g(_)})};class Pw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==j.boolean){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.boolean,received:$.parsedType}),I}return Q_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:K.ZodBoolean,coerce:_?.coerce||!1,...g(_)})};class Qw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==j.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_type,expected:j.date,received:Y.parsedType}),I}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:F.invalid_date}),I}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.getTime()<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),$.dirty()}else if(Y.kind==="max"){if(_.data.getTime()>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:F.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new Qw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:T.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:T.toString(w)})}get minDate(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _!=null?new Date(_):null}}Qw.create=(_)=>{return new Qw({checks:[],coerce:_?.coerce||!1,typeName:K.ZodDate,...g(_)})};class J0 extends x{_parse(_){if(this._getType(_)!==j.symbol){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.symbol,received:$.parsedType}),I}return Q_(_.data)}}J0.create=(_)=>{return new J0({typeName:K.ZodSymbol,...g(_)})};class Zw extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.undefined,received:$.parsedType}),I}return Q_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:K.ZodUndefined,...g(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==j.null){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.null,received:$.parsedType}),I}return Q_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:K.ZodNull,...g(_)})};class qw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return Q_(_.data)}}qw.create=(_)=>{return new qw({typeName:K.ZodAny,...g(_)})};class i_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return Q_(_.data)}}i_.create=(_)=>{return new i_({typeName:K.ZodUnknown,...g(_)})};class C_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:F.invalid_type,expected:j.never,received:w.parsedType}),I}}C_.create=(_)=>{return new C_({typeName:K.ZodNever,...g(_)})};class D0 extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.void,received:$.parsedType}),I}return Q_(_.data)}}D0.create=(_)=>{return new D0({typeName:K.ZodVoid,...g(_)})};class f_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==j.array)return S(w,{code:F.invalid_type,expected:j.array,received:w.parsedType}),I;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,D=w.data.length<X.exactLength.value;if(J||D)S(w,{code:J?F.too_big:F.too_small,minimum:D?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),$.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)S(w,{code:F.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),$.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)S(w,{code:F.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),$.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,D)=>{return X.type._parseAsync(new F_(w,J,w.path,D))})).then((J)=>{return W_.mergeArray($,J)});let Y=[...w.data].map((J,D)=>{return X.type._parseSync(new F_(w,J,w.path,D))});return W_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new f_({...this._def,minLength:{value:_,message:T.toString(w)}})}max(_,w){return new f_({...this._def,maxLength:{value:_,message:T.toString(w)}})}length(_,w){return new f_({...this._def,exactLength:{value:_,message:T.toString(w)}})}nonempty(_){return this.min(1,_)}}f_.create=(_,w)=>{return new f_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:K.ZodArray,...g(w)})};function Ew(_){if(_ instanceof t){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=L_.create(Ew(X))}return new t({..._._def,shape:()=>w})}else if(_ instanceof f_)return new f_({..._._def,type:Ew(_.element)});else if(_ instanceof L_)return L_.create(Ew(_.unwrap()));else if(_ instanceof x_)return x_.create(Ew(_.unwrap()));else if(_ instanceof T_)return T_.create(_.items.map((w)=>Ew(w)));else return _}class t extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),w=l.objectKeys(_);return this._cached={shape:_,keys:w},this._cached}_parse(_){if(this._getType(_)!==j.object){let G=this._getOrReturnCtx(_);return S(G,{code:F.invalid_type,expected:j.object,received:G.parsedType}),I}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),D=[];if(!(this._def.catchall instanceof C_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))D.push(G)}let W=[];for(let G of J){let Q=Y[G],q=X.data[G];W.push({key:{status:"valid",value:G},value:Q._parse(new F_(X,q,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof C_){let G=this._def.unknownKeys;if(G==="passthrough")for(let Q of D)W.push({key:{status:"valid",value:Q},value:{status:"valid",value:X.data[Q]}});else if(G==="strict"){if(D.length>0)S(X,{code:F.unrecognized_keys,keys:D}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let Q of D){let q=X.data[Q];W.push({key:{status:"valid",value:Q},value:G._parse(new F_(X,q,X.path,Q)),alwaysSet:Q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let Q of W){let q=await Q.key,H=await Q.value;G.push({key:q,value:H,alwaysSet:Q.alwaysSet})}return G}).then((G)=>{return W_.mergeObjectSync($,G)});else return W_.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(_){return T.errToObj,new t({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message:T.errToObj(_).message??X};return{message:X}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(_){return new t({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new t({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:K.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new t({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}deepPartial(){return Ew(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new t({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let Y=this.shape[$];while(Y instanceof L_)Y=Y._def.innerType;w[$]=Y}return new t({...this._def,shape:()=>w})}keyof(){return a$(l.objectKeys(this.shape))}}t.create=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.strictCreate=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strict",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};t.lazycreate=(_,w)=>{return new t({shape:_,unknownKeys:"strip",catchall:C_.create(),typeName:K.ZodObject,...g(w)})};class Tw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(Y){for(let D of Y)if(D.result.status==="valid")return D.result;for(let D of Y)if(D.result.status==="dirty")return w.common.issues.push(...D.ctx.common.issues),D.result;let J=Y.map((D)=>new D_(D.ctx.common.issues));return S(w,{code:F.invalid_union,unionErrors:J}),I}if(w.common.async)return Promise.all($.map(async(Y)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let Y=void 0,J=[];for(let W of $){let G={...w,common:{...w.common,issues:[]},parent:null},Q=W._parseSync({data:w.data,path:w.path,parent:G});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!Y)Y={result:Q,ctx:G};if(G.common.issues.length)J.push(G.common.issues)}if(Y)return w.common.issues.push(...Y.ctx.common.issues),Y.result;let D=J.map((W)=>new D_(W));return S(w,{code:F.invalid_union,unionErrors:D}),I}}get options(){return this._def.options}}Tw.create=(_,w)=>{return new Tw({options:_,typeName:K.ZodUnion,...g(w)})};var v_=(_)=>{if(_ instanceof kw)return v_(_.schema);else if(_ instanceof K_)return v_(_.innerType());else if(_ instanceof gw)return[_.value];else if(_ instanceof a_)return _.options;else if(_ instanceof hw)return l.objectValues(_.enum);else if(_ instanceof yw)return v_(_._def.innerType);else if(_ instanceof Zw)return[void 0];else if(_ instanceof Cw)return[null];else if(_ instanceof L_)return[void 0,...v_(_.unwrap())];else if(_ instanceof x_)return[null,...v_(_.unwrap())];else if(_ instanceof W1)return v_(_.unwrap());else if(_ instanceof xw)return v_(_.unwrap());else if(_ instanceof vw)return v_(_._def.innerType);else return[]};class D1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.object)return S(w,{code:F.invalid_type,expected:j.object,received:w.parsedType}),I;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:F.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),I;if(w.common.async)return Y._parseAsync({data:w.data,path:w.path,parent:w});else return Y._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,w,$){let X=new Map;for(let Y of w){let J=v_(Y.shape[_]);if(!J.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let D of J){if(X.has(D))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(D)}`);X.set(D,Y)}}return new D1({typeName:K.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...g($)})}}function N2(_,w){let $=Z_(_),X=Z_(w);if(_===w)return{valid:!0,data:_};else if($===j.object&&X===j.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((W)=>Y.indexOf(W)!==-1),D={..._,...w};for(let W of J){let G=N2(_[W],w[W]);if(!G.valid)return{valid:!1};D[W]=G.data}return{valid:!0,data:D}}else if($===j.array&&X===j.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let D=_[J],W=w[J],G=N2(D,W);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===j.date&&X===j.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class Iw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(Y,J)=>{if(Y1(Y)||Y1(J))return I;let D=N2(Y.value,J.value);if(!D.valid)return S($,{code:F.invalid_intersection_types}),I;if(J1(Y)||J1(J))w.dirty();return{status:w.value,value:D.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([Y,J])=>X(Y,J));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}Iw.create=(_,w,$)=>{return new Iw({left:_,right:w,typeName:K.ZodIntersection,...g($)})};class T_ extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.array)return S($,{code:F.invalid_type,expected:j.array,received:$.parsedType}),I;if($.data.length<this._def.items.length)return S($,{code:F.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),I;if(!this._def.rest&&$.data.length>this._def.items.length)S($,{code:F.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,D)=>{let W=this._def.items[D]||this._def.rest;if(!W)return null;return W._parse(new F_($,J,$.path,D))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return W_.mergeArray(w,J)});else return W_.mergeArray(w,Y)}get items(){return this._def.items}rest(_){return new T_({...this._def,rest:_})}}T_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new T_({items:_,typeName:K.ZodTuple,rest:null,...g(w)})};class W0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.object)return S($,{code:F.invalid_type,expected:j.object,received:$.parsedType}),I;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let D in $.data)X.push({key:Y._parse(new F_($,D,$.path,D)),value:J._parse(new F_($,$.data[D],$.path,D)),alwaysSet:D in $.data});if($.common.async)return W_.mergeObjectAsync(w,X);else return W_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new W0({keyType:_,valueType:w,typeName:K.ZodRecord,...g($)});return new W0({keyType:R_.create(),valueType:_,typeName:K.ZodRecord,...g(w)})}}class G0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.map)return S($,{code:F.invalid_type,expected:j.map,received:$.parsedType}),I;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([D,W],G)=>{return{key:X._parse(new F_($,D,$.path,[G,"key"])),value:Y._parse(new F_($,W,$.path,[G,"value"]))}});if($.common.async){let D=new Map;return Promise.resolve().then(async()=>{for(let W of J){let G=await W.key,Q=await W.value;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}})}else{let D=new Map;for(let W of J){let{key:G,value:Q}=W;if(G.status==="aborted"||Q.status==="aborted")return I;if(G.status==="dirty"||Q.status==="dirty")w.dirty();D.set(G.value,Q.value)}return{status:w.value,value:D}}}}G0.create=(_,w,$)=>{return new G0({valueType:w,keyType:_,typeName:K.ZodMap,...g($)})};class Hw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.set)return S($,{code:F.invalid_type,expected:j.set,received:$.parsedType}),I;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:F.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if($.data.size>X.maxSize.value)S($,{code:F.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let Y=this._def.valueType;function J(W){let G=new Set;for(let Q of W){if(Q.status==="aborted")return I;if(Q.status==="dirty")w.dirty();G.add(Q.value)}return{status:w.value,value:G}}let D=[...$.data.values()].map((W,G)=>Y._parse(new F_($,W,$.path,G)));if($.common.async)return Promise.all(D).then((W)=>J(W));else return J(D)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:T.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:T.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Hw.create=(_,w)=>{return new Hw({valueType:_,minSize:null,maxSize:null,typeName:K.ZodSet,...g(w)})};class Sw extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.function)return S(w,{code:F.invalid_type,expected:j.function,received:w.parsedType}),I;function $(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_arguments,argumentsError:W}})}function X(D,W){return Y0({data:D,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:F.invalid_return_type,returnTypeError:W}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Bw){let D=this;return Q_(async function(...W){let G=new D_([]),Q=await D._def.args.parseAsync(W,Y).catch((B)=>{throw G.addIssue($(W,B)),G}),q=await Reflect.apply(J,this,Q);return await D._def.returns._def.type.parseAsync(q,Y).catch((B)=>{throw G.addIssue(X(q,B)),G})})}else{let D=this;return Q_(function(...W){let G=D._def.args.safeParse(W,Y);if(!G.success)throw new D_([$(W,G.error)]);let Q=Reflect.apply(J,this,G.data),q=D._def.returns.safeParse(Q,Y);if(!q.success)throw new D_([X(Q,q.error)]);return q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Sw({...this._def,args:T_.create(_).rest(i_.create())})}returns(_){return new Sw({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Sw({args:_?_:T_.create([]).rest(i_.create()),returns:w||i_.create(),typeName:K.ZodFunction,...g($)})}}class kw extends x{get schema(){return this._def.getter()}_parse(_){let{ctx:w}=this._processInputParams(_);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}}kw.create=(_,w)=>{return new kw({getter:_,typeName:K.ZodLazy,...g(w)})};class gw extends x{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return S(w,{received:w.data,code:F.invalid_literal,expected:this._def.value}),I}return{status:"valid",value:_.data}}get value(){return this._def.value}}gw.create=(_,w)=>{return new gw({value:_,typeName:K.ZodLiteral,...g(w)})};function a$(_,w){return new a_({values:_,typeName:K.ZodEnum,...g(w)})}class a_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{received:w.data,code:F.invalid_enum_value,options:$}),I}return Q_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let w of this._def.values)_[w]=w;return _}get Values(){let _={};for(let w of this._def.values)_[w]=w;return _}get Enum(){let _={};for(let w of this._def.values)_[w]=w;return _}extract(_,w=this._def){return a_.create(_,{...this._def,...w})}exclude(_,w=this._def){return a_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}a_.create=a$;class hw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==j.string&&$.parsedType!==j.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:F.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:F.invalid_enum_value,options:X}),I}return Q_(_.data)}get enum(){return this._def.values}}hw.create=(_,w)=>{return new hw({values:_,typeName:K.ZodNativeEnum,...g(w)})};class Bw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.promise&&w.common.async===!1)return S(w,{code:F.invalid_type,expected:j.promise,received:w.parsedType}),I;let $=w.parsedType===j.promise?w.data:Promise.resolve(w.data);return Q_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Bw.create=(_,w)=>{return new Bw({type:_,typeName:K.ZodPromise,...g(w)})};class K_ extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===K.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=this._def.effect||null,Y={addIssue:(J)=>{if(S($,J),J.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let J=X.transform($.data,Y);if($.common.async)return Promise.resolve(J).then(async(D)=>{if(w.value==="aborted")return I;let W=await this._def.schema._parseAsync({data:D,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")return Gw(W.value);if(w.value==="dirty")return Gw(W.value);return W});else{if(w.value==="aborted")return I;let D=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")return Gw(D.value);if(w.value==="dirty")return Gw(D.value);return D}}if(X.type==="refinement"){let J=(D)=>{let W=X.refinement(D,Y);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return D};if($.common.async===!1){let D=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value),{status:w.value,value:D.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((D)=>{if(D.status==="aborted")return I;if(D.status==="dirty")w.dirty();return J(D.value).then(()=>{return{status:w.value,value:D.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!p_(J))return I;let D=X.transform(J.value,Y);if(D instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:D}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!p_(J))return I;return Promise.resolve(X.transform(J.value,Y)).then((D)=>({status:w.value,value:D}))});l.assertNever(X)}}K_.create=(_,w,$)=>{return new K_({schema:_,typeName:K.ZodEffects,effect:w,...g($)})};K_.createWithPreprocess=(_,w,$)=>{return new K_({schema:w,effect:{type:"preprocess",transform:_},typeName:K.ZodEffects,...g($)})};class L_ extends x{_parse(_){if(this._getType(_)===j.undefined)return Q_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}L_.create=(_,w)=>{return new L_({innerType:_,typeName:K.ZodOptional,...g(w)})};class x_ extends x{_parse(_){if(this._getType(_)===j.null)return Q_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}x_.create=(_,w)=>{return new x_({innerType:_,typeName:K.ZodNullable,...g(w)})};class yw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===j.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}yw.create=(_,w)=>{return new yw({innerType:_,typeName:K.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...g(w)})};class vw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(jw(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new D_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:K.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...g(w)})};class Q0 extends x{_parse(_){if(this._getType(_)!==j.nan){let $=this._getOrReturnCtx(_);return S($,{code:F.invalid_type,expected:j.nan,received:$.parsedType}),I}return{status:"valid",value:_.data}}}Q0.create=(_)=>{return new Q0({typeName:K.ZodNaN,...g(_)})};var w9=Symbol("zod_brand");class W1 extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;return this._def.type._parse({data:$,path:w.path,parent:w})}unwrap(){return this._def.type}}class q0 extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(Y.status==="aborted")return I;if(Y.status==="dirty")return w.dirty(),Gw(Y.value);else return this._def.out._parseAsync({data:Y.value,path:$.path,parent:$})})();else{let X=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(X.status==="aborted")return I;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:$.path,parent:$})}}static create(_,w){return new q0({in:_,out:w,typeName:K.ZodPipeline})}}class xw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(p_(X))X.value=Object.freeze(X.value);return X};return jw(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}xw.create=(_,w)=>{return new xw({innerType:_,typeName:K.ZodReadonly,...g(w)})};function p$(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function o$(_,w={},$){if(_)return qw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((D)=>{if(!D){let W=p$(w,X),G=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:G})}});if(!J){let D=p$(w,X),W=D.fatal??$??!0;Y.addIssue({code:"custom",...D,fatal:W})}return});return qw.create()}var $9={object:t.lazycreate},K;(function(_){_.ZodString="ZodString",_.ZodNumber="ZodNumber",_.ZodNaN="ZodNaN",_.ZodBigInt="ZodBigInt",_.ZodBoolean="ZodBoolean",_.ZodDate="ZodDate",_.ZodSymbol="ZodSymbol",_.ZodUndefined="ZodUndefined",_.ZodNull="ZodNull",_.ZodAny="ZodAny",_.ZodUnknown="ZodUnknown",_.ZodNever="ZodNever",_.ZodVoid="ZodVoid",_.ZodArray="ZodArray",_.ZodObject="ZodObject",_.ZodUnion="ZodUnion",_.ZodDiscriminatedUnion="ZodDiscriminatedUnion",_.ZodIntersection="ZodIntersection",_.ZodTuple="ZodTuple",_.ZodRecord="ZodRecord",_.ZodMap="ZodMap",_.ZodSet="ZodSet",_.ZodFunction="ZodFunction",_.ZodLazy="ZodLazy",_.ZodLiteral="ZodLiteral",_.ZodEnum="ZodEnum",_.ZodEffects="ZodEffects",_.ZodNativeEnum="ZodNativeEnum",_.ZodOptional="ZodOptional",_.ZodNullable="ZodNullable",_.ZodDefault="ZodDefault",_.ZodCatch="ZodCatch",_.ZodPromise="ZodPromise",_.ZodBranded="ZodBranded",_.ZodPipeline="ZodPipeline",_.ZodReadonly="ZodReadonly"})(K||(K={}));var X9=(_,w={message:`Input not instance of ${_.name}`})=>o$(($)=>$ instanceof _,w),s$=R_.create,t$=n_.create,Y9=Q0.create,J9=r_.create,e$=Pw.create,D9=Qw.create,W9=J0.create,G9=Zw.create,Q9=Cw.create,q9=qw.create,H9=i_.create,B9=C_.create,U9=D0.create,z9=f_.create,V9=t.create,O9=t.strictCreate,A9=Tw.create,M9=D1.create,R9=Iw.create,f9=T_.create,L9=W0.create,F9=G0.create,K9=Hw.create,N9=Sw.create,b9=kw.create,j9=gw.create,E9=a_.create,S9=hw.create,P9=Bw.create,Z9=K_.create,C9=L_.create,T9=x_.create,I9=K_.createWithPreprocess,k9=q0.create,g9=()=>s$().optional(),h9=()=>t$().optional(),y9=()=>e$().optional(),v9={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>n_.create({..._,coerce:!0}),boolean:(_)=>Pw.create({..._,coerce:!0}),bigint:(_)=>r_.create({..._,coerce:!0}),date:(_)=>Qw.create({..._,coerce:!0})};var x9=I;var b2=A.object({bgProcessId:A.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function m9(_){return{alive:_.status==="pending"||_.status==="running",status:_.status,createdAt:_.createdAt,lastUpdatedAt:_.lastUpdatedAt??_.completedAt??_.startedAt??_.createdAt,description:_.description,..._.result!==void 0?{result:_.result}:{},..._.error!==void 0?{error:_.error}:{}}}function _4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var EV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
232
|
+
\`problem\` milestone explaining the blocker instead of going silent.`;var Y0="roy",r$={action:"execute",resource:"*",effect:"deny"};function a$(){return{id:Y0,mode:"primary",description:F1,system:K1,permissions:[{...r$}]}}function v9(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((Y)=>Y.action===$.action&&Y.resource===$.resource&&Y.effect===$.effect))_.permissions.push({...$})}function N1(_){let w=a$();return _.update(Y0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;v9($,w.permissions)}),w}var M={};g9(M,{void:()=>FX,util:()=>l,unknown:()=>fX,union:()=>jX,undefined:()=>MX,tuple:()=>PX,transformer:()=>xX,symbol:()=>OX,string:()=>Y4,strictObject:()=>bX,setErrorMap:()=>u9,set:()=>IX,record:()=>ZX,quotelessJson:()=>x9,promise:()=>vX,preprocess:()=>lX,pipeline:()=>cX,ostring:()=>dX,optional:()=>mX,onumber:()=>pX,oboolean:()=>iX,objectUtil:()=>b1,object:()=>NX,number:()=>J4,nullable:()=>uX,null:()=>AX,never:()=>LX,nativeEnum:()=>yX,nan:()=>UX,map:()=>CX,makeIssue:()=>J0,literal:()=>gX,lazy:()=>kX,late:()=>BX,isValid:()=>i_,isDirty:()=>Q2,isAsync:()=>Ew,isAborted:()=>J2,intersection:()=>SX,instanceof:()=>HX,getParsedType:()=>I_,getErrorMap:()=>jw,function:()=>TX,enum:()=>hX,effect:()=>xX,discriminatedUnion:()=>EX,defaultErrorMap:()=>x_,datetimeRegex:()=>w4,date:()=>VX,custom:()=>X4,coerce:()=>nX,boolean:()=>Q4,bigint:()=>zX,array:()=>KX,any:()=>RX,addIssueToContext:()=>S,ZodVoid:()=>W0,ZodUnknown:()=>n_,ZodUnion:()=>Tw,ZodUndefined:()=>Cw,ZodType:()=>x,ZodTuple:()=>k_,ZodTransformer:()=>b_,ZodSymbol:()=>Q0,ZodString:()=>L_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>G0,ZodReadonly:()=>mw,ZodPromise:()=>Uw,ZodPipeline:()=>B0,ZodParsedType:()=>j,ZodOptional:()=>K_,ZodObject:()=>t,ZodNumber:()=>r_,ZodNullable:()=>u_,ZodNull:()=>Iw,ZodNever:()=>T_,ZodNativeEnum:()=>yw,ZodNaN:()=>q0,ZodMap:()=>D0,ZodLiteral:()=>hw,ZodLazy:()=>gw,ZodIssueCode:()=>f,ZodIntersection:()=>kw,ZodFunction:()=>Pw,ZodFirstPartyTypeKind:()=>F,ZodError:()=>Q_,ZodEnum:()=>o_,ZodEffects:()=>b_,ZodDiscriminatedUnion:()=>W2,ZodDefault:()=>vw,ZodDate:()=>qw,ZodCatch:()=>xw,ZodBranded:()=>G2,ZodBoolean:()=>Zw,ZodBigInt:()=>a_,ZodArray:()=>F_,ZodAny:()=>Bw,Schema:()=>x,ParseStatus:()=>W_,OK:()=>D_,NEVER:()=>rX,INVALID:()=>T,EMPTY_PATH:()=>l9,DIRTY:()=>Dw,BRAND:()=>qX});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let Q of Y)J[Q]=Q;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((W)=>typeof Y[Y[W]]!=="number"),Q={};for(let W of J)Q[W]=Y[W];return _.objectValues(Q)},_.objectValues=(Y)=>{return _.objectKeys(Y).map(function(J){return Y[J]})},_.objectKeys=typeof Object.keys==="function"?(Y)=>Object.keys(Y):(Y)=>{let J=[];for(let Q in Y)if(Object.prototype.hasOwnProperty.call(Y,Q))J.push(Q);return J},_.find=(Y,J)=>{for(let Q of Y)if(J(Q))return Q;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((Q)=>typeof Q==="string"?`'${Q}'`:Q).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var b1;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(b1||(b1={}));var j=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),I_=(_)=>{switch(typeof _){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(_)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray(_))return j.array;if(_===null)return j.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return j.promise;if(typeof Map<"u"&&_ instanceof Map)return j.map;if(typeof Set<"u"&&_ instanceof Set)return j.set;if(typeof Date<"u"&&_ instanceof Date)return j.date;return j.object;default:return j.unknown}};var f=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),x9=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class Q_ extends Error{get errors(){return this.issues}constructor(_){super();this.issues=[],this.addIssue=($)=>{this.issues=[...this.issues,$]},this.addIssues=($=[])=>{this.issues=[...this.issues,...$]};let w=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,w);else this.__proto__=w;this.name="ZodError",this.issues=_}format(_){let w=_||function(Y){return Y.message},$={_errors:[]},X=(Y)=>{for(let J of Y.issues)if(J.code==="invalid_union")J.unionErrors.map(X);else if(J.code==="invalid_return_type")X(J.returnTypeError);else if(J.code==="invalid_arguments")X(J.argumentsError);else if(J.path.length===0)$._errors.push(w(J));else{let Q=$,W=0;while(W<J.path.length){let G=J.path[W];if(W!==J.path.length-1)Q[G]=Q[G]||{_errors:[]};else Q[G]=Q[G]||{_errors:[]},Q[G]._errors.push(w(J));Q=Q[G],W++}}};return X(this),$}static assert(_){if(!(_ instanceof Q_))throw Error(`Not a ZodError: ${_}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,l.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(_=(w)=>w.message){let w={},$=[];for(let X of this.issues)if(X.path.length>0){let Y=X.path[0];w[Y]=w[Y]||[],w[Y].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}Q_.create=(_)=>{return new Q_(_)};var m9=(_,w)=>{let $;switch(_.code){case f.invalid_type:if(_.received===j.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case f.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case f.invalid_union:$="Invalid input";break;case f.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case f.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case f.invalid_arguments:$="Invalid function arguments";break;case f.invalid_return_type:$="Invalid function return type";break;case f.invalid_date:$="Invalid date";break;case f.invalid_string:if(typeof _.validation==="object")if("includes"in _.validation){if($=`Invalid input: must include "${_.validation.includes}"`,typeof _.validation.position==="number")$=`${$} at one or more positions greater than or equal to ${_.validation.position}`}else if("startsWith"in _.validation)$=`Invalid input: must start with "${_.validation.startsWith}"`;else if("endsWith"in _.validation)$=`Invalid input: must end with "${_.validation.endsWith}"`;else l.assertNever(_.validation);else if(_.validation!=="regex")$=`Invalid ${_.validation}`;else $="Invalid";break;case f.too_small:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at least":"more than"} ${_.minimum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at least":"over"} ${_.minimum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="bigint")$=`Number must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${_.minimum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly equal to ":_.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(_.minimum))}`;else $="Invalid input";break;case f.too_big:if(_.type==="array")$=`Array must contain ${_.exact?"exactly":_.inclusive?"at most":"less than"} ${_.maximum} element(s)`;else if(_.type==="string")$=`String must contain ${_.exact?"exactly":_.inclusive?"at most":"under"} ${_.maximum} character(s)`;else if(_.type==="number")$=`Number must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="bigint")$=`BigInt must be ${_.exact?"exactly":_.inclusive?"less than or equal to":"less than"} ${_.maximum}`;else if(_.type==="date")$=`Date must be ${_.exact?"exactly":_.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(_.maximum))}`;else $="Invalid input";break;case f.custom:$="Invalid input";break;case f.invalid_intersection_types:$="Intersection results could not be merged";break;case f.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case f.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},x_=m9;var o$=x_;function u9(_){o$=_}function jw(){return o$}var J0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],Q={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let W="",G=X.filter((D)=>!!D).slice().reverse();for(let D of G)W=D(Q,{data:w,defaultError:W}).message;return{...Y,path:J,message:W}},l9=[];function S(_,w){let $=jw(),X=J0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===x_?void 0:x_].filter((Y)=>!!Y)});_.common.issues.push(X)}class W_{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray(_,w){let $=[];for(let X of w){if(X.status==="aborted")return T;if(X.status==="dirty")_.dirty();$.push(X.value)}return{status:_.value,value:$}}static async mergeObjectAsync(_,w){let $=[];for(let X of w){let Y=await X.key,J=await X.value;$.push({key:Y,value:J})}return W_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:Y,value:J}=X;if(Y.status==="aborted")return T;if(J.status==="aborted")return T;if(Y.status==="dirty")_.dirty();if(J.status==="dirty")_.dirty();if(Y.value!=="__proto__"&&(typeof J.value<"u"||X.alwaysSet))$[Y.value]=J.value}return{status:_.value,value:$}}}var T=Object.freeze({status:"aborted"}),Dw=(_)=>({status:"dirty",value:_}),D_=(_)=>({status:"valid",value:_}),J2=(_)=>_.status==="aborted",Q2=(_)=>_.status==="dirty",i_=(_)=>_.status==="valid",Ew=(_)=>typeof Promise<"u"&&_ instanceof Promise;var I;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(I||(I={}));class N_{constructor(_,w,$,X){this._cachedPath=[],this.parent=_,this.data=w,this._path=$,this._key=X}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var s$=(_,w)=>{if(i_(w))return{success:!0,data:w.value};else{if(!_.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let $=new Q_(_.common.issues);return this._error=$,this._error}}}};function h(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:Y}=_;if(w&&($||X))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(w)return{errorMap:w,description:Y};return{errorMap:(Q,W)=>{let{message:G}=_;if(Q.code==="invalid_enum_value")return{message:G??W.defaultError};if(typeof W.data>"u")return{message:G??X??W.defaultError};if(Q.code!=="invalid_type")return{message:W.defaultError};return{message:G??$??W.defaultError}},description:Y}}class x{get description(){return this._def.description}_getType(_){return I_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:I_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new W_,ctx:{common:_.parent.common,data:_.data,parsedType:I_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(Ew(w))throw Error("Synchronous parse encountered promise.");return w}_parseAsync(_){let w=this._parse(_);return Promise.resolve(w)}parse(_,w){let $=this.safeParse(_,w);if($.success)return $.data;throw $.error}safeParse(_,w){let $={common:{issues:[],async:w?.async??!1,contextualErrorMap:w?.errorMap},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:I_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return s$($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:I_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return i_($)?{value:$.value}:{issues:w.common.issues}}catch($){if($?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;w.common={issues:[],async:!0}}return this._parseAsync({data:_,path:[],parent:w}).then(($)=>i_($)?{value:$.value}:{issues:w.common.issues})}async parseAsync(_,w){let $=await this.safeParseAsync(_,w);if($.success)return $.data;throw $.error}async safeParseAsync(_,w){let $={common:{issues:[],contextualErrorMap:w?.errorMap,async:!0},path:w?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:I_(_)},X=this._parse({data:_,path:$.path,parent:$}),Y=await(Ew(X)?X:Promise.resolve(X));return s$($,Y)}refine(_,w){let $=(X)=>{if(typeof w==="string"||typeof w>"u")return{message:w};else if(typeof w==="function")return w(X);else return w};return this._refinement((X,Y)=>{let J=_(X),Q=()=>Y.addIssue({code:f.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((W)=>{if(!W)return Q(),!1;else return!0});if(!J)return Q(),!1;else return!0})}refinement(_,w){return this._refinement(($,X)=>{if(!_($))return X.addIssue(typeof w==="function"?w($,X):w),!1;else return!0})}_refinement(_){return new b_({schema:this,typeName:F.ZodEffects,effect:{type:"refinement",refinement:_}})}superRefine(_){return this._refinement(_)}constructor(_){this.spa=this.safeParseAsync,this._def=_,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(w)=>this["~validate"](w)}}optional(){return K_.create(this,this._def)}nullable(){return u_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return F_.create(this)}promise(){return Uw.create(this,this._def)}or(_){return Tw.create([this,_],this._def)}and(_){return kw.create(this,_,this._def)}transform(_){return new b_({...h(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new vw({...h(this._def),innerType:this,defaultValue:w,typeName:F.ZodDefault})}brand(){return new G2({typeName:F.ZodBranded,type:this,...h(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new xw({...h(this._def),innerType:this,catchValue:w,typeName:F.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return B0.create(this,_)}readonly(){return mw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var c9=/^c[^\s-]{8,}$/i,d9=/^[0-9a-z]+$/,p9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,i9=/^[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,n9=/^[a-z0-9_-]{21}$/i,r9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,a9=/^[-+]?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)?)??$/,o9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,s9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",j1,t9=/^(?:(?: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])$/,e9=/^(?:(?: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])$/,_X=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wX=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,$X=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,XX=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,e$="((\\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])))",YX=new RegExp(`^${e$}$`);function _4(_){let w="[0-5]\\d";if(_.precision)w=`${w}\\.\\d{${_.precision}}`;else if(_.precision==null)w=`${w}(\\.\\d+)?`;let $=_.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${w})${$}`}function JX(_){return new RegExp(`^${_4(_)}$`)}function w4(_){let w=`${e$}T${_4(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function QX(_,w){if((w==="v4"||!w)&&t9.test(_))return!0;if((w==="v6"||!w)&&_X.test(_))return!0;return!1}function WX(_,w){if(!r9.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),Y=JSON.parse(atob(X));if(typeof Y!=="object"||Y===null)return!1;if("typ"in Y&&Y?.typ!=="JWT")return!1;if(!Y.alg)return!1;if(w&&Y.alg!==w)return!1;return!0}catch{return!1}}function GX(_,w){if((w==="v4"||!w)&&e9.test(_))return!0;if((w==="v6"||!w)&&wX.test(_))return!0;return!1}class L_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==j.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:f.invalid_type,expected:j.string,received:Y.parsedType}),T}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.length<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:f.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="max"){if(_.data.length>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:f.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!1,message:Y.message}),$.dirty()}else if(Y.kind==="length"){let J=_.data.length>Y.value,Q=_.data.length<Y.value;if(J||Q){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:f.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(Q)S(X,{code:f.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!o9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!j1)j1=new RegExp(s9,"u");if(!j1.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!i9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!n9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!c9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!d9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!p9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),S(X,{validation:"url",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="regex"){if(Y.regex.lastIndex=0,!Y.regex.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"regex",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="trim")_.data=_.data.trim();else if(Y.kind==="includes"){if(!_.data.includes(Y.value,Y.position))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:{includes:Y.value,position:Y.position},message:Y.message}),$.dirty()}else if(Y.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(Y.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(Y.kind==="startsWith"){if(!_.data.startsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:{startsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="endsWith"){if(!_.data.endsWith(Y.value))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!w4(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!YX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!JX(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:f.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!a9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!QX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!WX(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!GX(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!$X.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:f.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!XX.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:f.invalid_string,message:Y.message}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:f.invalid_string,...I.errToObj($)})}_addCheck(_){return new L_({...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(_,w){return this._addCheck({kind:"regex",regex:_,...I.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...I.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...I.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...I.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...I.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...I.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...I.errToObj(w)})}nonempty(_){return this.min(1,I.errToObj(_))}trim(){return new L_({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new L_({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new L_({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find((_)=>_.kind==="datetime")}get isDate(){return!!this._def.checks.find((_)=>_.kind==="date")}get isTime(){return!!this._def.checks.find((_)=>_.kind==="time")}get isDuration(){return!!this._def.checks.find((_)=>_.kind==="duration")}get isEmail(){return!!this._def.checks.find((_)=>_.kind==="email")}get isURL(){return!!this._def.checks.find((_)=>_.kind==="url")}get isEmoji(){return!!this._def.checks.find((_)=>_.kind==="emoji")}get isUUID(){return!!this._def.checks.find((_)=>_.kind==="uuid")}get isNANOID(){return!!this._def.checks.find((_)=>_.kind==="nanoid")}get isCUID(){return!!this._def.checks.find((_)=>_.kind==="cuid")}get isCUID2(){return!!this._def.checks.find((_)=>_.kind==="cuid2")}get isULID(){return!!this._def.checks.find((_)=>_.kind==="ulid")}get isIP(){return!!this._def.checks.find((_)=>_.kind==="ip")}get isCIDR(){return!!this._def.checks.find((_)=>_.kind==="cidr")}get isBase64(){return!!this._def.checks.find((_)=>_.kind==="base64")}get isBase64url(){return!!this._def.checks.find((_)=>_.kind==="base64url")}get minLength(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxLength(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}L_.create=(_)=>{return new L_({checks:[],typeName:F.ZodString,coerce:_?.coerce??!1,...h(_)})};function DX(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),Q=Number.parseInt(w.toFixed(Y).replace(".",""));return J%Q/10**Y}class r_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(_){if(this._def.coerce)_.data=Number(_.data);if(this._getType(_)!==j.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:f.invalid_type,expected:j.number,received:Y.parsedType}),T}let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:f.invalid_type,expected:"integer",received:"float",message:Y.message}),X.dirty()}else if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:f.too_small,minimum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:f.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(DX(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:f.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:f.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,I.toString(w))}gt(_,w){return this.setLimit("min",_,!1,I.toString(w))}lte(_,w){return this.setLimit("max",_,!0,I.toString(w))}lt(_,w){return this.setLimit("max",_,!1,I.toString(w))}setLimit(_,w,$,X){return new r_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:I.toString(X)}]})}_addCheck(_){return new r_({...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(_,w){return this._addCheck({kind:"multipleOf",value:_,message:I.toString(w)})}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 w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}get isInt(){return!!this._def.checks.find((_)=>_.kind==="int"||_.kind==="multipleOf"&&l.isInteger(_.value))}get isFinite(){let _=null,w=null;for(let $ of this._def.checks)if($.kind==="finite"||$.kind==="int"||$.kind==="multipleOf")return!0;else if($.kind==="min"){if(w===null||$.value>w)w=$.value}else if($.kind==="max"){if(_===null||$.value<_)_=$.value}return Number.isFinite(w)&&Number.isFinite(_)}}r_.create=(_)=>{return new r_({checks:[],typeName:F.ZodNumber,coerce:_?.coerce||!1,...h(_)})};class a_ extends x{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse(_){if(this._def.coerce)try{_.data=BigInt(_.data)}catch{return this._getInvalidInput(_)}if(this._getType(_)!==j.bigint)return this._getInvalidInput(_);let $=void 0,X=new W_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:f.too_small,type:"bigint",minimum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="max"){if(Y.inclusive?_.data>Y.value:_.data>=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:f.too_big,type:"bigint",maximum:Y.value,inclusive:Y.inclusive,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(_.data%Y.value!==BigInt(0))$=this._getOrReturnCtx(_,$),S($,{code:f.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return S(w,{code:f.invalid_type,expected:j.bigint,received:w.parsedType}),T}gte(_,w){return this.setLimit("min",_,!0,I.toString(w))}gt(_,w){return this.setLimit("min",_,!1,I.toString(w))}lte(_,w){return this.setLimit("max",_,!0,I.toString(w))}lt(_,w){return this.setLimit("max",_,!1,I.toString(w))}setLimit(_,w,$,X){return new a_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:I.toString(X)}]})}_addCheck(_){return new a_({...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(_,w){return this._addCheck({kind:"multipleOf",value:_,message:I.toString(w)})}get minValue(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _}get maxValue(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _}}a_.create=(_)=>{return new a_({checks:[],typeName:F.ZodBigInt,coerce:_?.coerce??!1,...h(_)})};class Zw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==j.boolean){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.boolean,received:$.parsedType}),T}return D_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:F.ZodBoolean,coerce:_?.coerce||!1,...h(_)})};class qw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==j.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:f.invalid_type,expected:j.date,received:Y.parsedType}),T}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:f.invalid_date}),T}let $=new W_,X=void 0;for(let Y of this._def.checks)if(Y.kind==="min"){if(_.data.getTime()<Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:f.too_small,message:Y.message,inclusive:!0,exact:!1,minimum:Y.value,type:"date"}),$.dirty()}else if(Y.kind==="max"){if(_.data.getTime()>Y.value)X=this._getOrReturnCtx(_,X),S(X,{code:f.too_big,message:Y.message,inclusive:!0,exact:!1,maximum:Y.value,type:"date"}),$.dirty()}else l.assertNever(Y);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new qw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:I.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:I.toString(w)})}get minDate(){let _=null;for(let w of this._def.checks)if(w.kind==="min"){if(_===null||w.value>_)_=w.value}return _!=null?new Date(_):null}get maxDate(){let _=null;for(let w of this._def.checks)if(w.kind==="max"){if(_===null||w.value<_)_=w.value}return _!=null?new Date(_):null}}qw.create=(_)=>{return new qw({checks:[],coerce:_?.coerce||!1,typeName:F.ZodDate,...h(_)})};class Q0 extends x{_parse(_){if(this._getType(_)!==j.symbol){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.symbol,received:$.parsedType}),T}return D_(_.data)}}Q0.create=(_)=>{return new Q0({typeName:F.ZodSymbol,...h(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.undefined,received:$.parsedType}),T}return D_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:F.ZodUndefined,...h(_)})};class Iw extends x{_parse(_){if(this._getType(_)!==j.null){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.null,received:$.parsedType}),T}return D_(_.data)}}Iw.create=(_)=>{return new Iw({typeName:F.ZodNull,...h(_)})};class Bw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return D_(_.data)}}Bw.create=(_)=>{return new Bw({typeName:F.ZodAny,...h(_)})};class n_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return D_(_.data)}}n_.create=(_)=>{return new n_({typeName:F.ZodUnknown,...h(_)})};class T_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:f.invalid_type,expected:j.never,received:w.parsedType}),T}}T_.create=(_)=>{return new T_({typeName:F.ZodNever,...h(_)})};class W0 extends x{_parse(_){if(this._getType(_)!==j.undefined){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.void,received:$.parsedType}),T}return D_(_.data)}}W0.create=(_)=>{return new W0({typeName:F.ZodVoid,...h(_)})};class F_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==j.array)return S(w,{code:f.invalid_type,expected:j.array,received:w.parsedType}),T;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,Q=w.data.length<X.exactLength.value;if(J||Q)S(w,{code:J?f.too_big:f.too_small,minimum:Q?X.exactLength.value:void 0,maximum:J?X.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:X.exactLength.message}),$.dirty()}if(X.minLength!==null){if(w.data.length<X.minLength.value)S(w,{code:f.too_small,minimum:X.minLength.value,type:"array",inclusive:!0,exact:!1,message:X.minLength.message}),$.dirty()}if(X.maxLength!==null){if(w.data.length>X.maxLength.value)S(w,{code:f.too_big,maximum:X.maxLength.value,type:"array",inclusive:!0,exact:!1,message:X.maxLength.message}),$.dirty()}if(w.common.async)return Promise.all([...w.data].map((J,Q)=>{return X.type._parseAsync(new N_(w,J,w.path,Q))})).then((J)=>{return W_.mergeArray($,J)});let Y=[...w.data].map((J,Q)=>{return X.type._parseSync(new N_(w,J,w.path,Q))});return W_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new F_({...this._def,minLength:{value:_,message:I.toString(w)}})}max(_,w){return new F_({...this._def,maxLength:{value:_,message:I.toString(w)}})}length(_,w){return new F_({...this._def,exactLength:{value:_,message:I.toString(w)}})}nonempty(_){return this.min(1,_)}}F_.create=(_,w)=>{return new F_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...h(w)})};function Sw(_){if(_ instanceof t){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=K_.create(Sw(X))}return new t({..._._def,shape:()=>w})}else if(_ instanceof F_)return new F_({..._._def,type:Sw(_.element)});else if(_ instanceof K_)return K_.create(Sw(_.unwrap()));else if(_ instanceof u_)return u_.create(Sw(_.unwrap()));else if(_ instanceof k_)return k_.create(_.items.map((w)=>Sw(w)));else return _}class t extends x{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let _=this._def.shape(),w=l.objectKeys(_);return this._cached={shape:_,keys:w},this._cached}_parse(_){if(this._getType(_)!==j.object){let G=this._getOrReturnCtx(_);return S(G,{code:f.invalid_type,expected:j.object,received:G.parsedType}),T}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),Q=[];if(!(this._def.catchall instanceof T_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))Q.push(G)}let W=[];for(let G of J){let D=Y[G],q=X.data[G];W.push({key:{status:"valid",value:G},value:D._parse(new N_(X,q,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof T_){let G=this._def.unknownKeys;if(G==="passthrough")for(let D of Q)W.push({key:{status:"valid",value:D},value:{status:"valid",value:X.data[D]}});else if(G==="strict"){if(Q.length>0)S(X,{code:f.unrecognized_keys,keys:Q}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let D of Q){let q=X.data[D];W.push({key:{status:"valid",value:D},value:G._parse(new N_(X,q,X.path,D)),alwaysSet:D in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let D of W){let q=await D.key,H=await D.value;G.push({key:q,value:H,alwaysSet:D.alwaysSet})}return G}).then((G)=>{return W_.mergeObjectSync($,G)});else return W_.mergeObjectSync($,W)}get shape(){return this._def.shape()}strict(_){return I.errToObj,new t({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message: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:F.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new t({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new t({...this._def,shape:()=>w})}deepPartial(){return Sw(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new t({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let Y=this.shape[$];while(Y instanceof K_)Y=Y._def.innerType;w[$]=Y}return new t({...this._def,shape:()=>w})}keyof(){return $4(l.objectKeys(this.shape))}}t.create=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strip",catchall:T_.create(),typeName:F.ZodObject,...h(w)})};t.strictCreate=(_,w)=>{return new t({shape:()=>_,unknownKeys:"strict",catchall:T_.create(),typeName:F.ZodObject,...h(w)})};t.lazycreate=(_,w)=>{return new t({shape:_,unknownKeys:"strip",catchall:T_.create(),typeName:F.ZodObject,...h(w)})};class Tw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(Y){for(let Q of Y)if(Q.result.status==="valid")return Q.result;for(let Q of Y)if(Q.result.status==="dirty")return w.common.issues.push(...Q.ctx.common.issues),Q.result;let J=Y.map((Q)=>new Q_(Q.ctx.common.issues));return S(w,{code:f.invalid_union,unionErrors:J}),T}if(w.common.async)return Promise.all($.map(async(Y)=>{let J={...w,common:{...w.common,issues:[]},parent:null};return{result:await Y._parseAsync({data:w.data,path:w.path,parent:J}),ctx:J}})).then(X);else{let Y=void 0,J=[];for(let W of $){let G={...w,common:{...w.common,issues:[]},parent:null},D=W._parseSync({data:w.data,path:w.path,parent:G});if(D.status==="valid")return D;else if(D.status==="dirty"&&!Y)Y={result:D,ctx:G};if(G.common.issues.length)J.push(G.common.issues)}if(Y)return w.common.issues.push(...Y.ctx.common.issues),Y.result;let Q=J.map((W)=>new Q_(W));return S(w,{code:f.invalid_union,unionErrors:Q}),T}}get options(){return this._def.options}}Tw.create=(_,w)=>{return new Tw({options:_,typeName:F.ZodUnion,...h(w)})};var m_=(_)=>{if(_ instanceof gw)return m_(_.schema);else if(_ instanceof b_)return m_(_.innerType());else if(_ instanceof hw)return[_.value];else if(_ instanceof o_)return _.options;else if(_ instanceof yw)return l.objectValues(_.enum);else if(_ instanceof vw)return m_(_._def.innerType);else if(_ instanceof Cw)return[void 0];else if(_ instanceof Iw)return[null];else if(_ instanceof K_)return[void 0,...m_(_.unwrap())];else if(_ instanceof u_)return[null,...m_(_.unwrap())];else if(_ instanceof G2)return m_(_.unwrap());else if(_ instanceof mw)return m_(_.unwrap());else if(_ instanceof xw)return m_(_._def.innerType);else return[]};class W2 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.object)return S(w,{code:f.invalid_type,expected:j.object,received:w.parsedType}),T;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),T;if(w.common.async)return Y._parseAsync({data:w.data,path:w.path,parent:w});else return Y._parseSync({data:w.data,path:w.path,parent:w})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(_,w,$){let X=new Map;for(let Y of w){let J=m_(Y.shape[_]);if(!J.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let Q of J){if(X.has(Q))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(Q)}`);X.set(Q,Y)}}return new W2({typeName:F.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...h($)})}}function E1(_,w){let $=I_(_),X=I_(w);if(_===w)return{valid:!0,data:_};else if($===j.object&&X===j.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((W)=>Y.indexOf(W)!==-1),Q={..._,...w};for(let W of J){let G=E1(_[W],w[W]);if(!G.valid)return{valid:!1};Q[W]=G.data}return{valid:!0,data:Q}}else if($===j.array&&X===j.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let Q=_[J],W=w[J],G=E1(Q,W);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===j.date&&X===j.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class kw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(Y,J)=>{if(J2(Y)||J2(J))return T;let Q=E1(Y.value,J.value);if(!Q.valid)return S($,{code:f.invalid_intersection_types}),T;if(Q2(Y)||Q2(J))w.dirty();return{status:w.value,value:Q.data}};if($.common.async)return Promise.all([this._def.left._parseAsync({data:$.data,path:$.path,parent:$}),this._def.right._parseAsync({data:$.data,path:$.path,parent:$})]).then(([Y,J])=>X(Y,J));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}kw.create=(_,w,$)=>{return new kw({left:_,right:w,typeName:F.ZodIntersection,...h($)})};class k_ extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.array)return S($,{code:f.invalid_type,expected:j.array,received:$.parsedType}),T;if($.data.length<this._def.items.length)return S($,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;if(!this._def.rest&&$.data.length>this._def.items.length)S($,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,Q)=>{let W=this._def.items[Q]||this._def.rest;if(!W)return null;return W._parse(new N_($,J,$.path,Q))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return W_.mergeArray(w,J)});else return W_.mergeArray(w,Y)}get items(){return this._def.items}rest(_){return new k_({...this._def,rest:_})}}k_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new k_({items:_,typeName:F.ZodTuple,rest:null,...h(w)})};class G0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.object)return S($,{code:f.invalid_type,expected:j.object,received:$.parsedType}),T;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let Q in $.data)X.push({key:Y._parse(new N_($,Q,$.path,Q)),value:J._parse(new N_($,$.data[Q],$.path,Q)),alwaysSet:Q in $.data});if($.common.async)return W_.mergeObjectAsync(w,X);else return W_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new G0({keyType:_,valueType:w,typeName:F.ZodRecord,...h($)});return new G0({keyType:L_.create(),valueType:_,typeName:F.ZodRecord,...h(w)})}}class D0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.map)return S($,{code:f.invalid_type,expected:j.map,received:$.parsedType}),T;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([Q,W],G)=>{return{key:X._parse(new N_($,Q,$.path,[G,"key"])),value:Y._parse(new N_($,W,$.path,[G,"value"]))}});if($.common.async){let Q=new Map;return Promise.resolve().then(async()=>{for(let W of J){let G=await W.key,D=await W.value;if(G.status==="aborted"||D.status==="aborted")return T;if(G.status==="dirty"||D.status==="dirty")w.dirty();Q.set(G.value,D.value)}return{status:w.value,value:Q}})}else{let Q=new Map;for(let W of J){let{key:G,value:D}=W;if(G.status==="aborted"||D.status==="aborted")return T;if(G.status==="dirty"||D.status==="dirty")w.dirty();Q.set(G.value,D.value)}return{status:w.value,value:Q}}}}D0.create=(_,w,$)=>{return new D0({valueType:w,keyType:_,typeName:F.ZodMap,...h($)})};class Hw extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==j.set)return S($,{code:f.invalid_type,expected:j.set,received:$.parsedType}),T;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:f.too_small,minimum:X.minSize.value,type:"set",inclusive:!0,exact:!1,message:X.minSize.message}),w.dirty()}if(X.maxSize!==null){if($.data.size>X.maxSize.value)S($,{code:f.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let Y=this._def.valueType;function J(W){let G=new Set;for(let D of W){if(D.status==="aborted")return T;if(D.status==="dirty")w.dirty();G.add(D.value)}return{status:w.value,value:G}}let Q=[...$.data.values()].map((W,G)=>Y._parse(new N_($,W,$.path,G)));if($.common.async)return Promise.all(Q).then((W)=>J(W));else return J(Q)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:I.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:I.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Hw.create=(_,w)=>{return new Hw({valueType:_,minSize:null,maxSize:null,typeName:F.ZodSet,...h(w)})};class Pw extends x{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.function)return S(w,{code:f.invalid_type,expected:j.function,received:w.parsedType}),T;function $(Q,W){return J0({data:Q,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,jw(),x_].filter((G)=>!!G),issueData:{code:f.invalid_arguments,argumentsError:W}})}function X(Q,W){return J0({data:Q,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,jw(),x_].filter((G)=>!!G),issueData:{code:f.invalid_return_type,returnTypeError:W}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Uw){let Q=this;return D_(async function(...W){let G=new Q_([]),D=await Q._def.args.parseAsync(W,Y).catch((B)=>{throw G.addIssue($(W,B)),G}),q=await Reflect.apply(J,this,D);return await Q._def.returns._def.type.parseAsync(q,Y).catch((B)=>{throw G.addIssue(X(q,B)),G})})}else{let Q=this;return D_(function(...W){let G=Q._def.args.safeParse(W,Y);if(!G.success)throw new Q_([$(W,G.error)]);let D=Reflect.apply(J,this,G.data),q=Q._def.returns.safeParse(D,Y);if(!q.success)throw new Q_([X(D,q.error)]);return q.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Pw({...this._def,args:k_.create(_).rest(n_.create())})}returns(_){return new Pw({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Pw({args:_?_:k_.create([]).rest(n_.create()),returns:w||n_.create(),typeName:F.ZodFunction,...h($)})}}class gw extends x{get schema(){return this._def.getter()}_parse(_){let{ctx:w}=this._processInputParams(_);return this._def.getter()._parse({data:w.data,path:w.path,parent:w})}}gw.create=(_,w)=>{return new gw({getter:_,typeName:F.ZodLazy,...h(w)})};class hw extends x{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return S(w,{received:w.data,code:f.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:_.data}}get value(){return this._def.value}}hw.create=(_,w)=>{return new hw({value:_,typeName:F.ZodLiteral,...h(w)})};function $4(_,w){return new o_({values:_,typeName:F.ZodEnum,...h(w)})}class o_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:f.invalid_type}),T}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has(_.data)){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{received:w.data,code:f.invalid_enum_value,options:$}),T}return D_(_.data)}get options(){return this._def.values}get enum(){let _={};for(let w of this._def.values)_[w]=w;return _}get Values(){let _={};for(let w of this._def.values)_[w]=w;return _}get Enum(){let _={};for(let w of this._def.values)_[w]=w;return _}extract(_,w=this._def){return o_.create(_,{...this._def,...w})}exclude(_,w=this._def){return o_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}o_.create=$4;class yw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==j.string&&$.parsedType!==j.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:f.invalid_type}),T}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:f.invalid_enum_value,options:X}),T}return D_(_.data)}get enum(){return this._def.values}}yw.create=(_,w)=>{return new yw({values:_,typeName:F.ZodNativeEnum,...h(w)})};class Uw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==j.promise&&w.common.async===!1)return S(w,{code:f.invalid_type,expected:j.promise,received:w.parsedType}),T;let $=w.parsedType===j.promise?w.data:Promise.resolve(w.data);return D_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Uw.create=(_,w)=>{return new Uw({type:_,typeName:F.ZodPromise,...h(w)})};class b_ extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===F.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=this._def.effect||null,Y={addIssue:(J)=>{if(S($,J),J.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(Y.addIssue=Y.addIssue.bind(Y),X.type==="preprocess"){let J=X.transform($.data,Y);if($.common.async)return Promise.resolve(J).then(async(Q)=>{if(w.value==="aborted")return T;let W=await this._def.schema._parseAsync({data:Q,path:$.path,parent:$});if(W.status==="aborted")return T;if(W.status==="dirty")return Dw(W.value);if(w.value==="dirty")return Dw(W.value);return W});else{if(w.value==="aborted")return T;let Q=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(Q.status==="aborted")return T;if(Q.status==="dirty")return Dw(Q.value);if(w.value==="dirty")return Dw(Q.value);return Q}}if(X.type==="refinement"){let J=(Q)=>{let W=X.refinement(Q,Y);if($.common.async)return Promise.resolve(W);if(W instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Q};if($.common.async===!1){let Q=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(Q.status==="aborted")return T;if(Q.status==="dirty")w.dirty();return J(Q.value),{status:w.value,value:Q.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((Q)=>{if(Q.status==="aborted")return T;if(Q.status==="dirty")w.dirty();return J(Q.value).then(()=>{return{status:w.value,value:Q.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!i_(J))return T;let Q=X.transform(J.value,Y);if(Q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:Q}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!i_(J))return T;return Promise.resolve(X.transform(J.value,Y)).then((Q)=>({status:w.value,value:Q}))});l.assertNever(X)}}b_.create=(_,w,$)=>{return new b_({schema:_,typeName:F.ZodEffects,effect:w,...h($)})};b_.createWithPreprocess=(_,w,$)=>{return new b_({schema:w,effect:{type:"preprocess",transform:_},typeName:F.ZodEffects,...h($)})};class K_ extends x{_parse(_){if(this._getType(_)===j.undefined)return D_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}K_.create=(_,w)=>{return new K_({innerType:_,typeName:F.ZodOptional,...h(w)})};class u_ extends x{_parse(_){if(this._getType(_)===j.null)return D_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}u_.create=(_,w)=>{return new u_({innerType:_,typeName:F.ZodNullable,...h(w)})};class vw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===j.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:F.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...h(w)})};class xw extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(Ew(X))return X.then((Y)=>{return{status:"valid",value:Y.status==="valid"?Y.value:this._def.catchValue({get error(){return new Q_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new Q_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}xw.create=(_,w)=>{return new xw({innerType:_,typeName:F.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...h(w)})};class q0 extends x{_parse(_){if(this._getType(_)!==j.nan){let $=this._getOrReturnCtx(_);return S($,{code:f.invalid_type,expected:j.nan,received:$.parsedType}),T}return{status:"valid",value:_.data}}}q0.create=(_)=>{return new q0({typeName:F.ZodNaN,...h(_)})};var qX=Symbol("zod_brand");class G2 extends x{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;return this._def.type._parse({data:$,path:w.path,parent:w})}unwrap(){return this._def.type}}class B0 extends x{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let Y=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(Y.status==="aborted")return T;if(Y.status==="dirty")return w.dirty(),Dw(Y.value);else return this._def.out._parseAsync({data:Y.value,path:$.path,parent:$})})();else{let X=this._def.in._parseSync({data:$.data,path:$.path,parent:$});if(X.status==="aborted")return T;if(X.status==="dirty")return w.dirty(),{status:"dirty",value:X.value};else return this._def.out._parseSync({data:X.value,path:$.path,parent:$})}}static create(_,w){return new B0({in:_,out:w,typeName:F.ZodPipeline})}}class mw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(i_(X))X.value=Object.freeze(X.value);return X};return Ew(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}mw.create=(_,w)=>{return new mw({innerType:_,typeName:F.ZodReadonly,...h(w)})};function t$(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function X4(_,w={},$){if(_)return Bw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((Q)=>{if(!Q){let W=t$(w,X),G=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:G})}});if(!J){let Q=t$(w,X),W=Q.fatal??$??!0;Y.addIssue({code:"custom",...Q,fatal:W})}return});return Bw.create()}var BX={object:t.lazycreate},F;(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"})(F||(F={}));var HX=(_,w={message:`Input not instance of ${_.name}`})=>X4(($)=>$ instanceof _,w),Y4=L_.create,J4=r_.create,UX=q0.create,zX=a_.create,Q4=Zw.create,VX=qw.create,OX=Q0.create,MX=Cw.create,AX=Iw.create,RX=Bw.create,fX=n_.create,LX=T_.create,FX=W0.create,KX=F_.create,NX=t.create,bX=t.strictCreate,jX=Tw.create,EX=W2.create,SX=kw.create,PX=k_.create,ZX=G0.create,CX=D0.create,IX=Hw.create,TX=Pw.create,kX=gw.create,gX=hw.create,hX=o_.create,yX=yw.create,vX=Uw.create,xX=b_.create,mX=K_.create,uX=u_.create,lX=b_.createWithPreprocess,cX=B0.create,dX=()=>Y4().optional(),pX=()=>J4().optional(),iX=()=>Q4().optional(),nX={string:(_)=>L_.create({..._,coerce:!0}),number:(_)=>r_.create({..._,coerce:!0}),boolean:(_)=>Zw.create({..._,coerce:!0}),bigint:(_)=>a_.create({..._,coerce:!0}),date:(_)=>qw.create({..._,coerce:!0})};var rX=T;var S1=M.object({bgProcessId:M.string().min(1,"bgProcessId must not be empty").describe("The background process ID returned by delegate_task (format: process_<timestamp>_<random>).")});function aX(_){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 W4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var oV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
226
233
|
|
|
227
234
|
Use this tool when:
|
|
228
235
|
- You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
|
|
@@ -239,7 +246,7 @@ Use this tool when:
|
|
|
239
246
|
- result: present when status is 'completed'
|
|
240
247
|
- error: present when status is 'failed'
|
|
241
248
|
|
|
242
|
-
Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:
|
|
249
|
+
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:S1,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(_,w)=>D2(null).execute(_,w)};function D2(_=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
243
250
|
|
|
244
251
|
Use this tool when:
|
|
245
252
|
- You delegated a long-running task but have NOT received any notification after a reasonable wait (5+ minutes), and want to confirm whether the process is still alive.
|
|
@@ -256,7 +263,7 @@ Use this tool when:
|
|
|
256
263
|
- result: present when status is 'completed'
|
|
257
264
|
- error: present when status is 'failed'
|
|
258
265
|
|
|
259
|
-
Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-agent, etc.) cannot see it because they do not need to query background tasks they themselves launched.`,parameters:
|
|
266
|
+
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:S1,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(w,$)=>{let X=Date.now(),Y=S1.parse(w),{bgProcessId:J}=Y;if(!_)return{success:!1,output:"",error:"query_background_process is not initialized: no BackgroundTaskManager has been bound. TaskComponent should call createQueryBackgroundProcessTool(manager) and register the tool during startup.",metadata:{execution_time_ms:Date.now()-X}};let Q;try{Q=_.getTask(J)}catch(G){return{success:!1,output:"",error:`failed to query background task: ${G.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(Q){let G=$.session_id;if(!G||Q.parentSessionId!==G)return{success:!0,output:JSON.stringify(W4(J),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:"not_found",alive:!1}}}let W=Q?aX(Q):W4(J);if(W.alive)try{let G=await _.getSubSessionActivity?.(J);if(G)W.lastUpdatedAt=Math.max(W.lastUpdatedAt,G.updatedAt),W.messageCount=G.messageCount,W.subSessionUpdatedAt=G.updatedAt}catch{}return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:W.status,alive:W.alive}}}}}var G4=M.object({task_id:M.string().describe("The ID of the background task to stop")}),oX=`Stop a running background task.
|
|
260
267
|
|
|
261
268
|
Use this tool to stop a background task that is currently running. This is useful when:
|
|
262
269
|
- The user wants to cancel a long-running task
|
|
@@ -266,10 +273,10 @@ Use this tool to stop a background task that is currently running. This is usefu
|
|
|
266
273
|
When stopped, the task will be terminated immediately and you will receive a confirmation.
|
|
267
274
|
|
|
268
275
|
Parameters:
|
|
269
|
-
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function
|
|
270
|
-
`),metadata:{execution_time_ms:Date.now()-X,task_id:J,previous_status:W.status}}}else{let W=
|
|
271
|
-
`);else G=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${J}`,"",
|
|
272
|
-
`);return{success:!1,output:G,error:
|
|
276
|
+
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function sX(_){let w=Math.floor(_/1000),$=Math.floor(w/60),X=Math.floor($/60);if(X>0)return`${X}h ${$%60}m ${w%60}s`;else if($>0)return`${$}m ${w%60}s`;else return`${w}s`}function D4(_){return{name:"stop_task",description:oX,parameters:G4,execute:async(w,$)=>{let X=Date.now(),Y=G4.parse(w),{task_id:J}=Y,Q=await _.stopTask(J);if(Q.success){let W=Q.task,G=W.startedAt?Date.now()-W.startedAt:Date.now()-W.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Status: ${W.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${sX(G)}`,"",Q.message].join(`
|
|
277
|
+
`),metadata:{execution_time_ms:Date.now()-X,task_id:J,previous_status:W.status}}}else{let W=Q.task,G;if(W)G=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${W.description}`,`\uD83D\uDD04 Current Status: ${W.status}`,"",Q.message].join(`
|
|
278
|
+
`);else G=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${J}`,"",Q.message].join(`
|
|
279
|
+
`);return{success:!1,output:G,error:Q.message,metadata:{execution_time_ms:Date.now()-X,task_id:J}}}}}}import{createRequire as tX}from"module";var{defineProperty:P1,getOwnPropertyNames:eX,getOwnPropertyDescriptor:_7}=Object,w7=Object.prototype.hasOwnProperty;function $7(_){return this[_]}var uw=(_)=>{var w=(q4??=new WeakMap).get(_),$;if(w)return w;if(w=P1({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var X of eX(_))if(!w7.call(w,X))P1(w,X,{get:$7.bind(_,X),enumerable:!($=_7(_,X))||$.enumerable})}return q4.set(_,w),w},q4,X7=(_)=>_;function Y7(_,w){this[_]=X7.bind(null,w)}var s_=(_,w)=>{for(var $ in w)P1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:Y7.bind(w,$)})},m=function(_,w,$,X){var Y=arguments.length,J=Y<3?w:X===null?X=Object.getOwnPropertyDescriptor(w,$):X,Q;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")J=Reflect.decorate(_,w,$,X);else for(var W=_.length-1;W>=0;W--)if(Q=_[W])J=(Y<3?Q(J):Y>3?Q(w,$,J):Q(w,$))||J;return Y>3&&J&&Object.defineProperty(w,$,J),J},r=(_,w)=>()=>(_&&(w=_(_=0)),w),e=tX(import.meta.url);function Z1(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function B4(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if("$typeof"in X||"type"in X&&"props"in X&&"key"in X)return"[ReactElement]";if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch($){return`[Unserializable: ${$ instanceof Error?$.message:String($)}]`}}function J7(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function Q7(_){let $=new(J7())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class C1{db=null;dbPath;initialized=!1;constructor(_){if(!_)throw Error("SQLiteSpanStorage requires a valid dbPath parameter");if(_===":memory:")throw Error("SQLiteSpanStorage does not support :memory: mode. Use a file path instead.");this.dbPath=_}async initialize(){if(this.initialized)return;let _=e("fs"),$=e("path").dirname(this.dbPath);if(!_.existsSync($))_.mkdirSync($,{recursive:!0});this.db=Q7(this.dbPath),this.db.run("PRAGMA journal_mode=WAL"),this.db.run("PRAGMA busy_timeout=5000"),this.db.run("PRAGMA synchronous=NORMAL"),this.db.run(`
|
|
273
280
|
CREATE TABLE IF NOT EXISTS span (
|
|
274
281
|
span_id TEXT PRIMARY KEY,
|
|
275
282
|
trace_id TEXT NOT NULL,
|
|
@@ -284,11 +291,11 @@ Parameters:
|
|
|
284
291
|
error TEXT,
|
|
285
292
|
time_created INTEGER NOT NULL
|
|
286
293
|
)
|
|
287
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_trace ON span(trace_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_span_parent ON span(parent_span_id)"),this.initialized=!0}save(_){if(!this.db){if(
|
|
294
|
+
`),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(Z1())console.log(`[SpanStorage] save() skipped: db not initialized for span "${_.name}" traceId=${_.traceId}`);return}let w=this.db.prepare(`
|
|
288
295
|
INSERT OR REPLACE INTO span
|
|
289
296
|
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
290
297
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
291
|
-
`),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:
|
|
298
|
+
`),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:B4(_.result):null;if(Z1())console.log(`[SpanStorage] Saving to "${this.dbPath}": name="${_.name}" traceId=${_.traceId} spanId=${_.spanId} status=${_.status}`);try{let X=w.run(_.spanId,_.traceId,_.parentSpanId||null,_.name,_.kind,_.status,_.startTime,_.endTime||null,B4(_.attributes),$,_.error||null,Date.now());if(Z1())console.log(`[SpanStorage] Save result: changes=${X?.changes}, lastInsertRowid=${X?.lastInsertRowid}`)}catch(X){console.error("[SpanStorage] Save ERROR:",X)}}saveBatch(_){for(let w of _)this.save(w)}findByTraceId(_){if(!this.db)return[];let w=this.db.prepare("SELECT * FROM span WHERE trace_id = ?").all(_);return this.buildTree(w.map(this.rowToSpan))}findBySpanId(_){if(!this.db)return;let w=this.db.prepare("SELECT * FROM span WHERE span_id = ?").get(_);return w?this.rowToSpan(w):void 0}listTraces(_=10){if(!this.db)return[];return this.db.prepare(`
|
|
292
299
|
SELECT trace_id,
|
|
293
300
|
MIN(start_time) as start_time,
|
|
294
301
|
MAX(end_time) as end_time,
|
|
@@ -303,10 +310,10 @@ Parameters:
|
|
|
303
310
|
GROUP BY trace_id
|
|
304
311
|
ORDER BY start_time DESC
|
|
305
312
|
LIMIT ?
|
|
306
|
-
`).all(_).map(($)=>{let X=Number($.span_count)||0,Y=Number($.error_count)||0,J=$.end_time??void 0,
|
|
307
|
-
`)||[];Error.stackTraceLimit=_;for(let X=1;X<$.length;X++){let Y=$[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let J=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(J){let
|
|
308
|
-
`,"utf-8")}catch(w){console.error("[Logger] Failed to write to log file:",w)}}log(_,w,$){if(!this.shouldLog(_))return;let X=this.formatMessage(_,w,$);if(this.writeToFile(X),!q7())if(M7)console.error(X);else(_==="error"?console.error:_==="warn"?console.warn:_==="info"?console.log:console.debug)(X)}debug(_,w){this.log("debug",_,w)}info(_,w){this.log("info",_,w)}warn(_,w){this.log("warn",_,w)}error(_,w){this.log("error",_,w)}}function n(_){if(!Q1.has(_))Q1.set(_,new U4(_));return Q1.get(_)}var N_=null,A7=!1,M7=!1;var I2,Q1,a=r(()=>{m2(),I2={debug:0,info:1,warn:2,error:3},Q1=new Map}),R7={};o_(R7,{setTracerProvider:()=>L7,resetTracerProvider:()=>f7,getTracerProvider:()=>B0,OTelTracerProvider:()=>x2});function v2(){if(!C2)C2=n("otel-tracer");return C2}function z4(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function V4(_,...w){v2().info(_,...w)}function G4(_,...w){v2().warn(_,...w)}function Q4(_,...w){v2().error(_,...w)}class k2{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,Y){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=Y}setAttribute(_,w){this.attributes[_]=w}addEvent(_,w){let $=this.attributes._events||[];$.push({name:_,attributes:w}),this.attributes._events=$}end(_,w){if(this.endTime=Date.now(),w)this.error=w.message;let $=this.endTime-(this.startTime||0);if(z4())V4(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${$}ms status=${w?"ERROR":"OK"}`);let X=this.storage;if(!X)G4(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=B0().getStorage();if(X){if(!(X.db||X.initialized))G4(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{Q4("[OTelSpan] Failed to initialize storage:",J)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else Q4(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class O4{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext(_){this.provider.setTracerCurrentContext(this.instanceId,_)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor(_,w,$,X){this.name=_,this.version=w,this.storage=$,this.provider=X,this.instanceId=`${_}@${X.instanceId}`}setOnSpanEndCallback(_){this.onSpanEndCallback=_}getActiveSpanCount(){return this.activeSpans.size}startSpan(_,w){let $=w?.parent,X=w&&"parent"in w,Y=w&&"context"in w,J=this.provider.getGlobalContext(),D,W,G,Q,q;if(Y&&w?.context){let B=w.context;W=B.traceId,G=this.generateSpanId(),Q=B.spanId,q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let O=new k2(_,q,this.storage,B,()=>this.handleSpanEnd(q.spanId,B.spanId));if(w?.attributes)for(let[z,U]of Object.entries(w.attributes))O.setAttribute(z,U);return this.activeSpans.set(G,O),O}if(X)D=$;else if(this.currentContext)D=this.currentContext;else if(J)D=J;if(W=D?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)Q=$.parentSpanId||$.spanId;else if(this.currentContext)Q=this.currentContext.spanId;else if(J)Q=J.spanId;q={traceId:W,spanId:G,parentSpanId:Q},this.currentContext={traceId:W,spanId:G,parentSpanId:Q};let H=new k2(_,q,this.storage,D,()=>this.handleSpanEnd(q.spanId,D?.spanId));if(w?.attributes)for(let[B,O]of Object.entries(w.attributes))H.setAttribute(B,O);if(this.activeSpans.set(G,H),z4())V4(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${W} spanId=${G} parentSpanId=${Q||"-"}`);return H}injectToEnv(_){if(this.currentContext)g2.inject(_,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext(_){this.currentContext=_}findStackParentSpan(_){for(let[,w]of this.activeSpans)if(w.spanContext.parentSpanId===_)return w;return}endSpan(_){let w=_.spanContext;this.activeSpans.delete(w.spanId);let $=this.currentContext?.traceId;if(w.parentSpanId){let Y=this.activeSpans.get(w.parentSpanId);if(Y){let J={traceId:w.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=J,J}if($){let J={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=J,J}}let X=this.findStackParentSpan(w.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let _=Date.now().toString(16).padStart(12,"0"),w=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return(_+w).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd(_,w){if(this.activeSpans.delete(_),w){let X=this.activeSpans.get(w);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:w,parentSpanId:void 0};return}}let $=this.findStackParentSpan(_);if($){this.currentContext={traceId:$.spanContext.traceId,spanId:$.spanContext.spanId,parentSpanId:$.spanContext.parentSpanId};return}this.currentContext=void 0}}class x2{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new W4;tracerContexts=new Map;tracerContextScope=new W4;instanceId;constructor(_,w){q4++,this.instanceId=`Provider#${q4}`,this.storage=_||new S2(w||F7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){let _=this.globalContextScope.getStore();if(_)return _.value;return this.globalContext}setGlobalContext(_){this.globalContext=_}withGlobalContext(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}runInGlobalContextSync(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}getTracerCurrentContext(_){let w=this.tracerContextScope.getStore();if(w)return w.contexts.get(_);return this.tracerContexts.get(_)}setTracerCurrentContext(_,w){let $=this.tracerContextScope.getStore();if($){$.contexts.set(_,w);return}this.tracerContexts.set(_,w)}clearAllTracerCurrentContexts(){let _=this.tracerContextScope.getStore();if(_){_.contexts.clear();return}this.tracerContexts.clear()}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new O4(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=g2.extract(process.env);if(w)_.setCurrentContext({traceId:w.traceId,spanId:w.spanId,parentSpanId:void 0})}shutdown(){for(let _ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function B0(){if(!m_)m_=new x2;return m_}function f7(){if(m_)m_.shutdown(),m_=null}function L7(_){if(m_)m_.shutdown();m_=_}function F7(){let _=e("os"),w=e("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var C2=null,m_=null,q4=0,m2=r(()=>{J4(),$7(),J7(),a()});import{AsyncLocalStorage as K7}from"async_hooks";a();var q1=n("process-tree-killer");function R4(){return e("child_process")}var A4;function N7(_,w,$){if(A4)return A4(_,w,$);return R4().spawn(_,w,$)}var M4;function b7(_,w,$){if(M4)return M4(_,w,$);let X=R4();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var j7;function E7(){return j7??process.platform}function S7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function P7(_){try{let w=b7("tasklist",["/fi",`PID eq ${_}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!w)return!0;return w.stdout.toString().includes(String(_))}catch{return!0}}function Z7(_){return new Promise((w)=>setTimeout(w,_))}async function C7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=E7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;q1.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let D=1;D<=Y;D++){let W=$==="win32"?T7(_):I7(_,X,$);if(await Z7(J),!($==="win32"?P7(_):S7(_)))return q1.info(`[bg-process:kill-done] pid=${_} attempts=${D} stillAlive=false`),{pid:_,platform:$,signal:W.signal,success:!0,attempts:D,stillAlive:!1};if(D<Y)q1.warn(`[bg-process:kill-retry] pid=${_} attempt=${D}/${Y}`)}return q1.error(`[bg-process:kill-failed] pid=${_} attempts=${Y} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function T7(_){try{return N7("taskkill",["/pid",String(_),"/f","/t"],{stdio:"ignore",windowsHide:!0}),{pid:_,platform:"win32",signal:"taskkill /f /t",success:!0}}catch{return{pid:_,platform:"win32",signal:"taskkill /f /t",success:!1}}}function I7(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var u2=n("task:process-registry");class l2{pids=new Set;register(_){if(!Number.isInteger(_)||_<=0)return;this.pids.add(_)}unregister(_){if(!Number.isInteger(_))return;this.pids.delete(_)}size(){return this.pids.size}async killAll(){if(this.pids.size===0)return;let _=Array.from(this.pids);u2.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await C7(w,{retry:3,retryDelayMs:500});if($.stillAlive)u2.error(`\u8FDB\u7A0B PID ${w} \u7ECF\u8FC7 ${$.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(w)}catch{}u2.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var k7=new K7;function f4(_,w){return k7.run(_,w)}function g7(){if(H1!==void 0)return H1;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return H1=_==="1"||_==="true"||_==="yes",H1}var H1;var h7=()=>{};function y7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordResultToDb:_?.recordResultToDb??!1,logResult:_?.logResult,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let W=Y.value,G=_?.name||String(X);return Y.value=I_(W,G,w()),Y}let J=$,D=X||{};if(typeof J==="function"){let W=_?.name||(D?.name?String(D.name):"anonymous");return I_(J,W,w())}return J}}function u(_,w){return y7({name:_,...w})}function I_(_,w,$){let X={recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!0,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter??!1,errorIf:$?.errorIf},Y=X.log,J=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let z=y2();return z!==void 0?z:500},D=(z)=>{if(z===void 0)return;if(z===null)return null;let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}if(U>0&&V.length>U)return V.slice(0,U)+" [TRUNCATED]";try{return JSON.parse(V)}catch{return V}},W=(z)=>{if(z===void 0)return"undefined";if(z===null)return"null";let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(M){V=`[Object with circular reference: ${M instanceof Error?M.message:String(M)}]`}return U>0&&V.length>U?V.slice(0,U)+" [TRUNCATED]":V},G=(z)=>{if(z===void 0)return;if(z===null)return null;if(typeof z==="string")return z;try{return JSON.parse(JSON.stringify(z))}catch(U){return`[Object with circular reference: ${U instanceof Error?U.message:String(U)}]`}},Q="[TRACE]",q=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},H=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(g7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:q(()=>X.resultFilter(z));if(V&&typeof V==="object"&&!Array.isArray(V))return{value:V,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:z,store:!0}},B=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,B);let V=U.stack?.split(`
|
|
309
|
-
`)||[];Error.stackTraceLimit=z;for(let
|
|
313
|
+
`).all(_).map(($)=>{let X=Number($.span_count)||0,Y=Number($.error_count)||0,J=$.end_time??void 0,Q=Y===0?"ok":Y>=X?"error":"mixed";return{traceId:$.trace_id,rootSpanName:$.root_name??"unknown",startTime:$.start_time,endTime:J,duration:J!==void 0?J-$.start_time:void 0,spanCount:X,status:Q}})}deleteByTraceId(_){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(_)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan(_){return{traceId:_.trace_id,spanId:_.span_id,parentSpanId:_.parent_span_id,name:_.name,kind:_.kind,status:_.status,startTime:_.start_time,endTime:_.end_time,attributes:_.attributes?JSON.parse(_.attributes):{},result:_.result||void 0,error:_.error||void 0}}buildTree(_){let w=new Map,$=[];for(let X of _)w.set(X.spanId,{...X,children:[]});for(let X of w.values())if(X.parentSpanId){let Y=w.get(X.parentSpanId);if(Y)Y.children.push(X);else $.push(X)}else $.push(X);return $}}var H4=()=>{};import{appendFileSync as V7,existsSync as O7,mkdirSync as M7}from"fs";import{join as H0}from"path";import{AsyncLocalStorage as z4}from"async_hooks";function U4(_,w){return _.padStart(w,"0")}function I1(_){return/^[0-9a-f]+$/i.test(_)}function W7(_){let w=U4(_.traceId.toLowerCase(),A4),$=U4(_.spanId.toLowerCase(),R4);return[g1,w,$,D7].join("-")}function G7(_){if(!_||typeof _!=="string")return;let $=_.trim().split("-");if($.length!==4)return;let[X,Y,J,Q]=$;if(X!==g1){if(X>g1)return}if(Y.length!==A4||!I1(Y))return;if(J.length!==R4||!I1(J))return;if(Q.length!==q7||!I1(Q))return;return{traceId:Y.toLowerCase(),spanId:J.toLowerCase()}}var g1="00",D7="01",T1="TRACEPARENT",A4=32,R4=16,q7=2,v1,B7=r(()=>{v1={inject(_,w){_[T1]=W7(w)},extract(_){let w=_[T1];if(!w)return;return G7(w)},getTraceparentHeader(){return T1}}}),H7,U7,z7=r(()=>{((_)=>{_.CLIENT="client",_.SERVER="server",_.INTERNAL="internal"})(H7||={}),((_)=>{_.OK="ok",_.ERROR="error"})(U7||={})});function x1(_){let w=_.replace(/\\/g,"/"),$=w.match(/\/\$bunfs\/root\/(.+)$/);if($){let Q=$[1],W=Q.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(W)return W[1];return Q}let X=w.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let Q=X[1].replace(/\+/g,"/"),W=X[2],G=Q,D=W.startsWith("src/")?W:`src/${W}`;return`${G}/${D}`}let Y=w.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let J=["packages/core/src","packages/core","packages"];for(let Q of J){let W=w.indexOf(Q);if(W!==-1)return w.substring(W)}return w}function A7(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let w=e("xdg-basedir");if(w.xdgData)return H0(w.xdgData,"roy-agent","logs")}catch{}return H0(_,".local","share","roy-agent","logs")}function R7(){return j7}function f7(){if(j_){let w=j_.get("log_trace.logging.level");if(w&&["debug","info","warn","error"].includes(w))return w}let _=process.env.LOG_LEVEL;if(_&&["debug","info","warn","error"].includes(_))return _;return"info"}function L7(_){if(j_){let X=j_.get("log_trace.logging.levels");if(X&&typeof X==="object"){let J=X[_];if(J&&["debug","info","warn","error"].includes(J))return J}let Y=j_.get(`log_trace.logging.levels.${_}`);if(Y&&["debug","info","warn","error"].includes(Y))return Y}let w=`LOG_LEVEL_${_.toUpperCase().replace(/:/g,"_")}`,$=process.env[w];if($&&["debug","info","warn","error"].includes($))return $;return f7()}function F7(_){if(_.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(_))return!0;return!1}function K7(_){if(_.startsWith("~")){let w=process.env.HOME||process.env.USERPROFILE||"/tmp";return H0(w,_.slice(1))}return _}function N7(){if(j_){let _=j_.get("log-trace.logging.file");if(_)return _}return"app.log"}function b7(){if(j_){let _=j_.get("log-trace.logging.dir");if(_)return _}return A7()}function m1(){if(j_){let _=j_.get("log-trace.logging.maxOutput");if(typeof _==="number")return _}return}class f4{prefix;constructor(_){this.prefix=_}shouldLog(_){let w=L7(this.prefix);return h1[_]>=h1[w]}ensureLogDirectory(_){if(!O7(_))try{M7(_,{recursive:!0})}catch(w){console.error("[Logger] Failed to create log directory:",_,w)}}getCallerLocation(){let _=Error.stackTraceLimit;Error.stackTraceLimit=10;let w=Error();Error.captureStackTrace(w,this.formatMessage);let $=w.stack?.split(`
|
|
314
|
+
`)||[];Error.stackTraceLimit=_;for(let X=1;X<$.length;X++){let Y=$[X];if(Y.includes("at ")&&!Y.includes("logger.ts")&&!Y.includes("formatMessage")){let J=Y.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||Y.match(/at\s+(.+):(\d+):\d+/);if(J){let Q=J[1];return{file:this.getRelativePath(Q),line:parseInt(J[2],10)}}}}return null}getRelativePath(_){return x1(_)}formatMessage(_,w,$){let X=new Date,Y=X.toLocaleString("zh-CN",{timeZone:"Asia/Shanghai",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).replace(/\//g,"-")+"."+String(X.getMilliseconds()).padStart(3,"0"),J=this.prefix?`[${this.prefix}]`:"",Q="";try{let B=U0().getTracer("roy-tracer").getCurrentContext();if(B?.traceId)Q=`[traceId=${B.traceId}]`}catch{}let W="";if($&&typeof $==="object"&&"callerLocation"in $){let q=$;W=q.callerLocation?` [${q.callerLocation}]`:"";let{callerLocation:H,...B}=q;$=Object.keys(B).length>0?B:void 0}else{let q=this.getCallerLocation();if(q)W=` [${q.file}:${q.line}]`}let G=`${Y} [${_.toUpperCase()}]${Q}${W}${J} ${w}`;if($!==void 0)if(typeof $==="object")G+=" "+JSON.stringify($).replace(/\n/g,"");else G+=" "+String($);let D=m1();if(D&&D>0&&G.length>D)G=G.substring(0,D)+" [TRUNCATED]";return G}writeToFile(_){try{let w=b7(),$=N7(),X=K7(w),Y=F7(X)?X:H0(process.cwd(),X);this.ensureLogDirectory(Y);let J=H0(Y,$);V7(J,_+`
|
|
315
|
+
`,"utf-8")}catch(w){console.error("[Logger] Failed to write to log file:",w)}}log(_,w,$){if(!this.shouldLog(_))return;let X=this.formatMessage(_,w,$);if(this.writeToFile(X),!R7())if(E7)console.error(X);else(_==="error"?console.error:_==="warn"?console.warn:_==="info"?console.log:console.debug)(X)}debug(_,w){this.log("debug",_,w)}info(_,w){this.log("info",_,w)}warn(_,w){this.log("warn",_,w)}error(_,w){this.log("error",_,w)}}function n(_){if(!q2.has(_))q2.set(_,new f4(_));return q2.get(_)}var j_=null,j7=!1,E7=!1;var h1,q2,a=r(()=>{c1(),h1={debug:0,info:1,warn:2,error:3},q2=new Map}),S7={};s_(S7,{setTracerProvider:()=>Z7,resetTracerProvider:()=>P7,getTracerProvider:()=>U0,OTelTracerProvider:()=>l1});function u1(){if(!k1)k1=n("otel-tracer");return k1}function L4(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function F4(_,...w){u1().info(_,...w)}function V4(_,...w){u1().warn(_,...w)}function O4(_,...w){u1().error(_,...w)}class y1{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,Y){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=Y}setAttribute(_,w){this.attributes[_]=w}addEvent(_,w){let $=this.attributes._events||[];$.push({name:_,attributes:w}),this.attributes._events=$}end(_,w){if(this.endTime=Date.now(),w)this.error=w.message;let $=this.endTime-(this.startTime||0);if(L4())F4(`[OTelSpan] Ending span: name="${this.name}" traceId=${this.spanContext.traceId} spanId=${this.spanContext.spanId} duration=${$}ms status=${w?"ERROR":"OK"}`);let X=this.storage;if(!X)V4(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=U0().getStorage();if(X){if(!(X.db||X.initialized))V4(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{O4("[OTelSpan] Failed to initialize storage:",J)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else O4(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class K4{name;version;storage;get currentContext(){return this.provider.getTracerCurrentContext(this.instanceId)}set currentContext(_){this.provider.setTracerCurrentContext(this.instanceId,_)}activeSpans=new Map;onSpanEndCallback;provider;instanceId;constructor(_,w,$,X){this.name=_,this.version=w,this.storage=$,this.provider=X,this.instanceId=`${_}@${X.instanceId}`}setOnSpanEndCallback(_){this.onSpanEndCallback=_}getActiveSpanCount(){return this.activeSpans.size}startSpan(_,w){let $=w?.parent,X=w&&"parent"in w,Y=w&&"context"in w,J=this.provider.getGlobalContext(),Q,W,G,D,q;if(Y&&w?.context){let B=w.context;W=B.traceId,G=this.generateSpanId(),D=B.spanId,q={traceId:W,spanId:G,parentSpanId:D},this.currentContext={traceId:W,spanId:G,parentSpanId:D};let O=new y1(_,q,this.storage,B,()=>this.handleSpanEnd(q.spanId,B.spanId));if(w?.attributes)for(let[z,U]of Object.entries(w.attributes))O.setAttribute(z,U);return this.activeSpans.set(G,O),O}if(X)Q=$;else if(this.currentContext)Q=this.currentContext;else if(J)Q=J;if(W=Q?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)D=$.parentSpanId||$.spanId;else if(this.currentContext)D=this.currentContext.spanId;else if(J)D=J.spanId;q={traceId:W,spanId:G,parentSpanId:D},this.currentContext={traceId:W,spanId:G,parentSpanId:D};let H=new y1(_,q,this.storage,Q,()=>this.handleSpanEnd(q.spanId,Q?.spanId));if(w?.attributes)for(let[B,O]of Object.entries(w.attributes))H.setAttribute(B,O);if(this.activeSpans.set(G,H),L4())F4(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${W} spanId=${G} parentSpanId=${D||"-"}`);return H}injectToEnv(_){if(this.currentContext)v1.inject(_,this.currentContext)}getCurrentContext(){return this.currentContext}setCurrentContext(_){this.currentContext=_}findStackParentSpan(_){for(let[,w]of this.activeSpans)if(w.spanContext.parentSpanId===_)return w;return}endSpan(_){let w=_.spanContext;this.activeSpans.delete(w.spanId);let $=this.currentContext?.traceId;if(w.parentSpanId){let Y=this.activeSpans.get(w.parentSpanId);if(Y){let J={traceId:w.traceId,spanId:Y.spanContext.spanId,parentSpanId:Y.spanContext.parentSpanId};return this.currentContext=J,J}if($){let J={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=J,J}}let X=this.findStackParentSpan(w.spanId);if(X){let Y={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=Y,Y}this.currentContext=void 0;return}generateTraceId(){let _=Date.now().toString(16).padStart(12,"0"),w=Array.from({length:5},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("");return(_+w).slice(0,32).padStart(32,"0")}generateSpanId(){return Math.floor(Math.random()*18446744073709552000).toString(16).padStart(16,"0")}handleSpanEnd(_,w){if(this.activeSpans.delete(_),w){let X=this.activeSpans.get(w);if(X){this.currentContext={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return}if(this.currentContext?.traceId){this.currentContext={traceId:this.currentContext.traceId,spanId:w,parentSpanId:void 0};return}}let $=this.findStackParentSpan(_);if($){this.currentContext={traceId:$.spanContext.traceId,spanId:$.spanContext.spanId,parentSpanId:$.spanContext.parentSpanId};return}this.currentContext=void 0}}class l1{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new z4;tracerContexts=new Map;tracerContextScope=new z4;instanceId;constructor(_,w){M4++,this.instanceId=`Provider#${M4}`,this.storage=_||new C1(w||C7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){let _=this.globalContextScope.getStore();if(_)return _.value;return this.globalContext}setGlobalContext(_){this.globalContext=_}withGlobalContext(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}runInGlobalContextSync(_,w){let $=new Map(this.tracerContexts);return this.globalContextScope.run({value:_},()=>this.tracerContextScope.run({contexts:$},w))}getTracerCurrentContext(_){let w=this.tracerContextScope.getStore();if(w)return w.contexts.get(_);return this.tracerContexts.get(_)}setTracerCurrentContext(_,w){let $=this.tracerContextScope.getStore();if($){$.contexts.set(_,w);return}this.tracerContexts.set(_,w)}clearAllTracerCurrentContexts(){let _=this.tracerContextScope.getStore();if(_){_.contexts.clear();return}this.tracerContexts.clear()}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new K4(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=v1.extract(process.env);if(w)_.setCurrentContext({traceId:w.traceId,spanId:w.spanId,parentSpanId:void 0})}shutdown(){for(let _ of this.tracers.values());this.tracers.clear(),this.storage.close(),this.initialized=!1,this.globalContext=void 0,delete process.env.TRACEPARENT,delete process.env.TRACE_ID,delete process.env.LOG_TRACE_REQUEST_ID}getStorage(){return this.storage}}function U0(){if(!l_)l_=new l1;return l_}function P7(){if(l_)l_.shutdown(),l_=null}function Z7(_){if(l_)l_.shutdown();l_=_}function C7(){let _=e("os"),w=e("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var k1=null,l_=null,M4=0,c1=r(()=>{H4(),B7(),z7(),a()});import{AsyncLocalStorage as I7}from"async_hooks";a();var B2=n("process-tree-killer");function j4(){return e("child_process")}var N4;function T7(_,w,$){if(N4)return N4(_,w,$);return j4().spawn(_,w,$)}var b4;function k7(_,w,$){if(b4)return b4(_,w,$);let X=j4();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var g7;function h7(){return g7??process.platform}function y7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function v7(_){try{let w=k7("tasklist",["/fi",`PID eq ${_}`,"/nh"],{stdio:["ignore","pipe","ignore"],windowsHide:!0,timeout:3000});if(!w)return!0;return w.stdout.toString().includes(String(_))}catch{return!0}}function x7(_){return new Promise((w)=>setTimeout(w,_))}async function m7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=h7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;B2.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let Q=1;Q<=Y;Q++){let W=$==="win32"?u7(_):l7(_,X,$);if(await x7(J),!($==="win32"?v7(_):y7(_)))return B2.info(`[bg-process:kill-done] pid=${_} attempts=${Q} stillAlive=false`),{pid:_,platform:$,signal:W.signal,success:!0,attempts:Q,stillAlive:!1};if(Q<Y)B2.warn(`[bg-process:kill-retry] pid=${_} attempt=${Q}/${Y}`)}return B2.error(`[bg-process:kill-failed] pid=${_} attempts=${Y} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:Y,stillAlive:!0}}function u7(_){try{return T7("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 l7(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let Y=X.code;if(Y==="ESRCH"||Y==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var d1=n("task:process-registry");class p1{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);d1.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await m7(w,{retry:3,retryDelayMs:500});if($.stillAlive)d1.error(`\u8FDB\u7A0B PID ${w} \u7ECF\u8FC7 ${$.attempts} \u6B21\u91CD\u8BD5\u540E\u4ECD\u672A\u6740\u6B7B\uFF01\u4FDD\u7559 PID \u4F9B\u540E\u7EED forceStopAll \u91CD\u8BD5\u3002`);else this.pids.delete(w)}catch{}d1.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var c7=new I7;function E4(_,w){return c7.run(_,w)}function d7(){if(H2!==void 0)return H2;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return H2=_==="1"||_==="true"||_==="yes",H2}var H2;var p7=()=>{};function i7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordResultToDb:_?.recordResultToDb??!1,logResult:_?.logResult,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,Y){if(Y!==void 0&&Y!==null&&typeof Y==="object"&&"value"in Y){let W=Y.value,G=_?.name||String(X);return Y.value=q_(W,G,w()),Y}let J=$,Q=X||{};if(typeof J==="function"){let W=_?.name||(Q?.name?String(Q.name):"anonymous");return q_(J,W,w())}return J}}function u(_,w){return i7({name:_,...w})}function q_(_,w,$){let X={recordParams:$?.recordParams??!0,recordResult:$?.recordResult??!0,recordResultToDb:$?.recordResultToDb??!1,logResult:$?.logResult,recordError:$?.recordError??!0,log:$?.log??!1,maxLogSize:$?.maxLogSize,paramFilter:$?.paramFilter,resultFilter:$?.resultFilter,flattenParamFilter:$?.flattenParamFilter??!1,errorIf:$?.errorIf},Y=X.log,J=()=>{if(X.maxLogSize!==void 0)return X.maxLogSize;let z=m1();return z!==void 0?z:500},Q=(z)=>{if(z===void 0)return;if(z===null)return null;let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(A){V=`[Object with circular reference: ${A instanceof Error?A.message:String(A)}]`}if(U>0&&V.length>U)return V.slice(0,U)+" [TRUNCATED]";try{return JSON.parse(V)}catch{return V}},W=(z)=>{if(z===void 0)return"undefined";if(z===null)return"null";let U=J(),V;try{V=typeof z==="string"?z:JSON.stringify(z,null,0).replace(/\n/g,"")}catch(A){V=`[Object with circular reference: ${A instanceof Error?A.message:String(A)}]`}return U>0&&V.length>U?V.slice(0,U)+" [TRUNCATED]":V},G=(z)=>{if(z===void 0)return;if(z===null)return null;if(typeof z==="string")return z;try{return JSON.parse(JSON.stringify(z))}catch(U){return`[Object with circular reference: ${U instanceof Error?U.message:String(U)}]`}},D="[TRACE]",q=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},H=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(d7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:q(()=>X.resultFilter(z));if(V&&typeof V==="object"&&!Array.isArray(V))return{value:V,store:!0}}if(X.recordResult===!1)return{value:void 0,store:!1};return{value:z,store:!0}},B=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,B);let V=U.stack?.split(`
|
|
316
|
+
`)||[];Error.stackTraceLimit=z;for(let A=1;A<V.length;A++){let R=V[A];if(R.includes("decorator.ts")||R.includes("decorator.js")||R.includes("logFn")||R.includes("getCallerLocation"))continue;let L=R.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||R.match(/at\s+(.+):(\d+):\d+/);if(L){let N=L[1];if(!N||N==="native")continue;return`${x1(N)}:${L[2]}`}}return""},O=(z,U,V)=>{if(!Y)return;let A=n("traced:"+w),L=`[TRACE] ${z==="enter"?">>>":z==="quit"?"<<<":"!!!"} ${w}`,N=V||B(),E=(b,C)=>{if(C!==void 0)A.info(`${L} ${b}: ${W(C)}`,{callerLocation:N});else A.info(`${L} ${b}`,{callerLocation:N})};if(z==="enter")E("enter",U);else if(z==="quit")E("quit",X.logResult??X.recordResult?U:void 0);else E("error",U)};return function(...z){let U=U0().getTracer("roy-tracer"),V={};if(X.recordParams!==!1)if(X.paramFilter){let L=q(()=>X.paramFilter(z));if(V.params=G(L),X.flattenParamFilter&&L&&typeof L==="object"&&!Array.isArray(L)){for(let[N,E]of Object.entries(L))if(!(N in V))V[N]=G(E)}}else V.params=G(z);let A=B(),R;try{R=U.startSpan(w,{attributes:V})}catch{}O("enter",z,A);try{let L=_.call(this,...z);if(L&&typeof L==="object"&&typeof L.then==="function")return L.then((N)=>{if(R){let E=X.resultFilter!==void 0,b=X.resultFilter?q(()=>X.resultFilter(N)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[P,g]of Object.entries(b))R.setAttribute(P,G(g));let C=H(N,{ran:E,value:b});if(C.store)R.setAttribute("result",JSON.stringify(G(C.value)));let K=X.errorIf?q(()=>X.errorIf(N)):void 0;if(K){let P=K instanceof Error?K:Error(String(K));R.setAttribute("error",P.message),R.end(void 0,P)}else R.end(C.store?C.value:void 0)}return O("quit",X.logResult??X.recordResult?N:void 0,A),N},(N)=>{if(R)R.setAttribute("error",String(N)),R.end(void 0,N instanceof Error?N:Error(String(N)));throw O("error",N.message,A),N});if(R){let N=X.resultFilter!==void 0,E=X.resultFilter?q(()=>X.resultFilter(L)):void 0;if(E&&typeof E==="object"&&!Array.isArray(E))for(let[K,P]of Object.entries(E))R.setAttribute(K,G(P));let b=H(L,{ran:N,value:E});if(b.store)R.setAttribute("result",JSON.stringify(G(b.value)));let C=X.errorIf?q(()=>X.errorIf(L)):void 0;if(C){let K=C instanceof Error?C:Error(String(C));R.setAttribute("error",K.message),R.end(void 0,K)}else R.end(b.store?b.value:void 0)}return O("quit",X.logResult??X.recordResult?L:void 0,A),L}catch(L){if(R)R.setAttribute("error",String(L)),R.end(void 0,L instanceof Error?L:Error(String(L)));throw O("error",L.message,A),L}}}var H_=r(()=>{c1(),a(),p7()});import{randomUUID as n7}from"crypto";H_();function r7(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}else return e("better-sqlite3")}function a7(_){let $=new(r7())(_);if(typeof $.run!=="function")$.run=function(X,...Y){if(Y.length>0)return this.prepare(X).run(...Y);else return this.exec(X)};return $}class i1{db;insertStmt;getByIdStmt;recentStmt;constructor(_){this.db=a7(_.dbPath);try{this.db.exec("PRAGMA journal_mode=WAL"),this.db.exec("PRAGMA synchronous=NORMAL"),this.db.exec("PRAGMA busy_timeout=5000")}catch{}this.db.exec(`CREATE TABLE IF NOT EXISTS event_store (
|
|
310
317
|
event_id TEXT PRIMARY KEY,
|
|
311
318
|
es_type TEXT NOT NULL,
|
|
312
319
|
sender_id TEXT NOT NULL,
|
|
@@ -321,7 +328,7 @@ Parameters:
|
|
|
321
328
|
FROM event_store
|
|
322
329
|
WHERE es_type = ? AND sender_id = ?
|
|
323
330
|
ORDER BY created_at DESC
|
|
324
|
-
LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${
|
|
331
|
+
LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${n7()}`,X=Date.now(),Y=JSON.stringify(_.metadata??{}),J=_.rawEvent===void 0?null:o7(_.rawEvent);return this.insertStmt.run($,w,_.senderId,_.text??null,Y,J,X),$}async getEventById(_){let w=this.getByIdStmt.get(_);if(!w)return null;return S4(w)}async getRecentEvents(_,w,$){return this.recentStmt.all(_,w,$).map((Y)=>S4(Y))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],i1.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],i1.prototype,"getEventById",null);function S4(_){let w;try{w=_.metadata?JSON.parse(_.metadata):{}}catch{w={}}let $;if(_.raw_event)try{$=JSON.parse(_.raw_event)}catch{$=null}else $=null;return{eventId:_.event_id,esType:_.es_type,senderId:_.sender_id,text:_.text??null,metadata:w,rawEvent:$,createdAt:typeof _.created_at==="bigint"?Number(_.created_at):_.created_at}}function o7(_){let w=new WeakSet;try{return JSON.stringify(_,($,X)=>{if(typeof X==="function")return"[Function]";if(X===void 0)return"[undefined]";if(X===null)return null;if(X instanceof Error)return`${X.name}: ${X.message}`;if(typeof X==="object"){if(w.has(X))return"[Circular]";w.add(X)}if(typeof X==="bigint")return X.toString();return X})}catch{return"{}"}}var s7=null;function P4(){return s7}var $_={BEFORE_CREATE:"task:before.create",AFTER_CREATE:"task:after.create",BEFORE_UPDATE:"task:before.update",AFTER_UPDATE:"task:after.update",BEFORE_DELETE:"task:before.delete",AFTER_DELETE:"task:after.delete",AFTER_COMPLETE:"task:after.complete",DELEGATE_BEFORE:"task:delegate:before",DELEGATE_AFTER:"task:delegate:after",OPERATION_BEFORE_CREATE:"task:operation:before.create",OPERATION_AFTER_CREATE:"task:operation:after.create"};var n1={default:`\u4F60\u662F {{agent_name}} \u63A5\u5F85\u667A\u80FD\u4F53\uFF08Receptionist Agent\uFF09\u2014\u2014 {{agent_name}} \u7CFB\u7EDF\u7684\u667A\u80FD\u5165\u53E3\u3002
|
|
325
332
|
|
|
326
333
|
## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
|
|
327
334
|
|
|
@@ -1128,7 +1135,7 @@ roy-agent <command> <subcmd> --help
|
|
|
1128
1135
|
| \`task_list\` | List tasks with optional filters for status/priority |
|
|
1129
1136
|
| \`task_complete\` | Mark a task as completed (progress=100, status=completed). Creates an operation record. |
|
|
1130
1137
|
| \`task_delete\` | Delete a task and all its operation records |
|
|
1131
|
-
| \`task_operation_create\` | Create operation records \u2014 **\u53CC\u7EF4\u5EA6**: milestone_* (\u72B6\u6001/\u91CC\u7A0B\u7891) + process_description (\u8FC7\u7A0B, 100-
|
|
1138
|
+
| \`task_operation_create\` | Create operation records \u2014 **\u53CC\u7EF4\u5EA6**: milestone_* (\u72B6\u6001/\u91CC\u7A0B\u7891) + process_description (\u8FC7\u7A0B, 100-500 \u5B57\u7B26) |
|
|
1132
1139
|
| \`task_operation_list\` | List operation records for a task |
|
|
1133
1140
|
|
|
1134
1141
|
### \u274C \u7981\u6B62\u4F7F\u7528\u7684\u5DE5\u5177\uFF08\u4F60\u4E0D\u80FD\u8C03\u7528\u4EE5\u4E0B\u5DE5\u5177\uFF09
|
|
@@ -1202,7 +1209,7 @@ Follow this lifecycle for every task:
|
|
|
1202
1209
|
\u2502 5. RECORD (task_operation_create) \u2014 **\u53CC\u7EF4\u5EA6\u5206\u5DE5** \u2502
|
|
1203
1210
|
\u2502 - **\u72B6\u6001/\u91CC\u7A0B\u7891\u7EF4\u5EA6**\uFF1A\u7528 milestone_type / milestone_title / \u2502
|
|
1204
1211
|
\u2502 milestone_description \u63CF\u8FF0"\u8FBE\u6210\u7684\u72B6\u6001/\u91CC\u7A0B\u7891"\u3002 \u2502
|
|
1205
|
-
\u2502 - **\u8FC7\u7A0B\u7EF4\u5EA6**\uFF1A\u7528 process_description\uFF08100-
|
|
1212
|
+
\u2502 - **\u8FC7\u7A0B\u7EF4\u5EA6**\uFF1A\u7528 process_description\uFF08100-500 \u5B57\u7B26\uFF09 \u2502
|
|
1206
1213
|
\u2502 \u7B80\u8981\u8BB0\u5F55"\u5982\u4F55\u8FBE\u5230"\u2014\u2014\u91C7\u53D6\u4E86\u4EC0\u4E48\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981\u3002 \u2502
|
|
1207
1214
|
\u2502 - \u26A0\uFE0F **\u4E0D\u8981\u628A action \u5F53\u72B6\u6001**\uFF0C\u4E5F\u4E0D\u8981\u8BA9 process_description \u4E0E \u2502
|
|
1208
1215
|
\u2502 milestone_description \u91CD\u590D\u3002 \u2502
|
|
@@ -1251,7 +1258,7 @@ When reusing an existing task, you MUST follow these rules:
|
|
|
1251
1258
|
|
|
1252
1259
|
#### \u7EF4\u5EA6 2\uFF1A\u8FC7\u7A0B\uFF08"\u5982\u4F55\u8FBE\u5230"\uFF09\u2014 \u53EF\u9009\u4F46\u63A8\u8350\u7EF4\u5EA6
|
|
1253
1260
|
\u4F7F\u7528 \`task_operation_create\` \u7684 \`process_description\` \u5B57\u6BB5\uFF1A
|
|
1254
|
-
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-
|
|
1261
|
+
- \u5B57\u7B26\u8303\u56F4\u786C\u7EA6\u675F 100-500 \u5B57\u7B26
|
|
1255
1262
|
- \u5185\u5BB9\uFF1A\u91C7\u53D6\u7684\u7B56\u7565 + \u5DE5\u5177\u6B65\u9AA4\u6982\u8981
|
|
1256
1263
|
- \u5B8C\u6574\u8FC7\u7A0B\u901A\u8FC7 sessionId \u56DE\u67E5 session
|
|
1257
1264
|
|
|
@@ -1857,7 +1864,7 @@ task_operation_create( \\
|
|
|
1857
1864
|
milestone_type="progress", \\
|
|
1858
1865
|
milestone_title="\u5EFA\u7ACB self-task \u8DDF\u8E2A (Task #$SELF_TASK_ID)", \\
|
|
1859
1866
|
milestone_description="\u4EFB\u52A1\u6574\u7406\u5F00\u59CB\uFF0C\u5EFA\u7ACB self-task \u8DDF\u8E2A\u672C\u6B21 reparent/upgrade \u64CD\u4F5C\u94FE", \\
|
|
1860
|
-
process_description="\u901A\u8FC7 task_create \u5EFA tracking task + task_operation_create \u7559\u75D5\u8D77\u6B65 100-
|
|
1867
|
+
process_description="\u901A\u8FC7 task_create \u5EFA tracking task + task_operation_create \u7559\u75D5\u8D77\u6B65 100-500 \u5B57\u7B26" \\
|
|
1861
1868
|
)
|
|
1862
1869
|
|
|
1863
1870
|
# 3. \u81EA\u6B64\u6240\u6709 reparent / \u5347\u7EA7 type \u64CD\u4F5C\u90FD\u5FC5\u987B task_update \u5173\u8054\u5230 $SELF_TASK_ID
|
|
@@ -2045,7 +2052,7 @@ task_operation_create({
|
|
|
2045
2052
|
- **milestone_type**: \`decision\`\uFF08"\u4E3A\u4EC0\u4E48\u6302\u8FD9\u91CC"\uFF09\u6216 \`milestone\`\uFF08"\u8FBE\u6210\u4E86\u4EC0\u4E48"\uFF09
|
|
2046
2053
|
- **milestone_title**: \u4E00\u53E5\u8BDD\u6807\u9898\uFF08\u5982 "Reparent #X \u2192 #Y\uFF08longterm \u951A\u70B9\uFF09"\uFF09
|
|
2047
2054
|
- **milestone_description**: \u8BE6\u7EC6\u63CF\u8FF0\uFF08\u51B3\u7B56\u4F9D\u636E\u3001\u5F3A\u5EA6\u3001\u9879\u76EE\u8DEF\u5F84\uFF09
|
|
2048
|
-
- **process_description**: 100-
|
|
2055
|
+
- **process_description**: 100-500 \u5B57\u7B26\u7B80\u8981\u8FC7\u7A0B
|
|
2049
2056
|
|
|
2050
2057
|
---
|
|
2051
2058
|
|
|
@@ -2058,8 +2065,8 @@ task_operation_create({
|
|
|
2058
2065
|
\u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
|
|
2059
2066
|
|
|
2060
2067
|
> \u2705 \u4EFB\u52A1\u6811\u5F62\u6001\u826F\u597D\uFF08root=N, depth=X, non_longterm_root=0, health_score=health\uFF09\u3002\u65E0\u9700\u64CD\u4F5C\u3002
|
|
2061
|
-
`},eV=d2["workflow-extract"];import K4 from"os";import z_ from"path";var B1="roy-agent";function c7(){let _=K4.homedir();try{let w=e("xdg-basedir");return{config:w.xdgConfig||z_.join(_,".config"),state:w.xdgState||z_.join(_,".local","state"),data:w.xdgData||z_.join(_,".local","share"),cache:w.xdgCache||z_.join(_,".cache")}}catch{return{config:z_.join(_,".config"),state:z_.join(_,".local","state"),data:z_.join(_,".local","share"),cache:z_.join(_,".cache")}}}function d7(){let _=K4.homedir(),w=c7();return{home:_,config:z_.join(w.config,B1),state:z_.join(w.state,B1),data:z_.join(w.data,B1),cache:z_.join(w.cache,B1)}}class N4{_paths;get paths(){if(!this._paths)this._paths=d7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return z_.join(this.paths[_],w)}reset(){this._paths=void 0}}var p7=new N4;function b4(_){return p7.getPath(_)}import*as pB from"fs/promises";import*as iB from"fs";import{join as tw}from"path";var X$=KX(g5(),1);a();V_();var __=n("agent:registry"),$$=A.object({name:A.string(),type:A.enum(["primary","sub","workflow"]),workflow:A.string().optional(),entryAgent:A.string().optional(),description:A.string().optional(),systemPromptRef:A.string().optional(),systemPrompt:A.string().optional(),model:A.string().optional(),maxIterations:A.number().optional(),maxErrorRetries:A.number().optional(),allowedTools:A.array(A.string()).optional(),deniedTools:A.array(A.string()).optional(),toolTimeout:A.number().optional(),toolRetries:A.number().optional(),doomLoopThreshold:A.number().optional(),filterHistory:A.boolean().optional()}).refine((_)=>_.type!=="workflow"||_.workflow&&_.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class M_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||iB,this.fsPromises=_.fsPromises||pB;let w=this.configComponent?.get?.("agent.configDir");if(w&&typeof w==="string"&&w.length>0)this.configDir=w;else if(_.baseDir)this.configDir=tw(_.baseDir,"agents");else this.configDir=tw(b4("data"),"agents");__.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=$$.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),__.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)__.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),__.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt(_){let w=this.agents.get(_);if(!w)return;let $=this.getActivePromptComponent();if(w.systemPromptRef)try{if($?.getPrompt){let Y=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(Y)return __.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return __.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return __.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return __.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${w.systemPromptRef}`,{error:X}),w.systemPrompt}return w.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt(_){let w=this.agents.get(_);if(!w)return;return w.systemPrompt}getWorkflowName(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.workflow}getEntryAgent(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let w={name:"workflow-runner",type:"sub",description:"Workflow runner \u2014 \u63A5\u53D7\u5E26 workflow_name\uFF08\u5FC5\u586B\uFF09\u7684\u59D4\u6258\uFF0C\u6216\u6307\u793A\u5176\u6309 search-first \u6D41\u7A0B\u81EA\u884C\u9009\u5B9A\uFF08workflow_tag_list + workflow_search + workflow_list + workflow_get\uFF09\uFF0C\u7136\u540E\u901A\u8FC7 workflow_run \u6267\u884C workflow\uFF1B\u652F\u6301 session resume \u548C stop\uFF1B\u5931\u8D25\u63A5\u7BA1\u7531 prompt \u63A8\u7406\u89E6\u53D1 (Task #2251)\u3002**\u8C03\u7528\u65B9\u5FC5\u987B\u5728 prompt \u4E2D\u660E\u786E\u6307\u5B9A workflow \u540D\uFF0C\u6216\u6307\u793A sub-agent \u81EA\u884C\u641C\u7D22\u9009\u62E9\uFF1B\u7981\u6B62\u76F2\u731C/\u7ED5\u8FC7/\u8DF3\u8FC7 schema \u9A8C\u8BC1** (Task #2486)\u3002",systemPromptRef:"workflow-runner",deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("workflow-runner",w)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let w={name:"task-organizer",type:"sub",description:"\u4EFB\u52A1\u6811\u6574\u7406\u5B50\u667A\u80FD\u4F53 \u2014 \u628A\u975E longterm \u7C7B\u578B\u7684\u6839\u4EFB\u52A1\u91CD\u65B0\u6302\u8F7D\u5230 longterm \u7236\u4EFB\u52A1\u4E0B\uFF0C\u6839\u4EFB\u52A1\u6536\u655B\u5230 10-20 \u4E2A\uFF1B\u7EF4\u62A4\u4EFB\u52A1\u6811\u5F62\u6001\u5065\u5EB7\uFF08re-parent / merge / archive / delete\uFF09\u3002Task #2348\u3002",systemPromptRef:"task-organizer",allowedTools:["task_create","task_get","task_list","task_update","task_delete","task_complete","task_tree","task_search","task_batch_archive","task_batch_delete","task_operation_create","task_operation_get","task_operation_list","task_operation_update","task_operation_delete"],deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("task-organizer",w)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let w={name:"json-extract",type:"sub",description:"JSON \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u5BF9\u8BDD\u5386\u53F2\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 JSON\uFF0C\u901A\u8FC7 workflow_submit_output \u5DE5\u5177\u63D0\u4EA4",systemPromptRef:"json-extract",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:5,filterHistory:!1};this.agents.set("json-extract",w)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let w={name:"workflow-extract",type:"sub",description:"Workflow \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 task \u7684\u5BF9\u8BDD\u5386\u53F2\u4E2D\u5206\u6790\u9700\u6C42\uFF0C\u8FED\u4EE3\u5F0F\u751F\u6210\u5E76\u9A8C\u8BC1 Workflow YAML",systemPromptRef:"workflow-extract",allowedTools:["workflow_get","workflow_list","workflow_add","workflow_validate"],deniedTools:[],maxIterations:10,filterHistory:!1};this.agents.set("workflow-extract",w)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let w={name:"workflow-creator",type:"sub",description:"Workflow \u6784\u5EFA\u5B50\u667A\u80FD\u4F53 \u2014 \u4E0E\u7528\u6237\u591A\u8F6E\u4EA4\u4E92\u5F0F\u534F\u4F5C\u8BBE\u8BA1\u3001\u9A8C\u8BC1\u5E76\u6CE8\u518C workflow",systemPromptRef:"workflow-creator",allowedTools:["workflow_list","workflow_get","workflow_search","workflow_tag_list","workflow_validate","workflow_add","bash","read_file","workflow_run","workflow_run_status"],deniedTools:["delegate_task","stop_task"],maxIterations:60};this.agents.set("workflow-creator",w)}registerCompactAgent(){if(this.agents.has("compact"))return;let w={name:"compact",type:"sub",description:"\u538B\u7F29\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 session \u7684\u5386\u53F2\u6D88\u606F\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 checkpoint JSON",systemPromptRef:"compact",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",w)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;let w={name:"compact-hint",type:"sub",description:"\u538B\u7F29\u63D0\u793A\u5B50\u667A\u80FD\u4F53 \u2014 \u5206\u6790\u7236 session \u5386\u53F2\uFF0C\u751F\u6210\u573A\u666F\u5316\u538B\u7F29\u6307\u5BFC\u63D0\u793A",systemPromptRef:"compact-hint",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact-hint",w)}registerRoyAgent(){if(this.agents.has("roy"))return;let w={name:"roy",type:"sub",description:"Roy \u2014 versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.",systemPromptRef:"roy",deniedTools:["delegate_task","stop_task"]};this.agents.set("roy",w)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch(_){return __.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return __.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let Y=tw(_,X.name);if(X.isDirectory())continue;if(!nB(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),D=this.parseAgentConfig(J,Y);if(D)this.agents.set(D.name,D),__.info(`[AgentRegistry] Loaded agent: ${D.name} from ${X.name}`),w++}catch(J){__.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}__.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){__.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=X$.default.parse(_),X=$$.safeParse($);if(!X.success)return __.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return __.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=$$.safeParse(_);if(!w.success)return __.error(`[AgentRegistry] Invalid agent config for "${_.name}": ${w.error.message}`),!1;await this.ensureConfigDir();let $=this.agentToYaml(_),X=tw(this.configDir,`${_.name}.yaml`);return await this.fsPromises.writeFile(X,$,"utf-8"),this.agents.set(_.name,_),__.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return __.error(`[AgentRegistry] Failed to save agent: ${_.name}`,{error:w}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),__.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml(_){let w={name:_.name,type:_.type,..._.description!==void 0?{description:_.description}:{},..._.systemPromptRef!==void 0?{systemPromptRef:_.systemPromptRef}:{},..._.systemPrompt!==void 0?{systemPrompt:_.systemPrompt}:{},..._.model!==void 0?{model:_.model}:{},..._.maxIterations!==void 0?{maxIterations:_.maxIterations}:{},..._.maxErrorRetries!==void 0?{maxErrorRetries:_.maxErrorRetries}:{},..._.allowedTools!==void 0?{allowedTools:_.allowedTools}:{},..._.deniedTools!==void 0?{deniedTools:_.deniedTools}:{},..._.toolTimeout!==void 0?{toolTimeout:_.toolTimeout}:{},..._.toolRetries!==void 0?{toolRetries:_.toolRetries}:{},..._.doomLoopThreshold!==void 0?{doomLoopThreshold:_.doomLoopThreshold}:{},..._.filterHistory!==void 0?{filterHistory:_.filterHistory}:{},..._.workflow!==void 0?{workflow:_.workflow}:{},..._.entryAgent!==void 0?{entryAgent:_.entryAgent}:{}};return X$.default.stringify(w).trimEnd()+`
|
|
2062
|
-
`}async deleteAgent(_){if(!this.agents.get(_))return __.warn(`[AgentRegistry] Agent not found: ${_}`),!1;try{let $=
|
|
2068
|
+
`},FO=n1["workflow-extract"];import Z4 from"os";import O_ from"path";var U2="roy-agent";function t7(){let _=Z4.homedir();try{let w=e("xdg-basedir");return{config:w.xdgConfig||O_.join(_,".config"),state:w.xdgState||O_.join(_,".local","state"),data:w.xdgData||O_.join(_,".local","share"),cache:w.xdgCache||O_.join(_,".cache")}}catch{return{config:O_.join(_,".config"),state:O_.join(_,".local","state"),data:O_.join(_,".local","share"),cache:O_.join(_,".cache")}}}function e7(){let _=Z4.homedir(),w=t7();return{home:_,config:O_.join(w.config,U2),state:O_.join(w.state,U2),data:O_.join(w.data,U2),cache:O_.join(w.cache,U2)}}class C4{_paths;get paths(){if(!this._paths)this._paths=e7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return O_.join(this.paths[_],w)}reset(){this._paths=void 0}}var _Y=new C4;function I4(_){return _Y.getPath(_)}import*as _U from"fs/promises";import*as wU from"fs";import{join as ew}from"path";var Q$=I9(l5(),1);a();H_();var __=n("agent:registry"),J$=M.object({name:M.string(),type:M.enum(["primary","sub","workflow"]),workflow:M.string().optional(),entryAgent:M.string().optional(),description:M.string().optional(),systemPromptRef:M.string().optional(),systemPrompt:M.string().optional(),model:M.string().optional(),maxIterations:M.number().optional(),maxErrorRetries:M.number().optional(),allowedTools:M.array(M.string()).optional(),deniedTools:M.array(M.string()).optional(),toolTimeout:M.number().optional(),toolRetries:M.number().optional(),doomLoopThreshold:M.number().optional(),filterHistory:M.boolean().optional()}).refine((_)=>_.type!=="workflow"||_.workflow&&_.workflow.length>0,{message:"workflow is required when type is 'workflow'"});class R_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||wU,this.fsPromises=_.fsPromises||_U;let w=this.configComponent?.get?.("agent.configDir");if(w&&typeof w==="string"&&w.length>0)this.configDir=w;else if(_.baseDir)this.configDir=ew(_.baseDir,"agents");else this.configDir=ew(I4("data"),"agents");__.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=J$.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),__.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)__.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),__.info("[AgentRegistry] Cleared all agents")}async getSystemPrompt(_){let w=this.agents.get(_);if(!w)return;let $=this.getActivePromptComponent();if(w.systemPromptRef)try{if($?.getPrompt){let Y=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(Y)return __.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return __.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return __.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return __.warn(`[AgentRegistry] Failed to resolve systemPromptRef: ${w.systemPromptRef}`,{error:X}),w.systemPrompt}return w.systemPrompt}getActivePromptComponent(){return this.resolvePromptComponent?.()??this.promptComponent}getInlineSystemPrompt(_){let w=this.agents.get(_);if(!w)return;return w.systemPrompt}getWorkflowName(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.workflow}getEntryAgent(_){let w=this.agents.get(_);if(!w||w.type!=="workflow")return;return w.entryAgent}registerWorkflowRunner(){if(this.agents.has("workflow-runner"))return;let w={name:"workflow-runner",type:"sub",description:"Workflow runner \u2014 \u63A5\u53D7\u5E26 workflow_name\uFF08\u5FC5\u586B\uFF09\u7684\u59D4\u6258\uFF0C\u6216\u6307\u793A\u5176\u6309 search-first \u6D41\u7A0B\u81EA\u884C\u9009\u5B9A\uFF08workflow_tag_list + workflow_search + workflow_list + workflow_get\uFF09\uFF0C\u7136\u540E\u901A\u8FC7 workflow_run \u6267\u884C workflow\uFF1B\u652F\u6301 session resume \u548C stop\uFF1B\u5931\u8D25\u63A5\u7BA1\u7531 prompt \u63A8\u7406\u89E6\u53D1 (Task #2251)\u3002**\u8C03\u7528\u65B9\u5FC5\u987B\u5728 prompt \u4E2D\u660E\u786E\u6307\u5B9A workflow \u540D\uFF0C\u6216\u6307\u793A sub-agent \u81EA\u884C\u641C\u7D22\u9009\u62E9\uFF1B\u7981\u6B62\u76F2\u731C/\u7ED5\u8FC7/\u8DF3\u8FC7 schema \u9A8C\u8BC1** (Task #2486)\u3002",systemPromptRef:"workflow-runner",deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("workflow-runner",w)}registerTaskOrganizer(){if(this.agents.has("task-organizer"))return;let w={name:"task-organizer",type:"sub",description:"\u4EFB\u52A1\u6811\u6574\u7406\u5B50\u667A\u80FD\u4F53 \u2014 \u628A\u975E longterm \u7C7B\u578B\u7684\u6839\u4EFB\u52A1\u91CD\u65B0\u6302\u8F7D\u5230 longterm \u7236\u4EFB\u52A1\u4E0B\uFF0C\u6839\u4EFB\u52A1\u6536\u655B\u5230 10-20 \u4E2A\uFF1B\u7EF4\u62A4\u4EFB\u52A1\u6811\u5F62\u6001\u5065\u5EB7\uFF08re-parent / merge / archive / delete\uFF09\u3002Task #2348\u3002",systemPromptRef:"task-organizer",allowedTools:["task_create","task_get","task_list","task_update","task_delete","task_complete","task_tree","task_search","task_batch_archive","task_batch_delete","task_operation_create","task_operation_get","task_operation_list","task_operation_update","task_operation_delete"],deniedTools:["delegate_task","stop_task"],maxIterations:30};this.agents.set("task-organizer",w)}registerJsonExtractAgent(){if(this.agents.has("json-extract"))return;let w={name:"json-extract",type:"sub",description:"JSON \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u5BF9\u8BDD\u5386\u53F2\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 JSON\uFF0C\u901A\u8FC7 workflow_submit_output \u5DE5\u5177\u63D0\u4EA4",systemPromptRef:"json-extract",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:5,filterHistory:!1};this.agents.set("json-extract",w)}registerWorkflowExtractAgent(){if(this.agents.has("workflow-extract"))return;let w={name:"workflow-extract",type:"sub",description:"Workflow \u63D0\u53D6\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 task \u7684\u5BF9\u8BDD\u5386\u53F2\u4E2D\u5206\u6790\u9700\u6C42\uFF0C\u8FED\u4EE3\u5F0F\u751F\u6210\u5E76\u9A8C\u8BC1 Workflow YAML",systemPromptRef:"workflow-extract",allowedTools:["workflow_get","workflow_list","workflow_add","workflow_validate"],deniedTools:[],maxIterations:10,filterHistory:!1};this.agents.set("workflow-extract",w)}registerWorkflowCreator(){if(this.agents.has("workflow-creator"))return;let w={name:"workflow-creator",type:"sub",description:"Workflow \u6784\u5EFA\u5B50\u667A\u80FD\u4F53 \u2014 \u4E0E\u7528\u6237\u591A\u8F6E\u4EA4\u4E92\u5F0F\u534F\u4F5C\u8BBE\u8BA1\u3001\u9A8C\u8BC1\u5E76\u6CE8\u518C workflow",systemPromptRef:"workflow-creator",allowedTools:["workflow_list","workflow_get","workflow_search","workflow_tag_list","workflow_validate","workflow_add","bash","read_file","workflow_run","workflow_run_status"],deniedTools:["delegate_task","stop_task"],maxIterations:60};this.agents.set("workflow-creator",w)}registerCompactAgent(){if(this.agents.has("compact"))return;let w={name:"compact",type:"sub",description:"\u538B\u7F29\u5B50\u667A\u80FD\u4F53 \u2014 \u4ECE\u7236 session \u7684\u5386\u53F2\u6D88\u606F\u4E2D\u63D0\u53D6\u7ED3\u6784\u5316 checkpoint JSON",systemPromptRef:"compact",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact",w)}registerCompactHintAgent(){if(this.agents.has("compact-hint"))return;let w={name:"compact-hint",type:"sub",description:"\u538B\u7F29\u63D0\u793A\u5B50\u667A\u80FD\u4F53 \u2014 \u5206\u6790\u7236 session \u5386\u53F2\uFF0C\u751F\u6210\u573A\u666F\u5316\u538B\u7F29\u6307\u5BFC\u63D0\u793A",systemPromptRef:"compact-hint",allowedTools:["workflow_submit_output"],deniedTools:[],maxIterations:3,filterHistory:!1};this.agents.set("compact-hint",w)}registerRoyAgent(){if(this.agents.has("roy"))return;let w={name:"roy",type:"sub",description:"Roy \u2014 versatile AI assistant inspired by Jarvis. Built-in general-purpose subagent for coding, research, planning, and complex multi-step tasks. Always available without `agent add roy`.",systemPromptRef:"roy",deniedTools:["delegate_task","stop_task"]};this.agents.set("roy",w)}async load(){try{return await this.loadFromDirectory(this.configDir)}catch(_){return __.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return __.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let Y=ew(_,X.name);if(X.isDirectory())continue;if(!$U(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),Q=this.parseAgentConfig(J,Y);if(Q)this.agents.set(Q.name,Q),__.info(`[AgentRegistry] Loaded agent: ${Q.name} from ${X.name}`),w++}catch(J){__.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}__.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){__.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=Q$.default.parse(_),X=J$.safeParse($);if(!X.success)return __.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return __.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=J$.safeParse(_);if(!w.success)return __.error(`[AgentRegistry] Invalid agent config for "${_.name}": ${w.error.message}`),!1;await this.ensureConfigDir();let $=this.agentToYaml(_),X=ew(this.configDir,`${_.name}.yaml`);return await this.fsPromises.writeFile(X,$,"utf-8"),this.agents.set(_.name,_),__.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return __.error(`[AgentRegistry] Failed to save agent: ${_.name}`,{error:w}),!1}}async ensureConfigDir(){if(!this.fs.existsSync(this.configDir))await this.fsPromises.mkdir(this.configDir,{recursive:!0}),__.debug(`[AgentRegistry] Created config directory: ${this.configDir}`)}agentToYaml(_){let w={name:_.name,type:_.type,..._.description!==void 0?{description:_.description}:{},..._.systemPromptRef!==void 0?{systemPromptRef:_.systemPromptRef}:{},..._.systemPrompt!==void 0?{systemPrompt:_.systemPrompt}:{},..._.model!==void 0?{model:_.model}:{},..._.maxIterations!==void 0?{maxIterations:_.maxIterations}:{},..._.maxErrorRetries!==void 0?{maxErrorRetries:_.maxErrorRetries}:{},..._.allowedTools!==void 0?{allowedTools:_.allowedTools}:{},..._.deniedTools!==void 0?{deniedTools:_.deniedTools}:{},..._.toolTimeout!==void 0?{toolTimeout:_.toolTimeout}:{},..._.toolRetries!==void 0?{toolRetries:_.toolRetries}:{},..._.doomLoopThreshold!==void 0?{doomLoopThreshold:_.doomLoopThreshold}:{},..._.filterHistory!==void 0?{filterHistory:_.filterHistory}:{},..._.workflow!==void 0?{workflow:_.workflow}:{},..._.entryAgent!==void 0?{entryAgent:_.entryAgent}:{}};return Q$.default.stringify(w).trimEnd()+`
|
|
2069
|
+
`}async deleteAgent(_){if(!this.agents.get(_))return __.warn(`[AgentRegistry] Agent not found: ${_}`),!1;try{let $=ew(this.configDir,`${_}.yaml`);if(this.fs.existsSync($))await this.fsPromises.unlink($),__.info(`[AgentRegistry] Deleted agent file: ${$}`);return this.agents.delete(_),!0}catch($){return __.error(`[AgentRegistry] Failed to delete agent: ${_}`,{error:$}),!1}}exportAgents(_={}){let w=this.list();if(_.format==="json")return w;return w}exportAgentsAsJson(){return JSON.stringify(this.list(),null,2)}size(){return this.agents.size}configDirExists(){return this.fs.existsSync(this.configDir)}getAgentFilePath(_){return ew(this.configDir,`${_}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],R_.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],R_.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],R_.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],R_.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],R_.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],R_.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],R_.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],R_.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],R_.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],R_.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],R_.prototype,"loadFromDirectory",null);function $U(_){return _.endsWith(".yaml")||_.endsWith(".yml")}var W$=`You are a subagent created by the main agent to handle a specific task.
|
|
2063
2070
|
|
|
2064
2071
|
## Your Role
|
|
2065
2072
|
- You were created to handle: {task_description}
|
|
@@ -2076,14 +2083,14 @@ task_operation_create({
|
|
|
2076
2083
|
## Execution
|
|
2077
2084
|
- Use the available tools to complete the task
|
|
2078
2085
|
- If you need more information, ask the main agent through the result
|
|
2079
|
-
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as
|
|
2086
|
+
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as XU}from"async_hooks";var YU=new XU;function G$(_,w){return YU.run(_,w)}import{AsyncLocalStorage as JU}from"async_hooks";var D$=()=>{};function _0(){return y0.getStore()}function X1(){return y0.getStore()||{}}function v0(){return y0.getStore()?.agentContext?.currentTaskId}function c5(_){return typeof _==="number"&&Number.isInteger(_)&&_>0?_:void 0}var d5,y0,QU,x0,Ww=r(()=>{a(),H_(),D$(),d5=n("env:context:env-context"),y0=new JU,QU=q_(function(w,$){return c5(w?.metadata?.parentTaskId)??c5($?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:(_)=>({parentTaskId:_??null})}),x0=q_(function(w){let $=v0(),X=y0.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=w}d5.info(`[setCurrentTaskId] taskId=${w??"undefined"} (was: ${$??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var Y1=r(()=>{Ww(),D$()});class J1{_hooks=new Map;componentName;componentVersion;defaultPriority;constructor(_={}){this.componentName=_.componentName??"unknown",this.componentVersion=_.componentVersion??"0.0.0",this.defaultPriority=_.defaultPriority??0}register(_,w){this.getOrCreateHooks(_).push(w)}registerMany(_,w){this.getOrCreateHooks(_).push(...w)}unregister(_,w){let $=this._hooks.get(_);if(!$)return!1;let X=$.findIndex((Y)=>Y.name===w);if(X===-1)return!1;return $.splice(X,1),!0}unregisterAll(_){this._hooks.delete(_)}async execute(_,w,$={}){let X=this._hooks.get(_),Y=process.env.ROY_HOOK_DEBUG==="1";if(Y)console.error(`[DEBUG hook-manager.execute] hookPoint=${_}, hooksCount=${X?.length??0}`);if(!X||X.length===0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EARLY RETURN (no hooks registered for ${_})`);return}let J=_0();if(Y){if(console.error(`[DEBUG hook-manager.execute] envContext=${J?"present":"absent"}`),J)console.error(`[DEBUG hook-manager.execute] envContext.pluginEnabled=${JSON.stringify(J.pluginEnabled)}`),console.error(`[DEBUG hook-manager.execute] envContext.sourceId=${J.sourceId}`)}if(J){if($.envContext=J,!$.pluginEnabled&&J.pluginEnabled)$.pluginEnabled=J.pluginEnabled}let Q=this.sortHooks(X),W=this.createContext(_,w,$,"before"),G=$.pluginEnabled||{};if(Y){console.error(`[DEBUG hook-manager.execute] final pluginEnabled=${JSON.stringify(G)}`),console.error(`[DEBUG hook-manager.execute] sortedHooks=${Q.length}:`);for(let D of Q)console.error(`[DEBUG hook-manager.execute] - name=${D.name} pluginName=${D.pluginName} sourceId=${D.sourceId}`)}for(let D of Q){if(D.pluginName&&D.sourceId){let q=`${D.sourceId}:${D.pluginName}`,H=G[q];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${D.name} (${q}) enabled=${H}`);if(H!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${q}] !== true, got ${JSON.stringify(H)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${D.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${D.name}`);await this.safeExecute(D,W)}}async executeAndCollect(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return[];let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),Q=[];for(let W of Y){let G=await this.safeExecuteAndReturn(W,J);if(G!==void 0)Q.push(G)}return Q}count(_){return this._hooks.get(_)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks(_){return this.count(_)>0}setComponentInfo(_,w){this.componentName=_,this.componentVersion=w}get hooks(){return this._hooks}async executeWithIntervention(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return{stopped:!1,results:[]};let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),Q=[],W=!1,G;for(let D of Y){if(W)break;let q=await this.safeExecuteAndReturn(D,J);if(Q.push(q),q&&typeof q==="object"&&"stopped"in q){let H=q;if(H.stopped)W=!0,G=H.action}}return{stopped:W,action:G,results:Q}}getOrCreateHooks(_){let w=this._hooks.get(_);if(!w)w=[],this._hooks.set(_,w);return w}sortHooks(_){return[..._].sort((w,$)=>{let X=w.priority??this.defaultPriority,Y=$.priority??this.defaultPriority;return X-Y})}createContext(_,w,$,X){return{component:{name:this.componentName,version:this.componentVersion},data:w,metadata:$,phase:X,hookPoint:_}}async safeExecute(_,w){try{let $=_.execute(w);if($&&typeof $==="object"&&typeof $.then==="function")await $}catch($){console.error(`Hook "${_.name}" failed:`,$)}}async safeExecuteAndReturn(_,w){try{return await _.execute(w)}catch($){console.error(`Hook "${_.name}" failed:`,$);return}}}var q$=r(()=>{Y1()});function WU(){let _=P_.register.bind(P_);P_.register=function(w,$){_(w,$);let X=p5[w];if(X)_(X,$)}}var P_,GU,DU,qU,p5,w0=r(()=>{q$(),P_=new J1,GU={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"},DU={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},qU={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"},p5={"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"},WU()});a();H_();Y1();function BU(_,w){if(z$(_))return!0;return w?.hasAgent(_)??!1}async function HU(_,w={}){let X=(w.getBuiltIn??z$)(_),Y=w.registry?.get(_);if(!X&&!Y)return;if(Y)return UU(_,Y,X,w.registry);return{subagentType:_,description:X.description,basePrompt:X.promptOverride||W$,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function UU(_,w,$,X){let Y=X?await X.getSystemPrompt(_):w.systemPrompt;return{subagentType:_,description:w.description||$?.description||"Custom agent",basePrompt:Y||$?.promptOverride||W$,allowedTools:w.allowedTools??$?.allowedTools,deniedTools:w.deniedTools??$?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function zU(_){return`
|
|
2080
2087
|
## Agent Selection Guide
|
|
2081
2088
|
|
|
2082
2089
|
- Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
|
|
2083
2090
|
${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
|
|
2084
|
-
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function
|
|
2085
|
-
`)+J}_0();var WU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function GU(_){let w=_;for(let $ of WU)w=w.replace($,"<redacted>");return w}function QU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function x5(_,w){return QU(GU(_),w)}class q${maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor(_={}){this.maxEntries=_.maxEntries??500,this.ttlMs=_.ttlMs??86400000,this.maxDescriptionChars=_.maxDescriptionChars??240}record(_,w={}){let $=new Date().toISOString(),X=this.toRecord(_,w,$);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update(_,w){let $=this.records.get(_.id);if(!$)return;let X=new Date().toISOString();this.records.delete(_.id);let Y={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove(_){let w=this.records.get(_);if(!w)return!1;if(this.records.delete(_),w.parentTaskId!==void 0){let $=this.childrenIndex.get(w.parentTaskId);if($?.delete(_),$&&$.size===0)this.childrenIndex.delete(w.parentTaskId)}return!0}getById(_){let w=this.records.get(_);if(!w)return;if(Date.now()-Date.parse(w.updatedAt)>this.ttlMs){this.remove(_);return}return w}peekById(_){return this.records.get(_)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent(_={}){let w=_.limit??10,$=_.statuses,X=new Set(_.excludeIds??[]),Y=_.excludeAncestorOf??_.excludeSelfOrDescendant,J=Y?this.collectSubtree(Y):new Set,D=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,W=Date.now(),G=new Set([...X,...J]),Q=[];for(let q of this.records.values()){if(W-Date.parse(q.updatedAt)>this.ttlMs)continue;if(D>0&&Date.parse(q.updatedAt)<D)continue;if(G.has(q.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&q.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&q.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&q.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(q.status))continue}else if(q.status==="archived")continue;Q.push(q)}if(_.activeChildFirst){let q=new Map;for(let H of Q)q.set(H.taskId,this.hasActiveChild(H.taskId));Q.sort((H,B)=>{let O=q.get(H.taskId)?1:0,z=q.get(B.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(U!==0)return U;return B.taskId-H.taskId})}else Q.sort((q,H)=>{let B=Date.parse(H.updatedAt)-Date.parse(q.updatedAt);if(B!==0)return B;return H.taskId-q.taskId});return Q.slice(0,w)}getSubtreeSummary(_,w={}){let $=w.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has(_)&&!this.childrenIndex.has(_))return X;let Y=this.childrenIndex.get(_),J=Y?Array.from(Y):[],D=J.length>0?1:0;X.maxDepth=D;let W=J;while(W.length>0){let G=[];for(let Q of W){let q=this.records.get(Q);if(!q)continue;if(!$&&q.status==="archived")continue;if(X.descendantCount++,q.status==="active")X.activeCount++;else if(q.status==="completed")X.completedCount++;let H=this.childrenIndex.get(Q);if(H&&H.size>0)for(let B of H)G.push(B)}if(G.length>0)D++,X.maxDepth=D;W=G}return X}hasActiveChild(_){let w=this.childrenIndex.get(_);if(!w)return!1;for(let $ of w){let X=this.records.get($);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord(_,w,$){let X=this.safeParseContext(_.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:x5(_.description||"",this.maxDescriptionChars),goals:x5(_.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:_.tags??[],status:_.status,priority:_.priority,type:_.type,parentTaskId:_.parent_task_id,source:w,createdAt:_.createdAt||$,updatedAt:_.updatedAt||$,operationCount:0,project_path:_.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext(_){if(!_||!_.trim())return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}pickString(_,w){if(!_)return;let $=_[w];return typeof $==="string"?$:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>this.stripSensitiveKeys(X));if(typeof _!=="object")return _;let w={},$=q$.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((D)=>J.includes(D)))continue;w[X]=this.stripSensitiveKeys(Y)}return w}upsert(_){this.records.set(_.taskId,_)}indexParentChild(_){if(_.parentTaskId===void 0||_.parentTaskId===null)return;let w=_.parentTaskId,$=this.childrenIndex.get(w);if(!$)$=new Set,this.childrenIndex.set(w,$);$.add(_.taskId)}collectSubtree(_){let w=new Set([_]),$=[_];while($.length>0){let X=$.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let J of Y)if(!w.has(J))w.add(J),$.push(J)}return w}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let _=this.records.size-this.maxEntries,w=Array.from(this.records.keys()).slice(0,_);for(let $ of w)this.remove($)}}a();var J2=n("registry-hook-installer");function qU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,J=$.priority??100,D=!1,W=(U,V)=>{try{w.record(U,V)}catch(M){J2.warn(`[registry-hook-installer] record failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(M){J2.warn(`[registry-hook-installer] update failed for task #${U.id}: ${M instanceof Error?M.message:String(M)}`)}},Q=(U)=>{try{w.remove(U)}catch(V){J2.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},q=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),H={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)W(V.task,q())}},B={name:`${Y}:after-update`,priority:J,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,q());else W(V.task,q())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,q())}},z={name:`${Y}:after-delete`,priority:J,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")Q(V.id)}};return _.registerHook($_.AFTER_CREATE,H),_.registerHook($_.AFTER_UPDATE,B),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(D)return;D=!0,_.unregisterHook($_.AFTER_CREATE,H.name),_.unregisterHook($_.AFTER_UPDATE,B.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),J2.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var G$=n("task-reuse-registry"),HU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},m5=new WeakMap;function BU(_){let w=m5.get(_);if(w)return w.registry;let $=new q$(HU),X={uninstall:()=>{}};try{let J=_.getComponent?.("task");if(J?.registerHook)X=qU(J,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),G$.debug("[task-reuse-registry] hook installed");else G$.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){G$.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return m5.set(_,Y),$}var UU=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b/g,/\bxox[abprs]-[A-Za-z0-9-]{8,}\b/g,/\bghp_[A-Za-z0-9]{16,}\b/g,/\bgithub_pat_[A-Za-z0-9_]{16,}\b/g,/\bBearer\s+[A-Za-z0-9._\-+/=]{12,}\b/g,/\bAKIA[0-9A-Z]{16}\b/g];function zU(_){let w=_;for(let $ of UU)w=w.replace($,"<redacted>");return w}function u5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function VU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,Y=_.heading??"Recent task context (reuse candidates)",J=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(J.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let D=[];D.push(`## ${Y}`),D.push(""),D.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),D.push("");for(let G of J){if(D.push(`### Task #${G.taskId}: ${G.title}`),D.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)D.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)D.push(`- Created by: ${G.source.subagentType}`);if(D.push(`- Updated: ${G.updatedAt}`),G.project_path)D.push(`- Project: ${G.project_path}`);if(G.worktree_path)D.push(`- Worktree: ${G.worktree_path}`);if(G.branch)D.push(`- Branch: ${G.branch}`);if(G.parentBranch)D.push(`- Parent branch: ${G.parentBranch}`);let Q;try{Q=_.registry.getSubtreeSummary(G.taskId)}catch{Q=void 0}if(Q&&Q.descendantCount>0)D.push(`- Children: ${Q.descendantCount} (active: ${Q.activeCount}, completed: ${Q.completedCount}, max depth: ${Q.maxDepth})`);let q=Q!==void 0&&Q.activeCount>0;if(G.status==="completed"&&q)D.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let H=zU(u5(G.description,X));if(H)D.push(`- Description: ${H}`);if(G.tags&&G.tags.length>0)D.push(`- Tags: ${G.tags.join(", ")}`);D.push("")}D.push("---"),D.push(""),D.push("### Reuse instructions"),D.push(""),D.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),D.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),D.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),D.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),D.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),D.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),D.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),D.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),D.push(""),D.push("### Decision matrix \u2014 three legal paths"),D.push(""),D.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),D.push("remains the default, but the matrix adds two new paths for independent work."),D.push(""),D.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),D.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),D.push("append description/goals. Do **not** create a new task id."),D.push(""),D.push("```"),D.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),D.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),D.push(' milestone_title: "Reopened for <new-scope>",'),D.push(' milestone_description: "<why this is the same work>" })'),D.push("```"),D.push(""),D.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),D.push("distinct: an independent bug fix, optimization, parallel delivery or"),D.push("independent acceptance item under the same feature. Create a child task so"),D.push("the audit trail is preserved. Always pair with an audit operation."),D.push(""),D.push("```");for(let G of J){let Q=G.project_path??"<project_path>";D.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${Q}", context=<inherit or override>)`);break}D.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),D.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),D.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),D.push("```"),D.push(""),D.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),D.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),D.push("should stay \u2264 ~10 to keep the tree readable."),D.push(""),D.push("```"),D.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),D.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),D.push(' milestone_title: "New root: <topic>",'),D.push(' milestone_description: "<why this is not a child of any existing task>" })'),D.push("```"),D.push(""),D.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),D.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),D.push("chosen. Use the appropriate `milestone_type`:"),D.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),D.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),D.push(" - new root \u2192 `create` (then `progress` per phase)"),D.push(""),D.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),D.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),D.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),D.push("tokens, secrets) are stripped automatically. Use the helper:"),D.push(""),D.push("```"),D.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),D.push("```"),D.push("");let W=D.join(`
|
|
2086
|
-
`);if(W.length>$)W=
|
|
2091
|
+
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function VU(_){let w=H$.map((Q)=>`- ${Q.id}: ${Q.description}`),X=(_?.list()??[]).filter((Q)=>!H$.some((W)=>W.id===Q.name)).map((Q)=>{if(Q.type==="workflow"){let W=Q.workflow?` (workflow: ${Q.workflow})`:"";return`- ${Q.name}: ${Q.description||"Workflow agent"}${W}`}return`- ${Q.name}: ${Q.description||"Custom agent"}`}),Y=[...w,...X],J=zU({hasCustomAgents:X.length>0});return Y.join(`
|
|
2092
|
+
`)+J}w0();var OU=[/\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 MU(_){let w=_;for(let $ of OU)w=w.replace($,"<redacted>");return w}function AU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function i5(_,w){return AU(MU(_),w)}class U${maxEntries;ttlMs;maxDescriptionChars;records=new Map;childrenIndex=new Map;constructor(_={}){this.maxEntries=_.maxEntries??500,this.ttlMs=_.ttlMs??86400000,this.maxDescriptionChars=_.maxDescriptionChars??240}record(_,w={}){let $=new Date().toISOString(),X=this.toRecord(_,w,$);return this.upsert(X),this.indexParentChild(X),this.evictIfNeeded(),X}update(_,w){let $=this.records.get(_.id);if(!$)return;let X=new Date().toISOString();this.records.delete(_.id);let Y={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,Y),this.childrenIndex.delete(Y.taskId),this.indexParentChild(Y),this.evictIfNeeded(),Y}remove(_){let w=this.records.get(_);if(!w)return!1;if(this.records.delete(_),w.parentTaskId!==void 0){let $=this.childrenIndex.get(w.parentTaskId);if($?.delete(_),$&&$.size===0)this.childrenIndex.delete(w.parentTaskId)}return!0}getById(_){let w=this.records.get(_);if(!w)return;if(Date.now()-Date.parse(w.updatedAt)>this.ttlMs){this.remove(_);return}return w}peekById(_){return this.records.get(_)}clear(){this.records.clear(),this.childrenIndex.clear()}size(){return this.records.size}recent(_={}){let w=_.limit??10,$=_.statuses,X=new Set(_.excludeIds??[]),Y=_.excludeAncestorOf??_.excludeSelfOrDescendant,J=Y?this.collectSubtree(Y):new Set,Q=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,W=Date.now(),G=new Set([...X,...J]),D=[];for(let q of this.records.values()){if(W-Date.parse(q.updatedAt)>this.ttlMs)continue;if(Q>0&&Date.parse(q.updatedAt)<Q)continue;if(G.has(q.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&q.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&q.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&q.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(q.status))continue}else if(q.status==="archived")continue;D.push(q)}if(_.activeChildFirst){let q=new Map;for(let H of D)q.set(H.taskId,this.hasActiveChild(H.taskId));D.sort((H,B)=>{let O=q.get(H.taskId)?1:0,z=q.get(B.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(U!==0)return U;return B.taskId-H.taskId})}else D.sort((q,H)=>{let B=Date.parse(H.updatedAt)-Date.parse(q.updatedAt);if(B!==0)return B;return H.taskId-q.taskId});return D.slice(0,w)}getSubtreeSummary(_,w={}){let $=w.includeArchived===!0,X={descendantCount:0,activeCount:0,completedCount:0,maxDepth:0};if(!this.records.has(_)&&!this.childrenIndex.has(_))return X;let Y=this.childrenIndex.get(_),J=Y?Array.from(Y):[],Q=J.length>0?1:0;X.maxDepth=Q;let W=J;while(W.length>0){let G=[];for(let D of W){let q=this.records.get(D);if(!q)continue;if(!$&&q.status==="archived")continue;if(X.descendantCount++,q.status==="active")X.activeCount++;else if(q.status==="completed")X.completedCount++;let H=this.childrenIndex.get(D);if(H&&H.size>0)for(let B of H)G.push(B)}if(G.length>0)Q++,X.maxDepth=Q;W=G}return X}hasActiveChild(_){let w=this.childrenIndex.get(_);if(!w)return!1;for(let $ of w){let X=this.records.get($);if(!X)continue;if(X.status==="active"||X.status==="todo")return!0}return!1}toRecord(_,w,$){let X=this.safeParseContext(_.context),Y=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:i5(_.description||"",this.maxDescriptionChars),goals:i5(_.goals_and_expected_deliverables||"",this.maxDescriptionChars),tags:_.tags??[],status:_.status,priority:_.priority,type:_.type,parentTaskId:_.parent_task_id,source:w,createdAt:_.createdAt||$,updatedAt:_.updatedAt||$,operationCount:0,project_path:_.project_path,branch:this.pickString(Y,"branch"),worktree_path:this.pickString(Y,"worktree_path"),parentBranch:this.pickString(Y,"parent_branch"),context:Y}}safeParseContext(_){if(!_||!_.trim())return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}pickString(_,w){if(!_)return;let $=_[w];return typeof $==="string"?$:void 0}static STRIPPED_KEYS=["commit","token","secret","password","api_key"];stripSensitiveKeys(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map((X)=>this.stripSensitiveKeys(X));if(typeof _!=="object")return _;let w={},$=U$.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((Q)=>J.includes(Q)))continue;w[X]=this.stripSensitiveKeys(Y)}return w}upsert(_){this.records.set(_.taskId,_)}indexParentChild(_){if(_.parentTaskId===void 0||_.parentTaskId===null)return;let w=_.parentTaskId,$=this.childrenIndex.get(w);if(!$)$=new Set,this.childrenIndex.set(w,$);$.add(_.taskId)}collectSubtree(_){let w=new Set([_]),$=[_];while($.length>0){let X=$.shift(),Y=this.childrenIndex.get(X);if(!Y)continue;for(let J of Y)if(!w.has(J))w.add(J),$.push(J)}return w}evictIfNeeded(){if(this.records.size<=this.maxEntries)return;let _=this.records.size-this.maxEntries,w=Array.from(this.records.keys()).slice(0,_);for(let $ of w)this.remove($)}}a();var Q1=n("registry-hook-installer");function RU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,Y=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,J=$.priority??100,Q=!1,W=(U,V)=>{try{w.record(U,V)}catch(A){Q1.warn(`[registry-hook-installer] record failed for task #${U.id}: ${A instanceof Error?A.message:String(A)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(A){Q1.warn(`[registry-hook-installer] update failed for task #${U.id}: ${A instanceof Error?A.message:String(A)}`)}},D=(U)=>{try{w.remove(U)}catch(V){Q1.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},q=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),H={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)W(V.task,q())}},B={name:`${Y}:after-update`,priority:J,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,q());else W(V.task,q())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,q())}},z={name:`${Y}:after-delete`,priority:J,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")D(V.id)}};return _.registerHook($_.AFTER_CREATE,H),_.registerHook($_.AFTER_UPDATE,B),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(Q)return;Q=!0,_.unregisterHook($_.AFTER_CREATE,H.name),_.unregisterHook($_.AFTER_UPDATE,B.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),Q1.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var B$=n("task-reuse-registry"),fU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},n5=new WeakMap;function LU(_){let w=n5.get(_);if(w)return w.registry;let $=new U$(fU),X={uninstall:()=>{}};try{let J=_.getComponent?.("task");if(J?.registerHook)X=RU(J,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),B$.debug("[task-reuse-registry] hook installed");else B$.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){B$.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return n5.set(_,Y),$}var FU=[/\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 KU(_){let w=_;for(let $ of FU)w=w.replace($,"<redacted>");return w}function r5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function NU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,Y=_.heading??"Recent task context (reuse candidates)",J=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(J.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let Q=[];Q.push(`## ${Y}`),Q.push(""),Q.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),Q.push("");for(let G of J){if(Q.push(`### Task #${G.taskId}: ${G.title}`),Q.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)Q.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)Q.push(`- Created by: ${G.source.subagentType}`);if(Q.push(`- Updated: ${G.updatedAt}`),G.project_path)Q.push(`- Project: ${G.project_path}`);if(G.worktree_path)Q.push(`- Worktree: ${G.worktree_path}`);if(G.branch)Q.push(`- Branch: ${G.branch}`);if(G.parentBranch)Q.push(`- Parent branch: ${G.parentBranch}`);let D;try{D=_.registry.getSubtreeSummary(G.taskId)}catch{D=void 0}if(D&&D.descendantCount>0)Q.push(`- Children: ${D.descendantCount} (active: ${D.activeCount}, completed: ${D.completedCount}, max depth: ${D.maxDepth})`);let q=D!==void 0&&D.activeCount>0;if(G.status==="completed"&&q)Q.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let H=KU(r5(G.description,X));if(H)Q.push(`- Description: ${H}`);if(G.tags&&G.tags.length>0)Q.push(`- Tags: ${G.tags.join(", ")}`);Q.push("")}Q.push("---"),Q.push(""),Q.push("### Reuse instructions"),Q.push(""),Q.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),Q.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),Q.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),Q.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),Q.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),Q.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),Q.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),Q.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),Q.push(""),Q.push("### Decision matrix \u2014 three legal paths"),Q.push(""),Q.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),Q.push("remains the default, but the matrix adds two new paths for independent work."),Q.push(""),Q.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),Q.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),Q.push("append description/goals. Do **not** create a new task id."),Q.push(""),Q.push("```"),Q.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),Q.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),Q.push(' milestone_title: "Reopened for <new-scope>",'),Q.push(' milestone_description: "<why this is the same work>" })'),Q.push("```"),Q.push(""),Q.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),Q.push("distinct: an independent bug fix, optimization, parallel delivery or"),Q.push("independent acceptance item under the same feature. Create a child task so"),Q.push("the audit trail is preserved. Always pair with an audit operation."),Q.push(""),Q.push("```");for(let G of J){let D=G.project_path??"<project_path>";Q.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${D}", context=<inherit or override>)`);break}Q.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),Q.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),Q.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),Q.push("```"),Q.push(""),Q.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),Q.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),Q.push("should stay \u2264 ~10 to keep the tree readable."),Q.push(""),Q.push("```"),Q.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),Q.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),Q.push(' milestone_title: "New root: <topic>",'),Q.push(' milestone_description: "<why this is not a child of any existing task>" })'),Q.push("```"),Q.push(""),Q.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),Q.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),Q.push("chosen. Use the appropriate `milestone_type`:"),Q.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),Q.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),Q.push(" - new root \u2192 `create` (then `progress` per phase)"),Q.push(""),Q.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),Q.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),Q.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),Q.push("tokens, secrets) are stripped automatically. Use the helper:"),Q.push(""),Q.push("```"),Q.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),Q.push("```"),Q.push("");let W=Q.join(`
|
|
2093
|
+
`);if(W.length>$)W=r5(W,$);return{markdown:W,candidateIds:J.map((G)=>G.taskId),isEmpty:!1}}var y=n("task:delegate"),p_={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"},H$=[{id:"general",name:"general",mode:"subagent",description:"General-purpose agent for researching complex questions and executing multi-step tasks.",promptOverride:`You are a subagent created by the main agent to handle a specific task.
|
|
2087
2094
|
|
|
2088
2095
|
## Your Role
|
|
2089
2096
|
- You were created to handle: {task_description}
|
|
@@ -2134,7 +2141,7 @@ ${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
|
|
|
2134
2141
|
## Execution
|
|
2135
2142
|
- Use the available tools to complete the task
|
|
2136
2143
|
- If you need more information, ask the main agent through the result
|
|
2137
|
-
- Return a clear summary of what you did and the results`,deniedTools:["delegate_task","stop_task"]},{id:"explore",name:"explore",mode:"subagent",description:"Fast agent specialized for exploring codebases, finding files, and searching for patterns.",allowedTools:["read_file","glob","grep","bash"],deniedTools:["delegate_task","stop_task"]},{id:"roy",name:"Roy",mode:"subagent",description:"Versatile AI assistant inspired by Jarvis \u2014 intelligent, proactive, and capable. Use for general-purpose tasks, coding, research, and complex multi-step work. Always available (built-in) without `agent add roy`.",promptOverride:
|
|
2144
|
+
- 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:n1.roy,deniedTools:["delegate_task","stop_task"]}];function z$(_){return H$.find((w)=>w.id===_)}function bU(_,w,$,X,Y){let J=_.getRegistry?.();if(J){if(J.get(w)?.type==="workflow")return y.debug(`[delegate] Skipping registration for workflow agent: ${w}`),null}let Q=_.getAgent(w);if(!Q){let W={type:"sub",systemPrompt:$};if(X?.allowedTools&&X.allowedTools.length>0)W.allowedTools=X.allowedTools;if(Y.length>0)W.deniedTools=Y;Q=_.registerAgent(w,W),y.debug(`[delegate] Registered subagent: ${w}`)}return Q}var a5=M.object({description:M.string().describe("A short (3-5 words) description of the task"),prompt:M.string().describe("The task for the agent to perform"),subagent_type:M.string().describe("The type of specialized agent to use for this task").default("general"),timeout:M.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:M.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:M.array(M.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:M.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:M.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 jU(_){let{workflowName:w,originalPrompt:$,description:X}=_;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
|
|
2138
2145
|
|
|
2139
2146
|
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${w}**\u3002
|
|
2140
2147
|
\u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
|
|
@@ -2158,7 +2165,7 @@ ${$}
|
|
|
2158
2165
|
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2159
2166
|
|
|
2160
2167
|
\u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
|
|
2161
|
-
`}var MU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),D2=1800000,RU=1200000;class w_{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor(_){this.env=_}setWorkflowService(_){this.workflowService=_}attachWorkflowRun(_,w){if(!_||!w)return;let $=this.workflowRunRegistries.get(_);if(!$)$=new Set,this.workflowRunRegistries.set(_,$);$.add(w)}detachWorkflowRun(_,w){this.workflowRunRegistries.get(_)?.delete(w)}replaceWorkflowRun(_,w,$){if(!_)return;let X=this.workflowRunRegistries.get(_);if(!X)return;if(w)X.delete(w);if($)X.add($)}async propagateStopToWorkflowRuns(_,w){let $=this.workflowRunRegistries.get(_);if(!$||$.size===0)return{runIds:[],stopResults:[]};let X=Array.from($);h.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${_}`);let Y=[];for(let J of X){if(typeof this.workflowService?.stopRun!=="function"){h.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${J}`),Y.push({runId:J,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(J,w),Y.push({runId:J,success:!0})}catch(D){let W=D instanceof Error?D.message:String(D);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${W}`),Y.push({runId:J,success:!1,error:W})}}return $.clear(),{runIds:X,stopResults:Y}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let J=this.terminalTasks.keys().next().value;if(J!==void 0)this.terminalTasks.delete(J)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let Y=this.processRegistries.get(_);if(Y&&Y.size()>0)h.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${Y.size()}, reason=${w})`);h.debug(`[BackgroundTaskManager] finalizeTask taskId=${_} reason=${w}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let _=0;for(let[w,$]of this.processRegistries)if($.size()===0)this.processRegistries.delete(w),_++;return _}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent(_){try{if(w_.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${w_.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),w_.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??w_.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=I_((_)=>MU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return w_._detectWorkflowShortcutWrapped(_)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession(_){if(!_)return;try{let $=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.(_);return typeof $==="number"&&$>0?$:void 0}catch(w){h.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${_}: ${w instanceof Error?w.message:String(w)}`);return}}publishBackgroundEvent(_,w,$,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),h.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,Y){this.publishBackgroundEvent(_,w,$,X,Y)}static parseAskUserErrorFromMessage(_){let w=_ instanceof Error?_.message:String(_);if(_&&typeof _==="object"&&_.name==="AskUserError"&&_.query){let X=_;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:w}}let $="__ASK_USER_ERROR__:";if(w.includes($))try{let X=w.substring(w.indexOf($)+$.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:w}}catch(X){return h.warn("[BackgroundTaskManager] Failed to parse __ASK_USER_ERROR__ payload",{error:X instanceof Error?X.message:String(X)}),null}return null}async createTask(_){let{parentSessionId:w,description:$,prompt:X,subagentType:Y,timeout:J,similarTaskIds:D,existingSubSessionId:W,triggerEventId:G,model:Q,fallbackModel:q}=_,H=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,B=this.getSessionComponent();if(!B)throw Error("SessionComponent not found");if(!await B.get(w))throw Error(`Parent session not found: ${w}`);let z;if(W){let f=await B.get(W);if(!f)throw Error(`Sub session not found for resume: ${W}`);let Z=f?.metadata?.created_by;if(Z&&Z!=="subagent")h.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${Z}); reusing anyway`);z=f;try{let L=f?.metadata??{};await B.update(W,{metadata:{...L,reused_sub_session:!0,reused_at:Date.now()}})}catch(L){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:L instanceof Error?L.message:String(L)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${H}`)}else{let f={subagent_type:Y,created_by:"subagent",task_description:$},Z=ew();if(Z){if(Z.messageId)f.messageId=Z.messageId;let L=Z.replyChannel;if(L?.messageId)f.larkMessageId=L.messageId;if(L?.chatId)f.chatId=L.chatId;if(L?.userId)f.larkUserId=L.userId;let C=L?.profile;if(C)f.larkProfile=C}if(G)f.triggerEventId=G;if(z=await B.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:f}),!z)throw Error("Failed to create sub-session")}let U=KU(),V=new AbortController;if(this.processRegistries.size>=this.maxProcessRegistries){if(this.cleanupEmptyProcessRegistries(),this.processRegistries.size>=this.maxProcessRegistries)throw Error(`BackgroundTaskManager.processRegistries \u8FBE\u5230\u4E0A\u9650 ${this.maxProcessRegistries}\uFF08\u542B\u6B8B\u7559 PID\uFF09\uFF0C\u62D2\u7EDD\u521B\u5EFA\u65B0 task\uFF08taskId=${H}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let M=new l2;this.processRegistries.set(H,M);let R=Date.now(),N=`${Y}:bg_${H}`,b={id:H,runId:N,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:R,lastUpdatedAt:R,timeoutMs:J||D2,abortController:V,similarTaskIds:D,triggerEventId:G,model:Q,fallbackModel:q,replyChannel:U};this.tasks.set(H,b),this.abortControllers.set(H,V);let E={backgroundTaskId:H,subSessionId:z.id,parentSessionId:w,description:$,subagentType:Y,startedAt:R,timeoutMs:J||D2};return this.publishBackgroundEvent(c_.STARTED,E,w,G,U),this.executeTask(H,X,J,w).catch((f)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:H,error:f instanceof Error?f.message:String(f)})}),{taskId:H,subSessionId:z.id}}async executeTask(_,w,$,X){let Y=this.tasks.get(_);if(!Y){h.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let J=Date.now();Y.status="running",Y.startedAt=J,Y.lastUpdatedAt=J;let D=$||D2,W=this.abortControllers.get(_);this.startProgressReporter(_,X||Y.parentSessionId);try{let Q=await this.getSessionComponent().get(Y.subSessionId);if(!Q)throw Error(`Sub session not found: ${Y.subSessionId}`);let q=this.processRegistries.get(_),H=await this.executeWithAbort(Q,w,D,_,W?.signal,Y.similarTaskIds,q,()=>W?.abort(),Y.subagentType);if(W?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let B=Date.now();Y.status="completed",Y.completedAt=B,Y.lastUpdatedAt=B,Y.result=H;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:O,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.COMPLETED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:O})}catch(G){let Q=G instanceof Error?G.message:String(G),q=w_.parseAskUserErrorFromMessage(G),H=Q.toLowerCase().includes("stopped")||Q.toLowerCase().includes("aborted"),B=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=y0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(q){Y.status="awaiting-user",Y.error=q.rawErrorMessage,Y.pendingAskUserQuery=q.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:q.query,sessionId:q.sessionId,nodeId:q.nodeId,nodeType:q.nodeType,agentSessionId:q.agentSessionId,error:q.rawErrorMessage,executionTimeMs:B,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.ASK_USER,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),h.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:Y.subSessionId,nodeId:q.nodeId,queryPreview:q.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(H){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(Q.startsWith("Task execution timeout after")){Y.status="timeout";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.TIMEOUT,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:Q,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.FAILED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=Q,h.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:Y.status,error:Q})}finally{this.finalizeTask(_,Y.status);let G=Y?._preserveSubSessionOnExit===!0,Q=this.getSessionComponent();if(!G&&Q?.endSessionCleanup&&Y?.subSessionId)try{await Q.endSessionCleanup(Y.subSessionId)}catch(q){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:q instanceof Error?q.message:String(q)})}else if(G)h.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let Y=y0();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let J={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(c_.PROGRESS,J,w,X.triggerEventId,X.replyChannel)},RU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,D,W,G){let Q=_?.metadata??{},q=Q.task_id,H=Q.task_description||"",B=_.id,O=Q.subagent_type,z=O||G||"general";if(!O&&!G)h.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${B}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),M=await XU(z,{registry:V}),R=H$(z),N=M?.basePrompt||R?.promptOverride||"You are a subagent. Complete this task: {task_description}",b=M?.deniedTools||R?.deniedTools||[],E=M?.allowedTools||R?.allowedTools,f=N.replace(/{task_description}/g,H||"N/A");if(f+=`
|
|
2168
|
+
`}var EU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),W1=1800000,SU=600000;class w_{env;maxProcessRegistries=1000;maxTerminalTasks=1000;tasks=new Map;terminalTasks=new Map;abortControllers=new Map;progressTimers=new Map;processRegistries=new Map;workflowRunRegistries=new Map;workflowService;constructor(_){this.env=_}setWorkflowService(_){this.workflowService=_}attachWorkflowRun(_,w){if(!_||!w)return;let $=this.workflowRunRegistries.get(_);if(!$)$=new Set,this.workflowRunRegistries.set(_,$);$.add(w)}detachWorkflowRun(_,w){this.workflowRunRegistries.get(_)?.delete(w)}replaceWorkflowRun(_,w,$){if(!_)return;let X=this.workflowRunRegistries.get(_);if(!X)return;if(w)X.delete(w);if($)X.add($)}async propagateStopToWorkflowRuns(_,w){let $=this.workflowRunRegistries.get(_);if(!$||$.size===0)return{runIds:[],stopResults:[]};let X=Array.from($);y.info(`[BackgroundTaskManager] propagateStopToWorkflowRuns count=${X.length} bgTaskId=${_}`);let Y=[];for(let J of X){if(typeof this.workflowService?.stopRun!=="function"){y.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${J}`),Y.push({runId:J,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(J,w),Y.push({runId:J,success:!0})}catch(Q){let W=Q instanceof Error?Q.message:String(Q);y.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${W}`),Y.push({runId:J,success:!1,error:W})}}return $.clear(),{runIds:X,stopResults:Y}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let J=this.terminalTasks.keys().next().value;if(J!==void 0)this.terminalTasks.delete(J)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let Y=this.processRegistries.get(_);if(Y&&Y.size()>0)y.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${Y.size()}, reason=${w})`);y.debug(`[BackgroundTaskManager] finalizeTask taskId=${_} reason=${w}`)}getProcessRegistrySize(){return this.processRegistries.size}getMaxProcessRegistries(){return this.maxProcessRegistries}cleanupEmptyProcessRegistries(){let _=0;for(let[w,$]of this.processRegistries)if($.size()===0)this.processRegistries.delete(w),_++;return _}static DEFAULT_WORKFLOW_ENTRY_AGENT="workflow-runner";resolveEntryAgent(_){try{if(w_.detectWorkflowShortcutCompat(_))return y.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${w_.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),w_.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??w_.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){y.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=q_((_)=>EU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return w_._detectWorkflowShortcutWrapped(_)}getSessionComponent(){return this.env?.getComponent?.("session")}async resolveAssociatedTaskIdBySubSession(_){if(!_)return;try{let $=await this.env?.getComponent?.("task")?.getTaskIdBySessionId?.(_);return typeof $==="number"&&$>0?$:void 0}catch(w){y.debug(`[BackgroundTaskManager] resolveAssociatedTaskIdBySubSession failed for ${_}: ${w instanceof Error?w.message:String(w)}`);return}}publishBackgroundEvent(_,w,$,X,Y){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...Y?{replyChannel:Y}:{}}}),y.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:Y?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,Y){this.publishBackgroundEvent(_,w,$,X,Y)}static parseAskUserErrorFromMessage(_){let w=_ instanceof Error?_.message:String(_);if(_&&typeof _==="object"&&_.name==="AskUserError"&&_.query){let X=_;return{query:X.query,sessionId:X.sessionId,nodeId:X.nodeId,nodeType:X.nodeType||"agent",agentSessionId:X.agentSessionId,rawErrorMessage:w}}let $="__ASK_USER_ERROR__:";if(w.includes($))try{let X=w.substring(w.indexOf($)+$.length),Y=JSON.parse(X);return{query:Y.query,sessionId:Y.sessionId,nodeId:Y.nodeId,nodeType:Y.nodeType||"agent",agentSessionId:Y.agentSessionId,rawErrorMessage:w}}catch(X){return 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:w,description:$,prompt:X,subagentType:Y,timeout:J,similarTaskIds:Q,existingSubSessionId:W,triggerEventId:G,model:D,fallbackModel:q,fallbackModels:H}=_,B=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,O=this.getSessionComponent();if(!O)throw Error("SessionComponent not found");if(!await O.get(w))throw Error(`Parent session not found: ${w}`);let U;if(W){let C=await O.get(W);if(!C)throw Error(`Sub session not found for resume: ${W}`);let K=C?.metadata?.created_by;if(K&&K!=="subagent")y.warn(`[BackgroundTaskManager] Session ${W} was not created by a sub-agent (created_by=${K}); reusing anyway`);U=C;try{let P=C?.metadata??{};await O.update(W,{metadata:{...P,reused_sub_session:!0,reused_at:Date.now()}})}catch(P){y.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:W,error:P instanceof Error?P.message:String(P)})}y.info(`[BackgroundTaskManager] Reusing sub session: ${W} for task ${B}`)}else{let C={subagent_type:Y,created_by:"subagent",task_description:$},K=_0();if(K){if(K.messageId)C.messageId=K.messageId;let P=K.replyChannel;if(P?.messageId)C.larkMessageId=P.messageId;if(P?.chatId)C.chatId=P.chatId;if(P?.userId)C.larkUserId=P.userId;let g=P?.profile;if(g)C.larkProfile=g}if(G)C.triggerEventId=G;if(U=await O.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:C}),!U)throw Error("Failed to create sub-session")}let V=IU(),A=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=${B}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let R=new p1;this.processRegistries.set(B,R);let L=Date.now(),N=`${Y}:bg_${B}`,E={id:B,runId:N,subSessionId:U.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:L,lastUpdatedAt:L,timeoutMs:J||W1,abortController:A,similarTaskIds:Q,triggerEventId:G,model:D,fallbackModel:q,fallbackModels:H,replyChannel:V};this.tasks.set(B,E),this.abortControllers.set(B,A);let b={backgroundTaskId:B,subSessionId:U.id,parentSessionId:w,description:$,subagentType:Y,startedAt:L,timeoutMs:J||W1};return this.publishBackgroundEvent(p_.STARTED,b,w,G,V),this.executeTask(B,X,J,w).catch((C)=>{y.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:B,error:C instanceof Error?C.message:String(C)})}),{taskId:B,subSessionId:U.id}}async executeTask(_,w,$,X){let Y=this.tasks.get(_);if(!Y){y.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let J=Date.now();Y.status="running",Y.startedAt=J,Y.lastUpdatedAt=J;let Q=$||W1,W=this.abortControllers.get(_);this.startProgressReporter(_,X||Y.parentSessionId);try{let D=await this.getSessionComponent().get(Y.subSessionId);if(!D)throw Error(`Sub session not found: ${Y.subSessionId}`);let q=this.processRegistries.get(_),H=await this.executeWithAbort(D,w,Q,_,W?.signal,Y.similarTaskIds,q,()=>W?.abort(),Y.subagentType);if(W?.signal.aborted){y.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let B=Date.now();Y.status="completed",Y.completedAt=B,Y.lastUpdatedAt=B,Y.result=H;let O=Y.completedAt-Y.startedAt;if(Y.associatedTaskId=v0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"completed",result:Y.result,description:Y.description,executionTimeMs:O,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.COMPLETED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:O})}catch(G){let D=G instanceof Error?G.message:String(G),q=w_.parseAskUserErrorFromMessage(G),H=D.toLowerCase().includes("stopped")||D.toLowerCase().includes("aborted"),B=Y.startedAt?Date.now()-Y.startedAt:0,O=Date.now();if(Y.completedAt=O,Y.lastUpdatedAt=O,Y.associatedTaskId=v0(),Y.associatedTaskId===void 0)Y.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(Y.subSessionId);if(q){Y.status="awaiting-user",Y.error=q.rawErrorMessage,Y.pendingAskUserQuery=q.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:q.query,sessionId:q.sessionId,nodeId:q.nodeId,nodeType:q.nodeType,agentSessionId:q.agentSessionId,error:q.rawErrorMessage,executionTimeMs:B,hints:["\u8BF7\u628A\u4E0A\u9762\u7684\u95EE\u9898\u539F\u6837\u901A\u8FC7 ask_user tool \u5C55\u793A\u7ED9\u7528\u6237\u5E76\u7B49\u5F85\u7B54\u590D",`\u5F97\u5230\u7528\u6237\u56DE\u590D\u540E\uFF0C\u901A\u8FC7 delegate_task(subagentType="${Y.subagentType}", existingSubSessionId="${Y.subSessionId}", prompt=<\u57FA\u4E8E\u7528\u6237\u56DE\u590D>) \u590D\u7528 sub-session \u8BA9 sub-agent \u7EE7\u627F\u4E4B\u524D\u6D88\u606F\u5386\u53F2\u7EE7\u7EED\u63A8\u8FDB\uFF0C\u65E0\u9700\u5B9E\u73B0 resume function`],associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.ASK_USER,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel),y.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:Y.subSessionId,nodeId:q.nodeId,queryPreview:q.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(H){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:D,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.STOPPED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else if(D.startsWith("Task execution timeout after")){Y.status="timeout";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"timeout",description:Y.description,error:D,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.TIMEOUT,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}else{Y.status="failed";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"failed",error:D,executionTimeMs:B,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.FAILED,z,X||Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}Y.error=D,y.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:Y.status,error:D})}finally{this.finalizeTask(_,Y.status);let G=Y?._preserveSubSessionOnExit===!0,D=this.getSessionComponent();if(!G&&D?.endSessionCleanup&&Y?.subSessionId)try{await D.endSessionCleanup(Y.subSessionId)}catch(q){y.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:q instanceof Error?q.message:String(q)})}else if(G)y.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${Y.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let Y=v0();if(Y!==void 0)X.associatedTaskId=Y;X.lastUpdatedAt=Date.now();let J={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId,startedAt:X.createdAt,timeoutMs:X.timeoutMs};this.publishBackgroundEvent(p_.PROGRESS,J,w,X.triggerEventId,X.replyChannel)},SU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,Q,W,G){let D=_?.metadata??{},q=D.task_id,H=D.task_description||"",B=_.id,O=D.subagent_type,z=O||G||"general";if(!O&&!G)y.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${B}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),A=await HU(z,{registry:V}),R=z$(z),L=A?.basePrompt||R?.promptOverride||"You are a subagent. Complete this task: {task_description}",N=A?.deniedTools||R?.deniedTools||[],E=A?.allowedTools||R?.allowedTools,b=L.replace(/{task_description}/g,H||"N/A");if(b+=`
|
|
2162
2169
|
|
|
2163
2170
|
---
|
|
2164
2171
|
|
|
@@ -2177,13 +2184,13 @@ ${w}
|
|
|
2177
2184
|
- \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
|
|
2178
2185
|
- \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
|
|
2179
2186
|
- \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
|
|
2180
|
-
- \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,J&&J.length>0)try{let
|
|
2181
|
-
`;if(
|
|
2182
|
-
`,c.description)
|
|
2183
|
-
`;if(c.goals_and_expected_deliverables)
|
|
2184
|
-
`;if(
|
|
2185
|
-
`;for(let
|
|
2186
|
-
`}i.push(
|
|
2187
|
+
- \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,J&&J.length>0)try{let g=this.env?.getComponent?.("task");if(g){let i=[];for(let v of J)try{let c=await g.getTask(v);if(!c){y.warn(`[delegate] Similar task #${v} not found, skipping`);continue}let z_=await g.listOperations({taskId:v,limit:10}),V_=`### Task #${c.id}: ${c.title}
|
|
2188
|
+
`;if(V_+=`- Status: ${c.status}
|
|
2189
|
+
`,c.description)V_+=`- Description: ${c.description}
|
|
2190
|
+
`;if(c.goals_and_expected_deliverables)V_+=`- Goals: ${c.goals_and_expected_deliverables}
|
|
2191
|
+
`;if(z_&&z_.length>0){V_+=`- Recent Operations:
|
|
2192
|
+
`;for(let v_ of z_)V_+=` - [${v_.actionType}] ${v_.actionTitle}: ${v_.actionDescription||""}
|
|
2193
|
+
`}i.push(V_)}catch(c){y.warn(`[delegate] Failed to fetch similar task #${v}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)b+=`
|
|
2187
2194
|
|
|
2188
2195
|
---
|
|
2189
2196
|
|
|
@@ -2191,19 +2198,19 @@ ${w}
|
|
|
2191
2198
|
|
|
2192
2199
|
The following similar tasks and their operation records can serve as reference:
|
|
2193
2200
|
|
|
2194
|
-
`,
|
|
2195
|
-
`),
|
|
2201
|
+
`,b+=i.join(`
|
|
2202
|
+
`),b+=`
|
|
2196
2203
|
|
|
2197
2204
|
---
|
|
2198
2205
|
|
|
2199
|
-
Use these as guidance to improve task execution efficiency.`}}catch(
|
|
2206
|
+
Use these as guidance to improve task execution efficiency.`}}catch(g){y.warn("[delegate] Failed to inject similar tasks reference",{error:g instanceof Error?g.message:String(g)})}if(!U)throw Error("AgentComponent not found");try{if(this.env){let g=LU(this.env),i=NU({registry:g,similarTaskIds:J??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)b+=`
|
|
2200
2207
|
|
|
2201
2208
|
---
|
|
2202
2209
|
|
|
2203
|
-
${i.markdown}`}}catch(
|
|
2210
|
+
${i.markdown}`}}catch(g){y.warn("[delegate] Failed to inject reuse candidate section",{error:g instanceof Error?g.message:String(g)})}let C=R?{...R,allowedTools:E}:E?{id:z,name:z,mode:"subagent",description:A?.description||"Custom agent",allowedTools:E,deniedTools:N}:void 0;bU(U,z,L,C,N);let P=V?.get(z)?.type==="workflow"?w:b;return new Promise((g,i)=>{let v=async()=>{try{await Q?.killAll()}catch(G_){y.warn("[delegate] ProcessRegistry.killAll failed",{error:G_ instanceof Error?G_.message:String(G_)})}},c=!1,z_,V_,v_=this.tasks.get(X);if(v_?.runId)V_=v_.runId;let w2=()=>{if(Y&&$2)try{Y.removeEventListener("abort",$2)}catch{}},$2;if($2=()=>{if(c)return;if(c=!0,z_)clearTimeout(z_);w2();try{let G_=this.env?.getComponent?.("agent");if(G_?.abortRun&&V_)G_.abortRun(V_,"task_signal_abort")}catch{}v().catch(()=>{}).then(()=>{i(Error("Task execution stopped"))})},z_=setTimeout(()=>{if(c)return;if(c=!0,z_)clearTimeout(z_);w2();try{W?.()}catch{}try{let G_=this.env?.getComponent?.("agent");if(G_?.abortRun&&V_)G_.abortRun(V_,"task_timeout")}catch{}v().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${$}ms`))})},$),Y)Y.addEventListener("abort",$2);let d$=()=>{let G_=v_?.model,p$=v_?.fallbackModel,i$=v_?.fallbackModels;return this.env.handle_query?.(P,{sessionId:B,deniedTools:N.length>0?N:void 0,agentType:z,abort:Y,runId:V_,...G_?{model:G_}:{},...p$?{fallbackModel:p$}:{},...Array.isArray(i$)?{fallbackModels:i$}:{}})};(Q?E4(Q,()=>G$(X,()=>d$())):G$(X,()=>d$()))?.then((G_)=>{if(c)return;if(c=!0,z_)clearTimeout(z_);w2(),g(G_)}).catch((G_)=>{if(c)return;if(c=!0,z_)clearTimeout(z_);w2(),i(G_)})})}async stopTask(_){let w=this.tasks.get(_)??this.terminalTasks.get(_);if(!w)return{success:!1,message:"Task not found"};if(this.terminalTasks.has(_))return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};if(w.status==="completed"||w.status==="failed"||w.status==="stopped"||w.status==="timeout")return{success:!1,task:w,message:`Cannot stop task with status: ${w.status}`};let $=Date.now();if(w.status="stopped",w.abortController?.abort(),w.runId)try{this.env?.getComponent?.("agent")?.abortRun?.(w.runId,"stop_task")}catch(Q){y.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:_,runId:w.runId,error:Q instanceof Error?Q.message:String(Q)})}w.completedAt=$,w.lastUpdatedAt=$;try{await this.processRegistries.get(_)?.killAll()}catch(Q){y.warn("[delegate] stopTask killAll failed",{taskId:_,error:Q instanceof Error?Q.message:String(Q)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns(_,"Task stopped by user"),J={backgroundTaskId:w.id,subSessionId:w.subSessionId,parentSessionId:w.parentSessionId,status:"stopped",description:w.description,error:"Task stopped by user",executionTimeMs:w.startedAt?w.completedAt-w.startedAt:0,associatedTaskId:w.associatedTaskId};return this.publishBackgroundEvent(p_.STOPPED,J,w.parentSessionId,w.triggerEventId,w.replyChannel),this.finalizeTask(_,"stopped"),{success:!0,task:w,message:"Task has been stopped",attached_workflow_run_ids:X,workflow_stop_results:Y}}getTask(_){return this.tasks.get(_)??this.terminalTasks.get(_)}async getSubSessionActivity(_){let w=this.getTask(_);if(!w)return;let $=this.getSessionComponent();if(!$?.get)return;try{let X=await $.get(w.subSessionId);if(!X)return;return{messageCount:X.messageCount??0,updatedAt:X.updatedAt??w.lastUpdatedAt??w.createdAt}}catch{return}}listTasks(){return Array.from(this.tasks.values()).concat(Array.from(this.terminalTasks.values()))}hasActiveTaskForParent(_){if(!_)return!1;for(let w of this.tasks.values())if(w.parentSessionId===_&&(w.status==="pending"||w.status==="running"))return!0;return!1}async stopAllForParent(_){if(!_)return{stoppedTaskIds:[]};let w=[];for(let[$,X]of this.tasks)if(X.parentSessionId===_&&(X.status==="running"||X.status==="pending"))try{if((await this.stopTask($))?.success)w.push($)}catch(Y){y.warn(`[BackgroundTaskManager] stopAllForParent failed for ${$}: ${Y instanceof Error?Y.message:String(Y)}`)}return{stoppedTaskIds:w}}async forceStopAllAcrossParents(){let _=new Set,w=new Set([...this.tasks.keys(),...this.terminalTasks.keys(),...this.processRegistries.keys()]);for(let $ of w){if(_.has($))continue;_.add($);let Y=this.tasks.get($)??this.terminalTasks.get($);try{await this.processRegistries.get($)?.killAll()}catch(Q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`)}try{await this.propagateStopToWorkflowRuns($,"force stop all")}catch(Q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`)}let J=!1;if(Y&&(Y.status==="running"||Y.status==="pending"))try{Y.status="stopped",Y.completedAt=Date.now(),Y.lastUpdatedAt=Y.completedAt,Y.abortController?.abort(),J=!0}catch(Q){y.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${$}: ${Q instanceof Error?Q.message:String(Q)}`)}if(J&&Y){let Q={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:Y.parentSessionId,status:"stopped",description:Y.description,error:"force stop all",executionTimeMs:Y.startedAt&&Y.completedAt?Y.completedAt-Y.startedAt:0,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(p_.STOPPED,Q,Y.parentSessionId,Y.triggerEventId,Y.replyChannel)}}}async forceStopAll(){return this.forceStopAllAcrossParents()}async dispose(){for(let[,_]of this.progressTimers)try{clearInterval(_)}catch{}this.progressTimers.clear();for(let[,_]of this.abortControllers)try{_.abort()}catch{}this.abortControllers.clear();for(let[,_]of this.processRegistries)try{await _.killAll()}catch(w){y.warn("[BackgroundTaskManager] dispose registry.killAll failed",{error:w instanceof Error?w.message:String(w)})}this.processRegistries.clear();for(let _ of this.workflowRunRegistries.keys())await this.propagateStopToWorkflowRuns(_,"BackgroundTaskManager disposed");this.workflowRunRegistries.clear(),this.tasks.clear(),y.info("[BackgroundTaskManager] Disposed")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],w_.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],w_.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],w_.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],w_.prototype,"forceStopAllAcrossParents",null);function o5(_){return _.env?.getComponent?.("agent")?.getRegistry?.()}function s5(_){let w=_.env,X=_.backgroundTaskManager??new w_(w),Y=o5(_);_._backgroundTaskManager=X;let J={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
|
|
2204
2211
|
|
|
2205
2212
|
Available agent types:
|
|
2206
|
-
${
|
|
2213
|
+
${VU(Y)}
|
|
2207
2214
|
|
|
2208
2215
|
When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
2209
2216
|
|
|
@@ -2232,8 +2239,14 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2232
2239
|
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2233
2240
|
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2234
2241
|
- **reason**: Brief reason for calling this tool (optional)
|
|
2235
|
-
- **similar_task_ids**: Similar task IDs (max 3) to reference for improving sub-agent execution efficiency. Search for similar tasks using \`task_search\` or \`task_list\` before calling this tool.`,parameters:
|
|
2236
|
-
`),metadata:{execution_time_ms:Date.now()-
|
|
2242
|
+
- **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:a5,execute:async(Q,W)=>{let G=Date.now(),D=a5.parse(Q),{description:q,prompt:H,subagent_type:B="general",timeout:O,reason:z,similar_task_ids:U}=D,V=W.session_id||"default",A=D.triggerEventId??ZU();if(A&&A!==D.triggerEventId)y.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${A}`);if(y.info(`[delegate_task] Called: description=${q}, subagent_type=${B}, triggerEventId=${A??"(none)"}`),A){let C=P4();if(C)try{if(!await C.getEventById(A))return{success:!1,output:"",error:`Unknown triggerEventId: ${A} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-G}}}catch(K){return{success:!1,output:"",error:`Failed to verify triggerEventId ${A}: ${K instanceof Error?K.message:String(K)}`,metadata:{execution_time_ms:Date.now()-G}}}else y.warn(`[delegate_task] triggerEventId=${A} supplied but no shared EventStore registered; skipping verification`)}let R=o5(_);if(!BU(B,R))return{success:!1,output:"",error:`Unknown subagent type: ${B}`,metadata:{execution_time_ms:Date.now()-G}};let L=_.getTagService(),N=H,E={prompt:N,subagentType:B,timeout:O,reason:z,tagService:L},b={component:{name:"task",version:"1.0.0"},data:E,metadata:{sessionId:V},phase:"before",hookPoint:$_.DELEGATE_BEFORE};return await P_.execute($_.DELEGATE_BEFORE,E,{sessionId:V}),N=E.prompt,await TU(X,V,q,N,E.subagentType,E.timeout,U,D.sub_session_id,A,W.model,W.fallbackModel,W.fallbackModels)}};return J.execute=q_(J.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),J}function PU(){let _=_0();if(!_)return;let w=_.envEvent,$=w?.metadata?.triggerEventId;if(typeof $==="string"&&$.length>0)return $;let X=w?.payload?.triggerEventId;if(typeof X==="string"&&X.length>0)return X;return}var ZU=q_(PU,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function CU(){let _=_0()?.replyChannel;if(!_)return;if(!_.chatId&&!_.messageId)return;let w={..._.params??{}};if(_.userId&&w.userId===void 0)w.userId=_.userId;return{type:_.type,appId:_.appId,chatId:_.chatId,messageId:_.messageId,profile:_.profile,params:Object.keys(w).length>0?w:void 0}}var IU=q_(CU,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function TU(_,w,$,X,Y,J,Q,W,G,D,q,H){let B=Date.now();try{let O=Y,z=X,U,V=_.resolveEntryAgent(Y);if(V)U=Y,O=V,z=jU({workflowName:U,originalPrompt:X,description:$}),y.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${V}'`);let{taskId:A,subSessionId:R}=await _.createTask({parentSessionId:w,description:$,prompt:z,subagentType:O,timeout:J,similarTaskIds:Q,originalWorkflowName:U,existingSubSessionId:W,triggerEventId:G,model:D,fallbackModel:q,fallbackModels:H});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${A}`,`\uD83D\uDCDD Description: ${$}`,`\uD83E\uDD16 Sub-agent: ${O}${U?` (workflow: ${U})`:""}`,`\u23F1\uFE0F Timeout: ${(J||W1)/1000}s`,"",`Use stop_task with task_id="${A}" to cancel this task.`].join(`
|
|
2243
|
+
`),metadata:{execution_time_ms:Date.now()-B,sessionId:R,background:!0,status:"accepted",bgProcessId:A}}}catch(O){return{success:!1,output:"",error:O instanceof Error?O.message:String(O),metadata:{execution_time_ms:Date.now()-B}}}}var Lw={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};H_();var kU=20;var gU=["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 hU(_){if(!_)return[];let w;try{w=JSON.parse(_)}catch{return[]}if(!w||typeof w!=="object"||Array.isArray(w))return[];let $=w.similar_task_ids;if(!Array.isArray($))return[];let X=[],Y=new Set;for(let J of $){if(typeof J!=="number")continue;if(!Number.isInteger(J)||J<=0)continue;if(Y.has(J))continue;if(Y.add(J),X.push(J),X.length>=kU)break}return X}function yU(_){switch(_){case"completed":case"cancelled":case"paused":case"archived":return"reopen";case"todo":case"active":default:return"enhance"}}function t5(_){return _==="paused"?"active":"todo"}var O$="__NEW_TASK_ID__",M$="#__NEW_TASK_ID__";function vU(_){switch(_.scenario){case"reuse":return xU(_);case"reopen":return mU(_);case"reopen_enhance":return uU(_);case"remount":return lU(_);case"soft_reuse":return cU(_)}}function V$(_){return _.newTaskId>0?String(_.newTaskId):O$}function f_(_){return _.newTaskId>0?`#${_.newTaskId}`:M$}function D1(_){let w=_.targetTask;if(!w)return"";return`#${_.targetTaskId} [${w.type}] ${w.title}
|
|
2244
|
+
\u72B6\u6001\uFF1A${w.status}`}function xU(_){let w=_.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","",D1(_),"\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>${w})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${f_(_)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${_.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${f_(_)}\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 ${f_(_)}\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(`
|
|
2245
|
+
`)}function mU(_){let w=_.targetTask?.status??"completed",$=t5(w),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","",D1(_),`\u72B6\u6001\uFF1A${w} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen\uFF08\u6062\u590D\u4E3A ${$}\uFF09`,"","\u5982\u9700\u91CD\u5F00\u5E76\u627F\u63A5\u672C\u6B21\u8BF7\u6C42\uFF0C\u53EF\u6267\u884C\uFF1A",` task_update(task_id=${_.targetTaskId}, status=${$}, description=<\u8FFD\u52A0\u672C\u6B21\u8BF7\u6C42\u7684\u63CF\u8FF0>${X})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${f_(_)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${_.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${f_(_)}\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=${$}, ...) \u6267\u884C\u91CD\u5F00\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${f_(_)}\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(`
|
|
2246
|
+
`)}function uU(_){let w=_.targetTask?.status??"completed",$=t5(w);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","",D1(_),`\u72B6\u6001\uFF1A${w} \uFF5C \u5EFA\u8BAE\u52A8\u4F5C\uFF1Areopen + enhance\uFF08\u6062\u590D\u4E3A ${$} \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=${$}, 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 ${f_(_)}\u3002\u82E5\u786E\u8BA4\u5E94\u590D\u7528 #${_.targetTaskId}\uFF0C\u8BF7\u8C03\u7528\u4E0A\u8FF0 task_update \u5E76\u6309\u9700\u5F52\u6863 ${f_(_)}\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=${$}, ..., goals_and_expected_deliverables=...) \u6267\u884C\u91CD\u5F00\u5E76\u589E\u5F3A\uFF0C\u5E76\u5F52\u6863\u672C\u6B21\u65B0\u5EFA\u7684\u4EFB\u52A1 ${f_(_)}\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(`
|
|
2247
|
+
`)}function lU(_){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=${V$(_)}, parent_task_id=${_.recommendedRootId})`,"",`\u8BF4\u660E\uFF1A\u672C\u6B21\u5DF2\u521B\u5EFA\u65B0\u4EFB\u52A1 ${f_(_)}\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(${V$(_)}) \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=${V$(_)}, 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(`
|
|
2248
|
+
`)}function cU(_){let w=_.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","",D1(_),"","\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>${w})`,"",`\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 ${f_(_)}\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 ${f_(_)}\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(`
|
|
2249
|
+
`)}function dU(_){let w=_.toLowerCase();return gU.some(($)=>$.endsWith("_")||$.endsWith("*")?w.startsWith($.slice(0,-1)):w===$)}function pU(_,w){let $=(X,Y)=>{if(Array.isArray(X)){X.forEach((J,Q)=>$(J,`${Y}[${Q}]`));return}if(!X||typeof X!=="object")return;for(let[J,Q]of Object.entries(X)){let W=Y?`${Y}.${J}`:J;if(dU(J))throw Error(`[assertNoLeakage] leakage key detected at ${W}: "${J}"`);$(Q,W)}};$(_,"state"),$(w,"questions")}function iU(_,w){let $;try{$=JSON.parse(_.context)}catch{return!1}if(!$||typeof $!=="object"||Array.isArray($))return!1;return $.decision_hint=w,_.context=JSON.stringify($),!0}var PA=q_(hU,"task.decision.parseSimilarTaskIds",{recordParams:!0,recordResult:!0,log:!1,paramFilter:(_)=>{let w=_[0],$=typeof w==="string"?w:"";return{contextLen:$.length,contextPreview:$.length>80?$.slice(0,80)+"\u2026":$}},resultFilter:(_)=>({count:_.length,ids:_.join(",")})}),ZA=q_(yU,"task.decision.deriveActionFromStatus",{recordParams:!0,recordResult:!0,log:!1}),CA=q_(vU,"task.decision.buildHintText",{recordParams:!0,recordResult:!0,log:!1,paramFilter:(_)=>{let w=_[0]??{};return{scenario:w.scenario,newTaskId:w.newTaskId,targetTaskId:w.targetTaskId??null,recommendedRootId:w.recommendedRootId??null,currentParentId:w.currentParentId??null,confidence:w.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(_)})}),IA=q_(pU,"task.decision.assertNoLeakage",{recordParams:!0,recordResult:!1,log:!1,paramFilter:(_)=>({stateKeys:G1(_[0]),questionKeys:G1(_[1])})}),TA=q_(iU,"task.decision.writeDecisionHint",{recordParams:!0,recordResult:!0,log:!1,paramFilter:(_)=>{let w=_[0]??{},$=typeof _[1]==="string"?_[1]:"";return{contextLen:typeof w.context==="string"?w.context.length:0,hintLen:$.length,hintScenario:/task_update\s*\(/.test($)?"actionable":"plain"}},resultFilter:(_)=>({written:_}),errorIf:(_)=>_===!1?Error("writeDecisionHint returned false (context not a JSON object)"):void 0});function G1(_,w=[],$=0){if(w.length>=40||$>4)return w;if(Array.isArray(_)){for(let X of _.slice(0,3))G1(X,w,$+1);return w}if(!_||typeof _!=="object")return w;for(let X of Object.keys(_)){if(w.length>=40)break;if(!w.includes(X))w.push(X);G1(_[X],w,$+1)}return w}import{execSync as oU}from"child_process";var e5="unknown",nU='{"type":"unknown"}';function rU(){return{task_id:M.number().describe("Task ID")}}function aU(_){if(typeof _!=="object"||_===null||Array.isArray(_))return _;let w=_;if(w.task_id===void 0&&w.id!==void 0)return{...w,task_id:w.id};return w}function R$(_){return M.preprocess(aU,M.object({...rU(),..._}))}var _6=M.object({title:M.string().describe("Task title"),description:M.string().optional().describe("Task description"),priority:M.enum(["low","medium","high"]).optional().describe("Task priority"),type:M.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:M.string().optional().describe("Goals and expected deliverables"),due_date:M.string().optional().describe("Due date (ISO format)"),tags:M.array(M.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:M.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:M.union([M.number(),M.null()]).optional().describe(`\u7236\u4EFB\u52A1 ID\uFF08\u53EF\u9009\uFF09\u3002\u4E0D\u4F20\u6216\u4F20 null \u65F6\uFF0C\u521B\u5EFA\u6839\u4EFB\u52A1\uFF08root task\uFF09\u3002
|
|
2237
2250
|
`+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
|
|
2238
2251
|
`+`**\u8C03\u7528\u524D\u5FC5\u987B\u5148\u8C03\u7528 task_tree(depth=2)** \u67E5\u770B\u73B0\u6709\u4EFB\u52A1\u6811\u7ED3\u6784\uFF0C\u907F\u514D\u91CD\u590D\u521B\u5EFA\u6839\u4EFB\u52A1\u3001\u907F\u514D\u5B64\u513F\u4EFB\u52A1\u3002
|
|
2239
2252
|
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
@@ -2241,7 +2254,7 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2241
2254
|
`+` B. \u5F52\u5C5E\u5230\u73B0\u6709\u4E3B\u9898\u805A\u7C7B\uFF08\u975E longterm \u6839\uFF0C\u4F46\u540C\u4E3B\u9898\uFF09\u2192 parent_task_id = \u8BE5\u6839 ID
|
|
2242
2255
|
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
2243
2256
|
`+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
|
|
2244
|
-
`+"\u6839\u636E\u8282\u70B9 id \u9009\u62E9\u5408\u9002\u7684\u7236\u4EFB\u52A1 ID\uFF08\u6765\u81EA tree \u8F93\u51FA\uFF0C**\u4E0D\u8981\u786C\u7F16\u7801**\u6570\u5B57\uFF09\u3002"),context:
|
|
2257
|
+
`+"\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:M.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]}')}),w6=R$({include_operations:M.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.")}),$6=M.object({status:M.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:M.enum(["low","medium","high"]).optional(),type:M.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:M.number().optional().default(20),offset:M.number().optional().default(0),depth:M.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:M.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")}),X6=M.object({keywords:M.array(M.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:M.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:M.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:M.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:M.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:M.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:M.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:M.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:M.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")}),Y6=R$({title:M.string().optional(),description:M.string().optional(),status:M.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:M.enum(["low","medium","high"]).optional(),type:M.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:M.number().min(0).max(100).optional(),current_status:M.string().optional(),goals_and_expected_deliverables:M.string().optional(),due_date:M.string().optional(),tags:M.array(M.string()).optional(),project_path:M.string().optional().describe("Project path, identifies which project this task belongs to"),context:M.string().optional().describe("Task context information for storing additional context"),parent_task_id:M.union([M.number(),M.null()]).optional().describe("Parent task ID (set to null to make it a root task)")}),J6=M.object({task_id:M.number().describe("Task ID")}),Q6=R$({deliverable_storage_path:M.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")}),W6=M.object({task_ids:M.array(M.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:M.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),G6=M.object({task_ids:M.array(M.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),D6=M.object({depth:M.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:M.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:M.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:M.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:M.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:M.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")});Ww();a();a();var sU=n("task-child-context"),tU=["commit","token","secret","password","api_key"];function A$(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map(A$);if(typeof _!=="object")return _;let w={};for(let[$,X]of Object.entries(_)){let Y=$.toLowerCase();if(tU.some((J)=>Y.includes(J)))continue;w[$]=A$(X)}return w}function eU(_){let{parent:w,overrides:$={}}=_,X=$.contextInherit!==!1,Y=$.inheritTags===!0,J=$.projectPath??w.projectPath??"unknown",Q={};if(w.contextJson&&w.contextJson.trim().length>0)try{let q=JSON.parse(w.contextJson);if(q&&typeof q==="object"&&!Array.isArray(q))Q=q}catch(q){sU.debug(`[task-child-context] parent #${w.taskId} context is malformed JSON; continuing with empty inherited context (${q instanceof Error?q.message:String(q)})`),Q={}}let W={};if(X){if(Q.worktree_path!==void 0&&$.worktreePath===void 0)W.worktree_path=Q.worktree_path;if(Q.branch!==void 0&&$.branch===void 0)W.branch=Q.branch;if(Q.parent_branch!==void 0)W.parent_branch=Q.parent_branch;if(Q.type!==void 0)W.type=Q.type;if(Q.prior_context&&typeof Q.prior_context==="object"){let H=Q.prior_context,B={};for(let[O,z]of Object.entries(H)){if(O.toLowerCase()==="commit")continue;B[O]=z}if(Object.keys(B).length>0)W.prior_context=B}let q=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[H,B]of Object.entries(Q)){if(q.has(H))continue;W[H]=B}}if($.worktreePath!==void 0)W.worktree_path=$.worktreePath;if($.branch!==void 0)W.branch=$.branch;let G=$.createdAt??new Date().toISOString();W.created_at=G,W.child_of=w.taskId;let D=A$(W);return{project_path:J,context:JSON.stringify(D),inheritedTags:Y?w.tags??[]:[]}}var q6=n("task:tools:create");function _z(_){if(!_)return;try{let w=JSON.parse(_);if(!w||typeof w!=="object"||Array.isArray(w))return;let $=w.decision_hint;return typeof $==="string"&&$.length>0?$:void 0}catch{return}}function wz(){try{let _=oU("git rev-parse --show-toplevel",{stdio:["ignore","pipe","ignore"]}).toString().trim(),w=process.cwd();if(!_)return null;if(w!==_)return w;if(w.includes(".worktrees/")||w.includes(".worktree/"))return w;return null}catch{return null}}function m0(_){return{name:"task_create",description:`
|
|
2245
2258
|
Create a new task for tracking work.
|
|
2246
2259
|
|
|
2247
2260
|
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
@@ -2259,6 +2272,30 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2259
2272
|
step 2: read the tree, then decide per "Decision Tree" below
|
|
2260
2273
|
step 3: task_create({...})
|
|
2261
2274
|
|
|
2275
|
+
## \u26A0\uFE0F STEP 1 \u2014 FIND SIMILAR TASKS FIRST (Task #4467)
|
|
2276
|
+
|
|
2277
|
+
Before creating a task, you **MUST** first look for existing tasks
|
|
2278
|
+
that cover the same ground, and record them in
|
|
2279
|
+
\`context.similar_task_ids\`. This lets the decision model detect
|
|
2280
|
+
duplicates and suggest reusing / reopening an existing task instead
|
|
2281
|
+
of piling up another root.
|
|
2282
|
+
|
|
2283
|
+
Workflow:
|
|
2284
|
+
step 1: task_search({keywords: [...]}) or task_get(...) to find
|
|
2285
|
+
existing tasks related to this request
|
|
2286
|
+
step 2: collect the relevant task ids (0 or more)
|
|
2287
|
+
step 3: task_create({..., context: {..., similar_task_ids: [id1, id2]}})
|
|
2288
|
+
|
|
2289
|
+
\`context.similar_task_ids\` is **required** (may be an empty array \`[]\`
|
|
2290
|
+
if you searched and found nothing related). It is an array of task ids.
|
|
2291
|
+
|
|
2292
|
+
The decision check runs on \`task:before.create\` and only **advises** \u2014
|
|
2293
|
+
the task is always created. If the output contains a
|
|
2294
|
+
\`[TASK_CREATE_HINT]\` section, you **MUST** read and verify it:
|
|
2295
|
+
verify with \`task_get\`, then either execute the suggested
|
|
2296
|
+
\`task_update\` (reusing / reopening / re-parenting) or explicitly
|
|
2297
|
+
state why it was not adopted. Never ignore it.
|
|
2298
|
+
|
|
2262
2299
|
## Decision Tree \u2014 How to choose parent_task_id
|
|
2263
2300
|
|
|
2264
2301
|
Walk these paths in order:
|
|
@@ -2381,20 +2418,22 @@ No need to poll \u2014 just wait for the notification and use \`task_get\` with
|
|
|
2381
2418
|
env-injected value is 0 / negative / non-integer, it's treated as
|
|
2382
2419
|
missing \u2014 only positive integers are honored.
|
|
2383
2420
|
|
|
2384
|
-
`,parameters:
|
|
2385
|
-
|
|
2421
|
+
`,parameters:_6,execute:async(w,$)=>{let X=_6.parse(w),Y=$.session_id||"unknown",J=wz(),Q=X.context,W=X1().parentTaskId,G=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:W!==void 0&&W!==null&&Number.isInteger(W)&&W>0?W:void 0,D=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,q=D!==void 0&&D!==e5,H=q?D:void 0,B=X.tags,O;if(G!==void 0)try{let z=await _.getTask(G);if(z){let U=eU({parent:{taskId:z.id,projectPath:z.project_path,contextJson:z.context??"",tags:z.tags},overrides:{projectPath:H,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(H===void 0)H=U.project_path;if(X.tags===void 0)B=U.inheritedTags;O=U.context}}catch(z){q6.debug(`[task_create] failed to pre-load parent #${G} for context inheritance: ${z instanceof Error?z.message:String(z)}`)}try{let z=X.context===nU?void 0:X.context,U=z?JSON.parse(z):{},V=typeof U==="object"&&U!==null&&!Array.isArray(U)?U:{};if(O)try{let A=JSON.parse(O);if(A&&typeof A==="object"&&!Array.isArray(A)){for(let[R,L]of Object.entries(A))if(V[R]===void 0)V[R]=L}}catch{}if(!V.created_at)V.created_at=new Date().toISOString();if(!V.worktree_path&&J)V.worktree_path=J;Q=JSON.stringify(V)}catch{Q=X.context}try{let z=await _.createTask({parent_task_id:G,title:X.title,description:X.description,priority:X.priority,type:X.type||"normal",goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:B,sessionId:Y,project_path:H??(q?D:e5),context:Q});x0(z.id),q6.info(`[createTask] Trace: Task #${z.id} created, currentTaskId=${z.id} set in EnvContext`);let U=_z(z.context),V=U?U.replaceAll(M$,`#${z.id}`).replaceAll(O$,String(z.id)):"";return{success:!0,output:`Task created successfully: #${z.id} - ${z.title}`+(V?`
|
|
2422
|
+
|
|
2423
|
+
${V}`:""),metadata:{execution_time_ms:0,task_id:z.id,status:z.status,createdAt:z.createdAt}}}catch(z){return{success:!1,output:"",error:z instanceof Error?z.message:String(z),metadata:{execution_time_ms:0}}}}}}function u0(_){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:w6,execute:async(w,$)=>{let X=w6.parse(w);try{if(X.include_operations){let Y=await _.getTaskWithOperations(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};let J=Y.task,Q=J&&typeof J==="object"?{...J,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(Q,null,2),metadata:{execution_time_ms:0}}}else{let Y=await _.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function l0(_){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
|
|
2424
|
+
`+"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:$6,execute:async(w,$)=>{let X=$6.parse(w);try{let Y=await _.listTasks({status:X.status,priority:X.priority,type:X.type,limit:X.limit,offset:X.offset,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({total:Y.total,count:Y.tasks.length,truncated:Y.total>Y.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:Y.tasks}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function c0(_){return{name:"task_search",description:"Search tasks by keywords across title, description, goals, tags, and operation records. Use this when you need to find tasks related to a "+"topic, feature, bug, or area of work \u2014 even when the keyword is only "+`in description / goals / tags / past operation logs.
|
|
2386
2425
|
|
|
2387
2426
|
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
2388
2427
|
|
|
2389
|
-
If \`keywords\` is empty, returns no results.`,parameters:
|
|
2428
|
+
If \`keywords\` is empty, returns no results.`,parameters:X6,execute:async(w,$)=>{let X=X6.parse(w);try{let Y=await _.searchTasksByKeywords(X.keywords,{limit:X.limit,offset:X.offset,excludeTaskId:X.exclude_task_id,status:X.status,priority:X.priority,type:X.type,depth:X.depth,include_archived:X.include_archived});return{success:!0,output:JSON.stringify({tasks:Y.tasks,total:Y.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function f$(_){return{name:"task_batch_archive",description:`Batch archive multiple tasks at once. Sets all specified tasks to 'archived' status and creates operation records for each.
|
|
2390
2429
|
|
|
2391
2430
|
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
2392
2431
|
|
|
2393
|
-
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:
|
|
2432
|
+
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:W6,execute:async(w,$)=>{let X=W6.parse(w),Y=X.task_ids,J=$.session_id||"batch-archive";if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let Q=[],W=0;for(let D of Y)try{if(await _.updateTask(D,{status:"archived"}))await _.createOperation({taskId:D,sessionId:J,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),W++,Q.push({id:D,success:!0});else Q.push({id:D,success:!1,error:"Task not found"})}catch(q){Q.push({id:D,success:!1,error:q instanceof Error?q.message:String(q)})}return{success:!Q.some((D)=>!D.success),output:JSON.stringify({archived_count:W,total:Y.length,errors:Q.filter((D)=>!D.success).map((D)=>({id:D.id,error:D.error})),results:Q},null,2),metadata:{execution_time_ms:0}}}}}function L$(_){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
2394
2433
|
|
|
2395
2434
|
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
2396
2435
|
|
|
2397
|
-
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:
|
|
2436
|
+
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:G6,execute:async(w,$)=>{let Y=G6.parse(w).task_ids;if(!Y||Y.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let J=[],Q=0;for(let G of Y)try{if(await _.deleteTask(G))Q++,J.push({id:G,success:!0});else J.push({id:G,success:!1,error:"Task not found"})}catch(D){J.push({id:G,success:!1,error:D instanceof Error?D.message:String(D)})}return{success:!J.some((G)=>!G.success),output:JSON.stringify({deleted_count:Q,total:Y.length,errors:J.filter((G)=>!G.success).map((G)=>({id:G.id,error:G.error})),results:J},null,2),metadata:{execution_time_ms:0}}}}}Ww();a();var $z=n("tool:update-task");async function Xz(_,w,$){let X=new Set,Y=$;while(Y!==null&&Y!==void 0){if(Y===w)return!0;if(X.has(Y))break;X.add(Y);let J=await _.getTask(Y);if(!J)break;Y=J.parent_task_id}return!1}function d0(_){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:Y6,execute:async(w,$)=>{let X=Y6.parse(w),Y=$.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await Xz(_,X.task_id,X.parent_task_id))return{success:!1,output:"",error:`Circular reference detected: setting parent_task_id to ${X.parent_task_id} for task #${X.task_id} would create a cycle`,metadata:{execution_time_ms:0}}}let J=await _.updateTask(X.task_id,{title:X.title,description:X.description,status:X.status,priority:X.priority,type:X.type,progress:X.progress,current_status:X.current_status,goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:X.tags,project_path:X.project_path,context:X.context,parent_task_id:X.parent_task_id});if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await _.createOperation({taskId:X.task_id,sessionId:Y,actionType:"progress",actionTitle:X.current_status||`Updated: ${X.status||`${X.progress}%`}`,actionDescription:JSON.stringify({status:X.status,progress:X.progress,current_status:X.current_status})});return x0(J.id),$z.info(`[updateTask] Trace: Task #${J.id} updated, currentTaskId=${J.id} set in EnvContext`),{success:!0,output:`Task updated: #${J.id} - ${J.title}`,metadata:{execution_time_ms:0,task:J}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function F$(_){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:J6,execute:async(w,$)=>{let X=J6.parse(w);try{if(!await _.deleteTask(X.task_id))return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Task deleted: #${X.task_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}Ww();a();var Yz=n("task:tools:complete"),Jz=`
|
|
2398
2437
|
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
2399
2438
|
|
|
2400
2439
|
**Before calling this tool**, you MUST:
|
|
@@ -2418,23 +2457,22 @@ The \`deliverable_storage_path\` will be persisted to the task's \`context.deliv
|
|
|
2418
2457
|
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
2419
2458
|
|
|
2420
2459
|
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
2421
|
-
`.trim();function
|
|
2422
|
-
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${
|
|
2423
|
-
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:
|
|
2460
|
+
`.trim();function p0(_){return{name:"task_complete",description:Jz,parameters:Q6,execute:async(w,$)=>{let X=Q6.parse(w),Y=$.session_id||"unknown";try{let J=await _.getTask(X.task_id);if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(J.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let Q=await _.completeTask(X.task_id,Y,X.deliverable_storage_path);if(!Q)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return x0(void 0),Yz.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: #${Q.id} - ${Q.title}
|
|
2461
|
+
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${Q.id} - ${Q.title}
|
|
2462
|
+
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:Q}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function B6(_,w){if(_.updatedAt<w.updatedAt)return 1;if(_.updatedAt>w.updatedAt)return-1;if(_.id<w.id)return 1;if(_.id>w.id)return-1;return 0}function H6(_,w){if(w<0)return _;if(w===0)return _.map(($)=>({...$,children:[]}));return _.map(($)=>({...$,children:H6($.children,w-1)}))}function U6(_){let w=0;for(let $ of _)w+=1+U6($.children);return w}function Qz(_){let w=new Map,$=new Map,X=[];for(let Y of _)w.set(Y.id,{id:Y.id,title:Y.title,status:Y.status,type:Y.type,priority:Y.priority,progress:Y.progress,children:[]});for(let Y of _){let J=Y.parent_task_id;if(J!==void 0&&J!==null&&w.has(J)){let Q=$.get(J)||[];Q.push(Y),$.set(J,Q)}else X.push(Y)}for(let[Y,J]of $.entries()){let Q=w.get(Y);J.sort(B6),Q.children=J.map((W)=>w.get(W.id))}return X.sort(B6),X.map((Y)=>w.get(Y.id))}function i0(_){return{name:"task_tree",description:"View the task tree (forest) with optional filters. Use this BEFORE task_create to decide whether to create a root task (omit parent_task_id) or attach to an existing parent. "+"depth: 0=\u53EA\u6839\u4EFB\u52A1, 1=\u6839+\u4E00\u5C42\u5B50\u4EFB\u52A1, 2=\u6839+\u4E8C\u5C42\u5B50\u4EFB\u52A1 (default), "+"-1 or omitted as -1=\u65E0\u9650\u5C42\u7EA7. "+`Returns { total, truncated, depth, parent_task_id, nodes } where:
|
|
2424
2463
|
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
2425
2464
|
- truncated: always false for now (no pagination cap on tree)
|
|
2426
2465
|
- depth: the resolved depth value
|
|
2427
2466
|
- parent_task_id: the root's id, or null for forest mode
|
|
2428
2467
|
- nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
|
|
2429
|
-
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:
|
|
2468
|
+
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:D6,execute:async(w,$)=>{let X=D6.parse(w);try{let Y=[],J=X.parent_task_id??null;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){let G=await _.getTask(X.parent_task_id);if(!G)Y=[];else{let D=await _.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[G,...D]}}else Y=(await _.listTasks({status:X.status,priority:X.priority,type:X.type,include_archived:X.include_archived,limit:9999,offset:0})).tasks;if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(X.status)Y=Y.filter((G)=>G.status===X.status);if(X.priority)Y=Y.filter((G)=>G.priority===X.priority);if(X.type)Y=Y.filter((G)=>G.type===X.type);if(!X.include_archived)Y=Y.filter((G)=>G.status!=="archived")}let Q=Qz(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)Q=H6(Q,X.depth);let W=U6(Q);return{success:!0,output:JSON.stringify({total:W,truncated:!1,depth:X.depth,parent_task_id:J,nodes:Q}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}var q1=M.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),K$=100,N$=500,B1=5000,Wz=1,H1=200,R6=M.string().min(K$,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${K$} \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(N$,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${N$} \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 ${K$}-${N$} \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"),f6=M.string().min(Wz,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(H1,{message:`milestone_title \u8D85\u8FC7 ${H1} \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"),L6=M.string().max(B1,{message:`milestone_description \u8D85\u8FC7 ${B1} \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"),Gz=M.object({task_id:M.number().describe("Task ID"),milestone_type:q1.optional(),milestone_title:f6.optional(),milestone_description:L6,process_description:R6.optional(),action_type:q1.optional(),action_title:M.string().min(1).max(H1).optional(),action_description:M.string().max(B1).optional(),md_path:M.string().optional().describe("Path to detailed markdown documentation")}),z6=Gz.transform((_)=>{let w=[],$=_.milestone_type,X=_.milestone_title,Y=_.milestone_description;if(!$&&_.action_type)$=_.action_type,w.push("action_type");if(!X&&_.action_title)X=_.action_title,w.push("action_title");if(Y===void 0&&_.action_description!==void 0)Y=_.action_description,w.push("action_description");return{task_id:_.task_id,milestone_type:$,milestone_title:X,milestone_description:Y,process_description:_.process_description,md_path:_.md_path,_deprecated_fields_used:w}}),V6=M.object({operation_id:M.number().describe("Operation ID")}),O6=M.object({task_id:M.number().describe("Task ID"),milestone_type:q1.optional(),action_type:q1.optional(),limit:M.number().optional().default(20),offset:M.number().optional().default(0)}).transform((_)=>{let w=[],$=_.milestone_type;if(!$&&_.action_type)$=_.action_type,w.push("action_type");return{task_id:_.task_id,milestone_type:$,limit:_.limit,offset:_.offset,_deprecated_fields_used:w}}),Dz=M.object({operation_id:M.number().describe("Operation ID"),milestone_title:f6.optional(),milestone_description:L6,process_description:R6.optional(),action_title:M.string().min(1).max(H1).optional(),action_description:M.string().max(B1).optional()}),M6=Dz.transform((_)=>{let w=[],$=_.milestone_title,X=_.milestone_description;if(!$&&_.action_title)$=_.action_title,w.push("action_title");if(X===void 0&&_.action_description!==void 0)X=_.action_description,w.push("action_description");return{operation_id:_.operation_id,milestone_title:$,milestone_description:X,process_description:_.process_description,_deprecated_fields_used:w}}),A6=M.object({operation_id:M.number().describe("Operation ID")});function qz(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function Bz(_){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 n0(_){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:z6,execute:async(w,$)=>{let X;try{X=z6.parse(w)}catch(Q){if(Q instanceof Q_)return{success:!1,output:"",error:qz(Q),metadata:{execution_time_ms:0}};throw Q}let Y=Bz(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let J=$.session_id||"unknown";try{let Q=await _.createOperation({taskId:X.task_id,sessionId:J,milestoneType:Y.milestoneType,milestoneTitle:Y.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),W=`Operation created: #${Q.id} for task #${Q.taskId} [milestone=${Q.milestoneType}] ${Q.milestoneTitle}`,G=[];if(X._deprecated_fields_used.length>0)G.push(`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_type / milestone_title / milestone_description \u4E3B\u5B57\u6BB5\u3002");if(G.length>0)W+=`
|
|
2430
2469
|
|
|
2431
2470
|
`+G.join(`
|
|
2432
|
-
`);return{success:!0,output:W,metadata:{execution_time_ms:0,operation_id:
|
|
2471
|
+
`);return{success:!0,output:W,metadata:{execution_time_ms:0,operation_id:Q.id,task_id:Q.taskId,session_id:Q.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(Q){return{success:!1,output:"",error:Q instanceof Error?Q.message:String(Q),metadata:{execution_time_ms:0}}}}}}function b$(_){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:V6,execute:async(w,$)=>{let X=V6.parse(w);try{let Y=await _.getOperation(X.operation_id);if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function r0(_){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:O6,execute:async(w,$)=>{let X=O6.parse(w);try{let Y=await _.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),J=JSON.stringify({operations:Y,count:Y.length});if(X._deprecated_fields_used.length>0)J=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
|
|
2433
2472
|
|
|
2434
|
-
`+J;return{success:!0,output:J,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function
|
|
2473
|
+
`+J;return{success:!0,output:J,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function Hz(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function j$(_){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:M6,execute:async(w,$)=>{let X;try{X=M6.parse(w)}catch(Y){if(Y instanceof Q_)return{success:!1,output:"",error:Hz(Y),metadata:{execution_time_ms:0}};throw Y}try{let Y=await _.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!Y)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let J=`Operation updated: #${Y.id}`;if(X._deprecated_fields_used.length>0)J+=`
|
|
2435
2474
|
|
|
2436
|
-
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:J,metadata:{execution_time_ms:0,operation:Y,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function
|
|
2437
|
-
`)}var r0=()=>{},z6={};o_(z6,{runMigration:()=>dU});function dU(_){o(`[Migration 001] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw $}try{w.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw $}o("[Migration 001] Migration completed successfully")}finally{w.close()}}var pU=r(()=>{Ww(),r0()}),V6={};o_(V6,{runMigration:()=>iU});function iU(_){o(`[Migration 002] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw $}o("[Migration 002] Migration completed successfully")}finally{w.close()}}var nU=r(()=>{Ww(),r0()}),O6={};o_(O6,{runMigration:()=>rU});function rU(_){o(`[Migration 003] Starting migration for: ${_}`);let w=w0(_);try{try{w.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw $}o("[Migration 003] Migration completed successfully")}finally{w.close()}}var aU=r(()=>{Ww(),r0()}),A6={};o_(A6,{runMigration:()=>oU});function oU(_){o(`[Migration 004] Starting migration for: ${_}`);let w=w0(_);try{let $=new Set,X=w.query("PRAGMA table_info(task_operation)").all();for(let Y of X)$.add(Y.name);for(let{oldName:Y,newName:J}of M6){let D=$.has(Y),W=$.has(J);if(D&&!W)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(W)o(`[Migration 004] ${J} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${J}`)}o("[Migration 004] Migration completed successfully")}finally{w.close()}}var M6,sU=r(()=>{Ww(),r0(),M6=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),R6={};o_(R6,{runMigration:()=>tU});function tU(_){o(`[Migration 005] Starting migration for: ${_}`);let w=w0(_),$={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(w.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return o("[Migration 005] task table does not exist, skipping"),$;let Y=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if($.blobCountBefore=Y[0]?.cnt??0,$.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),$;w.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),$.ran=!0;let J=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();$.blobCountAfter=J[0]?.cnt??0,o(`[Migration 005] Converted ${$.blobCountBefore-$.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{w.close()}return $}var eU=r(()=>{Ww(),r0()});function _z(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function w0(_){let w=_z();return wz(new w(_))}function wz(_){if(typeof _.run!=="function")_.run=function(w,...$){if($.length>0)return this.prepare(w).run(...$);else return this.exec(w)};return _.query=function(w,...$){if($.length===0){let Y=this.prepare(w);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(w);return{all:(...Y)=>X.all(...$,...Y),get:(...Y)=>X.get(...$,...Y),run:(...Y)=>X.run(...$,...Y)}},_}function $z(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return f6(_,".local","share")}function q2(){return f6($z(),"roy-agent","tasks.db")}var Lw,Fw,Ww=r(()=>{a(),V_(),Lw=n("task:store"),Fw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||q2()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=e("fs"),X=e("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=w0(this.dbPath),this.db.run(`
|
|
2475
|
+
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:J,metadata:{execution_time_ms:0,operation:Y,deprecated_fields_used:X._deprecated_fields_used}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function E$(_){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:A6,execute:async(w,$)=>{let X=A6.parse(w);try{if(!await _.deleteOperation(X.operation_id))return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:`Operation deleted: #${X.operation_id}`,metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}import{join as P6}from"path";function o(_){F6.warn(_)}var F6,a0=r(()=>{a(),F6=n("task:migration")}),K6={};s_(K6,{runMigration:()=>Uz});function Uz(_){o(`[Migration 001] Starting migration for: ${_}`);let w=$0(_);try{try{w.run("ALTER TABLE task ADD COLUMN project_path TEXT"),o("[Migration 001] Added project_path column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] project_path column already exists, skipping");else throw $}try{w.run("ALTER TABLE task ADD COLUMN context TEXT"),o("[Migration 001] Added context column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 001] context column already exists, skipping");else throw $}o("[Migration 001] Migration completed successfully")}finally{w.close()}}var zz=r(()=>{Gw(),a0()}),N6={};s_(N6,{runMigration:()=>Vz});function Vz(_){o(`[Migration 002] Starting migration for: ${_}`);let w=$0(_);try{try{w.run("ALTER TABLE task ADD COLUMN type TEXT NOT NULL DEFAULT 'normal'"),o("[Migration 002] Added type column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 002] type column already exists, skipping");else throw $}o("[Migration 002] Migration completed successfully")}finally{w.close()}}var Oz=r(()=>{Gw(),a0()}),b6={};s_(b6,{runMigration:()=>Mz});function Mz(_){o(`[Migration 003] Starting migration for: ${_}`);let w=$0(_);try{try{w.run("ALTER TABLE task_operation ADD COLUMN process_description TEXT NOT NULL DEFAULT ''"),o("[Migration 003] Added process_description column")}catch($){if($.message?.includes("duplicate column name"))o("[Migration 003] process_description column already exists, skipping");else throw $}o("[Migration 003] Migration completed successfully")}finally{w.close()}}var Az=r(()=>{Gw(),a0()}),j6={};s_(j6,{runMigration:()=>Rz});function Rz(_){o(`[Migration 004] Starting migration for: ${_}`);let w=$0(_);try{let $=new Set,X=w.query("PRAGMA table_info(task_operation)").all();for(let Y of X)$.add(Y.name);for(let{oldName:Y,newName:J}of E6){let Q=$.has(Y),W=$.has(J);if(Q&&!W)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(W)o(`[Migration 004] ${J} already exists, skipping rename of ${Y}`);else o(`[Migration 004] ${Y} not present, skipping rename to ${J}`)}o("[Migration 004] Migration completed successfully")}finally{w.close()}}var E6,fz=r(()=>{Gw(),a0(),E6=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),S6={};s_(S6,{runMigration:()=>Lz});function Lz(_){o(`[Migration 005] Starting migration for: ${_}`);let w=$0(_),$={blobCountBefore:0,blobCountAfter:0,ran:!1};try{if(w.query("SELECT name FROM sqlite_master WHERE type='table' AND name='task'").all().length===0)return o("[Migration 005] task table does not exist, skipping"),$;let Y=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();if($.blobCountBefore=Y[0]?.cnt??0,$.blobCountBefore===0)return o("[Migration 005] No BLOB descriptions found, no action needed"),$;w.run("UPDATE task SET description = CAST(description AS TEXT) WHERE typeof(description) = 'blob'"),$.ran=!0;let J=w.query("SELECT COUNT(*) as cnt FROM task WHERE typeof(description) = 'blob'").all();$.blobCountAfter=J[0]?.cnt??0,o(`[Migration 005] Converted ${$.blobCountBefore-$.blobCountAfter} BLOB description(s) to TEXT`),o("[Migration 005] Migration completed successfully")}finally{w.close()}return $}var Fz=r(()=>{Gw(),a0()});function Kz(){if(typeof Bun<"u"){let{Database:_}=e("bun:sqlite");return _}try{let{DatabaseSync:_}=e("node:sqlite");if(typeof _==="function")return _}catch{}return e("better-sqlite3")}function $0(_){let w=Kz();return Nz(new w(_))}function Nz(_){if(typeof _.run!=="function")_.run=function(w,...$){if($.length>0)return this.prepare(w).run(...$);else return this.exec(w)};return _.query=function(w,...$){if($.length===0){let Y=this.prepare(w);return{all:()=>Y.all(),get:()=>Y.get(),run:()=>Y.run()}}let X=this.prepare(w);return{all:(...Y)=>X.all(...$,...Y),get:(...Y)=>X.get(...$,...Y),run:(...Y)=>X.run(...$,...Y)}},_}function bz(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return P6(_,".local","share")}function U1(){return P6(bz(),"roy-agent","tasks.db")}var Fw,Kw,Gw=r(()=>{a(),H_(),Fw=n("task:store"),Kw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||U1()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=e("fs"),X=e("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=$0(this.dbPath),this.db.run(`
|
|
2438
2476
|
CREATE TABLE IF NOT EXISTS task (
|
|
2439
2477
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2440
2478
|
title TEXT NOT NULL,
|
|
@@ -2482,16 +2520,16 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2482
2520
|
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
2483
2521
|
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
2484
2522
|
)
|
|
2485
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)"),this.dbPath!==":memory:"){try{let{runMigration:w}=(
|
|
2523
|
+
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_tag_relation_tag_id ON task_tag_relation(tag_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_parent_task_id ON task(parent_task_id)"),this.dbPath!==":memory:"){try{let{runMigration:w}=(zz(),uw(K6));w(this.dbPath)}catch(w){Fw.warn(`[Migration 001] Failed to run: ${w.message}`)}try{let{runMigration:w}=(Oz(),uw(N6));w(this.dbPath)}catch(w){Fw.warn(`[Migration 002] Failed to run: ${w.message}`)}try{let{runMigration:w}=(Az(),uw(b6));w(this.dbPath)}catch(w){Fw.warn(`[Migration 003] Failed to run: ${w.message}`)}try{let{runMigration:w}=(fz(),uw(j6));w(this.dbPath)}catch(w){Fw.warn(`[Migration 004] Failed to run: ${w.message}`)}try{let{runMigration:w}=(Fz(),uw(S6));w(this.dbPath)}catch(w){Fw.warn(`[Migration 005] Failed to run: ${w.message}`)}}this.initialized=!0,Fw.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(w){await this.initialize();let $=Date.now(),Y=this.db.prepare(`
|
|
2486
2524
|
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
2487
2525
|
goals_and_expected_deliverables, due_date, tags, status,
|
|
2488
2526
|
current_status, created_at, updated_at, project_path, context)
|
|
2489
2527
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
|
|
2490
|
-
`).run(w.title,w.description||"",w.priority||"medium",w.type||"normal",w.parent_task_id||null,w.goals_and_expected_deliverables||"",w.due_date||null,w.tags?JSON.stringify(w.tags):null,$,$,w.project_path,w.context),J=await this.getTask(Y.lastInsertRowid);if(J)return this.tasksCache.set(J.id,J),J;throw Error("Failed to create task")}async getTask(w){if(await this.initialize(),this.tasksCache.has(w))return this.tasksCache.get(w);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(w);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(w,Y),Y}async updateTask(w,$){await this.initialize();let X=await this.getTask(w);if(!X)return;let Y=[],J=[];if($.title!==void 0)Y.push("title = ?"),J.push($.title);if($.description!==void 0)Y.push("description = ?"),J.push($.description);if($.status!==void 0)Y.push("status = ?"),J.push($.status);if($.priority!==void 0)Y.push("priority = ?"),J.push($.priority);if($.type!==void 0)Y.push("type = ?"),J.push($.type);if($.progress!==void 0)Y.push("progress = ?"),J.push($.progress);if($.current_status!==void 0)Y.push("current_status = ?"),J.push($.current_status);if($.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),J.push($.goals_and_expected_deliverables);if($.due_date!==void 0)Y.push("due_date = ?"),J.push($.due_date);if($.tags!==void 0)Y.push("tags = ?"),J.push(JSON.stringify($.tags));if($.project_path!==void 0)Y.push("project_path = ?"),J.push($.project_path);if($.context!==void 0)Y.push("context = ?"),J.push($.context);if($.parent_task_id!==void 0)Y.push("parent_task_id = ?"),J.push($.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),J.push(Date.now()),J.push(w),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...J),this.tasksCache.delete(w),this.getTask(w)}async deleteTask(w){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(w);if(X.changes>0)this.tasksCache.delete(w),this.operationsCache.delete(w);return X.changes>0}async listTasks(w){if(await this.initialize(),w?.depth!==void 0&&w.depth>=0&&w.parent_task_id===void 0)return this.listTasksByDepth(w);let $=["1=1"],X=[];if(w?.status)$.push("status = ?"),X.push(w.status);if(w?.priority)$.push("priority = ?"),X.push(w.priority);if(w?.type)$.push("type = ?"),X.push(w.type);if(w?.parent_task_id!==void 0)$.push("parent_task_id = ?"),X.push(w.parent_task_id);if(!w?.include_archived&&w?.status!=="archived")$.push("status != 'archived'");let Y=$.join(" AND "),J=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,W=this.db.prepare(J).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${Y}`,
|
|
2528
|
+
`).run(w.title,w.description||"",w.priority||"medium",w.type||"normal",w.parent_task_id||null,w.goals_and_expected_deliverables||"",w.due_date||null,w.tags?JSON.stringify(w.tags):null,$,$,w.project_path,w.context),J=await this.getTask(Y.lastInsertRowid);if(J)return this.tasksCache.set(J.id,J),J;throw Error("Failed to create task")}async getTask(w){if(await this.initialize(),this.tasksCache.has(w))return this.tasksCache.get(w);let X=this.db.prepare("SELECT * FROM task WHERE id = ?").get(w);if(!X)return;let Y=this.rowToTask(X);return this.tasksCache.set(w,Y),Y}async updateTask(w,$){await this.initialize();let X=await this.getTask(w);if(!X)return;let Y=[],J=[];if($.title!==void 0)Y.push("title = ?"),J.push($.title);if($.description!==void 0)Y.push("description = ?"),J.push($.description);if($.status!==void 0)Y.push("status = ?"),J.push($.status);if($.priority!==void 0)Y.push("priority = ?"),J.push($.priority);if($.type!==void 0)Y.push("type = ?"),J.push($.type);if($.progress!==void 0)Y.push("progress = ?"),J.push($.progress);if($.current_status!==void 0)Y.push("current_status = ?"),J.push($.current_status);if($.goals_and_expected_deliverables!==void 0)Y.push("goals_and_expected_deliverables = ?"),J.push($.goals_and_expected_deliverables);if($.due_date!==void 0)Y.push("due_date = ?"),J.push($.due_date);if($.tags!==void 0)Y.push("tags = ?"),J.push(JSON.stringify($.tags));if($.project_path!==void 0)Y.push("project_path = ?"),J.push($.project_path);if($.context!==void 0)Y.push("context = ?"),J.push($.context);if($.parent_task_id!==void 0)Y.push("parent_task_id = ?"),J.push($.parent_task_id);if(Y.length===0)return X;return Y.push("updated_at = ?"),J.push(Date.now()),J.push(w),this.db.prepare(`UPDATE task SET ${Y.join(", ")} WHERE id = ?`).run(...J),this.tasksCache.delete(w),this.getTask(w)}async deleteTask(w){await this.initialize();let X=this.db.prepare("DELETE FROM task WHERE id = ?").run(w);if(X.changes>0)this.tasksCache.delete(w),this.operationsCache.delete(w);return X.changes>0}async listTasks(w){if(await this.initialize(),w?.depth!==void 0&&w.depth>=0&&w.parent_task_id===void 0)return this.listTasksByDepth(w);let $=["1=1"],X=[];if(w?.status)$.push("status = ?"),X.push(w.status);if(w?.priority)$.push("priority = ?"),X.push(w.priority);if(w?.type)$.push("type = ?"),X.push(w.type);if(w?.parent_task_id!==void 0)$.push("parent_task_id = ?"),X.push(w.parent_task_id);if(!w?.include_archived&&w?.status!=="archived")$.push("status != 'archived'");let Y=$.join(" AND "),J=`SELECT COUNT(*) as total FROM task WHERE ${Y}`,W=this.db.prepare(J).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${Y}`,D=[...X];if(G+=" ORDER BY updated_at DESC",w?.limit)G+=" LIMIT ?",D.push(w.limit);if(w?.offset)G+=" OFFSET ?",D.push(w.offset);return{tasks:this.db.prepare(G).all(...D).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z}),total:W}}async listTasksByDepth(w){let $=w.depth??0,X=["1=1"],Y=[];if(w.status)X.push("status = ?"),Y.push(w.status);if(w.priority)X.push("priority = ?"),Y.push(w.priority);if(w.type)X.push("type = ?"),Y.push(w.type);if(!w?.include_archived&&w?.status!=="archived")X.push("status != 'archived'");let J=X.join(" AND "),Q=[];if($===0){let H=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`,B=this.db.prepare(H).all(...Y);for(let O of B){let z=this.rowToTask(O);this.tasksCache.set(z.id,z),Q.push(z)}}else{let B=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`).all(...Y).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z});Q.push(...B);for(let O=1;O<=$;O++){if(B.length===0)break;let z=B.map((L)=>L.id),V=`SELECT * FROM task WHERE parent_task_id IN (${z.map(()=>"?").join(",")}) AND ${J} ORDER BY updated_at DESC`,R=this.db.prepare(V).all(...z,...Y).map((L)=>{let N=this.rowToTask(L);return this.tasksCache.set(N.id,N),N});Q.push(...R),B=R}}let W=Q.length,G=w.offset??0,D=w.limit??W;return{tasks:Q.slice(G,G+D),total:W}}async getTaskTree(w,$=-1){await this.initialize();let X=[],Y=[w],J=0;while(Y.length>0){if($!==-1&&J>=$)break;let Q=Y.map(()=>"?").join(","),W=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${Q}) ORDER BY updated_at DESC`).all(...Y),G=[];for(let D of W){let q=this.rowToTask(D);this.tasksCache.set(q.id,q),X.push(q),G.push(q.id)}Y=G,J++}return X}async getChildTasks(w,$={}){return this.listTasks({...$,parent_task_id:w})}async createOperation(w){await this.initialize();let $=w.milestoneType??w.actionType,X=w.milestoneTitle??w.actionTitle,Y=w.milestoneDescription??w.actionDescription;if(!$||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let J=Date.now(),W=this.db.prepare(`
|
|
2491
2529
|
INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
|
|
2492
2530
|
milestone_description, process_description, timestamp, md_path)
|
|
2493
2531
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
2494
|
-
`).run(w.taskId,w.sessionId,$,X,Y||"",w.processDescription||"",J,w.mdPath||null);this.operationsCache.delete(w.taskId);let G=await this.getOperation(W.lastInsertRowid);if(!G)throw Error("Failed to create operation");return G}async getOperation(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(w);if(!X)return;return this.rowToOperation(X)}async updateOperation(w,$){await this.initialize();let X=await this.getOperation(w);if(!X)return;let Y=$.milestoneTitle??$.actionTitle,J=$.milestoneDescription??$.actionDescription,
|
|
2532
|
+
`).run(w.taskId,w.sessionId,$,X,Y||"",w.processDescription||"",J,w.mdPath||null);this.operationsCache.delete(w.taskId);let G=await this.getOperation(W.lastInsertRowid);if(!G)throw Error("Failed to create operation");return G}async getOperation(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_operation WHERE id = ?").get(w);if(!X)return;return this.rowToOperation(X)}async updateOperation(w,$){await this.initialize();let X=await this.getOperation(w);if(!X)return;let Y=$.milestoneTitle??$.actionTitle,J=$.milestoneDescription??$.actionDescription,Q=[],W=[];if(Y!==void 0)Q.push("milestone_title = ?"),W.push(Y);if(J!==void 0)Q.push("milestone_description = ?"),W.push(J);if($.processDescription!==void 0)Q.push("process_description = ?"),W.push($.processDescription);if(Q.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${Q.join(", ")} WHERE id = ?`).run(...W,w),this.operationsCache.delete(X.taskId),this.getOperation(w)}async deleteOperation(w){await this.initialize();let $=await this.getOperation(w);if(!$)return!1;let Y=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(w);if(Y.changes>0)this.operationsCache.delete($.taskId);return Y.changes>0}async listOperations(w){await this.initialize();let $=w.taskId;if(!this.operationsCache.has($)){let G=this.db.prepare("SELECT * FROM task_operation WHERE task_id = ? ORDER BY timestamp DESC").all(w.taskId);this.operationsCache.set($,G.map((D)=>this.rowToOperation(D)))}let X=this.operationsCache.get($),Y=w.milestoneType??w.actionType;if(Y)X=X.filter((W)=>W.milestoneType===Y);let J=w.offset||0,Q=w.limit||20;return X.slice(J,J+Q)}async getTaskIdBySessionId(w){if(await this.initialize(),!w)return;let $=this.db.prepare("SELECT task_id FROM task_operation WHERE session_id = ? AND milestone_type = 'create' ORDER BY timestamp ASC LIMIT 1").get(w);return typeof $?.task_id==="number"?$.task_id:void 0}rowToTask(w){return{id:w.id,title:String(w.title??""),description:String(w.description??""),status:String(w.status??"todo"),priority:String(w.priority??"medium"),type:String(w.type??"normal"),progress:w.progress,current_status:String(w.current_status??""),goals_and_expected_deliverables:String(w.goals_and_expected_deliverables??""),parent_task_id:w.parent_task_id||void 0,createdAt:new Date(w.created_at).toISOString(),updatedAt:new Date(w.updated_at).toISOString(),due_date:w.due_date?String(w.due_date):void 0,tags:_.parseTagsSafely(w.tags),project_path:String(w.project_path??"unknown"),context:w.context}}static parseTagsSafely(w){if(w===null||w===void 0||w==="")return;let $=typeof w==="string"?w:String(w);try{let X=JSON.parse($);if(Array.isArray(X))return X;if(typeof X==="string")return[X];return}catch{return[$]}}rowToOperation(w){let $=w.milestone_type??w.action_type,X=w.milestone_title??w.action_title,Y=w.milestone_description??w.action_description??"";return{id:w.id,taskId:w.task_id,sessionId:w.session_id,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:w.process_description??"",timestamp:new Date(w.timestamp).toISOString(),mdPath:w.md_path||void 0,actionType:$,actionTitle:X,actionDescription:Y}}async createTag(w){await this.initialize();let $=Date.now(),X=await this.getTagByName(w);if(X)return X;return{id:this.db.prepare(`
|
|
2495
2533
|
INSERT INTO task_tag (name, created_at, task_count)
|
|
2496
2534
|
VALUES (?, ?, 0)
|
|
2497
2535
|
`).run(w,$).lastInsertRowid,name:w,createdAt:new Date($).toISOString(),taskCount:0}}async getTag(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE id = ?").get(w);if(!X)return;return this.rowToTag(X)}async getTagByName(w){await this.initialize();let X=this.db.prepare("SELECT * FROM task_tag WHERE name = ?").get(w);if(!X)return;return this.rowToTag(X)}async listTags(w){await this.initialize();let $="SELECT * FROM task_tag",X=[],Y=w?.orderBy||"count";if(Y==="count")$+=" ORDER BY task_count DESC";else if(Y==="name")$+=" ORDER BY name ASC";else $+=" ORDER BY created_at DESC";if(w?.limit)$+=" LIMIT ?",X.push(w.limit);if(w?.offset)$+=" OFFSET ?",X.push(w.offset);return this.db.prepare($).all(...X).map((W)=>this.rowToTag(W))}async searchTags(w){await this.initialize();let $=`
|
|
@@ -2515,12 +2553,12 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2515
2553
|
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
2516
2554
|
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
2517
2555
|
WHERE t.name IN (${w.map(()=>"?").join(", ")})
|
|
2518
|
-
`;return this.db.prepare(X).all(...w).map((
|
|
2556
|
+
`;return this.db.prepare(X).all(...w).map((Q)=>Q.task_id)}async updateTaskTags(w,$){await this.initialize();let X=await this.getTagsForTask(w);if(X.length>0)await this.removeTagsFromTask(w,X.map((J)=>J.id));let Y=[];for(let J of $){let Q=await this.getTagByName(J);if(!Q)Q=await this.createTag(J);Y.push(Q.id)}if(Y.length>0)await this.addTagsToTask(w,Y)}async searchTasksByKeywords(w,$={}){if(await this.initialize(),!w||w.length===0)return{tasks:[],total:0};let{limit:X=20,offset:Y=0,excludeTaskId:J,status:Q,priority:W,type:G,depth:D}=$,q=null;if(D!==void 0&&D>=0)q=await this.collectTaskIdsByDepth(D);let H=new Map,B="SELECT * FROM task WHERE 1=1",O=[];if(J)B+=" AND id != ?",O.push(J);if(Q)B+=" AND status = ?",O.push(Q);if(W)B+=" AND priority = ?",O.push(W);if(G)B+=" AND type = ?",O.push(G);if(!$?.include_archived&&$?.status!=="archived")B+=" AND status != 'archived'";let z=Math.max(X*5,200);B+=" ORDER BY updated_at DESC LIMIT ?",O.push(z);let U=this.db.prepare(B).all(...O);for(let E of U){let b=this.rowToTask(E),C=new Set,K=0;if(typeof b.title==="string"&&b.title){let P=b.title.toLowerCase();for(let g of w)if(P.includes(g.toLowerCase()))K++,C.add(g)}if(b.tags&&Array.isArray(b.tags))for(let P of w){let g=P.toLowerCase();if(b.tags.some((i)=>i.toLowerCase().includes(g)))K+=2,C.add(P)}if(typeof b.description==="string"&&b.description){let P=b.description.toLowerCase();for(let g of w)if(P.includes(g.toLowerCase()))K++,C.add(g)}if(typeof b.goals_and_expected_deliverables==="string"&&b.goals_and_expected_deliverables){let P=b.goals_and_expected_deliverables.toLowerCase();for(let g of w)if(P.includes(g.toLowerCase()))K++,C.add(g)}if(C.size===w.length)H.set(b.id,{task:b,matchCount:K})}let V=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let E of V){let C=new Set;for(let i of w){let v=`%${i}%`;if(this.db.prepare(`
|
|
2519
2557
|
SELECT * FROM task_operation
|
|
2520
2558
|
WHERE task_id = ?
|
|
2521
2559
|
AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
|
|
2522
2560
|
LIMIT 10
|
|
2523
|
-
`).all(E.task_id,v,v,v).length>0)
|
|
2561
|
+
`).all(E.task_id,v,v,v).length>0)C.add(i)}if(C.size===0)continue;let K=this.db.prepare("SELECT * FROM task WHERE id = ?").get(E.task_id);if(!K)continue;let P=this.rowToTask(K);if(J&&P.id===J)continue;if(Q&&P.status!==Q)continue;if(W&&P.priority!==W)continue;if(G&&P.type!==G)continue;if(!$?.include_archived&&P.status==="archived")continue;let g=H.get(P.id);if(g)g.matchCount+=2;else{let i=new Set(C);if(typeof P.title==="string"&&P.title){let v=P.title.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof P.description==="string"&&P.description){let v=P.description.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof P.goals_and_expected_deliverables==="string"&&P.goals_and_expected_deliverables){let v=P.goals_and_expected_deliverables.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(P.tags&&Array.isArray(P.tags)){for(let v of w)if(P.tags.some((c)=>c.toLowerCase().includes(v.toLowerCase())))i.add(v)}if(i.size===w.length)H.set(P.id,{task:P,matchCount:2})}}let A=Array.from(H.values()).sort((E,b)=>b.matchCount-E.matchCount);if(q!==null)A=A.filter((E)=>q.has(E.task.id));let R=A.length;return{tasks:A.slice(Y,Y+X).map((E)=>E.task),total:R}}async collectTaskIdsByDepth(w){let $=new Set,Y=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((J)=>J.id);for(let J of Y)$.add(J);if(w===0)return $;for(let J=1;J<=w;J++){if(Y.length===0)break;let Q=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${Q})`).all(...Y).map((G)=>G.id);for(let G of Y)$.add(G)}return $}async findSimilarTasksByKeywords(w,$={}){let X={...$,limit:$.limit??5};return(await this.searchTasksByKeywords(w,X)).tasks}async findSimilarTasks(w,$=5){await this.initialize();let X=await this.getTagsForTask(w);if(X.length===0)return[];let Y=X.map((D)=>D.id),Q=`
|
|
2524
2562
|
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
2525
2563
|
FROM task t
|
|
2526
2564
|
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
@@ -2530,21 +2568,21 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
2530
2568
|
GROUP BY t.id
|
|
2531
2569
|
ORDER BY match_count DESC, t.updated_at DESC
|
|
2532
2570
|
LIMIT ?
|
|
2533
|
-
`;return this.db.prepare(
|
|
2571
|
+
`;return this.db.prepare(Q).all(...Y,w,$).map((D)=>this.rowToTask(D))}async searchTasks(w,$=20){await this.initialize();let X=`
|
|
2534
2572
|
SELECT * FROM task
|
|
2535
2573
|
WHERE title LIKE ? OR description LIKE ?
|
|
2536
2574
|
ORDER BY updated_at DESC
|
|
2537
2575
|
LIMIT ?
|
|
2538
|
-
`;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((
|
|
2576
|
+
`;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((Q)=>this.rowToTask(Q))}async findTasksByContextValue(w,$=50){if(await this.initialize(),!w)return[];let X=`
|
|
2539
2577
|
SELECT * FROM task
|
|
2540
2578
|
WHERE context LIKE ?
|
|
2541
2579
|
ORDER BY updated_at DESC
|
|
2542
2580
|
LIMIT ?
|
|
2543
|
-
`;return this.db.prepare(X).all(`%${w}%`,$).map((J)=>this.rowToTask(J))}rowToTag(w){return{id:w.id,name:w.name,createdAt:new Date(w.created_at).toISOString(),taskCount:w.task_count}}async syncTaskTagsJson(w){let X=(await this.getTagsForTask(w)).map((J)=>J.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,w),this.tasksCache.delete(w)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"searchTasksByKeywords",null)});function L6(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let Y=$.replace(/-/g,"_").toUpperCase(),J=_.slice(X.length);if(J.startsWith("_"))J=J.slice(1);if(!J)return;let D=J.indexOf("_"),W;if(D===-1)W=J;else{let Q=J.slice(0,D),q=J.slice(D+1);if(Q===Y)W=q;else W=J}if(!W)return;let G=W.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function F6(_,w){return{..._,execute:w}}var Xz=()=>{},K6=r(()=>{Xz(),W$(),_0()});K6();class F${_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new Y2}getStatus(){return this._status}getConfig(){return{name:this.name,version:this.version,enabled:this._enabled,env:this.env}}isEnvInitialized(){return this._status!=="created"}setStatus(_){this._status=_}getEnv(){return this.env}async init(_){if(_?.env)this.env=_.env;this.setStatus("initializing");try{if(_?.name)Object.defineProperty(this,"name",{value:_.name,writable:!1});if(_?.version)Object.defineProperty(this,"version",{value:_.version,writable:!1})}catch{}if(_?.enabled!==void 0)this._enabled=_.enabled;this.hookManager.setComponentInfo(this.name,this.version),await this.onInit(),this.setStatus("running")}async start(){if(this._started)return;this._started=!0,await this.onStart(),this.setStatus("running")}async stop(){this.setStatus("stopping"),this.hookManager.clear(),await this.onStop(),this.setStatus("stopped")}async onInit(){}async onStart(){}async onStop(){}registerHook(_,w){this.hookManager.register(_,w)}addHook(_,w,$,X){this.hookManager.register(_,F6({name:w,priority:X},$))}removeHook(_,w){return this.hookManager.unregister(_,w)}async executeHooks(_,w,$){await this.hookManager.execute(_,w,$)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig(_,w){let $=this.getConfigComponent();if($){let X=$.get(_);if(X!==void 0)return X}return w}}a();var Yz={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Jz={name:"task",sources:[{type:"env",envPrefix:"TASK",priority:20,watch:!1}],keys:[{key:"task.storage.type",sources:["env","file"]},{key:"task.storage.dbPath",sources:["env","file"]}]};_0();var Dz=["completed","failed","cancelled","timeout"];Dw();a();var a0=n("task:tag");class N6{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return a0.debug(`[TagService] Created tag: ${w.name} (id=${w.id})`),w}async getTag(_){return this.store.getTag(_)}async getTagByName(_){return this.store.getTagByName(_)}async listTags(_){return this.store.listTags(_)}async searchTags(_){return this.store.searchTags(_)}async deleteTag(_){let w=await this.store.deleteTag(_);if(w)a0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),a0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),a0.debug(`[TagService] Removed ${w.length} tags from task ${_}`)}async getTagsForTask(_){return this.store.getTagsForTask(_)}async getTaskIdsByTags(_){return this.store.getTaskIdsByTags(_)}async findSimilarTasks(_,w=5){return this.store.findSimilarTasks(_,w)}async searchTasks(_,w=20){return this.store.searchTasks(_,w)}async searchTasksByKeywords(_,w){return(await this.store.searchTasksByKeywords(_,w)).tasks}async findSimilarTasksByKeywords(_,w){return this.store.findSimilarTasksByKeywords(_,w)}async syncTagsToTask(_,w){let $=[];for(let G of w){let Q=await this.store.getTagByName(G);if(!Q)Q=await this.store.createTag(G);$.push(Q.id)}let X=await this.store.getTagsForTask(_),Y=new Set(X.map((G)=>G.id)),J=new Set($),D=$.filter((G)=>!Y.has(G)),W=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(W.length>0)await this.store.removeTagsFromTask(_,W);if(D.length>0)await this.store.addTagsToTask(_,D);await this.store.updateTaskTags(_,w),a0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}V_();var J_=n("task"),Wz="Deliverable: ";function Gz(_){if(!_)return;return`${Wz}${_}`}class Kw extends F${name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent(_,w,$){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.component",trigger_session_id:$}}),J_.info(`[TaskComponent] Event published: ${_}`)}constructor(){super()}async init(_){await super.init(_);let w=_?.options;if(!w?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=w.configComponent,await this.registerConfig(w),this.setStatus("running"),J_.info("[TaskComponent] Initialized")}async registerConfig(_){let w=this.configComponent;if(!w)return;let{configPath:$,envPrefix:X,config:Y}=_,J=X??"TASK";if(w.registerComponent(Jz),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:J,priority:20,watch:!1}),await w.load("task");for(let D of Object.keys(process.env)){let W=L6(D,J,"task");if(!W)continue;let G=process.env[D];if(G!==void 0)await w.set(W,G)}for(let[D,W]of Object.entries(Yz))if(w.get(D)===void 0)await w.set(D,W);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",q2());if(Y){let D=this.flattenConfig(Y);for(let[W,G]of Object.entries(D))await w.set(W,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new N6(this.store)}async initStore(){let _=this.configComponent;if(!_)return;let w=_.get("task.storage.type")??"sqlite",$=_.get("task.storage.dbPath");if(w==="sqlite")this.store=new Fw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Fw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,Y]of Object.entries(_)){let J=`${w}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign($,this.flattenConfig(Y,J));else $[J]=Y}return $}registerConfigWatcher(_){if(typeof _.watch!=="function")return;this.configWatcher=_.watch("task.*",(w)=>{this.onConfigChange(w)})}onConfigChange(_){if(J_.info(`[TaskComponent] Config changed: ${_.key}`,{oldValue:_.oldValue,newValue:_.newValue}),_.key==="task.storage.type"||_.key==="task.storage.dbPath")this.initStore()}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new w_(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(G1(this.backgroundTaskManager),"built-in"),J_.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else J_.warn("[TaskComponent] ToolComponent not found, skipping tool registration")}async stop(){if(this.configWatcher)this.configWatcher(),this.configWatcher=void 0;if(this.toolComponent)try{this.toolComponent.register(G1(null),"built-in"),J_.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch(_){J_.warn(`[TaskComponent] Failed to reset query_background_process tool: ${_.message}`)}if(this.backgroundTaskManager)this.backgroundTaskManager.dispose(),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let _=[x0(this),m0(this),u0(this),p0(this),l0(this),z$(this),V$(this),c0(this),O$(this),d0(this)],w=[i0(this),R$(this),n0(this),f$(this),L$(this)],$=[d5(this),$4(this.backgroundTaskManager)];for(let X of[..._,...w,...$])this.toolComponent.register(X),J_.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook(_,w,$={}){let X={component:{name:this.name,version:this.version},data:w,metadata:$,phase:_.includes("before")?"before":"after",hookPoint:_};await E_.execute(_,w,$)}async createTask(_){let w=_.sessionId;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){if(!await this.store.getTask(_.parent_task_id))throw Error(`Parent task #${_.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let $={options:{..._},sessionId:w,tagService:this.tagService};await this.executeHook($_.BEFORE_CREATE,$);let X=await this.store.createTask($.options);await this.store.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook($_.AFTER_CREATE,Y),this.publishEvent(fw.CREATED,{task:X,sessionId:w},w),J_.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask(_){return this.store.getTask(_)}async getTaskIdBySessionId(_){return this.store.getTaskIdBySessionId(_)}async getTaskWithOperations(_){let w=await this.store.getTask(_);if(!w)return;let $=await this.store.listOperations({taskId:_});return{...w,operations:$,task:w}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook($_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let Y={task:X,changes:w,tagService:this.tagService};if(await this.executeHook($_.AFTER_UPDATE,Y),this.publishEvent(fw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Dz.includes(w.status)){let J=$2(),D={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,D),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook($_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook($_.AFTER_DELETE,X),$)this.publishEvent(fw.DELETED,{taskId:_,sessionId:""},""),J_.info(`[TaskComponent] Task deleted: ${_}`);return $}async listTasks(_){return this.store.listTasks(_)}async searchTasksByKeywords(_,w){return this.store.searchTasksByKeywords(_,w||{})}async getTaskTree(_,w=-1){return this.store.getTaskTree(_,w)}async getChildTasks(_,w){return this.store.getChildTasks(_,w)}async completeTask(_,w,$){let X=await this.store.getTask(_);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${_} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($){let D={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))D=W}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}D.deliverable_storage_path=$,Y.context=JSON.stringify(D)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Gz($)}),this.publishEvent(fw.COMPLETED,{task:J,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return J}async createOperation(_){let w={options:{..._}};await this.executeHook($_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),Y={operation:$};return await this.executeHook($_.OPERATION_AFTER_CREATE,Y,{task:X,operation:$}),this.publishEvent(fw.OPERATION_ADDED,{operation:$,taskId:$.taskId},$.sessionId),J_.info(`[TaskComponent] Operation created: ${$.id} for task ${$.taskId}`),$}async getOperation(_){return this.store.getOperation(_)}async updateOperation(_,w){return this.store.updateOperation(_,w)}async deleteOperation(_){return this.store.deleteOperation(_)}async listOperations(_){return this.store.listOperations(_)}getTagService(){return this.tagService}registerHook(_,w){E_.register(_,w),this.plugins.set(this.makePluginKey(_,w.name),w),J_.debug(`[TaskComponent] Registered hook: ${w.name} at ${_}`)}registerHooks(_){for(let{hookPoint:w,hook:$}of _)this.registerHook(w,$)}unregisterHook(_,w){let $=E_.unregister(_,w);if($)this.plugins.delete(this.makePluginKey(_,w)),J_.info(`[TaskComponent] Unregistered hook: ${w} from ${_}`);return $}listHooks(){return Array.from(this.plugins.values())}makePluginKey(_,w){return`${_}::${w}`}countHooks(_){return E_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],Kw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"createOperation",null);var K$=A.enum(["todo","active","completed","paused","cancelled","archived"]),N$=A.enum(["low","medium","high"]),b$=A.enum(["normal","cycle","longterm"]),j$=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Qz=A.object({storage:A.object({type:A.enum(["memory","sqlite"]).default("sqlite"),dbPath:A.string().optional()}).default({})}).default({});Ww();Ww();var qz="Deliverable: ";function Hz(_){if(!_)return;return`${qz}${_}`}var H2=1e6;class E${port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=Bz(_);if(w!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(w);return(await this.scanAllTasks()).find(($)=>$.id===w)??null}return await this.port.getTask(String(_))}toTask(_){let{nativeId:w,...$}=_;return $}toOperation(_){let{nativeId:w,...$}=_;return $}async scanAllTasks(){return(await this.port.listTasks({limit:H2,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let Y=await this.resolve(_.parent_task_id);if(!Y)throw Error(`Parent task #${_.parent_task_id} not found.`);$=Y.id}let X=await this.port.createTask({title:_.title,description:_.description,priority:_.priority,type:_.type,goals_and_expected_deliverables:_.goals_and_expected_deliverables,...$!==void 0?{parent_task_id:$}:{},due_date:_.due_date,tags:_.tags,project_path:_.project_path,context:_.context,sessionId:w});return await this.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask(_){let w=await this.resolve(_);return w?this.toTask(w):null}async getTaskWithOperations(_){let w=await this.getTask(_);if(!w)return null;let $=await this.listOperations({taskId:w.id,limit:H2,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,_),{tasks:X.slice($,$+w),total:X.length}}async updateTask(_,w){let $=await this.resolve(_);if(!$)return null;let X;if(w.parent_task_id!==void 0)if(w.parent_task_id===null)X=null;else{let J=await this.resolve(w.parent_task_id);if(!J)throw Error(`Parent task #${w.parent_task_id} not found.`);X=J.id}let Y=await this.port.updateTask($.nativeId,{title:w.title,description:w.description,status:w.status,priority:w.priority,type:w.type,progress:w.progress,current_status:w.current_status,goals_and_expected_deliverables:w.goals_and_expected_deliverables,due_date:w.due_date,tags:w.tags,project_path:w.project_path,context:w.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask(_){let w=await this.resolve(_);if(!w)return!1;return await this.port.deleteTask(w.nativeId)}async completeTask(_,w,$){let X=await this.resolve(_);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($)Y.context=zz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let D=Hz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:D??"Task completed",...$?{mdPath:$}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??J)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((Q)=>this.toTask(Q)),Y=new Map;for(let Q of X){if(Q.parent_task_id===void 0)continue;let q=Y.get(Q.parent_task_id)??[];q.push(Q),Y.set(Q.parent_task_id,q)}let J=[],D=new Set([$.id]),W=[$.id],G=0;while(W.length>0){if(w!==-1&&G>=w)break;let Q=[];for(let q of W)for(let H of Y.get(q)??[]){if(D.has(H.id))continue;D.add(H.id),J.push(H),Q.push(H.id)}W=Q,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((W)=>W.id!==w.excludeTaskId);let J=_.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),D=J.length===0?Y:Y.filter((W)=>{let G=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return J.every((Q)=>G.includes(Q))});return{tasks:D.slice(X,X+$),total:D.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",Y=_.milestoneDescription??_.actionDescription??"",J=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(J)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let Y=await this.resolve(_.taskId);if(!Y)return[];let D=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?H2:w,offset:X?0:$})).operations.map((W)=>this.toOperation(W));if(X)D=D.filter((W)=>W.milestoneType===X),D=D.slice($,$+w);return D}async getOperation(_){if(typeof this.port.getOperationByNum==="function"){let $=await this.port.getOperationByNum(_);return $?this.toOperation($):null}let w=await this.scanAllTasks();for(let $ of w){let Y=(await this.port.listOperations({taskNativeId:$.nativeId,limit:H2})).operations.find((J)=>J.id===_);if(Y)return this.toOperation(Y)}return null}async updateOperation(_,w){let $=await this.getOperation(_);if(!$)return null;if(typeof this.port.updateOperationByNum!=="function")return $;let X=await this.port.updateOperationByNum(_,{sessionId:w.sessionId??$.sessionId,milestoneType:w.milestoneType??w.actionType??$.milestoneType,milestoneTitle:w.milestoneTitle??w.actionTitle??$.milestoneTitle,milestoneDescription:w.milestoneDescription??w.actionDescription??$.milestoneDescription,processDescription:w.processDescription??$.processDescription,...w.mdPath!==void 0?{mdPath:w.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation(_){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum(_)}applyFilters(_,w){let $=_;if(w.include_archived!==!0&&w.status!=="archived")$=$.filter((Y)=>Y.status!=="archived");if(w.status!==void 0)$=$.filter((Y)=>Y.status===w.status);if(w.priority!==void 0)$=$.filter((Y)=>Y.priority===w.priority);if(w.type!==void 0)$=$.filter((Y)=>Y.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((Y)=>Y.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let Y=Uz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function Bz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function Uz(_,w){if(w<0)return new Set(_.map((D)=>D.id));let $=new Set(_.map((D)=>D.id)),X=new Map;for(let D of _){let W=D.parent_task_id;if(W===void 0||!$.has(W))continue;let G=X.get(W)??[];G.push(D),X.set(W,G)}let Y=new Set,J=_.filter((D)=>D.parent_task_id===void 0||!$.has(D.parent_task_id));for(let D of J)Y.add(D.id);for(let D=1;D<=w;D++){let W=[];for(let G of J)for(let Q of X.get(G.id)??[]){if(Y.has(Q.id))continue;Y.add(Q.id),W.push(Q)}if(W.length===0)break;J=W}return Y}function zz(_,w){let $={};if(typeof _==="string"&&_.trim().length>0)try{let X=JSON.parse(_);if(X&&typeof X==="object"&&!Array.isArray(X))$=X}catch{}return $.deliverable_storage_path=w,JSON.stringify($)}var Vz=1e6;function Oz(_){let w={};if(_.type!==void 0)w.type=_.type;if(_.progress!==void 0)w.progress=_.progress;if(_.current_status!==void 0)w.current_status=_.current_status;if(_.goals_and_expected_deliverables!==void 0)w.goals_and_expected_deliverables=_.goals_and_expected_deliverables;if(_.project_path!==void 0)w.project_path=_.project_path;if(_.context!==void 0)w.context=_.context;if(_.due_date!==void 0)w.due_date=_.due_date;return w}function o0(_,w,$){if(typeof _.num!=="number")throw Error(`store did not expose a numeric handle for task ${_.id}`);let X=_.roy??{};return{id:_.num,nativeId:_.id,title:_.title,description:_.description??"",status:w.toRoyStatus(_.status),priority:w.toRoyPriority(_.priority),type:X.type??"normal",progress:typeof X.progress==="number"?X.progress:_.status==="done"?100:0,current_status:X.current_status??"",goals_and_expected_deliverables:X.goals_and_expected_deliverables??"",...$!==void 0?{parent_task_id:$}:{},createdAt:_.created_at,updatedAt:_.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:w.toRoyTags(_.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function s0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),Y=String(w.milestoneDescription??w.actionDescription??""),J=w.taskId??_.task_id,D=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:D,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:Y}}function b6(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??Vz;async function D(){let Q=await _.listTasks({limit:J});return new Map(Q.tasks.filter((q)=>typeof q.num==="number").map((q)=>[q.id,q.num]))}async function W(Q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(Q);return(await _.listTasks({limit:J})).tasks.find((H)=>H.num===Q)??null}async function G(Q){let H=[...(await D()).entries()].find(([,B])=>B===Q);if(!H)throw Error(`parent task not found: ${Q}`);return H[0]}return{async createTask(Q){let q=Q.parent_task_id!==void 0?await G(Q.parent_task_id):null,H={type:Q.type??"normal",progress:Q.progress??0,current_status:Q.current_status??"",goals_and_expected_deliverables:Q.goals_and_expected_deliverables??"",project_path:Q.project_path,context:Q.context,...Q.due_date?{due_date:Q.due_date}:{}},B=await _.createTask({title:Q.title,description:Q.description,priority:w.toStorePriority(Q.priority),owner:Y,tags:w.toStoreTags(Q.tags),parent_id:q,session_id:Q.sessionId??"unknown",roy:H});return o0(B,w,Q.parent_task_id)},async getTask(Q){let q=await _.getTask(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async getTaskByNum(Q){let q=await W(Q);if(!q)return null;let H=await D();return o0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async listTasks(Q){let q=await _.listTasks({limit:Q?.limit??20,offset:Q?.offset??0}),H=await D();return{tasks:q.tasks.map((B)=>o0(B,w,B.parent_id?H.get(B.parent_id):void 0)),total:q.total}},async updateTask(Q,q){let H=Oz(q),B=await _.updateTask(Q,{...q.title!==void 0?{title:q.title}:{},...q.description!==void 0?{description:q.description}:{},...q.status!==void 0?{status:w.toStoreStatus(q.status)}:{},...q.priority!==void 0?{priority:w.toStorePriority(q.priority)}:{},...q.tags!==void 0?{tags:w.toStoreTags(q.tags)}:{},...Object.keys(H).length>0?{roy:H}:{}});if(!B)return null;let O;if(q.parent_task_id!==void 0){let U=q.parent_task_id===null?null:await G(q.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(Q,U);O=q.parent_task_id===null?void 0:q.parent_task_id}let z=await _.getTask(Q)??B;if(O===void 0&&z.parent_id)O=(await D()).get(z.parent_id);return o0(z,w,O)},async deleteTask(Q){return await _.deleteTask(Q)},async createOperation(Q){let q=await _.appendOperation({task_id:Q.taskNativeId??String(Q.taskId),type:X,data:{taskId:Q.taskId,sessionId:Q.sessionId,milestoneType:Q.milestoneType,milestoneTitle:Q.milestoneTitle,milestoneDescription:Q.milestoneDescription,processDescription:Q.processDescription,...Q.mdPath?{mdPath:Q.mdPath}:{}}});return s0(q)},async listOperations(Q){let q=await _.listOperations({...Q?.taskNativeId?{task_id:Q.taskNativeId}:{},type:X,limit:Q?.limit??J,offset:Q?.offset??0});return{operations:q.operations.map(s0),total:q.total}},async getOperationByNum(Q){if(typeof _.getOperationByNum!=="function")return null;let q=await _.getOperationByNum(Q);return q?s0(q):null},async updateOperationByNum(Q,q){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(Q);if(!H)return null;let B=s0(H),O=await _.updateOperation(Q,{data:{taskId:B.taskId,sessionId:q.sessionId??B.sessionId,milestoneType:q.milestoneType??B.milestoneType,milestoneTitle:q.milestoneTitle??B.milestoneTitle,milestoneDescription:q.milestoneDescription??B.milestoneDescription,processDescription:q.processDescription??B.processDescription,...q.mdPath??B.mdPath?{mdPath:q.mdPath??B.mdPath}:{}}});return O?s0(O):null},async deleteOperationByNum(Q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(Q)}}}var Az="roy.milestone",Mz={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Rz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function j6(_){return Mz[_]??"pending"}function E6(_){return Rz[_]??"todo"}function S6(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function P6(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function Z6(_){if(!_||_.length===0)return;return _.join(",")}function C6(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var fz={toRoyStatus:(_)=>E6(_),toStoreStatus:(_)=>j6(_),toRoyPriority:(_)=>P6(_),toStorePriority:(_)=>S6(_),toRoyTags:(_)=>C6(_),toStoreTags:(_)=>Z6(_)};function T6(_,w={}){return new E$(b6(_,fz,{operationType:Az,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var FR=K$.options,KR=N$.options,NR=b$.options,bR=j$.options;var k6=Symbol("Let zodToJsonSchema decide on which parser to use");var I6={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},g6=(_)=>typeof _==="string"?{...I6,name:_}:{...I6,..._};var h6=(_)=>{let w=g6(_),$=w.name!==void 0?[...w.basePath,w.definitionPath,w.name]:w.basePath;return{...w,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(w.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...w.basePath,w.definitionPath,X],jsonSchema:void 0}]))}};function S$(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,S$(_,w,X,Y)}var B2=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function s(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?B2(w,_.currentPath):w.join("/")}}function y6(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==K.ZodAny)$.items=k(_.type._def,{...w,currentPath:[...w.currentPath,"items"]});if(_.minLength)d($,"minItems",_.minLength.value,_.minLength.message,w);if(_.maxLength)d($,"maxItems",_.maxLength.value,_.maxLength.message,w);if(_.exactLength)d($,"minItems",_.exactLength.value,_.exactLength.message,w),d($,"maxItems",_.exactLength.value,_.exactLength.message,w);return $}function v6(_,w){let $={type:"integer",format:"int64"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function x6(){return{type:"boolean"}}function U2(_,w){return k(_.type._def,w)}var m6=(_,w)=>{return k(_.innerType._def,w)};function P$(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>P$(_,w,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return Lz(_,w)}}var Lz=(_,w)=>{let $={type:"integer",format:"unix-time"};if(w.target==="openApi3")return $;for(let X of _.checks)switch(X.kind){case"min":d($,"minimum",X.value,X.message,w);break;case"max":d($,"maximum",X.value,X.message,w);break}return $};function u6(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function l6(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function c6(_){return{type:"string",enum:Array.from(_.values)}}var Fz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function d6(_,w){let $=[k(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),k(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((J)=>!!J),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((J)=>{if(Fz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let D=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...G}=J;D=G}else X=void 0;Y.push(D)}}),Y.length?{allOf:Y,...X}:void 0}function p6(_,w){let $=typeof _.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(_.value)?"array":"object"};if(w.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[_.value]};return{type:$==="bigint"?"integer":$,const:_.value}}var Z$=void 0,S_={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(Z$===void 0)Z$=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z$},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function z2(_,w){let $={type:"string"};if(_.checks)for(let X of _.checks)switch(X.kind){case"min":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w);break;case"max":d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"email":switch(w.emailStrategy){case"format:email":P_($,"email",X.message,w);break;case"format:idn-email":P_($,"idn-email",X.message,w);break;case"pattern:zod":q_($,S_.email,X.message,w);break}break;case"url":P_($,"uri",X.message,w);break;case"uuid":P_($,"uuid",X.message,w);break;case"regex":q_($,X.regex,X.message,w);break;case"cuid":q_($,S_.cuid,X.message,w);break;case"cuid2":q_($,S_.cuid2,X.message,w);break;case"startsWith":q_($,RegExp(`^${C$(X.value,w)}`),X.message,w);break;case"endsWith":q_($,RegExp(`${C$(X.value,w)}$`),X.message,w);break;case"datetime":P_($,"date-time",X.message,w);break;case"date":P_($,"date",X.message,w);break;case"time":P_($,"time",X.message,w);break;case"duration":P_($,"duration",X.message,w);break;case"length":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w),d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"includes":{q_($,RegExp(C$(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")P_($,"ipv4",X.message,w);if(X.version!=="v4")P_($,"ipv6",X.message,w);break}case"base64url":q_($,S_.base64url,X.message,w);break;case"jwt":q_($,S_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")q_($,S_.ipv4Cidr,X.message,w);if(X.version!=="v4")q_($,S_.ipv6Cidr,X.message,w);break}case"emoji":q_($,S_.emoji(),X.message,w);break;case"ulid":{q_($,S_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{P_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{q_($,S_.base64,X.message,w);break}}break}case"nanoid":q_($,S_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return $}function C$(_,w){return w.patternStrategy==="escape"?Nz(_):_}var Kz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Nz(_){let w="";for(let $=0;$<_.length;$++){if(!Kz.has(_[$]))w+="\\";w+=_[$]}return w}function P_(_,w,$,X){if(_.format||_.anyOf?.some((Y)=>Y.format)){if(!_.anyOf)_.anyOf=[];if(_.format){if(_.anyOf.push({format:_.format,..._.errorMessage&&X.errorMessages&&{errorMessage:{format:_.errorMessage.format}}}),delete _.format,_.errorMessage){if(delete _.errorMessage.format,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.anyOf.push({format:w,...$&&X.errorMessages&&{errorMessage:{format:$}}})}else d(_,"format",w,$,X)}function q_(_,w,$,X){if(_.pattern||_.allOf?.some((Y)=>Y.pattern)){if(!_.allOf)_.allOf=[];if(_.pattern){if(_.allOf.push({pattern:_.pattern,..._.errorMessage&&X.errorMessages&&{errorMessage:{pattern:_.errorMessage.pattern}}}),delete _.pattern,_.errorMessage){if(delete _.errorMessage.pattern,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.allOf.push({pattern:i6(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",i6(w,X),$,X)}function i6(_,w){if(!w.applyRegexFlags||!_.flags)return _.source;let $={i:_.flags.includes("i"),m:_.flags.includes("m"),s:_.flags.includes("s")},X=$.i?_.source.toLowerCase():_.source,Y="",J=!1,D=!1,W=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(D){if(X[G].match(/[a-z]/)){if(W)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),W=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],W=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
|
|
2581
|
+
`;return this.db.prepare(X).all(`%${w}%`,$).map((J)=>this.rowToTask(J))}rowToTag(w){return{id:w.id,name:w.name,createdAt:new Date(w.created_at).toISOString(),taskCount:w.task_count}}async syncTaskTagsJson(w){let X=(await this.getTagsForTask(w)).map((J)=>J.name);this.db.prepare("UPDATE task SET tags = ? WHERE id = ?").run(X.length>0?JSON.stringify(X):null,w),this.tasksCache.delete(w)}async close(){if(this.db)this.db.close(),this.db=null,this.initialized=!1;this.tasksCache.clear(),this.operationsCache.clear()}},m([u("task.rowToTask",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Kw.prototype,"searchTasksByKeywords",null)});function Z6(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let Y=$.replace(/-/g,"_").toUpperCase(),J=_.slice(X.length);if(J.startsWith("_"))J=J.slice(1);if(!J)return;let Q=J.indexOf("_"),W;if(Q===-1)W=J;else{let D=J.slice(0,Q),q=J.slice(Q+1);if(D===Y)W=q;else W=J}if(!W)return;let G=W.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function C6(_,w){return{..._,execute:w}}var jz=()=>{},I6=r(()=>{jz(),q$(),w0()});I6();class S${_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new J1}getStatus(){return this._status}getConfig(){return{name:this.name,version:this.version,enabled:this._enabled,env:this.env}}isEnvInitialized(){return this._status!=="created"}setStatus(_){this._status=_}getEnv(){return this.env}async init(_){if(_?.env)this.env=_.env;this.setStatus("initializing");try{if(_?.name)Object.defineProperty(this,"name",{value:_.name,writable:!1});if(_?.version)Object.defineProperty(this,"version",{value:_.version,writable:!1})}catch{}if(_?.enabled!==void 0)this._enabled=_.enabled;this.hookManager.setComponentInfo(this.name,this.version),await this.onInit(),this.setStatus("running")}async start(){if(this._started)return;this._started=!0,await this.onStart(),this.setStatus("running")}async stop(){this.setStatus("stopping"),this.hookManager.clear(),await this.onStop(),this.setStatus("stopped")}async onInit(){}async onStart(){}async onStop(){}registerHook(_,w){this.hookManager.register(_,w)}addHook(_,w,$,X){this.hookManager.register(_,C6({name:w,priority:X},$))}removeHook(_,w){return this.hookManager.unregister(_,w)}async executeHooks(_,w,$){await this.hookManager.execute(_,w,$)}getConfigComponent(){return this.env?.getComponent("config")}getRuntimeConfig(_,w){let $=this.getConfigComponent();if($){let X=$.get(_);if(X!==void 0)return X}return w}}a();var Ez={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Sz={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"]}]};w0();var Pz=["completed","failed","cancelled","timeout"];Ww();a();var o0=n("task:tag");class T6{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return o0.debug(`[TagService] Created tag: ${w.name} (id=${w.id})`),w}async getTag(_){return this.store.getTag(_)}async getTagByName(_){return this.store.getTagByName(_)}async listTags(_){return this.store.listTags(_)}async searchTags(_){return this.store.searchTags(_)}async deleteTag(_){let w=await this.store.deleteTag(_);if(w)o0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),o0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),o0.debug(`[TagService] Removed ${w.length} tags from task ${_}`)}async getTagsForTask(_){return this.store.getTagsForTask(_)}async getTaskIdsByTags(_){return this.store.getTaskIdsByTags(_)}async findSimilarTasks(_,w=5){return this.store.findSimilarTasks(_,w)}async searchTasks(_,w=20){return this.store.searchTasks(_,w)}async searchTasksByKeywords(_,w){return(await this.store.searchTasksByKeywords(_,w)).tasks}async findSimilarTasksByKeywords(_,w){return this.store.findSimilarTasksByKeywords(_,w)}async syncTagsToTask(_,w){let $=[];for(let G of w){let D=await this.store.getTagByName(G);if(!D)D=await this.store.createTag(G);$.push(D.id)}let X=await this.store.getTagsForTask(_),Y=new Set(X.map((G)=>G.id)),J=new Set($),Q=$.filter((G)=>!Y.has(G)),W=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(W.length>0)await this.store.removeTagsFromTask(_,W);if(Q.length>0)await this.store.addTagsToTask(_,Q);await this.store.updateTaskTags(_,w),o0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}H_();var J_=n("task"),Zz="Deliverable: ";function Cz(_){if(!_)return;return`${Zz}${_}`}class Nw extends S${name="task";version="1.0.0";store;config;toolComponent;backgroundTaskManager;configComponent;tagService;plugins=new Map;getBackgroundTaskManager(){return this.backgroundTaskManager}publishEvent(_,w,$){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.component",trigger_session_id:$}}),J_.info(`[TaskComponent] Event published: ${_}`)}constructor(){super()}async init(_){await super.init(_);let w=_?.options;if(!w?.configComponent)throw Error("ConfigComponent is required for TaskComponent initialization");this.configComponent=w.configComponent,await this.registerConfig(w),this.setStatus("running"),J_.info("[TaskComponent] Initialized")}async registerConfig(_){let w=this.configComponent;if(!w)return;let{configPath:$,envPrefix:X,config:Y}=_,J=X??"TASK";if(w.registerComponent(Sz),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:J,priority:20,watch:!1}),await w.load("task");for(let Q of Object.keys(process.env)){let W=Z6(Q,J,"task");if(!W)continue;let G=process.env[Q];if(G!==void 0)await w.set(W,G)}for(let[Q,W]of Object.entries(Ez))if(w.get(Q)===void 0)await w.set(Q,W);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",U1());if(Y){let Q=this.flattenConfig(Y);for(let[W,G]of Object.entries(Q))await w.set(W,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new T6(this.store)}async initStore(){let _=this.configComponent;if(!_)return;let w=_.get("task.storage.type")??"sqlite",$=_.get("task.storage.dbPath");if(w==="sqlite")this.store=new Kw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Kw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,Y]of Object.entries(_)){let J=`${w}.${X}`;if(Y&&typeof Y==="object"&&!Array.isArray(Y))Object.assign($,this.flattenConfig(Y,J));else $[J]=Y}return $}registerConfigWatcher(_){if(typeof _.watch!=="function")return;this.configWatcher=_.watch("task.*",(w)=>{this.onConfigChange(w)})}onConfigChange(_){if(J_.info(`[TaskComponent] Config changed: ${_.key}`,{oldValue:_.oldValue,newValue:_.newValue}),_.key==="task.storage.type"||_.key==="task.storage.dbPath")this.initStore()}configWatcher;async start(){if(await super.start(),this.backgroundTaskManager=new w_(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(D2(this.backgroundTaskManager),"built-in"),J_.debug("[TaskComponent] Injected BackgroundTaskManager into query_background_process tool (factory pattern)");else J_.warn("[TaskComponent] ToolComponent not found, skipping tool registration")}async stop(){if(this.configWatcher)this.configWatcher(),this.configWatcher=void 0;if(this.toolComponent)try{this.toolComponent.register(D2(null),"built-in"),J_.debug("[TaskComponent] Reset query_background_process tool to no-manager default (cleanup)")}catch(_){J_.warn(`[TaskComponent] Failed to reset query_background_process tool: ${_.message}`)}if(this.backgroundTaskManager)this.backgroundTaskManager.dispose(),this.backgroundTaskManager=void 0;if(this.store)await this.store.close();await super.stop()}async registerTools(){if(!this.toolComponent)return;let _=[m0(this),u0(this),l0(this),i0(this),c0(this),f$(this),L$(this),d0(this),F$(this),p0(this)],w=[n0(this),b$(this),r0(this),j$(this),E$(this)],$=[s5(this),D4(this.backgroundTaskManager)];for(let X of[..._,...w,...$])this.toolComponent.register(X),J_.info(`[TaskComponent] Registered tool: ${X.name}`)}async executeHook(_,w,$={}){let X={component:{name:this.name,version:this.version},data:w,metadata:$,phase:_.includes("before")?"before":"after",hookPoint:_};await P_.execute(_,w,$)}async createTask(_){let w=_.sessionId;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){if(!await this.store.getTask(_.parent_task_id))throw Error(`Parent task #${_.parent_task_id} not found. Please provide a valid parent_task_id. Use task_list(depth=0) to see all root tasks.`)}let $={options:{..._},sessionId:w,tagService:this.tagService,taskComponent:this};await this.executeHook($_.BEFORE_CREATE,$);let X=await this.store.createTask($.options);await this.store.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description||""});let Y={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook($_.AFTER_CREATE,Y),this.publishEvent(Lw.CREATED,{task:X,sessionId:w},w),J_.info(`[TaskComponent] Task created: ${X.id} - ${X.title}`),X}async getTask(_){return this.store.getTask(_)}async getTaskIdBySessionId(_){return this.store.getTaskIdBySessionId(_)}async getTaskWithOperations(_){let w=await this.store.getTask(_);if(!w)return;let $=await this.store.listOperations({taskId:_});return{...w,operations:$,task:w}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook($_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let Y={task:X,changes:w,tagService:this.tagService};if(await this.executeHook($_.AFTER_UPDATE,Y),this.publishEvent(Lw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Pz.includes(w.status)){let J=X1(),Q={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,Q),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook($_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook($_.AFTER_DELETE,X),$)this.publishEvent(Lw.DELETED,{taskId:_,sessionId:""},""),J_.info(`[TaskComponent] Task deleted: ${_}`);return $}async listTasks(_){return this.store.listTasks(_)}async searchTasksByKeywords(_,w){return this.store.searchTasksByKeywords(_,w||{})}async getTaskTree(_,w=-1){return this.store.getTaskTree(_,w)}async getChildTasks(_,w){return this.store.getChildTasks(_,w)}async completeTask(_,w,$){let X=await this.store.getTask(_);if(X&&X.type==="cycle")throw Error(`Cannot complete cycle task: #${_} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($){let Q={};if(X?.context)try{let W=JSON.parse(X.context);if(W&&typeof W==="object"&&!Array.isArray(W))Q=W}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}Q.deliverable_storage_path=$,Y.context=JSON.stringify(Q)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Cz($)}),this.publishEvent(Lw.COMPLETED,{task:J,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return J}async createOperation(_){let w={options:{..._}};await this.executeHook($_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),Y={operation:$};return await this.executeHook($_.OPERATION_AFTER_CREATE,Y,{task:X,operation:$}),this.publishEvent(Lw.OPERATION_ADDED,{operation:$,taskId:$.taskId},$.sessionId),J_.info(`[TaskComponent] Operation created: ${$.id} for task ${$.taskId}`),$}async getOperation(_){return this.store.getOperation(_)}async updateOperation(_,w){return this.store.updateOperation(_,w)}async deleteOperation(_){return this.store.deleteOperation(_)}async listOperations(_){return this.store.listOperations(_)}getTagService(){return this.tagService}registerHook(_,w){P_.register(_,w),this.plugins.set(this.makePluginKey(_,w.name),w),J_.debug(`[TaskComponent] Registered hook: ${w.name} at ${_}`)}registerHooks(_){for(let{hookPoint:w,hook:$}of _)this.registerHook(w,$)}unregisterHook(_,w){let $=P_.unregister(_,w);if($)this.plugins.delete(this.makePluginKey(_,w)),J_.info(`[TaskComponent] Unregistered hook: ${w} from ${_}`);return $}listHooks(){return Array.from(this.plugins.values())}makePluginKey(_,w){return`${_}::${w}`}countHooks(_){return P_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],Nw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Nw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Nw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Nw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Nw.prototype,"createOperation",null);var P$=M.enum(["todo","active","completed","paused","cancelled","archived"]),Z$=M.enum(["low","medium","high"]),C$=M.enum(["normal","cycle","longterm"]),I$=M.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Iz=M.object({storage:M.object({type:M.enum(["memory","sqlite"]).default("sqlite"),dbPath:M.string().optional()}).default({})}).default({});Gw();Gw();var Tz="Deliverable: ";function kz(_){if(!_)return;return`${Tz}${_}`}var z1=1e6;class T${port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=gz(_);if(w!==void 0){if(typeof this.port.getTaskByNum==="function")return await this.port.getTaskByNum(w);return(await this.scanAllTasks()).find(($)=>$.id===w)??null}return await this.port.getTask(String(_))}toTask(_){let{nativeId:w,...$}=_;return $}toOperation(_){let{nativeId:w,...$}=_;return $}async scanAllTasks(){return(await this.port.listTasks({limit:z1,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let Y=await this.resolve(_.parent_task_id);if(!Y)throw Error(`Parent task #${_.parent_task_id} not found.`);$=Y.id}let X=await this.port.createTask({title:_.title,description:_.description,priority:_.priority,type:_.type,goals_and_expected_deliverables:_.goals_and_expected_deliverables,...$!==void 0?{parent_task_id:$}:{},due_date:_.due_date,tags:_.tags,project_path:_.project_path,context:_.context,sessionId:w});return await this.createOperation({taskId:X.id,sessionId:w,milestoneType:"create",milestoneTitle:`Task created: ${X.title}`,milestoneDescription:X.description??""}),this.toTask(X)}async getTask(_){let w=await this.resolve(_);return w?this.toTask(w):null}async getTaskWithOperations(_){let w=await this.getTask(_);if(!w)return null;let $=await this.listOperations({taskId:w.id,limit:z1,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((Y)=>this.toTask(Y));return X=this.applyFilters(X,_),{tasks:X.slice($,$+w),total:X.length}}async updateTask(_,w){let $=await this.resolve(_);if(!$)return null;let X;if(w.parent_task_id!==void 0)if(w.parent_task_id===null)X=null;else{let J=await this.resolve(w.parent_task_id);if(!J)throw Error(`Parent task #${w.parent_task_id} not found.`);X=J.id}let Y=await this.port.updateTask($.nativeId,{title:w.title,description:w.description,status:w.status,priority:w.priority,type:w.type,progress:w.progress,current_status:w.current_status,goals_and_expected_deliverables:w.goals_and_expected_deliverables,due_date:w.due_date,tags:w.tags,project_path:w.project_path,context:w.context,...X!==void 0?{parent_task_id:X}:{}});return Y?this.toTask(Y):null}async deleteTask(_){let w=await this.resolve(_);if(!w)return!1;return await this.port.deleteTask(w.nativeId)}async completeTask(_,w,$){let X=await this.resolve(_);if(!X)return null;if(X.type==="cycle")throw Error(`Cannot complete cycle task: #${X.id} - ${X.title}. Cycle tasks are not meant to be completed.`);let Y={status:"completed",progress:100};if($)Y.context=yz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let Q=kz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:Q??"Task completed",...$?{mdPath:$}:{}});let W=await this.resolve(X.nativeId);return this.toTask(W??J)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((D)=>this.toTask(D)),Y=new Map;for(let D of X){if(D.parent_task_id===void 0)continue;let q=Y.get(D.parent_task_id)??[];q.push(D),Y.set(D.parent_task_id,q)}let J=[],Q=new Set([$.id]),W=[$.id],G=0;while(W.length>0){if(w!==-1&&G>=w)break;let D=[];for(let q of W)for(let H of Y.get(q)??[]){if(Q.has(H.id))continue;Q.add(H.id),J.push(H),D.push(H.id)}W=D,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((W)=>this.toTask(W));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((W)=>W.id!==w.excludeTaskId);let J=_.map((W)=>W.toLowerCase()).filter((W)=>W.length>0),Q=J.length===0?Y:Y.filter((W)=>{let G=[W.title,W.description,W.goals_and_expected_deliverables,W.current_status,(W.tags??[]).join(" "),W.project_path].join(" ").toLowerCase();return J.every((D)=>G.includes(D))});return{tasks:Q.slice(X,X+$),total:Q.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",Y=_.milestoneDescription??_.actionDescription??"",J=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(J)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let Y=await this.resolve(_.taskId);if(!Y)return[];let Q=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?z1:w,offset:X?0:$})).operations.map((W)=>this.toOperation(W));if(X)Q=Q.filter((W)=>W.milestoneType===X),Q=Q.slice($,$+w);return Q}async getOperation(_){if(typeof this.port.getOperationByNum==="function"){let $=await this.port.getOperationByNum(_);return $?this.toOperation($):null}let w=await this.scanAllTasks();for(let $ of w){let Y=(await this.port.listOperations({taskNativeId:$.nativeId,limit:z1})).operations.find((J)=>J.id===_);if(Y)return this.toOperation(Y)}return null}async updateOperation(_,w){let $=await this.getOperation(_);if(!$)return null;if(typeof this.port.updateOperationByNum!=="function")return $;let X=await this.port.updateOperationByNum(_,{sessionId:w.sessionId??$.sessionId,milestoneType:w.milestoneType??w.actionType??$.milestoneType,milestoneTitle:w.milestoneTitle??w.actionTitle??$.milestoneTitle,milestoneDescription:w.milestoneDescription??w.actionDescription??$.milestoneDescription,processDescription:w.processDescription??$.processDescription,...w.mdPath!==void 0?{mdPath:w.mdPath}:{}});return X?this.toOperation(X):null}async deleteOperation(_){if(typeof this.port.deleteOperationByNum!=="function")return!1;return await this.port.deleteOperationByNum(_)}applyFilters(_,w){let $=_;if(w.include_archived!==!0&&w.status!=="archived")$=$.filter((Y)=>Y.status!=="archived");if(w.status!==void 0)$=$.filter((Y)=>Y.status===w.status);if(w.priority!==void 0)$=$.filter((Y)=>Y.priority===w.priority);if(w.type!==void 0)$=$.filter((Y)=>Y.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((Y)=>Y.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let Y=hz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function gz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function hz(_,w){if(w<0)return new Set(_.map((Q)=>Q.id));let $=new Set(_.map((Q)=>Q.id)),X=new Map;for(let Q of _){let W=Q.parent_task_id;if(W===void 0||!$.has(W))continue;let G=X.get(W)??[];G.push(Q),X.set(W,G)}let Y=new Set,J=_.filter((Q)=>Q.parent_task_id===void 0||!$.has(Q.parent_task_id));for(let Q of J)Y.add(Q.id);for(let Q=1;Q<=w;Q++){let W=[];for(let G of J)for(let D of X.get(G.id)??[]){if(Y.has(D.id))continue;Y.add(D.id),W.push(D)}if(W.length===0)break;J=W}return Y}function yz(_,w){let $={};if(typeof _==="string"&&_.trim().length>0)try{let X=JSON.parse(_);if(X&&typeof X==="object"&&!Array.isArray(X))$=X}catch{}return $.deliverable_storage_path=w,JSON.stringify($)}var vz=1e6;function xz(_){let w={};if(_.type!==void 0)w.type=_.type;if(_.progress!==void 0)w.progress=_.progress;if(_.current_status!==void 0)w.current_status=_.current_status;if(_.goals_and_expected_deliverables!==void 0)w.goals_and_expected_deliverables=_.goals_and_expected_deliverables;if(_.project_path!==void 0)w.project_path=_.project_path;if(_.context!==void 0)w.context=_.context;if(_.due_date!==void 0)w.due_date=_.due_date;return w}function s0(_,w,$){if(typeof _.num!=="number")throw Error(`store did not expose a numeric handle for task ${_.id}`);let X=_.roy??{};return{id:_.num,nativeId:_.id,title:_.title,description:_.description??"",status:w.toRoyStatus(_.status),priority:w.toRoyPriority(_.priority),type:X.type??"normal",progress:typeof X.progress==="number"?X.progress:_.status==="done"?100:0,current_status:X.current_status??"",goals_and_expected_deliverables:X.goals_and_expected_deliverables??"",...$!==void 0?{parent_task_id:$}:{},createdAt:_.created_at,updatedAt:_.updated_at,...X.due_date?{due_date:X.due_date}:{},tags:w.toRoyTags(_.tags),project_path:X.project_path??"unknown",context:X.context??"{}"}}function t0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),Y=String(w.milestoneDescription??w.actionDescription??""),J=w.taskId??_.task_id,Q=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:Q,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:Y,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:Y}}function k6(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??vz;async function Q(){let D=await _.listTasks({limit:J});return new Map(D.tasks.filter((q)=>typeof q.num==="number").map((q)=>[q.id,q.num]))}async function W(D){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(D);return(await _.listTasks({limit:J})).tasks.find((H)=>H.num===D)??null}async function G(D){let H=[...(await Q()).entries()].find(([,B])=>B===D);if(!H)throw Error(`parent task not found: ${D}`);return H[0]}return{async createTask(D){let q=D.parent_task_id!==void 0?await G(D.parent_task_id):null,H={type:D.type??"normal",progress:D.progress??0,current_status:D.current_status??"",goals_and_expected_deliverables:D.goals_and_expected_deliverables??"",project_path:D.project_path,context:D.context,...D.due_date?{due_date:D.due_date}:{}},B=await _.createTask({title:D.title,description:D.description,priority:w.toStorePriority(D.priority),owner:Y,tags:w.toStoreTags(D.tags),parent_id:q,session_id:D.sessionId??"unknown",roy:H});return s0(B,w,D.parent_task_id)},async getTask(D){let q=await _.getTask(D);if(!q)return null;let H=await Q();return s0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async getTaskByNum(D){let q=await W(D);if(!q)return null;let H=await Q();return s0(q,w,q.parent_id?H.get(q.parent_id):void 0)},async listTasks(D){let q=await _.listTasks({limit:D?.limit??20,offset:D?.offset??0}),H=await Q();return{tasks:q.tasks.map((B)=>s0(B,w,B.parent_id?H.get(B.parent_id):void 0)),total:q.total}},async updateTask(D,q){let H=xz(q),B=await _.updateTask(D,{...q.title!==void 0?{title:q.title}:{},...q.description!==void 0?{description:q.description}:{},...q.status!==void 0?{status:w.toStoreStatus(q.status)}:{},...q.priority!==void 0?{priority:w.toStorePriority(q.priority)}:{},...q.tags!==void 0?{tags:w.toStoreTags(q.tags)}:{},...Object.keys(H).length>0?{roy:H}:{}});if(!B)return null;let O;if(q.parent_task_id!==void 0){let U=q.parent_task_id===null?null:await G(q.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(D,U);O=q.parent_task_id===null?void 0:q.parent_task_id}let z=await _.getTask(D)??B;if(O===void 0&&z.parent_id)O=(await Q()).get(z.parent_id);return s0(z,w,O)},async deleteTask(D){return await _.deleteTask(D)},async createOperation(D){let q=await _.appendOperation({task_id:D.taskNativeId??String(D.taskId),type:X,data:{taskId:D.taskId,sessionId:D.sessionId,milestoneType:D.milestoneType,milestoneTitle:D.milestoneTitle,milestoneDescription:D.milestoneDescription,processDescription:D.processDescription,...D.mdPath?{mdPath:D.mdPath}:{}}});return t0(q)},async listOperations(D){let q=await _.listOperations({...D?.taskNativeId?{task_id:D.taskNativeId}:{},type:X,limit:D?.limit??J,offset:D?.offset??0});return{operations:q.operations.map(t0),total:q.total}},async getOperationByNum(D){if(typeof _.getOperationByNum!=="function")return null;let q=await _.getOperationByNum(D);return q?t0(q):null},async updateOperationByNum(D,q){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(D);if(!H)return null;let B=t0(H),O=await _.updateOperation(D,{data:{taskId:B.taskId,sessionId:q.sessionId??B.sessionId,milestoneType:q.milestoneType??B.milestoneType,milestoneTitle:q.milestoneTitle??B.milestoneTitle,milestoneDescription:q.milestoneDescription??B.milestoneDescription,processDescription:q.processDescription??B.processDescription,...q.mdPath??B.mdPath?{mdPath:q.mdPath??B.mdPath}:{}}});return O?t0(O):null},async deleteOperationByNum(D){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(D)}}}var mz="roy.milestone",uz={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},lz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function g6(_){return uz[_]??"pending"}function h6(_){return lz[_]??"todo"}function y6(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function v6(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function x6(_){if(!_||_.length===0)return;return _.join(",")}function m6(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var cz={toRoyStatus:(_)=>h6(_),toStoreStatus:(_)=>g6(_),toRoyPriority:(_)=>v6(_),toStorePriority:(_)=>y6(_),toRoyTags:(_)=>m6(_),toStoreTags:(_)=>x6(_)};function u6(_,w={}){return new T$(k6(_,cz,{operationType:mz,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var _f=P$.options,wf=Z$.options,$f=C$.options,Xf=I$.options;var c6=Symbol("Let zodToJsonSchema decide on which parser to use");var l6={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"},d6=(_)=>typeof _==="string"?{...l6,name:_}:{...l6,..._};var p6=(_)=>{let w=d6(_),$=w.name!==void 0?[...w.basePath,w.definitionPath,w.name]:w.basePath;return{...w,flags:{hasReferencedOpenAiAnyType:!1},currentPath:$,propertyPath:void 0,seen:new Map(Object.entries(w.definitions).map(([X,Y])=>[Y._def,{def:Y._def,path:[...w.basePath,w.definitionPath,X],jsonSchema:void 0}]))}};function k$(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,k$(_,w,X,Y)}var V1=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function s(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?V1(w,_.currentPath):w.join("/")}}function i6(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==F.ZodAny)$.items=k(_.type._def,{...w,currentPath:[...w.currentPath,"items"]});if(_.minLength)d($,"minItems",_.minLength.value,_.minLength.message,w);if(_.maxLength)d($,"maxItems",_.maxLength.value,_.maxLength.message,w);if(_.exactLength)d($,"minItems",_.exactLength.value,_.exactLength.message,w),d($,"maxItems",_.exactLength.value,_.exactLength.message,w);return $}function n6(_,w){let $={type:"integer",format:"int64"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function r6(){return{type:"boolean"}}function O1(_,w){return k(_.type._def,w)}var a6=(_,w)=>{return k(_.innerType._def,w)};function g$(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>g$(_,w,Y))};switch(X){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return dz(_,w)}}var dz=(_,w)=>{let $={type:"integer",format:"unix-time"};if(w.target==="openApi3")return $;for(let X of _.checks)switch(X.kind){case"min":d($,"minimum",X.value,X.message,w);break;case"max":d($,"maximum",X.value,X.message,w);break}return $};function o6(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function s6(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function t6(_){return{type:"string",enum:Array.from(_.values)}}var pz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function e6(_,w){let $=[k(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),k(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((J)=>!!J),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,Y=[];return $.forEach((J)=>{if(pz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let Q=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:W,...G}=J;Q=G}else X=void 0;Y.push(Q)}}),Y.length?{allOf:Y,...X}:void 0}function _9(_,w){let $=typeof _.value;if($!=="bigint"&&$!=="number"&&$!=="boolean"&&$!=="string")return{type:Array.isArray(_.value)?"array":"object"};if(w.target==="openApi3")return{type:$==="bigint"?"integer":$,enum:[_.value]};return{type:$==="bigint"?"integer":$,const:_.value}}var h$=void 0,Z_={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(h$===void 0)h$=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return h$},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 M1(_,w){let $={type:"string"};if(_.checks)for(let X of _.checks)switch(X.kind){case"min":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w);break;case"max":d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"email":switch(w.emailStrategy){case"format:email":C_($,"email",X.message,w);break;case"format:idn-email":C_($,"idn-email",X.message,w);break;case"pattern:zod":B_($,Z_.email,X.message,w);break}break;case"url":C_($,"uri",X.message,w);break;case"uuid":C_($,"uuid",X.message,w);break;case"regex":B_($,X.regex,X.message,w);break;case"cuid":B_($,Z_.cuid,X.message,w);break;case"cuid2":B_($,Z_.cuid2,X.message,w);break;case"startsWith":B_($,RegExp(`^${y$(X.value,w)}`),X.message,w);break;case"endsWith":B_($,RegExp(`${y$(X.value,w)}$`),X.message,w);break;case"datetime":C_($,"date-time",X.message,w);break;case"date":C_($,"date",X.message,w);break;case"time":C_($,"time",X.message,w);break;case"duration":C_($,"duration",X.message,w);break;case"length":d($,"minLength",typeof $.minLength==="number"?Math.max($.minLength,X.value):X.value,X.message,w),d($,"maxLength",typeof $.maxLength==="number"?Math.min($.maxLength,X.value):X.value,X.message,w);break;case"includes":{B_($,RegExp(y$(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")C_($,"ipv4",X.message,w);if(X.version!=="v4")C_($,"ipv6",X.message,w);break}case"base64url":B_($,Z_.base64url,X.message,w);break;case"jwt":B_($,Z_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")B_($,Z_.ipv4Cidr,X.message,w);if(X.version!=="v4")B_($,Z_.ipv6Cidr,X.message,w);break}case"emoji":B_($,Z_.emoji(),X.message,w);break;case"ulid":{B_($,Z_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{C_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{B_($,Z_.base64,X.message,w);break}}break}case"nanoid":B_($,Z_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((Y)=>{})(X)}return $}function y$(_,w){return w.patternStrategy==="escape"?nz(_):_}var iz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function nz(_){let w="";for(let $=0;$<_.length;$++){if(!iz.has(_[$]))w+="\\";w+=_[$]}return w}function C_(_,w,$,X){if(_.format||_.anyOf?.some((Y)=>Y.format)){if(!_.anyOf)_.anyOf=[];if(_.format){if(_.anyOf.push({format:_.format,..._.errorMessage&&X.errorMessages&&{errorMessage:{format:_.errorMessage.format}}}),delete _.format,_.errorMessage){if(delete _.errorMessage.format,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.anyOf.push({format:w,...$&&X.errorMessages&&{errorMessage:{format:$}}})}else d(_,"format",w,$,X)}function B_(_,w,$,X){if(_.pattern||_.allOf?.some((Y)=>Y.pattern)){if(!_.allOf)_.allOf=[];if(_.pattern){if(_.allOf.push({pattern:_.pattern,..._.errorMessage&&X.errorMessages&&{errorMessage:{pattern:_.errorMessage.pattern}}}),delete _.pattern,_.errorMessage){if(delete _.errorMessage.pattern,Object.keys(_.errorMessage).length===0)delete _.errorMessage}}_.allOf.push({pattern:w9(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",w9(w,X),$,X)}function w9(_,w){if(!w.applyRegexFlags||!_.flags)return _.source;let $={i:_.flags.includes("i"),m:_.flags.includes("m"),s:_.flags.includes("s")},X=$.i?_.source.toLowerCase():_.source,Y="",J=!1,Q=!1,W=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(Q){if(X[G].match(/[a-z]/)){if(W)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),W=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],W=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
|
|
2544
2582
|
]))`;continue}else if(X[G]==="$"){Y+=`($|(?=[\r
|
|
2545
|
-
]))`;continue}}if($.s&&X[G]==="."){Y+=
|
|
2583
|
+
]))`;continue}}if($.s&&X[G]==="."){Y+=Q?`${X[G]}\r
|
|
2546
2584
|
`:`[${X[G]}\r
|
|
2547
|
-
]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(D&&X[G]==="]")D=!1;else if(!D&&X[G]==="[")D=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${w.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),_.source}return Y}function V2(_,w){if(w.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(w.target==="openApi3"&&_.keyType?._def.typeName===K.ZodEnum)return{type:"object",required:_.keyType._def.values,properties:_.keyType._def.values.reduce((X,Y)=>({...X,[Y]:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",Y]})??s(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]})??w.allowedAdditionalProperties};if(w.target==="openApi3")return $;if(_.keyType?._def.typeName===K.ZodString&&_.keyType._def.checks?.length){let{type:X,...Y}=z2(_.keyType._def,w);return{...$,propertyNames:Y}}else if(_.keyType?._def.typeName===K.ZodEnum)return{...$,propertyNames:{enum:_.keyType._def.values}};else if(_.keyType?._def.typeName===K.ZodBranded&&_.keyType._def.type._def.typeName===K.ZodString&&_.keyType._def.type._def.checks?.length){let{type:X,...Y}=U2(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function n6(_,w){if(w.mapStrategy==="record")return V2(_,w);let $=k(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||s(w),X=k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||s(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function r6(_){let w=_.values,X=Object.keys(_.values).filter((J)=>{return typeof w[w[J]]!=="number"}).map((J)=>w[J]),Y=Array.from(new Set(X.map((J)=>typeof J)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function a6(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function o6(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function t6(_,w){if(w.target==="openApi3")return s6(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in t0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((Y,J)=>{let D=t0[J._def.typeName];return D&&!Y.includes(D)?[...Y,D]:Y},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((Y,J)=>{let D=typeof J._def.value;switch(D){case"string":case"number":case"boolean":return[...Y,D];case"bigint":return[...Y,"integer"];case"object":if(J._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===$.length){let Y=X.filter((J,D,W)=>W.indexOf(J)===D);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,D)=>{return J.includes(D._def.value)?J:[...J,D._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,Y)=>[...X,...Y._def.values.filter((J)=>!X.includes(J))],[])};return s6(_,w)}var s6=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,Y)=>k(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function e6(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:t0[_.innerType._def.typeName],nullable:!0};return{type:[t0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=k(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function _X(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",S$($,"type",X.message,w);break;case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function wX(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let W in J){let G=J[W];if(G===void 0||G._def===void 0)continue;let Q=jz(G);if(Q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();Q=!1}let q=k(G._def,{...w,currentPath:[...w.currentPath,"properties",W],propertyPath:[...w.currentPath,"properties",W]});if(q===void 0)continue;if(X.properties[W]=q,!Q)Y.push(W)}if(Y.length)X.required=Y;let D=bz(_,w);if(D!==void 0)X.additionalProperties=D;return X}function bz(_,w){if(_.catchall._def.typeName!=="ZodNever")return k(_.catchall._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]});switch(_.unknownKeys){case"passthrough":return w.allowedAdditionalProperties;case"strict":return w.rejectedAdditionalProperties;case"strip":return w.removeAdditionalStrategy==="strict"?w.allowedAdditionalProperties:w.rejectedAdditionalProperties}}function jz(_){try{return _.isOptional()}catch{return!0}}var $X=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return k(_.innerType._def,w);let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:s(w)},$]}:s(w)};var XX=(_,w)=>{if(w.pipeStrategy==="input")return k(_.in._def,w);else if(w.pipeStrategy==="output")return k(_.out._def,w);let $=k(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=k(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((Y)=>Y!==void 0)}};function YX(_,w){return k(_.type._def,w)}function JX(_,w){let X={type:"array",uniqueItems:!0,items:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items"]})};if(_.minSize)d(X,"minItems",_.minSize.value,_.minSize.message,w);if(_.maxSize)d(X,"maxItems",_.maxSize.value,_.maxSize.message,w);return X}function DX(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:k(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function WX(_){return{not:s(_)}}function GX(_){return s(_)}var QX=(_,w)=>{return k(_.innerType._def,w)};var qX=(_,w,$)=>{switch(w){case K.ZodString:return z2(_,$);case K.ZodNumber:return _X(_,$);case K.ZodObject:return wX(_,$);case K.ZodBigInt:return v6(_,$);case K.ZodBoolean:return x6();case K.ZodDate:return P$(_,$);case K.ZodUndefined:return WX($);case K.ZodNull:return o6($);case K.ZodArray:return y6(_,$);case K.ZodUnion:case K.ZodDiscriminatedUnion:return t6(_,$);case K.ZodIntersection:return d6(_,$);case K.ZodTuple:return DX(_,$);case K.ZodRecord:return V2(_,$);case K.ZodLiteral:return p6(_,$);case K.ZodEnum:return c6(_);case K.ZodNativeEnum:return r6(_);case K.ZodNullable:return e6(_,$);case K.ZodOptional:return $X(_,$);case K.ZodMap:return n6(_,$);case K.ZodSet:return JX(_,$);case K.ZodLazy:return()=>_.getter()._def;case K.ZodPromise:return YX(_,$);case K.ZodNaN:case K.ZodNever:return a6($);case K.ZodEffects:return l6(_,$);case K.ZodAny:return s($);case K.ZodUnknown:return GX($);case K.ZodDefault:return u6(_,$);case K.ZodBranded:return U2(_,$);case K.ZodReadonly:return QX(_,$);case K.ZodCatch:return m6(_,$);case K.ZodPipeline:return XX(_,$);case K.ZodFunction:case K.ZodVoid:case K.ZodSymbol:return;default:return((X)=>{return})(w)}};function k(_,w,$=!1){let X=w.seen.get(_);if(w.override){let W=w.override?.(_,w,X,$);if(W!==k6)return W}if(X&&!$){let W=Ez(X,w);if(W!==void 0)return W}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=qX(_,_.typeName,w),D=typeof J==="function"?k(J(),w):J;if(D)Sz(_,w,D);if(w.postProcess){let W=w.postProcess(D,_,w);return Y.jsonSchema=D,W}return Y.jsonSchema=D,D}var Ez=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:B2(w.currentPath,_.path)};case"none":case"seen":{if(_.path.length<w.currentPath.length&&_.path.every(($,X)=>w.currentPath[X]===$))return console.warn(`Recursive reference detected at ${w.currentPath.join("/")}! Defaulting to any`),s(w);return w.$refStrategy==="seen"?s(w):void 0}}},Sz=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var T$=(_,w)=>{let $=h6(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[Q,q])=>({...G,[Q]:k(q._def,{...$,currentPath:[...$.basePath,$.definitionPath,Q]},!0)??s($)}),{}):void 0,Y=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,J=k(_._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??s($),D=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(D!==void 0)J.title=D;if($.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[$.openAiAnyTypeName])X[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let W=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in W)||("oneOf"in W)||("allOf"in W)||("type"in W)&&Array.isArray(W.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return W};var Pz=[x0,p0,m0,u0,l0,c0,d0,i0,n0];function Zz(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=T$($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function HX(_,w={}){let $=T6(_,w);return Pz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:Zz(Y.parameters),options:{codemode:!1},execute:async(J,D)=>{let W={session_id:D?.sessionID??w.sessionId??"unknown",workdir:D?.directory};try{let G=await Y.execute(J??{},W),Q=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?Q:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:Y.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function BX(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function UX(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let Y=_??{},J=w.agent??X0;if(typeof Y.agent?.transform==="function")try{let W=await Y.agent.transform((G)=>{L2(G)});BX(W,X.disposers),X.agentId=J}catch(W){X.errors.push(`roy agent registration failed: ${I$(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let D=[];try{D=HX(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${I$(W)}`),X}if(typeof Y.tool?.transform==="function")try{let W=await Y.tool.transform((G)=>{for(let Q of D)G.add(Q)});BX(W,X.disposers),X.toolNames=D.map((G)=>G.name)}catch(W){X.errors.push(`roy tool registration failed: ${I$(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function I$(_){return _ instanceof Error?_.message:String(_)}import{join as h$}from"path";import{homedir as vz}from"os";import{mkdirSync as xz}from"fs";import{Database as Cz}from"bun:sqlite";import{createHash as Tz,randomUUID as Iz}from"crypto";var kz=`
|
|
2585
|
+
]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(Q&&X[G]==="]")Q=!1;else if(!Q&&X[G]==="[")Q=!0}try{new RegExp(Y)}catch{return console.warn(`Could not convert regex pattern at ${w.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),_.source}return Y}function A1(_,w){if(w.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(w.target==="openApi3"&&_.keyType?._def.typeName===F.ZodEnum)return{type:"object",required:_.keyType._def.values,properties:_.keyType._def.values.reduce((X,Y)=>({...X,[Y]:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",Y]})??s(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]})??w.allowedAdditionalProperties};if(w.target==="openApi3")return $;if(_.keyType?._def.typeName===F.ZodString&&_.keyType._def.checks?.length){let{type:X,...Y}=M1(_.keyType._def,w);return{...$,propertyNames:Y}}else if(_.keyType?._def.typeName===F.ZodEnum)return{...$,propertyNames:{enum:_.keyType._def.values}};else if(_.keyType?._def.typeName===F.ZodBranded&&_.keyType._def.type._def.typeName===F.ZodString&&_.keyType._def.type._def.checks?.length){let{type:X,...Y}=O1(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function $9(_,w){if(w.mapStrategy==="record")return A1(_,w);let $=k(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||s(w),X=k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||s(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function X9(_){let w=_.values,X=Object.keys(_.values).filter((J)=>{return typeof w[w[J]]!=="number"}).map((J)=>w[J]),Y=Array.from(new Set(X.map((J)=>typeof J)));return{type:Y.length===1?Y[0]==="string"?"string":"number":["string","number"],enum:X}}function Y9(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function J9(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var e0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function W9(_,w){if(w.target==="openApi3")return Q9(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in e0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((Y,J)=>{let Q=e0[J._def.typeName];return Q&&!Y.includes(Q)?[...Y,Q]:Y},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((Y,J)=>{let Q=typeof J._def.value;switch(Q){case"string":case"number":case"boolean":return[...Y,Q];case"bigint":return[...Y,"integer"];case"object":if(J._def.value===null)return[...Y,"null"];case"symbol":case"undefined":case"function":default:return Y}},[]);if(X.length===$.length){let Y=X.filter((J,Q,W)=>W.indexOf(J)===Q);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,Q)=>{return J.includes(Q._def.value)?J:[...J,Q._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,Y)=>[...X,...Y._def.values.filter((J)=>!X.includes(J))],[])};return Q9(_,w)}var Q9=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,Y)=>k(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${Y}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function G9(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:e0[_.innerType._def.typeName],nullable:!0};return{type:[e0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=k(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function D9(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",k$($,"type",X.message,w);break;case"min":if(w.target==="jsonSchema7")if(X.inclusive)d($,"minimum",X.value,X.message,w);else d($,"exclusiveMinimum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMinimum=!0;d($,"minimum",X.value,X.message,w)}break;case"max":if(w.target==="jsonSchema7")if(X.inclusive)d($,"maximum",X.value,X.message,w);else d($,"exclusiveMaximum",X.value,X.message,w);else{if(!X.inclusive)$.exclusiveMaximum=!0;d($,"maximum",X.value,X.message,w)}break;case"multipleOf":d($,"multipleOf",X.value,X.message,w);break}return $}function q9(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let W in J){let G=J[W];if(G===void 0||G._def===void 0)continue;let D=az(G);if(D&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();D=!1}let q=k(G._def,{...w,currentPath:[...w.currentPath,"properties",W],propertyPath:[...w.currentPath,"properties",W]});if(q===void 0)continue;if(X.properties[W]=q,!D)Y.push(W)}if(Y.length)X.required=Y;let Q=rz(_,w);if(Q!==void 0)X.additionalProperties=Q;return X}function rz(_,w){if(_.catchall._def.typeName!=="ZodNever")return k(_.catchall._def,{...w,currentPath:[...w.currentPath,"additionalProperties"]});switch(_.unknownKeys){case"passthrough":return w.allowedAdditionalProperties;case"strict":return w.rejectedAdditionalProperties;case"strip":return w.removeAdditionalStrategy==="strict"?w.allowedAdditionalProperties:w.rejectedAdditionalProperties}}function az(_){try{return _.isOptional()}catch{return!0}}var B9=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return k(_.innerType._def,w);let $=k(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:s(w)},$]}:s(w)};var H9=(_,w)=>{if(w.pipeStrategy==="input")return k(_.in._def,w);else if(w.pipeStrategy==="output")return k(_.out._def,w);let $=k(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=k(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((Y)=>Y!==void 0)}};function U9(_,w){return k(_.type._def,w)}function z9(_,w){let X={type:"array",uniqueItems:!0,items:k(_.valueType._def,{...w,currentPath:[...w.currentPath,"items"]})};if(_.minSize)d(X,"minItems",_.minSize.value,_.minSize.message,w);if(_.maxSize)d(X,"maxItems",_.maxSize.value,_.maxSize.message,w);return X}function V9(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:k(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>k($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function O9(_){return{not:s(_)}}function M9(_){return s(_)}var A9=(_,w)=>{return k(_.innerType._def,w)};var R9=(_,w,$)=>{switch(w){case F.ZodString:return M1(_,$);case F.ZodNumber:return D9(_,$);case F.ZodObject:return q9(_,$);case F.ZodBigInt:return n6(_,$);case F.ZodBoolean:return r6();case F.ZodDate:return g$(_,$);case F.ZodUndefined:return O9($);case F.ZodNull:return J9($);case F.ZodArray:return i6(_,$);case F.ZodUnion:case F.ZodDiscriminatedUnion:return W9(_,$);case F.ZodIntersection:return e6(_,$);case F.ZodTuple:return V9(_,$);case F.ZodRecord:return A1(_,$);case F.ZodLiteral:return _9(_,$);case F.ZodEnum:return t6(_);case F.ZodNativeEnum:return X9(_);case F.ZodNullable:return G9(_,$);case F.ZodOptional:return B9(_,$);case F.ZodMap:return $9(_,$);case F.ZodSet:return z9(_,$);case F.ZodLazy:return()=>_.getter()._def;case F.ZodPromise:return U9(_,$);case F.ZodNaN:case F.ZodNever:return Y9($);case F.ZodEffects:return s6(_,$);case F.ZodAny:return s($);case F.ZodUnknown:return M9($);case F.ZodDefault:return o6(_,$);case F.ZodBranded:return O1(_,$);case F.ZodReadonly:return A9(_,$);case F.ZodCatch:return a6(_,$);case F.ZodPipeline:return H9(_,$);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return((X)=>{return})(w)}};function k(_,w,$=!1){let X=w.seen.get(_);if(w.override){let W=w.override?.(_,w,X,$);if(W!==c6)return W}if(X&&!$){let W=oz(X,w);if(W!==void 0)return W}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=R9(_,_.typeName,w),Q=typeof J==="function"?k(J(),w):J;if(Q)sz(_,w,Q);if(w.postProcess){let W=w.postProcess(Q,_,w);return Y.jsonSchema=Q,W}return Y.jsonSchema=Q,Q}var oz=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:V1(w.currentPath,_.path)};case"none":case"seen":{if(_.path.length<w.currentPath.length&&_.path.every(($,X)=>w.currentPath[X]===$))return console.warn(`Recursive reference detected at ${w.currentPath.join("/")}! Defaulting to any`),s(w);return w.$refStrategy==="seen"?s(w):void 0}}},sz=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var v$=(_,w)=>{let $=p6(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[D,q])=>({...G,[D]:k(q._def,{...$,currentPath:[...$.basePath,$.definitionPath,D]},!0)??s($)}),{}):void 0,Y=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,J=k(_._def,Y===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,Y]},!1)??s($),Q=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(Q!==void 0)J.title=Q;if($.flags.hasReferencedOpenAiAnyType){if(!X)X={};if(!X[$.openAiAnyTypeName])X[$.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:$.$refStrategy==="relative"?"1":[...$.basePath,$.definitionPath,$.openAiAnyTypeName].join("/")}}}let W=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")W.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")W.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in W)||("oneOf"in W)||("allOf"in W)||("type"in W)&&Array.isArray(W.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return W};var tz=[m0,i0,u0,l0,c0,d0,p0,n0,r0];function ez(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=v$($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function f9(_,w={}){let $=u6(_,w);return tz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:ez(Y.parameters),options:{codemode:!1},execute:async(J,Q)=>{let W={session_id:Q?.sessionID??w.sessionId??"unknown",workdir:Q?.directory};try{let G=await Y.execute(J??{},W),D=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?D:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:Y.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:Y.name,ok:!1}}}}}})}function L9(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function F9(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let Y=_??{},J=w.agent??Y0;if(typeof Y.agent?.transform==="function")try{let W=await Y.agent.transform((G)=>{N1(G)});L9(W,X.disposers),X.agentId=J}catch(W){X.errors.push(`roy agent registration failed: ${x$(W)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let Q=[];try{Q=f9(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(W){return X.errors.push(`roy tool construction failed: ${x$(W)}`),X}if(typeof Y.tool?.transform==="function")try{let W=await Y.tool.transform((G)=>{for(let D of Q)G.add(D)});L9(W,X.disposers),X.toolNames=Q.map((G)=>G.name)}catch(W){X.errors.push(`roy tool registration failed: ${x$(W)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function x$(_){return _ instanceof Error?_.message:String(_)}import{join as l$}from"path";import{homedir as WV}from"os";import{mkdirSync as GV}from"fs";import{Database as _V}from"bun:sqlite";import{createHash as wV,randomUUID as $V}from"crypto";var XV=`
|
|
2548
2586
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
2549
2587
|
id TEXT PRIMARY KEY,
|
|
2550
2588
|
title TEXT NOT NULL,
|
|
@@ -2599,13 +2637,13 @@ CREATE TABLE IF NOT EXISTS bounties (
|
|
|
2599
2637
|
done_at TEXT
|
|
2600
2638
|
);
|
|
2601
2639
|
CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
|
|
2602
|
-
`;function
|
|
2640
|
+
`;function bw(){return new Date().toISOString()}function m$(){return $V()}function YV(_){return wV("sha256").update(_).digest("hex")}function K9(_){let w=JSON.stringify({id:_.id,type:_.type,data:_.data,prev_hash:_.prev_hash,created_at:_.created_at});return YV(w)}function u$(_){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:JV(_.roy),created_at:_.created_at,updated_at:_.updated_at}}function JV(_){if(_===null||_===void 0||_==="")return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}function QV(_){try{let w=_.query("PRAGMA table_info(tasks)").all();if(!new Set(w.map((X)=>X.name)).has("roy"))_.exec("ALTER TABLE tasks ADD COLUMN roy TEXT")}catch{}}function N9(_){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 R1(_){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 f1{db;closedFlag=!1;constructor(_){this.db=_}static async create(_){let w=new _V(_);return w.exec(XV),QV(w),new f1(w)}async close(){if(this.closedFlag)return;this.closedFlag=!0,this.db.close()}async createTask(_,w){if(this.closedFlag)throw Error("store closed");if(w){let Q=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(w);if(Q){let W=await this.getTask(Q.task_id);if(W)return W}}let $=m$(),X=bw(),Y=_.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
|
|
2603
2641
|
parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
|
|
2604
2642
|
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run($,_.title,_.description??null,Y,_.owner??null,_.tags??null,_.parent_id??null,JSON.stringify(_.blocked_by??[]),_.retry_of??null,_.session_id??null,_.roy===void 0?null:JSON.stringify(_.roy),X,X),w)this.db.query(`INSERT INTO task_idempotency (idempotency_key, task_id, created_at)
|
|
2605
|
-
VALUES (?, ?, ?)`).run(w,$,X);await this.appendOperation({task_id:$,type:"task.created",data:{title:_.title,parent_id:_.parent_id??null}});let J=await this.getTask($);if(!J)throw Error("internal: task vanished after insert");return J}async getTask(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get(_);return w?
|
|
2606
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),Y,$,J);let
|
|
2607
|
-
VALUES (?, ?, ?, ?, 'open', ?)`).run(w,_.subject,_.body,_.from,$),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:w,subject:_.subject,from:_.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w);return
|
|
2608
|
-
WHERE id = ? AND status = 'claimed'`).run(w,$,_).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:_,task_id:w}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get(_);return
|
|
2643
|
+
VALUES (?, ?, ?)`).run(w,$,X);await this.appendOperation({task_id:$,type:"task.created",data:{title:_.title,parent_id:_.parent_id??null}});let J=await this.getTask($);if(!J)throw Error("internal: task vanished after insert");return J}async getTask(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE id = ?").get(_);return w?u$(w):null}async getTaskByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM tasks WHERE rowid = ?").get(_);return w?u$(w):null}async updateTask(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getTask(_);if(!$)return null;let X=[],Y=[];if(w.title!==void 0)X.push("title = ?"),Y.push(w.title);if(w.description!==void 0)X.push("description = ?"),Y.push(w.description);if(w.status!==void 0)X.push("status = ?"),Y.push(w.status);if(w.priority!==void 0)X.push("priority = ?"),Y.push(w.priority);if(w.owner!==void 0)X.push("owner = ?"),Y.push(w.owner);if(w.tags!==void 0)X.push("tags = ?"),Y.push(w.tags);if(w.blocked_by!==void 0)X.push("blocked_by = ?"),Y.push(JSON.stringify(w.blocked_by));if(w.roy!==void 0){let J={...$.roy??{},...w.roy};X.push("roy = ?"),Y.push(JSON.stringify(J))}if(X.push("updated_at = ?"),Y.push(bw()),Y.push(_),this.db.query(`UPDATE tasks SET ${X.join(", ")} WHERE id = ?`).run(...Y),w.status!==void 0&&w.status!==$.status)await this.appendOperation({task_id:_,type:"task.status_changed",data:{from:$.status,to:w.status}});else await this.appendOperation({task_id:_,type:"task.updated",data:{keys:Object.keys(w)}});return await this.getTask(_)}async listTasks(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)if(Array.isArray(_.status))w.push(`status IN (${_.status.map(()=>"?").join(",")})`),$.push(..._.status);else w.push("status = ?"),$.push(_.status);if(_.parent_id!==void 0)if(_.parent_id===null)w.push("parent_id IS NULL");else w.push("parent_id = ?"),$.push(_.parent_id);if(_.session_id!==void 0)w.push("session_id = ?"),$.push(_.session_id);if(_.owner!==void 0)w.push("owner = ?"),$.push(_.owner);if(_.tags!==void 0)w.push("tags LIKE ?"),$.push(`%${_.tags}%`);if(_.search!==void 0)w.push("(title LIKE ? OR description LIKE ?)"),$.push(`%${_.search}%`,`%${_.search}%`);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",Q=this.db.query(`SELECT COUNT(*) AS n FROM tasks ${J}`).get(...$).n;return{tasks:this.db.query(`SELECT rowid AS num, * FROM tasks ${J} ORDER BY created_at DESC LIMIT ? OFFSET ?`).all(...$,X,Y).map(u$),total:Q}}async deleteTask(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run(_).changes>0}async setParentId(_,w){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(w,bw(),_)}async appendOperation(_){if(this.closedFlag)throw Error("store closed");let $=this.db.query("SELECT hash FROM operations ORDER BY rowid DESC LIMIT 1").get()?.hash??"0".repeat(64),X=m$(),Y=bw(),J=K9({id:X,type:_.type,data:_.data,prev_hash:$,created_at:Y});this.db.query(`INSERT INTO operations (id, task_id, type, data, created_at, prev_hash, hash)
|
|
2644
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),Y,$,J);let Q=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:Q,task_id:_.task_id,type:_.type,data:_.data,created_at:Y,prev_hash:$,hash:J}}async getOperationByNum(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT rowid AS num, * FROM operations WHERE rowid = ?").get(_);return w?N9(w):null}async updateOperation(_,w){if(this.closedFlag)throw Error("store closed");let $=await this.getOperationByNum(_);if(!$)return null;let X=[],Y=[];if(w.type!==void 0)X.push("type = ?"),Y.push(w.type);if(w.data!==void 0)X.push("data = ?"),Y.push(JSON.stringify(w.data));if(X.length===0)return $;return Y.push(_),this.db.query(`UPDATE operations SET ${X.join(", ")} WHERE rowid = ?`).run(...Y),await this.getOperationByNum(_)}async deleteOperation(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM operations WHERE rowid = ?").run(_).changes>0}async listOperations(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.task_id!==void 0)w.push("task_id = ?"),$.push(_.task_id);if(_.type!==void 0)w.push("type = ?"),$.push(_.type);let X=_.limit??100,Y=_.offset??0,J=w.length?`WHERE ${w.join(" AND ")}`:"",Q=this.db.query(`SELECT COUNT(*) AS n FROM operations ${J}`).get(...$).n;return{operations:this.db.query(`SELECT rowid AS num, * FROM operations ${J} ORDER BY rowid ASC LIMIT ? OFFSET ?`).all(...$,X,Y).map(N9),total:Q}}async verifyChain(){if(this.closedFlag)throw Error("store closed");let _=this.db.query("SELECT * FROM operations ORDER BY rowid ASC").all(),w="0".repeat(64);for(let $ of _){let X=K9({id:$.id,type:$.type,data:JSON.parse($.data),prev_hash:w,created_at:$.created_at});if($.prev_hash!==w)return!1;if($.hash!==X)return!1;w=$.hash}return!0}async tamperOpForTest(_,w){this.db.query("UPDATE operations SET data = ? WHERE rowid = ?").run(JSON.stringify(w),_)}async sendBounty(_){if(this.closedFlag)throw Error("store closed");let w=m$(),$=bw();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
|
|
2645
|
+
VALUES (?, ?, ?, ?, 'open', ?)`).run(w,_.subject,_.body,_.from,$),await this.appendOperation({task_id:null,type:"bounty.sent",data:{bounty_id:w,subject:_.subject,from:_.from}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w);return R1(X)}async claimBounty(_){if(this.closedFlag)throw Error("store closed");let w=this.db.query("SELECT * FROM bounties WHERE status = 'open' ORDER BY created_at ASC LIMIT 1").get();if(!w)return null;let $=bw();this.db.query("UPDATE bounties SET status = 'claimed', claimed_by = ?, claimed_at = ? WHERE id = ?").run(_,$,w.id),await this.appendOperation({task_id:null,type:"bounty.claimed",data:{bounty_id:w.id,by:_}});let X=this.db.query("SELECT * FROM bounties WHERE id = ?").get(w.id);return R1(X)}async completeBounty(_,w){if(this.closedFlag)throw Error("store closed");let $=bw();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
|
|
2646
|
+
WHERE id = ? AND status = 'claimed'`).run(w,$,_).changes===0)return null;await this.appendOperation({task_id:null,type:"bounty.completed",data:{bounty_id:_,task_id:w}});let Y=this.db.query("SELECT * FROM bounties WHERE id = ?").get(_);return R1(Y)}async listBounties(_={}){if(this.closedFlag)throw Error("store closed");let w=[],$=[];if(_.status!==void 0)w.push("status = ?"),$.push(_.status);if(_.to!==void 0)w.push("to_ = ?"),$.push(_.to);let X=w.length?`WHERE ${w.join(" AND ")}`:"";return this.db.query(`SELECT * FROM bounties ${X} ORDER BY created_at DESC`).all(...$).map(R1)}}var DV=l$(WV(),".roy-task-plugin"),qV=l$(DV,"tasks.db");class X0{inner;constructor(_){this.inner=_}static async create(_){let w=_??qV;if(w!==":memory:")GV(l$(w,".."),{recursive:!0});let $=await f1.create(w);return new X0($)}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 y_ extends Error{status;body;constructor(_,w,$){super(w);this.status=_,this.body=$}}class c${baseUrl;headers;closedFlag=!1;constructor(_){this.baseUrl=_.baseUrl.replace(/\/+$/,""),this.headers={"content-type":"application/json",..._.authToken?{authorization:`Bearer ${_.authToken}`}:{},..._.headers??{}}}async close(){this.closedFlag=!0}async request(_,w,$){if(this.closedFlag)throw Error("client closed");let X={...this.headers};if($?.idempotencyKey)X["idempotency-key"]=$.idempotencyKey;let Y=await fetch(`${this.baseUrl}${w}`,{method:_,headers:X,body:$?.body!==void 0?JSON.stringify($.body):void 0});if(Y.status===204)return null;let J=await Y.text(),Q=null;try{Q=J?JSON.parse(J):null}catch{Q=J}if(!Y.ok)throw new y_(Y.status,`HTTP ${Y.status}`,Q);return Q}async createTask(_,w){let $=await this.request("POST","/tasks",{body:_,idempotencyKey:w});if(!$)throw new y_(500,"empty response from POST /tasks");return $}async getTask(_){try{return await this.request("GET",`/tasks/${encodeURIComponent(_)}`)}catch(w){if(w instanceof y_&&w.status===404)return null;throw w}}async updateTask(_,w){try{return await this.request("PATCH",`/tasks/${encodeURIComponent(_)}`,{body:w})}catch($){if($ instanceof y_&&$.status===404)return null;throw $}}async deleteTask(_){try{return await this.request("DELETE",`/tasks/${encodeURIComponent(_)}`),!0}catch(w){if(w instanceof y_&&w.status===404)return!1;throw w}}async listTasks(_={}){let w=new URLSearchParams;if(_.status!==void 0){let X=Array.isArray(_.status)?_.status.join(","):_.status;w.set("status",X)}if(_.parent_id!==void 0&&_.parent_id!==null)w.set("parent_id",_.parent_id);if(_.session_id!==void 0)w.set("session_id",_.session_id);if(_.owner!==void 0)w.set("owner",_.owner);if(_.tags!==void 0)w.set("tags",_.tags);if(_.search!==void 0)w.set("search",_.search);w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0));let $=await this.request("GET",`/tasks?${w}`);if(!$)throw new y_(500,"empty response");return $}async appendOperation(_){return await this.request("POST","/operations",{body:_})}async listOperations(_={}){let w=new URLSearchParams;if(_.task_id!==void 0)w.set("task_id",_.task_id);if(_.type!==void 0)w.set("type",_.type);return w.set("limit",String(_.limit??100)),w.set("offset",String(_.offset??0)),await this.request("GET",`/operations?${w}`)}async verifyChain(){return(await this.request("GET","/verify"))?.valid===!0}async sendBounty(_){let w=await this.request("POST","/bounties",{body:_});if(!w)throw new y_(500,"empty bounty response");return w}async claimBounty(_){try{return await this.request("POST","/bounties/claim",{body:{agent:_}})}catch(w){if(w instanceof y_&&w.status===404)return null;throw w}}async completeBounty(_,w){try{return await this.request("POST",`/bounties/${encodeURIComponent(_)}/complete`,{body:{task_id:w}})}catch($){if($ instanceof y_&&$.status===404)return null;throw $}}async listBounties(_={}){let w=new URLSearchParams;if(_.status!==void 0)w.set("status",_.status);if(_.to!==void 0)w.set("to",_.to);return(await this.request("GET",`/bounties?${w}`))?.bounties??[]}}class _2{inner;constructor(_){this.inner=new c$(_)}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 vK(_={}){let w=_.persistence??"local",$;if(w==="remote"){if(!_.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");$=new _2({baseUrl:_.remoteUrl,authToken:_.remoteAuthToken})}else $=await X0.create(_.localDbPath);let X={store:$,agent:_.agent??"opencode-default"};return{handlers:Y2(X),store:$,async close(){await $.close()}}}var BV={id:"roy-task-plugin",async setup(_){let w=_.options??{},$=w.persistence??"local",X;if($==="remote"){if(!w.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");X=new _2({baseUrl:w.remoteUrl,authToken:w.remoteAuthToken})}else X=await X0.create(w.localDbPath);let Y={store:X,agent:w.agent??"opencode-default"},J=Y2(Y),Q=await F9(_,{store:X,enabled:w.royAgent!==!1,agent:"roy"}),W=await _.agent.transform(async(D)=>{let H=D.get("build");if(!H)return;let B=String(H.system??""),O=`
|
|
2609
2647
|
|
|
2610
2648
|
# Roy Task Plugin (auto-injected by roy-task-plugin v2)
|
|
2611
2649
|
|
|
@@ -2620,7 +2658,7 @@ Mark progress on long tasks via \`task-update <id> --status <status>\`.
|
|
|
2620
2658
|
For task-first-class-citizen work (task tree, milestones, deliverables), switch
|
|
2621
2659
|
to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
|
|
2622
2660
|
lifecycle as native tools.
|
|
2623
|
-
`;
|
|
2624
|
-
`)[0]?.trim()||`task-${Date.now()}`;await J.session({type:"session.created",payload:{id:q?.sessionID??`cmd-${Date.now()}`,title:B,body:H,source:"command:task-create"}})}}),
|
|
2661
|
+
`;D.update("build",(z)=>{if(typeof z.system==="string"||z.system===void 0)z.system=B+O})}),G=await _.command.transform((D)=>{D.add({name:"task-create",description:"Create a tracked task in roy-task-plugin store. Persists to SQLite (~/.roy-task-plugin/tasks.db) or remote service. Args: <title> [body]",template:"task-create <title> [body]",execute:async(q)=>{let H=String(q?.prompt?.text??"").trim(),B=H.split(`
|
|
2662
|
+
`)[0]?.trim()||`task-${Date.now()}`;await J.session({type:"session.created",payload:{id:q?.sessionID??`cmd-${Date.now()}`,title:B,body:H,source:"command:task-create"}})}}),D.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),D.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 D of Q.disposers)try{await D()}catch{}await W.dispose(),await G.dispose(),await X.close()}}}},mK=BV;export{mK as default,vK as createRoyTaskPlugin,Y2 as createHandlers,_2 as RemoteTaskStore,X0 as LocalTaskStore};
|
|
2625
2663
|
|
|
2626
|
-
//# debugId=
|
|
2664
|
+
//# debugId=1E507AD8DFEE7B9864756E2164756E21
|