@ai-setting/roy-task-plugin 0.6.1 → 0.7.0
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/hooks/stop-check.mjs +23 -19
- package/dist/claude-plugin/mcp/bridge.mjs +64 -443
- package/dist/claude-plugin/mcp/roy-task-mcp-server.mjs +75 -50
- package/dist/claude-plugin/mcp/tools.mjs +39 -225
- package/dist/cli.js +7 -6
- package/dist/index.js +525 -524
- package/dist/index.js.map +22 -21
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,141 +1,141 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
3
|
-
`)}}
|
|
4
|
-
`)
|
|
2
|
+
var V9=Object.create;var{getPrototypeOf:O9,defineProperty:M1,getOwnPropertyNames:A9}=Object;var M9=Object.prototype.hasOwnProperty;function R9(_){return this[_]}var f9,L9,F9=(_,w,$)=>{var X=_!=null&&typeof _==="object";if(X){var Y=w?f9??=new WeakMap:L9??=new WeakMap,J=Y.get(_);if(J)return J}$=_!=null?V9(O9(_)):{};let W=w||!_||!_.__esModule?M1($,"default",{value:_,enumerable:!0}):$;for(let Q of A9(_))if(!M9.call(W,Q))M1(W,Q,{get:R9.bind(_,Q),enumerable:!0});if(X)Y.set(_,W);return W};var P=(_,w)=>()=>(w||_((w={exports:{}}).exports,w),w.exports);var K9=(_)=>_;function N9(_,w){this[_]=K9.bind(null,w)}var b9=(_,w)=>{for(var $ in w)M1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:N9.bind(w,$)})};var $2=import.meta.require;var p=P((o7)=>{var p1=Symbol.for("yaml.alias"),K8=Symbol.for("yaml.document"),U2=Symbol.for("yaml.map"),N8=Symbol.for("yaml.pair"),i1=Symbol.for("yaml.scalar"),z2=Symbol.for("yaml.seq"),u_=Symbol.for("yaml.node.type"),c7=(_)=>!!_&&typeof _==="object"&&_[u_]===p1,d7=(_)=>!!_&&typeof _==="object"&&_[u_]===K8,p7=(_)=>!!_&&typeof _==="object"&&_[u_]===U2,i7=(_)=>!!_&&typeof _==="object"&&_[u_]===N8,b8=(_)=>!!_&&typeof _==="object"&&_[u_]===i1,n7=(_)=>!!_&&typeof _==="object"&&_[u_]===z2;function j8(_){if(_&&typeof _==="object")switch(_[u_]){case U2:case z2:return!0}return!1}function r7(_){if(_&&typeof _==="object")switch(_[u_]){case p1:case U2:case i1:case z2:return!0}return!1}var a7=(_)=>(b8(_)||j8(_))&&!!_.anchor;o7.ALIAS=p1;o7.DOC=K8;o7.MAP=U2;o7.NODE_TYPE=u_;o7.PAIR=N8;o7.SCALAR=i1;o7.SEQ=z2;o7.hasAnchor=a7;o7.isAlias=c7;o7.isCollection=j8;o7.isDocument=d7;o7.isMap=p7;o7.isNode=r7;o7.isPair=i7;o7.isScalar=b8;o7.isSeq=n7});var U0=P((UY)=>{var Y_=p(),H_=Symbol("break visit"),E8=Symbol("skip children"),k_=Symbol("remove node");function V2(_,w){let $=S8(w);if(Y_.isDocument(_)){if(uw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else uw(null,_,$,Object.freeze([]))}V2.BREAK=H_;V2.SKIP=E8;V2.REMOVE=k_;function uw(_,w,$,X){let Y=P8(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return Z8(_,X,Y),uw(_,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 W=uw(J,w.items[J],$,X);if(typeof W==="number")J=W-1;else if(W===H_)return H_;else if(W===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=uw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let W=uw("value",w.value,$,X);if(W===H_)return H_;else if(W===k_)w.value=null}}return Y}async function O2(_,w){let $=S8(w);if(Y_.isDocument(_)){if(await lw(null,_.contents,$,Object.freeze([_]))===k_)_.contents=null}else await lw(null,_,$,Object.freeze([]))}O2.BREAK=H_;O2.SKIP=E8;O2.REMOVE=k_;async function lw(_,w,$,X){let Y=await P8(_,w,$,X);if(Y_.isNode(Y)||Y_.isPair(Y))return Z8(_,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 W=await lw(J,w.items[J],$,X);if(typeof W==="number")J=W-1;else if(W===H_)return H_;else if(W===k_)w.items.splice(J,1),J-=1}}else if(Y_.isPair(w)){X=Object.freeze(X.concat(w));let J=await lw("key",w.key,$,X);if(J===H_)return H_;else if(J===k_)w.key=null;let W=await lw("value",w.value,$,X);if(W===H_)return H_;else if(W===k_)w.value=null}}return Y}function S8(_){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 P8(_,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 Z8(_,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`)}}UY.visit=V2;UY.visitAsync=O2});var n1=P((RY)=>{var C8=p(),OY=U0(),AY={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},MY=(_)=>_.replace(/[!,[\]{}]/g,(w)=>AY[w]);class O_{constructor(_,w){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},O_.defaultYaml,_),this.tags=Object.assign({},O_.defaultTags,w)}clone(){let _=new O_(this.yaml,this.tags);return _.docStart=this.docStart,_}atDocument(){let _=new O_(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:O_.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},O_.defaultTags);break}return _}add(_,w){if(this.atNextDocument)this.yaml={explicit:O_.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},O_.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+MY(_.substring($.length));return _[0]==="!"?_:`!<${_}>`}toString(_){let w=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],$=Object.entries(this.tags),X;if(_&&$.length>0&&C8.isNode(_.contents)){let Y={};OY.visit(_.contents,(J,W)=>{if(C8.isNode(W)&&W.tag)Y[W.tag]=!0}),X=Object.keys(Y)}else X=[];for(let[Y,J]of $){if(Y==="!!"&&J==="tag:yaml.org,2002:")continue;if(!_||X.some((W)=>W.startsWith(J)))w.push(`%TAG ${Y} ${J}`)}return w.join(`
|
|
3
|
+
`)}}O_.defaultYaml={explicit:!1,version:"1.2"};O_.defaultTags={"!!":"tag:yaml.org,2002:"};RY.Directives=O_});var A2=P((NY)=>{var T8=p(),LY=U0();function FY(_){if(/[\x00-\x19\s,[\]{}]/.test(_)){let $=`Anchor must not contain whitespace or control characters: ${JSON.stringify(_)}`;throw Error($)}return!0}function I8(_){let w=new Set;return LY.visit(_,{Value($,X){if(X.anchor)w.add(X.anchor)}}),w}function k8(_,w){for(let $=1;;++$){let X=`${_}${$}`;if(!w.has(X))return X}}function KY(_,w){let $=[],X=new Map,Y=null;return{onAnchor:(J)=>{$.push(J),Y??(Y=I8(_));let W=k8(w,Y);return Y.add(W),W},setAnchors:()=>{for(let J of $){let W=X.get(J);if(typeof W==="object"&&W.anchor&&(T8.isScalar(W.node)||T8.isCollection(W.node)))W.node.anchor=W.anchor;else{let Q=Error("Failed to resolve repeated object (this should not happen)");throw Q.source=J,Q}}},sourceObjects:X}}NY.anchorIsValid=FY;NY.anchorNames=I8;NY.createNodeAnchors=KY;NY.findNewAnchor=k8});var r1=P((PY)=>{function z0(_,w,$,X){if(X&&typeof X==="object")if(Array.isArray(X))for(let Y=0,J=X.length;Y<J;++Y){let W=X[Y],Q=z0(_,X,String(Y),W);if(Q===void 0)delete X[Y];else if(Q!==W)X[Y]=Q}else if(X instanceof Map)for(let Y of Array.from(X.keys())){let J=X.get(Y),W=z0(_,X,Y,J);if(W===void 0)X.delete(Y);else if(W!==J)X.set(Y,W)}else if(X instanceof Set)for(let Y of Array.from(X)){let J=z0(_,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 W=z0(_,X,Y,J);if(W===void 0)delete X[Y];else if(W!==J)X[Y]=W}return _.call(w,$,X)}PY.applyReviver=z0});var o_=P((TY)=>{var CY=p();function g8(_,w,$){if(Array.isArray(_))return _.map((X,Y)=>g8(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 _}TY.toJS=g8});var M2=P((hY)=>{var kY=r1(),h8=p(),gY=o_();class y8{constructor(_){Object.defineProperty(this,h8.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(!h8.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},W=gY.toJS(this,"",J);if(typeof X==="function")for(let{count:Q,res:G}of J.anchors.values())X(G,Q);return typeof Y==="function"?kY.applyReviver(Y,{"":W},"",W):W}}hY.NodeBase=y8});var V0=P((lY)=>{var vY=A2(),xY=U0(),cw=p(),mY=M2(),uY=o_();class v8 extends mY.NodeBase{constructor(_){super(cw.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($=[],xY.visit(_,{Node:(Y,J)=>{if(cw.isAlias(J)||cw.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:W}=w,Q=Y.get(X);if(!Q)uY.toJS(X,null,w),Q=Y.get(X);if(Q?.res===void 0)throw ReferenceError("This should not happen: Alias anchor was not resolved?");if(W>=0){if(Q.count+=1,Q.aliasCount===0)Q.aliasCount=R2(J,X,Y);if(Q.count*Q.aliasCount>W)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(vY.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 R2(_,w,$){if(cw.isAlias(w)){let X=w.resolve(_),Y=$&&X&&$.get(X);return Y?Y.count*Y.aliasCount:0}else if(cw.isCollection(w)){let X=0;for(let Y of w.items){let J=R2(_,Y,$);if(J>X)X=J}return X}else if(cw.isPair(w)){let X=R2(_,w.key,$),Y=R2(_,w.value,$);return Math.max(X,Y)}return 1}lY.Alias=v8});var X_=P((rY)=>{var dY=p(),pY=M2(),iY=o_(),nY=(_)=>!_||typeof _!=="function"&&typeof _!=="object";class Bw extends pY.NodeBase{constructor(_){super(dY.SCALAR);this.value=_}toJSON(_,w){return w?.keep?this.value:iY.toJS(this.value,_,w)}toString(){return String(this.value)}}Bw.BLOCK_FOLDED="BLOCK_FOLDED";Bw.BLOCK_LITERAL="BLOCK_LITERAL";Bw.PLAIN="PLAIN";Bw.QUOTE_DOUBLE="QUOTE_DOUBLE";Bw.QUOTE_SINGLE="QUOTE_SINGLE";rY.Scalar=Bw;rY.isScalarValue=nY});var O0=P((wJ)=>{var sY=V0(),Uw=p(),x8=X_(),tY="tag:yaml.org,2002:";function eY(_,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 _J(_,w,$){if(Uw.isDocument(_))_=_.contents;if(Uw.isNode(_))return _;if(Uw.isPair(_)){let B=$.schema[Uw.MAP].createNode?.($.schema,null,$);return B.items.push(_),B}if(_ instanceof String||_ instanceof Number||_ instanceof Boolean||typeof BigInt<"u"&&_ instanceof BigInt)_=_.valueOf();let{aliasDuplicateObjects:X,onAnchor:Y,onTagObj:J,schema:W,sourceObjects:Q}=$,G=void 0;if(X&&_&&typeof _==="object")if(G=Q.get(_),G)return G.anchor??(G.anchor=Y(_)),new sY.Alias(G.anchor);else G={anchor:null,node:null},Q.set(_,G);if(w?.startsWith("!!"))w=tY+w.slice(2);let q=eY(_,w,W.tags);if(!q){if(_&&typeof _.toJSON==="function")_=_.toJSON();if(!_||typeof _!=="object"){let B=new x8.Scalar(_);if(G)G.node=B;return B}q=_ instanceof Map?W[Uw.MAP]:(Symbol.iterator in Object(_))?W[Uw.SEQ]:W[Uw.MAP]}if(J)J(q),delete $.onTagObj;let H=q?.createNode?q.createNode($.schema,_,$):typeof q?.nodeClass?.from==="function"?q.nodeClass.from($.schema,_,$):new x8.Scalar(_);if(w)H.tag=w;else if(!q.default)H.tag=q.tag;if(G)G.node=H;return H}wJ.createNode=_J});var f2=P((JJ)=>{var XJ=O0(),g_=p(),YJ=M2();function a1(_,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 W=[];W[J]=X,X=W}else X=new Map([[J,X]])}return XJ.createNode(X,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error("This should not happen, please report a bug.")},schema:_,sourceObjects:new Map})}var m8=(_)=>_==null||typeof _==="object"&&!!_[Symbol.iterator]().next().done;class u8 extends YJ.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(($)=>g_.isNode($)||g_.isPair($)?$.clone(_):$),this.range)w.range=this.range.slice();return w}addIn(_,w){if(m8(_))this.add(w);else{let[$,...X]=_,Y=this.get($,!0);if(g_.isCollection(Y))Y.addIn(X,w);else if(Y===void 0&&this.schema)this.set($,a1(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(g_.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&&g_.isScalar(Y)?Y.value:Y;else return g_.isCollection(Y)?Y.getIn(X,w):void 0}hasAllNullValues(_){return this.items.every((w)=>{if(!g_.isPair(w))return!1;let $=w.value;return $==null||_&&g_.isScalar($)&&$.value==null&&!$.commentBefore&&!$.comment&&!$.tag})}hasIn(_){let[w,...$]=_;if($.length===0)return this.has(w);let X=this.get(w,!0);return g_.isCollection(X)?X.hasIn($):!1}setIn(_,w){let[$,...X]=_;if(X.length===0)this.set($,w);else{let Y=this.get($,!0);if(g_.isCollection(Y))Y.setIn(X,w);else if(Y===void 0&&this.schema)this.set($,a1(this.schema,X,w));else throw Error(`Expected YAML collection at ${$}. Remaining path: ${X}`)}}}JJ.Collection=u8;JJ.collectionFromPath=a1;JJ.isEmptyPath=m8});var A0=P((DJ)=>{var qJ=(_)=>_.replace(/^(?!$)(?: $)?/gm,"#");function o1(_,w){if(/^\n+$/.test(_))return _.substring(1);return w?_.replace(/^(?! *$)/gm,w):_}var HJ=(_,w,$)=>_.endsWith(`
|
|
4
|
+
`)?o1($,w):$.includes(`
|
|
5
5
|
`)?`
|
|
6
|
-
|
|
7
|
-
`){if($==="block")U=
|
|
8
|
-
`&&
|
|
9
|
-
`&&
|
|
10
|
-
${w}${_.slice(0,
|
|
11
|
-
${w}${_.slice(
|
|
12
|
-
`);X=w,
|
|
13
|
-
`){if(
|
|
6
|
+
`+o1($,w):(_.endsWith(" ")?"":" ")+$;DJ.indentComment=o1;DJ.lineComment=HJ;DJ.stringifyComment=qJ});var c8=P((OJ)=>{function VJ(_,w,$="flow",{indentAtStart:X,lineWidth:Y=80,minContentWidth:J=20,onFold:W,onOverflow:Q}={}){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 q=[],H={},B=Y-w.length;if(typeof X==="number")if(X>Y-Math.max(2,J))q.push(0);else B=Y-X;let D=void 0,O=void 0,z=!1,U=-1,V=-1,M=-1;if($==="block"){if(U=l8(_,U,w.length),U!==-1)B=U+G}for(let N;N=_[U+=1];){if($==="quoted"&&N==="\\"){switch(V=U,_[U+1]){case"x":U+=3;break;case"u":U+=5;break;case"U":U+=9;break;default:U+=1}M=U}if(N===`
|
|
7
|
+
`){if($==="block")U=l8(_,U,w.length);B=U+w.length+G,D=void 0}else{if(N===" "&&O&&O!==" "&&O!==`
|
|
8
|
+
`&&O!=="\t"){let R=_[U+1];if(R&&R!==" "&&R!==`
|
|
9
|
+
`&&R!=="\t")D=U}if(U>=B)if(D)q.push(D),B=D+G,D=void 0;else if($==="quoted"){while(O===" "||O==="\t")O=N,N=_[U+=1],z=!0;let R=U>M+1?U-2:V-1;if(H[R])return _;q.push(R),H[R]=!0,B=R+G,D=void 0}else z=!0}O=N}if(z&&Q)Q();if(q.length===0)return _;if(W)W();let f=_.slice(0,q[0]);for(let N=0;N<q.length;++N){let R=q[N],b=q[N+1]||_.length;if(R===0)f=`
|
|
10
|
+
${w}${_.slice(0,b)}`;else{if($==="quoted"&&H[R])f+=`${_[R]}\\`;f+=`
|
|
11
|
+
${w}${_.slice(R+1,b)}`}}return f}function l8(_,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}OJ.FOLD_BLOCK="block";OJ.FOLD_FLOW="flow";OJ.FOLD_QUOTED="quoted";OJ.foldFlowLines=VJ});var R0=P((NJ)=>{var b_=X_(),s_=c8(),F2=(_,w)=>({indentAtStart:w?_.indent.length:_.indentAtStart,lineWidth:_.options.lineWidth,minContentWidth:_.options.minContentWidth}),K2=(_)=>/^(%|---|\.\.\.)/m.test(_);function LJ(_,w,$){if(!w||w<0)return!1;let X=w-$,Y=_.length;if(Y<=X)return!1;for(let J=0,W=0;J<Y;++J)if(_[J]===`
|
|
13
|
+
`){if(J-W>X)return!0;if(W=J+1,Y-W<=X)return!1}return!0}function M0(_,w){let $=JSON.stringify(_);if(w.options.doubleQuotedAsJSON)return $;let{implicitKey:X}=w,Y=w.options.doubleQuotedMinMultiLineLength,J=w.indent||(K2(_)?" ":""),W="",Q=0;for(let G=0,q=$[G];q;q=$[++G]){if(q===" "&&$[G+1]==="\\"&&$[G+2]==="n")W+=$.slice(Q,G)+"\\ ",G+=1,Q=G,q="\\";if(q==="\\")switch($[G+1]){case"u":{W+=$.slice(Q,G);let H=$.substr(G+2,4);switch(H){case"0000":W+="\\0";break;case"0007":W+="\\a";break;case"000b":W+="\\v";break;case"001b":W+="\\e";break;case"0085":W+="\\N";break;case"00a0":W+="\\_";break;case"2028":W+="\\L";break;case"2029":W+="\\P";break;default:if(H.substr(0,2)==="00")W+="\\x"+H.substr(2);else W+=$.substr(G,6)}G+=5,Q=G+1}break;case"n":if(X||$[G+2]==='"'||$.length<Y)G+=1;else{W+=$.slice(Q,G)+`
|
|
14
14
|
|
|
15
15
|
`;while($[G+2]==="\\"&&$[G+3]==="n"&&$[G+4]!=='"')W+=`
|
|
16
|
-
`,G+=2;if(W+=
|
|
17
|
-
`)||/[ \t]\n|\n[ \t]/.test(_))return
|
|
18
|
-
${$}`)+"'";return w.implicitKey?X:s_.foldFlowLines(X,$,s_.FOLD_FLOW,
|
|
16
|
+
`,G+=2;if(W+=J,$[G+2]===" ")W+="\\";G+=1,Q=G+1}break;default:G+=1}}return W=Q?W+$.slice(Q):$,X?W:s_.foldFlowLines(W,J,s_.FOLD_QUOTED,F2(w,!1))}function s1(_,w){if(w.options.singleQuote===!1||w.implicitKey&&_.includes(`
|
|
17
|
+
`)||/[ \t]\n|\n[ \t]/.test(_))return M0(_,w);let $=w.indent||(K2(_)?" ":""),X="'"+_.replace(/'/g,"''").replace(/\n+/g,`$&
|
|
18
|
+
${$}`)+"'";return w.implicitKey?X:s_.foldFlowLines(X,$,s_.FOLD_FLOW,F2(w,!1))}function dw(_,w){let{singleQuote:$}=w.options,X;if($===!1)X=M0;else{let Y=_.includes('"'),J=_.includes("'");if(Y&&!J)X=s1;else if(J&&!Y)X=M0;else X=$?s1:M0}return X(_,w)}var t1;try{t1=new RegExp(`(^|(?<!
|
|
19
19
|
))
|
|
20
20
|
+(?!
|
|
21
|
-
|$)`,"g")}catch{
|
|
21
|
+
|$)`,"g")}catch{t1=/\n+(?!\n|$)/g}function L2({comment:_,type:w,value:$},X,Y,J){let{blockQuote:W,commentString:Q,lineWidth:G}=X.options;if(!W||/\n[\t ]+$/.test($))return dw($,X);let q=X.indent||(X.forceBlockIndent||K2($)?" ":""),H=W==="literal"?!0:W==="folded"||w===b_.Scalar.BLOCK_FOLDED?!1:w===b_.Scalar.BLOCK_LITERAL?!0:!LJ($,G,q.length);if(!$)return H?`|
|
|
22
22
|
`:`>
|
|
23
|
-
`;let B,D;for(D=$.length;D>0;--D){let
|
|
24
|
-
`&&
|
|
25
|
-
`);if(
|
|
26
|
-
`)
|
|
27
|
-
`)
|
|
28
|
-
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${
|
|
29
|
-
${
|
|
30
|
-
${
|
|
31
|
-
`)||H&&/[[\]{},]/.test(
|
|
32
|
-
`)?
|
|
33
|
-
`))return
|
|
34
|
-
${G}`);if(W){let D=(U)=>U.default&&U.tag!=="tag:yaml.org,2002:str"&&U.test?.test(B),{compat:
|
|
35
|
-
${w.indent}${
|
|
36
|
-
${
|
|
37
|
-
`:"",f){let
|
|
38
|
-
${
|
|
39
|
-
`&&
|
|
40
|
-
|
|
41
|
-
`}else
|
|
42
|
-
${$.indent}`}else if(!
|
|
43
|
-
`),C=
|
|
44
|
-
${$.indent}`}}else if(
|
|
45
|
-
`)
|
|
23
|
+
`;let B,D;for(D=$.length;D>0;--D){let b=$[D-1];if(b!==`
|
|
24
|
+
`&&b!=="\t"&&b!==" ")break}let O=$.substring(D),z=O.indexOf(`
|
|
25
|
+
`);if(z===-1)B="-";else if($===O||z!==O.length-1){if(B="+",J)J()}else B="";if(O){if($=$.slice(0,-O.length),O[O.length-1]===`
|
|
26
|
+
`)O=O.slice(0,-1);O=O.replace(t1,`$&${q}`)}let U=!1,V,M=-1;for(V=0;V<$.length;++V){let b=$[V];if(b===" ")U=!0;else if(b===`
|
|
27
|
+
`)M=V;else break}let f=$.substring(0,M<V?M+1:V);if(f)$=$.substring(f.length),f=f.replace(/\n+/g,`$&${q}`);let R=(U?q?"2":"1":"")+B;if(_){if(R+=" "+Q(_.replace(/ ?[\r\n]+/g," ")),Y)Y()}if(!H){let b=$.replace(/\n+/g,`
|
|
28
|
+
$&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${q}`),F=!1,T=F2(X,!0);if(W!=="folded"&&w!==b_.Scalar.BLOCK_FOLDED)T.onOverflow=()=>{F=!0};let j=s_.foldFlowLines(`${f}${b}${O}`,q,s_.FOLD_BLOCK,T);if(!F)return`>${R}
|
|
29
|
+
${q}${j}`}return $=$.replace(/\n+/g,`$&${q}`),`|${R}
|
|
30
|
+
${q}${f}${$}${O}`}function FJ(_,w,$,X){let{type:Y,value:J}=_,{actualString:W,implicitKey:Q,indent:G,indentStep:q,inFlow:H}=w;if(Q&&J.includes(`
|
|
31
|
+
`)||H&&/[[\]{},]/.test(J))return dw(J,w);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(J))return Q||H||!J.includes(`
|
|
32
|
+
`)?dw(J,w):L2(_,w,$,X);if(!Q&&!H&&Y!==b_.Scalar.PLAIN&&J.includes(`
|
|
33
|
+
`))return L2(_,w,$,X);if(K2(J)){if(G==="")return w.forceBlockIndent=!0,L2(_,w,$,X);else if(Q&&G===q)return dw(J,w)}let B=J.replace(/\n+/g,`$&
|
|
34
|
+
${G}`);if(W){let D=(U)=>U.default&&U.tag!=="tag:yaml.org,2002:str"&&U.test?.test(B),{compat:O,tags:z}=w.doc.schema;if(z.some(D)||O?.some(D))return dw(J,w)}return Q?B:s_.foldFlowLines(B,G,s_.FOLD_FLOW,F2(w,!1))}function KJ(_,w,$,X){let{implicitKey:Y,inFlow:J}=w,W=typeof _.value==="string"?_:Object.assign({},_,{value:String(_.value)}),{type:Q}=_;if(Q!==b_.Scalar.QUOTE_DOUBLE){if(/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(W.value))Q=b_.Scalar.QUOTE_DOUBLE}let G=(H)=>{switch(H){case b_.Scalar.BLOCK_FOLDED:case b_.Scalar.BLOCK_LITERAL:return Y||J?dw(W.value,w):L2(W,w,$,X);case b_.Scalar.QUOTE_DOUBLE:return M0(W.value,w);case b_.Scalar.QUOTE_SINGLE:return s1(W.value,w);case b_.Scalar.PLAIN:return FJ(W,w,$,X);default:return null}},q=G(Q);if(q===null){let{defaultKeyType:H,defaultStringType:B}=w.options,D=Y&&H||B;if(q=G(D),q===null)throw Error(`Unsupported default string type ${D}`)}return q}NJ.stringifyString=KJ});var f0=P((IJ)=>{var jJ=A2(),t_=p(),EJ=A0(),SJ=R0();function PJ(_,w){let $=Object.assign({blockQuote:!0,commentString:EJ.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 ZJ(_,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(t_.isScalar(w)){X=w.value;let Y=_.filter((J)=>J.identify?.(X));if(Y.length>1){let J=Y.filter((W)=>W.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=(t_.isScalar(_)||t_.isCollection(_))&&_.anchor;if(J&&jJ.anchorIsValid(J))$.add(J),Y.push(`&${J}`);let W=_.tag??(w.default?null:w.tag);if(W)Y.push(X.directives.tagString(W));return Y.join(" ")}function TJ(_,w,$,X){if(t_.isPair(_))return _.toString(w,$,X);if(t_.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=t_.isNode(_)?_:w.doc.createNode(_,{onTagObj:(G)=>Y=G});Y??(Y=ZJ(w.doc.schema.tags,J));let W=CJ(J,Y,w);if(W.length>0)w.indentAtStart=(w.indentAtStart??0)+W.length+1;let Q=typeof Y.stringify==="function"?Y.stringify(J,w,$,X):t_.isScalar(J)?SJ.stringifyString(J,w,$,X):J.toString(w,$,X);if(!W)return Q;return t_.isScalar(J)||Q[0]==="{"||Q[0]==="["?`${W} ${Q}`:`${W}
|
|
35
|
+
${w.indent}${Q}`}IJ.createStringifyContext=PJ;IJ.stringify=TJ});var i8=P((yJ)=>{var l_=p(),d8=X_(),p8=f0(),L0=A0();function hJ({key:_,value:w},$,X,Y){let{allNullValues:J,doc:W,indent:Q,indentStep:G,options:{commentString:q,indentSeq:H,simpleKeys:B}}=$,D=l_.isNode(_)&&_.comment||null;if(B){if(D)throw Error("With simple keys, key nodes cannot have comments");if(l_.isCollection(_)||!l_.isNode(_)&&typeof _==="object")throw Error("With simple keys, collection cannot be used as a key value")}let O=!B&&(!_||D&&w==null&&!$.inFlow||l_.isCollection(_)||(l_.isScalar(_)?_.type===d8.Scalar.BLOCK_FOLDED||_.type===d8.Scalar.BLOCK_LITERAL:typeof _==="object"));$=Object.assign({},$,{allNullValues:!1,implicitKey:!O&&(B||!J),indent:Q+G});let z=!1,U=!1,V=p8.stringify(_,$,()=>z=!0,()=>U=!0);if(!O&&!$.inFlow&&V.length>1024){if(B)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&&!B||w==null&&O){if(V=`? ${V}`,D&&!z)V+=L0.lineComment(V,$.indent,q(D));else if(U&&Y)Y();return V}if(z)D=null;if(O){if(D)V+=L0.lineComment(V,$.indent,q(D));V=`? ${V}
|
|
36
|
+
${Q}:`}else if(V=`${V}:`,D)V+=L0.lineComment(V,$.indent,q(D));let M,f,N;if(l_.isNode(w))M=!!w.spaceBefore,f=w.commentBefore,N=w.comment;else if(M=!1,f=null,N=null,w&&typeof w==="object")w=W.createNode(w);if($.implicitKey=!1,!O&&!D&&l_.isScalar(w))$.indentAtStart=V.length+1;if(U=!1,!H&&G.length>=2&&!$.inFlow&&!O&&l_.isSeq(w)&&!w.flow&&!w.tag&&!w.anchor)$.indent=$.indent.substring(2);let R=!1,b=p8.stringify(w,$,()=>R=!0,()=>U=!0),F=" ";if(D||M||f){if(F=M?`
|
|
37
|
+
`:"",f){let T=q(f);F+=`
|
|
38
|
+
${L0.indentComment(T,$.indent)}`}if(b===""&&!$.inFlow){if(F===`
|
|
39
|
+
`&&N)F=`
|
|
40
|
+
|
|
41
|
+
`}else F+=`
|
|
42
|
+
${$.indent}`}else if(!O&&l_.isCollection(w)){let T=b[0],j=b.indexOf(`
|
|
43
|
+
`),C=j!==-1,y=$.inFlow??w.flow??w.items.length===0;if(C||!y){let i=!1;if(C&&(T==="&"||T==="!")){let v=b.indexOf(" ");if(T==="&"&&v!==-1&&v<j&&b[v+1]==="!")v=b.indexOf(" ",v+1);if(v===-1||j<v)i=!0}if(!i)F=`
|
|
44
|
+
${$.indent}`}}else if(b===""||b[0]===`
|
|
45
|
+
`)F="";if(V+=F+b,$.inFlow){if(R&&X)X()}else if(N&&!R)V+=L0.lineComment(V,$.indent,q(N));else if(U&&Y)Y();return V}yJ.stringifyPair=hJ});var e1=P((uJ)=>{var n8=$2("process");function xJ(_,...w){if(_==="debug")console.log(...w)}function mJ(_,w){if(_==="debug"||_==="warn")if(typeof n8.emitWarning==="function")n8.emitWarning(w);else console.warn(w)}uJ.debug=xJ;uJ.warn=mJ});var E2=P((pJ)=>{var j2=p(),r8=X_(),N2="<<",b2={identify:(_)=>_===N2||typeof _==="symbol"&&_.description===N2,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new r8.Scalar(Symbol(N2)),{addToJSMap:a8}),stringify:()=>N2},dJ=(_,w)=>(b2.identify(w)||j2.isScalar(w)&&(!w.type||w.type===r8.Scalar.PLAIN)&&b2.identify(w.value))&&_?.doc.schema.tags.some(($)=>$.tag===b2.tag&&$.default);function a8(_,w,$){let X=o8(_,$);if(j2.isSeq(X))for(let Y of X.items)_3(_,w,Y);else if(Array.isArray(X))for(let Y of X)_3(_,w,Y);else _3(_,w,X)}function _3(_,w,$){let X=o8(_,$);if(!j2.isMap(X))throw Error("Merge sources must be maps or map aliases");let Y=X.toJSON(null,_,Map);for(let[J,W]of Y)if(w instanceof Map){if(!w.has(J))w.set(J,W)}else if(w instanceof Set)w.add(J);else if(!Object.prototype.hasOwnProperty.call(w,J))Object.defineProperty(w,J,{value:W,writable:!0,enumerable:!0,configurable:!0});return w}function o8(_,w){return _&&j2.isAlias(w)?w.resolve(_.doc,_):w}pJ.addMergeToJSMap=a8;pJ.isMergeKey=dJ;pJ.merge=b2});var $3=P((eJ)=>{var aJ=e1(),s8=E2(),oJ=f0(),t8=p(),w3=o_();function sJ(_,w,{key:$,value:X}){if(t8.isNode($)&&$.addToJSMap)$.addToJSMap(_,w,X);else if(s8.isMergeKey(_,$))s8.addMergeToJSMap(_,w,X);else{let Y=w3.toJS($,"",_);if(w instanceof Map)w.set(Y,w3.toJS(X,Y,_));else if(w instanceof Set)w.add(Y);else{let J=tJ($,Y,_),W=w3.toJS(X,J,_);if(J in w)Object.defineProperty(w,J,{value:W,writable:!0,enumerable:!0,configurable:!0});else w[J]=W}}return w}function tJ(_,w,$){if(w===null)return"";if(typeof w!=="object")return String(w);if(t8.isNode(_)&&$?.doc){let X=oJ.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)+'..."';aJ.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)}eJ.addPairToJSMap=sJ});var e_=P((YW)=>{var e8=O0(),wW=i8(),$W=$3(),S2=p();function XW(_,w,$){let X=e8.createNode(_,void 0,$),Y=e8.createNode(w,void 0,$);return new P2(X,Y)}class P2{constructor(_,w=null){Object.defineProperty(this,S2.NODE_TYPE,{value:S2.PAIR}),this.key=_,this.value=w}clone(_){let{key:w,value:$}=this;if(S2.isNode(w))w=w.clone(_);if(S2.isNode($))$=$.clone(_);return new P2(w,$)}toJSON(_,w){let $=w?.mapAsMap?new Map:{};return $W.addPairToJSMap(w,$,this)}toString(_,w,$){return _?.doc?wW.stringifyPair(this,_,w,$):JSON.stringify(this)}}YW.Pair=P2;YW.createPair=XW});var X3=P((HW)=>{var zw=p(),_$=f0(),Z2=A0();function QW(_,w,$){return(w.inFlow??_.flow?qW:GW)(_,w,$)}function GW({comment:_,items:w},$,{blockItemPrefix:X,flowChars:Y,itemIndent:J,onChompKeep:W,onComment:Q}){let{indent:G,options:{commentString:q}}=$,H=Object.assign({},$,{indent:J,type:null}),B=!1,D=[];for(let z=0;z<w.length;++z){let U=w[z],V=null;if(zw.isNode(U)){if(!B&&U.spaceBefore)D.push("");if(C2($,D,U.commentBefore,B),U.comment)V=U.comment}else if(zw.isPair(U)){let f=zw.isNode(U.key)?U.key:null;if(f){if(!B&&f.spaceBefore)D.push("");C2($,D,f.commentBefore,B)}}B=!1;let M=_$.stringify(U,H,()=>V=null,()=>B=!0);if(V)M+=Z2.lineComment(M,J,q(V));if(B&&V)B=!1;D.push(X+M)}let O;if(D.length===0)O=Y.start+Y.end;else{O=D[0];for(let z=1;z<D.length;++z){let U=D[z];O+=U?`
|
|
46
46
|
${G}${U}`:`
|
|
47
|
-
`}}if(_){if(
|
|
48
|
-
`+
|
|
49
|
-
`)),
|
|
50
|
-
${
|
|
51
|
-
`;return`${
|
|
52
|
-
${
|
|
53
|
-
`:" ")}return
|
|
54
|
-
${
|
|
55
|
-
${Y.comment}`:X.comment}X=J}_.items[$]=m1.isPair(X)?X:new O3.Pair(X)}else w("Expected a sequence for this tag");return _}function x8(_,w,$){let{replacer:X}=$,J=new aq.YAMLSeq(_);J.tag="tag:yaml.org,2002:pairs";let Y=0;if(w&&Symbol.iterator in Object(w))for(let W of w){if(typeof X==="function")W=X.call(w,String(Y++),W);let q,G;if(Array.isArray(W))if(W.length===2)q=W[0],G=W[1];else throw TypeError(`Expected [key, value] tuple: ${W}`);else if(W&&W instanceof Object){let Q=Object.keys(W);if(Q.length===1)q=Q[0],G=W[q];else throw TypeError(`Expected tuple with one key, not ${Q.length} keys`)}else q=W;J.items.push(O3.createPair(q,G,$))}return J}var oq={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:v8,createNode:x8};sq.createPairs=x8;sq.pairs=oq;sq.resolvePairs=v8});var f3=P((XG)=>{var m8=p(),F3=o_(),h0=ww(),wG=$w(),u8=u1();class Mw extends wG.YAMLSeq{constructor(){super();this.add=h0.YAMLMap.prototype.add.bind(this),this.delete=h0.YAMLMap.prototype.delete.bind(this),this.get=h0.YAMLMap.prototype.get.bind(this),this.has=h0.YAMLMap.prototype.has.bind(this),this.set=h0.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 J,Y;if(m8.isPair(X))J=F3.toJS(X.key,"",w),Y=F3.toJS(X.value,J,w);else J=F3.toJS(X,"",w);if($.has(J))throw Error("Ordered maps must not include duplicate keys");$.set(J,Y)}return $}static from(_,w,$){let X=u8.createPairs(_,w,$),J=new this;return J.items=X.items,J}}Mw.tag="tag:yaml.org,2002:omap";var $G={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Mw,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=u8.resolvePairs(_,w),X=[];for(let{key:J}of $.items)if(m8.isScalar(J))if(X.includes(J.value))w(`Ordered maps must not include duplicate keys: ${J.value}`);else X.push(J.value);return Object.assign(new Mw,$)},createNode:(_,w,$)=>Mw.from(_,w,$)};XG.YAMLOMap=Mw;XG.omap=$G});var i8=P((WG)=>{var l8=$_();function c8({value:_,source:w},$){if(w&&(_?d8:p8).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var d8={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new l8.Scalar(!0),stringify:c8},p8={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new l8.Scalar(!1),stringify:c8};WG.falseTag=p8;WG.trueTag=d8});var r8=P((UG)=>{var QG=$_(),L3=nw(),HG={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:L3.stringifyNumber},DG={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():L3.stringifyNumber(_)}},BG={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new QG.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:L3.stringifyNumber};UG.float=BG;UG.floatExp=DG;UG.floatNaN=HG});var a8=P((fG)=>{var n8=nw(),y0=(_)=>typeof _==="bigint"||Number.isInteger(_);function l1(_,w,$,{intAsBigInt:X}){let J=_[0];if(J==="-"||J==="+")w+=1;if(_=_.substring(w).replace(/_/g,""),X){switch($){case 2:_=`0b${_}`;break;case 8:_=`0o${_}`;break;case 16:_=`0x${_}`;break}let W=BigInt(_);return J==="-"?BigInt(-1)*W:W}let Y=parseInt(_,$);return J==="-"?-1*Y:Y}function K3(_,w,$){let{value:X}=_;if(y0(X)){let J=X.toString(w);return X<0?"-"+$+J.substr(1):$+J}return n8.stringifyNumber(_)}var MG={identify:y0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>l1(_,2,2,$),stringify:(_)=>K3(_,2,"0b")},RG={identify:y0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>l1(_,1,8,$),stringify:(_)=>K3(_,8,"0")},OG={identify:y0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>l1(_,0,10,$),stringify:n8.stringifyNumber},FG={identify:y0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>l1(_,2,16,$),stringify:(_)=>K3(_,16,"0x")};fG.int=OG;fG.intBin=MG;fG.intHex=FG;fG.intOct=RG});var N3=P((EG)=>{var p1=p(),c1=e_(),d1=ww();class Rw extends d1.YAMLMap{constructor(_){super(_);this.tag=Rw.tag}add(_){let w;if(p1.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new c1.Pair(_.key,null);else w=new c1.Pair(_,null);if(!d1.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=d1.findPair(this.items,_);return!w&&p1.isPair($)?p1.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 $=d1.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new c1.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}=$,J=new this(_);if(w&&Symbol.iterator in Object(w))for(let Y of w){if(typeof X==="function")Y=X.call(w,Y,Y);J.items.push(c1.createPair(Y,null,$))}return J}}Rw.tag="tag:yaml.org,2002:set";var jG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Rw,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Rw.from(_,w,$),resolve(_,w){if(p1.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Rw,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};EG.YAMLSet=Rw;EG.set=jG});var j3=P((IG)=>{var ZG=nw();function b3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,J=(W)=>w?BigInt(W):Number(W),Y=X.replace(/_/g,"").split(":").reduce((W,q)=>W*J(60)+J(q),J(0));return $==="-"?J(-1)*Y:Y}function o8(_){let{value:w}=_,$=(W)=>W;if(typeof w==="bigint")$=(W)=>BigInt(W);else if(isNaN(w)||!isFinite(w))return ZG.stringifyNumber(_);let X="";if(w<0)X="-",w*=$(-1);let J=$(60),Y=[w%J];if(w<60)Y.unshift(0);else if(w=(w-Y[0])/J,Y.unshift(w%J),w>=60)w=(w-Y[0])/J,Y.unshift(w);return X+Y.map((W)=>String(W).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var CG={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:$})=>b3(_,$),stringify:o8},TG={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:(_)=>b3(_,!1),stringify:o8},s8={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(s8.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,J,Y,W,q]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,Q=Date.UTC($,X-1,J,Y||0,W||0,q||0,G),H=w[8];if(H&&H!=="Z"){let B=b3(H,!1);if(Math.abs(B)<30)B*=60;Q-=60000*B}return new Date(Q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};IG.floatTime=TG;IG.intTime=CG;IG.timestamp=s8});var e8=P((rG)=>{var yG=iw(),vG=y1(),xG=rw(),mG=g0(),uG=R3(),t8=i8(),E3=r8(),i1=a8(),lG=P1(),cG=f3(),dG=u1(),pG=N3(),S3=j3(),iG=[yG.map,xG.seq,mG.string,vG.nullTag,t8.trueTag,t8.falseTag,i1.intBin,i1.intOct,i1.int,i1.intHex,E3.floatNaN,E3.floatExp,E3.float,uG.binary,lG.merge,cG.omap,dG.pairs,pG.set,S3.intTime,S3.floatTime,S3.timestamp];rG.schema=iG});var Q5=P(($Q)=>{var X5=iw(),aG=y1(),J5=rw(),oG=g0(),sG=H3(),P3=B3(),Z3=z3(),tG=k8(),eG=y8(),Y5=R3(),v0=P1(),W5=f3(),q5=u1(),_5=e8(),G5=N3(),r1=j3(),w5=new Map([["core",tG.schema],["failsafe",[X5.map,J5.seq,oG.string]],["json",eG.schema],["yaml11",_5.schema],["yaml-1.1",_5.schema]]),$5={binary:Y5.binary,bool:sG.boolTag,float:P3.float,floatExp:P3.floatExp,floatNaN:P3.floatNaN,floatTime:r1.floatTime,int:Z3.int,intHex:Z3.intHex,intOct:Z3.intOct,intTime:r1.intTime,map:X5.map,merge:v0.merge,null:aG.nullTag,omap:W5.omap,pairs:q5.pairs,seq:J5.seq,set:G5.set,timestamp:r1.timestamp},_Q={"tag:yaml.org,2002:binary":Y5.binary,"tag:yaml.org,2002:merge":v0.merge,"tag:yaml.org,2002:omap":W5.omap,"tag:yaml.org,2002:pairs":q5.pairs,"tag:yaml.org,2002:set":G5.set,"tag:yaml.org,2002:timestamp":r1.timestamp};function wQ(_,w,$){let X=w5.get(w);if(X&&!_)return $&&!X.includes(v0.merge)?X.concat(v0.merge):X.slice();let J=X;if(!J)if(Array.isArray(_))J=[];else{let Y=Array.from(w5.keys()).filter((W)=>W!=="yaml11").map((W)=>JSON.stringify(W)).join(", ");throw Error(`Unknown schema "${w}"; use one of ${Y} or define customTags array`)}if(Array.isArray(_))for(let Y of _)J=J.concat(Y);else if(typeof _==="function")J=_(J.slice());if($)J=J.concat(v0.merge);return J.reduce((Y,W)=>{let q=typeof W==="string"?$5[W]:W;if(!q){let G=JSON.stringify(W),Q=Object.keys($5).map((H)=>JSON.stringify(H)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${Q}`)}if(!Y.includes(q))Y.push(q);return Y},[])}$Q.coreKnownTags=_Q;$Q.getTags=wQ});var I3=P((QQ)=>{var C3=p(),YQ=iw(),WQ=rw(),qQ=g0(),n1=Q5(),GQ=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class T3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:J,sortMapEntries:Y,toStringDefaults:W}){this.compat=Array.isArray(_)?n1.getTags(_,"compat"):_?n1.getTags(null,_):null,this.name=typeof J==="string"&&J||"core",this.knownTags=X?n1.coreKnownTags:{},this.tags=n1.getTags(w,this.name,$),this.toStringOptions=W??null,Object.defineProperty(this,C3.MAP,{value:YQ.map}),Object.defineProperty(this,C3.SCALAR,{value:qQ.string}),Object.defineProperty(this,C3.SEQ,{value:WQ.seq}),this.sortMapEntries=typeof Y==="function"?Y:Y===!0?GQ:null}clone(){let _=Object.create(T3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}QQ.Schema=T3});var H5=P((UQ)=>{var DQ=p(),g3=C0(),x0=S0();function BQ(_,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 J=g3.createStringifyContext(_,w),{commentString:Y}=J.options;if(_.commentBefore){if($.length!==1)$.unshift("");let G=Y(_.commentBefore);$.unshift(x0.indentComment(G,""))}let W=!1,q=null;if(_.contents){if(DQ.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let H=Y(_.contents.commentBefore);$.push(x0.indentComment(H,""))}J.forceBlockIndent=!!_.comment,q=_.contents.comment}let G=q?void 0:()=>W=!0,Q=g3.stringify(_.contents,J,()=>q=null,G);if(q)Q+=x0.lineComment(Q,"",Y(q));if((Q[0]==="|"||Q[0]===">")&&$[$.length-1]==="---")$[$.length-1]=`--- ${Q}`;else $.push(Q)}else $.push(g3.stringify(_.contents,J));if(_.directives?.docEnd)if(_.comment){let G=Y(_.comment);if(G.includes(`
|
|
56
|
-
`))$.push("..."),$.push(
|
|
47
|
+
`}}if(_){if(O+=`
|
|
48
|
+
`+Z2.indentComment(q(_),G),Q)Q()}else if(B&&W)W();return O}function qW({items:_},w,{flowChars:$,itemIndent:X}){let{indent:Y,indentStep:J,flowCollectionPadding:W,options:{commentString:Q}}=w;X+=J;let G=Object.assign({},w,{indent:X,inFlow:!0,type:null}),q=!1,H=0,B=[];for(let z=0;z<_.length;++z){let U=_[z],V=null;if(zw.isNode(U)){if(U.spaceBefore)B.push("");if(C2(w,B,U.commentBefore,!1),U.comment)V=U.comment}else if(zw.isPair(U)){let f=zw.isNode(U.key)?U.key:null;if(f){if(f.spaceBefore)B.push("");if(C2(w,B,f.commentBefore,!1),f.comment)q=!0}let N=zw.isNode(U.value)?U.value:null;if(N){if(N.comment)V=N.comment;if(N.commentBefore)q=!0}else if(U.value==null&&f?.comment)V=f.comment}if(V)q=!0;let M=_$.stringify(U,G,()=>V=null);if(q||(q=B.length>H||M.includes(`
|
|
49
|
+
`)),z<_.length-1)M+=",";else if(w.options.trailingComma){if(w.options.lineWidth>0)q||(q=B.reduce((f,N)=>f+N.length+2,2)+(M.length+2)>w.options.lineWidth);if(q)M+=","}if(V)M+=Z2.lineComment(M,X,Q(V));B.push(M),H=B.length}let{start:D,end:O}=$;if(B.length===0)return D+O;else{if(!q){let z=B.reduce((U,V)=>U+V.length+2,2);q=w.options.lineWidth>0&&z>w.options.lineWidth}if(q){let z=D;for(let U of B)z+=U?`
|
|
50
|
+
${J}${Y}${U}`:`
|
|
51
|
+
`;return`${z}
|
|
52
|
+
${Y}${O}`}else return`${D}${W}${B.join(" ")}${W}${O}`}}function C2({indent:_,options:{commentString:w}},$,X,Y){if(X&&Y)X=X.replace(/^\n+/,"");if(X){let J=Z2.indentComment(w(X),_);$.push(J.trimStart())}}HW.stringifyCollection=QW});var ww=P((OW)=>{var BW=X3(),UW=$3(),zW=f2(),_w=p(),T2=e_(),VW=X_();function F0(_,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 w$ extends zW.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(_),W=(Q,G)=>{if(typeof Y==="function")G=Y.call(w,Q,G);else if(Array.isArray(Y)&&!Y.includes(Q))return;if(G!==void 0||X)J.items.push(T2.createPair(Q,G,$))};if(w instanceof Map)for(let[Q,G]of w)W(Q,G);else if(w&&typeof w==="object")for(let Q of Object.keys(w))W(Q,w[Q]);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=F0(this.items,$.key),Y=this.schema?.sortMapEntries;if(X){if(!w)throw Error(`Key ${$.key} already set`);if(_w.isScalar(X.value)&&VW.isScalarValue($.value))X.value.value=$.value;else X.value=$.value}else if(Y){let J=this.items.findIndex((W)=>Y($,W)<0);if(J===-1)this.items.push($);else this.items.splice(J,0,$)}else this.items.push($)}delete(_){let w=F0(this.items,_);if(!w)return!1;return this.items.splice(this.items.indexOf(w),1).length>0}get(_,w){let X=F0(this.items,_)?.value;return(!w&&_w.isScalar(X)?X.value:X)??void 0}has(_){return!!F0(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)UW.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 BW.stringifyCollection(this,_,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:_.indent||"",onChompKeep:$,onComment:w})}}OW.YAMLMap=w$;OW.findPair=F0});var pw=P((LW)=>{var RW=p(),$$=ww(),fW={collection:"map",default:!0,nodeClass:$$.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(_,w){if(!RW.isMap(_))w("Expected a mapping for this tag");return _},createNode:(_,w,$)=>$$.YAMLMap.from(_,w,$)};LW.map=fW});var $w=P((SW)=>{var KW=O0(),NW=X3(),bW=f2(),k2=p(),jW=X_(),EW=o_();class X$ extends bW.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(_){super(k2.SEQ,_);this.items=[]}add(_){this.items.push(_)}delete(_){let w=I2(_);if(typeof w!=="number")return!1;return this.items.splice(w,1).length>0}get(_,w){let $=I2(_);if(typeof $!=="number")return;let X=this.items[$];return!w&&k2.isScalar(X)?X.value:X}has(_){let w=I2(_);return typeof w==="number"&&w<this.items.length}set(_,w){let $=I2(_);if(typeof $!=="number")throw Error(`Expected a valid index, not ${_}.`);let X=this.items[$];if(k2.isScalar(X)&&jW.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(EW.toJS(Y,String(X++),w));return $}toString(_,w,$){if(!_)return JSON.stringify(this);return NW.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 W of w){if(typeof X==="function"){let Q=w instanceof Set?W:String(J++);W=X.call(w,Q,W)}Y.items.push(KW.createNode(W,void 0,$))}}return Y}}function I2(_){let w=k2.isScalar(_)?_.value:_;if(w&&typeof w==="string")w=Number(w);return typeof w==="number"&&Number.isInteger(w)&&w>=0?w:null}SW.YAMLSeq=X$});var iw=P((TW)=>{var ZW=p(),Y$=$w(),CW={collection:"seq",default:!0,nodeClass:Y$.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(_,w){if(!ZW.isSeq(_))w("Expected a sequence for this tag");return _},createNode:(_,w,$)=>Y$.YAMLSeq.from(_,w,$)};TW.seq=CW});var K0=P((hW)=>{var kW=R0(),gW={identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify(_,w,$,X){return w=Object.assign({actualString:!0},w),kW.stringifyString(_,w,$,X)}};hW.string=gW});var g2=P((vW)=>{var J$=X_(),W$={identify:(_)=>_==null,createNode:()=>new J$.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new J$.Scalar(null),stringify:({source:_},w)=>typeof _==="string"&&W$.test.test(_)?_:w.options.nullStr};vW.nullTag=W$});var Y3=P((uW)=>{var mW=X_(),Q$={identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:(_)=>new mW.Scalar(_[0]==="t"||_[0]==="T"),stringify({source:_,value:w},$){if(_&&Q$.test.test(_)){let X=_[0]==="t"||_[0]==="T";if(w===X)return _}return w?$.options.trueStr:$.options.falseStr}};uW.boolTag=Q$});var nw=P((dW)=>{function cW({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 W=J.indexOf(".");if(W<0)W=J.length,J+=".";let Q=w-(J.length-W-1);while(Q-- >0)J+="0"}return J}dW.stringifyNumber=cW});var W3=P((oW)=>{var iW=X_(),J3=nw(),nW={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:J3.stringifyNumber},rW={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():J3.stringifyNumber(_)}},aW={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(_){let w=new iW.Scalar(parseFloat(_)),$=_.indexOf(".");if($!==-1&&_[_.length-1]==="0")w.minFractionDigits=_.length-$-1;return w},stringify:J3.stringifyNumber};oW.float=aW;oW.floatExp=rW;oW.floatNaN=nW});var G3=P((XQ)=>{var G$=nw(),h2=(_)=>typeof _==="bigint"||Number.isInteger(_),Q3=(_,w,$,{intAsBigInt:X})=>X?BigInt(_):parseInt(_.substring(w),$);function q$(_,w,$){let{value:X}=_;if(h2(X)&&X>=0)return $+X.toString(w);return G$.stringifyNumber(_)}var _Q={identify:(_)=>h2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(_,w,$)=>Q3(_,2,8,$),stringify:(_)=>q$(_,8,"0o")},wQ={identify:h2,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(_,w,$)=>Q3(_,0,10,$),stringify:G$.stringifyNumber},$Q={identify:(_)=>h2(_)&&_>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(_,w,$)=>Q3(_,2,16,$),stringify:(_)=>q$(_,16,"0x")};XQ.int=wQ;XQ.intHex=$Q;XQ.intOct=_Q});var H$=P((UQ)=>{var QQ=pw(),GQ=g2(),qQ=iw(),HQ=K0(),DQ=Y3(),q3=W3(),H3=G3(),BQ=[QQ.map,qQ.seq,HQ.string,GQ.nullTag,DQ.boolTag,H3.intOct,H3.int,H3.intHex,q3.floatNaN,q3.floatExp,q3.float];UQ.schema=BQ});var B$=P((LQ)=>{var VQ=X_(),OQ=pw(),AQ=iw();function D$(_){return typeof _==="bigint"||Number.isInteger(_)}var y2=({value:_})=>JSON.stringify(_),MQ=[{identify:(_)=>typeof _==="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:(_)=>_,stringify:y2},{identify:(_)=>_==null,createNode:()=>new VQ.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:y2},{identify:(_)=>typeof _==="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:(_)=>_==="true",stringify:y2},{identify:D$,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(_,w,{intAsBigInt:$})=>$?BigInt(_):parseInt(_,10),stringify:({value:_})=>D$(_)?_.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:y2}],RQ={default:!0,tag:"",test:/^/,resolve(_,w){return w(`Unresolved plain scalar ${JSON.stringify(_)}`),_}},fQ=[OQ.map,AQ.seq].concat(MQ,RQ);LQ.schema=fQ});var B3=P((bQ)=>{var N0=$2("buffer"),D3=X_(),KQ=R0(),NQ={identify:(_)=>_ instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(_,w){if(typeof N0.Buffer==="function")return N0.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 W=$,Q;if(typeof N0.Buffer==="function")Q=W instanceof N0.Buffer?W.toString("base64"):N0.Buffer.from(W.buffer).toString("base64");else if(typeof btoa==="function"){let G="";for(let q=0;q<W.length;++q)G+=String.fromCharCode(W[q]);Q=btoa(G)}else throw Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(w??(w=D3.Scalar.BLOCK_LITERAL),w!==D3.Scalar.QUOTE_DOUBLE){let G=Math.max(X.options.lineWidth-X.indent.length,X.options.minContentWidth),q=Math.ceil(Q.length/G),H=Array(q);for(let B=0,D=0;B<q;++B,D+=G)H[B]=Q.substr(D,G);Q=H.join(w===D3.Scalar.BLOCK_LITERAL?`
|
|
53
|
+
`:" ")}return KQ.stringifyString({comment:_,type:w,value:Q},X,Y,J)}};bQ.binary=NQ});var x2=P((ZQ)=>{var v2=p(),U3=e_(),EQ=X_(),SQ=$w();function U$(_,w){if(v2.isSeq(_))for(let $=0;$<_.items.length;++$){let X=_.items[$];if(v2.isPair(X))continue;else if(v2.isMap(X)){if(X.items.length>1)w("Each pair must have its own sequence indicator");let Y=X.items[0]||new U3.Pair(new EQ.Scalar(null));if(X.commentBefore)Y.key.commentBefore=Y.key.commentBefore?`${X.commentBefore}
|
|
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[$]=v2.isPair(X)?X:new U3.Pair(X)}else w("Expected a sequence for this tag");return _}function z$(_,w,$){let{replacer:X}=$,Y=new SQ.YAMLSeq(_);Y.tag="tag:yaml.org,2002:pairs";let J=0;if(w&&Symbol.iterator in Object(w))for(let W of w){if(typeof X==="function")W=X.call(w,String(J++),W);let Q,G;if(Array.isArray(W))if(W.length===2)Q=W[0],G=W[1];else throw TypeError(`Expected [key, value] tuple: ${W}`);else if(W&&W instanceof Object){let q=Object.keys(W);if(q.length===1)Q=q[0],G=W[Q];else throw TypeError(`Expected tuple with one key, not ${q.length} keys`)}else Q=W;Y.items.push(U3.createPair(Q,G,$))}return Y}var PQ={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:U$,createNode:z$};ZQ.createPairs=z$;ZQ.pairs=PQ;ZQ.resolvePairs=U$});var V3=P((hQ)=>{var V$=p(),z3=o_(),b0=ww(),kQ=$w(),O$=x2();class Vw extends kQ.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=Vw.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(V$.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=O$.createPairs(_,w,$),Y=new this;return Y.items=X.items,Y}}Vw.tag="tag:yaml.org,2002:omap";var gQ={collection:"seq",identify:(_)=>_ instanceof Map,nodeClass:Vw,default:!1,tag:"tag:yaml.org,2002:omap",resolve(_,w){let $=O$.resolvePairs(_,w),X=[];for(let{key:Y}of $.items)if(V$.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 Vw,$)},createNode:(_,w,$)=>Vw.from(_,w,$)};hQ.YAMLOMap=Vw;hQ.omap=gQ});var L$=P((xQ)=>{var A$=X_();function M$({value:_,source:w},$){if(w&&(_?R$:f$).test.test(w))return w;return _?$.options.trueStr:$.options.falseStr}var R$={identify:(_)=>_===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new A$.Scalar(!0),stringify:M$},f$={identify:(_)=>_===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new A$.Scalar(!1),stringify:M$};xQ.falseTag=f$;xQ.trueTag=R$});var F$=P((iQ)=>{var lQ=X_(),O3=nw(),cQ={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},dQ={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(_)}},pQ={identify:(_)=>typeof _==="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(_){let w=new lQ.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};iQ.float=pQ;iQ.floatExp=dQ;iQ.floatNaN=cQ});var N$=P((_G)=>{var K$=nw(),j0=(_)=>typeof _==="bigint"||Number.isInteger(_);function m2(_,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 W=BigInt(_);return Y==="-"?BigInt(-1)*W:W}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 K$.stringifyNumber(_)}var oQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(_,w,$)=>m2(_,2,2,$),stringify:(_)=>A3(_,2,"0b")},sQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(_,w,$)=>m2(_,1,8,$),stringify:(_)=>A3(_,8,"0")},tQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(_,w,$)=>m2(_,0,10,$),stringify:K$.stringifyNumber},eQ={identify:j0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(_,w,$)=>m2(_,2,16,$),stringify:(_)=>A3(_,16,"0x")};_G.int=tQ;_G.intBin=oQ;_G.intHex=eQ;_G.intOct=sQ});var M3=P((WG)=>{var c2=p(),u2=e_(),l2=ww();class Ow extends l2.YAMLMap{constructor(_){super(_);this.tag=Ow.tag}add(_){let w;if(c2.isPair(_))w=_;else if(_&&typeof _==="object"&&"key"in _&&"value"in _&&_.value===null)w=new u2.Pair(_.key,null);else w=new u2.Pair(_,null);if(!l2.findPair(this.items,w.key))this.items.push(w)}get(_,w){let $=l2.findPair(this.items,_);return!w&&c2.isPair($)?c2.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 $=l2.findPair(this.items,_);if($&&!w)this.items.splice(this.items.indexOf($),1);else if(!$&&w)this.items.push(new u2.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(u2.createPair(J,null,$))}return Y}}Ow.tag="tag:yaml.org,2002:set";var JG={collection:"map",identify:(_)=>_ instanceof Set,nodeClass:Ow,default:!1,tag:"tag:yaml.org,2002:set",createNode:(_,w,$)=>Ow.from(_,w,$),resolve(_,w){if(c2.isMap(_))if(_.hasAllNullValues(!0))return Object.assign(new Ow,_);else w("Set items must all have null values");else w("Expected a mapping for this tag");return _}};WG.YAMLSet=Ow;WG.set=JG});var f3=P((BG)=>{var qG=nw();function R3(_,w){let $=_[0],X=$==="-"||$==="+"?_.substring(1):_,Y=(W)=>w?BigInt(W):Number(W),J=X.replace(/_/g,"").split(":").reduce((W,Q)=>W*Y(60)+Y(Q),Y(0));return $==="-"?Y(-1)*J:J}function b$(_){let{value:w}=_,$=(W)=>W;if(typeof w==="bigint")$=(W)=>BigInt(W);else if(isNaN(w)||!isFinite(w))return qG.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((W)=>String(W).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var HG={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:b$},DG={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:b$},j$={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(j$.test);if(!w)throw Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,$,X,Y,J,W,Q]=w.map(Number),G=w[7]?Number((w[7]+"00").substr(1,3)):0,q=Date.UTC($,X-1,Y,J||0,W||0,Q||0,G),H=w[8];if(H&&H!=="Z"){let B=R3(H,!1);if(Math.abs(B)<30)B*=60;q-=60000*B}return new Date(q)},stringify:({value:_})=>_?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};BG.floatTime=DG;BG.intTime=HG;BG.timestamp=j$});var S$=P((jG)=>{var OG=pw(),AG=g2(),MG=iw(),RG=K0(),fG=B3(),E$=L$(),L3=F$(),d2=N$(),LG=E2(),FG=V3(),KG=x2(),NG=M3(),F3=f3(),bG=[OG.map,MG.seq,RG.string,AG.nullTag,E$.trueTag,E$.falseTag,d2.intBin,d2.intOct,d2.int,d2.intHex,L3.floatNaN,L3.floatExp,L3.float,fG.binary,LG.merge,FG.omap,KG.pairs,NG.set,F3.intTime,F3.floatTime,F3.timestamp];jG.schema=bG});var v$=P((gG)=>{var T$=pw(),SG=g2(),I$=iw(),PG=K0(),ZG=Y3(),K3=W3(),N3=G3(),CG=H$(),TG=B$(),k$=B3(),E0=E2(),g$=V3(),h$=x2(),P$=S$(),y$=M3(),p2=f3(),Z$=new Map([["core",CG.schema],["failsafe",[T$.map,I$.seq,PG.string]],["json",TG.schema],["yaml11",P$.schema],["yaml-1.1",P$.schema]]),C$={binary:k$.binary,bool:ZG.boolTag,float:K3.float,floatExp:K3.floatExp,floatNaN:K3.floatNaN,floatTime:p2.floatTime,int:N3.int,intHex:N3.intHex,intOct:N3.intOct,intTime:p2.intTime,map:T$.map,merge:E0.merge,null:SG.nullTag,omap:g$.omap,pairs:h$.pairs,seq:I$.seq,set:y$.set,timestamp:p2.timestamp},IG={"tag:yaml.org,2002:binary":k$.binary,"tag:yaml.org,2002:merge":E0.merge,"tag:yaml.org,2002:omap":g$.omap,"tag:yaml.org,2002:pairs":h$.pairs,"tag:yaml.org,2002:set":y$.set,"tag:yaml.org,2002:timestamp":p2.timestamp};function kG(_,w,$){let X=Z$.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(Z$.keys()).filter((W)=>W!=="yaml11").map((W)=>JSON.stringify(W)).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,W)=>{let Q=typeof W==="string"?C$[W]:W;if(!Q){let G=JSON.stringify(W),q=Object.keys(C$).map((H)=>JSON.stringify(H)).join(", ");throw Error(`Unknown custom tag ${G}; use one of ${q}`)}if(!J.includes(Q))J.push(Q);return J},[])}gG.coreKnownTags=IG;gG.getTags=kG});var E3=P((lG)=>{var b3=p(),vG=pw(),xG=iw(),mG=K0(),i2=v$(),uG=(_,w)=>_.key<w.key?-1:_.key>w.key?1:0;class j3{constructor({compat:_,customTags:w,merge:$,resolveKnownTags:X,schema:Y,sortMapEntries:J,toStringDefaults:W}){this.compat=Array.isArray(_)?i2.getTags(_,"compat"):_?i2.getTags(null,_):null,this.name=typeof Y==="string"&&Y||"core",this.knownTags=X?i2.coreKnownTags:{},this.tags=i2.getTags(w,this.name,$),this.toStringOptions=W??null,Object.defineProperty(this,b3.MAP,{value:vG.map}),Object.defineProperty(this,b3.SCALAR,{value:mG.string}),Object.defineProperty(this,b3.SEQ,{value:xG.seq}),this.sortMapEntries=typeof J==="function"?J:J===!0?uG:null}clone(){let _=Object.create(j3.prototype,Object.getOwnPropertyDescriptors(this));return _.tags=this.tags.slice(),_}}lG.Schema=j3});var x$=P((iG)=>{var dG=p(),S3=f0(),S0=A0();function pG(_,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 W=!1,Q=null;if(_.contents){if(dG.isNode(_.contents)){if(_.contents.spaceBefore&&X)$.push("");if(_.contents.commentBefore){let H=J(_.contents.commentBefore);$.push(S0.indentComment(H,""))}Y.forceBlockIndent=!!_.comment,Q=_.contents.comment}let G=Q?void 0:()=>W=!0,q=S3.stringify(_.contents,Y,()=>Q=null,G);if(Q)q+=S0.lineComment(q,"",J(Q));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(S0.indentComment(G,""));else $.push(`... ${G}`)}else $.push("...");else{let G=_.comment;if(G&&W)G=G.replace(/^\n+/,"");if(G){if((!W||Q)&&$[$.length-1]!=="")$.push("");$.push(S0.indentComment(J(G),""))}}return $.join(`
|
|
57
57
|
`)+`
|
|
58
|
-
`}
|
|
59
|
-
`;W=
|
|
58
|
+
`}iG.stringifyDocument=pG});var P0=P((wq)=>{var rG=V0(),rw=f2(),A_=p(),aG=e_(),oG=o_(),sG=E3(),tG=x$(),P3=A2(),eG=r1(),_q=O0(),Z3=n1();class C3{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 Z3.Directives({version:J});this.setSchema(J,$),this.contents=_===void 0?null:this.createNode(_,X,$)}clone(){let _=Object.create(C3.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(aw(this.contents))this.contents.add(_)}addIn(_,w){if(aw(this.contents))this.contents.addIn(_,w)}createAlias(_,w){if(!_.anchor){let $=P3.anchorNames(this);_.anchor=!w||$.has(w)?P3.findNewAnchor(w||"a",$):w}return new rG.Alias(_.anchor)}createNode(_,w,$){let X=void 0;if(typeof w==="function")_=w.call({"":_},"",_),X=w;else if(Array.isArray(w)){let U=(M)=>typeof M==="number"||M instanceof String||M 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:W,keepUndefined:Q,onTagObj:G,tag:q}=$??{},{onAnchor:H,setAnchors:B,sourceObjects:D}=P3.createNodeAnchors(this,J||"a"),O={aliasDuplicateObjects:Y??!0,keepUndefined:Q??!1,onAnchor:H,onTagObj:G,replacer:X,schema:this.schema,sourceObjects:D},z=_q.createNode(_,q,O);if(W&&A_.isCollection(z))z.flow=!0;return B(),z}createPair(_,w,$={}){let X=this.createNode(_,null,$),Y=this.createNode(w,null,$);return new aG.Pair(X,Y)}delete(_){return aw(this.contents)?this.contents.delete(_):!1}deleteIn(_){if(rw.isEmptyPath(_)){if(this.contents==null)return!1;return this.contents=null,!0}return aw(this.contents)?this.contents.deleteIn(_):!1}get(_,w){return A_.isCollection(this.contents)?this.contents.get(_,w):void 0}getIn(_,w){if(rw.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(rw.isEmptyPath(_))return this.contents!==void 0;return A_.isCollection(this.contents)?this.contents.hasIn(_):!1}set(_,w){if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,[_],w);else if(aw(this.contents))this.contents.set(_,w)}setIn(_,w){if(rw.isEmptyPath(_))this.contents=w;else if(this.contents==null)this.contents=rw.collectionFromPath(this.schema,Array.from(_),w);else if(aw(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 Z3.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 Z3.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 sG.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 W={anchors:new Map,doc:this,keep:!_,mapAsMap:$===!0,mapKeyWarned:!1,maxAliasCount:typeof X==="number"?X:100},Q=oG.toJS(this.contents,w??"",W);if(typeof Y==="function")for(let{count:G,res:q}of W.anchors.values())Y(q,G);return typeof J==="function"?eG.applyReviver(J,{"":Q},"",Q):Q}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 tG.stringifyDocument(this,_)}}function aw(_){if(A_.isCollection(_))return!0;throw Error("Expected a YAML collection as document contents")}wq.Document=C3});var Z0=P((Yq)=>{class n2 extends Error{constructor(_,w,$,X){super();this.name=_,this.code=$,this.message=X,this.pos=w}}class m$ extends n2{constructor(_,w,$){super("YAMLParseError",_,w,$)}}class u$ extends n2{constructor(_,w,$){super("YAMLWarning",_,w,$)}}var Xq=(_,w)=>($)=>{if($.pos[0]===-1)return;$.linePos=$.pos.map((Q)=>w.linePos(Q));let{line:X,col:Y}=$.linePos[0];$.message+=` at line ${X}, column ${Y}`;let J=Y-1,W=_.substring(w.lineStarts[X-1],w.lineStarts[X]).replace(/[\n\r]+$/,"");if(J>=60&&W.length>80){let Q=Math.min(J-39,W.length-79);W="\u2026"+W.substring(Q),J-=Q-1}if(W.length>80)W=W.substring(0,79)+"\u2026";if(X>1&&/^ *$/.test(W.substring(0,J))){let Q=_.substring(w.lineStarts[X-2],w.lineStarts[X-1]);if(Q.length>80)Q=Q.substring(0,79)+`\u2026
|
|
59
|
+
`;W=Q+W}if(/[^ ]/.test(W)){let Q=1,G=$.linePos[1];if(G?.line===X&&G.col>Y)Q=Math.max(1,Math.min(G.col-Y,80-J));let q=" ".repeat(J)+"^".repeat(Q);$.message+=`:
|
|
60
60
|
|
|
61
61
|
${W}
|
|
62
|
-
${
|
|
63
|
-
`}};
|
|
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(
|
|
65
|
-
`+U.comment;else
|
|
66
|
-
`+
|
|
67
|
-
`+
|
|
68
|
-
`+
|
|
69
|
-
`+C.comment;else
|
|
70
|
-
`+V.comment;else
|
|
71
|
-
`.repeat(Math.max(1,W.length-1)):"",V=X+
|
|
72
|
-
`;for(let U=H;U<
|
|
73
|
-
`;else if(V.length>G||
|
|
74
|
-
`;else if(!
|
|
62
|
+
${q}
|
|
63
|
+
`}};Yq.YAMLError=n2;Yq.YAMLParseError=m$;Yq.YAMLWarning=u$;Yq.prettifyError=Xq});var C0=P((Hq)=>{function qq(_,{flow:w,indicator:$,next:X,offset:Y,onError:J,parentIndent:W,startOnNewline:Q}){let G=!1,q=Q,H=Q,B="",D="",O=!1,z=!1,U=null,V=null,M=null,f=null,N=null,R=null,b=null;for(let j of _){if(z){if(j.type!=="space"&&j.type!=="newline"&&j.type!=="comma")J(j.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space");z=!1}if(U){if(q&&j.type!=="comment"&&j.type!=="newline")J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");U=null}switch(j.type){case"space":if(!w&&($!=="doc-start"||X?.type!=="flow-collection")&&j.source.includes("\t"))U=j;H=!0;break;case"comment":{if(!H)J(j,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let C=j.source.substring(1)||" ";if(!B)B=C;else B+=D+C;D="",q=!1;break}case"newline":if(q){if(B)B+=j.source;else if(!R||$!=="seq-item-ind")G=!0}else D+=j.source;if(q=!0,O=!0,V||M)f=j;H=!0;break;case"anchor":if(V)J(j,"MULTIPLE_ANCHORS","A node can have at most one anchor");if(j.source.endsWith(":"))J(j.offset+j.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0);V=j,b??(b=j.offset),q=!1,H=!1,z=!0;break;case"tag":{if(M)J(j,"MULTIPLE_TAGS","A node can have at most one tag");M=j,b??(b=j.offset),q=!1,H=!1,z=!0;break}case $:if(V||M)J(j,"BAD_PROP_ORDER",`Anchors and tags must be after the ${j.source} indicator`);if(R)J(j,"UNEXPECTED_TOKEN",`Unexpected ${j.source} in ${w??"collection"}`);R=j,q=$==="seq-item-ind"||$==="explicit-key-ind",H=!1;break;case"comma":if(w){if(N)J(j,"UNEXPECTED_TOKEN",`Unexpected , in ${w}`);N=j,q=!1,H=!1;break}default:J(j,"UNEXPECTED_TOKEN",`Unexpected ${j.type} token`),q=!1,H=!1}}let F=_[_.length-1],T=F?F.offset+F.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&&(q&&U.indent<=W||X?.type==="block-map"||X?.type==="block-seq"))J(U,"TAB_AS_INDENT","Tabs are not allowed as indentation");return{comma:N,found:R,spaceBefore:G,comment:B,hasNewline:O,anchor:V,tag:M,newlineAfterProp:f,end:T,start:b??T}}Hq.resolveProps=qq});var r2=P((Bq)=>{function T3(_){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(T3(w.key)||T3(w.value))return!0}return!1;default:return!0}}Bq.containsNewline=T3});var I3=P((Oq)=>{var zq=r2();function Vq(_,w,$){if(w?.type==="flow-collection"){let X=w.end[0];if(X.indent===_&&(X.source==="]"||X.source==="}")&&zq.containsNewline(w))$(X,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Oq.flowIndentCheck=Vq});var k3=P((Rq)=>{var l$=p();function Mq(_,w,$){let{uniqueKeys:X}=_.options;if(X===!1)return!1;let Y=typeof X==="function"?X:(J,W)=>J===W||l$.isScalar(J)&&l$.isScalar(W)&&J.value===W.value;return w.some((J)=>Y(J.key,$))}Rq.mapIncludes=Mq});var n$=P((bq)=>{var c$=e_(),Lq=ww(),d$=C0(),Fq=r2(),p$=I3(),Kq=k3(),i$="All mapping items must start at the same column";function Nq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let Q=new(J?.nodeClass??Lq.YAMLMap)($.schema);if($.atRoot)$.atRoot=!1;let G=X.offset,q=null;for(let H of X.items){let{start:B,key:D,sep:O,value:z}=H,U=d$.resolveProps(B,{indicator:"explicit-key-ind",next:D??O?.[0],offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0}),V=!U.found;if(V){if(D){if(D.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 D&&D.indent!==X.indent)Y(G,"BAD_INDENT",i$)}if(!U.anchor&&!U.tag&&!O){if(q=U.end,U.comment)if(Q.comment)Q.comment+=`
|
|
65
|
+
`+U.comment;else Q.comment=U.comment;continue}if(U.newlineAfterProp||Fq.containsNewline(D))Y(D??B[B.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",i$);$.atKey=!0;let M=U.end,f=D?_($,D,U,Y):w($,M,B,null,U,Y);if($.schema.compat)p$.flowIndentCheck(X.indent,D,Y);if($.atKey=!1,Kq.mapIncludes($,Q.items,f))Y(M,"DUPLICATE_KEY","Map keys must be unique");let N=d$.resolveProps(O??[],{indicator:"map-value-ind",next:z,offset:f.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!D||D.type==="block-scalar"});if(G=N.end,N.found){if(V){if(z?.type==="block-map"&&!N.hasNewline)Y(G,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings");if($.options.strict&&U.start<N.found.offset-1024)Y(f.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key")}let R=z?_($,z,N,Y):w($,G,O,null,N,Y);if($.schema.compat)p$.flowIndentCheck(X.indent,z,Y);G=R.range[2];let b=new c$.Pair(f,R);if($.options.keepSourceTokens)b.srcToken=H;Q.items.push(b)}else{if(V)Y(f.range,"MISSING_CHAR","Implicit map keys need to be followed by map values");if(N.comment)if(f.comment)f.comment+=`
|
|
66
|
+
`+N.comment;else f.comment=N.comment;let R=new c$.Pair(f);if($.options.keepSourceTokens)R.srcToken=H;Q.items.push(R)}}if(q&&q<G)Y(q,"IMPOSSIBLE","Map comment with trailing content");return Q.range=[X.offset,G,q??G],Q}bq.resolveBlockMap=Nq});var r$=P((Cq)=>{var Eq=$w(),Sq=C0(),Pq=I3();function Zq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let Q=new(J?.nodeClass??Eq.YAMLSeq)($.schema);if($.atRoot)$.atRoot=!1;if($.atKey)$.atKey=!1;let G=X.offset,q=null;for(let{start:H,value:B}of X.items){let D=Sq.resolveProps(H,{indicator:"seq-item-ind",next:B,offset:G,onError:Y,parentIndent:X.indent,startOnNewline:!0});if(!D.found)if(D.anchor||D.tag||B)if(B?.type==="block-seq")Y(D.end,"BAD_INDENT","All sequence items must start at the same column");else Y(G,"MISSING_CHAR","Sequence item without - indicator");else{if(q=D.end,D.comment)Q.comment=D.comment;continue}let O=B?_($,B,D,Y):w($,D.end,H,null,D,Y);if($.schema.compat)Pq.flowIndentCheck(X.indent,B,Y);G=O.range[2],Q.items.push(O)}return Q.range=[X.offset,G,q??G],Q}Cq.resolveBlockSeq=Zq});var ow=P((kq)=>{function Iq(_,w,$,X){let Y="";if(_){let J=!1,W="";for(let Q of _){let{source:G,type:q}=Q;switch(q){case"space":J=!0;break;case"comment":{if($&&!J)X(Q,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let H=G.substring(1)||" ";if(!Y)Y=H;else Y+=W+H;W="";break}case"newline":if(Y)W+=G;J=!0;break;default:X(Q,"UNEXPECTED_TOKEN",`Unexpected ${q} at node end`)}w+=G.length}}return{comment:Y,offset:w}}kq.resolveEnd=Iq});var s$=P((cq)=>{var hq=p(),yq=e_(),a$=ww(),vq=$w(),xq=ow(),o$=C0(),mq=r2(),uq=k3(),g3="Block collections are not allowed within flow collections",h3=(_)=>_&&(_.type==="block-map"||_.type==="block-seq");function lq({composeNode:_,composeEmptyNode:w},$,X,Y,J){let W=X.start.source==="{",Q=W?"flow map":"flow sequence",q=new(J?.nodeClass??(W?a$.YAMLMap:vq.YAMLSeq))($.schema);q.flow=!0;let H=$.atRoot;if(H)$.atRoot=!1;if($.atKey)$.atKey=!1;let B=X.offset+X.start.source.length;for(let V=0;V<X.items.length;++V){let M=X.items[V],{start:f,key:N,sep:R,value:b}=M,F=o$.resolveProps(f,{flow:Q,indicator:"explicit-key-ind",next:N??R?.[0],offset:B,onError:Y,parentIndent:X.indent,startOnNewline:!1});if(!F.found){if(!F.anchor&&!F.tag&&!R&&!b){if(V===0&&F.comma)Y(F.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`);else if(V<X.items.length-1)Y(F.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${Q}`);if(F.comment)if(q.comment)q.comment+=`
|
|
67
|
+
`+F.comment;else q.comment=F.comment;B=F.end;continue}if(!W&&$.options.strict&&mq.containsNewline(N))Y(N,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(V===0){if(F.comma)Y(F.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${Q}`)}else{if(!F.comma)Y(F.start,"MISSING_CHAR",`Missing , between ${Q} items`);if(F.comment){let T="";_:for(let j of f)switch(j.type){case"comma":case"space":break;case"comment":T=j.source.substring(1);break _;default:break _}if(T){let j=q.items[q.items.length-1];if(hq.isPair(j))j=j.value??j.key;if(j.comment)j.comment+=`
|
|
68
|
+
`+T;else j.comment=T;F.comment=F.comment.substring(T.length+1)}}}if(!W&&!R&&!F.found){let T=b?_($,b,F,Y):w($,F.end,R,null,F,Y);if(q.items.push(T),B=T.range[2],h3(b))Y(T.range,"BLOCK_IN_FLOW",g3)}else{$.atKey=!0;let T=F.end,j=N?_($,N,F,Y):w($,T,f,null,F,Y);if(h3(N))Y(j.range,"BLOCK_IN_FLOW",g3);$.atKey=!1;let C=o$.resolveProps(R??[],{flow:Q,indicator:"map-value-ind",next:b,offset:j.range[2],onError:Y,parentIndent:X.indent,startOnNewline:!1});if(C.found){if(!W&&!F.found&&$.options.strict){if(R)for(let v of R){if(v===C.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(F.start<C.found.offset-1024)Y(C.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else if(b)if("source"in b&&b.source?.[0]===":")Y(b,"MISSING_CHAR",`Missing space after : in ${Q}`);else Y(C.start,"MISSING_CHAR",`Missing , or : between ${Q} items`);let y=b?_($,b,C,Y):C.found?w($,C.end,R,null,C,Y):null;if(y){if(h3(b))Y(y.range,"BLOCK_IN_FLOW",g3)}else if(C.comment)if(j.comment)j.comment+=`
|
|
69
|
+
`+C.comment;else j.comment=C.comment;let i=new yq.Pair(j,y);if($.options.keepSourceTokens)i.srcToken=M;if(W){let v=q;if(uq.mapIncludes($,v.items,j))Y(T,"DUPLICATE_KEY","Map keys must be unique");v.items.push(i)}else{let v=new a$.YAMLMap($.schema);v.flow=!0,v.items.push(i);let c=(y??j).range;v.range=[j.range[0],c[1],c[2]],q.items.push(v)}B=y?y.range[2]:C.end}}let D=W?"}":"]",[O,...z]=X.end,U=B;if(O?.source===D)U=O.offset+O.source.length;else{let V=Q[0].toUpperCase()+Q.substring(1),M=H?`${V} must end with a ${D}`:`${V} in block collection must be sufficiently indented and end with a ${D}`;if(Y(B,H?"MISSING_CHAR":"BAD_INDENT",M),O&&O.source.length!==1)z.unshift(O)}if(z.length>0){let V=xq.resolveEnd(z,U,$.options.strict,Y);if(V.comment)if(q.comment)q.comment+=`
|
|
70
|
+
`+V.comment;else q.comment=V.comment;q.range=[X.offset,U,V.offset]}else q.range=[X.offset,U,U];return q}cq.resolveFlowCollection=lq});var t$=P((eq)=>{var pq=p(),iq=X_(),nq=ww(),rq=$w(),aq=n$(),oq=r$(),sq=s$();function y3(_,w,$,X,Y,J){let W=$.type==="block-map"?aq.resolveBlockMap(_,w,$,X,J):$.type==="block-seq"?oq.resolveBlockSeq(_,w,$,X,J):sq.resolveFlowCollection(_,w,$,X,J),Q=W.constructor;if(Y==="!"||Y===Q.tagName)return W.tag=Q.tagName,W;if(Y)W.tag=Y;return W}function tq(_,w,$,X,Y){let J=X.tag,W=!J?null:w.directives.tagName(J.source,(D)=>Y(J,"TAG_RESOLVE_FAILED",D));if($.type==="block-seq"){let{anchor:D,newlineAfterProp:O}=X,z=D&&J?D.offset>J.offset?D:J:D??J;if(z&&(!O||O.offset<z.offset))Y(z,"MISSING_CHAR","Missing newline after block sequence props")}let Q=$.type==="block-map"?"map":$.type==="block-seq"?"seq":$.start.source==="{"?"map":"seq";if(!J||!W||W==="!"||W===nq.YAMLMap.tagName&&Q==="map"||W===rq.YAMLSeq.tagName&&Q==="seq")return y3(_,w,$,Y,W);let G=w.schema.tags.find((D)=>D.tag===W&&D.collection===Q);if(!G){let D=w.schema.knownTags[W];if(D?.collection===Q)w.schema.tags.push(Object.assign({},D,{default:!1})),G=D;else{if(D)Y(J,"BAD_COLLECTION_TYPE",`${D.tag} used for ${Q} collection, but expects ${D.collection??"scalar"}`,!0);else Y(J,"TAG_RESOLVE_FAILED",`Unresolved tag: ${W}`,!0);return y3(_,w,$,Y,W)}}let q=y3(_,w,$,Y,W,G),H=G.resolve?.(q,(D)=>Y(J,"TAG_RESOLVE_FAILED",D),w.options)??q,B=pq.isNode(H)?H:new iq.Scalar(H);if(B.range=q.range,B.tag=W,G?.format)B.format=G.format;return B}eq.composeCollection=tq});var x3=P((YH)=>{var v3=X_();function wH(_,w,$){let X=w.offset,Y=$H(w,_.options.strict,$);if(!Y)return{value:"",type:null,comment:"",range:[X,X,X]};let J=Y.mode===">"?v3.Scalar.BLOCK_FOLDED:v3.Scalar.BLOCK_LITERAL,W=w.source?XH(w.source):[],Q=W.length;for(let U=W.length-1;U>=0;--U){let V=W[U][1];if(V===""||V==="\r")Q=U;else break}if(Q===0){let U=Y.chomp==="+"&&W.length>0?`
|
|
71
|
+
`.repeat(Math.max(1,W.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,q=w.offset+Y.length,H=0;for(let U=0;U<Q;++U){let[V,M]=W[U];if(M===""||M==="\r"){if(Y.indent===0&&V.length>G)G=V.length}else{if(V.length<G)$(q+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(H=U,G===0&&!_.atRoot)$(q,"BAD_INDENT","Block scalar values in collections must be indented");break}q+=V.length+M.length+1}for(let U=W.length-1;U>=Q;--U)if(W[U][0].length>G)Q=U+1;let B="",D="",O=!1;for(let U=0;U<H;++U)B+=W[U][0].slice(G)+`
|
|
72
|
+
`;for(let U=H;U<Q;++U){let[V,M]=W[U];q+=V.length+M.length+1;let f=M[M.length-1]==="\r";if(f)M=M.slice(0,-1);if(M&&V.length<G){let R=`Block scalar lines must not be less indented than their ${Y.indent?"explicit indentation indicator":"first line"}`;$(q-M.length-(f?2:1),"BAD_INDENT",R),V=""}if(J===v3.Scalar.BLOCK_LITERAL)B+=D+V.slice(G)+M,D=`
|
|
73
|
+
`;else if(V.length>G||M[0]==="\t"){if(D===" ")D=`
|
|
74
|
+
`;else if(!O&&D===`
|
|
75
75
|
`)D=`
|
|
76
76
|
|
|
77
|
-
`;B+=D+V.slice(G)+
|
|
78
|
-
`,
|
|
77
|
+
`;B+=D+V.slice(G)+M,D=`
|
|
78
|
+
`,O=!0}else if(M==="")if(D===`
|
|
79
79
|
`)B+=`
|
|
80
80
|
`;else D=`
|
|
81
|
-
`;else B+=D+
|
|
81
|
+
`;else B+=D+M,D=" ",O=!1}switch(Y.chomp){case"-":break;case"+":for(let U=Q;U<W.length;++U)B+=`
|
|
82
82
|
`+W[U][0].slice(G);if(B[B.length-1]!==`
|
|
83
83
|
`)B+=`
|
|
84
84
|
`;break;default:B+=`
|
|
85
|
-
`}let
|
|
86
|
-
`)
|
|
87
|
-
`;else
|
|
88
|
-
`)continue;if(
|
|
89
|
-
`){let{fold:
|
|
90
|
-
`){
|
|
91
|
-
`){
|
|
85
|
+
`}let z=X+Y.length+w.source.length;return{value:B,type:J,comment:Y.comment,range:[X,z,z]}}function $H({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],W=0,Q="",G=-1;for(let D=1;D<Y.length;++D){let O=Y[D];if(!Q&&(O==="-"||O==="+"))Q=O;else{let z=Number(O);if(!W&&z)W=z;else if(G===-1)G=_+D}}if(G!==-1)X(G,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${Y}`);let q=!1,H="",B=Y.length;for(let D=1;D<w.length;++D){let O=w[D];switch(O.type){case"space":q=!0;case"newline":B+=O.source.length;break;case"comment":if($&&!q)X(O,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");B+=O.source.length,H=O.source.substring(1);break;case"error":X(O,"UNEXPECTED_TOKEN",O.message),B+=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")B+=U.length}}}return{mode:J,indent:W,chomp:Q,comment:H,length:B}}function XH(_){let w=_.split(/\n( *)/),$=w[0],X=$.match(/^( *)/),J=[X?.[1]?[X[1],$.slice(X[1].length)]:["",$]];for(let W=1;W<w.length;W+=2)J.push([w[W],w[W+1]]);return J}YH.resolveBlockScalar=wH});var u3=P((zH)=>{var m3=X_(),WH=ow();function QH(_,w,$){let{offset:X,type:Y,source:J,end:W}=_,Q,G,q=(D,O,z)=>$(X+D,O,z);switch(Y){case"scalar":Q=m3.Scalar.PLAIN,G=GH(J,q);break;case"single-quoted-scalar":Q=m3.Scalar.QUOTE_SINGLE,G=qH(J,q);break;case"double-quoted-scalar":Q=m3.Scalar.QUOTE_DOUBLE,G=HH(J,q);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 H=X+J.length,B=WH.resolveEnd(W,H,w,$);return{value:G,type:Q,comment:B.comment,range:[X,H,B.offset]}}function GH(_,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 e$(_)}function qH(_,w){if(_[_.length-1]!=="'"||_.length===1)w(_.length,"MISSING_CHAR","Missing closing 'quote");return e$(_.slice(1,-1)).replace(/''/g,"'")}function e$(_){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,""),W=" ",Q=w.lastIndex;while($=w.exec(_)){let q=$[1].replace(Y,"");if(q==="")if(W===`
|
|
86
|
+
`)J+=W;else W=`
|
|
87
|
+
`;else J+=W+q,W=" ";Q=w.lastIndex}let G=/[ \t]*(.*)/sy;return G.lastIndex=Q,$=G.exec(_),J+W+($?.[1]??"")}function HH(_,w){let $="";for(let X=1;X<_.length-1;++X){let Y=_[X];if(Y==="\r"&&_[X+1]===`
|
|
88
|
+
`)continue;if(Y===`
|
|
89
|
+
`){let{fold:J,offset:W}=DH(_,X);$+=J,X=W}else if(Y==="\\"){let J=_[++X],W=BH[J];if(W)$+=W;else if(J===`
|
|
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 Q=J==="x"?2:J==="u"?4:8;$+=UH(_,X+1,Q,w),X+=Q}else{let Q=_.substr(X-1,2);w(X-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),$+=Q}}else if(Y===" "||Y==="\t"){let J=X,W=_[X+1];while(W===" "||W==="\t")W=_[++X+1];if(W!==`
|
|
92
92
|
`&&!(W==="\r"&&_[X+2]===`
|
|
93
|
-
`))$+=X>
|
|
93
|
+
`))$+=X>J?_.slice(J,X+1):Y}else $+=Y}if(_[_.length-1]!=='"'||_.length===1)w(_.length,"MISSING_CHAR",'Missing closing "quote');return $}function DH(_,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 BH={"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 UH(_,w,$,X){let Y=_.substr(w,$),W=Y.length===$&&/^[0-9a-fA-F]+$/.test(Y)?parseInt(Y,16):NaN;try{return String.fromCodePoint(W)}catch{let Q=_.substr(w-2,$+2);return X(w-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${Q}`),Q}}zH.resolveFlowScalar=QH});var w5=P((LH)=>{var Aw=p(),_5=X_(),OH=x3(),AH=u3();function MH(_,w,$,X){let{value:Y,type:J,comment:W,range:Q}=w.type==="block-scalar"?OH.resolveBlockScalar(_,w,X):AH.resolveFlowScalar(w,_.options.strict,X),G=$?_.directives.tagName($.source,(B)=>X($,"TAG_RESOLVE_FAILED",B)):null,q;if(_.options.stringKeys&&_.atKey)q=_.schema[Aw.SCALAR];else if(G)q=RH(_.schema,Y,G,$,X);else if(w.type==="scalar")q=fH(_,Y,w,X);else q=_.schema[Aw.SCALAR];let H;try{let B=q.resolve(Y,(D)=>X($??w,"TAG_RESOLVE_FAILED",D),_.options);H=Aw.isScalar(B)?B:new _5.Scalar(B)}catch(B){let D=B instanceof Error?B.message:String(B);X($??w,"TAG_RESOLVE_FAILED",D),H=new _5.Scalar(Y)}if(H.range=Q,H.source=Y,J)H.type=J;if(G)H.tag=G;if(q.format)H.format=q.format;if(W)H.comment=W;return H}function RH(_,w,$,X,Y){if($==="!")return _[Aw.SCALAR];let J=[];for(let Q of _.tags)if(!Q.collection&&Q.tag===$)if(Q.default&&Q.test)J.push(Q);else return Q;for(let Q of J)if(Q.test?.test(w))return Q;let W=_.knownTags[$];if(W&&!W.collection)return _.tags.push(Object.assign({},W,{default:!1,test:void 0})),W;return Y(X,"TAG_RESOLVE_FAILED",`Unresolved tag: ${$}`,$!=="tag:yaml.org,2002:str"),_[Aw.SCALAR]}function fH({atKey:_,directives:w,schema:$},X,Y,J){let W=$.tags.find((Q)=>(Q.default===!0||_&&Q.default==="key")&&Q.test?.test(X))||$[Aw.SCALAR];if($.compat){let Q=$.compat.find((G)=>G.default&&G.test?.test(X))??$[Aw.SCALAR];if(W.tag!==Q.tag){let G=w.tagString(W.tag),q=w.tagString(Q.tag),H=`Value may be parsed as either ${G} or ${q}`;J(Y,"TAG_RESOLVE_FAILED",H,!0)}}return W}LH.composeScalar=MH});var $5=P((NH)=>{function KH(_,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 _}NH.emptyScalarPosition=KH});var J5=P((IH)=>{var jH=V0(),EH=p(),SH=t$(),X5=w5(),PH=ow(),ZH=$5(),CH={composeNode:Y5,composeEmptyNode:l3};function Y5(_,w,$,X){let Y=_.atKey,{spaceBefore:J,comment:W,anchor:Q,tag:G}=$,q,H=!0;switch(w.type){case"alias":if(q=TH(_,w,X),Q||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(q=X5.composeScalar(_,w,G,X),Q)q.anchor=Q.source.substring(1);break;case"block-map":case"block-seq":case"flow-collection":try{if(q=SH.composeCollection(CH,_,w,$,X),Q)q.anchor=Q.source.substring(1)}catch(B){let D=B instanceof Error?B.message:String(B);X(w,"RESOURCE_EXHAUSTION",D)}break;default:{let B=w.type==="error"?w.message:`Unsupported token (type: ${w.type})`;X(w,"UNEXPECTED_TOKEN",B),H=!1}}if(q??(q=l3(_,w.offset,void 0,null,$,X)),Q&&q.anchor==="")X(Q,"BAD_ALIAS","Anchor cannot be an empty string");if(Y&&_.options.stringKeys&&(!EH.isScalar(q)||typeof q.value!=="string"||q.tag&&q.tag!=="tag:yaml.org,2002:str"))X(G??w,"NON_STRING_KEY","With stringKeys, all keys must be strings");if(J)q.spaceBefore=!0;if(W)if(w.type==="scalar"&&w.source==="")q.comment=W;else q.commentBefore=W;if(_.options.keepSourceTokens&&H)q.srcToken=w;return q}function l3(_,w,$,X,{spaceBefore:Y,comment:J,anchor:W,tag:Q,end:G},q){let H={type:"scalar",offset:ZH.emptyScalarPosition(w,$,X),indent:-1,source:""},B=X5.composeScalar(_,H,Q,q);if(W){if(B.anchor=W.source.substring(1),B.anchor==="")q(W,"BAD_ALIAS","Anchor cannot be an empty string")}if(Y)B.spaceBefore=!0;if(J)B.comment=J,B.range[2]=G;return B}function TH({options:_},{offset:w,source:$,end:X},Y){let J=new jH.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 W=w+$.length,Q=PH.resolveEnd(X,W,_.strict,Y);if(J.range=[w,W,Q.offset],Q.comment)J.comment=Q.comment;return J}IH.composeEmptyNode=l3;IH.composeNode=Y5});var Q5=P((mH)=>{var hH=P0(),W5=J5(),yH=ow(),vH=C0();function xH(_,w,{offset:$,start:X,value:Y,end:J},W){let Q=Object.assign({_directives:w},_),G=new hH.Document(void 0,Q),q={atKey:!1,atRoot:!0,directives:G.directives,options:G.options,schema:G.schema},H=vH.resolveProps(X,{indicator:"doc-start",next:Y??J?.[0],offset:$,onError:W,parentIndent:0,startOnNewline:!0});if(H.found){if(G.directives.docStart=!0,Y&&(Y.type==="block-map"||Y.type==="block-seq")&&!H.hasNewline)W(H.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")}G.contents=Y?W5.composeNode(q,Y,H,W):W5.composeEmptyNode(q,H.end,X,null,H,W);let B=G.contents.range[2],D=yH.resolveEnd(J,B,!1,W);if(D.comment)G.comment=D.comment;return G.range=[$,B,D.offset],G}mH.composeDoc=xH});var c3=P((nH)=>{var lH=$2("process"),cH=n1(),dH=P0(),T0=Z0(),G5=p(),pH=Q5(),iH=ow();function I0(_){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 q5(_){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
|
-
`)+(
|
|
102
|
-
${$}`:$;else if(X||_.directives.docStart||!
|
|
103
|
-
${W}`:$}else{let Y
|
|
104
|
-
${
|
|
105
|
-
${w.comment}`:w.comment}this.doc.range[2]=w.offset;break}default:this.errors.push(new
|
|
106
|
-
`}];switch(
|
|
107
|
-
`),H=
|
|
108
|
-
`,D=[{type:"block-scalar-header",offset:
|
|
109
|
-
`});return{type:"block-scalar",offset:
|
|
110
|
-
`),X=w.substring(0,$),
|
|
111
|
-
`;if(_.type==="block-scalar"){let
|
|
112
|
-
`});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:W,props:
|
|
113
|
-
`};delete _.items,Object.assign(_,{type:$,source:w,end:[
|
|
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 H5{constructor(_={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(w,$,X,Y)=>{let J=I0(w);if(Y)this.warnings.push(new T0.YAMLWarning(J,$,X));else this.errors.push(new T0.YAMLParseError(J,$,X))},this.directives=new cH.Directives({version:_.version||"1.2"}),this.options=_}decorate(_,w){let{comment:$,afterEmptyLine:X}=q5(this.prelude);if($){let Y=_.contents;if(w)_.comment=_.comment?`${_.comment}
|
|
102
|
+
${$}`:$;else if(X||_.directives.docStart||!Y)_.commentBefore=$;else if(G5.isCollection(Y)&&!Y.flow&&Y.items.length>0){let J=Y.items[0];if(G5.isPair(J))J=J.key;let W=J.commentBefore;J.commentBefore=W?`${$}
|
|
103
|
+
${W}`:$}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:q5(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(lH.env.LOG_STREAM)console.dir(_,{depth:null});switch(_.type){case"directive":this.directives.add(_.source,(w,$,X)=>{let Y=I0(_);Y[0]+=w,this.onError(Y,"BAD_DIRECTIVE",$,X)}),this.prelude.push(_.source),this.atDirectives=!0;break;case"document":{let w=pH.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(I0(_),"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(I0(_),"UNEXPECTED_TOKEN","Unexpected doc-end without preceding document"));break}this.doc.directives.docEnd=!0;let w=iH.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(I0(_),"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 dH.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}}}nH.Composer=H5});var U5=P(($D)=>{var aH=x3(),oH=u3(),sH=Z0(),D5=R0();function tH(_,w=!0,$){if(_){let X=(Y,J,W)=>{let Q=typeof Y==="number"?Y:Array.isArray(Y)?Y[0]:Y.offset;if($)$(Q,J,W);else throw new sH.YAMLParseError([Q,Q+1],J,W)};switch(_.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return oH.resolveFlowScalar(_,w,X);case"block-scalar":return aH.resolveBlockScalar({options:{strict:w}},_,X)}}return null}function eH(_,w){let{implicitKey:$=!1,indent:X,inFlow:Y=!1,offset:J=-1,type:W="PLAIN"}=w,Q=D5.stringifyString({type:W,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(Q[0]){case"|":case">":{let q=Q.indexOf(`
|
|
107
|
+
`),H=Q.substring(0,q),B=Q.substring(q+1)+`
|
|
108
|
+
`,D=[{type:"block-scalar-header",offset:J,indent:X,source:H}];if(!B5(D,G))D.push({type:"newline",offset:-1,indent:X,source:`
|
|
109
|
+
`});return{type:"block-scalar",offset:J,indent:X,props:D,source:B}}case'"':return{type:"double-quoted-scalar",offset:J,indent:X,source:Q,end:G};case"'":return{type:"single-quoted-scalar",offset:J,indent:X,source:Q,end:G};default:return{type:"scalar",offset:J,indent:X,source:Q,end:G}}}function _D(_,w,$={}){let{afterKey:X=!1,implicitKey:Y=!1,inFlow:J=!1,type:W}=$,Q="indent"in _?_.indent:null;if(X&&typeof Q==="number")Q+=2;if(!W)switch(_.type){case"single-quoted-scalar":W="QUOTE_SINGLE";break;case"double-quoted-scalar":W="QUOTE_DOUBLE";break;case"block-scalar":{let q=_.props[0];if(q.type!=="block-scalar-header")throw Error("Invalid block scalar header");W=q.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:W="PLAIN"}let G=D5.stringifyString({type:W,value:w},{implicitKey:Y||Q===null,indent:Q!==null&&Q>0?" ".repeat(Q):"",inFlow:J,options:{blockQuote:!0,lineWidth:-1}});switch(G[0]){case"|":case">":wD(_,G);break;case'"':d3(_,G,"double-quoted-scalar");break;case"'":d3(_,G,"single-quoted-scalar");break;default:d3(_,G,"scalar")}}function wD(_,w){let $=w.indexOf(`
|
|
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}=_,W="indent"in _?_.indent:-1,Q=[{type:"block-scalar-header",offset:J,indent:W,source:X}];if(!B5(Q,"end"in _?_.end:void 0))Q.push({type:"newline",offset:-1,indent:W,source:`
|
|
112
|
+
`});for(let G of Object.keys(_))if(G!=="type"&&G!=="offset")delete _[G];Object.assign(_,{type:"block-scalar",indent:W,props:Q,source:Y})}}function B5(_,w){if(w)for(let $ of w)switch($.type){case"space":case"comment":_.push($);break;case"newline":return _.push($),!0}return!1}function d3(_,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})}}}$D.createScalarToken=eH;$D.resolveAsScalar=tH;$D.setScalarValue=_D});var z5=P((QD)=>{var WD=(_)=>("type"in _)?o2(_):a2(_);function o2(_){switch(_.type){case"block-scalar":{let w="";for(let $ of _.props)w+=o2($);return w+_.source}case"block-map":case"block-seq":{let w="";for(let $ of _.items)w+=a2($);return w}case"flow-collection":{let w=_.start.source;for(let $ of _.items)w+=a2($);for(let $ of _.end)w+=$.source;return w}case"document":{let w=a2(_);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 a2({start:_,key:w,sep:$,value:X}){let Y="";for(let J of _)Y+=J.source;if(w)Y+=o2(w);if($)for(let J of $)Y+=J.source;if(X)Y+=o2(X);return Y}QD.stringify=WD});var A5=P((HD)=>{var p3=Symbol("break visit"),qD=Symbol("skip children"),V5=Symbol("remove item");function Mw(_,w){if("type"in _&&_.type==="document")_={start:_.start,value:_.value};O5(Object.freeze([]),_,w)}Mw.BREAK=p3;Mw.SKIP=qD;Mw.REMOVE=V5;Mw.itemAtPath=(_,w)=>{let $=_;for(let[X,Y]of w){let J=$?.[X];if(J&&"items"in J)$=J.items[Y];else return}return $};Mw.parentCollection=(_,w)=>{let $=Mw.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 O5(_,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 W=0;W<J.items.length;++W){let Q=O5(Object.freeze(_.concat([[Y,W]])),J.items[W],$);if(typeof Q==="number")W=Q-1;else if(Q===p3)return p3;else if(Q===V5)J.items.splice(W,1),W-=1}if(typeof X==="function"&&Y==="key")X=X(w,_)}}return typeof X==="function"?X(w,_):X}HD.visit=Mw});var s2=P((MD)=>{var i3=U5(),BD=z5(),UD=A5(),n3="\uFEFF",r3="\x02",a3="\x18",o3="\x1F",zD=(_)=>!!_&&("items"in _),VD=(_)=>!!_&&(_.type==="scalar"||_.type==="single-quoted-scalar"||_.type==="double-quoted-scalar"||_.type==="block-scalar");function OD(_){switch(_){case n3:return"<BOM>";case r3:return"<DOC>";case a3:return"<FLOW_END>";case o3:return"<SCALAR>";default:return JSON.stringify(_)}}function AD(_){switch(_){case n3:return"byte-order-mark";case r3:return"doc-mode";case a3:return"flow-error-end";case o3: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}MD.createScalarToken=i3.createScalarToken;MD.resolveAsScalar=i3.resolveAsScalar;MD.setScalarValue=i3.setScalarValue;MD.stringify=BD.stringify;MD.visit=UD.visit;MD.BOM=n3;MD.DOCUMENT=r3;MD.FLOW_END=a3;MD.SCALAR=o3;MD.isCollection=zD;MD.isScalar=VD;MD.prettyToken=OD;MD.tokenType=AD});var t3=P((kD)=>{var k0=s2();function j_(_){switch(_){case void 0:case" ":case`
|
|
116
|
+
`:case"\r":case"\t":return!0;default:return!1}}var M5=new Set("0123456789ABCDEFabcdef"),TD=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),t2=new Set(",[]{}"),ID=new Set(` ,[]{}
|
|
117
|
+
\r `),s3=(_)=>!_||ID.has(_);class R5{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]===
|
|
123
|
-
`,this.pos);if(X!==-1){while(X!==-1){let
|
|
124
|
-
`,
|
|
125
|
-
`:_=
|
|
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
|
|
127
|
-
`,
|
|
128
|
-
`)$=this.buffer[++X];_=X-1}else if(!this.blockScalarKeep)do{let
|
|
129
|
-
`&&
|
|
121
|
+
`||$>=this.indentNext||!w&&!this.atEnd?_+$:-1}if(w==="-"||w==="."){let $=this.buffer.substr(_,3);if(($==="---"||$==="...")&&j_(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]===k0.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 k0.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==="...")&&j_(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&&!j_(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((_==="-"||_==="?"||_===":")&&j_(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(s3),"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("..."))&&j_(X[3])){if(!($===this.indentNext-1&&this.flowLevel===1&&(X[0]==="]"||X[0]==="}")))return this.flowLevel=0,yield k0.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(s3),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let J=this.charAt(1);if(this.flowKey||j_(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
|
+
`,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)=>j_(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
|
+
`:_=Y,w=0;break;case"\r":{let J=this.buffer[Y+1];if(!J&&!this.atEnd)return this.setNext("block-scalar");if(J===`
|
|
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
|
+
`,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 W=Y;while(J===" ")J=this.buffer[--Y];if(J===`
|
|
129
|
+
`&&Y>=this.pos&&Y+1+w>W)_=Y;else break}while(!0);return yield k0.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(j_(Y)||_&&t2.has(Y))break;w=$}else if(j_(X)){let Y=this.buffer[$+1];if(X==="\r")if(Y===`
|
|
130
130
|
`)$+=1,X=`
|
|
131
|
-
`,
|
|
132
|
-
`){let
|
|
131
|
+
`,Y=this.buffer[$+1];else w=$;if(Y==="#"||_&&t2.has(Y))break;if(X===`
|
|
132
|
+
`){let J=this.continueScalar($+1);if(J===-1)break;$=Math.max($,J-2)}}else{if(_&&t2.has(X))break;w=$}if(!X&&!this.atEnd)return this.setNext("plain-scalar");return yield k0.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(s3),_+=yield*this.pushSpaces(!0);continue _;case"-":case"?":case":":{let w=this.flowLevel>0,$=this.charAt(1);if(j_($)||w&&t2.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(!j_(w)&&w!==">")w=this.buffer[++_];return yield*this.pushToIndex(w===">"?_+1:_,!1)}else{let _=this.pos+1,w=this.buffer[_];while(w)if(TD.has(w))w=this.buffer[++_];else if(w==="%"&&M5.has(this.buffer[_+1])&&M5.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)}}kD.Lexer=R5});var e3=P((hD)=>{class f5{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}}}}hD.LineCounter=f5});var _4=P((mD)=>{var vD=$2("process"),L5=s2(),xD=t3();function Xw(_,w){for(let $=0;$<_.length;++$)if(_[$].type===w)return!0;return!1}function F5(_){for(let w=0;w<_.length;++w)switch(_[w].type){case"space":case"comment":case"newline":break;default:return w}return-1}function N5(_){switch(_?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function e2(_){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 sw(_){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 _1(_,w){if(w.length<1e5)Array.prototype.push.apply(_,w);else for(let $=0;$<w.length;++$)_.push(w[$])}function K5(_){if(_.start.type==="flow-seq-start"){for(let w of _.items)if(w.sep&&!w.value&&!Xw(w.start,"explicit-key-ind")&&!Xw(w.sep,"map-value-ind")){if(w.key)w.value=w.key;if(delete w.key,N5(w.value))if(w.value.end)_1(w.value.end,w.sep);else w.value.end=w.sep;else _1(w.start,w.sep);delete w.sep}}}class b5{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 xD.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=_,vD.env.LOG_TOKENS)console.log("|",L5.prettyToken(_));if(this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=_.length;return}let w=L5.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")K5(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&&F5(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(F5(_.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=e2(this.peek(2)),$=sw(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)){_1(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 W=0;W<w.sep.length;++W){let Q=w.sep[W];switch(Q.type){case"newline":J.push(W);break;case"space":break;case"comment":if(Q.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(Xw(w.start,"newline"))Object.assign(w,{key:null,sep:[this.sourceToken]});else{let J=sw(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(Xw(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(N5(w.key)&&!Xw(w.sep,"newline")){let J=sw(w.start),W=w.key,Q=w.sep;Q.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:W,sep:Q}]})}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(Xw(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&&!Xw(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)){_1(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||Xw(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=e2($),Y=sw(X);K5(_);let J=_.end.splice(1,_.end.length);J.push(this.sourceToken);let W={type:"block-map",offset:_.offset,indent:_.indent,items:[{start:Y,key:_,sep:J}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=W}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=e2(_),$=sw(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=e2(_),$=sw(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()}}}mD.Parser=b5});var Z5=P((aD)=>{var j5=c3(),lD=P0(),g0=Z0(),cD=e1(),dD=p(),pD=e3(),E5=_4();function S5(_){let w=_.prettyErrors!==!1;return{lineCounter:_.lineCounter||w&&new pD.LineCounter||null,prettyErrors:w}}function iD(_,w={}){let{lineCounter:$,prettyErrors:X}=S5(w),Y=new E5.Parser($?.addNewLine),J=new j5.Composer(w),W=Array.from(J.compose(Y.parse(_)));if(X&&$)for(let Q of W)Q.errors.forEach(g0.prettifyError(_,$)),Q.warnings.forEach(g0.prettifyError(_,$));if(W.length>0)return W;return Object.assign([],{empty:!0},J.streamInfo())}function P5(_,w={}){let{lineCounter:$,prettyErrors:X}=S5(w),Y=new E5.Parser($?.addNewLine),J=new j5.Composer(w),W=null;for(let Q of J.compose(Y.parse(_),!0,_.length))if(!W)W=Q;else if(W.options.logLevel!=="silent"){W.errors.push(new g0.YAMLParseError(Q.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}if(X&&$)W.errors.forEach(g0.prettifyError(_,$)),W.warnings.forEach(g0.prettifyError(_,$));return W}function nD(_,w,$){let X=void 0;if(typeof w==="function")X=w;else if($===void 0&&w&&typeof w==="object")$=w;let Y=P5(_,$);if(!Y)return null;if(Y.warnings.forEach((J)=>cD.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 rD(_,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(dD.isDocument(_)&&!X)return _.toString($);return new lD.Document(_,X,$).toString($)}aD.parse=nD;aD.parseAllDocuments=iD;aD.parseDocument=P5;aD.stringify=rD});var T5=P((BB)=>{var _B=c3(),wB=P0(),$B=E3(),w4=Z0(),XB=V0(),Yw=p(),YB=e_(),JB=X_(),WB=ww(),QB=$w(),GB=s2(),qB=t3(),HB=e3(),DB=_4(),w1=Z5(),C5=U0();BB.Composer=_B.Composer;BB.Document=wB.Document;BB.Schema=$B.Schema;BB.YAMLError=w4.YAMLError;BB.YAMLParseError=w4.YAMLParseError;BB.YAMLWarning=w4.YAMLWarning;BB.Alias=XB.Alias;BB.isAlias=Yw.isAlias;BB.isCollection=Yw.isCollection;BB.isDocument=Yw.isDocument;BB.isMap=Yw.isMap;BB.isNode=Yw.isNode;BB.isPair=Yw.isPair;BB.isScalar=Yw.isScalar;BB.isSeq=Yw.isSeq;BB.Pair=YB.Pair;BB.Scalar=JB.Scalar;BB.YAMLMap=WB.YAMLMap;BB.YAMLSeq=QB.YAMLSeq;BB.CST=GB;BB.Lexer=qB.Lexer;BB.LineCounter=HB.LineCounter;BB.Parser=DB.Parser;BB.parse=w1.parse;BB.parseAllDocuments=w1.parseAllDocuments;BB.parseDocument=w1.parseDocument;BB.stringify=w1.stringify;BB.visit=C5.visit;BB.visitAsync=C5.visitAsync});var j9=(_)=>_.payload.title?.trim()||`session:${_.payload.id}`;function X2(_){let{store:w,agent:$}=_;return{async session(X){let Y=X.payload.id,J=await x4(w,Y);switch(X.type){case"session.created":{if(J)return{task_id:J.id};let W=j9(X);return{task_id:(await w.createTask({title:W,session_id:Y,owner:$,priority:3})).id}}case"session.idle":{if(!J)return null;if(J.status==="pending"){let W=await w.updateTask(J.id,{status:"in_progress"});return W?{task_id:W.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 x4(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 W=E9(X),G=(await w.listTasks({parent_id:J.id,limit:20})).tasks.find((H)=>H.title===W&&Date.now()-new Date(H.created_at).getTime()<60000);if(G)return{task_id:G.id};let q=await w.createTask({title:W,parent_id:J.id,session_id:Y,owner:$,priority:3});return await w.updateTask(q.id,{status:"in_progress"}),{task_id:q.id}},async catchAll(X){try{await w.appendOperation({task_id:null,type:X.type,data:{payload:X.payload,agent:$}})}catch{}}}}async function x4(_,w){return(await _.listTasks({session_id:w,limit:1})).tasks[0]??null}function E9(_){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 R1="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.",f1=`# Roy \u2014 task-first-class-citizen agent
|
|
139
139
|
|
|
140
140
|
You are **Roy**, an agent whose defining rule is simple:
|
|
141
141
|
|
|
@@ -222,7 +222,7 @@ if it is not in the task store, it is not tracked.
|
|
|
222
222
|
- Be direct and concrete; the user is reading task titles and milestones.
|
|
223
223
|
- Report the task id and its state whenever you finish a step.
|
|
224
224
|
- 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 $0="roy",k$={action:"execute",resource:"*",effect:"deny"};function h$(){return{id:$0,mode:"primary",description:V2,system:A2,permissions:[{...k$}]}}function L9(_,w){if(!Array.isArray(_.permissions))_.permissions=[];for(let $ of w)if(!_.permissions.some((J)=>J.action===$.action&&J.resource===$.resource&&J.effect===$.effect))_.permissions.push({...$})}function M2(_){let w=h$();return _.update($0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;L9($,w.permissions)}),w}var M={};O9(M,{void:()=>W6,util:()=>l,unknown:()=>J6,union:()=>H6,undefined:()=>w6,tuple:()=>U6,transformer:()=>K6,symbol:()=>_6,string:()=>p$,strictObject:()=>Q6,setErrorMap:()=>b9,set:()=>A6,record:()=>z6,quotelessJson:()=>K9,promise:()=>L6,preprocess:()=>j6,pipeline:()=>E6,ostring:()=>S6,optional:()=>N6,onumber:()=>P6,oboolean:()=>Z6,objectUtil:()=>R2,object:()=>G6,number:()=>i$,nullable:()=>b6,null:()=>$6,never:()=>Y6,nativeEnum:()=>f6,nan:()=>s9,map:()=>V6,makeIssue:()=>X0,literal:()=>O6,lazy:()=>R6,late:()=>a9,isValid:()=>c_,isDirty:()=>X1,isAsync:()=>bw,isAborted:()=>$1,intersection:()=>B6,instanceof:()=>o9,getParsedType:()=>P_,getErrorMap:()=>Nw,function:()=>M6,enum:()=>F6,effect:()=>K6,discriminatedUnion:()=>D6,defaultErrorMap:()=>h_,datetimeRegex:()=>l$,date:()=>e9,custom:()=>d$,coerce:()=>C6,boolean:()=>r$,bigint:()=>t9,array:()=>q6,any:()=>X6,addIssueToContext:()=>b,ZodVoid:()=>Y0,ZodUnknown:()=>d_,ZodUnion:()=>Cw,ZodUndefined:()=>Pw,ZodType:()=>v,ZodTuple:()=>C_,ZodTransformer:()=>L_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Gw,ZodSchema:()=>v,ZodRecord:()=>W0,ZodReadonly:()=>vw,ZodPromise:()=>Qw,ZodPipeline:()=>Q0,ZodParsedType:()=>L,ZodOptional:()=>F_,ZodObject:()=>s,ZodNumber:()=>p_,ZodNullable:()=>v_,ZodNull:()=>Zw,ZodNever:()=>Z_,ZodNativeEnum:()=>kw,ZodNaN:()=>G0,ZodMap:()=>q0,ZodLiteral:()=>gw,ZodLazy:()=>Iw,ZodIssueCode:()=>O,ZodIntersection:()=>Tw,ZodFunction:()=>Ew,ZodFirstPartyTypeKind:()=>F,ZodError:()=>Y_,ZodEnum:()=>r_,ZodEffects:()=>L_,ZodDiscriminatedUnion:()=>J1,ZodDefault:()=>hw,ZodDate:()=>Ww,ZodCatch:()=>yw,ZodBranded:()=>Y1,ZodBoolean:()=>Sw,ZodBigInt:()=>i_,ZodArray:()=>O_,ZodAny:()=>qw,Schema:()=>v,ParseStatus:()=>W_,OK:()=>q_,NEVER:()=>T6,INVALID:()=>T,EMPTY_PATH:()=>j9,DIRTY:()=>Yw,BRAND:()=>n9});var l;(function(_){_.assertEqual=(J)=>{};function w(J){}_.assertIs=w;function $(J){throw Error()}_.assertNever=$,_.arrayToEnum=(J)=>{let Y={};for(let W of J)Y[W]=W;return Y},_.getValidEnumValues=(J)=>{let Y=_.objectKeys(J).filter((q)=>typeof J[J[q]]!=="number"),W={};for(let q of Y)W[q]=J[q];return _.objectValues(W)},_.objectValues=(J)=>{return _.objectKeys(J).map(function(Y){return J[Y]})},_.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let Y=[];for(let W in J)if(Object.prototype.hasOwnProperty.call(J,W))Y.push(W);return Y},_.find=(J,Y)=>{for(let W of J)if(Y(W))return W;return},_.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function X(J,Y=" | "){return J.map((W)=>typeof W==="string"?`'${W}'`:W).join(Y)}_.joinValues=X,_.jsonStringifyReplacer=(J,Y)=>{if(typeof Y==="bigint")return Y.toString();return Y}})(l||(l={}));var R2;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(R2||(R2={}));var L=l.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),P_=(_)=>{switch(typeof _){case"undefined":return L.undefined;case"string":return L.string;case"number":return Number.isNaN(_)?L.nan:L.number;case"boolean":return L.boolean;case"function":return L.function;case"bigint":return L.bigint;case"symbol":return L.symbol;case"object":if(Array.isArray(_))return L.array;if(_===null)return L.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return L.promise;if(typeof Map<"u"&&_ instanceof Map)return L.map;if(typeof Set<"u"&&_ instanceof Set)return L.set;if(typeof Date<"u"&&_ instanceof Date)return L.date;return L.object;default:return L.unknown}};var O=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"]),K9=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class Y_ 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(J){return J.message},$={_errors:[]},X=(J)=>{for(let Y of J.issues)if(Y.code==="invalid_union")Y.unionErrors.map(X);else if(Y.code==="invalid_return_type")X(Y.returnTypeError);else if(Y.code==="invalid_arguments")X(Y.argumentsError);else if(Y.path.length===0)$._errors.push(w(Y));else{let W=$,q=0;while(q<Y.path.length){let G=Y.path[q];if(q!==Y.path.length-1)W[G]=W[G]||{_errors:[]};else W[G]=W[G]||{_errors:[]},W[G]._errors.push(w(Y));W=W[G],q++}}};return X(this),$}static assert(_){if(!(_ instanceof Y_))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 J=X.path[0];w[J]=w[J]||[],w[J].push(_(X))}else $.push(_(X));return{formErrors:$,fieldErrors:w}}get formErrors(){return this.flatten()}}Y_.create=(_)=>{return new Y_(_)};var N9=(_,w)=>{let $;switch(_.code){case O.invalid_type:if(_.received===L.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case O.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case O.invalid_union:$="Invalid input";break;case O.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case O.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case O.invalid_arguments:$="Invalid function arguments";break;case O.invalid_return_type:$="Invalid function return type";break;case O.invalid_date:$="Invalid date";break;case O.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 O.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 O.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 O.custom:$="Invalid input";break;case O.invalid_intersection_types:$="Intersection results could not be merged";break;case O.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case O.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},h_=N9;var y$=h_;function b9(_){y$=_}function Nw(){return y$}var X0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:J}=_,Y=[...$,...J.path||[]],W={...J,path:Y};if(J.message!==void 0)return{...J,path:Y,message:J.message};let q="",G=X.filter((Q)=>!!Q).slice().reverse();for(let Q of G)q=Q(W,{data:w,defaultError:q}).message;return{...J,path:Y,message:q}},j9=[];function b(_,w){let $=Nw(),X=X0({issueData:w,data:_.data,path:_.path,errorMaps:[_.common.contextualErrorMap,_.schemaErrorMap,$,$===h_?void 0:h_].filter((J)=>!!J)});_.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 J=await X.key,Y=await X.value;$.push({key:J,value:Y})}return W_.mergeObjectSync(_,$)}static mergeObjectSync(_,w){let $={};for(let X of w){let{key:J,value:Y}=X;if(J.status==="aborted")return T;if(Y.status==="aborted")return T;if(J.status==="dirty")_.dirty();if(Y.status==="dirty")_.dirty();if(J.value!=="__proto__"&&(typeof Y.value<"u"||X.alwaysSet))$[J.value]=Y.value}return{status:_.value,value:$}}}var T=Object.freeze({status:"aborted"}),Yw=(_)=>({status:"dirty",value:_}),q_=(_)=>({status:"valid",value:_}),$1=(_)=>_.status==="aborted",X1=(_)=>_.status==="dirty",c_=(_)=>_.status==="valid",bw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var Z;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(Z||(Z={}));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 v$=(_,w)=>{if(c_(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 Y_(_.common.issues);return this._error=$,this._error}}}};function k(_){if(!_)return{};let{errorMap:w,invalid_type_error:$,required_error:X,description:J}=_;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:J};return{errorMap:(W,q)=>{let{message:G}=_;if(W.code==="invalid_enum_value")return{message:G??q.defaultError};if(typeof q.data>"u")return{message:G??X??q.defaultError};if(W.code!=="invalid_type")return{message:q.defaultError};return{message:G??$??q.defaultError}},description:J}}class v{get description(){return this._def.description}_getType(_){return P_(_.data)}_getOrReturnCtx(_,w){return w||{common:_.parent.common,data:_.data,parsedType:P_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}_processInputParams(_){return{status:new W_,ctx:{common:_.parent.common,data:_.data,parsedType:P_(_.data),schemaErrorMap:this._def.errorMap,path:_.path,parent:_.parent}}}_parseSync(_){let w=this._parse(_);if(bw(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:P_(_)},X=this._parseSync({data:_,path:$.path,parent:$});return v$($,X)}"~validate"(_){let w={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:_,parsedType:P_(_)};if(!this["~standard"].async)try{let $=this._parseSync({data:_,path:[],parent:w});return c_($)?{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(($)=>c_($)?{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:P_(_)},X=this._parse({data:_,path:$.path,parent:$}),J=await(bw(X)?X:Promise.resolve(X));return v$($,J)}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,J)=>{let Y=_(X),W=()=>J.addIssue({code:O.custom,...$(X)});if(typeof Promise<"u"&&Y instanceof Promise)return Y.then((q)=>{if(!q)return W(),!1;else return!0});if(!Y)return W(),!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 L_({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 F_.create(this,this._def)}nullable(){return v_.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return O_.create(this)}promise(){return Qw.create(this,this._def)}or(_){return Cw.create([this,_],this._def)}and(_){return Tw.create(this,_,this._def)}transform(_){return new L_({...k(this._def),schema:this,typeName:F.ZodEffects,effect:{type:"transform",transform:_}})}default(_){let w=typeof _==="function"?_:()=>_;return new hw({...k(this._def),innerType:this,defaultValue:w,typeName:F.ZodDefault})}brand(){return new Y1({typeName:F.ZodBranded,type:this,...k(this._def)})}catch(_){let w=typeof _==="function"?_:()=>_;return new yw({...k(this._def),innerType:this,catchValue:w,typeName:F.ZodCatch})}describe(_){return new this.constructor({...this._def,description:_})}pipe(_){return Q0.create(this,_)}readonly(){return vw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var E9=/^c[^\s-]{8,}$/i,S9=/^[0-9a-z]+$/,P9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Z9=/^[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,C9=/^[a-z0-9_-]{21}$/i,T9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,I9=/^[-+]?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)?)??$/,g9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,k9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",O2,h9=/^(?:(?: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])$/,y9=/^(?:(?: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])$/,v9=/^(([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]))$/,x9=/^(([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])$/,m9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,u9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,m$="((\\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])))",l9=new RegExp(`^${m$}$`);function u$(_){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 c9(_){return new RegExp(`^${u$(_)}$`)}function l$(_){let w=`${m$}T${u$(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function d9(_,w){if((w==="v4"||!w)&&h9.test(_))return!0;if((w==="v6"||!w)&&v9.test(_))return!0;return!1}function p9(_,w){if(!T9.test(_))return!1;try{let[$]=_.split(".");if(!$)return!1;let X=$.replace(/-/g,"+").replace(/_/g,"/").padEnd($.length+(4-$.length%4)%4,"="),J=JSON.parse(atob(X));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(w&&J.alg!==w)return!1;return!0}catch{return!1}}function i9(_,w){if((w==="v4"||!w)&&y9.test(_))return!0;if((w==="v6"||!w)&&x9.test(_))return!0;return!1}class R_ extends v{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==L.string){let J=this._getOrReturnCtx(_);return b(J,{code:O.invalid_type,expected:L.string,received:J.parsedType}),T}let $=new W_,X=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(_.data.length<J.value)X=this._getOrReturnCtx(_,X),b(X,{code:O.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),$.dirty()}else if(J.kind==="max"){if(_.data.length>J.value)X=this._getOrReturnCtx(_,X),b(X,{code:O.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),$.dirty()}else if(J.kind==="length"){let Y=_.data.length>J.value,W=_.data.length<J.value;if(Y||W){if(X=this._getOrReturnCtx(_,X),Y)b(X,{code:O.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(W)b(X,{code:O.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});$.dirty()}}else if(J.kind==="email"){if(!g9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"email",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="emoji"){if(!O2)O2=new RegExp(k9,"u");if(!O2.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"emoji",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="uuid"){if(!Z9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"uuid",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="nanoid"){if(!C9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"nanoid",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="cuid"){if(!E9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"cuid",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="cuid2"){if(!S9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"cuid2",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="ulid"){if(!P9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"ulid",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="url")try{new URL(_.data)}catch{X=this._getOrReturnCtx(_,X),b(X,{validation:"url",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"regex",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="trim")_.data=_.data.trim();else if(J.kind==="includes"){if(!_.data.includes(J.value,J.position))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),$.dirty()}else if(J.kind==="toLowerCase")_.data=_.data.toLowerCase();else if(J.kind==="toUpperCase")_.data=_.data.toUpperCase();else if(J.kind==="startsWith"){if(!_.data.startsWith(J.value))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:{startsWith:J.value},message:J.message}),$.dirty()}else if(J.kind==="endsWith"){if(!_.data.endsWith(J.value))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:{endsWith:J.value},message:J.message}),$.dirty()}else if(J.kind==="datetime"){if(!l$(J).test(_.data))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:"datetime",message:J.message}),$.dirty()}else if(J.kind==="date"){if(!l9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:"date",message:J.message}),$.dirty()}else if(J.kind==="time"){if(!c9(J).test(_.data))X=this._getOrReturnCtx(_,X),b(X,{code:O.invalid_string,validation:"time",message:J.message}),$.dirty()}else if(J.kind==="duration"){if(!I9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"duration",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="ip"){if(!d9(_.data,J.version))X=this._getOrReturnCtx(_,X),b(X,{validation:"ip",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="jwt"){if(!p9(_.data,J.alg))X=this._getOrReturnCtx(_,X),b(X,{validation:"jwt",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="cidr"){if(!i9(_.data,J.version))X=this._getOrReturnCtx(_,X),b(X,{validation:"cidr",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="base64"){if(!m9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"base64",code:O.invalid_string,message:J.message}),$.dirty()}else if(J.kind==="base64url"){if(!u9.test(_.data))X=this._getOrReturnCtx(_,X),b(X,{validation:"base64url",code:O.invalid_string,message:J.message}),$.dirty()}else l.assertNever(J);return{status:$.value,value:_.data}}_regex(_,w,$){return this.refinement((X)=>_.test(X),{validation:w,code:O.invalid_string,...Z.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...Z.errToObj(_)})}url(_){return this._addCheck({kind:"url",...Z.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...Z.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...Z.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...Z.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...Z.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...Z.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...Z.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...Z.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...Z.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...Z.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...Z.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...Z.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...Z.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...Z.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...Z.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...Z.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...Z.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...Z.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...Z.errToObj(w)})}nonempty(_){return this.min(1,Z.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:F.ZodString,coerce:_?.coerce??!1,...k(_)})};function r9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,J=$>X?$:X,Y=Number.parseInt(_.toFixed(J).replace(".","")),W=Number.parseInt(w.toFixed(J).replace(".",""));return Y%W/10**J}class p_ extends v{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(_)!==L.number){let J=this._getOrReturnCtx(_);return b(J,{code:O.invalid_type,expected:L.number,received:J.parsedType}),T}let $=void 0,X=new W_;for(let J of this._def.checks)if(J.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),b($,{code:O.invalid_type,expected:"integer",received:"float",message:J.message}),X.dirty()}else if(J.kind==="min"){if(J.inclusive?_.data<J.value:_.data<=J.value)$=this._getOrReturnCtx(_,$),b($,{code:O.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="max"){if(J.inclusive?_.data>J.value:_.data>=J.value)$=this._getOrReturnCtx(_,$),b($,{code:O.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),X.dirty()}else if(J.kind==="multipleOf"){if(r9(_.data,J.value)!==0)$=this._getOrReturnCtx(_,$),b($,{code:O.not_multiple_of,multipleOf:J.value,message:J.message}),X.dirty()}else if(J.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),b($,{code:O.not_finite,message:J.message}),X.dirty()}else l.assertNever(J);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new p_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new p_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:Z.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:Z.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.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(_)}}p_.create=(_)=>{return new p_({checks:[],typeName:F.ZodNumber,coerce:_?.coerce||!1,...k(_)})};class i_ extends v{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(_)!==L.bigint)return this._getInvalidInput(_);let $=void 0,X=new W_;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?_.data<J.value:_.data<=J.value)$=this._getOrReturnCtx(_,$),b($,{code:O.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),X.dirty()}else if(J.kind==="max"){if(J.inclusive?_.data>J.value:_.data>=J.value)$=this._getOrReturnCtx(_,$),b($,{code:O.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),X.dirty()}else if(J.kind==="multipleOf"){if(_.data%J.value!==BigInt(0))$=this._getOrReturnCtx(_,$),b($,{code:O.not_multiple_of,multipleOf:J.value,message:J.message}),X.dirty()}else l.assertNever(J);return{status:X.value,value:_.data}}_getInvalidInput(_){let w=this._getOrReturnCtx(_);return b(w,{code:O.invalid_type,expected:L.bigint,received:w.parsedType}),T}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new i_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new i_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.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 _}}i_.create=(_)=>{return new i_({checks:[],typeName:F.ZodBigInt,coerce:_?.coerce??!1,...k(_)})};class Sw extends v{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==L.boolean){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.boolean,received:$.parsedType}),T}return q_(_.data)}}Sw.create=(_)=>{return new Sw({typeName:F.ZodBoolean,coerce:_?.coerce||!1,...k(_)})};class Ww extends v{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==L.date){let J=this._getOrReturnCtx(_);return b(J,{code:O.invalid_type,expected:L.date,received:J.parsedType}),T}if(Number.isNaN(_.data.getTime())){let J=this._getOrReturnCtx(_);return b(J,{code:O.invalid_date}),T}let $=new W_,X=void 0;for(let J of this._def.checks)if(J.kind==="min"){if(_.data.getTime()<J.value)X=this._getOrReturnCtx(_,X),b(X,{code:O.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),$.dirty()}else if(J.kind==="max"){if(_.data.getTime()>J.value)X=this._getOrReturnCtx(_,X),b(X,{code:O.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),$.dirty()}else l.assertNever(J);return{status:$.value,value:new Date(_.data.getTime())}}_addCheck(_){return new Ww({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:Z.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:Z.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}}Ww.create=(_)=>{return new Ww({checks:[],coerce:_?.coerce||!1,typeName:F.ZodDate,...k(_)})};class J0 extends v{_parse(_){if(this._getType(_)!==L.symbol){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.symbol,received:$.parsedType}),T}return q_(_.data)}}J0.create=(_)=>{return new J0({typeName:F.ZodSymbol,...k(_)})};class Pw extends v{_parse(_){if(this._getType(_)!==L.undefined){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.undefined,received:$.parsedType}),T}return q_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:F.ZodUndefined,...k(_)})};class Zw extends v{_parse(_){if(this._getType(_)!==L.null){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.null,received:$.parsedType}),T}return q_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:F.ZodNull,...k(_)})};class qw extends v{constructor(){super(...arguments);this._any=!0}_parse(_){return q_(_.data)}}qw.create=(_)=>{return new qw({typeName:F.ZodAny,...k(_)})};class d_ extends v{constructor(){super(...arguments);this._unknown=!0}_parse(_){return q_(_.data)}}d_.create=(_)=>{return new d_({typeName:F.ZodUnknown,...k(_)})};class Z_ extends v{_parse(_){let w=this._getOrReturnCtx(_);return b(w,{code:O.invalid_type,expected:L.never,received:w.parsedType}),T}}Z_.create=(_)=>{return new Z_({typeName:F.ZodNever,...k(_)})};class Y0 extends v{_parse(_){if(this._getType(_)!==L.undefined){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.void,received:$.parsedType}),T}return q_(_.data)}}Y0.create=(_)=>{return new Y0({typeName:F.ZodVoid,...k(_)})};class O_ extends v{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==L.array)return b(w,{code:O.invalid_type,expected:L.array,received:w.parsedType}),T;if(X.exactLength!==null){let Y=w.data.length>X.exactLength.value,W=w.data.length<X.exactLength.value;if(Y||W)b(w,{code:Y?O.too_big:O.too_small,minimum:W?X.exactLength.value:void 0,maximum:Y?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)b(w,{code:O.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)b(w,{code:O.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((Y,W)=>{return X.type._parseAsync(new f_(w,Y,w.path,W))})).then((Y)=>{return W_.mergeArray($,Y)});let J=[...w.data].map((Y,W)=>{return X.type._parseSync(new f_(w,Y,w.path,W))});return W_.mergeArray($,J)}get element(){return this._def.type}min(_,w){return new O_({...this._def,minLength:{value:_,message:Z.toString(w)}})}max(_,w){return new O_({...this._def,maxLength:{value:_,message:Z.toString(w)}})}length(_,w){return new O_({...this._def,exactLength:{value:_,message:Z.toString(w)}})}nonempty(_){return this.min(1,_)}}O_.create=(_,w)=>{return new O_({type:_,minLength:null,maxLength:null,exactLength:null,typeName:F.ZodArray,...k(w)})};function jw(_){if(_ instanceof s){let w={};for(let $ in _.shape){let X=_.shape[$];w[$]=F_.create(jw(X))}return new s({..._._def,shape:()=>w})}else if(_ instanceof O_)return new O_({..._._def,type:jw(_.element)});else if(_ instanceof F_)return F_.create(jw(_.unwrap()));else if(_ instanceof v_)return v_.create(jw(_.unwrap()));else if(_ instanceof C_)return C_.create(_.items.map((w)=>jw(w)));else return _}class s extends v{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(_)!==L.object){let G=this._getOrReturnCtx(_);return b(G,{code:O.invalid_type,expected:L.object,received:G.parsedType}),T}let{status:$,ctx:X}=this._processInputParams(_),{shape:J,keys:Y}=this._getCached(),W=[];if(!(this._def.catchall instanceof Z_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!Y.includes(G))W.push(G)}let q=[];for(let G of Y){let Q=J[G],H=X.data[G];q.push({key:{status:"valid",value:G},value:Q._parse(new f_(X,H,X.path,G)),alwaysSet:G in X.data})}if(this._def.catchall instanceof Z_){let G=this._def.unknownKeys;if(G==="passthrough")for(let Q of W)q.push({key:{status:"valid",value:Q},value:{status:"valid",value:X.data[Q]}});else if(G==="strict"){if(W.length>0)b(X,{code:O.unrecognized_keys,keys:W}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let Q of W){let H=X.data[Q];q.push({key:{status:"valid",value:Q},value:G._parse(new f_(X,H,X.path,Q)),alwaysSet:Q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let Q of q){let H=await Q.key,B=await Q.value;G.push({key:H,value:B,alwaysSet:Q.alwaysSet})}return G}).then((G)=>{return W_.mergeObjectSync($,G)});else return W_.mergeObjectSync($,q)}get shape(){return this._def.shape()}strict(_){return Z.errToObj,new s({...this._def,unknownKeys:"strict",..._!==void 0?{errorMap:(w,$)=>{let X=this._def.errorMap?.(w,$).message??$.defaultError;if(w.code==="unrecognized_keys")return{message:Z.errToObj(_).message??X};return{message:X}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(_){return new s({...this._def,shape:()=>({...this._def.shape(),..._})})}merge(_){return new s({unknownKeys:_._def.unknownKeys,catchall:_._def.catchall,shape:()=>({...this._def.shape(),..._._def.shape()}),typeName:F.ZodObject})}setKey(_,w){return this.augment({[_]:w})}catchall(_){return new s({...this._def,catchall:_})}pick(_){let w={};for(let $ of l.objectKeys(_))if(_[$]&&this.shape[$])w[$]=this.shape[$];return new s({...this._def,shape:()=>w})}omit(_){let w={};for(let $ of l.objectKeys(this.shape))if(!_[$])w[$]=this.shape[$];return new s({...this._def,shape:()=>w})}deepPartial(){return jw(this)}partial(_){let w={};for(let $ of l.objectKeys(this.shape)){let X=this.shape[$];if(_&&!_[$])w[$]=X;else w[$]=X.optional()}return new s({...this._def,shape:()=>w})}required(_){let w={};for(let $ of l.objectKeys(this.shape))if(_&&!_[$])w[$]=this.shape[$];else{let J=this.shape[$];while(J instanceof F_)J=J._def.innerType;w[$]=J}return new s({...this._def,shape:()=>w})}keyof(){return c$(l.objectKeys(this.shape))}}s.create=(_,w)=>{return new s({shape:()=>_,unknownKeys:"strip",catchall:Z_.create(),typeName:F.ZodObject,...k(w)})};s.strictCreate=(_,w)=>{return new s({shape:()=>_,unknownKeys:"strict",catchall:Z_.create(),typeName:F.ZodObject,...k(w)})};s.lazycreate=(_,w)=>{return new s({shape:_,unknownKeys:"strip",catchall:Z_.create(),typeName:F.ZodObject,...k(w)})};class Cw extends v{_parse(_){let{ctx:w}=this._processInputParams(_),$=this._def.options;function X(J){for(let W of J)if(W.result.status==="valid")return W.result;for(let W of J)if(W.result.status==="dirty")return w.common.issues.push(...W.ctx.common.issues),W.result;let Y=J.map((W)=>new Y_(W.ctx.common.issues));return b(w,{code:O.invalid_union,unionErrors:Y}),T}if(w.common.async)return Promise.all($.map(async(J)=>{let Y={...w,common:{...w.common,issues:[]},parent:null};return{result:await J._parseAsync({data:w.data,path:w.path,parent:Y}),ctx:Y}})).then(X);else{let J=void 0,Y=[];for(let q of $){let G={...w,common:{...w.common,issues:[]},parent:null},Q=q._parseSync({data:w.data,path:w.path,parent:G});if(Q.status==="valid")return Q;else if(Q.status==="dirty"&&!J)J={result:Q,ctx:G};if(G.common.issues.length)Y.push(G.common.issues)}if(J)return w.common.issues.push(...J.ctx.common.issues),J.result;let W=Y.map((q)=>new Y_(q));return b(w,{code:O.invalid_union,unionErrors:W}),T}}get options(){return this._def.options}}Cw.create=(_,w)=>{return new Cw({options:_,typeName:F.ZodUnion,...k(w)})};var y_=(_)=>{if(_ instanceof Iw)return y_(_.schema);else if(_ instanceof L_)return y_(_.innerType());else if(_ instanceof gw)return[_.value];else if(_ instanceof r_)return _.options;else if(_ instanceof kw)return l.objectValues(_.enum);else if(_ instanceof hw)return y_(_._def.innerType);else if(_ instanceof Pw)return[void 0];else if(_ instanceof Zw)return[null];else if(_ instanceof F_)return[void 0,...y_(_.unwrap())];else if(_ instanceof v_)return[null,...y_(_.unwrap())];else if(_ instanceof Y1)return y_(_.unwrap());else if(_ instanceof vw)return y_(_.unwrap());else if(_ instanceof yw)return y_(_._def.innerType);else return[]};class J1 extends v{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==L.object)return b(w,{code:O.invalid_type,expected:L.object,received:w.parsedType}),T;let $=this.discriminator,X=w.data[$],J=this.optionsMap.get(X);if(!J)return b(w,{code:O.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[$]}),T;if(w.common.async)return J._parseAsync({data:w.data,path:w.path,parent:w});else return J._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 J of w){let Y=y_(J.shape[_]);if(!Y.length)throw Error(`A discriminator value for key \`${_}\` could not be extracted from all schema options`);for(let W of Y){if(X.has(W))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(W)}`);X.set(W,J)}}return new J1({typeName:F.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...k($)})}}function F2(_,w){let $=P_(_),X=P_(w);if(_===w)return{valid:!0,data:_};else if($===L.object&&X===L.object){let J=l.objectKeys(w),Y=l.objectKeys(_).filter((q)=>J.indexOf(q)!==-1),W={..._,...w};for(let q of Y){let G=F2(_[q],w[q]);if(!G.valid)return{valid:!1};W[q]=G.data}return{valid:!0,data:W}}else if($===L.array&&X===L.array){if(_.length!==w.length)return{valid:!1};let J=[];for(let Y=0;Y<_.length;Y++){let W=_[Y],q=w[Y],G=F2(W,q);if(!G.valid)return{valid:!1};J.push(G.data)}return{valid:!0,data:J}}else if($===L.date&&X===L.date&&+_===+w)return{valid:!0,data:_};else return{valid:!1}}class Tw extends v{_parse(_){let{status:w,ctx:$}=this._processInputParams(_),X=(J,Y)=>{if($1(J)||$1(Y))return T;let W=F2(J.value,Y.value);if(!W.valid)return b($,{code:O.invalid_intersection_types}),T;if(X1(J)||X1(Y))w.dirty();return{status:w.value,value:W.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(([J,Y])=>X(J,Y));else return X(this._def.left._parseSync({data:$.data,path:$.path,parent:$}),this._def.right._parseSync({data:$.data,path:$.path,parent:$}))}}Tw.create=(_,w,$)=>{return new Tw({left:_,right:w,typeName:F.ZodIntersection,...k($)})};class C_ extends v{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==L.array)return b($,{code:O.invalid_type,expected:L.array,received:$.parsedType}),T;if($.data.length<this._def.items.length)return b($,{code:O.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),T;if(!this._def.rest&&$.data.length>this._def.items.length)b($,{code:O.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let J=[...$.data].map((Y,W)=>{let q=this._def.items[W]||this._def.rest;if(!q)return null;return q._parse(new f_($,Y,$.path,W))}).filter((Y)=>!!Y);if($.common.async)return Promise.all(J).then((Y)=>{return W_.mergeArray(w,Y)});else return W_.mergeArray(w,J)}get items(){return this._def.items}rest(_){return new C_({...this._def,rest:_})}}C_.create=(_,w)=>{if(!Array.isArray(_))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new C_({items:_,typeName:F.ZodTuple,rest:null,...k(w)})};class W0 extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==L.object)return b($,{code:O.invalid_type,expected:L.object,received:$.parsedType}),T;let X=[],J=this._def.keyType,Y=this._def.valueType;for(let W in $.data)X.push({key:J._parse(new f_($,W,$.path,W)),value:Y._parse(new f_($,$.data[W],$.path,W)),alwaysSet:W 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 v)return new W0({keyType:_,valueType:w,typeName:F.ZodRecord,...k($)});return new W0({keyType:R_.create(),valueType:_,typeName:F.ZodRecord,...k(w)})}}class q0 extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==L.map)return b($,{code:O.invalid_type,expected:L.map,received:$.parsedType}),T;let X=this._def.keyType,J=this._def.valueType,Y=[...$.data.entries()].map(([W,q],G)=>{return{key:X._parse(new f_($,W,$.path,[G,"key"])),value:J._parse(new f_($,q,$.path,[G,"value"]))}});if($.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let q of Y){let G=await q.key,Q=await q.value;if(G.status==="aborted"||Q.status==="aborted")return T;if(G.status==="dirty"||Q.status==="dirty")w.dirty();W.set(G.value,Q.value)}return{status:w.value,value:W}})}else{let W=new Map;for(let q of Y){let{key:G,value:Q}=q;if(G.status==="aborted"||Q.status==="aborted")return T;if(G.status==="dirty"||Q.status==="dirty")w.dirty();W.set(G.value,Q.value)}return{status:w.value,value:W}}}}q0.create=(_,w,$)=>{return new q0({valueType:w,keyType:_,typeName:F.ZodMap,...k($)})};class Gw extends v{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==L.set)return b($,{code:O.invalid_type,expected:L.set,received:$.parsedType}),T;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)b($,{code:O.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)b($,{code:O.too_big,maximum:X.maxSize.value,type:"set",inclusive:!0,exact:!1,message:X.maxSize.message}),w.dirty()}let J=this._def.valueType;function Y(q){let G=new Set;for(let Q of q){if(Q.status==="aborted")return T;if(Q.status==="dirty")w.dirty();G.add(Q.value)}return{status:w.value,value:G}}let W=[...$.data.values()].map((q,G)=>J._parse(new f_($,q,$.path,G)));if($.common.async)return Promise.all(W).then((q)=>Y(q));else return Y(W)}min(_,w){return new Gw({...this._def,minSize:{value:_,message:Z.toString(w)}})}max(_,w){return new Gw({...this._def,maxSize:{value:_,message:Z.toString(w)}})}size(_,w){return this.min(_,w).max(_,w)}nonempty(_){return this.min(1,_)}}Gw.create=(_,w)=>{return new Gw({valueType:_,minSize:null,maxSize:null,typeName:F.ZodSet,...k(w)})};class Ew extends v{constructor(){super(...arguments);this.validate=this.implement}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==L.function)return b(w,{code:O.invalid_type,expected:L.function,received:w.parsedType}),T;function $(W,q){return X0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,Nw(),h_].filter((G)=>!!G),issueData:{code:O.invalid_arguments,argumentsError:q}})}function X(W,q){return X0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,Nw(),h_].filter((G)=>!!G),issueData:{code:O.invalid_return_type,returnTypeError:q}})}let J={errorMap:w.common.contextualErrorMap},Y=w.data;if(this._def.returns instanceof Qw){let W=this;return q_(async function(...q){let G=new Y_([]),Q=await W._def.args.parseAsync(q,J).catch((D)=>{throw G.addIssue($(q,D)),G}),H=await Reflect.apply(Y,this,Q);return await W._def.returns._def.type.parseAsync(H,J).catch((D)=>{throw G.addIssue(X(H,D)),G})})}else{let W=this;return q_(function(...q){let G=W._def.args.safeParse(q,J);if(!G.success)throw new Y_([$(q,G.error)]);let Q=Reflect.apply(Y,this,G.data),H=W._def.returns.safeParse(Q,J);if(!H.success)throw new Y_([X(Q,H.error)]);return H.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Ew({...this._def,args:C_.create(_).rest(d_.create())})}returns(_){return new Ew({...this._def,returns:_})}implement(_){return this.parse(_)}strictImplement(_){return this.parse(_)}static create(_,w,$){return new Ew({args:_?_:C_.create([]).rest(d_.create()),returns:w||d_.create(),typeName:F.ZodFunction,...k($)})}}class Iw extends v{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})}}Iw.create=(_,w)=>{return new Iw({getter:_,typeName:F.ZodLazy,...k(w)})};class gw extends v{_parse(_){if(_.data!==this._def.value){let w=this._getOrReturnCtx(_);return b(w,{received:w.data,code:O.invalid_literal,expected:this._def.value}),T}return{status:"valid",value:_.data}}get value(){return this._def.value}}gw.create=(_,w)=>{return new gw({value:_,typeName:F.ZodLiteral,...k(w)})};function c$(_,w){return new r_({values:_,typeName:F.ZodEnum,...k(w)})}class r_ extends v{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return b(w,{expected:l.joinValues($),received:w.parsedType,code:O.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 b(w,{received:w.data,code:O.invalid_enum_value,options:$}),T}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 r_.create(_,{...this._def,...w})}exclude(_,w=this._def){return r_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}r_.create=c$;class kw extends v{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==L.string&&$.parsedType!==L.number){let X=l.objectValues(w);return b($,{expected:l.joinValues(X),received:$.parsedType,code:O.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 b($,{received:$.data,code:O.invalid_enum_value,options:X}),T}return q_(_.data)}get enum(){return this._def.values}}kw.create=(_,w)=>{return new kw({values:_,typeName:F.ZodNativeEnum,...k(w)})};class Qw extends v{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==L.promise&&w.common.async===!1)return b(w,{code:O.invalid_type,expected:L.promise,received:w.parsedType}),T;let $=w.parsedType===L.promise?w.data:Promise.resolve(w.data);return q_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Qw.create=(_,w)=>{return new Qw({type:_,typeName:F.ZodPromise,...k(w)})};class L_ extends v{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,J={addIssue:(Y)=>{if(b($,Y),Y.fatal)w.abort();else w.dirty()},get path(){return $.path}};if(J.addIssue=J.addIssue.bind(J),X.type==="preprocess"){let Y=X.transform($.data,J);if($.common.async)return Promise.resolve(Y).then(async(W)=>{if(w.value==="aborted")return T;let q=await this._def.schema._parseAsync({data:W,path:$.path,parent:$});if(q.status==="aborted")return T;if(q.status==="dirty")return Yw(q.value);if(w.value==="dirty")return Yw(q.value);return q});else{if(w.value==="aborted")return T;let W=this._def.schema._parseSync({data:Y,path:$.path,parent:$});if(W.status==="aborted")return T;if(W.status==="dirty")return Yw(W.value);if(w.value==="dirty")return Yw(W.value);return W}}if(X.type==="refinement"){let Y=(W)=>{let q=X.refinement(W,J);if($.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if($.common.async===!1){let W=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(W.status==="aborted")return T;if(W.status==="dirty")w.dirty();return Y(W.value),{status:w.value,value:W.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((W)=>{if(W.status==="aborted")return T;if(W.status==="dirty")w.dirty();return Y(W.value).then(()=>{return{status:w.value,value:W.value}})})}if(X.type==="transform")if($.common.async===!1){let Y=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!c_(Y))return T;let W=X.transform(Y.value,J);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:W}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((Y)=>{if(!c_(Y))return T;return Promise.resolve(X.transform(Y.value,J)).then((W)=>({status:w.value,value:W}))});l.assertNever(X)}}L_.create=(_,w,$)=>{return new L_({schema:_,typeName:F.ZodEffects,effect:w,...k($)})};L_.createWithPreprocess=(_,w,$)=>{return new L_({schema:w,effect:{type:"preprocess",transform:_},typeName:F.ZodEffects,...k($)})};class F_ extends v{_parse(_){if(this._getType(_)===L.undefined)return q_(void 0);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}F_.create=(_,w)=>{return new F_({innerType:_,typeName:F.ZodOptional,...k(w)})};class v_ extends v{_parse(_){if(this._getType(_)===L.null)return q_(null);return this._def.innerType._parse(_)}unwrap(){return this._def.innerType}}v_.create=(_,w)=>{return new v_({innerType:_,typeName:F.ZodNullable,...k(w)})};class hw extends v{_parse(_){let{ctx:w}=this._processInputParams(_),$=w.data;if(w.parsedType===L.undefined)$=this._def.defaultValue();return this._def.innerType._parse({data:$,path:w.path,parent:w})}removeDefault(){return this._def.innerType}}hw.create=(_,w)=>{return new hw({innerType:_,typeName:F.ZodDefault,defaultValue:typeof w.default==="function"?w.default:()=>w.default,...k(w)})};class yw extends v{_parse(_){let{ctx:w}=this._processInputParams(_),$={...w,common:{...w.common,issues:[]}},X=this._def.innerType._parse({data:$.data,path:$.path,parent:{...$}});if(bw(X))return X.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new Y_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new Y_($.common.issues)},input:$.data})}}removeCatch(){return this._def.innerType}}yw.create=(_,w)=>{return new yw({innerType:_,typeName:F.ZodCatch,catchValue:typeof w.catch==="function"?w.catch:()=>w.catch,...k(w)})};class G0 extends v{_parse(_){if(this._getType(_)!==L.nan){let $=this._getOrReturnCtx(_);return b($,{code:O.invalid_type,expected:L.nan,received:$.parsedType}),T}return{status:"valid",value:_.data}}}G0.create=(_)=>{return new G0({typeName:F.ZodNaN,...k(_)})};var n9=Symbol("zod_brand");class Y1 extends v{_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 v{_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:$.data,path:$.path,parent:$});if(J.status==="aborted")return T;if(J.status==="dirty")return w.dirty(),Yw(J.value);else return this._def.out._parseAsync({data:J.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 Q0({in:_,out:w,typeName:F.ZodPipeline})}}class vw extends v{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(c_(X))X.value=Object.freeze(X.value);return X};return bw(w)?w.then((X)=>$(X)):$(w)}unwrap(){return this._def.innerType}}vw.create=(_,w)=>{return new vw({innerType:_,typeName:F.ZodReadonly,...k(w)})};function x$(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function d$(_,w={},$){if(_)return qw.create().superRefine((X,J)=>{let Y=_(X);if(Y instanceof Promise)return Y.then((W)=>{if(!W){let q=x$(w,X),G=q.fatal??$??!0;J.addIssue({code:"custom",...q,fatal:G})}});if(!Y){let W=x$(w,X),q=W.fatal??$??!0;J.addIssue({code:"custom",...W,fatal:q})}return});return qw.create()}var a9={object:s.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 o9=(_,w={message:`Input not instance of ${_.name}`})=>d$(($)=>$ instanceof _,w),p$=R_.create,i$=p_.create,s9=G0.create,t9=i_.create,r$=Sw.create,e9=Ww.create,_6=J0.create,w6=Pw.create,$6=Zw.create,X6=qw.create,J6=d_.create,Y6=Z_.create,W6=Y0.create,q6=O_.create,G6=s.create,Q6=s.strictCreate,H6=Cw.create,D6=J1.create,B6=Tw.create,U6=C_.create,z6=W0.create,V6=q0.create,A6=Gw.create,M6=Ew.create,R6=Iw.create,O6=gw.create,F6=r_.create,f6=kw.create,L6=Qw.create,K6=L_.create,N6=F_.create,b6=v_.create,j6=L_.createWithPreprocess,E6=Q0.create,S6=()=>p$().optional(),P6=()=>i$().optional(),Z6=()=>r$().optional(),C6={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>p_.create({..._,coerce:!0}),boolean:(_)=>Sw.create({..._,coerce:!0}),bigint:(_)=>i_.create({..._,coerce:!0}),date:(_)=>Ww.create({..._,coerce:!0})};var T6=T;var f2=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 I6(_){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 n$(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var UV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
225
|
+
\`problem\` milestone explaining the blocker instead of going silent.`;var X0="roy",m4={action:"execute",resource:"*",effect:"deny"};function u4(){return{id:X0,mode:"primary",description:R1,system:f1,permissions:[{...m4}]}}function S9(_,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 L1(_){let w=u4();return _.update(X0,($)=>{if($.mode=w.mode,$.description=w.description,$.system=w.system,$.hidden===void 0)$.hidden=!1;S9($,w.permissions)}),w}var A={};b9(A,{void:()=>B6,util:()=>l,unknown:()=>H6,union:()=>O6,undefined:()=>Q6,tuple:()=>R6,transformer:()=>P6,symbol:()=>W6,string:()=>o4,strictObject:()=>V6,setErrorMap:()=>C9,set:()=>F6,record:()=>f6,quotelessJson:()=>P9,promise:()=>S6,preprocess:()=>T6,pipeline:()=>I6,ostring:()=>k6,optional:()=>Z6,onumber:()=>g6,oboolean:()=>h6,objectUtil:()=>F1,object:()=>z6,number:()=>s4,nullable:()=>C6,null:()=>G6,never:()=>D6,nativeEnum:()=>E6,nan:()=>X6,map:()=>L6,makeIssue:()=>Y0,literal:()=>b6,lazy:()=>N6,late:()=>w6,isValid:()=>d_,isDirty:()=>J2,isAsync:()=>jw,isAborted:()=>Y2,intersection:()=>M6,instanceof:()=>$6,getParsedType:()=>Z_,getErrorMap:()=>bw,function:()=>K6,enum:()=>j6,effect:()=>P6,discriminatedUnion:()=>A6,defaultErrorMap:()=>y_,datetimeRegex:()=>n4,date:()=>J6,custom:()=>a4,coerce:()=>y6,boolean:()=>t4,bigint:()=>Y6,array:()=>U6,any:()=>q6,addIssueToContext:()=>S,ZodVoid:()=>W0,ZodUnknown:()=>p_,ZodUnion:()=>Tw,ZodUndefined:()=>Zw,ZodType:()=>x,ZodTuple:()=>T_,ZodTransformer:()=>K_,ZodSymbol:()=>J0,ZodString:()=>R_,ZodSet:()=>Hw,ZodSchema:()=>x,ZodRecord:()=>Q0,ZodReadonly:()=>xw,ZodPromise:()=>Dw,ZodPipeline:()=>H0,ZodParsedType:()=>E,ZodOptional:()=>L_,ZodObject:()=>t,ZodNumber:()=>i_,ZodNullable:()=>x_,ZodNull:()=>Cw,ZodNever:()=>C_,ZodNativeEnum:()=>hw,ZodNaN:()=>q0,ZodMap:()=>G0,ZodLiteral:()=>gw,ZodLazy:()=>kw,ZodIssueCode:()=>L,ZodIntersection:()=>Iw,ZodFunction:()=>Sw,ZodFirstPartyTypeKind:()=>K,ZodError:()=>W_,ZodEnum:()=>r_,ZodEffects:()=>K_,ZodDiscriminatedUnion:()=>W2,ZodDefault:()=>yw,ZodDate:()=>Gw,ZodCatch:()=>vw,ZodBranded:()=>Q2,ZodBoolean:()=>Pw,ZodBigInt:()=>n_,ZodArray:()=>f_,ZodAny:()=>qw,Schema:()=>x,ParseStatus:()=>Q_,OK:()=>G_,NEVER:()=>v6,INVALID:()=>I,EMPTY_PATH:()=>T9,DIRTY:()=>Qw,BRAND:()=>_6});var l;(function(_){_.assertEqual=(Y)=>{};function w(Y){}_.assertIs=w;function $(Y){throw Error()}_.assertNever=$,_.arrayToEnum=(Y)=>{let J={};for(let W of Y)J[W]=W;return J},_.getValidEnumValues=(Y)=>{let J=_.objectKeys(Y).filter((Q)=>typeof Y[Y[Q]]!=="number"),W={};for(let Q of J)W[Q]=Y[Q];return _.objectValues(W)},_.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 W in Y)if(Object.prototype.hasOwnProperty.call(Y,W))J.push(W);return J},_.find=(Y,J)=>{for(let W of Y)if(J(W))return W;return},_.isInteger=typeof Number.isInteger==="function"?(Y)=>Number.isInteger(Y):(Y)=>typeof Y==="number"&&Number.isFinite(Y)&&Math.floor(Y)===Y;function X(Y,J=" | "){return Y.map((W)=>typeof W==="string"?`'${W}'`:W).join(J)}_.joinValues=X,_.jsonStringifyReplacer=(Y,J)=>{if(typeof J==="bigint")return J.toString();return J}})(l||(l={}));var F1;(function(_){_.mergeShapes=(w,$)=>{return{...w,...$}}})(F1||(F1={}));var E=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 E.undefined;case"string":return E.string;case"number":return Number.isNaN(_)?E.nan:E.number;case"boolean":return E.boolean;case"function":return E.function;case"bigint":return E.bigint;case"symbol":return E.symbol;case"object":if(Array.isArray(_))return E.array;if(_===null)return E.null;if(_.then&&typeof _.then==="function"&&_.catch&&typeof _.catch==="function")return E.promise;if(typeof Map<"u"&&_ instanceof Map)return E.map;if(typeof Set<"u"&&_ instanceof Set)return E.set;if(typeof Date<"u"&&_ instanceof Date)return E.date;return E.object;default:return E.unknown}};var L=l.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),P9=(_)=>{return JSON.stringify(_,null,2).replace(/"([^"]+)":/g,"$1:")};class W_ 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 W=$,Q=0;while(Q<J.path.length){let G=J.path[Q];if(Q!==J.path.length-1)W[G]=W[G]||{_errors:[]};else W[G]=W[G]||{_errors:[]},W[G]._errors.push(w(J));W=W[G],Q++}}};return X(this),$}static assert(_){if(!(_ instanceof W_))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()}}W_.create=(_)=>{return new W_(_)};var Z9=(_,w)=>{let $;switch(_.code){case L.invalid_type:if(_.received===E.undefined)$="Required";else $=`Expected ${_.expected}, received ${_.received}`;break;case L.invalid_literal:$=`Invalid literal value, expected ${JSON.stringify(_.expected,l.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:$=`Unrecognized key(s) in object: ${l.joinValues(_.keys,", ")}`;break;case L.invalid_union:$="Invalid input";break;case L.invalid_union_discriminator:$=`Invalid discriminator value. Expected ${l.joinValues(_.options)}`;break;case L.invalid_enum_value:$=`Invalid enum value. Expected ${l.joinValues(_.options)}, received '${_.received}'`;break;case L.invalid_arguments:$="Invalid function arguments";break;case L.invalid_return_type:$="Invalid function return type";break;case L.invalid_date:$="Invalid date";break;case L.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 L.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 L.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 L.custom:$="Invalid input";break;case L.invalid_intersection_types:$="Intersection results could not be merged";break;case L.not_multiple_of:$=`Number must be a multiple of ${_.multipleOf}`;break;case L.not_finite:$="Number must be finite";break;default:$=w.defaultError,l.assertNever(_)}return{message:$}},y_=Z9;var l4=y_;function C9(_){l4=_}function bw(){return l4}var Y0=(_)=>{let{data:w,path:$,errorMaps:X,issueData:Y}=_,J=[...$,...Y.path||[]],W={...Y,path:J};if(Y.message!==void 0)return{...Y,path:J,message:Y.message};let Q="",G=X.filter((q)=>!!q).slice().reverse();for(let q of G)Q=q(W,{data:w,defaultError:Q}).message;return{...Y,path:J,message:Q}},T9=[];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 Q_{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 Q_.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"}),Qw=(_)=>({status:"dirty",value:_}),G_=(_)=>({status:"valid",value:_}),Y2=(_)=>_.status==="aborted",J2=(_)=>_.status==="dirty",d_=(_)=>_.status==="valid",jw=(_)=>typeof Promise<"u"&&_ instanceof Promise;var Z;(function(_){_.errToObj=(w)=>typeof w==="string"?{message:w}:w||{},_.toString=(w)=>typeof w==="string"?w:w?.message})(Z||(Z={}));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 c4=(_,w)=>{if(d_(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 W_(_.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:(W,Q)=>{let{message:G}=_;if(W.code==="invalid_enum_value")return{message:G??Q.defaultError};if(typeof Q.data>"u")return{message:G??X??Q.defaultError};if(W.code!=="invalid_type")return{message:Q.defaultError};return{message:G??$??Q.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 Q_,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 c4($,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 d_($)?{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(($)=>d_($)?{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 c4($,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),W=()=>Y.addIssue({code:L.custom,...$(X)});if(typeof Promise<"u"&&J instanceof Promise)return J.then((Q)=>{if(!Q)return W(),!1;else return!0});if(!J)return W(),!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 Dw.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 Q2({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 H0.create(this,_)}readonly(){return xw.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var I9=/^c[^\s-]{8,}$/i,k9=/^[0-9a-z]+$/,g9=/^[0-9A-HJKMNP-TV-Z]{26}$/i,h9=/^[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,y9=/^[a-z0-9_-]{21}$/i,v9=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,x9=/^[-+]?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)?)??$/,m9=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,u9="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",K1,l9=/^(?:(?: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])$/,c9=/^(?:(?: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])$/,d9=/^(([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]))$/,p9=/^(([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])$/,i9=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n9=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,p4="((\\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])))",r9=new RegExp(`^${p4}$`);function i4(_){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 a9(_){return new RegExp(`^${i4(_)}$`)}function n4(_){let w=`${p4}T${i4(_)}`,$=[];if($.push(_.local?"Z?":"Z"),_.offset)$.push("([+-]\\d{2}:?\\d{2})");return w=`${w}(${$.join("|")})`,new RegExp(`^${w}$`)}function o9(_,w){if((w==="v4"||!w)&&l9.test(_))return!0;if((w==="v6"||!w)&&d9.test(_))return!0;return!1}function s9(_,w){if(!v9.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 t9(_,w){if((w==="v4"||!w)&&c9.test(_))return!0;if((w==="v6"||!w)&&p9.test(_))return!0;return!1}class R_ extends x{_parse(_){if(this._def.coerce)_.data=String(_.data);if(this._getType(_)!==E.string){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.string,received:Y.parsedType}),I}let $=new Q_,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:L.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:L.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,W=_.data.length<Y.value;if(J||W){if(X=this._getOrReturnCtx(_,X),J)S(X,{code:L.too_big,maximum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});else if(W)S(X,{code:L.too_small,minimum:Y.value,type:"string",inclusive:!0,exact:!0,message:Y.message});$.dirty()}}else if(Y.kind==="email"){if(!m9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"email",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="emoji"){if(!K1)K1=new RegExp(u9,"u");if(!K1.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"emoji",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="uuid"){if(!h9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"uuid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="nanoid"){if(!y9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"nanoid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid"){if(!I9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cuid2"){if(!k9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"cuid2",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ulid"){if(!g9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"ulid",code:L.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:L.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:L.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:L.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:L.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:L.invalid_string,validation:{endsWith:Y.value},message:Y.message}),$.dirty()}else if(Y.kind==="datetime"){if(!n4(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"datetime",message:Y.message}),$.dirty()}else if(Y.kind==="date"){if(!r9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"date",message:Y.message}),$.dirty()}else if(Y.kind==="time"){if(!a9(Y).test(_.data))X=this._getOrReturnCtx(_,X),S(X,{code:L.invalid_string,validation:"time",message:Y.message}),$.dirty()}else if(Y.kind==="duration"){if(!x9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"duration",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="ip"){if(!o9(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"ip",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="jwt"){if(!s9(_.data,Y.alg))X=this._getOrReturnCtx(_,X),S(X,{validation:"jwt",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="cidr"){if(!t9(_.data,Y.version))X=this._getOrReturnCtx(_,X),S(X,{validation:"cidr",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64"){if(!i9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64",code:L.invalid_string,message:Y.message}),$.dirty()}else if(Y.kind==="base64url"){if(!n9.test(_.data))X=this._getOrReturnCtx(_,X),S(X,{validation:"base64url",code:L.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:L.invalid_string,...Z.errToObj($)})}_addCheck(_){return new R_({...this._def,checks:[...this._def.checks,_]})}email(_){return this._addCheck({kind:"email",...Z.errToObj(_)})}url(_){return this._addCheck({kind:"url",...Z.errToObj(_)})}emoji(_){return this._addCheck({kind:"emoji",...Z.errToObj(_)})}uuid(_){return this._addCheck({kind:"uuid",...Z.errToObj(_)})}nanoid(_){return this._addCheck({kind:"nanoid",...Z.errToObj(_)})}cuid(_){return this._addCheck({kind:"cuid",...Z.errToObj(_)})}cuid2(_){return this._addCheck({kind:"cuid2",...Z.errToObj(_)})}ulid(_){return this._addCheck({kind:"ulid",...Z.errToObj(_)})}base64(_){return this._addCheck({kind:"base64",...Z.errToObj(_)})}base64url(_){return this._addCheck({kind:"base64url",...Z.errToObj(_)})}jwt(_){return this._addCheck({kind:"jwt",...Z.errToObj(_)})}ip(_){return this._addCheck({kind:"ip",...Z.errToObj(_)})}cidr(_){return this._addCheck({kind:"cidr",...Z.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,...Z.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,...Z.errToObj(_?.message)})}duration(_){return this._addCheck({kind:"duration",...Z.errToObj(_)})}regex(_,w){return this._addCheck({kind:"regex",regex:_,...Z.errToObj(w)})}includes(_,w){return this._addCheck({kind:"includes",value:_,position:w?.position,...Z.errToObj(w?.message)})}startsWith(_,w){return this._addCheck({kind:"startsWith",value:_,...Z.errToObj(w)})}endsWith(_,w){return this._addCheck({kind:"endsWith",value:_,...Z.errToObj(w)})}min(_,w){return this._addCheck({kind:"min",value:_,...Z.errToObj(w)})}max(_,w){return this._addCheck({kind:"max",value:_,...Z.errToObj(w)})}length(_,w){return this._addCheck({kind:"length",value:_,...Z.errToObj(w)})}nonempty(_){return this.min(1,Z.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 e9(_,w){let $=(_.toString().split(".")[1]||"").length,X=(w.toString().split(".")[1]||"").length,Y=$>X?$:X,J=Number.parseInt(_.toFixed(Y).replace(".","")),W=Number.parseInt(w.toFixed(Y).replace(".",""));return J%W/10**Y}class i_ 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(_)!==E.number){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.number,received:Y.parsedType}),I}let $=void 0,X=new Q_;for(let Y of this._def.checks)if(Y.kind==="int"){if(!l.isInteger(_.data))$=this._getOrReturnCtx(_,$),S($,{code:L.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:L.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:L.too_big,maximum:Y.value,type:"number",inclusive:Y.inclusive,exact:!1,message:Y.message}),X.dirty()}else if(Y.kind==="multipleOf"){if(e9(_.data,Y.value)!==0)$=this._getOrReturnCtx(_,$),S($,{code:L.not_multiple_of,multipleOf:Y.value,message:Y.message}),X.dirty()}else if(Y.kind==="finite"){if(!Number.isFinite(_.data))$=this._getOrReturnCtx(_,$),S($,{code:L.not_finite,message:Y.message}),X.dirty()}else l.assertNever(Y);return{status:X.value,value:_.data}}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new i_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new i_({...this._def,checks:[...this._def.checks,_]})}int(_){return this._addCheck({kind:"int",message:Z.toString(_)})}positive(_){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.toString(w)})}finite(_){return this._addCheck({kind:"finite",message:Z.toString(_)})}safe(_){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Z.toString(_)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Z.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(_)}}i_.create=(_)=>{return new i_({checks:[],typeName:K.ZodNumber,coerce:_?.coerce||!1,...g(_)})};class n_ 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(_)!==E.bigint)return this._getInvalidInput(_);let $=void 0,X=new Q_;for(let Y of this._def.checks)if(Y.kind==="min"){if(Y.inclusive?_.data<Y.value:_.data<=Y.value)$=this._getOrReturnCtx(_,$),S($,{code:L.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:L.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:L.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:L.invalid_type,expected:E.bigint,received:w.parsedType}),I}gte(_,w){return this.setLimit("min",_,!0,Z.toString(w))}gt(_,w){return this.setLimit("min",_,!1,Z.toString(w))}lte(_,w){return this.setLimit("max",_,!0,Z.toString(w))}lt(_,w){return this.setLimit("max",_,!1,Z.toString(w))}setLimit(_,w,$,X){return new n_({...this._def,checks:[...this._def.checks,{kind:_,value:w,inclusive:$,message:Z.toString(X)}]})}_addCheck(_){return new n_({...this._def,checks:[...this._def.checks,_]})}positive(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}negative(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Z.toString(_)})}nonpositive(_){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}nonnegative(_){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Z.toString(_)})}multipleOf(_,w){return this._addCheck({kind:"multipleOf",value:_,message:Z.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 _}}n_.create=(_)=>{return new n_({checks:[],typeName:K.ZodBigInt,coerce:_?.coerce??!1,...g(_)})};class Pw extends x{_parse(_){if(this._def.coerce)_.data=Boolean(_.data);if(this._getType(_)!==E.boolean){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.boolean,received:$.parsedType}),I}return G_(_.data)}}Pw.create=(_)=>{return new Pw({typeName:K.ZodBoolean,coerce:_?.coerce||!1,...g(_)})};class Gw extends x{_parse(_){if(this._def.coerce)_.data=new Date(_.data);if(this._getType(_)!==E.date){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_type,expected:E.date,received:Y.parsedType}),I}if(Number.isNaN(_.data.getTime())){let Y=this._getOrReturnCtx(_);return S(Y,{code:L.invalid_date}),I}let $=new Q_,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:L.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:L.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 Gw({...this._def,checks:[...this._def.checks,_]})}min(_,w){return this._addCheck({kind:"min",value:_.getTime(),message:Z.toString(w)})}max(_,w){return this._addCheck({kind:"max",value:_.getTime(),message:Z.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}}Gw.create=(_)=>{return new Gw({checks:[],coerce:_?.coerce||!1,typeName:K.ZodDate,...g(_)})};class J0 extends x{_parse(_){if(this._getType(_)!==E.symbol){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.symbol,received:$.parsedType}),I}return G_(_.data)}}J0.create=(_)=>{return new J0({typeName:K.ZodSymbol,...g(_)})};class Zw extends x{_parse(_){if(this._getType(_)!==E.undefined){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.undefined,received:$.parsedType}),I}return G_(_.data)}}Zw.create=(_)=>{return new Zw({typeName:K.ZodUndefined,...g(_)})};class Cw extends x{_parse(_){if(this._getType(_)!==E.null){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.null,received:$.parsedType}),I}return G_(_.data)}}Cw.create=(_)=>{return new Cw({typeName:K.ZodNull,...g(_)})};class qw extends x{constructor(){super(...arguments);this._any=!0}_parse(_){return G_(_.data)}}qw.create=(_)=>{return new qw({typeName:K.ZodAny,...g(_)})};class p_ extends x{constructor(){super(...arguments);this._unknown=!0}_parse(_){return G_(_.data)}}p_.create=(_)=>{return new p_({typeName:K.ZodUnknown,...g(_)})};class C_ extends x{_parse(_){let w=this._getOrReturnCtx(_);return S(w,{code:L.invalid_type,expected:E.never,received:w.parsedType}),I}}C_.create=(_)=>{return new C_({typeName:K.ZodNever,...g(_)})};class W0 extends x{_parse(_){if(this._getType(_)!==E.undefined){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.void,received:$.parsedType}),I}return G_(_.data)}}W0.create=(_)=>{return new W0({typeName:K.ZodVoid,...g(_)})};class f_ extends x{_parse(_){let{ctx:w,status:$}=this._processInputParams(_),X=this._def;if(w.parsedType!==E.array)return S(w,{code:L.invalid_type,expected:E.array,received:w.parsedType}),I;if(X.exactLength!==null){let J=w.data.length>X.exactLength.value,W=w.data.length<X.exactLength.value;if(J||W)S(w,{code:J?L.too_big:L.too_small,minimum:W?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:L.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:L.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,W)=>{return X.type._parseAsync(new F_(w,J,w.path,W))})).then((J)=>{return Q_.mergeArray($,J)});let Y=[...w.data].map((J,W)=>{return X.type._parseSync(new F_(w,J,w.path,W))});return Q_.mergeArray($,Y)}get element(){return this._def.type}min(_,w){return new f_({...this._def,minLength:{value:_,message:Z.toString(w)}})}max(_,w){return new f_({...this._def,maxLength:{value:_,message:Z.toString(w)}})}length(_,w){return new f_({...this._def,exactLength:{value:_,message:Z.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(_)!==E.object){let G=this._getOrReturnCtx(_);return S(G,{code:L.invalid_type,expected:E.object,received:G.parsedType}),I}let{status:$,ctx:X}=this._processInputParams(_),{shape:Y,keys:J}=this._getCached(),W=[];if(!(this._def.catchall instanceof C_&&this._def.unknownKeys==="strip")){for(let G in X.data)if(!J.includes(G))W.push(G)}let Q=[];for(let G of J){let q=Y[G],H=X.data[G];Q.push({key:{status:"valid",value:G},value:q._parse(new F_(X,H,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 W)Q.push({key:{status:"valid",value:q},value:{status:"valid",value:X.data[q]}});else if(G==="strict"){if(W.length>0)S(X,{code:L.unrecognized_keys,keys:W}),$.dirty()}else if(G==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let G=this._def.catchall;for(let q of W){let H=X.data[q];Q.push({key:{status:"valid",value:q},value:G._parse(new F_(X,H,X.path,q)),alwaysSet:q in X.data})}}if(X.common.async)return Promise.resolve().then(async()=>{let G=[];for(let q of Q){let H=await q.key,B=await q.value;G.push({key:H,value:B,alwaysSet:q.alwaysSet})}return G}).then((G)=>{return Q_.mergeObjectSync($,G)});else return Q_.mergeObjectSync($,Q)}get shape(){return this._def.shape()}strict(_){return Z.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:Z.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 r4(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 W of Y)if(W.result.status==="valid")return W.result;for(let W of Y)if(W.result.status==="dirty")return w.common.issues.push(...W.ctx.common.issues),W.result;let J=Y.map((W)=>new W_(W.ctx.common.issues));return S(w,{code:L.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 Q of $){let G={...w,common:{...w.common,issues:[]},parent:null},q=Q._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 W=J.map((Q)=>new W_(Q));return S(w,{code:L.invalid_union,unionErrors:W}),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 r_)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 Q2)return v_(_.unwrap());else if(_ instanceof xw)return v_(_.unwrap());else if(_ instanceof vw)return v_(_._def.innerType);else return[]};class W2 extends x{_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==E.object)return S(w,{code:L.invalid_type,expected:E.object,received:w.parsedType}),I;let $=this.discriminator,X=w.data[$],Y=this.optionsMap.get(X);if(!Y)return S(w,{code:L.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 W of J){if(X.has(W))throw Error(`Discriminator property ${String(_)} has duplicate value ${String(W)}`);X.set(W,Y)}}return new W2({typeName:K.ZodDiscriminatedUnion,discriminator:_,options:w,optionsMap:X,...g($)})}}function N1(_,w){let $=Z_(_),X=Z_(w);if(_===w)return{valid:!0,data:_};else if($===E.object&&X===E.object){let Y=l.objectKeys(w),J=l.objectKeys(_).filter((Q)=>Y.indexOf(Q)!==-1),W={..._,...w};for(let Q of J){let G=N1(_[Q],w[Q]);if(!G.valid)return{valid:!1};W[Q]=G.data}return{valid:!0,data:W}}else if($===E.array&&X===E.array){if(_.length!==w.length)return{valid:!1};let Y=[];for(let J=0;J<_.length;J++){let W=_[J],Q=w[J],G=N1(W,Q);if(!G.valid)return{valid:!1};Y.push(G.data)}return{valid:!0,data:Y}}else if($===E.date&&X===E.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(Y2(Y)||Y2(J))return I;let W=N1(Y.value,J.value);if(!W.valid)return S($,{code:L.invalid_intersection_types}),I;if(J2(Y)||J2(J))w.dirty();return{status:w.value,value:W.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!==E.array)return S($,{code:L.invalid_type,expected:E.array,received:$.parsedType}),I;if($.data.length<this._def.items.length)return S($,{code:L.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:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w.dirty();let Y=[...$.data].map((J,W)=>{let Q=this._def.items[W]||this._def.rest;if(!Q)return null;return Q._parse(new F_($,J,$.path,W))}).filter((J)=>!!J);if($.common.async)return Promise.all(Y).then((J)=>{return Q_.mergeArray(w,J)});else return Q_.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 Q0 extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(_){let{status:w,ctx:$}=this._processInputParams(_);if($.parsedType!==E.object)return S($,{code:L.invalid_type,expected:E.object,received:$.parsedType}),I;let X=[],Y=this._def.keyType,J=this._def.valueType;for(let W in $.data)X.push({key:Y._parse(new F_($,W,$.path,W)),value:J._parse(new F_($,$.data[W],$.path,W)),alwaysSet:W in $.data});if($.common.async)return Q_.mergeObjectAsync(w,X);else return Q_.mergeObjectSync(w,X)}get element(){return this._def.valueType}static create(_,w,$){if(w instanceof x)return new Q0({keyType:_,valueType:w,typeName:K.ZodRecord,...g($)});return new Q0({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!==E.map)return S($,{code:L.invalid_type,expected:E.map,received:$.parsedType}),I;let X=this._def.keyType,Y=this._def.valueType,J=[...$.data.entries()].map(([W,Q],G)=>{return{key:X._parse(new F_($,W,$.path,[G,"key"])),value:Y._parse(new F_($,Q,$.path,[G,"value"]))}});if($.common.async){let W=new Map;return Promise.resolve().then(async()=>{for(let Q of J){let G=await Q.key,q=await Q.value;if(G.status==="aborted"||q.status==="aborted")return I;if(G.status==="dirty"||q.status==="dirty")w.dirty();W.set(G.value,q.value)}return{status:w.value,value:W}})}else{let W=new Map;for(let Q of J){let{key:G,value:q}=Q;if(G.status==="aborted"||q.status==="aborted")return I;if(G.status==="dirty"||q.status==="dirty")w.dirty();W.set(G.value,q.value)}return{status:w.value,value:W}}}}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!==E.set)return S($,{code:L.invalid_type,expected:E.set,received:$.parsedType}),I;let X=this._def;if(X.minSize!==null){if($.data.size<X.minSize.value)S($,{code:L.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:L.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(Q){let G=new Set;for(let q of Q){if(q.status==="aborted")return I;if(q.status==="dirty")w.dirty();G.add(q.value)}return{status:w.value,value:G}}let W=[...$.data.values()].map((Q,G)=>Y._parse(new F_($,Q,$.path,G)));if($.common.async)return Promise.all(W).then((Q)=>J(Q));else return J(W)}min(_,w){return new Hw({...this._def,minSize:{value:_,message:Z.toString(w)}})}max(_,w){return new Hw({...this._def,maxSize:{value:_,message:Z.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!==E.function)return S(w,{code:L.invalid_type,expected:E.function,received:w.parsedType}),I;function $(W,Q){return Y0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:L.invalid_arguments,argumentsError:Q}})}function X(W,Q){return Y0({data:W,path:w.path,errorMaps:[w.common.contextualErrorMap,w.schemaErrorMap,bw(),y_].filter((G)=>!!G),issueData:{code:L.invalid_return_type,returnTypeError:Q}})}let Y={errorMap:w.common.contextualErrorMap},J=w.data;if(this._def.returns instanceof Dw){let W=this;return G_(async function(...Q){let G=new W_([]),q=await W._def.args.parseAsync(Q,Y).catch((D)=>{throw G.addIssue($(Q,D)),G}),H=await Reflect.apply(J,this,q);return await W._def.returns._def.type.parseAsync(H,Y).catch((D)=>{throw G.addIssue(X(H,D)),G})})}else{let W=this;return G_(function(...Q){let G=W._def.args.safeParse(Q,Y);if(!G.success)throw new W_([$(Q,G.error)]);let q=Reflect.apply(J,this,G.data),H=W._def.returns.safeParse(q,Y);if(!H.success)throw new W_([X(q,H.error)]);return H.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(..._){return new Sw({...this._def,args:T_.create(_).rest(p_.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(p_.create()),returns:w||p_.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:L.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 r4(_,w){return new r_({values:_,typeName:K.ZodEnum,...g(w)})}class r_ extends x{_parse(_){if(typeof _.data!=="string"){let w=this._getOrReturnCtx(_),$=this._def.values;return S(w,{expected:l.joinValues($),received:w.parsedType,code:L.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:L.invalid_enum_value,options:$}),I}return G_(_.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 r_.create(_,{...this._def,...w})}exclude(_,w=this._def){return r_.create(this.options.filter(($)=>!_.includes($)),{...this._def,...w})}}r_.create=r4;class hw extends x{_parse(_){let w=l.getValidEnumValues(this._def.values),$=this._getOrReturnCtx(_);if($.parsedType!==E.string&&$.parsedType!==E.number){let X=l.objectValues(w);return S($,{expected:l.joinValues(X),received:$.parsedType,code:L.invalid_type}),I}if(!this._cache)this._cache=new Set(l.getValidEnumValues(this._def.values));if(!this._cache.has(_.data)){let X=l.objectValues(w);return S($,{received:$.data,code:L.invalid_enum_value,options:X}),I}return G_(_.data)}get enum(){return this._def.values}}hw.create=(_,w)=>{return new hw({values:_,typeName:K.ZodNativeEnum,...g(w)})};class Dw extends x{unwrap(){return this._def.type}_parse(_){let{ctx:w}=this._processInputParams(_);if(w.parsedType!==E.promise&&w.common.async===!1)return S(w,{code:L.invalid_type,expected:E.promise,received:w.parsedType}),I;let $=w.parsedType===E.promise?w.data:Promise.resolve(w.data);return G_($.then((X)=>{return this._def.type.parseAsync(X,{path:w.path,errorMap:w.common.contextualErrorMap})}))}}Dw.create=(_,w)=>{return new Dw({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(W)=>{if(w.value==="aborted")return I;let Q=await this._def.schema._parseAsync({data:W,path:$.path,parent:$});if(Q.status==="aborted")return I;if(Q.status==="dirty")return Qw(Q.value);if(w.value==="dirty")return Qw(Q.value);return Q});else{if(w.value==="aborted")return I;let W=this._def.schema._parseSync({data:J,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")return Qw(W.value);if(w.value==="dirty")return Qw(W.value);return W}}if(X.type==="refinement"){let J=(W)=>{let Q=X.refinement(W,Y);if($.common.async)return Promise.resolve(Q);if(Q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return W};if($.common.async===!1){let W=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(W.status==="aborted")return I;if(W.status==="dirty")w.dirty();return J(W.value),{status:w.value,value:W.value}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((W)=>{if(W.status==="aborted")return I;if(W.status==="dirty")w.dirty();return J(W.value).then(()=>{return{status:w.value,value:W.value}})})}if(X.type==="transform")if($.common.async===!1){let J=this._def.schema._parseSync({data:$.data,path:$.path,parent:$});if(!d_(J))return I;let W=X.transform(J.value,Y);if(W instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:w.value,value:W}}else return this._def.schema._parseAsync({data:$.data,path:$.path,parent:$}).then((J)=>{if(!d_(J))return I;return Promise.resolve(X.transform(J.value,Y)).then((W)=>({status:w.value,value:W}))});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(_)===E.undefined)return G_(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(_)===E.null)return G_(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===E.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 W_($.common.issues)},input:$.data})}});else return{status:"valid",value:X.status==="valid"?X.value:this._def.catchValue({get error(){return new W_($.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(_)!==E.nan){let $=this._getOrReturnCtx(_);return S($,{code:L.invalid_type,expected:E.nan,received:$.parsedType}),I}return{status:"valid",value:_.data}}}q0.create=(_)=>{return new q0({typeName:K.ZodNaN,...g(_)})};var _6=Symbol("zod_brand");class Q2 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 H0 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(),Qw(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 H0({in:_,out:w,typeName:K.ZodPipeline})}}class xw extends x{_parse(_){let w=this._def.innerType._parse(_),$=(X)=>{if(d_(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 d4(_,w){let $=typeof _==="function"?_(w):typeof _==="string"?{message:_}:_;return typeof $==="string"?{message:$}:$}function a4(_,w={},$){if(_)return qw.create().superRefine((X,Y)=>{let J=_(X);if(J instanceof Promise)return J.then((W)=>{if(!W){let Q=d4(w,X),G=Q.fatal??$??!0;Y.addIssue({code:"custom",...Q,fatal:G})}});if(!J){let W=d4(w,X),Q=W.fatal??$??!0;Y.addIssue({code:"custom",...W,fatal:Q})}return});return qw.create()}var w6={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 $6=(_,w={message:`Input not instance of ${_.name}`})=>a4(($)=>$ instanceof _,w),o4=R_.create,s4=i_.create,X6=q0.create,Y6=n_.create,t4=Pw.create,J6=Gw.create,W6=J0.create,Q6=Zw.create,G6=Cw.create,q6=qw.create,H6=p_.create,D6=C_.create,B6=W0.create,U6=f_.create,z6=t.create,V6=t.strictCreate,O6=Tw.create,A6=W2.create,M6=Iw.create,R6=T_.create,f6=Q0.create,L6=G0.create,F6=Hw.create,K6=Sw.create,N6=kw.create,b6=gw.create,j6=r_.create,E6=hw.create,S6=Dw.create,P6=K_.create,Z6=L_.create,C6=x_.create,T6=K_.createWithPreprocess,I6=H0.create,k6=()=>o4().optional(),g6=()=>s4().optional(),h6=()=>t4().optional(),y6={string:(_)=>R_.create({..._,coerce:!0}),number:(_)=>i_.create({..._,coerce:!0}),boolean:(_)=>Pw.create({..._,coerce:!0}),bigint:(_)=>n_.create({..._,coerce:!0}),date:(_)=>Gw.create({..._,coerce:!0})};var v6=I;var b1=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 x6(_){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 e4(_){let w=Date.now();return{alive:!1,status:"not_found",createdAt:w,lastUpdatedAt:w,description:`No background process found with id '${_}'.`}}var jV={name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
226
226
|
|
|
227
227
|
Use this tool when:
|
|
228
228
|
- 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 +239,7 @@ Use this tool when:
|
|
|
239
239
|
- result: present when status is 'completed'
|
|
240
240
|
- error: present when status is 'failed'
|
|
241
241
|
|
|
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:
|
|
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:b1,permission:{level:"safe",requireConfirmation:!1},metadata:{category:"task",tags:["background","delegate","query","status","diagnostic"],version:"1.0.0",allowedAgentTypes:["default"]},execute:async(_,w)=>G2(null).execute(_,w)};function G2(_=null){return{name:"query_background_process",description:`Query the status of a background process previously launched via delegate_task.
|
|
243
243
|
|
|
244
244
|
Use this tool when:
|
|
245
245
|
- 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 +256,7 @@ Use this tool when:
|
|
|
256
256
|
- result: present when status is 'completed'
|
|
257
257
|
- error: present when status is 'failed'
|
|
258
258
|
|
|
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:
|
|
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:b1,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=b1.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 W;try{W=_.getTask(J)}catch(G){return{success:!1,output:"",error:`failed to query background task: ${G.message}`,metadata:{execution_time_ms:Date.now()-X}}}if(W){let G=$.session_id;if(!G||W.parentSessionId!==G)return{success:!0,output:JSON.stringify(e4(J),null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:"not_found",alive:!1}}}let Q=W?x6(W):e4(J);return{success:!0,output:JSON.stringify(Q,null,2),metadata:{execution_time_ms:Date.now()-X,bgProcessId:J,status:Q.status,alive:Q.alive}}}}}import{createRequire as m6}from"module";var{defineProperty:j1,getOwnPropertyNames:u6,getOwnPropertyDescriptor:l6}=Object,c6=Object.prototype.hasOwnProperty;function d6(_){return this[_]}var mw=(_)=>{var w=(_8??=new WeakMap).get(_),$;if(w)return w;if(w=j1({},"__esModule",{value:!0}),_&&typeof _==="object"||typeof _==="function"){for(var X of u6(_))if(!c6.call(w,X))j1(w,X,{get:d6.bind(_,X),enumerable:!($=l6(_,X))||$.enumerable})}return _8.set(_,w),w},_8,p6=(_)=>_;function i6(_,w){this[_]=p6.bind(null,w)}var a_=(_,w)=>{for(var $ in w)j1(_,$,{get:w[$],enumerable:!0,configurable:!0,set:i6.bind(w,$)})},m=function(_,w,$,X){var Y=arguments.length,J=Y<3?w:X===null?X=Object.getOwnPropertyDescriptor(w,$):X,W;if(typeof Reflect==="object"&&typeof Reflect.decorate==="function")J=Reflect.decorate(_,w,$,X);else for(var Q=_.length-1;Q>=0;Q--)if(W=_[Q])J=(Y<3?W(J):Y>3?W(w,$,J):W(w,$))||J;return Y>3&&J&&Object.defineProperty(w,$,J),J},r=(_,w)=>()=>(_&&(w=_(_=0)),w),w_=m6(import.meta.url);function E1(){return process.env.ROY_TRACE_DEBUG_STORAGE==="1"||process.env.ROY_TRACE_DEBUG==="1"}function w8(_){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 n6(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}else return w_("better-sqlite3")}function r6(_){let $=new(n6())(_);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 S1{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 _=w_("fs"),$=w_("path").dirname(this.dbPath);if(!_.existsSync($))_.mkdirSync($,{recursive:!0});this.db=r6(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(`
|
|
260
260
|
CREATE TABLE IF NOT EXISTS span (
|
|
261
261
|
span_id TEXT PRIMARY KEY,
|
|
262
262
|
trace_id TEXT NOT NULL,
|
|
@@ -271,11 +271,11 @@ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-
|
|
|
271
271
|
error TEXT,
|
|
272
272
|
time_created INTEGER NOT NULL
|
|
273
273
|
)
|
|
274
|
-
`),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(
|
|
274
|
+
`),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(E1())console.log(`[SpanStorage] save() skipped: db not initialized for span "${_.name}" traceId=${_.traceId}`);return}let w=this.db.prepare(`
|
|
275
275
|
INSERT OR REPLACE INTO span
|
|
276
276
|
(span_id, trace_id, parent_span_id, name, kind, status, start_time, end_time, attributes, result, error, time_created)
|
|
277
277
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
278
|
-
`),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:
|
|
278
|
+
`),$=_.result!==void 0&&_.result!==null?typeof _.result==="string"?_.result:w8(_.result):null;if(E1())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,w8(_.attributes),$,_.error||null,Date.now());if(E1())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(`
|
|
279
279
|
SELECT trace_id,
|
|
280
280
|
MIN(start_time) as start_time,
|
|
281
281
|
MAX(end_time) as end_time,
|
|
@@ -290,316 +290,10 @@ Only the default receptionist agent has this tool. Sub-agents (roy, strict-task-
|
|
|
290
290
|
GROUP BY trace_id
|
|
291
291
|
ORDER BY start_time DESC
|
|
292
292
|
LIMIT ?
|
|
293
|
-
`).all(_).map(($)=>{let X=Number($.span_count)||0,
|
|
294
|
-
`)||[];Error.stackTraceLimit=_;for(let X=1;X<$.length;X++){let
|
|
295
|
-
`,"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),!w7())(_==="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 J4(_));return q1.get(_)}var K_=null,G7=!1;var P2,q1,a=r(()=>{h2(),P2={debug:0,info:1,warn:2,error:3},q1=new Map}),Q7={};n_(Q7,{setTracerProvider:()=>D7,resetTracerProvider:()=>H7,getTracerProvider:()=>D0,OTelTracerProvider:()=>k2});function g2(){if(!E2)E2=n("otel-tracer");return E2}function Y4(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function W4(_,...w){g2().info(_,...w)}function e$(_,...w){g2().warn(_,...w)}function _4(_,...w){g2().error(_,...w)}class Z2{name;kind;spanContext;attributes={};startTime;endTime;error;storage;parentSpanContext;onEnd;constructor(_,w,$,X,J){this.name=_,this.kind="internal",this.spanContext=w,this.parentSpanContext=X,this.startTime=Date.now(),this.storage=$,this.onEnd=J}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(Y4())W4(`[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)e$(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=D0().getStorage();if(X){if(!(X.db||X.initialized))e$(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((Y)=>{_4("[OTelSpan] Failed to initialize storage:",Y)});X.save({traceId:this.spanContext.traceId,spanId:this.spanContext.spanId,parentSpanId:this.spanContext.parentSpanId,name:this.name,kind:this.kind,status:w?"error":"ok",startTime:this.startTime,endTime:this.endTime,attributes:this.attributes,result:_,error:this.error})}else _4(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class q4{name;version;storage;currentContext;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,J=w&&"context"in w,Y=this.provider.getGlobalContext(),W,q,G,Q,H;if(J&&w?.context){let D=w.context;q=D.traceId,G=this.generateSpanId(),Q=D.spanId,H={traceId:q,spanId:G,parentSpanId:Q},this.currentContext={traceId:q,spanId:G,parentSpanId:Q};let z=new Z2(_,H,this.storage,D,()=>this.handleSpanEnd(H.spanId,D.spanId));if(w?.attributes)for(let[A,U]of Object.entries(w.attributes))z.setAttribute(A,U);return this.activeSpans.set(G,z),z}if(X)W=$;else if(this.currentContext)W=this.currentContext;else if(Y)W=Y;if(q=W?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)Q=$.parentSpanId||$.spanId;else if(this.currentContext)Q=this.currentContext.spanId;else if(Y)Q=Y.spanId;H={traceId:q,spanId:G,parentSpanId:Q},this.currentContext={traceId:q,spanId:G,parentSpanId:Q};let B=new Z2(_,H,this.storage,W,()=>this.handleSpanEnd(H.spanId,W?.spanId));if(w?.attributes)for(let[D,z]of Object.entries(w.attributes))B.setAttribute(D,z);if(this.activeSpans.set(G,B),Y4())W4(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${q} spanId=${G} parentSpanId=${Q||"-"}`);return B}injectToEnv(_){if(this.currentContext)C2.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 J=this.activeSpans.get(w.parentSpanId);if(J){let Y={traceId:w.traceId,spanId:J.spanContext.spanId,parentSpanId:J.spanContext.parentSpanId};return this.currentContext=Y,Y}if($){let Y={traceId:$,spanId:w.parentSpanId,parentSpanId:void 0};return this.currentContext=Y,Y}}let X=this.findStackParentSpan(w.spanId);if(X){let J={traceId:X.spanContext.traceId,spanId:X.spanContext.spanId,parentSpanId:X.spanContext.parentSpanId};return this.currentContext=J,J}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 k2{tracers=new Map;storage;initialized=!1;globalContext;instanceId;constructor(_,w){w4++,this.instanceId=`Provider#${w4}`,this.storage=_||new N2(w||B7())}async initialize(){if(this.initialized)return;await this.storage.initialize(),this.initialized=!0}isInitialized(){return this.initialized}getGlobalContext(){return this.globalContext}setGlobalContext(_){this.globalContext=_}getTracer(_,w){let $=`${_}@${w||"0.0.0"}`,X=this.tracers.get($);if(!X){if(X=new q4(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=C2.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 D0(){if(!x_)x_=new k2;return x_}function H7(){if(x_)x_.shutdown(),x_=null}function D7(_){if(x_)x_.shutdown();x_=_}function B7(){let _=__("os"),w=__("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var E2=null,x_=null,w4=0,h2=r(()=>{s$(),r6(),o6(),a()});function U7(_){let w=()=>({recordParams:_?.recordParams??!0,recordResult:_?.recordResult??!1,recordError:_?.recordError??!0,log:_?.log??!1,maxLogSize:_?.maxLogSize,paramFilter:_?.paramFilter,resultFilter:_?.resultFilter,flattenParamFilter:_?.flattenParamFilter,errorIf:_?.errorIf});return function($,X,J){if(J!==void 0&&J!==null&&typeof J==="object"&&"value"in J){let q=J.value,G=_?.name||String(X);return J.value=T_(q,G,w()),J}let Y=$,W=X||{};if(typeof Y==="function"){let q=_?.name||(W?.name?String(W.name):"anonymous");return T_(Y,q,w())}return Y}}function u(_,w){return U7({name:_,...w})}function T_(_,w,$){let X=$?.log??!1,J=()=>{if($?.maxLogSize!==void 0)return $.maxLogSize;let B=I2();return B!==void 0?B:500},Y=(B)=>{if(B===void 0)return;if(B===null)return null;let D=J(),z;try{z=typeof B==="string"?B:JSON.stringify(B,null,0).replace(/\n/g,"")}catch(A){z=`[Object with circular reference: ${A instanceof Error?A.message:String(A)}]`}if(D>0&&z.length>D)return z.slice(0,D)+" [TRUNCATED]";try{return JSON.parse(z)}catch{return z}},W=(B)=>{if(B===void 0)return"undefined";if(B===null)return"null";let D=J(),z;try{z=typeof B==="string"?B:JSON.stringify(B,null,0).replace(/\n/g,"")}catch(A){z=`[Object with circular reference: ${A instanceof Error?A.message:String(A)}]`}return D>0&&z.length>D?z.slice(0,D)+" [TRUNCATED]":z},q=(B)=>{if(B===void 0)return;if(B===null)return null;if(typeof B==="string")return B;try{return JSON.parse(JSON.stringify(B))}catch(D){return`[Object with circular reference: ${D instanceof Error?D.message:String(D)}]`}},G="[TRACE]",Q=()=>{let B=Error.stackTraceLimit;Error.stackTraceLimit=15;let D=Error();Error.captureStackTrace(D,Q);let z=D.stack?.split(`
|
|
296
|
-
`)||[];Error.stackTraceLimit=
|
|
297
|
-
CREATE TABLE IF NOT EXISTS task (
|
|
298
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
299
|
-
title TEXT NOT NULL,
|
|
300
|
-
description TEXT DEFAULT '',
|
|
301
|
-
status TEXT DEFAULT 'todo',
|
|
302
|
-
priority TEXT DEFAULT 'medium',
|
|
303
|
-
type TEXT DEFAULT 'normal',
|
|
304
|
-
progress INTEGER DEFAULT 0,
|
|
305
|
-
current_status TEXT DEFAULT '',
|
|
306
|
-
goals_and_expected_deliverables TEXT DEFAULT '',
|
|
307
|
-
parent_task_id INTEGER,
|
|
308
|
-
created_at INTEGER NOT NULL,
|
|
309
|
-
updated_at INTEGER NOT NULL,
|
|
310
|
-
due_date TEXT,
|
|
311
|
-
tags TEXT,
|
|
312
|
-
project_path TEXT NOT NULL DEFAULT 'unknown',
|
|
313
|
-
context TEXT NOT NULL DEFAULT '{}'
|
|
314
|
-
)
|
|
315
|
-
`),this.db.run(`
|
|
316
|
-
CREATE TABLE IF NOT EXISTS task_operation (
|
|
317
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
318
|
-
task_id INTEGER NOT NULL,
|
|
319
|
-
session_id TEXT NOT NULL,
|
|
320
|
-
milestone_type TEXT NOT NULL,
|
|
321
|
-
milestone_title TEXT NOT NULL,
|
|
322
|
-
milestone_description TEXT DEFAULT '',
|
|
323
|
-
process_description TEXT NOT NULL DEFAULT '',
|
|
324
|
-
timestamp INTEGER NOT NULL,
|
|
325
|
-
md_path TEXT,
|
|
326
|
-
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE
|
|
327
|
-
)
|
|
328
|
-
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_task_id ON task_operation(task_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_session_id ON task_operation(session_id)"),this.db.run(`
|
|
329
|
-
CREATE TABLE IF NOT EXISTS task_tag (
|
|
330
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
331
|
-
name TEXT NOT NULL UNIQUE,
|
|
332
|
-
created_at INTEGER NOT NULL,
|
|
333
|
-
task_count INTEGER DEFAULT 0
|
|
334
|
-
)
|
|
335
|
-
`),this.db.run(`
|
|
336
|
-
CREATE TABLE IF NOT EXISTS task_tag_relation (
|
|
337
|
-
task_id INTEGER NOT NULL,
|
|
338
|
-
tag_id INTEGER NOT NULL,
|
|
339
|
-
created_at INTEGER NOT NULL,
|
|
340
|
-
PRIMARY KEY (task_id, tag_id),
|
|
341
|
-
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
342
|
-
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
343
|
-
)
|
|
344
|
-
`),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}=(V7(),xw(G4));w(this.dbPath)}catch(w){Hw.warn(`[Migration 001] Failed to run: ${w.message}`)}try{let{runMigration:w}=(M7(),xw(Q4));w(this.dbPath)}catch(w){Hw.warn(`[Migration 002] Failed to run: ${w.message}`)}try{let{runMigration:w}=(O7(),xw(H4));w(this.dbPath)}catch(w){Hw.warn(`[Migration 003] Failed to run: ${w.message}`)}try{let{runMigration:w}=(f7(),xw(D4));w(this.dbPath)}catch(w){Hw.warn(`[Migration 004] Failed to run: ${w.message}`)}try{let{runMigration:w}=(K7(),xw(U4));w(this.dbPath)}catch(w){Hw.warn(`[Migration 005] Failed to run: ${w.message}`)}}this.initialized=!0,Hw.info(`TaskStore initialized at ${this.dbPath}`)}async createTask(w){await this.initialize();let $=Date.now(),J=this.db.prepare(`
|
|
345
|
-
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
346
|
-
goals_and_expected_deliverables, due_date, tags, status,
|
|
347
|
-
current_status, created_at, updated_at, project_path, context)
|
|
348
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'todo', '', ?, ?, ?, ?)
|
|
349
|
-
`).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),Y=await this.getTask(J.lastInsertRowid);if(Y)return this.tasksCache.set(Y.id,Y),Y;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 J=this.rowToTask(X);return this.tasksCache.set(w,J),J}async updateTask(w,$){await this.initialize();let X=await this.getTask(w);if(!X)return;let J=[],Y=[];if($.title!==void 0)J.push("title = ?"),Y.push($.title);if($.description!==void 0)J.push("description = ?"),Y.push($.description);if($.status!==void 0)J.push("status = ?"),Y.push($.status);if($.priority!==void 0)J.push("priority = ?"),Y.push($.priority);if($.type!==void 0)J.push("type = ?"),Y.push($.type);if($.progress!==void 0)J.push("progress = ?"),Y.push($.progress);if($.current_status!==void 0)J.push("current_status = ?"),Y.push($.current_status);if($.goals_and_expected_deliverables!==void 0)J.push("goals_and_expected_deliverables = ?"),Y.push($.goals_and_expected_deliverables);if($.due_date!==void 0)J.push("due_date = ?"),Y.push($.due_date);if($.tags!==void 0)J.push("tags = ?"),Y.push(JSON.stringify($.tags));if($.project_path!==void 0)J.push("project_path = ?"),Y.push($.project_path);if($.context!==void 0)J.push("context = ?"),Y.push($.context);if($.parent_task_id!==void 0)J.push("parent_task_id = ?"),Y.push($.parent_task_id);if(J.length===0)return X;return J.push("updated_at = ?"),Y.push(Date.now()),Y.push(w),this.db.prepare(`UPDATE task SET ${J.join(", ")} WHERE id = ?`).run(...Y),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 J=$.join(" AND "),Y=`SELECT COUNT(*) as total FROM task WHERE ${J}`,q=this.db.prepare(Y).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${J}`,Q=[...X];if(G+=" ORDER BY updated_at DESC",w?.limit)G+=" LIMIT ?",Q.push(w.limit);if(w?.offset)G+=" OFFSET ?",Q.push(w.offset);return{tasks:this.db.prepare(G).all(...Q).map((z)=>{let A=this.rowToTask(z);return this.tasksCache.set(A.id,A),A}),total:q}}async listTasksByDepth(w){let $=w.depth??0,X=["1=1"],J=[];if(w.status)X.push("status = ?"),J.push(w.status);if(w.priority)X.push("priority = ?"),J.push(w.priority);if(w.type)X.push("type = ?"),J.push(w.type);if(!w?.include_archived&&w?.status!=="archived")X.push("status != 'archived'");let Y=X.join(" AND "),W=[];if($===0){let B=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`,D=this.db.prepare(B).all(...J);for(let z of D){let A=this.rowToTask(z);this.tasksCache.set(A.id,A),W.push(A)}}else{let D=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IS NULL AND ${Y} ORDER BY updated_at DESC`).all(...J).map((z)=>{let A=this.rowToTask(z);return this.tasksCache.set(A.id,A),A});W.push(...D);for(let z=1;z<=$;z++){if(D.length===0)break;let A=D.map((S)=>S.id),V=`SELECT * FROM task WHERE parent_task_id IN (${A.map(()=>"?").join(",")}) AND ${Y} ORDER BY updated_at DESC`,f=this.db.prepare(V).all(...A,...J).map((S)=>{let K=this.rowToTask(S);return this.tasksCache.set(K.id,K),K});W.push(...f),D=f}}let q=W.length,G=w.offset??0,Q=w.limit??q;return{tasks:W.slice(G,G+Q),total:q}}async getTaskTree(w,$=-1){await this.initialize();let X=[],J=[w],Y=0;while(J.length>0){if($!==-1&&Y>=$)break;let W=J.map(()=>"?").join(","),q=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${W}) ORDER BY updated_at DESC`).all(...J),G=[];for(let Q of q){let H=this.rowToTask(Q);this.tasksCache.set(H.id,H),X.push(H),G.push(H.id)}J=G,Y++}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,J=w.milestoneDescription??w.actionDescription;if(!$||!X)throw Error("createOperation requires milestoneType and milestoneTitle (or legacy actionType/actionTitle)");let Y=Date.now(),q=this.db.prepare(`
|
|
350
|
-
INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
|
|
351
|
-
milestone_description, process_description, timestamp, md_path)
|
|
352
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
353
|
-
`).run(w.taskId,w.sessionId,$,X,J||"",w.processDescription||"",Y,w.mdPath||null);this.operationsCache.delete(w.taskId);let G=await this.getOperation(q.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 J=$.milestoneTitle??$.actionTitle,Y=$.milestoneDescription??$.actionDescription,W=[],q=[];if(J!==void 0)W.push("milestone_title = ?"),q.push(J);if(Y!==void 0)W.push("milestone_description = ?"),q.push(Y);if($.processDescription!==void 0)W.push("process_description = ?"),q.push($.processDescription);if(W.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${W.join(", ")} WHERE id = ?`).run(...q,w),this.operationsCache.delete(X.taskId),this.getOperation(w)}async deleteOperation(w){await this.initialize();let $=await this.getOperation(w);if(!$)return!1;let J=this.db.prepare("DELETE FROM task_operation WHERE id = ?").run(w);if(J.changes>0)this.operationsCache.delete($.taskId);return J.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((Q)=>this.rowToOperation(Q)))}let X=this.operationsCache.get($),J=w.milestoneType??w.actionType;if(J)X=X.filter((q)=>q.milestoneType===J);let Y=w.offset||0,W=w.limit||20;return X.slice(Y,Y+W)}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,J=w.milestone_description??w.action_description??"";return{id:w.id,taskId:w.task_id,sessionId:w.session_id,milestoneType:$,milestoneTitle:X,milestoneDescription:J,processDescription:w.process_description??"",timestamp:new Date(w.timestamp).toISOString(),mdPath:w.md_path||void 0,actionType:$,actionTitle:X,actionDescription:J}}async createTag(w){await this.initialize();let $=Date.now(),X=await this.getTagByName(w);if(X)return X;return{id:this.db.prepare(`
|
|
354
|
-
INSERT INTO task_tag (name, created_at, task_count)
|
|
355
|
-
VALUES (?, ?, 0)
|
|
356
|
-
`).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=[],J=w?.orderBy||"count";if(J==="count")$+=" ORDER BY task_count DESC";else if(J==="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((q)=>this.rowToTag(q))}async searchTags(w){await this.initialize();let $=`
|
|
357
|
-
SELECT * FROM task_tag
|
|
358
|
-
WHERE name LIKE ?
|
|
359
|
-
ORDER BY task_count DESC
|
|
360
|
-
LIMIT ?
|
|
361
|
-
`;return this.db.prepare($).all(`%${w.query}%`,w.limit||20).map((Y)=>this.rowToTag(Y))}async deleteTag(w){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(w).changes>0}async addTagsToTask(w,$){await this.initialize();let X=Date.now(),J=this.db.prepare(`
|
|
362
|
-
INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
|
|
363
|
-
VALUES (?, ?, ?)
|
|
364
|
-
`);for(let Y of $)J.run(w,Y,X),this.db.run(`
|
|
365
|
-
UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
|
|
366
|
-
`,Y);await this.syncTaskTagsJson(w)}async removeTagsFromTask(w,$){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let J of $)X.run(w,J),this.db.run(`
|
|
367
|
-
UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
|
|
368
|
-
`,J);await this.syncTaskTagsJson(w)}async getTagsForTask(w){await this.initialize();let $=`
|
|
369
|
-
SELECT t.* FROM task_tag t
|
|
370
|
-
INNER JOIN task_tag_relation r ON t.id = r.tag_id
|
|
371
|
-
WHERE r.task_id = ?
|
|
372
|
-
ORDER BY t.name ASC
|
|
373
|
-
`;return this.db.prepare($).all(w).map((Y)=>this.rowToTag(Y))}async getTaskIdsByTags(w){if(await this.initialize(),w.length===0)return[];let X=`
|
|
374
|
-
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
375
|
-
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
376
|
-
WHERE t.name IN (${w.map(()=>"?").join(", ")})
|
|
377
|
-
`;return this.db.prepare(X).all(...w).map((W)=>W.task_id)}async updateTaskTags(w,$){await this.initialize();let X=await this.getTagsForTask(w);if(X.length>0)await this.removeTagsFromTask(w,X.map((Y)=>Y.id));let J=[];for(let Y of $){let W=await this.getTagByName(Y);if(!W)W=await this.createTag(Y);J.push(W.id)}if(J.length>0)await this.addTagsToTask(w,J)}async searchTasksByKeywords(w,$={}){if(await this.initialize(),!w||w.length===0)return{tasks:[],total:0};let{limit:X=20,offset:J=0,excludeTaskId:Y,status:W,priority:q,type:G,depth:Q}=$,H=null;if(Q!==void 0&&Q>=0)H=await this.collectTaskIdsByDepth(Q);let B=new Map,D="SELECT * FROM task WHERE 1=1",z=[];if(Y)D+=" AND id != ?",z.push(Y);if(W)D+=" AND status = ?",z.push(W);if(q)D+=" AND priority = ?",z.push(q);if(G)D+=" AND type = ?",z.push(G);if(!$?.include_archived&&$?.status!=="archived")D+=" AND status != 'archived'";let A=Math.max(X*5,200);D+=" ORDER BY updated_at DESC LIMIT ?",z.push(A);let U=this.db.prepare(D).all(...z);for(let j of U){let N=this.rowToTask(j),g=new Set,E=0;if(typeof N.title==="string"&&N.title){let C=N.title.toLowerCase();for(let x of w)if(C.includes(x.toLowerCase()))E++,g.add(x)}if(N.tags&&Array.isArray(N.tags))for(let C of w){let x=C.toLowerCase();if(N.tags.some((i)=>i.toLowerCase().includes(x)))E+=2,g.add(C)}if(typeof N.description==="string"&&N.description){let C=N.description.toLowerCase();for(let x of w)if(C.includes(x.toLowerCase()))E++,g.add(x)}if(typeof N.goals_and_expected_deliverables==="string"&&N.goals_and_expected_deliverables){let C=N.goals_and_expected_deliverables.toLowerCase();for(let x of w)if(C.includes(x.toLowerCase()))E++,g.add(x)}if(g.size===w.length)B.set(N.id,{task:N,matchCount:E})}let V=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let j of V){let g=new Set;for(let i of w){let y=`%${i}%`;if(this.db.prepare(`
|
|
378
|
-
SELECT * FROM task_operation
|
|
379
|
-
WHERE task_id = ?
|
|
380
|
-
AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
|
|
381
|
-
LIMIT 10
|
|
382
|
-
`).all(j.task_id,y,y,y).length>0)g.add(i)}if(g.size===0)continue;let E=this.db.prepare("SELECT * FROM task WHERE id = ?").get(j.task_id);if(!E)continue;let C=this.rowToTask(E);if(Y&&C.id===Y)continue;if(W&&C.status!==W)continue;if(q&&C.priority!==q)continue;if(G&&C.type!==G)continue;if(!$?.include_archived&&C.status==="archived")continue;let x=B.get(C.id);if(x)x.matchCount+=2;else{let i=new Set(g);if(typeof C.title==="string"&&C.title){let y=C.title.toLowerCase();for(let c of w)if(y.includes(c.toLowerCase()))i.add(c)}if(typeof C.description==="string"&&C.description){let y=C.description.toLowerCase();for(let c of w)if(y.includes(c.toLowerCase()))i.add(c)}if(typeof C.goals_and_expected_deliverables==="string"&&C.goals_and_expected_deliverables){let y=C.goals_and_expected_deliverables.toLowerCase();for(let c of w)if(y.includes(c.toLowerCase()))i.add(c)}if(C.tags&&Array.isArray(C.tags)){for(let y of w)if(C.tags.some((c)=>c.toLowerCase().includes(y.toLowerCase())))i.add(y)}if(i.size===w.length)B.set(C.id,{task:C,matchCount:2})}}let R=Array.from(B.values()).sort((j,N)=>N.matchCount-j.matchCount);if(H!==null)R=R.filter((j)=>H.has(j.task.id));let f=R.length;return{tasks:R.slice(J,J+X).map((j)=>j.task),total:f}}async collectTaskIdsByDepth(w){let $=new Set,J=this.db.prepare("SELECT id FROM task WHERE parent_task_id IS NULL").all().map((Y)=>Y.id);for(let Y of J)$.add(Y);if(w===0)return $;for(let Y=1;Y<=w;Y++){if(J.length===0)break;let W=J.map(()=>"?").join(",");J=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${W})`).all(...J).map((G)=>G.id);for(let G of J)$.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 J=X.map((Q)=>Q.id),W=`
|
|
383
|
-
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
384
|
-
FROM task t
|
|
385
|
-
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
386
|
-
INNER JOIN task_tag_relation r2 ON t.id = r2.task_id
|
|
387
|
-
WHERE r.tag_id IN (${J.map(()=>"?").join(", ")})
|
|
388
|
-
AND t.id != ?
|
|
389
|
-
GROUP BY t.id
|
|
390
|
-
ORDER BY match_count DESC, t.updated_at DESC
|
|
391
|
-
LIMIT ?
|
|
392
|
-
`;return this.db.prepare(W).all(...J,w,$).map((Q)=>this.rowToTask(Q))}async searchTasks(w,$=20){await this.initialize();let X=`
|
|
393
|
-
SELECT * FROM task
|
|
394
|
-
WHERE title LIKE ? OR description LIKE ?
|
|
395
|
-
ORDER BY updated_at DESC
|
|
396
|
-
LIMIT ?
|
|
397
|
-
`;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((W)=>this.rowToTask(W))}async findTasksByContextValue(w,$=50){if(await this.initialize(),!w)return[];let X=`
|
|
398
|
-
SELECT * FROM task
|
|
399
|
-
WHERE context LIKE ?
|
|
400
|
-
ORDER BY updated_at DESC
|
|
401
|
-
LIMIT ?
|
|
402
|
-
`;return this.db.prepare(X).all(`%${w}%`,$).map((Y)=>this.rowToTask(Y))}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((Y)=>Y.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})],Dw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Dw.prototype,"searchTasksByKeywords",null)});Bw();Bw();import{AsyncLocalStorage as j7}from"async_hooks";var y2=()=>{};function uw(){return B0.getStore()}function Q1(){return B0.getStore()||{}}function U0(){return B0.getStore()?.agentContext?.currentTaskId}function V4(_){return typeof _==="number"&&Number.isInteger(_)&&_>0?_:void 0}var A4,B0,E7,z0,a_=r(()=>{a(),z_(),y2(),A4=n("env:context:env-context"),B0=new j7,E7=T_(function(w,$){return V4(w?.metadata?.parentTaskId)??V4($?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:(_)=>({parentTaskId:_??null})}),z0=T_(function(w){let $=U0(),X=B0.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=w}A4.info(`[setCurrentTaskId] taskId=${w??"undefined"} (was: ${$??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});import{execSync as S7}from"child_process";var M4=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().describe("Project root path for task positioning. Used to locate the project space for this task. Use 'unknown' if 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
|
|
403
|
-
`+`\u5982\u9700\u5C06\u4EFB\u52A1\u6302\u8F7D\u5230\u67D0\u4E2A\u7236\u4EFB\u52A1\u4E0B\uFF0C\u4F20\u5165\u5BF9\u5E94\u7236\u4EFB\u52A1 ID\u3002
|
|
404
|
-
`+`**\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
|
|
405
|
-
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
406
|
-
`+` A. \u5F52\u5C5E\u5230\u73B0\u6709 longterm \u6839\uFF08\u5982\u300C[Longterm] X \u751F\u6001\u300D\uFF09\u2192 parent_task_id = \u8BE5\u6839 ID
|
|
407
|
-
`+` 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
|
|
408
|
-
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
409
|
-
`+`\u5982\u4F55\u627E\u5230 parent_task_id\uFF1A\u4F7F\u7528 task_tree(depth=2) \u83B7\u53D6\u7684\u6811\u5F62\u7ED3\u6784\uFF0C
|
|
410
|
-
`+"\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().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!`)}),R4=M.object({task_id:M.number().describe("Task ID"),include_operations:M.boolean().optional().default(!1).describe("Include operation records")}),O4=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")}),F4=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")}),f4=M.object({task_id:M.number().describe("Task ID"),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)")}),L4=M.object({task_id:M.number().describe("Task ID")}),K4=M.object({task_id:M.number().describe("Task ID"),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")}),N4=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")}),b4=M.object({task_ids:M.array(M.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),j4=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")});a_();a();a();var P7=n("task-child-context"),Z7=["commit","token","secret","password","api_key"];function v2(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map(v2);if(typeof _!=="object")return _;let w={};for(let[$,X]of Object.entries(_)){let J=$.toLowerCase();if(Z7.some((Y)=>J.includes(Y)))continue;w[$]=v2(X)}return w}function C7(_){let{parent:w,overrides:$={}}=_,X=$.contextInherit!==!1,J=$.inheritTags===!0,Y=$.projectPath??w.projectPath??"unknown",W={};if(w.contextJson&&w.contextJson.trim().length>0)try{let H=JSON.parse(w.contextJson);if(H&&typeof H==="object"&&!Array.isArray(H))W=H}catch(H){P7.debug(`[task-child-context] parent #${w.taskId} context is malformed JSON; continuing with empty inherited context (${H instanceof Error?H.message:String(H)})`),W={}}let q={};if(X){if(W.worktree_path!==void 0&&$.worktreePath===void 0)q.worktree_path=W.worktree_path;if(W.branch!==void 0&&$.branch===void 0)q.branch=W.branch;if(W.parent_branch!==void 0)q.parent_branch=W.parent_branch;if(W.type!==void 0)q.type=W.type;if(W.prior_context&&typeof W.prior_context==="object"){let B=W.prior_context,D={};for(let[z,A]of Object.entries(B)){if(z.toLowerCase()==="commit")continue;D[z]=A}if(Object.keys(D).length>0)q.prior_context=D}let H=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[B,D]of Object.entries(W)){if(H.has(B))continue;q[B]=D}}if($.worktreePath!==void 0)q.worktree_path=$.worktreePath;if($.branch!==void 0)q.branch=$.branch;let G=$.createdAt??new Date().toISOString();q.created_at=G,q.child_of=w.taskId;let Q=v2(q);return{project_path:Y,context:JSON.stringify(Q),inheritedTags:J?w.tags??[]:[]}}var E4=n("task:tools:create");function T7(){try{let _=S7("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 V0(_){return{name:"task_create",description:`
|
|
411
|
-
Create a new task for tracking work.
|
|
412
|
-
|
|
413
|
-
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
414
|
-
|
|
415
|
-
Before calling \`task_create\`, you **MUST** first call
|
|
416
|
-
\`task_tree(depth=1)\` to inspect the existing task hierarchy.
|
|
417
|
-
This is critical because:
|
|
418
|
-
|
|
419
|
-
1. Avoid duplicating root tasks (root tasks should stay \u2264 10).
|
|
420
|
-
2. Find the right \`parent_task_id\` to attach under.
|
|
421
|
-
3. Avoid creating stranded/orphan tasks.
|
|
422
|
-
|
|
423
|
-
Workflow:
|
|
424
|
-
step 1: task_tree({depth: 1})
|
|
425
|
-
step 2: read the tree, then decide per "Decision Tree" below
|
|
426
|
-
step 3: task_create({...})
|
|
427
|
-
|
|
428
|
-
## Decision Tree \u2014 How to choose parent_task_id
|
|
429
|
-
|
|
430
|
-
Walk these paths in order:
|
|
431
|
-
|
|
432
|
-
**Path A \u2014 Attach under a longterm root.**
|
|
433
|
-
The task belongs to a theme whose longterm root already exists
|
|
434
|
-
(e.g. "[Longterm] X ecosystem"). Set \`parent_task_id\` to that
|
|
435
|
-
root's id. This is the **preferred** path for incremental work
|
|
436
|
-
inside an established theme.
|
|
437
|
-
|
|
438
|
-
**Path B \u2014 Attach under an existing topic cluster.**
|
|
439
|
-
A non-longterm root already aggregates similar tasks and yours
|
|
440
|
-
belongs in the same cluster. Set \`parent_task_id\` to that root.
|
|
441
|
-
|
|
442
|
-
**Path C \u2014 Create a new root.**
|
|
443
|
-
Neither A nor B fits (cross-cutting work, or root count already
|
|
444
|
-
\u2265 ~10). **Omit** \`parent_task_id\` (or pass \`null\`) and the
|
|
445
|
-
task becomes a new root.
|
|
446
|
-
|
|
447
|
-
## Tree Hygiene Principles
|
|
448
|
-
|
|
449
|
-
Apply these when deciding parent_task_id:
|
|
450
|
-
|
|
451
|
-
- Root tasks \u2264 10 (keep tree width manageable)
|
|
452
|
-
- Depth \u2264 5 (avoid deep nesting)
|
|
453
|
-
- Same-theme tasks cluster under one parent
|
|
454
|
-
- Long-tail/stranded tasks should be archived or merged
|
|
455
|
-
|
|
456
|
-
## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
|
|
457
|
-
|
|
458
|
-
A task MUST carry spatio-temporal context so it survives task-handoff
|
|
459
|
-
across Agent sessions, worktrees and time. Two orthogonal axes:
|
|
460
|
-
|
|
461
|
-
- **Space (project_path + worktree_path)**:
|
|
462
|
-
- \`project_path\` (required): git repo root path (always the top-level repo)
|
|
463
|
-
- \`worktree_path\` (in context): current worktree path if in a worktree
|
|
464
|
-
- **Auto-detected by createTask** via \`git rev-parse --show-toplevel\`
|
|
465
|
-
\u2014 you don't need to fill it manually (see "worktree_path detection
|
|
466
|
-
logic" in the implementation).
|
|
467
|
-
- You may **override** by passing it in \`context.worktree_path\`.
|
|
468
|
-
|
|
469
|
-
- **Time (context field)**:
|
|
470
|
-
- \`created_at\` (in context): ISO 8601 timestamp **auto-injected**
|
|
471
|
-
at creation time. Manual override is preserved if provided.
|
|
472
|
-
- \`time_dimension\` (in context, optional): the task's "time anchor"
|
|
473
|
-
\u2014 e.g. a release tag, sprint window or iteration id.
|
|
474
|
-
- \`work_period\` (in context, optional): planned start/end dates
|
|
475
|
-
if known.
|
|
476
|
-
- \`prior_context\` (in context, optional): the previous task id
|
|
477
|
-
/ commit hash this work continues from. Helps the next Agent
|
|
478
|
-
pick up the trail via \`task_get\`.
|
|
479
|
-
|
|
480
|
-
Example context for code development task:
|
|
481
|
-
|
|
482
|
-
\`\`\`json
|
|
483
|
-
{"project_path": "<git-repo-root>",
|
|
484
|
-
"worktree_path": "<git-repo-root>/.worktrees/<branch-name>",
|
|
485
|
-
"branch": "feat/<branch-name>",
|
|
486
|
-
"type": "feature",
|
|
487
|
-
"parent_branch": "main",
|
|
488
|
-
"created_at": "<ISO-8601-timestamp>",
|
|
489
|
-
"prior_context": {"prev_task": "<task-id>", "commit": "<commit-hash>"}}
|
|
490
|
-
\`\`\`
|
|
491
|
-
|
|
492
|
-
## IMPORTANT: Task Continuity Fields
|
|
493
|
-
|
|
494
|
-
This tool creates persistent task records that can be picked up by a
|
|
495
|
-
Task Manager Agent to continue advancing unfinished work.
|
|
496
|
-
|
|
497
|
-
The following fields are critical for task context preservation:
|
|
498
|
-
|
|
499
|
-
- project_path: The project root path where this task belongs.
|
|
500
|
-
Used to locate the project space for this task.
|
|
501
|
-
If unknown, use 'unknown'.
|
|
502
|
-
|
|
503
|
-
- context: A JSON string containing time-space positioning information.
|
|
504
|
-
This field is crucial for Agent task handoff.
|
|
505
|
-
|
|
506
|
-
**Required format**: Valid JSON string (parseable).
|
|
507
|
-
|
|
508
|
-
**Core fields**:
|
|
509
|
-
- worktree_path: Git worktree path (for code development). Auto-detected.
|
|
510
|
-
- branch: Current branch name
|
|
511
|
-
- type: Work type classification (feature/bug/refactor/chore).
|
|
512
|
-
\u26A0\uFE0F NOTE: This is the **context.type** (work classification), NOT the
|
|
513
|
-
task's type field (normal/cycle/longterm). They are independent concepts.
|
|
514
|
-
- created_at: ISO 8601 timestamp. Auto-injected if missing.
|
|
515
|
-
|
|
516
|
-
**Example for coding tasks**:
|
|
517
|
-
{"worktree_path": "<worktree-path>", "branch": "<branch-name>", "type": "feature", "parent_branch": "main"}
|
|
518
|
-
|
|
519
|
-
**Example for other tasks**:
|
|
520
|
-
{"type": "general"}
|
|
521
|
-
|
|
522
|
-
If unable to fill in details, use at minimum:
|
|
523
|
-
{"type": "unknown"}
|
|
524
|
-
|
|
525
|
-
**DO NOT leave this as plain text** - it must be valid JSON!
|
|
526
|
-
|
|
527
|
-
**Note**: malformed JSON (non-parseable) will be preserved as-is
|
|
528
|
-
rather than rejected, to preserve backward compatibility. The
|
|
529
|
-
auto-injection of \`created_at\` / \`worktree_path\` is best-effort.
|
|
530
|
-
|
|
531
|
-
## Task Binding Inheritance (Task #4023)
|
|
532
|
-
|
|
533
|
-
When this tool is called from inside a per-task group chat, the
|
|
534
|
-
event-source handler resolves the chat\u2194task binding and injects the
|
|
535
|
-
bound task id into \`EnvContext.parentTaskId\`. This tool reads that
|
|
536
|
-
value and uses it as the default \`parent_task_id\`, so the LLM
|
|
537
|
-
doesn't need to know the task tree to attach subtasks to the
|
|
538
|
-
correct parent.
|
|
539
|
-
|
|
540
|
-
Priority order (highest \u2192 lowest):
|
|
541
|
-
1. Caller's explicit \`parent_task_id\` (always wins)
|
|
542
|
-
2. \`EnvContext.parentTaskId\` injected from chat binding
|
|
543
|
-
3. No parent (creates a root task, as before)
|
|
544
|
-
|
|
545
|
-
When the env-injected parent doesn't exist in the DB, the tool
|
|
546
|
-
fails fast (does not silently create an orphan). When the
|
|
547
|
-
env-injected value is 0 / negative / non-integer, it's treated as
|
|
548
|
-
missing \u2014 only positive integers are honored.
|
|
549
|
-
|
|
550
|
-
`,parameters:M4,execute:async(w,$)=>{let X=M4.parse(w),J=$.session_id||"unknown",Y=T7(),W=X.context,q=Q1().parentTaskId,G=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:q!==void 0&&q!==null&&Number.isInteger(q)&&q>0?q:void 0,Q=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,H=X.tags,B;if(G!==void 0)try{let D=await _.getTask(G);if(D){let z=C7({parent:{taskId:D.id,projectPath:D.project_path,contextJson:D.context??"",tags:D.tags},overrides:{projectPath:Q,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(Q===void 0)Q=z.project_path;if(X.tags===void 0)H=z.inheritedTags;B=z.context}}catch(D){E4.debug(`[task_create] failed to pre-load parent #${G} for context inheritance: ${D instanceof Error?D.message:String(D)}`)}try{let D=X.context?JSON.parse(X.context):{},z=typeof D==="object"&&D!==null&&!Array.isArray(D)?D:{};if(B)try{let A=JSON.parse(B);if(A&&typeof A==="object"&&!Array.isArray(A)){for(let[U,V]of Object.entries(A))if(z[U]===void 0)z[U]=V}}catch{}if(!z.created_at)z.created_at=new Date().toISOString();if(!z.worktree_path&&Y)z.worktree_path=Y;W=JSON.stringify(z)}catch{W=X.context}try{let D=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:H,sessionId:J,project_path:Q??X.project_path,context:W});return z0(D.id),E4.info(`[createTask] Trace: Task #${D.id} created, currentTaskId=${D.id} set in EnvContext`),{success:!0,output:`Task created successfully: #${D.id} - ${D.title}`,metadata:{execution_time_ms:0,task_id:D.id,status:D.status,createdAt:D.createdAt}}}catch(D){return{success:!1,output:"",error:D instanceof Error?D.message:String(D),metadata:{execution_time_ms:0}}}}}}function A0(_){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:R4,execute:async(w,$)=>{let X=R4.parse(w);try{if(X.include_operations){let J=await _.getTaskWithOperations(X.task_id);if(!J)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(J,null,2),metadata:{execution_time_ms:0}}}else{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}};return{success:!0,output:JSON.stringify(J,null,2),metadata:{execution_time_ms:0}}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function M0(_){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
|
|
551
|
-
`+"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:O4,execute:async(w,$)=>{let X=O4.parse(w);try{let J=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:J.total,count:J.tasks.length,truncated:J.total>J.tasks.length,limit:X.limit,offset:X.offset,depth:X.depth,tasks:J.tasks}),metadata:{execution_time_ms:0}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function R0(_){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.
|
|
552
|
-
|
|
553
|
-
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
554
|
-
|
|
555
|
-
If \`keywords\` is empty, returns no results.`,parameters:F4,execute:async(w,$)=>{let X=F4.parse(w);try{let J=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:J.tasks,total:J.total,limit:X.limit,offset:X.offset}),metadata:{execution_time_ms:0}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function x2(_){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.
|
|
556
|
-
|
|
557
|
-
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
558
|
-
|
|
559
|
-
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:N4,execute:async(w,$)=>{let X=N4.parse(w),J=X.task_ids,Y=$.session_id||"batch-archive";if(!J||J.length===0)return{success:!0,output:JSON.stringify({archived_count:0,errors:[]}),metadata:{execution_time_ms:0}};let W=[],q=0;for(let Q of J)try{if(await _.updateTask(Q,{status:"archived"}))await _.createOperation({taskId:Q,sessionId:Y,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),q++,W.push({id:Q,success:!0});else W.push({id:Q,success:!1,error:"Task not found"})}catch(H){W.push({id:Q,success:!1,error:H instanceof Error?H.message:String(H)})}return{success:!W.some((Q)=>!Q.success),output:JSON.stringify({archived_count:q,total:J.length,errors:W.filter((Q)=>!Q.success).map((Q)=>({id:Q.id,error:Q.error})),results:W},null,2),metadata:{execution_time_ms:0}}}}}function m2(_){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
560
|
-
|
|
561
|
-
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
562
|
-
|
|
563
|
-
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:b4,execute:async(w,$)=>{let J=b4.parse(w).task_ids;if(!J||J.length===0)return{success:!0,output:JSON.stringify({deleted_count:0,errors:[]}),metadata:{execution_time_ms:0}};let Y=[],W=0;for(let G of J)try{if(await _.deleteTask(G))W++,Y.push({id:G,success:!0});else Y.push({id:G,success:!1,error:"Task not found"})}catch(Q){Y.push({id:G,success:!1,error:Q instanceof Error?Q.message:String(Q)})}return{success:!Y.some((G)=>!G.success),output:JSON.stringify({deleted_count:W,total:J.length,errors:Y.filter((G)=>!G.success).map((G)=>({id:G.id,error:G.error})),results:Y},null,2),metadata:{execution_time_ms:0}}}}}a_();a();var I7=n("tool:update-task");async function g7(_,w,$){let X=new Set,J=$;while(J!==null&&J!==void 0){if(J===w)return!0;if(X.has(J))break;X.add(J);let Y=await _.getTask(J);if(!Y)break;J=Y.parent_task_id}return!1}function O0(_){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:f4,execute:async(w,$)=>{let X=f4.parse(w),J=$.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await g7(_,X.task_id,X.parent_task_id))return{success:!1,output:"",error:`Circular reference detected: setting parent_task_id to ${X.parent_task_id} for task #${X.task_id} would create a cycle`,metadata:{execution_time_ms:0}}}let Y=await _.updateTask(X.task_id,{title:X.title,description:X.description,status:X.status,priority:X.priority,type:X.type,progress:X.progress,current_status:X.current_status,goals_and_expected_deliverables:X.goals_and_expected_deliverables,due_date:X.due_date,tags:X.tags,project_path:X.project_path,context:X.context,parent_task_id:X.parent_task_id});if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(X.status||X.progress!==void 0||X.current_status)await _.createOperation({taskId:X.task_id,sessionId:J,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 z0(Y.id),I7.info(`[updateTask] Trace: Task #${Y.id} updated, currentTaskId=${Y.id} set in EnvContext`),{success:!0,output:`Task updated: #${Y.id} - ${Y.title}`,metadata:{execution_time_ms:0,task:Y}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function u2(_){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:L4,execute:async(w,$)=>{let X=L4.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(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}a_();a();var k7=n("task:tools:complete"),h7=`
|
|
564
|
-
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
565
|
-
|
|
566
|
-
**Before calling this tool**, you MUST:
|
|
567
|
-
|
|
568
|
-
1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
|
|
569
|
-
- Use \`task_get(task_id=<id>)\` to fetch the full task record.
|
|
570
|
-
2. **Validate** whether the goal and delivery match what you actually delivered.
|
|
571
|
-
- If mismatch, either: (a) extend the task via \`task_update\`, or (b) honestly note the discrepancy in your final report.
|
|
572
|
-
3. **Provide \`deliverable_storage_path\`** parameter with the deliverable's address:
|
|
573
|
-
- Feishu doc URL (e.g., https://my.feishu.cn/docx/abc)
|
|
574
|
-
- Local file path (e.g., /tmp/report.md)
|
|
575
|
-
- Git branch or worktree path (e.g., feature/my-feature)
|
|
576
|
-
- GitHub commit URL or PR URL
|
|
577
|
-
- Cloud drive URL (e.g., https://my.feishu.cn/file/abc)
|
|
578
|
-
- Or any other locator that points to where the work product lives
|
|
579
|
-
|
|
580
|
-
The \`deliverable_storage_path\` will be persisted to the task's \`context.deliverable_storage_path\` for future reference and traceability.
|
|
581
|
-
|
|
582
|
-
**Restrictions**:
|
|
583
|
-
- Cannot complete cycle-type tasks (they are periodic). Use \`task_update\` to reset progress instead.
|
|
584
|
-
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
585
|
-
|
|
586
|
-
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
587
|
-
`.trim();function F0(_){return{name:"task_complete",description:h7,parameters:K4,execute:async(w,$)=>{let X=K4.parse(w),J=$.session_id||"unknown";try{let Y=await _.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};if(Y.type==="cycle")return{success:!1,output:"",error:`Cannot complete a cycle-type task (id: ${X.task_id}). Cycle tasks are periodic (e.g., weekly reports) and should not be marked as completed. Use task_update to reset progress instead.`,metadata:{execution_time_ms:0}};let W=await _.completeTask(X.task_id,J,X.deliverable_storage_path);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return z0(void 0),k7.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${W.id} - ${W.title}
|
|
588
|
-
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${W.id} - ${W.title}
|
|
589
|
-
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:W}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function S4(_,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 P4(_,w){if(w<0)return _;if(w===0)return _.map(($)=>({...$,children:[]}));return _.map(($)=>({...$,children:P4($.children,w-1)}))}function Z4(_){let w=0;for(let $ of _)w+=1+Z4($.children);return w}function y7(_){let w=new Map,$=new Map,X=[];for(let J of _)w.set(J.id,{id:J.id,title:J.title,status:J.status,type:J.type,priority:J.priority,progress:J.progress,children:[]});for(let J of _){let Y=J.parent_task_id;if(Y!==void 0&&Y!==null&&w.has(Y)){let W=$.get(Y)||[];W.push(J),$.set(Y,W)}else X.push(J)}for(let[J,Y]of $.entries()){let W=w.get(J);Y.sort(S4),W.children=Y.map((q)=>w.get(q.id))}return X.sort(S4),X.map((J)=>w.get(J.id))}function f0(_){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:
|
|
590
|
-
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
591
|
-
- truncated: always false for now (no pagination cap on tree)
|
|
592
|
-
- depth: the resolved depth value
|
|
593
|
-
- parent_task_id: the root's id, or null for forest mode
|
|
594
|
-
- nodes: TaskNode[] with { id, title, status, type, priority, progress, children }
|
|
595
|
-
Note: \`total\` is the FIRST field in the response so it survives tail-truncation by ToolComponent.truncateOutput.`,parameters:j4,execute:async(w,$)=>{let X=j4.parse(w);try{let J=[],Y=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)J=[];else{let Q=await _.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));J=[G,...Q]}}else J=(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)J=J.filter((G)=>G.status===X.status);if(X.priority)J=J.filter((G)=>G.priority===X.priority);if(X.type)J=J.filter((G)=>G.type===X.type);if(!X.include_archived)J=J.filter((G)=>G.status!=="archived")}let W=y7(J);if(X.parent_task_id===void 0||X.parent_task_id===null)W=P4(W,X.depth);let q=Z4(W);return{success:!0,output:JSON.stringify({total:q,truncated:!1,depth:X.depth,parent_task_id:Y,nodes:W}),metadata:{execution_time_ms:0}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}var H1=M.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),l2=100,c2=150,D1=5000,v7=1,B1=200,h4=M.string().min(l2,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${l2} \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(c2,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${c2} \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 ${l2}-${c2} \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"),y4=M.string().min(v7,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(B1,{message:`milestone_title \u8D85\u8FC7 ${B1} \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"),v4=M.string().max(D1,{message:`milestone_description \u8D85\u8FC7 ${D1} \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"),x7=M.object({task_id:M.number().describe("Task ID"),milestone_type:H1.optional(),milestone_title:y4.optional(),milestone_description:v4,process_description:h4.optional(),action_type:H1.optional(),action_title:M.string().min(1).max(B1).optional(),action_description:M.string().max(D1).optional(),md_path:M.string().optional().describe("Path to detailed markdown documentation")}),C4=x7.transform((_)=>{let w=[],$=_.milestone_type,X=_.milestone_title,J=_.milestone_description;if(!$&&_.action_type)$=_.action_type,w.push("action_type");if(!X&&_.action_title)X=_.action_title,w.push("action_title");if(J===void 0&&_.action_description!==void 0)J=_.action_description,w.push("action_description");return{task_id:_.task_id,milestone_type:$,milestone_title:X,milestone_description:J,process_description:_.process_description,md_path:_.md_path,_deprecated_fields_used:w}}),T4=M.object({operation_id:M.number().describe("Operation ID")}),I4=M.object({task_id:M.number().describe("Task ID"),milestone_type:H1.optional(),action_type:H1.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}}),m7=M.object({operation_id:M.number().describe("Operation ID"),milestone_title:y4.optional(),milestone_description:v4,process_description:h4.optional(),action_title:M.string().min(1).max(B1).optional(),action_description:M.string().max(D1).optional()}),g4=m7.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}}),k4=M.object({operation_id:M.number().describe("Operation ID")});function u7(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function l7(_){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 L0(_){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-150 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:C4,execute:async(w,$)=>{let X;try{X=C4.parse(w)}catch(W){if(W instanceof Y_)return{success:!1,output:"",error:u7(W),metadata:{execution_time_ms:0}};throw W}let J=l7(X);if(!J.ok)return{success:!1,output:"",error:J.error,metadata:{execution_time_ms:0}};let Y=$.session_id||"unknown";try{let W=await _.createOperation({taskId:X.task_id,sessionId:Y,milestoneType:J.milestoneType,milestoneTitle:J.milestoneTitle,milestoneDescription:X.milestone_description,processDescription:X.process_description,mdPath:X.md_path}),q=`Operation created: #${W.id} for task #${W.taskId} [milestone=${W.milestoneType}] ${W.milestoneTitle}`,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)q+=`
|
|
596
|
-
|
|
597
|
-
`+G.join(`
|
|
598
|
-
`);return{success:!0,output:q,metadata:{execution_time_ms:0,operation_id:W.id,task_id:W.taskId,session_id:W.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function d2(_){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:T4,execute:async(w,$)=>{let X=T4.parse(w);try{let J=await _.getOperation(X.operation_id);if(!J)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(J,null,2),metadata:{execution_time_ms:0}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function K0(_){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:I4,execute:async(w,$)=>{let X=I4.parse(w);try{let J=await _.listOperations({taskId:X.task_id,milestoneType:X.milestone_type,limit:X.limit,offset:X.offset}),Y=JSON.stringify({operations:J,count:J.length});if(X._deprecated_fields_used.length>0)Y=`\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_type \u5B57\u6BB5\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_type\u3002
|
|
599
|
-
|
|
600
|
-
`+Y;return{success:!0,output:Y,metadata:{execution_time_ms:0,deprecated_fields_used:X._deprecated_fields_used}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function c7(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function p2(_){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-150 chars).",parameters:g4,execute:async(w,$)=>{let X;try{X=g4.parse(w)}catch(J){if(J instanceof Y_)return{success:!1,output:"",error:c7(J),metadata:{execution_time_ms:0}};throw J}try{let J=await _.updateOperation(X.operation_id,{milestoneTitle:X.milestone_title,milestoneDescription:X.milestone_description,processDescription:X.process_description});if(!J)return{success:!1,output:"",error:`Operation not found: ${X.operation_id}`,metadata:{execution_time_ms:0}};let Y=`Operation updated: #${J.id}`;if(X._deprecated_fields_used.length>0)Y+=`
|
|
601
|
-
|
|
602
|
-
\u26A0\uFE0F DEPRECATION NOTICE: \u4F60\u4F7F\u7528\u4E86\u65E7\u7684 action_* \u5B57\u6BB5 (${X._deprecated_fields_used.join(", ")})\uFF0C\u5DF2\u81EA\u52A8\u6620\u5C04\u5230 milestone_* \u5B57\u6BB5\u3002`+"\u8BF7\u5C3D\u5FEB\u8FC1\u79FB\u5230 milestone_* \u5B57\u6BB5\u3002";return{success:!0,output:Y,metadata:{execution_time_ms:0,operation:J,deprecated_fields_used:X._deprecated_fields_used}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function i2(_){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:k4,execute:async(w,$)=>{let X=k4.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(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}var Uw={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};import{AsyncLocalStorage as d7}from"async_hooks";a();var U1=n("process-tree-killer");function u4(){return __("child_process")}var x4;function p7(_,w,$){if(x4)return x4(_,w,$);return u4().spawn(_,w,$)}var m4;function i7(_,w,$){if(m4)return m4(_,w,$);let X=u4();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var r7;function n7(){return r7??process.platform}function a7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function o7(_){try{let w=i7("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 s7(_){return new Promise((w)=>setTimeout(w,_))}async function t7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=n7(),X=w?.signal??"SIGKILL",J=w?.retry??3,Y=w?.retryDelayMs??500;U1.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${J} delayMs=${Y}`);for(let W=1;W<=J;W++){let q=$==="win32"?e7(_):_J(_,X,$);if(await s7(Y),!($==="win32"?o7(_):a7(_)))return U1.info(`[bg-process:kill-done] pid=${_} attempts=${W} stillAlive=false`),{pid:_,platform:$,signal:q.signal,success:!0,attempts:W,stillAlive:!1};if(W<J)U1.warn(`[bg-process:kill-retry] pid=${_} attempt=${W}/${J}`)}return U1.error(`[bg-process:kill-failed] pid=${_} attempts=${J} stillAlive=true`),{pid:_,platform:$,signal:$==="win32"?"taskkill /f /t":X,success:!1,attempts:J,stillAlive:!0}}function e7(_){try{return p7("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 _J(_,w,$){try{return process.kill(-_,w),{pid:_,platform:$,signal:w,success:!0}}catch(X){let J=X.code;if(J==="ESRCH"||J==="EPERM")return{pid:_,platform:$,signal:w,success:!0};return{pid:_,platform:$,signal:w,success:!1}}}a();var r2=n("task:process-registry");class n2{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);r2.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await t7(w,{retry:3,retryDelayMs:500});if($.stillAlive)r2.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{}r2.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var wJ=new d7;function l4(_,w){return wJ.run(_,w)}import{randomUUID as $J}from"crypto";z_();function XJ(){if(typeof Bun<"u"){let{Database:_}=__("bun:sqlite");return _}else return __("better-sqlite3")}function JJ(_){let $=new(XJ())(_);if(typeof $.run!=="function")$.run=function(X,...J){if(J.length>0)return this.prepare(X).run(...J);else return this.exec(X)};return $}class a2{db;insertStmt;getByIdStmt;recentStmt;constructor(_){this.db=JJ(_.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 (
|
|
293
|
+
`).all(_).map(($)=>{let X=Number($.span_count)||0,Y=Number($.error_count)||0,J=$.end_time??void 0,W=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:W}})}deleteByTraceId(_){if(this.db)this.db.prepare("DELETE FROM span WHERE trace_id = ?").run(_)}close(){if(this.db)this.db.close(),this.db=null}rowToSpan(_){return{traceId:_.trace_id,spanId:_.span_id,parentSpanId:_.parent_span_id,name:_.name,kind:_.kind,status:_.status,startTime:_.start_time,endTime:_.end_time,attributes:_.attributes?JSON.parse(_.attributes):{},result:_.result||void 0,error:_.error||void 0}}buildTree(_){let 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 $8=()=>{};import{appendFileSync as X7,existsSync as Y7,mkdirSync as J7}from"fs";import{join as D0}from"path";import{AsyncLocalStorage as Y8}from"async_hooks";function X8(_,w){return _.padStart(w,"0")}function P1(_){return/^[0-9a-f]+$/i.test(_)}function a6(_){let w=X8(_.traceId.toLowerCase(),G8),$=X8(_.spanId.toLowerCase(),q8);return[T1,w,$,s6].join("-")}function o6(_){if(!_||typeof _!=="string")return;let $=_.trim().split("-");if($.length!==4)return;let[X,Y,J,W]=$;if(X!==T1){if(X>T1)return}if(Y.length!==G8||!P1(Y))return;if(J.length!==q8||!P1(J))return;if(W.length!==t6||!P1(W))return;return{traceId:Y.toLowerCase(),spanId:J.toLowerCase()}}var T1="00",s6="01",Z1="TRACEPARENT",G8=32,q8=16,t6=2,g1,e6=r(()=>{g1={inject(_,w){_[Z1]=a6(w)},extract(_){let w=_[Z1];if(!w)return;return o6(w)},getTraceparentHeader(){return Z1}}}),_7,w7,$7=r(()=>{((_)=>{_.CLIENT="client",_.SERVER="server",_.INTERNAL="internal"})(_7||={}),((_)=>{_.OK="ok",_.ERROR="error"})(w7||={})});function h1(_){let w=_.replace(/\\/g,"/"),$=w.match(/\/\$bunfs\/root\/(.+)$/);if($){let W=$[1],Q=W.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Q)return Q[1];return W}let X=w.match(/@roy-agent\+core@file\+([^/]+)\/node_modules\/@roy-agent\/core\/(.+)$/);if(X){let W=X[1].replace(/\+/g,"/"),Q=X[2],G=W,q=Q.startsWith("src/")?Q:`src/${Q}`;return`${G}/${q}`}let Y=w.match(/(packages\/[^/]+\/src\/[^/]+\/.+)$/);if(Y)return Y[1];let J=["packages/core/src","packages/core","packages"];for(let W of J){let Q=w.indexOf(W);if(Q!==-1)return w.substring(Q)}return w}function W7(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";try{let w=w_("xdg-basedir");if(w.xdgData)return D0(w.xdgData,"roy-agent","logs")}catch{}return D0(_,".local","share","roy-agent","logs")}function Q7(){return z7}function G7(){if(N_){let w=N_.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 q7(_){if(N_){let X=N_.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=N_.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 G7()}function H7(_){if(_.startsWith("/"))return!0;if(/^[a-zA-Z]:[/\\]/.test(_))return!0;return!1}function D7(_){if(_.startsWith("~")){let w=process.env.HOME||process.env.USERPROFILE||"/tmp";return D0(w,_.slice(1))}return _}function B7(){if(N_){let _=N_.get("log-trace.logging.file");if(_)return _}return"app.log"}function U7(){if(N_){let _=N_.get("log-trace.logging.dir");if(_)return _}return W7()}function y1(){if(N_){let _=N_.get("log-trace.logging.maxOutput");if(typeof _==="number")return _}return}class H8{prefix;constructor(_){this.prefix=_}shouldLog(_){let w=q7(this.prefix);return I1[_]>=I1[w]}ensureLogDirectory(_){if(!Y7(_))try{J7(_,{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(`
|
|
294
|
+
`)||[];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 W=J[1];return{file:this.getRelativePath(W),line:parseInt(J[2],10)}}}}return null}getRelativePath(_){return h1(_)}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}]`:"",W="";try{let D=B0().getTracer("roy-tracer").getCurrentContext();if(D?.traceId)W=`[traceId=${D.traceId}]`}catch{}let Q="";if($&&typeof $==="object"&&"callerLocation"in $){let H=$;Q=H.callerLocation?` [${H.callerLocation}]`:"";let{callerLocation:B,...D}=H;$=Object.keys(D).length>0?D:void 0}else{let H=this.getCallerLocation();if(H)Q=` [${H.file}:${H.line}]`}let G=`${Y} [${_.toUpperCase()}]${W}${Q}${J} ${w}`;if($!==void 0)if(typeof $==="object")G+=" "+JSON.stringify($).replace(/\n/g,"");else G+=" "+String($);let q=y1();if(q&&q>0&&G.length>q)G=G.substring(0,q)+" [TRUNCATED]";return G}writeToFile(_){try{let w=U7(),$=B7(),X=D7(w),Y=H7(X)?X:D0(process.cwd(),X);this.ensureLogDirectory(Y);let J=D0(Y,$);X7(J,_+`
|
|
295
|
+
`,"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(V7)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 H8(_));return q2.get(_)}var N_=null,z7=!1,V7=!1;var I1,q2,a=r(()=>{m1(),I1={debug:0,info:1,warn:2,error:3},q2=new Map}),O7={};a_(O7,{setTracerProvider:()=>M7,resetTracerProvider:()=>A7,getTracerProvider:()=>B0,OTelTracerProvider:()=>x1});function v1(){if(!C1)C1=n("otel-tracer");return C1}function D8(){return process.env.ROY_TRACE_DEBUG_OTEL==="1"||process.env.ROY_TRACE_DEBUG==="1"}function B8(_,...w){v1().info(_,...w)}function J8(_,...w){v1().warn(_,...w)}function W8(_,...w){v1().error(_,...w)}class k1{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(D8())B8(`[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)J8(`[OTelSpan] storage is null for "${this.name}", attempting to re-fetch...`),X=B0().getStorage();if(X){if(!(X.db||X.initialized))J8(`[OTelSpan] storage not initialized for "${this.name}", initializing now...`),X.initialize().catch((J)=>{W8("[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 W8(`[OTelSpan] Failed to save span "${this.name}": storage still null after re-fetch`);this.onEnd?.()}}class U8{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(),W,Q,G,q,H;if(Y&&w?.context){let D=w.context;Q=D.traceId,G=this.generateSpanId(),q=D.spanId,H={traceId:Q,spanId:G,parentSpanId:q},this.currentContext={traceId:Q,spanId:G,parentSpanId:q};let O=new k1(_,H,this.storage,D,()=>this.handleSpanEnd(H.spanId,D.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)W=$;else if(this.currentContext)W=this.currentContext;else if(J)W=J;if(Q=W?.traceId||this.generateTraceId(),G=this.generateSpanId(),X&&$)q=$.parentSpanId||$.spanId;else if(this.currentContext)q=this.currentContext.spanId;else if(J)q=J.spanId;H={traceId:Q,spanId:G,parentSpanId:q},this.currentContext={traceId:Q,spanId:G,parentSpanId:q};let B=new k1(_,H,this.storage,W,()=>this.handleSpanEnd(H.spanId,W?.spanId));if(w?.attributes)for(let[D,O]of Object.entries(w.attributes))B.setAttribute(D,O);if(this.activeSpans.set(G,B),D8())B8(`[OTelTracer] \u2713 Span created: name="${_}" traceId=${Q} spanId=${G} parentSpanId=${q||"-"}`);return B}injectToEnv(_){if(this.currentContext)g1.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 x1{tracers=new Map;storage;initialized=!1;globalContext;globalContextScope=new Y8;tracerContexts=new Map;tracerContextScope=new Y8;instanceId;constructor(_,w){Q8++,this.instanceId=`Provider#${Q8}`,this.storage=_||new S1(w||R7())}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 U8(_,w,this.storage,this),this.tracers.set($,X),this.initialized)this.restoreFromEnv(X)}return X}restoreFromEnv(_){let w=g1.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 x1;return m_}function A7(){if(m_)m_.shutdown(),m_=null}function M7(_){if(m_)m_.shutdown();m_=_}function R7(){let _=w_("os"),w=w_("path"),$=_.homedir(),X=process.env.XDG_DATA_HOME||w.join($,".local","share");return w.join(X,"roy-agent","traces.db")}var C1=null,m_=null,Q8=0,m1=r(()=>{$8(),e6(),$7(),a()});import{AsyncLocalStorage as f7}from"async_hooks";a();var H2=n("process-tree-killer");function O8(){return w_("child_process")}var z8;function L7(_,w,$){if(z8)return z8(_,w,$);return O8().spawn(_,w,$)}var V8;function F7(_,w,$){if(V8)return V8(_,w,$);let X=O8();if(typeof X.spawnSync!=="function")return;return X.spawnSync(_,w,$)}var K7;function N7(){return K7??process.platform}function b7(_){try{return process.kill(_,0),!0}catch(w){if(w.code==="ESRCH")return!1;return!0}}function j7(_){try{let w=F7("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 E7(_){return new Promise((w)=>setTimeout(w,_))}async function S7(_,w){if(!Number.isInteger(_)||_<=0)throw Error(`Invalid PID: ${_} (must be a positive integer)`);let $=N7(),X=w?.signal??"SIGKILL",Y=w?.retry??3,J=w?.retryDelayMs??500;H2.info(`[bg-process:kill-begin] pid=${_} signal=${X} retry=${Y} delayMs=${J}`);for(let W=1;W<=Y;W++){let Q=$==="win32"?P7(_):Z7(_,X,$);if(await E7(J),!($==="win32"?j7(_):b7(_)))return H2.info(`[bg-process:kill-done] pid=${_} attempts=${W} stillAlive=false`),{pid:_,platform:$,signal:Q.signal,success:!0,attempts:W,stillAlive:!1};if(W<Y)H2.warn(`[bg-process:kill-retry] pid=${_} attempt=${W}/${Y}`)}return H2.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 P7(_){try{return L7("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 Z7(_,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 u1=n("task:process-registry");class l1{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);u1.info(`[bg-process:killAll-begin] count=${_.length} pids=[${_.join(",")}]`);for(let w of _)try{let $=await S7(w,{retry:3,retryDelayMs:500});if($.stillAlive)u1.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{}u1.info(`[bg-process:killAll-done] remaining=${this.pids.size}`)}}var C7=new f7;function A8(_,w){return C7.run(_,w)}function T7(){if(D2!==void 0)return D2;let _=process.env.ROY_TRACE_FULL?.trim().toLowerCase();return D2=_==="1"||_==="true"||_==="yes",D2}var D2;var I7=()=>{};function k7(_){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 Q=Y.value,G=_?.name||String(X);return Y.value=I_(Q,G,w()),Y}let J=$,W=X||{};if(typeof J==="function"){let Q=_?.name||(W?.name?String(W.name):"anonymous");return I_(J,Q,w())}return J}}function u(_,w){return k7({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=y1();return z!==void 0?z:500},W=(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}},Q=(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]",H=(z)=>{try{return z()}catch(U){try{n("traced:"+w).warn(`[trace] filter threw, ignoring: ${U instanceof Error?U.message:String(U)}`)}catch{}return}},B=(z,U)=>{if(X.recordResultToDb===!0)return{value:z,store:!0};if(T7())return{value:z,store:!0};if(X.resultFilter){let V=U?.ran?U.value:H(()=>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}},D=()=>{let z=Error.stackTraceLimit;Error.stackTraceLimit=15;let U=Error();Error.captureStackTrace(U,D);let V=U.stack?.split(`
|
|
296
|
+
`)||[];Error.stackTraceLimit=z;for(let M=1;M<V.length;M++){let f=V[M];if(f.includes("decorator.ts")||f.includes("decorator.js")||f.includes("logFn")||f.includes("getCallerLocation"))continue;let N=f.match(/at\s+.+\s+\((.+):(\d+):\d+\)/)||f.match(/at\s+(.+):(\d+):\d+/);if(N){let R=N[1];if(!R||R==="native")continue;return`${h1(R)}:${N[2]}`}}return""},O=(z,U,V)=>{if(!Y)return;let M=n("traced:"+w),N=`[TRACE] ${z==="enter"?">>>":z==="quit"?"<<<":"!!!"} ${w}`,R=V||D(),b=(F,T)=>{if(T!==void 0)M.info(`${N} ${F}: ${Q(T)}`,{callerLocation:R});else M.info(`${N} ${F}`,{callerLocation:R})};if(z==="enter")b("enter",U);else if(z==="quit")b("quit",X.logResult??X.recordResult?U:void 0);else b("error",U)};return function(...z){let U=B0().getTracer("roy-tracer"),V={};if(X.recordParams!==!1)if(X.paramFilter){let N=H(()=>X.paramFilter(z));if(V.params=G(N),X.flattenParamFilter&&N&&typeof N==="object"&&!Array.isArray(N)){for(let[R,b]of Object.entries(N))if(!(R in V))V[R]=G(b)}}else V.params=G(z);let M=D(),f;try{f=U.startSpan(w,{attributes:V})}catch{}O("enter",z,M);try{let N=_.call(this,...z);if(N&&typeof N==="object"&&typeof N.then==="function")return N.then((R)=>{if(f){let b=X.resultFilter!==void 0,F=X.resultFilter?H(()=>X.resultFilter(R)):void 0;if(F&&typeof F==="object"&&!Array.isArray(F))for(let[C,y]of Object.entries(F))f.setAttribute(C,G(y));let T=B(R,{ran:b,value:F});if(T.store)f.setAttribute("result",JSON.stringify(G(T.value)));let j=X.errorIf?H(()=>X.errorIf(R)):void 0;if(j){let C=j instanceof Error?j:Error(String(j));f.setAttribute("error",C.message),f.end(void 0,C)}else f.end(T.store?T.value:void 0)}return O("quit",X.logResult??X.recordResult?R:void 0,M),R},(R)=>{if(f)f.setAttribute("error",String(R)),f.end(void 0,R instanceof Error?R:Error(String(R)));throw O("error",R.message,M),R});if(f){let R=X.resultFilter!==void 0,b=X.resultFilter?H(()=>X.resultFilter(N)):void 0;if(b&&typeof b==="object"&&!Array.isArray(b))for(let[j,C]of Object.entries(b))f.setAttribute(j,G(C));let F=B(N,{ran:R,value:b});if(F.store)f.setAttribute("result",JSON.stringify(G(F.value)));let T=X.errorIf?H(()=>X.errorIf(N)):void 0;if(T){let j=T instanceof Error?T:Error(String(T));f.setAttribute("error",j.message),f.end(void 0,j)}else f.end(F.store?F.value:void 0)}return O("quit",X.logResult??X.recordResult?N:void 0,M),N}catch(N){if(f)f.setAttribute("error",String(N)),f.end(void 0,N instanceof Error?N:Error(String(N)));throw O("error",N.message,M),N}}}var V_=r(()=>{m1(),a(),I7()});import{randomUUID as g7}from"crypto";V_();function h7(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}else return w_("better-sqlite3")}function y7(_){let $=new(h7())(_);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;insertStmt;getByIdStmt;recentStmt;constructor(_){this.db=y7(_.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 (
|
|
603
297
|
event_id TEXT PRIMARY KEY,
|
|
604
298
|
es_type TEXT NOT NULL,
|
|
605
299
|
sender_id TEXT NOT NULL,
|
|
@@ -614,7 +308,7 @@ Note: \`total\` is the FIRST field in the response so it survives tail-truncatio
|
|
|
614
308
|
FROM event_store
|
|
615
309
|
WHERE es_type = ? AND sender_id = ?
|
|
616
310
|
ORDER BY created_at DESC
|
|
617
|
-
LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${
|
|
311
|
+
LIMIT ?`)}async insertTriggerEvent(_,w){let $=`evt_${Date.now()}_${g7()}`,X=Date.now(),Y=JSON.stringify(_.metadata??{}),J=_.rawEvent===void 0?null:v7(_.rawEvent);return this.insertStmt.run($,w,_.senderId,_.text??null,Y,J,X),$}async getEventById(_){let w=this.getByIdStmt.get(_);if(!w)return null;return M8(w)}async getRecentEvents(_,w,$){return this.recentStmt.all(_,w,$).map((Y)=>M8(Y))}close(){this.db.close()}}m([u("event_store.insert_trigger",{recordParams:!0,recordResult:!0})],c1.prototype,"insertTriggerEvent",null);m([u("event_store.query_by_id",{recordParams:!0,recordResult:!1})],c1.prototype,"getEventById",null);function M8(_){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 v7(_){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 x7=null;function R8(){return x7}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 d1={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
|
|
618
312
|
|
|
619
313
|
## \u26A0\uFE0F \u91CD\u8981\u6F84\u6E05\uFF1A\u5173\u4E8E\u672C prompt \u4E2D\u7684\u5DE5\u5177\u5F15\u7528
|
|
620
314
|
|
|
@@ -2027,7 +1721,7 @@ outputs: [] # \u8F93\u51FA\u5B9A\u4E49\uFF08\u53EF\u7A7A\uFF
|
|
|
2027
1721
|
|
|
2028
1722
|
\u4F60\u662F\u4F1A\u8BDD\u538B\u7F29\u6307\u5BFC\u63D0\u793A\u751F\u6210\u5668\u3002\u5206\u6790\u5BF9\u8BDD\u5386\u53F2\uFF0C\u751F\u6210"\u538B\u7F29\u6307\u5BFC\u63D0\u793A"\u544A\u8BC9 checkpoint \u751F\u6210\u5668\u5728\u538B\u7F29\u65F6\u91CD\u70B9\u63D0\u53D6\u4EC0\u4E48\u3002
|
|
2029
1723
|
|
|
2030
|
-
\u4F7F\u7528 \`workflow_submit_output\` \u5DE5\u5177\u63D0\u4EA4\u7ED3\u679C\uFF0C\u5305\u542B guidance_prompt \u5B57\u6BB5\u3002`,"workflow-creator":'# Workflow Creator (\u4EA4\u4E92\u5F0F workflow \u6784\u5EFA\u5B50\u4EE3\u7406)\n\n## \u4F60\u7684\u8EAB\u4EFD\n\n\u4F60\u662F Roy \u7CFB\u7EDF\u7684 **workflow-creator** \u5B50\u4EE3\u7406 (type=sub)\uFF0C\u4E0E workflow-runner / workflow-extract / roy / explore \u540C\u5C42\u3002\n\n\u8C03\u7528\u4F60\u7684 parent agent \u4F1A\u544A\u8BC9\u4F60\uFF1A**\u7528\u6237\u60F3\u6784\u5EFA\u7684 workflow \u662F\u4EC0\u4E48**\uFF0C\u53EF\u80FD\u9644\u5E26\uFF1A\n- \u4EFB\u52A1\u63CF\u8FF0\uFF08\u7528\u6237\u5E0C\u671B workflow \u89E3\u51B3\u4EC0\u4E48\u95EE\u9898\uFF09\n- task/log/trace/session \u5931\u8D25\u4E0A\u4E0B\u6587\uFF08\u7528\u6237\u60F3\u62BD\u8C61\u6210\u53EF\u590D\u7528 workflow\uFF09\n- \u73B0\u6709 workflow \u540D\uFF08\u7528\u6237\u60F3\u57FA\u4E8E\u5B83\u6539\u9020\u51FA\u65B0\u53D8\u4F53\uFF09\n\n**\u4F60\u4E0D\u662F** primary mediator\uFF08\u4E0D\u50CF\u8001\u7684 workflow-agent\uFF09\uFF0C\u4F60\u53EA\u662F sub-agent\uFF0C**\u4E0D\u8981**\u81EA\u5DF1\u53BB\u505A\u7528\u6237\u9762\u5BF9\u9762\u7684\u5BF9\u8BDD\u6F84\u6E05\u3002\n\n## \u4F60\u7684\u5DE5\u5177 (10 \u4E2A, \u4E25\u683C\u767D\u540D\u5355)\n\n| \u5DE5\u5177 | \u7528\u9014 |\n|------|------|\n| `workflow_list` | \u6D4F\u89C8\u5DF2\u6709 workflow\uFF08\u627E\u76F8\u4F3C\u6A21\u677F\u3001\u547D\u540D\u7EA6\u5B9A\uFF09 |\n| `workflow_get` | \u53D6\u6307\u5B9A workflow \u5B8C\u6574\u5B9A\u4E49\uFF08\u5B66\u4E60\u8282\u70B9\u7ED3\u6784\u3001template \u5199\u6CD5\uFF09 |\n| `workflow_search` | \u5173\u952E\u8BCD\u641C\u7D22\uFF08"code-review" / "agentNode" / "parallel" \u7B49\uFF09 |\n| `workflow_tag_list` | **\u67E5 tag \u6C60\uFF0C\u907F\u514D tag \u81A8\u80C0**\uFF08\u5DF2\u6709 `code-review` \u65F6\u4E0D\u8981\u65B0\u589E `review-workflow`\uFF09 |\n| `workflow_validate` | **\u5FC5\u987B**\u5728 `workflow_add` \u4E4B\u524D\u8C03\u7528\uFF0C\u76F4\u5230\u8FD4\u56DE **\u96F6 error**\u3002\u5B83\u73B0\u5728\u505A\u4E24\u5C42\u6821\u9A8C\uFF1A\u2460 DAG \u7ED3\u6784\uFF1B\u2461 **\u6A21\u677F\u5F15\u7528\u5951\u7EA6**\uFF08`{{nodes.X.<\u5B57\u6BB5>}}` \u662F\u5426\u5339\u914D X \u7684\u8F93\u51FA schema\uFF09\uFF0C\u5E76\u8FD4\u56DE\u53EF\u64CD\u4F5C\u7684 `warnings` / `infos` |\n| `workflow_add` | \u6CE8\u518C\u65B0 workflow\uFF08\u9700\u8981 1-3 \u4E2A tags\uFF09 |\n| `bash` | **\u4EC5\u7528\u4E8E\u5951\u7EA6\u771F\u5B9E\u6027\u6821\u9A8C**\uFF08\u89C1\u9636\u6BB5 4.5\uFF09\uFF1A`ls` \u6838\u5BF9\u811A\u672C\u771F\u540D\u3001`grep` \u6838\u5BF9\u8F93\u51FA\u6807\u8BB0\u3001`roy-agent debug trace/debug span` \u53D6\u8BC1\u3002**\u7981\u6B62**\u7528\u5B83\u7ED5\u8FC7 workflow \u76F4\u63A5\u5E72\u6D3B |\n| `read_file` | \u8BFB\u811A\u672C/\u6D4B\u8BD5\u6587\u4EF6\u5185\u5BB9\uFF0C\u6838\u5BF9\u5B83\u771F\u7684\u8F93\u51FA\u4F60 grep \u7684\u6807\u8BB0 |\n| `workflow_run` | **\u6784\u5EFA\u540E\u5192\u70DF\u771F\u8DD1**\uFF08\u89C1\u9636\u6BB5 5.5\uFF0CDoD \u786C\u95E8\u69DB\uFF09 |\n| `workflow_run_status` | \u8F6E\u8BE2\u5192\u70DF run \u7684\u7EC8\u6001\uFF08completed / failed / timeout\uFF09 |\n\n> \u26A0\uFE0F **\u4F60\u53EA\u6709\u8FD9 10 \u4E2A\u5DE5\u5177**\uFF0C\u4E0D\u8981\u4F7F\u7528 `edit_file` / `write_file` / `delegate_task` \u7B49\u3002\n> \u26A0\uFE0F `bash` **\u53EA\u7528\u4E8E"\u6838\u5B9E\u4E8B\u5B9E"\u4E0E"\u53D6\u8BC1"\uFF0C\u7EDD\u4E0D\u7528\u4E8E"\u66FF\u4EE3 workflow \u8282\u70B9\u5B8C\u6210\u4E1A\u52A1\u903B\u8F91"** \u2014\u2014\n> \u540E\u8005\u4F1A\u8BA9 workflow \u53D8\u6210\u4E00\u4E2A\u7A7A\u58F3\uFF0C\u662F\u672C prompt \u660E\u4EE4\u7981\u6B62\u7684\u8D70\u6377\u5F84\u884C\u4E3A\u3002\n> \u26A0\uFE0F \u4E0D\u8981\u76F4\u63A5\u8BFB `*.workflow.yaml` \u6587\u4EF6\u81EA\u5DF1 parse\uFF08\u7528 `workflow_get`\uFF09\u3002\n\n## \u591A\u8F6E\u4EA4\u4E92\u6D41\u7A0B (\u4E0E workflow-extract \u7684\u5173\u952E\u5DEE\u5F02)\n\nworkflow-creator \u662F**\u591A\u8F6E\u5BF9\u8BDD\u5F0F**\u534F\u4F5C\u3002\u6BCF\u4E2A\u9636\u6BB5\u90FD\u53EF\u80FD\u9700\u8981 ask parent agent \u8DDF\u7528\u6237\u6F84\u6E05\u3002\n\n### \u9636\u6BB5 1: \u9700\u6C42\u6F84\u6E05 (Requirements Clarification)\n\n\u6839\u636E\u7528\u6237\u63D0\u4F9B\u7684\u4EFB\u52A1/\u65E5\u5FD7/trace/session \u4FE1\u606F\uFF0C**\u4E3B\u52A8\u5411 parent agent \u63D0\u95EE**\uFF1A\n- \u8FD9\u4E2A workflow \u8981\u89E3\u51B3\u4EC0\u4E48\u5177\u4F53\u95EE\u9898\uFF1F\n- \u8F93\u5165\u662F\u4EC0\u4E48\uFF1F\u8F93\u51FA\u662F\u4EC0\u4E48\uFF1F\n- \u5173\u952E\u8282\u70B9\u662F\u5426\u6709\u7279\u6B8A\u884C\u4E3A\u8981\u6C42\uFF1F\n- \u5931\u8D25\u5904\u7406\u7B56\u7565\uFF1F\uFF08\u91CD\u8BD5/\u4E2D\u65AD/\u8BE2\u95EE\u7528\u6237/\u76F4\u63A5\u5931\u8D25\uFF09\n\n### \u9636\u6BB5 2: \u5B66\u4E60\u73B0\u6709\u6A21\u5F0F (Learn from existing workflows)\n\n\u8C03\u7528 `workflow_list` + `workflow_get <\u76F8\u4F3C workflow>` \u5B66\u4E60\uFF1A\n- **\u547D\u540D\u7EA6\u5B9A**\uFF08kebab-case\u3001\u52A8\u8BCD+\u540D\u8BCD\uFF09\n- **entry \u8282\u70B9\u5B9A\u4E49**\n- **config \u5B57\u6BB5**\uFF08parallel_limit\u3001timeout\u3001strict\u3001loopEnabled \u7B49\uFF09\n- **\u8282\u70B9\u7EC4\u5408\u65B9\u5F0F**\uFF08\u7EBF\u6027\uFF1F\u6761\u4EF6\u5206\u652F\uFF1F\u5E76\u884C\uFF1F\uFF09\n\n### \u9636\u6BB5 3: \u8BBE\u8BA1\u8349\u6848 (Design Draft)\n\n\u7528 Markdown \u8F93\u51FA\u8BBE\u8BA1\uFF1A\n- **\u8282\u70B9\u8868**\uFF08id / type / name / \u804C\u8D23 / \u4F9D\u8D56\uFF09\n- **\u6570\u636E\u6D41**\uFF08\u54EA\u4E00\u6B65\u7684\u8F93\u51FA\u5230\u54EA\u4E00\u6B65\u7684\u8F93\u5165\uFF09\n- **\u5DE5\u5177\u9009\u62E9\u7406\u7531**\uFF08tool / skill / agent / workflow / condition / askUser / pythonCall\uFF09\n- **tags \u9009\u62E9**\uFF08\u4ECE `workflow_tag_list` \u9009\u5DF2\u6709 tag\uFF0C\u5FC5\u8981\u65F6\u65B0\u589E\uFF09\n\n### \u9636\u6BB5 4: \u751F\u6210 YAML (Generate Draft YAML)\n\n\u8F93\u51FA\u5B8C\u6574 YAML draft\uFF0C\u53C2\u8003\u4EE5\u4E0B\u6700\u5C0F\u5316\u6A21\u677F\u3002\n\n### \u9636\u6BB5 4.5: \u8F93\u5165\u5951\u7EA6\u771F\u5B9E\u6027\u6821\u9A8C (Contract Grounding) \uD83D\uDD0D\n\n> \u80CC\u666F\uFF08\u771F\u5B9E\u4E8B\u6545\uFF09\uFF1A\u66FE\u4EA4\u4ED8\u4E00\u4E2A\u300Cvalidate \u901A\u8FC7\u3001\u6CE8\u518C\u6210\u529F\uFF0C\u4F46\u4E00\u8DD1\u5C31\u5047\u9633\u6027 PASS\u300D\u7684 workflow \u2014\u2014\n> \u811A\u672C\u540D\u62FC\u63A5\u9519\uFF08`PY_TAG=312` vs \u78C1\u76D8 `cp12`\uFF09\u3001\u56DE\u9000\u811A\u672C\u5728\u5BB9\u5668\u5185\u5D4C\u5957 docker \u5BFC\u81F4\u7A7A\u8DD1\u3001\n> \u811A\u672C\u786C\u7F16\u7801 `Total 99 PASS 99` \u88AB\u805A\u5408\u8282\u70B9\u5F53\u771F\u503C\uFF0C\u6700\u7EC8 0/0/0 \u5374\u62A5 PASS\u3002\n> \u6839\u56E0\uFF1A**validate \u53EA\u770B DAG \u7ED3\u6784\uFF0C\u4E0D\u770B\u8BED\u4E49**\u3002\n\n\u5728\u628A\u4EFB\u4F55**\u6587\u4EF6\u8DEF\u5F84 / \u547D\u4EE4\u540D / \u8F93\u51FA\u6807\u8BB0**\u5199\u8FDB YAML \u4E4B\u524D\uFF0C**\u7528 `bash` / `read_file` \u6838\u5B9E\u5B83\u771F\u7684\u5B58\u5728\u3001\u771F\u7684\u5339\u914D**\uFF1A\n\n- **\u8DEF\u5F84\u5951\u7EA6**\uFF1A\u5F62\u5982 `/tmp/xxx_${VAR}.sh` \u7684\u8DEF\u5F84\uFF0C\u5FC5\u987B\u628A**\u53D8\u91CF\u4EE3\u5165\u540E\u7684\u6700\u7EC8\u5B57\u7B26\u4E32**\u4E0E\u78C1\u76D8\u771F\u5B9E\u6587\u4EF6\u9010\u4E00\u6BD4\u5BF9\n \uFF08\u4F8B\uFF1A`for v in 3.12 3.13; do ls /tmp/..._cp${v//./}.sh; done`\uFF09\u3002\n \u811A\u672C\u540D\u89C4\u5F8B\u82E5\u662F `cp12` \u800C\u4F60\u62FC\u51FA `cp312` \u2192 \u5951\u7EA6\u9519\u8BEF\uFF0C\u5FC5\u987B\u6539 YAML\u3002\n- **\u8F93\u51FA\u6807\u8BB0\u5951\u7EA6**\uFF1Aworkflow \u91CC grep \u7684\u6807\u8BB0\uFF08\u5982 `[PASS]`\uFF09\u5FC5\u987B\u4E0E\u6D4B\u8BD5\u811A\u672C**\u771F\u5B9E\u8F93\u51FA**\u7684\u6807\u8BB0\u5B8C\u5168\u4E00\u81F4\n \uFF08\u53BB\u811A\u672C\u91CC\u6838\u5BF9\u5B83\u7684\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0D\u8981\u51ED\u60F3\u8C61\u5199\u6807\u8BB0\uFF09\u3002\n- **\u6267\u884C\u73AF\u5883\u5951\u7EA6**\uFF1A\u786E\u8BA4\u811A\u672C\u662F\u300C\u5BBF\u4E3B\u673A\u8DD1\uFF08\u5185\u90E8 docker exec\uFF09\u300D\u8FD8\u662F\u300C\u5BB9\u5668\u5185\u8DD1\u300D\u2014\u2014\n \u628A\u300C\u5BBF\u4E3B\u673A\u7528 docker \u9A71\u52A8\u300D\u7684\u811A\u672C `docker cp` \u8FDB\u5BB9\u5668\u518D\u8DD1 = **\u5FC5\u7136\u7A7A\u8DD1**\uFF0C\u7981\u6B62\u3002\n- \u6821\u9A8C\u7ED3\u8BBA\u5199\u8FDB\u8BBE\u8BA1\u62A5\u544A\u300C\u5951\u7EA6\u6821\u9A8C\u300D\u5C0F\u8282\uFF0C\u6CE8\u660E\u6BCF\u6761\u5951\u7EA6\u7684**\u6838\u5B9E\u547D\u4EE4 + \u5B9E\u9645\u7ED3\u679C**\u3002\n\n### \u9636\u6BB5 4.6: \u5F15\u7528\u5951\u7EA6\u5148\u884C (Reference Contracts First) \uD83D\uDD17\n\n> \u80CC\u666F\uFF08\u771F\u5B9E\u4E8B\u6545\uFF0CTask #4296\uFF09\uFF1A`wheels-validate-v1` v1.3.0 \u7684 `report-results`(agent)\n> \u8282\u70B9 prompt \u5199\u4E86 `{{nodes.run-validation-tests.result}}`\uFF0C\u4F46 `run-validation-tests`\n> \u662F **tool** \u8282\u70B9 \u2014\u2014 tool \u8282\u70B9**\u6CA1\u6709** `result` \u5B57\u6BB5\uFF08\u53EA\u6709 `output`\uFF09\u3002\u5F15\u64CE\u628A\u8BE5\u6A21\u677F\u9759\u9ED8\u89E3\u6790\u6210**\u7A7A\u5B57\u7B26\u4E32**\uFF08\u53EA warn \u4E0D\u62A5\u9519\uFF09\uFF0Cagent \u62FF\u5230\u7A7A\u4E0A\u4E0B\u6587\u540E\u81EA\u5224 ERROR\uFF0C\n> \u6700\u7EC8\u9876\u5C42 status \u5374\u662F `completed`\uFF0C\u5199\u51FA\u4E00\u4EFD 0/0/0 \u7684\u5047\u62A5\u544A\u3002\n>\n> **\u6839\u56E0\u4E0D\u662F DAG\uFF0C\u662F\u300C\u5F15\u7528\u5B57\u6BB5\u540D\u4E0E\u6E90\u8282\u70B9\u8F93\u51FA schema \u4E0D\u5339\u914D\u300D\u3002**\n\n**\u94C1\u5F8B\uFF1A\u5199 `{{nodes.X.<\u5B57\u6BB5>}}` \u4E4B\u524D\uFF0C\u5148\u786E\u8BA4 X \u7684\u8282\u70B9\u7C7B\u578B\u80FD\u4EA7\u51FA\u8BE5\u5B57\u6BB5\u3002**\n\n#### \u8282\u70B9\u8F93\u51FA\u5951\u7EA6\u8868\uFF08\u5199\u5F15\u7528\u65F6\u7684\u552F\u4E00\u771F\u503C\uFF09\n\n| \u6E90\u8282\u70B9 type | \u53EF\u5F15\u7528\u7684\u9996\u5C42\u5B57\u6BB5 | \u8BF4\u660E |\n|---|---|---|\n| `tool` | **`output`** | tool \u8282\u70B9\u7684\u5B58\u50A8\u503C\u5C31\u662F\u5B83\u7684\u7ED3\u679C\uFF08\u5E38\u5E38\u662F\u5B57\u7B26\u4E32\uFF09\u3002**\u6CA1\u6709** `.result` |\n| `pythonCall` | **`output`** | JSON \u89E3\u6790\u540E\u7684 stdout |\n| `skill` | **`output`** | skill \u7684\u8FD4\u56DE\u503C |\n| `condition` | `output` / `success` / `condition` | \u5B58\u50A8\u503C\u4E3A `{ success, condition }` |\n| `merge` | `output` / `strategy` / `results` / `count` | \u5B58\u50A8\u503C\u4E3A `{ strategy, results, count }` |\n| `agent` | **`result`** / `output` / `metadata` / `workflowHistory` + \u58F0\u660E\u7684 JSON schema \u5B57\u6BB5 | agent \u81EA\u7531\u8F93\u51FA\uFF1B\u82E5\u58F0\u660E\u4E86 `output.schema.properties`\uFF0C\u5B57\u6BB5\u540D\u5E94\u4E0E schema \u5BF9\u9F50 |\n| `workflow` | `output` / `result` | \u5B50 workflow \u9876\u5C42 output\uFF08\u5F62\u72B6\u672A\u77E5\uFF09 |\n\n**\u8BB0\u5FC6\u53E3\u8BC0**\uFF1A\n- **`agent` \u2192 `.result`**\uFF08\u552F\u4E00\u7528 `.result` \u7684\u8282\u70B9\u7C7B\u578B\uFF09\n- **\u6570\u636E\u7C7B\u8282\u70B9\uFF08tool / pythonCall / skill\uFF09\u2192 `.output`**\n- **`.output` \u5BF9\u6240\u6709\u7C7B\u578B\u90FD\u5B89\u5168**\uFF08\u5F15\u64CE\u628A\u5B83\u5F53\u300C\u53D6\u51FA\u8BE5\u8282\u70B9\u7684\u503C\u300D\u7684\u901A\u7528\u524D\u7F00\uFF09\n\n#### \u81EA\u68C0\u4E24\u6B65\n\n1. **\u5148 validate**\uFF1A\u5199\u5B8C YAML \u5148\u8DD1 `workflow_validate`\uFF0C\u5B83\u4F1A\u628A\n `{{nodes.<toolNode>.result}}` \u8FD9\u7C7B\u9519\u8BEF\u76F4\u63A5\u6807\u6210 **error**\uFF0C\u5E76\u7ED9\u51FA `Did you mean "{{nodes.<toolNode>.output}}"` \u7684\u4FEE\u590D\u5EFA\u8BAE \u2014\u2014 **\u7167\u6284\u5EFA\u8BAE\u6539**\u3002\n2. **\u5FC5\u8981\u65F6\u67E5 schema**\uFF1A\u9700\u8981\u5F15\u7528 agent \u8282\u70B9\u7684\u7ED3\u6784\u5316\u5B57\u6BB5\u65F6\uFF0C\u5148 `workflow_get <\u76F8\u4F3C workflow>` \u770B\u5B83\u7684 `output.schema` \u5B57\u6BB5\u540D\uFF0C\u6216\u5728\u81EA\u5DF1\u7684 `config.output.schema` \u91CC**\u663E\u5F0F\u58F0\u660E**\u6240\u6709\u4E0B\u6E38\u4F1A\u7528\u5230\u7684\u5B57\u6BB5\uFF0C\u518D\u7167\u5B57\u6BB5\u540D\u5199\u5F15\u7528\u3002\n\n#### \u786C\u7EA6\u675F\n\n- \u274C **\u7981\u6B62**\u5728 `tool` / `pythonCall` / `skill` \u8282\u70B9\u4E0A\u7528 `.result`\n- \u274C **\u7981\u6B62**\u5728\u672A\u58F0\u660E `output.schema` \u7684 agent \u8282\u70B9\u4E0A\u5F15\u7528\u300C\u770B\u8D77\u6765\u5E94\u8BE5\u5B58\u5728\u300D\u7684\u5B57\u6BB5\uFF08\u5148\u58F0\u660E\u518D\u5F15\u7528\uFF09\n- \u274C **\u7981\u6B62**\u5BF9 `tool` \u8282\u70B9\u5199\u6DF1\u5C42\u8DEF\u5F84\uFF08\u5982 `{{nodes.bash-node.output.foo}}`\uFF09\u2014\u2014 tool \u8F93\u51FA\u5E38\u662F\u5B57\u7B26\u4E32\uFF0C\u65E0\u6CD5\u518D\u53D6\u5C5E\u6027\n- \u2705 \u5B58\u7591\u65F6\u4E00\u5F8B\u9000\u56DE `.output`\uFF0C\u6216\u7528 `{{nodes.X.output}}` \u6253\u5370\u540E**\u4EBA\u8089\u6838\u5BF9**\n\n### \u9636\u6BB5 5: \u8FED\u4EE3\u9A8C\u8BC1 (Iterative Validate) \uD83D\uDD01\n\n\u8C03\u7528 `workflow_validate`\uFF0C\u5B83\u8FD4\u56DE `{ valid, errors, warnings, infos, errorCount, warningCount }`\u3002\n\n**\u5FAA\u73AF\u76F4\u5230 `valid === true`\uFF08\u5373 errorCount === 0\uFF09\uFF1A**\n\n| \u8FD4\u56DE\u9879 | \u4F60\u5FC5\u987B\u505A\u4EC0\u4E48 |\n|---|---|\n| `errors`\uFF08\u963B\u585E\uFF09 | **\u9010\u6761\u4FEE\u590D**\u3002\u5E38\u89C1\u4E24\u7C7B\uFF1A\u2460 **DAG \u7ED3\u6784**\uFF1A\u8282\u70B9 ID \u91CD\u590D / \u4F9D\u8D56\u7F3A\u5931 / \u73AF / \u7A7A ID\uFF1B\u2461 **\u6A21\u677F\u5F15\u7528\u5951\u7EA6**\uFF08\u9519\u8BEF\u4FE1\u606F\u4EE5 `[template-contract:...]` \u5F00\u5934\uFF0C\u5982 `R2-result-on-non-agent`\uFF09\uFF1A\u6E90\u8282\u70B9\u7C7B\u578B\u4E0E\u6240\u5F15\u7528\u5B57\u6BB5\u4E0D\u5339\u914D \u2014\u2014 **\u76F4\u63A5\u91C7\u7528\u9519\u8BEF\u4FE1\u606F\u91CC\u7684 `Did you mean ...` \u5EFA\u8BAE** |\n| `warnings`\uFF08\u5EFA\u8BAE\uFF09 | **\u9010\u6761\u8BC4\u4F30**\u3002\u82E5\u5224\u65AD\u53EF\u63A5\u53D7\uFF08\u5982\u8F93\u51FA\u6070\u597D\u662F\u5BF9\u8C61\u4E14\u542B\u8BE5\u952E\uFF09\uFF0C\u5728\u6700\u7EC8\u62A5\u544A\u91CC**\u5199\u660E\u7406\u7531**\uFF1B\u5426\u5219**\u4E00\u5E76\u4FEE\u6389** |\n| `infos`\uFF08\u63D0\u793A\uFF09 | \u9605\u8BFB\u5373\u53EF\uFF0C\u591A\u4E3A loop \u524D\u5411\u5F15\u7528\u7B49\u826F\u6027\u573A\u666F\uFF0C\u65E0\u9700\u4FEE\u6539 |\n\n\u89C4\u5219\uFF1A\n- \u2705 `errorCount === 0` \u624D\u7B97\u901A\u8FC7 \u2192 \u8FDB\u5165\u9636\u6BB5 5.5\n- \u274C \u6709 error \u2192 \u4FEE YAML \u2192 **\u91CD\u65B0 validate**\uFF08**\u6700\u591A\u8FED\u4EE3 8 \u6B21**\uFF0C\u8D85\u8FC7\u5219\u505C\u6B62\u5E76\u62A5\u544A\u5931\u8D25\u539F\u56E0\uFF09\n- \u274C **\u4E0D\u8981**\u8DF3\u8FC7 validate \u76F4\u63A5 `workflow_add`\n- \u274C **\u4E0D\u8981**\u5728\u8FD8\u6709 error \u65F6\u7528\u300C\u7ED3\u6784\u6CA1\u95EE\u9898\u300D\u81EA\u6211\u8BF4\u670D \u2014\u2014 error \u662F**\u786C\u963B\u585E**\uFF0C`workflow_add` \u4E5F\u4F1A\u62D2\u7EDD\n\n### \u9636\u6BB5 5.5: \u7AEF\u5230\u7AEF\u5192\u70DF\u9A8C\u8BC1 (Smoke Run) \uD83D\uDEA8 \u5B8C\u6210\u786C\u95E8\u69DB\n\n> \u26A0\uFE0F **`workflow_validate` \u901A\u8FC7 \u2260 workflow \u53EF\u7528\u3002** \u5B83\u6821\u9A8C DAG \u7ED3\u6784 **+ \u6A21\u677F\u5F15\u7528\u5951\u7EA6**\n> \uFF08\u5B57\u6BB5\u540D\u662F\u5426\u5339\u914D\u6E90\u8282\u70B9\u8F93\u51FA schema\uFF09\uFF0C\u4F46**\u4ECD\u7136\u4E0D\u6821\u9A8C**\uFF1A\u811A\u672C\u8DEF\u5F84\u662F\u5426\u771F\u5B9E\u5B58\u5728\u3001\n> \u53D8\u91CF\u62FC\u63A5\u540E\u7684\u5B57\u7B26\u4E32\u662F\u5426\u6B63\u786E\u3001\u8F93\u51FA\u6807\u8BB0\u662F\u5426\u4E0E\u811A\u672C\u771F\u5B9E\u8F93\u51FA\u4E00\u81F4\u3001\u6D4B\u8BD5\u662F\u5426\u771F\u88AB\u6267\u884C\u3002\n> \u8FD9\u4E9B**\u53EA\u6709\u771F\u8DD1**\u624D\u80FD\u8BC1\u660E\u3002\u4F60**\u5FC5\u987B**\u8BA9 workflow \u771F\u7684\u8DD1\u4E00\u6B21\u5E76\u62FF\u5230\u8BC1\u636E\uFF0C\u5426\u5219**\u4E0D\u7B97\u5B8C\u6210**\u3002\n\n**\u6267\u884C\u8DEF\u5F84\uFF08\u4F60\u6709 `workflow_run`\uFF09\uFF1A**\n\n1. `workflow_run(name, input=<\u771F\u5B9E\u6837\u4F8B\u8F93\u5165>)` \u2014\u2014 \u7528**\u771F\u5B9E\u8F93\u5165**\uFF0C\u4E0D\u8981\u7528 `echo ok` \u4E4B\u7C7B\u7684\u6869\n2. `workflow_run_status(run_id)` \u8F6E\u8BE2\u5230**\u7EC8\u6001**\uFF08completed / failed / timeout\uFF09\n3. **\u7528 trace \u53D6\u8BC1**\uFF08\u8FD9\u662F\u5224\u5B9A"\u771F\u7684\u8DD1\u8FC7"\u7684\u552F\u4E00\u5BA2\u89C2\u4F9D\u636E\uFF0C\u4E0D\u8981\u53EA\u770B\u5DE5\u5177\u8FD4\u56DE\u503C\uFF09\uFF1A\n - `roy-agent debug trace <trace_id>` \u2014\u2014 \u770B\u6574\u4E2A run \u7684 span \u6811\uFF1A\u662F\u5426\u771F\u7684\u7ECF\u8FC7\n `workflow.engine.runWorkflow \u2192 startNode \u2192 validateAndExecute \u2192 executeNode`\uFF0C\n \u6BCF\u4E2A\u8282\u70B9\u662F\u5426\u90FD\u6267\u884C\u5230\uFF0C\u6709\u6CA1\u6709\u8282\u70B9\u88AB\u8DF3\u8FC7 / \u76F4\u63A5\u5931\u8D25\n - `roy-agent debug span <span_id>` \u2014\u2014 \u770B**\u5355\u4E2A\u8282\u70B9**\u7684\u5B8C\u6574\u8F93\u5165\u8F93\u51FA\u4E0E\u9519\u8BEF\n \uFF08\u8282\u70B9\u7EA7\u6392\u969C\u7528\uFF1A`workflow.executor.executeNode` / `workflow.tool.execute` \u7B49\uFF09\n - \u62FF\u4E0D\u5230 trace_id \u65F6\uFF0C\u7528 `bash` \u67E5\u6700\u8FD1 trace\uFF1A`roy-agent debug trace --list -n 5`\n4. \u628A run \u8BC1\u636E\u843D\u76D8\u5E76\u5199 `task_operation`\uFF1A`run_id + trace_id + session_id + \u5404\u8282\u70B9\u6267\u884C\u6761\u6570`\n\n**\u5192\u70DF\u901A\u8FC7\u5224\u636E\uFF08\u5168\u90E8\u6EE1\u8DB3\u624D\u7B97\u901A\u8FC7\uFF09\uFF1A**\n\n| \u5224\u636E | \u8BF4\u660E |\n|------|------|\n| \u2705 run \u7EC8\u6001 = completed | \u4E0D\u662F failed / timeout |\n| \u2705 **\u6BCF\u4E2A\u8282\u70B9\u90FD\u6709 output \u4E14\u975E\u7A7A** | \u9010\u4E2A\u68C0\u67E5\uFF1B\u51FA\u73B0 `command not found` / `Bad substitution` / `timeout` \u5373\u5931\u8D25 |\n| \u2705 **\u771F\u5B9E\u6267\u884C\u6761\u6570 > 0** | \u4F8B\uFF1A`passed_count + failed_count + expected_count > 0`\uFF1B**\u4E25\u7981 0/0/0 \u5224 PASS** |\n| \u2705 \u5173\u952E\u8F93\u5165\u5951\u7EA6\u5728\u8FD0\u884C\u4E2D\u88AB**\u771F\u5B9E\u547D\u4E2D** | \u4F8B\uFF1A\u65E5\u5FD7\u51FA\u73B0 `Test script: <\u771F\u540D>`\uFF0C\u800C\u4E0D\u662F fallback \u8B66\u544A\u5206\u652F |\n| \u2705 **\u65E0 unresolved template \u8B66\u544A** | \u5728 trace / app.log \u91CC **grep `has unresolved templates`**\uFF0C\u547D\u4E2D\u5373\u8BF4\u660E\u4ECD\u6709\u5F15\u7528\u88AB\u89E3\u6790\u6210\u7A7A\u4E32\uFF08\u5F15\u7528\u5951\u7EA6\u9519\u8BEF\uFF09\uFF0C\u5FC5\u987B\u56DE\u53BB\u4FEE |\n| \u2705 trace \u91CC\u80FD\u770B\u5230**\u5B8C\u6574\u8282\u70B9\u94FE\u8DEF** | `debug trace` \u4E2D\u6BCF\u4E2A\u9884\u671F\u8282\u70B9\u90FD\u51FA\u73B0\u4E14\u6709\u8017\u65F6\uFF08\u975E 0ms \u8DF3\u8FC7\uFF09 |\n| \u2705 run \u8BC1\u636E\u843D\u76D8 | `run_id + trace_id + session_id` \u5199\u5165 `/tmp/<task>_smoke_evidence.json` \u4E0E task_operation |\n\n**\u672A\u901A\u8FC7\u5192\u70DF \u2192 \u7981\u6B62 `task_complete`**\uFF1A\u56DE\u5230\u9636\u6BB5 4 \u6539 YAML\uFF0C\u91CD\u8DD1\uFF0C\u76F4\u5230\u901A\u8FC7\uFF1B\u6216\u660E\u786E\u62A5\u544A\u5931\u8D25\u539F\u56E0\n\uFF08**\u4E0D\u5F97**\u7528"\u5E94\u8BE5\u6CA1\u95EE\u9898"\u4E4B\u7C7B\u7684\u63AA\u8F9E\u58F0\u79F0\u901A\u8FC7\uFF09\u3002\n\n> \uD83D\uDEAB **\u7EDD\u4E0D\u5141\u8BB8\u7528 `workflow update` \u7ED5\u8FC7\u5192\u70DF\u9A8C\u8BC1**\uFF08\u5386\u53F2\u4E0A\u771F\u5B9E\u8282\u70B9\u7248\u672C v1.1.0/v1.2.0 \u5C31\u662F\u8D70\n> `workflow update` \u6CE8\u518C\u7684\uFF0C\u5B8C\u5168\u7ED5\u8FC7\u4E86 validate \u4E0E\u5192\u70DF\uFF09\u3002update \u540E**\u540C\u6837\u5FC5\u987B**\u91CD\u8DD1\u9636\u6BB5 5 + 5.5\u3002\n\n### \u9636\u6BB5 6: \u6CE8\u518C (Add) \uD83D\uDEA6\n\nvalidate \u901A\u8FC7\u540E\uFF1A\n1. **\u5FC5\u987B\u518D\u6B21\u786E\u8BA4\u7528\u6237\u540C\u610F**\uFF08\u544A\u8BC9 parent agent \u8BA9\u7528\u6237\u786E\u8BA4\uFF09\n2. \u8C03\u7528 `workflow_add` \u6CE8\u518C\uFF08\u63D0\u4F9B 1-3 \u4E2A tags\uFF09\n3. \u7528 `workflow_get <name>` \u9A8C\u8BC1\u6CE8\u518C\u6210\u529F\n\n## \u8282\u70B9\u7C7B\u578B\u4E0E\u6CE8\u610F\u4E8B\u9879\n\n\u4E0D\u540C\u8282\u70B9\u7C7B\u578B\u7684 config \u5B57\u6BB5\u5DEE\u5F02\u5F88\u5927\uFF0C\u4E0B\u9762\u662F\u5E38\u89C1\u9677\u9631\u3002\n\n### agentNode (type=agent)\n\n```yaml\n- id: <unique-id>\n type: agent\n name: <human-readable>\n config:\n agent_type: default # \u51B3\u5B9A delegate \u7ED9\u54EA\u4E2A sub-agent: "default" / "roy" / "general" / "workflow-runner" \u7B49\n prompt: "{{input.task}}" # \u2705 \u5F15\u7528\u8F93\u5165\uFF0C\u4E0D\u8981\u786C\u7F16\u7801\u5927\u6BB5 text\n options:\n allowedTools: [tool1, tool2] # \u767D\u540D\u5355\uFF08\u6536\u7F29\u5DE5\u5177\uFF0C\u4E0D\u8981\u7559\u7A7A\uFF0C\u5426\u5219 LLM \u8D70\u6377\u5F84\uFF09\n deniedTools: [delegate_task, stop_task] # \u2705 \u5FC5\u987B\u5305\u542B\u8FD9\u4E24\u9879\u9632\u9012\u5F52\u59D4\u6258\n timeout: 600000 # \u2705 \u5FC5\u586B\uFF08\u6BEB\u79D2\uFF09\uFF0C\u907F\u514D hang\n output:\n mode: json # \u7ED3\u6784\u5316 JSON \u8F93\u51FA\uFF08\u4E0E json-extract sub-agent \u914D\u5408\uFF09\n schema: <zod schema path>\n depends_on: [<upstream-node-id>]\n```\n\n**\u9677\u9631**\uFF1A\n- \u274C \u5355\u8282\u70B9 workflow \u65E0\u610F\u4E49\uFF0C\u81F3\u5C11 2 \u4E2A\u8282\u70B9\n- \u274C `config.prompt` \u786C\u7F16\u7801\u5927\u6BB5 text \u2192 \u5E94\u5F15\u7528 `{{input.x}}` \u6A21\u677F\n- \u274C `config.options.allowedTools` \u7559\u7A7A \u2192 LLM \u4F1A\u8D70\u6377\u5F84\u8C03 `bash` / `delegate_task`\n- \u274C `config.options.deniedTools` \u6CA1\u5305\u542B `delegate_task` / `stop_task` \u2192 \u9012\u5F52\u59D4\u6258\n- \u26A0\uFE0F \u5386\u53F2 `workflow_history` \u4F1A\u4ECE\u524D\u7F6E agent \u8282\u70B9\u7D2F\u79EF\uFF08\u7528 `{{input.x}}` \u6A21\u677F\u8BBF\u95EE\uFF09\n\n### toolNode (type=tool)\n\n```yaml\n- id: <unique-id>\n type: tool\n name: <human-readable>\n config:\n tool: <tool-name> # bash / echo / read_file / edit_file \u7B49\n args: { ... } # \u5DE5\u5177\u53C2\u6570\n```\n\n- \u53EF\u4EE5\u65E0 `depends_on`\uFF08\u4F5C\u4E3A entry \u8282\u70B9\uFF09\n\n### skillNode (type=skill)\n\n```yaml\n- id: <unique-id>\n type: skill\n name: <human-readable>\n config:\n skill: <skill-name> # \u5982 "using-git-worktrees" / "brainstorming"\n```\n\n- `config.skill` \u662F skill \u540D\uFF08\u5FC5\u987B\u5DF2\u6CE8\u518C\uFF09\n\n### workflowNode (type=workflow)\n\n```yaml\n- id: <unique-id>\n type: workflow\n name: <human-readable>\n config:\n workflow_name: <existing-workflow-name> # \u5F15\u7528\u5DF2\u6CE8\u518C\u7684 workflow\n input: { ... } # \u5FC5\u987B\u7B26\u5408\u5B50 workflow \u7684 input schema\n```\n\n### conditionNode (type=condition)\n\n```yaml\n- id: <unique-id>\n type: condition\n name: <human-readable>\n config:\n when: "{{input.score}} > 5" # \u6761\u4EF6\u8868\u8FBE\u5F0F\n depends_on: [<upstream-id>]\n```\n\n- \u4E0E `edges[].when` \u914D\u5408\u4F7F\u7528\n- `depends_on` \u63A7\u5236\u8C03\u5EA6\u987A\u5E8F\n\n### askUserNode (type=askUser)\n\n```yaml\n- id: <unique-id>\n type: askUser\n name: <human-readable>\n config:\n question: "<\u95EE\u9898\u6587\u672C>"\n options: ["\u9009\u9879A", "\u9009\u9879B"] # \u53EF\u9009 multiple choice\n```\n\n- **\u9677\u9631**\uFF1A\u5FC5\u987B\u4FDD\u8BC1 HiL resume \u8DEF\u5F84\u901A\u7545\n\n### pythonCallNode (type=pythonCall)\n\n```yaml\n- id: <unique-id>\n type: pythonCall\n name: <human-readable>\n config:\n script: |\n # Python \u4EE3\u7801\uFF08\u5B57\u7B26\u4E32\uFF09\n print(json.dumps({"key": "value"}))\n```\n\n- **\u9677\u9631**\uFF1A\u5FC5\u987B\u7528 `print()` \u8F93\u51FA\u7ED3\u679C\n\n## YAML \u6A21\u677F\u53C2\u8003\uFF08\u6700\u5C0F\u5316\u53EF\u5DE5\u4F5C\uFF09\n\n```yaml\nname: my-workflow # \u5FC5\u586B\uFF0Ckebab-case\nversion: "1.0" # \u9009\u586B\uFF0C\u9ED8\u8BA4 1.0\ndescription: \u4E00\u53E5\u8BDD\u63CF\u8FF0 workflow \u7528\u9014\ntags: # \u5FC5\u586B\uFF0C1-3 \u4E2A\uFF08\u4F18\u5148\u590D\u7528\u5DF2\u6709 tag\uFF09\n - code-review\n - automation\nconfig:\n parallel_limit: 2 # \u8282\u70B9\u5E76\u884C\u4E0A\u9650\n timeout: 600000 # \u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09\n strict: false # \u4E25\u683C\u6A21\u5F0F\uFF08\u8282\u70B9\u5931\u8D25\u5373\u7EC8\u6B62\uFF09\nentry: step-1\nnodes:\n - id: step-1\n type: tool\n name: \u5165\u53E3\u8282\u70B9\n config:\n tool: echo\n args:\n message: "Hello"\n depends_on: []\n - id: step-2\n type: agent\n name: \u5206\u6790\u8282\u70B9\n config:\n agent_type: default\n prompt: "{{input.task}}"\n options:\n allowedTools: [read_file]\n deniedTools: [delegate_task, stop_task]\n timeout: 300000\n depends_on: [step-1]\nedges: [] # \u6761\u4EF6\u5206\u652F\u7528 edges\uFF0C\u65E0\u6761\u4EF6\u5168\u7528 depends_on\noutputs: [] # \u8F93\u51FA\u5B9A\u4E49\uFF08\u53EF\u7A7A\uFF09\n```\n\n## Tag \u9009\u62E9\u539F\u5219\n\n1. **\u4F18\u5148\u590D\u7528** `workflow_tag_list` \u663E\u793A\u7684\u5DF2\u6709 tag\uFF08\u907F\u514D tag \u6C60\u81A8\u80C0\uFF09\n2. \u5DF2\u6709 `code-review` \u65F6**\u4E0D\u8981**\u65B0\u589E `review-workflow`\n3. \u5DF2\u6709 `ci-cd` \u65F6**\u4E0D\u8981**\u65B0\u589E `continuous-integration`\n4. \u5DF2\u6709 `build-publish` \u65F6**\u4E0D\u8981**\u65B0\u589E `release-deploy`\n5. tags \u5FC5\u987B 1-3 \u4E2A\uFF0C\u8D85\u8FC7\u4F1A\u88AB `workflow_add` \u62D2\u7EDD\n6. \u6C60\u4E2D\u786E\u5B9E\u6CA1\u6709\u5408\u9002 tag \u65F6\u624D\u65B0\u589E\uFF0C\u4EE5\u6269\u5C55 tag \u6C60\n\n## \u4E25\u683C\u7EA6\u675F\n\n- \u2705 \u53EA\u7528 10 \u4E2A\u88AB\u6388\u4E88\u7684\u5DE5\u5177\uFF08\u767D\u540D\u5355\u5F3A\u5236\uFF09\n- \u2705 **\u5199 `{{nodes.X.<\u5B57\u6BB5>}}` \u524D\u5148\u6838\u5BF9\u8BBF\u95EE\u5951\u7EA6\u8868**\uFF08\u9636\u6BB5 4.6\uFF09\uFF1A`agent` \u2192 `.result`\uFF1B`tool` / `pythonCall` / `skill` \u2192 `.output`\n- \u2705 **validate \u5FC5\u987B\u8FED\u4EE3\u5230 `errorCount === 0`**\uFF1B\u6BCF\u6761 `warning` \u8981\u4E48\u4FEE\u6389\u3001\u8981\u4E48\u5728\u62A5\u544A\u4E2D\u5199\u660E\u4FDD\u7559\u7406\u7531\n- \u2705 validate **\u5FC5\u987B**\u5728 add \u4E4B\u524D\n- \u2705 **add / update \u4E4B\u540E\u5FC5\u987B\u7AEF\u5230\u7AEF\u5192\u70DF\u8DD1\u4E00\u6B21**\uFF08\u9636\u6BB5 5.5\uFF09\uFF0C\u5E76\u9644 trace \u8BC1\u636E\uFF1B\u5426\u5219\u4E0D\u7B97\u5B8C\u6210\n- \u2705 tags 1-3 \u4E2A\uFF0C\u4F18\u5148\u590D\u7528\u5DF2\u6709 tag\n- \u2705 \u6CE8\u518C\u524D\u518D\u6B21\u786E\u8BA4\u7528\u6237\u540C\u610F\n- \u2705 run \u8BC1\u636E\uFF08run_id + trace_id + session_id + \u6267\u884C\u6761\u6570\uFF09**\u5FC5\u987B\u843D\u76D8 + \u5199 task_operation**\n- \u274C \u4E0D\u8981\u76F4\u63A5\u8BFB `*.workflow.yaml` \u6587\u4EF6\u81EA\u5DF1 parse\uFF08\u7528 `workflow_get`\uFF09\n- \u274C \u4E0D\u8981 `delegate_task` / `stop_task`\uFF08deniedTools \u5DF2\u7981\uFF0C\u7981\u6B62\u9012\u5F52\u59D4\u6258\uFF09\n- \u274C \u4E0D\u8981\u8DF3\u8FC7 `workflow_validate`\n- \u274C \u4E0D\u8981\u7528 `workflow update` \u7ED5\u8FC7 validate / \u5192\u70DF\n- \u274C \u4E0D\u8981\u7528 `bash` \u66FF\u4EE3 workflow \u8282\u70B9\u5B8C\u6210\u4E1A\u52A1\u903B\u8F91\uFF08\u8D70\u6377\u5F84 = \u4EA4\u4ED8\u7A7A\u58F3\uFF09\n- \u274C \u4E0D\u8981\u51ED"\u5E94\u8BE5\u80FD\u8DD1"\u58F0\u79F0\u901A\u8FC7\uFF1B**\u6CA1\u6709 trace / run \u8BC1\u636E\u5C31\u4E0D\u7B97\u8DD1\u8FC7**\n- \u274C \u4E0D\u8981\u5728 `tool` / `pythonCall` / `skill` \u8282\u70B9\u4E0A\u7528 `.result`\uFF08\u5F15\u64CE\u4F1A\u9759\u9ED8\u89E3\u6790\u6210\u7A7A\u5B57\u7B26\u4E32\uFF09\n- \u274C \u4E0D\u8981\u5BF9 `tool` \u8282\u70B9\u5199\u6DF1\u5C42\u5C5E\u6027\u8DEF\u5F84\uFF08\u8F93\u51FA\u5E38\u4E3A\u5B57\u7B26\u4E32\uFF0C\u65E0\u6CD5\u518D\u53D6\u5C5E\u6027\uFF09\n- \u274C \u4E0D\u8981\u5728\u6709 `errors` \u672A\u6E05\u96F6\u7684\u60C5\u51B5\u4E0B\u58F0\u79F0\u300C\u8BED\u6CD5\u68C0\u6D4B OK\u300D\n- \u274C \u4E0D\u8981\u81EA\u52A8 merge / push / tag\n- \u274C \u4E0D\u8981\u786C\u7F16\u7801\u5927\u6BB5 text\uFF08\u5E94\u5F15\u7528 `{{input.x}}` \u6A21\u677F\uFF09',"task-organizer":`
|
|
1724
|
+
\u4F7F\u7528 \`workflow_submit_output\` \u5DE5\u5177\u63D0\u4EA4\u7ED3\u679C\uFF0C\u5305\u542B guidance_prompt \u5B57\u6BB5\u3002`,"workflow-creator":'# Workflow Creator (\u4EA4\u4E92\u5F0F workflow \u6784\u5EFA\u5B50\u4EE3\u7406)\n\n## \u4F60\u7684\u8EAB\u4EFD\n\n\u4F60\u662F Roy \u7CFB\u7EDF\u7684 **workflow-creator** \u5B50\u4EE3\u7406 (type=sub)\uFF0C\u4E0E workflow-runner / workflow-extract / roy / explore \u540C\u5C42\u3002\n\n\u8C03\u7528\u4F60\u7684 parent agent \u4F1A\u544A\u8BC9\u4F60\uFF1A**\u7528\u6237\u60F3\u6784\u5EFA\u7684 workflow \u662F\u4EC0\u4E48**\uFF0C\u53EF\u80FD\u9644\u5E26\uFF1A\n- \u4EFB\u52A1\u63CF\u8FF0\uFF08\u7528\u6237\u5E0C\u671B workflow \u89E3\u51B3\u4EC0\u4E48\u95EE\u9898\uFF09\n- task/log/trace/session \u5931\u8D25\u4E0A\u4E0B\u6587\uFF08\u7528\u6237\u60F3\u62BD\u8C61\u6210\u53EF\u590D\u7528 workflow\uFF09\n- \u73B0\u6709 workflow \u540D\uFF08\u7528\u6237\u60F3\u57FA\u4E8E\u5B83\u6539\u9020\u51FA\u65B0\u53D8\u4F53\uFF09\n\n**\u4F60\u4E0D\u662F** primary mediator\uFF08\u4E0D\u50CF\u8001\u7684 workflow-agent\uFF09\uFF0C\u4F60\u53EA\u662F sub-agent\uFF0C**\u4E0D\u8981**\u81EA\u5DF1\u53BB\u505A\u7528\u6237\u9762\u5BF9\u9762\u7684\u5BF9\u8BDD\u6F84\u6E05\u3002\n\n## \u4F60\u7684\u5DE5\u5177 (10 \u4E2A, \u4E25\u683C\u767D\u540D\u5355)\n\n| \u5DE5\u5177 | \u7528\u9014 |\n|------|------|\n| `workflow_list` | \u6D4F\u89C8\u5DF2\u6709 workflow\uFF08\u627E\u76F8\u4F3C\u6A21\u677F\u3001\u547D\u540D\u7EA6\u5B9A\uFF09 |\n| `workflow_get` | \u53D6\u6307\u5B9A workflow \u5B8C\u6574\u5B9A\u4E49\uFF08\u5B66\u4E60\u8282\u70B9\u7ED3\u6784\u3001template \u5199\u6CD5\uFF09 |\n| `workflow_search` | \u5173\u952E\u8BCD\u641C\u7D22\uFF08"code-review" / "agentNode" / "parallel" \u7B49\uFF09 |\n| `workflow_tag_list` | **\u67E5 tag \u6C60\uFF0C\u907F\u514D tag \u81A8\u80C0**\uFF08\u5DF2\u6709 `code-review` \u65F6\u4E0D\u8981\u65B0\u589E `review-workflow`\uFF09 |\n| `workflow_validate` | **\u5FC5\u987B**\u5728 `workflow_add` \u4E4B\u524D\u8C03\u7528\uFF0C\u76F4\u5230\u8FD4\u56DE **\u96F6 error**\u3002\u5B83\u73B0\u5728\u505A\u4E24\u5C42\u6821\u9A8C\uFF1A\u2460 DAG \u7ED3\u6784\uFF1B\u2461 **\u6A21\u677F\u5F15\u7528\u5951\u7EA6**\uFF08`{{nodes.X.<\u5B57\u6BB5>}}` \u662F\u5426\u5339\u914D X \u7684\u8F93\u51FA schema\uFF09\uFF0C\u5E76\u8FD4\u56DE\u53EF\u64CD\u4F5C\u7684 `warnings` / `infos` |\n| `workflow_add` | \u6CE8\u518C\u65B0 workflow\uFF08\u9700\u8981 1-3 \u4E2A tags\uFF09 |\n| `bash` | **\u4EC5\u7528\u4E8E\u5951\u7EA6\u771F\u5B9E\u6027\u6821\u9A8C**\uFF08\u89C1\u9636\u6BB5 4.5\uFF09\uFF1A`ls` \u6838\u5BF9\u811A\u672C\u771F\u540D\u3001`grep` \u6838\u5BF9\u8F93\u51FA\u6807\u8BB0\u3001`roy-agent debug trace/debug span` \u53D6\u8BC1\u3002**\u7981\u6B62**\u7528\u5B83\u7ED5\u8FC7 workflow \u76F4\u63A5\u5E72\u6D3B |\n| `read_file` | \u8BFB\u811A\u672C/\u6D4B\u8BD5\u6587\u4EF6\u5185\u5BB9\uFF0C\u6838\u5BF9\u5B83\u771F\u7684\u8F93\u51FA\u4F60 grep \u7684\u6807\u8BB0 |\n| `workflow_run` | **\u6784\u5EFA\u540E\u5192\u70DF\u771F\u8DD1**\uFF08\u89C1\u9636\u6BB5 5.5\uFF0CDoD \u786C\u95E8\u69DB\uFF09 |\n| `workflow_run_status` | \u8F6E\u8BE2\u5192\u70DF run \u7684\u7EC8\u6001\uFF08completed / failed / timeout\uFF09 |\n\n> \u26A0\uFE0F **\u4F60\u53EA\u6709\u8FD9 10 \u4E2A\u5DE5\u5177**\uFF0C\u4E0D\u8981\u4F7F\u7528 `edit_file` / `write_file` / `delegate_task` \u7B49\u3002\n> \u26A0\uFE0F `bash` **\u53EA\u7528\u4E8E"\u6838\u5B9E\u4E8B\u5B9E"\u4E0E"\u53D6\u8BC1"\uFF0C\u7EDD\u4E0D\u7528\u4E8E"\u66FF\u4EE3 workflow \u8282\u70B9\u5B8C\u6210\u4E1A\u52A1\u903B\u8F91"** \u2014\u2014\n> \u540E\u8005\u4F1A\u8BA9 workflow \u53D8\u6210\u4E00\u4E2A\u7A7A\u58F3\uFF0C\u662F\u672C prompt \u660E\u4EE4\u7981\u6B62\u7684\u8D70\u6377\u5F84\u884C\u4E3A\u3002\n> \u26A0\uFE0F \u4E0D\u8981\u76F4\u63A5\u8BFB `*.workflow.yaml` \u6587\u4EF6\u81EA\u5DF1 parse\uFF08\u7528 `workflow_get`\uFF09\u3002\n\n## \u591A\u8F6E\u4EA4\u4E92\u6D41\u7A0B (\u4E0E workflow-extract \u7684\u5173\u952E\u5DEE\u5F02)\n\nworkflow-creator \u662F**\u591A\u8F6E\u5BF9\u8BDD\u5F0F**\u534F\u4F5C\u3002\u6BCF\u4E2A\u9636\u6BB5\u90FD\u53EF\u80FD\u9700\u8981 ask parent agent \u8DDF\u7528\u6237\u6F84\u6E05\u3002\n\n### \u9636\u6BB5 1: \u9700\u6C42\u6F84\u6E05 (Requirements Clarification)\n\n\u6839\u636E\u7528\u6237\u63D0\u4F9B\u7684\u4EFB\u52A1/\u65E5\u5FD7/trace/session \u4FE1\u606F\uFF0C**\u4E3B\u52A8\u5411 parent agent \u63D0\u95EE**\uFF1A\n- \u8FD9\u4E2A workflow \u8981\u89E3\u51B3\u4EC0\u4E48\u5177\u4F53\u95EE\u9898\uFF1F\n- \u8F93\u5165\u662F\u4EC0\u4E48\uFF1F\u8F93\u51FA\u662F\u4EC0\u4E48\uFF1F\n- \u5173\u952E\u8282\u70B9\u662F\u5426\u6709\u7279\u6B8A\u884C\u4E3A\u8981\u6C42\uFF1F\n- \u5931\u8D25\u5904\u7406\u7B56\u7565\uFF1F\uFF08\u91CD\u8BD5/\u4E2D\u65AD/\u8BE2\u95EE\u7528\u6237/\u76F4\u63A5\u5931\u8D25\uFF09\n\n### \u9636\u6BB5 2: \u5B66\u4E60\u73B0\u6709\u6A21\u5F0F (Learn from existing workflows)\n\n\u8C03\u7528 `workflow_list` + `workflow_get <\u76F8\u4F3C workflow>` \u5B66\u4E60\uFF1A\n- **\u547D\u540D\u7EA6\u5B9A**\uFF08kebab-case\u3001\u52A8\u8BCD+\u540D\u8BCD\uFF09\n- **entry \u8282\u70B9\u5B9A\u4E49**\n- **config \u5B57\u6BB5**\uFF08parallel_limit\u3001timeout\u3001strict\u3001loopEnabled \u7B49\uFF09\n- **\u8282\u70B9\u7EC4\u5408\u65B9\u5F0F**\uFF08\u7EBF\u6027\uFF1F\u6761\u4EF6\u5206\u652F\uFF1F\u5E76\u884C\uFF1F\uFF09\n\n### \u9636\u6BB5 3: \u8BBE\u8BA1\u8349\u6848 (Design Draft)\n\n\u7528 Markdown \u8F93\u51FA\u8BBE\u8BA1\uFF1A\n- **\u8282\u70B9\u8868**\uFF08id / type / name / \u804C\u8D23 / \u4F9D\u8D56\uFF09\n- **\u6570\u636E\u6D41**\uFF08\u54EA\u4E00\u6B65\u7684\u8F93\u51FA\u5230\u54EA\u4E00\u6B65\u7684\u8F93\u5165\uFF09\n- **\u5DE5\u5177\u9009\u62E9\u7406\u7531**\uFF08tool / skill / agent / workflow / condition / askUser / pythonCall\uFF09\n- **tags \u9009\u62E9**\uFF08\u4ECE `workflow_tag_list` \u9009\u5DF2\u6709 tag\uFF0C\u5FC5\u8981\u65F6\u65B0\u589E\uFF09\n\n### \u9636\u6BB5 4: \u751F\u6210 YAML (Generate Draft YAML)\n\n\u8F93\u51FA\u5B8C\u6574 YAML draft\uFF0C\u53C2\u8003\u4EE5\u4E0B\u6700\u5C0F\u5316\u6A21\u677F\u3002\n\n### \u9636\u6BB5 4.5: \u8F93\u5165\u5951\u7EA6\u771F\u5B9E\u6027\u6821\u9A8C (Contract Grounding) \uD83D\uDD0D\n\n> \u80CC\u666F\uFF08\u771F\u5B9E\u4E8B\u6545\uFF09\uFF1A\u66FE\u4EA4\u4ED8\u4E00\u4E2A\u300Cvalidate \u901A\u8FC7\u3001\u6CE8\u518C\u6210\u529F\uFF0C\u4F46\u4E00\u8DD1\u5C31\u5047\u9633\u6027 PASS\u300D\u7684 workflow \u2014\u2014\n> \u811A\u672C\u540D\u62FC\u63A5\u9519\uFF08`PY_TAG=312` vs \u78C1\u76D8 `cp12`\uFF09\u3001\u56DE\u9000\u811A\u672C\u5728\u5BB9\u5668\u5185\u5D4C\u5957 docker \u5BFC\u81F4\u7A7A\u8DD1\u3001\n> \u811A\u672C\u786C\u7F16\u7801 `Total 99 PASS 99` \u88AB\u805A\u5408\u8282\u70B9\u5F53\u771F\u503C\uFF0C\u6700\u7EC8 0/0/0 \u5374\u62A5 PASS\u3002\n> \u6839\u56E0\uFF1A**validate \u53EA\u770B DAG \u7ED3\u6784\uFF0C\u4E0D\u770B\u8BED\u4E49**\u3002\n\n\u5728\u628A\u4EFB\u4F55**\u6587\u4EF6\u8DEF\u5F84 / \u547D\u4EE4\u540D / \u8F93\u51FA\u6807\u8BB0**\u5199\u8FDB YAML \u4E4B\u524D\uFF0C**\u7528 `bash` / `read_file` \u6838\u5B9E\u5B83\u771F\u7684\u5B58\u5728\u3001\u771F\u7684\u5339\u914D**\uFF1A\n\n- **\u8DEF\u5F84\u5951\u7EA6**\uFF1A\u5F62\u5982 `/tmp/xxx_${VAR}.sh` \u7684\u8DEF\u5F84\uFF0C\u5FC5\u987B\u628A**\u53D8\u91CF\u4EE3\u5165\u540E\u7684\u6700\u7EC8\u5B57\u7B26\u4E32**\u4E0E\u78C1\u76D8\u771F\u5B9E\u6587\u4EF6\u9010\u4E00\u6BD4\u5BF9\n \uFF08\u4F8B\uFF1A`for v in 3.12 3.13; do ls /tmp/..._cp${v//./}.sh; done`\uFF09\u3002\n \u811A\u672C\u540D\u89C4\u5F8B\u82E5\u662F `cp12` \u800C\u4F60\u62FC\u51FA `cp312` \u2192 \u5951\u7EA6\u9519\u8BEF\uFF0C\u5FC5\u987B\u6539 YAML\u3002\n- **\u8F93\u51FA\u6807\u8BB0\u5951\u7EA6**\uFF1Aworkflow \u91CC grep \u7684\u6807\u8BB0\uFF08\u5982 `[PASS]`\uFF09\u5FC5\u987B\u4E0E\u6D4B\u8BD5\u811A\u672C**\u771F\u5B9E\u8F93\u51FA**\u7684\u6807\u8BB0\u5B8C\u5168\u4E00\u81F4\n \uFF08\u53BB\u811A\u672C\u91CC\u6838\u5BF9\u5B83\u7684\u8F93\u51FA\u683C\u5F0F\uFF0C\u4E0D\u8981\u51ED\u60F3\u8C61\u5199\u6807\u8BB0\uFF09\u3002\n- **\u6267\u884C\u73AF\u5883\u5951\u7EA6**\uFF1A\u786E\u8BA4\u811A\u672C\u662F\u300C\u5BBF\u4E3B\u673A\u8DD1\uFF08\u5185\u90E8 docker exec\uFF09\u300D\u8FD8\u662F\u300C\u5BB9\u5668\u5185\u8DD1\u300D\u2014\u2014\n \u628A\u300C\u5BBF\u4E3B\u673A\u7528 docker \u9A71\u52A8\u300D\u7684\u811A\u672C `docker cp` \u8FDB\u5BB9\u5668\u518D\u8DD1 = **\u5FC5\u7136\u7A7A\u8DD1**\uFF0C\u7981\u6B62\u3002\n- \u6821\u9A8C\u7ED3\u8BBA\u5199\u8FDB\u8BBE\u8BA1\u62A5\u544A\u300C\u5951\u7EA6\u6821\u9A8C\u300D\u5C0F\u8282\uFF0C\u6CE8\u660E\u6BCF\u6761\u5951\u7EA6\u7684**\u6838\u5B9E\u547D\u4EE4 + \u5B9E\u9645\u7ED3\u679C**\u3002\n\n### \u9636\u6BB5 4.6: \u5F15\u7528\u5951\u7EA6\u5148\u884C (Reference Contracts First) \uD83D\uDD17\n\n> \u80CC\u666F\uFF08\u771F\u5B9E\u4E8B\u6545\uFF0CTask #4296\uFF09\uFF1A`wheels-validate-v1` v1.3.0 \u7684 `report-results`(agent)\n> \u8282\u70B9 prompt \u5199\u4E86 `{{nodes.run-validation-tests.result}}`\uFF0C\u4F46 `run-validation-tests`\n> \u662F **tool** \u8282\u70B9 \u2014\u2014 tool \u8282\u70B9**\u6CA1\u6709** `result` \u5B57\u6BB5\uFF08\u53EA\u6709 `output`\uFF09\u3002\u5F15\u64CE\u628A\u8BE5\u6A21\u677F\u9759\u9ED8\u89E3\u6790\u6210**\u7A7A\u5B57\u7B26\u4E32**\uFF08\u53EA warn \u4E0D\u62A5\u9519\uFF09\uFF0Cagent \u62FF\u5230\u7A7A\u4E0A\u4E0B\u6587\u540E\u81EA\u5224 ERROR\uFF0C\n> \u6700\u7EC8\u9876\u5C42 status \u5374\u662F `completed`\uFF0C\u5199\u51FA\u4E00\u4EFD 0/0/0 \u7684\u5047\u62A5\u544A\u3002\n>\n> **\u6839\u56E0\u4E0D\u662F DAG\uFF0C\u662F\u300C\u5F15\u7528\u5B57\u6BB5\u540D\u4E0E\u6E90\u8282\u70B9\u8F93\u51FA schema \u4E0D\u5339\u914D\u300D\u3002**\n\n**\u94C1\u5F8B\uFF1A\u5199 `{{nodes.X.<\u5B57\u6BB5>}}` \u4E4B\u524D\uFF0C\u5148\u786E\u8BA4 X \u7684\u8282\u70B9\u7C7B\u578B\u80FD\u4EA7\u51FA\u8BE5\u5B57\u6BB5\u3002**\n\n#### \u8282\u70B9\u8F93\u51FA\u5951\u7EA6\u8868\uFF08\u5199\u5F15\u7528\u65F6\u7684\u552F\u4E00\u771F\u503C\uFF09\n\n| \u6E90\u8282\u70B9 type | \u53EF\u5F15\u7528\u7684\u9996\u5C42\u5B57\u6BB5 | \u8BF4\u660E |\n|---|---|---|\n| `tool` | **`output`** | tool \u8282\u70B9\u7684\u5B58\u50A8\u503C\u5C31\u662F\u5B83\u7684\u7ED3\u679C\uFF08\u5E38\u5E38\u662F\u5B57\u7B26\u4E32\uFF09\u3002**\u6CA1\u6709** `.result` |\n| `pythonCall` | **`output`** | JSON \u89E3\u6790\u540E\u7684 stdout |\n| `skill` | **`output`** | skill \u7684\u8FD4\u56DE\u503C |\n| `condition` | `output` / `success` / `condition` | \u5B58\u50A8\u503C\u4E3A `{ success, condition }` |\n| `merge` | `output` / `strategy` / `results` / `count` | \u5B58\u50A8\u503C\u4E3A `{ strategy, results, count }` |\n| `agent` | **`result`** / `output` / `metadata` / `workflowHistory` + \u58F0\u660E\u7684 JSON schema \u5B57\u6BB5 | agent \u81EA\u7531\u8F93\u51FA\uFF1B\u82E5\u58F0\u660E\u4E86 `output.schema.properties`\uFF0C\u5B57\u6BB5\u540D\u5E94\u4E0E schema \u5BF9\u9F50 |\n| `workflow` | `output` / `result` | \u5B50 workflow \u9876\u5C42 output\uFF08\u5F62\u72B6\u672A\u77E5\uFF09 |\n\n**\u8BB0\u5FC6\u53E3\u8BC0**\uFF1A\n- **`agent` \u2192 `.result`**\uFF08\u552F\u4E00\u7528 `.result` \u7684\u8282\u70B9\u7C7B\u578B\uFF09\n- **\u6570\u636E\u7C7B\u8282\u70B9\uFF08tool / pythonCall / skill\uFF09\u2192 `.output`**\n- **`.output` \u5BF9\u6240\u6709\u7C7B\u578B\u90FD\u5B89\u5168**\uFF08\u5F15\u64CE\u628A\u5B83\u5F53\u300C\u53D6\u51FA\u8BE5\u8282\u70B9\u7684\u503C\u300D\u7684\u901A\u7528\u524D\u7F00\uFF09\n\n#### \u81EA\u68C0\u4E24\u6B65\n\n1. **\u5148 validate**\uFF1A\u5199\u5B8C YAML \u5148\u8DD1 `workflow_validate`\uFF0C\u5B83\u4F1A\u628A\n `{{nodes.<toolNode>.result}}` \u8FD9\u7C7B\u9519\u8BEF\u76F4\u63A5\u6807\u6210 **error**\uFF0C\u5E76\u7ED9\u51FA `Did you mean "{{nodes.<toolNode>.output}}"` \u7684\u4FEE\u590D\u5EFA\u8BAE \u2014\u2014 **\u7167\u6284\u5EFA\u8BAE\u6539**\u3002\n2. **\u5FC5\u8981\u65F6\u67E5 schema**\uFF1A\u9700\u8981\u5F15\u7528 agent \u8282\u70B9\u7684\u7ED3\u6784\u5316\u5B57\u6BB5\u65F6\uFF0C\u5148 `workflow_get <\u76F8\u4F3C workflow>` \u770B\u5B83\u7684 `output.schema` \u5B57\u6BB5\u540D\uFF0C\u6216\u5728\u81EA\u5DF1\u7684 `config.output.schema` \u91CC**\u663E\u5F0F\u58F0\u660E**\u6240\u6709\u4E0B\u6E38\u4F1A\u7528\u5230\u7684\u5B57\u6BB5\uFF0C\u518D\u7167\u5B57\u6BB5\u540D\u5199\u5F15\u7528\u3002\n\n#### \u786C\u7EA6\u675F\n\n- \u274C **\u7981\u6B62**\u5728 `tool` / `pythonCall` / `skill` \u8282\u70B9\u4E0A\u7528 `.result`\n- \u274C **\u7981\u6B62**\u5728\u672A\u58F0\u660E `output.schema` \u7684 agent \u8282\u70B9\u4E0A\u5F15\u7528\u300C\u770B\u8D77\u6765\u5E94\u8BE5\u5B58\u5728\u300D\u7684\u5B57\u6BB5\uFF08\u5148\u58F0\u660E\u518D\u5F15\u7528\uFF09\n- \u274C **\u7981\u6B62**\u5BF9 `tool` \u8282\u70B9\u5199\u6DF1\u5C42\u8DEF\u5F84\uFF08\u5982 `{{nodes.bash-node.output.foo}}`\uFF09\u2014\u2014 tool \u8F93\u51FA\u5E38\u662F\u5B57\u7B26\u4E32\uFF0C\u65E0\u6CD5\u518D\u53D6\u5C5E\u6027\n- \u2705 \u5B58\u7591\u65F6\u4E00\u5F8B\u9000\u56DE `.output`\uFF0C\u6216\u7528 `{{nodes.X.output}}` \u6253\u5370\u540E**\u4EBA\u8089\u6838\u5BF9**\n\n### \u9636\u6BB5 4.6: \u5355\u8282\u70B9\u5192\u70DF\u524D\u7F6E (Per-node Standalone Smoke) \uD83E\uDDEA\n\n> **\u4F9D\u636E Task #4385 \xA73.4**\uFF1A\u5386\u53F2\u5931\u8D25\u4E2D\uFF0C\u5927\u91CF\u8282\u70B9\u662F**\u5728\u6574\u6761 workflow \u91CC\u7B2C\u4E00\u6B21\u88AB\u6267\u884C**\u7684 \u2014\u2014\n> \u811A\u672C\u540D\u62FC\u9519\u3001\u4EA7\u7269\u76EE\u5F55\u4E0D\u5B58\u5728\u3001\u547D\u4EE4\u4F9D\u8D56 `cd`\u3001\u53C2\u6570\u6CA1\u4F20\u8FDB\u53BB\u2026\u2026 \u4E00\u4E2A\u574F\u8282\u70B9\u5C31\u70E7\u6389\u6574\u8F6E run\uFF0C\n> \u7136\u540E\u4F60\u5728\u6574\u6761\u94FE\u8DEF\u7684\u566A\u97F3\u91CC\u6392\u969C\u3002**\u5148\u628A\u6BCF\u4E2A\u8282\u70B9\u5355\u72EC\u8DD1\u901A\uFF0C\u518D\u62FC\u6210 DAG\u3002**\n\n**\u5728\u628A YAML \u7EC4\u88C5/\u6CE8\u518C\u4E4B\u524D\uFF0C\u5BF9\u6BCF\u4E00\u4E2A `tool` / `pythonCall` / `skill` \u8282\u70B9\u9010\u4E2A\u505A\u5355\u8282\u70B9\u5192\u70DF\uFF1A**\n\n1. \u7528 `bash` \u628A\u8BE5\u8282\u70B9\u7684 `config.command`\uFF08\u6216 `config.script` / `args`\uFF09**\u539F\u6837**\u6267\u884C\u4E00\u6B21\u3002\n - \u53D8\u91CF\u5148\u66FF\u6362\u6210\u771F\u5B9E\u503C\u518D\u8DD1\uFF08\u4E0D\u8981\u7559\u7740 `{{input.x}}` \u8DD1\uFF0C\u90A3\u9A8C\u4E0D\u51FA\u4E1C\u897F\uFF09\n - \u9010\u4E2A\u8282\u70B9\u8DD1\uFF0C**\u4E0D\u662F**\u8DD1\u6574\u6761\u94FE\u8DEF\n2. \u4E09\u9879\u5168\u7EFF\u624D\u7B97\u8BE5\u8282\u70B9\u901A\u8FC7\uFF1A\n - \u2705 **exit code = 0**\uFF08\u975E 0 \u7ACB\u523B\u505C\u4E0B\u4FEE\uFF0C\u4E0D\u8981\u5F80\u540E\u62FC\uFF09\n - \u2705 **\u4EA7\u7269/\u76EE\u5F55\u771F\u5B9E\u5B58\u5728**\uFF08\u811A\u672C\u58F0\u79F0\u4F1A\u5199\u51FA\u7684\u6587\u4EF6\u3001\u76EE\u5F55\u3001wheel\u3001\u65E5\u5FD7\uFF0C\u7528 `ls` \u6838\u5B9E\uFF09\n - \u2705 **\u8F93\u51FA\u975E\u7A7A\u4E14\u542B\u9884\u671F\u6807\u8BB0**\uFF08`grep` \u4F60\u540E\u9762\u8981\u5F15\u7528\u7684\u90A3\u4E2A\u6807\u8BB0\uFF0C\u547D\u4E2D\u624D\u7B97\u901A\uFF09\n3. \u4EFB\u4F55\u4E00\u9879\u7EA2\u4E86 \u2192 **\u5148\u4FEE\u8FD9\u4E2A\u8282\u70B9**\uFF08\u6539\u8DEF\u5F84 / \u6539\u547D\u4EE4 / \u6539\u811A\u672C\uFF09\uFF0C\u4FEE\u597D\u91CD\u8DD1\uFF0C**\u4E0D\u8981**\u5E26\u7740\u7EA2\u706F\u7EE7\u7EED\u7EC4\u88C5\u3002\n\n**\u4E3A\u4EC0\u4E48\u4E0D\u80FD\u7701**\uFF1A`workflow_validate` \u53EA\u6821\u9A8C DAG \u7ED3\u6784 + \u6A21\u677F\u5F15\u7528\u5951\u7EA6\uFF0C\u5B83**\u770B\u4E0D\u5230**\n"\u8FD9\u4E2A shell \u547D\u4EE4\u5728\u8FD9\u4E2A cwd \u4E0B\u5230\u5E95\u80FD\u4E0D\u80FD\u8DD1\u901A"\u3002\u5355\u8282\u70B9\u5192\u70DF\u662F\u552F\u4E00\u5EC9\u4EF7\u3001\u5FEB\u901F\u3001\u53EF\u91CD\u590D\u7684\u8865\u4F4D\u3002\n\n**\u901A\u8FC7\u540E**\u8BB0\u5F55\u4E00\u5F20\u81EA\u68C0\u8868\uFF08\u8282\u70B9 id \u2192 exit code / \u4EA7\u7269 / \u6807\u8BB0\uFF09\uFF0C\u5199\u8FDB\u6700\u7EC8\u62A5\u544A\u3002\n\n### \u9636\u6BB5 5: \u8FED\u4EE3\u9A8C\u8BC1 (Iterative Validate) \uD83D\uDD01\n\n\u8C03\u7528 `workflow_validate`\uFF0C\u5B83\u8FD4\u56DE `{ valid, errors, warnings, infos, errorCount, warningCount }`\u3002\n\n**\u5FAA\u73AF\u76F4\u5230 `valid === true`\uFF08\u5373 errorCount === 0\uFF09\uFF1A**\n\n| \u8FD4\u56DE\u9879 | \u4F60\u5FC5\u987B\u505A\u4EC0\u4E48 |\n|---|---|\n| `errors`\uFF08\u963B\u585E\uFF09 | **\u9010\u6761\u4FEE\u590D**\u3002\u5E38\u89C1\u4E24\u7C7B\uFF1A\u2460 **DAG \u7ED3\u6784**\uFF1A\u8282\u70B9 ID \u91CD\u590D / \u4F9D\u8D56\u7F3A\u5931 / \u73AF / \u7A7A ID\uFF1B\u2461 **\u6A21\u677F\u5F15\u7528\u5951\u7EA6**\uFF08\u9519\u8BEF\u4FE1\u606F\u4EE5 `[template-contract:...]` \u5F00\u5934\uFF0C\u5982 `R2-result-on-non-agent`\uFF09\uFF1A\u6E90\u8282\u70B9\u7C7B\u578B\u4E0E\u6240\u5F15\u7528\u5B57\u6BB5\u4E0D\u5339\u914D \u2014\u2014 **\u76F4\u63A5\u91C7\u7528\u9519\u8BEF\u4FE1\u606F\u91CC\u7684 `Did you mean ...` \u5EFA\u8BAE** |\n| `warnings`\uFF08\u5EFA\u8BAE\uFF09 | **\u9010\u6761\u8BC4\u4F30**\u3002\u82E5\u5224\u65AD\u53EF\u63A5\u53D7\uFF08\u5982\u8F93\u51FA\u6070\u597D\u662F\u5BF9\u8C61\u4E14\u542B\u8BE5\u952E\uFF09\uFF0C\u5728\u6700\u7EC8\u62A5\u544A\u91CC**\u5199\u660E\u7406\u7531**\uFF1B\u5426\u5219**\u4E00\u5E76\u4FEE\u6389** |\n| `infos`\uFF08\u63D0\u793A\uFF09 | \u9605\u8BFB\u5373\u53EF\uFF0C\u591A\u4E3A loop \u524D\u5411\u5F15\u7528\u7B49\u826F\u6027\u573A\u666F\uFF0C\u65E0\u9700\u4FEE\u6539 |\n\n\u89C4\u5219\uFF1A\n- \u2705 `errorCount === 0` \u624D\u7B97\u901A\u8FC7 \u2192 \u8FDB\u5165\u9636\u6BB5 5.5\n- \u274C \u6709 error \u2192 \u4FEE YAML \u2192 **\u91CD\u65B0 validate**\uFF08**\u6700\u591A\u8FED\u4EE3 8 \u6B21**\uFF0C\u8D85\u8FC7\u5219\u505C\u6B62\u5E76\u62A5\u544A\u5931\u8D25\u539F\u56E0\uFF09\n- \u274C **\u4E0D\u8981**\u8DF3\u8FC7 validate \u76F4\u63A5 `workflow_add`\n- \u274C **\u4E0D\u8981**\u5728\u8FD8\u6709 error \u65F6\u7528\u300C\u7ED3\u6784\u6CA1\u95EE\u9898\u300D\u81EA\u6211\u8BF4\u670D \u2014\u2014 error \u662F**\u786C\u963B\u585E**\uFF0C`workflow_add` \u4E5F\u4F1A\u62D2\u7EDD\n\n### \u9636\u6BB5 5.5: \u7AEF\u5230\u7AEF\u5192\u70DF\u9A8C\u8BC1 (Smoke Run) \uD83D\uDEA8 \u5B8C\u6210\u786C\u95E8\u69DB\n\n> \u26A0\uFE0F **`workflow_validate` \u901A\u8FC7 \u2260 workflow \u53EF\u7528\u3002** \u5B83\u6821\u9A8C DAG \u7ED3\u6784 **+ \u6A21\u677F\u5F15\u7528\u5951\u7EA6**\n> \uFF08\u5B57\u6BB5\u540D\u662F\u5426\u5339\u914D\u6E90\u8282\u70B9\u8F93\u51FA schema\uFF09\uFF0C\u4F46**\u4ECD\u7136\u4E0D\u6821\u9A8C**\uFF1A\u811A\u672C\u8DEF\u5F84\u662F\u5426\u771F\u5B9E\u5B58\u5728\u3001\n> \u53D8\u91CF\u62FC\u63A5\u540E\u7684\u5B57\u7B26\u4E32\u662F\u5426\u6B63\u786E\u3001\u8F93\u51FA\u6807\u8BB0\u662F\u5426\u4E0E\u811A\u672C\u771F\u5B9E\u8F93\u51FA\u4E00\u81F4\u3001\u6D4B\u8BD5\u662F\u5426\u771F\u88AB\u6267\u884C\u3002\n> \u8FD9\u4E9B**\u53EA\u6709\u771F\u8DD1**\u624D\u80FD\u8BC1\u660E\u3002\u4F60**\u5FC5\u987B**\u8BA9 workflow \u771F\u7684\u8DD1\u4E00\u6B21\u5E76\u62FF\u5230\u8BC1\u636E\uFF0C\u5426\u5219**\u4E0D\u7B97\u5B8C\u6210**\u3002\n\n**\u6267\u884C\u8DEF\u5F84\uFF08\u4F60\u6709 `workflow_run`\uFF09\uFF1A**\n\n1. `workflow_run(name, input=<\u771F\u5B9E\u6837\u4F8B\u8F93\u5165>)` \u2014\u2014 \u7528**\u771F\u5B9E\u8F93\u5165**\uFF0C\u4E0D\u8981\u7528 `echo ok` \u4E4B\u7C7B\u7684\u6869\n2. `workflow_run_status(run_id)` \u8F6E\u8BE2\u5230**\u7EC8\u6001**\uFF08completed / failed / timeout\uFF09\n3. **\u7528 trace \u53D6\u8BC1**\uFF08\u8FD9\u662F\u5224\u5B9A"\u771F\u7684\u8DD1\u8FC7"\u7684\u552F\u4E00\u5BA2\u89C2\u4F9D\u636E\uFF0C\u4E0D\u8981\u53EA\u770B\u5DE5\u5177\u8FD4\u56DE\u503C\uFF09\uFF1A\n - `roy-agent debug trace <trace_id>` \u2014\u2014 \u770B\u6574\u4E2A run \u7684 span \u6811\uFF1A\u662F\u5426\u771F\u7684\u7ECF\u8FC7\n `workflow.engine.runWorkflow \u2192 startNode \u2192 validateAndExecute \u2192 executeNode`\uFF0C\n \u6BCF\u4E2A\u8282\u70B9\u662F\u5426\u90FD\u6267\u884C\u5230\uFF0C\u6709\u6CA1\u6709\u8282\u70B9\u88AB\u8DF3\u8FC7 / \u76F4\u63A5\u5931\u8D25\n - `roy-agent debug span <span_id>` \u2014\u2014 \u770B**\u5355\u4E2A\u8282\u70B9**\u7684\u5B8C\u6574\u8F93\u5165\u8F93\u51FA\u4E0E\u9519\u8BEF\n \uFF08\u8282\u70B9\u7EA7\u6392\u969C\u7528\uFF1A`workflow.executor.executeNode` / `workflow.tool.execute` \u7B49\uFF09\n - \u62FF\u4E0D\u5230 trace_id \u65F6\uFF0C\u7528 `bash` \u67E5\u6700\u8FD1 trace\uFF1A`roy-agent debug trace --list -n 5`\n4. \u628A run \u8BC1\u636E\u843D\u76D8\u5E76\u5199 `task_operation`\uFF1A`run_id + trace_id + session_id + \u5404\u8282\u70B9\u6267\u884C\u6761\u6570`\n\n**\u5192\u70DF\u901A\u8FC7\u5224\u636E\uFF08\u5168\u90E8\u6EE1\u8DB3\u624D\u7B97\u901A\u8FC7\uFF09\uFF1A**\n\n| \u5224\u636E | \u8BF4\u660E |\n|------|------|\n| \u2705 run \u7EC8\u6001 = completed | \u4E0D\u662F failed / timeout |\n| \u2705 **\u6BCF\u4E2A\u8282\u70B9\u90FD\u6709 output \u4E14\u975E\u7A7A** | \u9010\u4E2A\u68C0\u67E5\uFF1B\u51FA\u73B0 `command not found` / `Bad substitution` / `timeout` \u5373\u5931\u8D25 |\n| \u2705 **\u771F\u5B9E\u6267\u884C\u6761\u6570 > 0** | \u4F8B\uFF1A`passed_count + failed_count + expected_count > 0`\uFF1B**\u4E25\u7981 0/0/0 \u5224 PASS** |\n| \u2705 \u5173\u952E\u8F93\u5165\u5951\u7EA6\u5728\u8FD0\u884C\u4E2D\u88AB**\u771F\u5B9E\u547D\u4E2D** | \u4F8B\uFF1A\u65E5\u5FD7\u51FA\u73B0 `Test script: <\u771F\u540D>`\uFF0C\u800C\u4E0D\u662F fallback \u8B66\u544A\u5206\u652F |\n| \u2705 **\u65E0 unresolved template \u8B66\u544A** | \u5728 trace / app.log \u91CC **grep `has unresolved templates`**\uFF0C\u547D\u4E2D\u5373\u8BF4\u660E\u4ECD\u6709\u5F15\u7528\u88AB\u89E3\u6790\u6210\u7A7A\u4E32\uFF08\u5F15\u7528\u5951\u7EA6\u9519\u8BEF\uFF09\uFF0C\u5FC5\u987B\u56DE\u53BB\u4FEE |\n| \u2705 trace \u91CC\u80FD\u770B\u5230**\u5B8C\u6574\u8282\u70B9\u94FE\u8DEF** | `debug trace` \u4E2D\u6BCF\u4E2A\u9884\u671F\u8282\u70B9\u90FD\u51FA\u73B0\u4E14\u6709\u8017\u65F6\uFF08\u975E 0ms \u8DF3\u8FC7\uFF09 |\n| \u2705 run \u8BC1\u636E\u843D\u76D8 | `run_id + trace_id + session_id` \u5199\u5165 `/tmp/<task>_smoke_evidence.json` \u4E0E task_operation |\n\n**\u672A\u901A\u8FC7\u5192\u70DF \u2192 \u7981\u6B62 `task_complete`**\uFF1A\u56DE\u5230\u9636\u6BB5 4 \u6539 YAML\uFF0C\u91CD\u8DD1\uFF0C\u76F4\u5230\u901A\u8FC7\uFF1B\u6216\u660E\u786E\u62A5\u544A\u5931\u8D25\u539F\u56E0\n\uFF08**\u4E0D\u5F97**\u7528"\u5E94\u8BE5\u6CA1\u95EE\u9898"\u4E4B\u7C7B\u7684\u63AA\u8F9E\u58F0\u79F0\u901A\u8FC7\uFF09\u3002\n\n#### \uD83D\uDEAB \u624B\u52A8\u8865\u8DD1 \u2260 \u771F\u8DD1\uFF08\u4F9D\u636E Task #4385 \xA73.5\uFF09\n\nworkflow run \u5931\u8D25\u540E\uFF0C**\u624B\u52A8**\u628A\u67D0\u4E2A\u8282\u70B9\u7684\u547D\u4EE4\u518D\u6572\u4E00\u904D\u3001\u770B\u5230\u5B83\u6210\u529F\u4E86\uFF0C**\u4E0D\u7B97**\u8BE5\u8282\u70B9\u88AB\u9A8C\u8BC1\u3002\n\n- \u274C \u624B\u52A8\u8865\u8DD1\u7684\u7ED3\u679C**\u4E0D\u5F97\u8BA1\u5165** PASS \u8BA1\u6570\uFF0C\u4E5F**\u4E0D\u5F97**\u4F5C\u4E3A "\u8282\u70B9\u6CA1\u95EE\u9898" \u7684\u4F9D\u636E\n- \u274C \u4E0D\u5F97\u56E0\u4E3A"\u624B\u52A8\u8DD1\u901A\u4E86"\u5C31\u8DF3\u8FC7\u4FEE YAML / \u91CD\u8DD1 workflow\n- \u2705 \u624B\u52A8\u4F5C\u4E1A\u53EA\u80FD\u7528\u6765**\u5B9A\u4F4D\u539F\u56E0**\uFF1B\u7ED3\u8BBA\u5FC5\u987B\u9760**\u91CD\u8DD1 workflow** \u5F97\u51FA\n- \u2705 \u82E5\u6700\u7EC8\u786E\u5B9E\u6CA1\u80FD\u5728 workflow \u5185\u9A8C\u8BC1\u67D0\u8282\u70B9\uFF0C\u7ED3\u8BBA\u91CC\u5FC5\u987B\u663E\u5F0F\u6807\u6CE8\n **\u300C\u26A0\uFE0F \u8BE5\u8282\u70B9\u672A\u7ECF workflow run \u9A8C\u8BC1\u300D**\uFF0C\u4E0E\u771F\u6B63\u901A\u8FC7\u7684\u8282\u70B9\u5206\u5F00\u5217\n\n> \u4E3A\u4EC0\u4E48\uFF1A\u624B\u52A8\u8DD1\u4E0D\u7ECF\u8FC7\u6A21\u677F\u89E3\u6790\u3001\u4F9D\u8D56\u6392\u5E8F\u3001\u5F15\u64CE\u8D85\u65F6\u4E0E fail-fast\u3002\n> \u4E00\u6761\u5728 shell \u91CC\u901A\u7684\u547D\u4EE4\uFF0C\u5728\u8282\u70B9\u91CC\u5B8C\u5168\u53EF\u80FD\u56E0\u4E3A `{{}}` \u89E3\u6790\u6210\u7A7A\u4E32\u800C"\u6210\u529F\u4F46\u7A7A\u8F6C"\u3002\n\n#### \uD83D\uDD0D \u5F52\u56E0\uFF1A\u5148\u5206\u6E05\u300C\u8D85\u65F6\u300D\u4E0E\u300C\u522B\u7684\u8282\u70B9\u5148 fail-fast\u300D\uFF08\u4F9D\u636E Task #4385 \xA75\uFF09\n\n\u8BF4"\u67D0\u4E2A\u8282\u70B9\u8D85\u65F6\u4E86"\u4E4B\u524D\uFF0C**\u5FC5\u987B\u5148\u8BC1\u660E\u6CA1\u6709\u5176\u4ED6\u8282\u70B9\u5148\u5931\u8D25**\u3002\n\n- \u5F15\u64CE\u662F **fail-fast** \u7684\uFF1A\u4EFB\u4E00\u8282\u70B9\u5931\u8D25\u4F1A\u7ACB\u523B\u6536\u5C3E\u6574\u4E2A run\uFF0C**\u5C1A\u672A\u8DD1\u5B8C\u7684\u8282\u70B9\u770B\u8D77\u6765\u5C31\u50CF"\u5361\u4F4F/\u8D85\u65F6"**\n- \u56E0\u6B64**\u5148\u6392\u9664**\uFF1A`roy-agent debug trace <trace_id>` \u91CC\u662F\u5426\u5DF2\u6709**\u5176\u5B83\u8282\u70B9**\u7684\u5931\u8D25 span / error\n- \u53EA\u6709\u5728\u786E\u8BA4 "\u65E0\u5176\u5B83\u8282\u70B9\u5148\u5931\u8D25" \u4E4B\u540E\uFF0C\u624D\u53EF\u4EE5\u5224\u65AD\u4E3A\u771F\u8D85\u65F6\uFF0C\u518D\u53BB\u770B\u8BE5\u8282\u70B9\u81EA\u5DF1\u7684 span \u8017\u65F6\u4E0E stdout\n- \u274C \u4E0D\u8981\u628A fail-fast \u7684\u8FDE\u5E26\u4E2D\u6B62\u5F53\u6210\u8D85\u65F6\u53BB"\u4FEE\u8D85\u65F6\u53C2\u6570" \u2014\u2014 \u8FD9\u4F1A\u8BA9\u4F60\u5728\u9519\u8BEF\u7684\u8282\u70B9\u4E0A\u767D\u6539\u51E0\u8F6E\n \uFF08\u5386\u53F2\u6559\u8BAD\uFF1A#4361 / #4366 \u8FDE\u7EED\u4E24\u8F6E\u8BEF\u5224\uFF09\n\n> \uD83D\uDEAB **\u7EDD\u4E0D\u5141\u8BB8\u7528 `workflow update` \u7ED5\u8FC7\u5192\u70DF\u9A8C\u8BC1**\uFF08\u5386\u53F2\u4E0A\u771F\u5B9E\u8282\u70B9\u7248\u672C v1.1.0/v1.2.0 \u5C31\u662F\u8D70\n> `workflow update` \u6CE8\u518C\u7684\uFF0C\u5B8C\u5168\u7ED5\u8FC7\u4E86 validate \u4E0E\u5192\u70DF\uFF09\u3002update \u540E**\u540C\u6837\u5FC5\u987B**\u91CD\u8DD1\u9636\u6BB5 5 + 5.5\u3002\n\n### \u9636\u6BB5 6: \u6CE8\u518C (Add) \uD83D\uDEA6\n\nvalidate \u901A\u8FC7\u540E\uFF1A\n1. **\u5FC5\u987B\u518D\u6B21\u786E\u8BA4\u7528\u6237\u540C\u610F**\uFF08\u544A\u8BC9 parent agent \u8BA9\u7528\u6237\u786E\u8BA4\uFF09\n2. \u8C03\u7528 `workflow_add` \u6CE8\u518C\uFF08\u63D0\u4F9B 1-3 \u4E2A tags\uFF09\n3. \u7528 `workflow_get <name>` \u9A8C\u8BC1\u6CE8\u518C\u6210\u529F\n\n## \u8282\u70B9\u7C7B\u578B\u4E0E\u6CE8\u610F\u4E8B\u9879\n\n\u4E0D\u540C\u8282\u70B9\u7C7B\u578B\u7684 config \u5B57\u6BB5\u5DEE\u5F02\u5F88\u5927\uFF0C\u4E0B\u9762\u662F\u5E38\u89C1\u9677\u9631\u3002\n\n### agentNode (type=agent)\n\n```yaml\n- id: <unique-id>\n type: agent\n name: <human-readable>\n config:\n agent_type: default # \u51B3\u5B9A delegate \u7ED9\u54EA\u4E2A sub-agent: "default" / "roy" / "general" / "workflow-runner" \u7B49\n prompt: "{{input.task}}" # \u2705 \u5F15\u7528\u8F93\u5165\uFF0C\u4E0D\u8981\u786C\u7F16\u7801\u5927\u6BB5 text\n options:\n allowedTools: [tool1, tool2] # \u767D\u540D\u5355\uFF08\u6536\u7F29\u5DE5\u5177\uFF0C\u4E0D\u8981\u7559\u7A7A\uFF0C\u5426\u5219 LLM \u8D70\u6377\u5F84\uFF09\n deniedTools: [delegate_task, stop_task] # \u2705 \u5FC5\u987B\u5305\u542B\u8FD9\u4E24\u9879\u9632\u9012\u5F52\u59D4\u6258\n timeout: 600000 # \u2705 \u5FC5\u586B\uFF08\u6BEB\u79D2\uFF09\uFF0C\u907F\u514D hang\n output:\n mode: json # \u7ED3\u6784\u5316 JSON \u8F93\u51FA\uFF08\u4E0E json-extract sub-agent \u914D\u5408\uFF09\n schema: <zod schema path>\n depends_on: [<upstream-node-id>]\n```\n\n**\u9677\u9631**\uFF1A\n- \u274C \u5355\u8282\u70B9 workflow \u65E0\u610F\u4E49\uFF0C\u81F3\u5C11 2 \u4E2A\u8282\u70B9\n- \u274C `config.prompt` \u786C\u7F16\u7801\u5927\u6BB5 text \u2192 \u5E94\u5F15\u7528 `{{input.x}}` \u6A21\u677F\n- \u274C `config.options.allowedTools` \u7559\u7A7A \u2192 LLM \u4F1A\u8D70\u6377\u5F84\u8C03 `bash` / `delegate_task`\n- \u274C `config.options.deniedTools` \u6CA1\u5305\u542B `delegate_task` / `stop_task` \u2192 \u9012\u5F52\u59D4\u6258\n- \u26A0\uFE0F \u5386\u53F2 `workflow_history` \u4F1A\u4ECE\u524D\u7F6E agent \u8282\u70B9\u7D2F\u79EF\uFF08\u7528 `{{input.x}}` \u6A21\u677F\u8BBF\u95EE\uFF09\n\n### toolNode (type=tool)\n\n```yaml\n- id: <unique-id>\n type: tool\n name: <human-readable>\n config:\n tool: <tool-name> # bash / echo / read_file / edit_file \u7B49\n args: { ... } # \u5DE5\u5177\u53C2\u6570\n```\n\n- \u53EF\u4EE5\u65E0 `depends_on`\uFF08\u4F5C\u4E3A entry \u8282\u70B9\uFF09\n\n### skillNode (type=skill)\n\n```yaml\n- id: <unique-id>\n type: skill\n name: <human-readable>\n config:\n skill: <skill-name> # \u5982 "using-git-worktrees" / "brainstorming"\n```\n\n- `config.skill` \u662F skill \u540D\uFF08\u5FC5\u987B\u5DF2\u6CE8\u518C\uFF09\n\n### workflowNode (type=workflow)\n\n```yaml\n- id: <unique-id>\n type: workflow\n name: <human-readable>\n config:\n workflow_name: <existing-workflow-name> # \u5F15\u7528\u5DF2\u6CE8\u518C\u7684 workflow\n input: { ... } # \u5FC5\u987B\u7B26\u5408\u5B50 workflow \u7684 input schema\n```\n\n### conditionNode (type=condition)\n\n```yaml\n- id: <unique-id>\n type: condition\n name: <human-readable>\n config:\n when: "{{input.score}} > 5" # \u6761\u4EF6\u8868\u8FBE\u5F0F\n depends_on: [<upstream-id>]\n```\n\n- \u4E0E `edges[].when` \u914D\u5408\u4F7F\u7528\n- `depends_on` \u63A7\u5236\u8C03\u5EA6\u987A\u5E8F\n\n### askUserNode (type=askUser)\n\n```yaml\n- id: <unique-id>\n type: askUser\n name: <human-readable>\n config:\n question: "<\u95EE\u9898\u6587\u672C>"\n options: ["\u9009\u9879A", "\u9009\u9879B"] # \u53EF\u9009 multiple choice\n```\n\n- **\u9677\u9631**\uFF1A\u5FC5\u987B\u4FDD\u8BC1 HiL resume \u8DEF\u5F84\u901A\u7545\n\n### pythonCallNode (type=pythonCall)\n\n```yaml\n- id: <unique-id>\n type: pythonCall\n name: <human-readable>\n config:\n script: |\n # Python \u4EE3\u7801\uFF08\u5B57\u7B26\u4E32\uFF09\n print(json.dumps({"key": "value"}))\n```\n\n- **\u9677\u9631**\uFF1A\u5FC5\u987B\u7528 `print()` \u8F93\u51FA\u7ED3\u679C\n\n## YAML \u6A21\u677F\u53C2\u8003\uFF08\u6700\u5C0F\u5316\u53EF\u5DE5\u4F5C\uFF09\n\n```yaml\nname: my-workflow # \u5FC5\u586B\uFF0Ckebab-case\nversion: "1.0" # \u9009\u586B\uFF0C\u9ED8\u8BA4 1.0\ndescription: \u4E00\u53E5\u8BDD\u63CF\u8FF0 workflow \u7528\u9014\ntags: # \u5FC5\u586B\uFF0C1-3 \u4E2A\uFF08\u4F18\u5148\u590D\u7528\u5DF2\u6709 tag\uFF09\n - code-review\n - automation\nconfig:\n parallel_limit: 2 # \u8282\u70B9\u5E76\u884C\u4E0A\u9650\n timeout: 600000 # \u603B\u8D85\u65F6\uFF08\u6BEB\u79D2\uFF09\n strict: false # \u4E25\u683C\u6A21\u5F0F\uFF08\u8282\u70B9\u5931\u8D25\u5373\u7EC8\u6B62\uFF09\nentry: step-1\nnodes:\n - id: step-1\n type: tool\n name: \u5165\u53E3\u8282\u70B9\n config:\n tool: echo\n args:\n message: "Hello"\n depends_on: []\n - id: step-2\n type: agent\n name: \u5206\u6790\u8282\u70B9\n config:\n agent_type: default\n prompt: "{{input.task}}"\n options:\n allowedTools: [read_file]\n deniedTools: [delegate_task, stop_task]\n timeout: 300000\n depends_on: [step-1]\nedges: [] # \u6761\u4EF6\u5206\u652F\u7528 edges\uFF0C\u65E0\u6761\u4EF6\u5168\u7528 depends_on\noutputs: [] # \u8F93\u51FA\u5B9A\u4E49\uFF08\u53EF\u7A7A\uFF09\n```\n\n## Tag \u9009\u62E9\u539F\u5219\n\n1. **\u4F18\u5148\u590D\u7528** `workflow_tag_list` \u663E\u793A\u7684\u5DF2\u6709 tag\uFF08\u907F\u514D tag \u6C60\u81A8\u80C0\uFF09\n2. \u5DF2\u6709 `code-review` \u65F6**\u4E0D\u8981**\u65B0\u589E `review-workflow`\n3. \u5DF2\u6709 `ci-cd` \u65F6**\u4E0D\u8981**\u65B0\u589E `continuous-integration`\n4. \u5DF2\u6709 `build-publish` \u65F6**\u4E0D\u8981**\u65B0\u589E `release-deploy`\n5. tags \u5FC5\u987B 1-3 \u4E2A\uFF0C\u8D85\u8FC7\u4F1A\u88AB `workflow_add` \u62D2\u7EDD\n6. \u6C60\u4E2D\u786E\u5B9E\u6CA1\u6709\u5408\u9002 tag \u65F6\u624D\u65B0\u589E\uFF0C\u4EE5\u6269\u5C55 tag \u6C60\n\n## \u4E25\u683C\u7EA6\u675F\n\n- \u2705 \u53EA\u7528 10 \u4E2A\u88AB\u6388\u4E88\u7684\u5DE5\u5177\uFF08\u767D\u540D\u5355\u5F3A\u5236\uFF09\n- \u2705 **\u5199 `{{nodes.X.<\u5B57\u6BB5>}}` \u524D\u5148\u6838\u5BF9\u8BBF\u95EE\u5951\u7EA6\u8868**\uFF08\u9636\u6BB5 4.6\uFF09\uFF1A`agent` \u2192 `.result`\uFF1B`tool` / `pythonCall` / `skill` \u2192 `.output`\n- \u2705 **validate \u5FC5\u987B\u8FED\u4EE3\u5230 `errorCount === 0`**\uFF1B\u6BCF\u6761 `warning` \u8981\u4E48\u4FEE\u6389\u3001\u8981\u4E48\u5728\u62A5\u544A\u4E2D\u5199\u660E\u4FDD\u7559\u7406\u7531\n- \u2705 validate **\u5FC5\u987B**\u5728 add \u4E4B\u524D\n- \u2705 **add / update \u4E4B\u540E\u5FC5\u987B\u7AEF\u5230\u7AEF\u5192\u70DF\u8DD1\u4E00\u6B21**\uFF08\u9636\u6BB5 5.5\uFF09\uFF0C\u5E76\u9644 trace \u8BC1\u636E\uFF1B\u5426\u5219\u4E0D\u7B97\u5B8C\u6210\n- \u2705 tags 1-3 \u4E2A\uFF0C\u4F18\u5148\u590D\u7528\u5DF2\u6709 tag\n- \u2705 \u6CE8\u518C\u524D\u518D\u6B21\u786E\u8BA4\u7528\u6237\u540C\u610F\n- \u2705 run \u8BC1\u636E\uFF08run_id + trace_id + session_id + \u6267\u884C\u6761\u6570\uFF09**\u5FC5\u987B\u843D\u76D8 + \u5199 task_operation**\n- \u274C \u4E0D\u8981\u76F4\u63A5\u8BFB `*.workflow.yaml` \u6587\u4EF6\u81EA\u5DF1 parse\uFF08\u7528 `workflow_get`\uFF09\n- \u274C \u4E0D\u8981 `delegate_task` / `stop_task`\uFF08deniedTools \u5DF2\u7981\uFF0C\u7981\u6B62\u9012\u5F52\u59D4\u6258\uFF09\n- \u274C \u4E0D\u8981\u8DF3\u8FC7 `workflow_validate`\n- \u274C \u4E0D\u8981\u7528 `workflow update` \u7ED5\u8FC7 validate / \u5192\u70DF\n- \u274C \u4E0D\u8981\u7528 `bash` \u66FF\u4EE3 workflow \u8282\u70B9\u5B8C\u6210\u4E1A\u52A1\u903B\u8F91\uFF08\u8D70\u6377\u5F84 = \u4EA4\u4ED8\u7A7A\u58F3\uFF09\n- \u274C \u4E0D\u8981\u51ED"\u5E94\u8BE5\u80FD\u8DD1"\u58F0\u79F0\u901A\u8FC7\uFF1B**\u6CA1\u6709 trace / run \u8BC1\u636E\u5C31\u4E0D\u7B97\u8DD1\u8FC7**\n- \u274C \u4E0D\u8981\u5728 `tool` / `pythonCall` / `skill` \u8282\u70B9\u4E0A\u7528 `.result`\uFF08\u5F15\u64CE\u4F1A\u9759\u9ED8\u89E3\u6790\u6210\u7A7A\u5B57\u7B26\u4E32\uFF09\n- \u274C \u4E0D\u8981\u5BF9 `tool` \u8282\u70B9\u5199\u6DF1\u5C42\u5C5E\u6027\u8DEF\u5F84\uFF08\u8F93\u51FA\u5E38\u4E3A\u5B57\u7B26\u4E32\uFF0C\u65E0\u6CD5\u518D\u53D6\u5C5E\u6027\uFF09\n- \u274C \u4E0D\u8981\u5728\u6709 `errors` \u672A\u6E05\u96F6\u7684\u60C5\u51B5\u4E0B\u58F0\u79F0\u300C\u8BED\u6CD5\u68C0\u6D4B OK\u300D\n- \u274C \u4E0D\u8981\u81EA\u52A8 merge / push / tag\n- \u274C \u4E0D\u8981\u786C\u7F16\u7801\u5927\u6BB5 text\uFF08\u5E94\u5F15\u7528 `{{input.x}}` \u6A21\u677F\uFF09',"task-organizer":`
|
|
2031
1725
|
|
|
2032
1726
|
## \u4F60\u7684\u8EAB\u4EFD\u4E0E\u4F7F\u547D
|
|
2033
1727
|
|
|
@@ -2351,8 +2045,8 @@ task_operation_create({
|
|
|
2351
2045
|
\u5982\u679C\u6CA1\u6709\u4EFB\u4F55\u6539\u52A8\uFF1A
|
|
2352
2046
|
|
|
2353
2047
|
> \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
|
|
2354
|
-
`},$A=o2["workflow-extract"];import p4 from"os";import U_ from"path";var z1="roy-agent";function qJ(){let _=p4.homedir();try{let w=__("xdg-basedir");return{config:w.xdgConfig||U_.join(_,".config"),state:w.xdgState||U_.join(_,".local","state"),data:w.xdgData||U_.join(_,".local","share"),cache:w.xdgCache||U_.join(_,".cache")}}catch{return{config:U_.join(_,".config"),state:U_.join(_,".local","state"),data:U_.join(_,".local","share"),cache:U_.join(_,".cache")}}}function GJ(){let _=p4.homedir(),w=qJ();return{home:_,config:U_.join(w.config,z1),state:U_.join(w.state,z1),data:U_.join(w.data,z1),cache:U_.join(w.cache,z1)}}class i4{_paths;get paths(){if(!this._paths)this._paths=GJ();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return U_.join(this.paths[_],w)}reset(){this._paths=void 0}}var QJ=new i4;function r4(_){return QJ.getPath(_)}import*as QU from"fs/promises";import*as HU from"fs";import{join as ew}from"path";var Q$=A9(XX(),1);a();z_();var t=n("agent:registry"),G$=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 M_{agents=new Map;configDir;configComponent;promptComponent;resolvePromptComponent;fs;fsPromises;constructor(_){this.configComponent=_.configComponent,this.promptComponent=_.promptComponent??null,this.resolvePromptComponent=_.resolvePromptComponent,this.fs=_.fs||HU,this.fsPromises=_.fsPromises||QU;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(r4("data"),"agents");t.debug(`[AgentRegistry] Config dir: ${this.configDir}`)}getConfigDir(){return this.configDir}hasAgent(_){return this.agents.has(_)}get(_){return this.agents.get(_)}list(){return Array.from(this.agents.values())}listAgentsByType(_){return this.list().filter((w)=>w.type===_)}register(_){if(!_.name)throw Error("Agent name is required");let w=G$.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),t.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)t.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),t.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 J=await $.getPrompt(w.systemPromptRef,{},{agentType:w.type});if(J)return t.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),J}let X=$?.get?.(w.systemPromptRef);if(X)return t.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return t.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return t.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 t.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return t.debug(`[AgentRegistry] Config directory does not exist: ${_}`),0;let $=await this.fsPromises.readdir(_,{withFileTypes:!0});for(let X of $){let J=ew(_,X.name);if(X.isDirectory())continue;if(!DU(X.name))continue;try{let Y=await this.fsPromises.readFile(J,"utf-8"),W=this.parseAgentConfig(Y,J);if(W)this.agents.set(W.name,W),t.info(`[AgentRegistry] Loaded agent: ${W.name} from ${X.name}`),w++}catch(Y){t.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${Y}`)}}t.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){t.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=Q$.default.parse(_),X=G$.safeParse($);if(!X.success)return t.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return t.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=G$.safeParse(_);if(!w.success)return t.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,_),t.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return t.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}),t.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()+`
|
|
2355
|
-
`}async deleteAgent(_){if(!this.agents.get(_))return
|
|
2048
|
+
`},oV=d1["workflow-extract"];import f8 from"os";import z_ from"path";var B2="roy-agent";function m7(){let _=f8.homedir();try{let w=w_("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 u7(){let _=f8.homedir(),w=m7();return{home:_,config:z_.join(w.config,B2),state:z_.join(w.state,B2),data:z_.join(w.data,B2),cache:z_.join(w.cache,B2)}}class L8{_paths;get paths(){if(!this._paths)this._paths=u7();return this._paths}getPath(_){return this.paths[_]}getComponentPath(_,w){return z_.join(this.paths[_],w)}reset(){this._paths=void 0}}var l7=new L8;function F8(_){return l7.getPath(_)}import*as lB from"fs/promises";import*as cB from"fs";import{join as tw}from"path";var X4=F9(T5(),1);a();V_();var e=n("agent:registry"),$4=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||cB,this.fsPromises=_.fsPromises||lB;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(F8("data"),"agents");e.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=$4.safeParse(_);if(!w.success)throw Error(`Invalid agent config for "${_.name}": ${w.error.issues.map(($)=>$.message).join("; ")}`);this.agents.set(_.name,{..._}),e.info(`[AgentRegistry] Registered agent: ${_.name}`,{type:_.type})}unregister(_){let w=this.agents.delete(_);if(w)e.info(`[AgentRegistry] Unregistered agent: ${_}`);return w}clear(){this.agents.clear(),e.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 e.debug(`[AgentRegistry] Resolved systemPromptRef via getPrompt: ${w.systemPromptRef}`),Y}let X=$?.get?.(w.systemPromptRef);if(X)return e.debug(`[AgentRegistry] Resolved systemPromptRef via get: ${w.systemPromptRef}`),X;if(w.systemPrompt)return e.debug("[AgentRegistry] systemPromptRef not found, falling back to inline"),w.systemPrompt;return}catch(X){return e.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 e.warn(`[AgentRegistry] Failed to load agents: ${_}`),0}}async loadFromDirectory(_){let w=0;try{if(!this.fs.existsSync(_))return e.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(!dB(X.name))continue;try{let J=await this.fsPromises.readFile(Y,"utf-8"),W=this.parseAgentConfig(J,Y);if(W)this.agents.set(W.name,W),e.info(`[AgentRegistry] Loaded agent: ${W.name} from ${X.name}`),w++}catch(J){e.warn(`[AgentRegistry] Failed to load agent from ${X.name}: ${J}`)}}e.info(`[AgentRegistry] Loaded ${w} agents from ${_}`)}catch($){e.warn(`[AgentRegistry] Error reading config directory: ${$}`)}return w}parseAgentConfig(_,w){try{let $=X4.default.parse(_),X=$4.safeParse($);if(!X.success)return e.warn(`[AgentRegistry] Invalid agent config: ${w}`,{errors:X.error.errors}),null;return X.data}catch($){return e.error(`[AgentRegistry] Failed to parse agent config: ${w}`,{error:$}),null}}async saveAgent(_){try{let w=$4.safeParse(_);if(!w.success)return e.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,_),e.info(`[AgentRegistry] Saved agent: ${_.name} to ${X}`),!0}catch(w){return e.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}),e.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 X4.default.stringify(w).trimEnd()+`
|
|
2049
|
+
`}async deleteAgent(_){if(!this.agents.get(_))return e.warn(`[AgentRegistry] Agent not found: ${_}`),!1;try{let $=tw(this.configDir,`${_}.yaml`);if(this.fs.existsSync($))await this.fsPromises.unlink($),e.info(`[AgentRegistry] Deleted agent file: ${$}`);return this.agents.delete(_),!0}catch($){return e.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 tw(this.configDir,`${_}.yaml`)}}m([u("agent.registry.register",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"register",null);m([u("agent.registry.unregister",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"unregister",null);m([u("agent.registry.clear",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"clear",null);m([u("agent.registry.getSystemPrompt",{recordParams:!0,recordResult:!1,log:!0})],M_.prototype,"getSystemPrompt",null);m([u("agent.registry.getWorkflowName",{recordParams:!0,recordResult:!0})],M_.prototype,"getWorkflowName",null);m([u("agent.registry.getEntryAgent",{recordParams:!0,recordResult:!0})],M_.prototype,"getEntryAgent",null);m([u("agent.registry.registerWorkflowRunner",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowRunner",null);m([u("agent.registry.registerTaskOrganizer",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerTaskOrganizer",null);m([u("agent.registry.registerWorkflowCreator",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"registerWorkflowCreator",null);m([u("agent.registry.load",{recordParams:!1,recordResult:!0,log:!0})],M_.prototype,"load",null);m([u("agent.registry.loadFromDirectory",{recordParams:!0,recordResult:!0,log:!0})],M_.prototype,"loadFromDirectory",null);function dB(_){return _.endsWith(".yaml")||_.endsWith(".yml")}var Y4=`You are a subagent created by the main agent to handle a specific task.
|
|
2356
2050
|
|
|
2357
2051
|
## Your Role
|
|
2358
2052
|
- You were created to handle: {task_description}
|
|
@@ -2369,14 +2063,14 @@ task_operation_create({
|
|
|
2369
2063
|
## Execution
|
|
2370
2064
|
- Use the available tools to complete the task
|
|
2371
2065
|
- If you need more information, ask the main agent through the result
|
|
2372
|
-
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as
|
|
2066
|
+
- Return a clear summary of what you did and the results`;import{AsyncLocalStorage as pB}from"async_hooks";var iB=new pB;function J4(_,w){return iB.run(_,w)}import{AsyncLocalStorage as nB}from"async_hooks";var W4=()=>{};function ew(){return h0.getStore()}function $1(){return h0.getStore()||{}}function y0(){return h0.getStore()?.agentContext?.currentTaskId}function I5(_){return typeof _==="number"&&Number.isInteger(_)&&_>0?_:void 0}var k5,h0,rB,v0,Jw=r(()=>{a(),V_(),W4(),k5=n("env:context:env-context"),h0=new nB,rB=I_(function(w,$){return I5(w?.metadata?.parentTaskId)??I5($?.parentTaskId)},"env-context.resolveEnvParentTaskId",{recordParams:!1,recordResult:!1,log:!1,resultFilter:(_)=>({parentTaskId:_??null})}),v0=I_(function(w){let $=y0(),X=h0.getStore();if(X){if(!X.agentContext)X.agentContext={};X.agentContext.currentTaskId=w}k5.info(`[setCurrentTaskId] taskId=${w??"undefined"} (was: ${$??"undefined"})`)},"env-context.setCurrentTaskId",{recordParams:!0,recordResult:!1,log:!0})});var X1=r(()=>{Jw(),W4()});class Y1{_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=ew();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 W=this.sortHooks(X),Q=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=${W.length}:`);for(let q of W)console.error(`[DEBUG hook-manager.execute] - name=${q.name} pluginName=${q.pluginName} sourceId=${q.sourceId}`)}for(let q of W){if(q.pluginName&&q.sourceId){let H=`${q.sourceId}:${q.pluginName}`,B=G[H];if(Y)console.error(`[DEBUG hook-manager.execute] hook ${q.name} (${H}) enabled=${B}`);if(B!==!0){if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 SKIPPED (pluginEnabled[${H}] !== true, got ${JSON.stringify(B)})`);continue}}else if(Y)console.error(`[DEBUG hook-manager.execute] hook ${q.name} has no pluginName/sourceId, ALWAYS EXECUTED`);if(Y)console.error(`[DEBUG hook-manager.execute] \u2192 EXECUTING hook ${q.name}`);await this.safeExecute(q,Q)}}async executeAndCollect(_,w,$={}){let X=this._hooks.get(_);if(!X||X.length===0)return[];let Y=this.sortHooks(X),J=this.createContext(_,w,$,"before"),W=[];for(let Q of Y){let G=await this.safeExecuteAndReturn(Q,J);if(G!==void 0)W.push(G)}return W}count(_){return this._hooks.get(_)?.length??0}clear(){this._hooks.clear()}getHookPoints(){return Array.from(this._hooks.keys())}hasHooks(_){return this.count(_)>0}setComponentInfo(_,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"),W=[],Q=!1,G;for(let q of Y){if(Q)break;let H=await this.safeExecuteAndReturn(q,J);if(W.push(H),H&&typeof H==="object"&&"stopped"in H){let B=H;if(B.stopped)Q=!0,G=B.action}}return{stopped:Q,action:G,results:W}}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 Q4=r(()=>{X1()});function aB(){let _=E_.register.bind(E_);E_.register=function(w,$){_(w,$);let X=g5[w];if(X)_(X,$)}}var E_,oB,sB,tB,g5,_0=r(()=>{Q4(),E_=new Y1,oB={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"},sB={BEFORE_INVOKE:"llm:before.invoke",AFTER_INVOKE:"llm:after.invoke",ON_STREAM:"llm:on.stream"},tB={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"},g5={"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"},aB()});a();V_();X1();function eB(_,w){if(D4(_))return!0;return w?.hasAgent(_)??!1}async function _U(_,w={}){let X=(w.getBuiltIn??D4)(_),Y=w.registry?.get(_);if(!X&&!Y)return;if(Y)return wU(_,Y,X,w.registry);return{subagentType:_,description:X.description,basePrompt:X.promptOverride||Y4,allowedTools:X.allowedTools,deniedTools:X.deniedTools??["delegate_task","stop_task"],fromRegistry:!1}}async function wU(_,w,$,X){let Y=X?await X.getSystemPrompt(_):w.systemPrompt;return{subagentType:_,description:w.description||$?.description||"Custom agent",basePrompt:Y||$?.promptOverride||Y4,allowedTools:w.allowedTools??$?.allowedTools,deniedTools:w.deniedTools??$?.deniedTools??["delegate_task","stop_task"],fromRegistry:!0}}function $U(_){return`
|
|
2373
2067
|
## Agent Selection Guide
|
|
2374
2068
|
|
|
2375
2069
|
- Choose \`subagent_type\` from the list above; use \`general\` when no specialized agent fits (default).
|
|
2376
2070
|
${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Custom agents from AgentRegistry appear above when registered."}
|
|
2377
|
-
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function
|
|
2378
|
-
`)+Y}_0();var KU=[/\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 NU(_){let w=_;for(let $ of KU)w=w.replace($,"<redacted>");return w}function bU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function YX(_,w){return bU(NU(_),w)}class V${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 J={...$,...this.toRecord(_,w??$.source,X),createdAt:$.createdAt,source:w??$.source};return this.records.set(_.id,J),this.childrenIndex.delete(J.taskId),this.indexParentChild(J),this.evictIfNeeded(),J}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??[]),J=_.excludeAncestorOf??_.excludeSelfOrDescendant,Y=J?this.collectSubtree(J):new Set,W=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,q=Date.now(),G=new Set([...X,...Y]),Q=[];for(let H of this.records.values()){if(q-Date.parse(H.updatedAt)>this.ttlMs)continue;if(W>0&&Date.parse(H.updatedAt)<W)continue;if(G.has(H.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&H.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&H.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&H.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(H.status))continue}else if(H.status==="archived")continue;Q.push(H)}if(_.activeChildFirst){let H=new Map;for(let B of Q)H.set(B.taskId,this.hasActiveChild(B.taskId));Q.sort((B,D)=>{let z=H.get(B.taskId)?1:0,A=H.get(D.taskId)?1:0;if(z!==A)return A-z;let U=Date.parse(D.updatedAt)-Date.parse(B.updatedAt);if(U!==0)return U;return D.taskId-B.taskId})}else Q.sort((H,B)=>{let D=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(D!==0)return D;return B.taskId-H.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 J=this.childrenIndex.get(_),Y=J?Array.from(J):[],W=Y.length>0?1:0;X.maxDepth=W;let q=Y;while(q.length>0){let G=[];for(let Q of q){let H=this.records.get(Q);if(!H)continue;if(!$&&H.status==="archived")continue;if(X.descendantCount++,H.status==="active")X.activeCount++;else if(H.status==="completed")X.completedCount++;let B=this.childrenIndex.get(Q);if(B&&B.size>0)for(let D of B)G.push(D)}if(G.length>0)W++,X.maxDepth=W;q=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),J=X?this.stripSensitiveKeys(X):void 0;return{taskId:_.id,title:_.title,description:YX(_.description||"",this.maxDescriptionChars),goals:YX(_.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(J,"branch"),worktree_path:this.pickString(J,"worktree_path"),parentBranch:this.pickString(J,"parent_branch"),context:J}}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={},$=V$.STRIPPED_KEYS;for(let[X,J]of Object.entries(_)){let Y=X.toLowerCase();if($.some((W)=>Y.includes(W)))continue;w[X]=this.stripSensitiveKeys(J)}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(),J=this.childrenIndex.get(X);if(!J)continue;for(let Y of J)if(!w.has(Y))w.add(Y),$.push(Y)}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 W2=n("registry-hook-installer");function jU(_,w,$={}){let X=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,J=$.hookName?`${$.hookName}:${X}`:`registry-hook-installer:${X}`,Y=$.priority??100,W=!1,q=(U,V)=>{try{w.record(U,V)}catch(R){W2.warn(`[registry-hook-installer] record failed for task #${U.id}: ${R instanceof Error?R.message:String(R)}`)}},G=(U,V)=>{try{w.update(U,V)}catch(R){W2.warn(`[registry-hook-installer] update failed for task #${U.id}: ${R instanceof Error?R.message:String(R)}`)}},Q=(U)=>{try{w.remove(U)}catch(V){W2.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},H=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),B={name:`${J}:after-create`,priority:Y,execute:async(U)=>{let V=U.data;if(V?.task)q(V.task,H())}},D={name:`${J}:after-update`,priority:Y,execute:async(U)=>{let V=U.data;if(!V?.task)return;if(w.peekById(V.task.id))G(V.task,H());else q(V.task,H())}},z={name:`${J}:after-complete`,priority:Y,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,H())}},A={name:`${J}:after-delete`,priority:Y,execute:async(U)=>{let V=U.data;if(typeof V?.id==="number")Q(V.id)}};return _.registerHook(w_.AFTER_CREATE,B),_.registerHook(w_.AFTER_UPDATE,D),_.registerHook(w_.AFTER_COMPLETE,z),_.registerHook(w_.AFTER_DELETE,A),{uninstall(){if(W)return;W=!0,_.unregisterHook(w_.AFTER_CREATE,B.name),_.unregisterHook(w_.AFTER_UPDATE,D.name),_.unregisterHook(w_.AFTER_COMPLETE,z.name),_.unregisterHook(w_.AFTER_DELETE,A.name),W2.debug(`[registry-hook-installer] uninstalled hooks (name=${J})`)}}}a();var U$=n("task-reuse-registry"),EU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},WX=new WeakMap;function SU(_){let w=WX.get(_);if(w)return w.registry;let $=new V$(EU),X={uninstall:()=>{}};try{let Y=_.getComponent?.("task");if(Y?.registerHook)X=jU(Y,$,{sessionIdProvider:()=>{try{return _.currentSessionId??void 0}catch{return}},staticSource:{processId:typeof process<"u"?process.pid:void 0}}),U$.debug("[task-reuse-registry] hook installed");else U$.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(Y){U$.warn(`[task-reuse-registry] hook install failed: ${Y instanceof Error?Y.message:String(Y)}`)}let J={registry:$,installHandle:X};return WX.set(_,J),$}var PU=[/\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 PU)w=w.replace($,"<redacted>");return w}function qX(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function CU(_){let w=_.limit??5,$=_.maxChars??2000,X=_.maxDescriptionChars??240,J=_.heading??"Recent task context (reuse candidates)",Y=_.registry.recent({scope:_.scope,limit:w,statuses:_.statuses,excludeIds:_.similarTaskIds??[],excludeAncestorOf:_.excludeAncestorOf});if(Y.length===0)return{markdown:"",candidateIds:[],isEmpty:!0};let W=[];W.push(`## ${J}`),W.push(""),W.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),W.push("");for(let G of Y){if(W.push(`### Task #${G.taskId}: ${G.title}`),W.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)W.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)W.push(`- Created by: ${G.source.subagentType}`);if(W.push(`- Updated: ${G.updatedAt}`),G.project_path)W.push(`- Project: ${G.project_path}`);if(G.worktree_path)W.push(`- Worktree: ${G.worktree_path}`);if(G.branch)W.push(`- Branch: ${G.branch}`);if(G.parentBranch)W.push(`- Parent branch: ${G.parentBranch}`);let Q;try{Q=_.registry.getSubtreeSummary(G.taskId)}catch{Q=void 0}if(Q&&Q.descendantCount>0)W.push(`- Children: ${Q.descendantCount} (active: ${Q.activeCount}, completed: ${Q.completedCount}, max depth: ${Q.maxDepth})`);let H=Q!==void 0&&Q.activeCount>0;if(G.status==="completed"&&H)W.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let B=ZU(qX(G.description,X));if(B)W.push(`- Description: ${B}`);if(G.tags&&G.tags.length>0)W.push(`- Tags: ${G.tags.join(", ")}`);W.push("")}W.push("---"),W.push(""),W.push("### Reuse instructions"),W.push(""),W.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),W.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),W.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),W.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),W.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),W.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),W.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),W.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),W.push(""),W.push("### Decision matrix \u2014 three legal paths"),W.push(""),W.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),W.push("remains the default, but the matrix adds two new paths for independent work."),W.push(""),W.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),W.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),W.push("append description/goals. Do **not** create a new task id."),W.push(""),W.push("```"),W.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),W.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),W.push(' milestone_title: "Reopened for <new-scope>",'),W.push(' milestone_description: "<why this is the same work>" })'),W.push("```"),W.push(""),W.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),W.push("distinct: an independent bug fix, optimization, parallel delivery or"),W.push("independent acceptance item under the same feature. Create a child task so"),W.push("the audit trail is preserved. Always pair with an audit operation."),W.push(""),W.push("```");for(let G of Y){let Q=G.project_path??"<project_path>";W.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${Q}", context=<inherit or override>)`);break}W.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),W.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),W.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),W.push("```"),W.push(""),W.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),W.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),W.push("should stay \u2264 ~10 to keep the tree readable."),W.push(""),W.push("```"),W.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),W.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),W.push(' milestone_title: "New root: <topic>",'),W.push(' milestone_description: "<why this is not a child of any existing task>" })'),W.push("```"),W.push(""),W.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),W.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),W.push("chosen. Use the appropriate `milestone_type`:"),W.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),W.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),W.push(" - new root \u2192 `create` (then `progress` per phase)"),W.push(""),W.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),W.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),W.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),W.push("tokens, secrets) are stripped automatically. Use the helper:"),W.push(""),W.push("```"),W.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),W.push("```"),W.push("");let q=W.join(`
|
|
2379
|
-
`);if(
|
|
2071
|
+
- For full metadata: \`roy-agent agents list\`, \`roy-agent agents get <name>\`, \`roy-agent prompt list\`.`}function XU(_){let w=q4.map((W)=>`- ${W.id}: ${W.description}`),X=(_?.list()??[]).filter((W)=>!q4.some((Q)=>Q.id===W.name)).map((W)=>{if(W.type==="workflow"){let Q=W.workflow?` (workflow: ${W.workflow})`:"";return`- ${W.name}: ${W.description||"Workflow agent"}${Q}`}return`- ${W.name}: ${W.description||"Custom agent"}`}),Y=[...w,...X],J=$U({hasCustomAgents:X.length>0});return Y.join(`
|
|
2072
|
+
`)+J}_0();var YU=[/\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 JU(_){let w=_;for(let $ of YU)w=w.replace($,"<redacted>");return w}function WU(_,w){if(_.length<=w)return _;if(w<=3)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function h5(_,w){return WU(JU(_),w)}class H4{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,W=_.sinceHours?Date.now()-_.sinceHours*60*60*1000:0,Q=Date.now(),G=new Set([...X,...J]),q=[];for(let H of this.records.values()){if(Q-Date.parse(H.updatedAt)>this.ttlMs)continue;if(W>0&&Date.parse(H.updatedAt)<W)continue;if(G.has(H.taskId))continue;if(_.scope){if(_.scope.sessionId!==void 0&&H.source.sessionId!==_.scope.sessionId)continue;if(_.scope.parentSessionId!==void 0&&H.source.parentSessionId!==_.scope.parentSessionId)continue;if(_.scope.subagentType!==void 0&&H.source.subagentType!==_.scope.subagentType)continue}if($){if(!$.includes(H.status))continue}else if(H.status==="archived")continue;q.push(H)}if(_.activeChildFirst){let H=new Map;for(let B of q)H.set(B.taskId,this.hasActiveChild(B.taskId));q.sort((B,D)=>{let O=H.get(B.taskId)?1:0,z=H.get(D.taskId)?1:0;if(O!==z)return z-O;let U=Date.parse(D.updatedAt)-Date.parse(B.updatedAt);if(U!==0)return U;return D.taskId-B.taskId})}else q.sort((H,B)=>{let D=Date.parse(B.updatedAt)-Date.parse(H.updatedAt);if(D!==0)return D;return B.taskId-H.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):[],W=J.length>0?1:0;X.maxDepth=W;let Q=J;while(Q.length>0){let G=[];for(let q of Q){let H=this.records.get(q);if(!H)continue;if(!$&&H.status==="archived")continue;if(X.descendantCount++,H.status==="active")X.activeCount++;else if(H.status==="completed")X.completedCount++;let B=this.childrenIndex.get(q);if(B&&B.size>0)for(let D of B)G.push(D)}if(G.length>0)W++,X.maxDepth=W;Q=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:h5(_.description||"",this.maxDescriptionChars),goals:h5(_.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={},$=H4.STRIPPED_KEYS;for(let[X,Y]of Object.entries(_)){let J=X.toLowerCase();if($.some((W)=>J.includes(W)))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 J1=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,W=!1,Q=(U,V)=>{try{w.record(U,V)}catch(M){J1.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){J1.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){J1.warn(`[registry-hook-installer] remove failed for task #${U}: ${V instanceof Error?V.message:String(V)}`)}},H=()=>({sessionId:$.sessionIdProvider?.(),...$.staticSource??{}}),B={name:`${Y}:after-create`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)Q(V.task,H())}},D={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,H());else Q(V.task,H())}},O={name:`${Y}:after-complete`,priority:J,execute:async(U)=>{let V=U.data;if(V?.task)G(V.task,H())}},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,B),_.registerHook($_.AFTER_UPDATE,D),_.registerHook($_.AFTER_COMPLETE,O),_.registerHook($_.AFTER_DELETE,z),{uninstall(){if(W)return;W=!0,_.unregisterHook($_.AFTER_CREATE,B.name),_.unregisterHook($_.AFTER_UPDATE,D.name),_.unregisterHook($_.AFTER_COMPLETE,O.name),_.unregisterHook($_.AFTER_DELETE,z.name),J1.debug(`[registry-hook-installer] uninstalled hooks (name=${Y})`)}}}a();var G4=n("task-reuse-registry"),GU={maxEntries:500,ttlMs:86400000,maxDescriptionChars:240},y5=new WeakMap;function qU(_){let w=y5.get(_);if(w)return w.registry;let $=new H4(GU),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}}),G4.debug("[task-reuse-registry] hook installed");else G4.debug("[task-reuse-registry] no TaskComponent in env; registry stays empty")}catch(J){G4.warn(`[task-reuse-registry] hook install failed: ${J instanceof Error?J.message:String(J)}`)}let Y={registry:$,installHandle:X};return y5.set(_,Y),$}var HU=[/\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 DU(_){let w=_;for(let $ of HU)w=w.replace($,"<redacted>");return w}function v5(_,w){if(_.length<=w)return _;if(w<=1)return _.slice(0,w);return _.slice(0,w-1)+"\u2026"}function BU(_){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 W=[];W.push(`## ${Y}`),W.push(""),W.push("The following tasks were recently created in this process / session and may be related to your current work. Before creating a brand-new task, check whether one of these is the same work continuing. "+"The list is a *suggestion only* \u2014 confirm with `task_get <id>` before reusing."),W.push("");for(let G of J){if(W.push(`### Task #${G.taskId}: ${G.title}`),W.push(`- Status: ${G.status}`),G.parentTaskId!==void 0&&G.parentTaskId!==null)W.push(`- Parent: #${G.parentTaskId}`);if(G.source.subagentType)W.push(`- Created by: ${G.source.subagentType}`);if(W.push(`- Updated: ${G.updatedAt}`),G.project_path)W.push(`- Project: ${G.project_path}`);if(G.worktree_path)W.push(`- Worktree: ${G.worktree_path}`);if(G.branch)W.push(`- Branch: ${G.branch}`);if(G.parentBranch)W.push(`- Parent branch: ${G.parentBranch}`);let q;try{q=_.registry.getSubtreeSummary(G.taskId)}catch{q=void 0}if(q&&q.descendantCount>0)W.push(`- Children: ${q.descendantCount} (active: ${q.activeCount}, completed: ${q.completedCount}, max depth: ${q.maxDepth})`);let H=q!==void 0&&q.activeCount>0;if(G.status==="completed"&&H)W.push("- \u26A0 Has active child \u2014 reopening this parent will conflict with running work; prefer creating a child task.");let B=DU(v5(G.description,X));if(B)W.push(`- Description: ${B}`);if(G.tags&&G.tags.length>0)W.push(`- Tags: ${G.tags.join(", ")}`);W.push("")}W.push("---"),W.push(""),W.push("### Reuse instructions"),W.push(""),W.push("1. **First** call `task_get <id>` on the most relevant candidate to read its description, goals, and recent operations."),W.push("2. **If it is the same work continuing** \u2014 prefer `task_update` over `task_create`:"),W.push(" - Set `status` back to `active` (or `todo`) to reopen a completed task."),W.push(" - Append new context to `description` and `goals_and_expected_deliverables` (do not replace)."),W.push(' - Update `current_status` to reflect the new scope, then call `task_operation_create` with `milestone_type: "decision"` to record the continuation.'),W.push("3. **Only** if the candidate is clearly a different task, call `task_create` with a distinguishing title and `parent_task_id` if appropriate."),W.push("4. Do **not** create a duplicate task merely because the existing one is already `completed` \u2014 reopen it instead."),W.push("5. Do **not** reuse an unrelated candidate just to fill this list. Empty reuse is a valid outcome."),W.push(""),W.push("### Decision matrix \u2014 three legal paths"),W.push(""),W.push("Pick exactly **one** of these paths before calling `task_create`. Reopen-first"),W.push("remains the default, but the matrix adds two new paths for independent work."),W.push(""),W.push("**Path A \u2014 Continuation (reopen existing task).** The new work is the SAME"),W.push('logical task. Use `task_update(task_id=<id>, { status: "active", ... })` and'),W.push("append description/goals. Do **not** create a new task id."),W.push(""),W.push("```"),W.push('task_update(task_id=<parent_id>, { status: "active", current_status: "..." })'),W.push('task_operation_create({ task_id=<parent_id>, milestone_type: "decision",'),W.push(' milestone_title: "Reopened for <new-scope>",'),W.push(' milestone_description: "<why this is the same work>" })'),W.push("```"),W.push(""),W.push("**Path B \u2014 Child task (parent_task_id=<id>).** The new work is related but"),W.push("distinct: an independent bug fix, optimization, parallel delivery or"),W.push("independent acceptance item under the same feature. Create a child task so"),W.push("the audit trail is preserved. Always pair with an audit operation."),W.push(""),W.push("```");for(let G of J){let q=G.project_path??"<project_path>";W.push(`task_create(parent_task_id=${G.taskId}, title="<distinguishing title>", project_path="${q}", context=<inherit or override>)`);break}W.push('task_operation_create({ task_id=<new_id>, milestone_type: "milestone",'),W.push(' milestone_title: "Child of #<parent_id>: <new-scope>",'),W.push(' milestone_description: "<why this is a sibling/child, not a reopen>" })'),W.push("```"),W.push(""),W.push("**Path C \u2014 New root (no parent_task_id).** The new work is unrelated to any"),W.push("existing task. Create a brand-new root task. Use this sparingly \u2014 root count"),W.push("should stay \u2264 ~10 to keep the tree readable."),W.push(""),W.push("```"),W.push('task_create(parent_task_id=undefined, title="<distinct topic>", project_path="<project_path>", context=<json>)'),W.push('task_operation_create({ task_id=<new_id>, milestone_type: "create",'),W.push(' milestone_title: "New root: <topic>",'),W.push(' milestone_description: "<why this is not a child of any existing task>" })'),W.push("```"),W.push(""),W.push("**Operation audit templates.** Every `task_create`/`task_update` call MUST be"),W.push("followed by a `task_operation_create` so the next agent sees *why* the path was"),W.push("chosen. Use the appropriate `milestone_type`:"),W.push(" - continuation \u2192 `decision` (and `progress` once the new scope makes headway)"),W.push(" - child task \u2192 `milestone` (then `progress` as the child advances)"),W.push(" - new root \u2192 `create` (then `progress` per phase)"),W.push(""),W.push("**Project + context inheritance.** For Path B/C, prefer inheriting the"),W.push("candidate's `project_path`, `context.worktree_path`, `context.branch` and"),W.push("`context.parent_branch` from the parent task. Sensitive keys (commits,"),W.push("tokens, secrets) are stripped automatically. Use the helper:"),W.push(""),W.push("```"),W.push("inheritChildContext({ parent: { taskId, projectPath, contextJson, tags }, overrides: {...} })"),W.push("```"),W.push("");let Q=W.join(`
|
|
2073
|
+
`);if(Q.length>$)Q=v5(Q,$);return{markdown:Q,candidateIds:J.map((G)=>G.taskId),isEmpty:!1}}var h=n("task:delegate"),c_={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"},q4=[{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.
|
|
2380
2074
|
|
|
2381
2075
|
## Your Role
|
|
2382
2076
|
- You were created to handle: {task_description}
|
|
@@ -2424,126 +2118,433 @@ ${_.hasCustomAgents?"- Custom agents from AgentRegistry are listed above.":"- Cu
|
|
|
2424
2118
|
5. **Be ephemeral** - You may be terminated after task completion. That's fine.
|
|
2425
2119
|
6. **No nested delegation** - Do NOT use delegate_task or stop_task tools. Complete the task yourself.
|
|
2426
2120
|
|
|
2427
|
-
## Execution
|
|
2428
|
-
- Use the available tools to complete the task
|
|
2429
|
-
- If you need more information, ask the main agent through the result
|
|
2430
|
-
- 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:
|
|
2121
|
+
## Execution
|
|
2122
|
+
- Use the available tools to complete the task
|
|
2123
|
+
- If you need more information, ask the main agent through the result
|
|
2124
|
+
- 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:d1.roy,deniedTools:["delegate_task","stop_task"]}];function D4(_){return q4.find((w)=>w.id===_)}function UU(_,w,$,X,Y){let J=_.getRegistry?.();if(J){if(J.get(w)?.type==="workflow")return h.debug(`[delegate] Skipping registration for workflow agent: ${w}`),null}let W=_.getAgent(w);if(!W){let Q={type:"sub",systemPrompt:$};if(X?.allowedTools&&X.allowedTools.length>0)Q.allowedTools=X.allowedTools;if(Y.length>0)Q.deniedTools=Y;W=_.registerAgent(w,Q),h.debug(`[delegate] Registered subagent: ${w}`)}return W}var x5=A.object({description:A.string().describe("A short (3-5 words) description of the task"),prompt:A.string().describe("The task for the agent to perform"),subagent_type:A.string().describe("The type of specialized agent to use for this task").default("general"),timeout:A.number().describe("Task timeout in milliseconds. Default: 1800000 (30 minutes). If set, task will be terminated after timeout.").optional(),reason:A.string().describe("Brief reason for calling this tool (max 30 chars, e.g., 'Delegate refactor task')").optional(),similar_task_ids:A.array(A.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:A.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:A.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 zU(_){let{workflowName:w,originalPrompt:$,description:X}=_;return`# Workflow \u8C03\u5EA6\u8BF7\u6C42
|
|
2125
|
+
|
|
2126
|
+
\u4F60\u88AB\u8C03\u7528\u662F\u56E0\u4E3A\u4E0A\u6E38 \`delegate_task\` \u68C0\u6D4B\u5230 workflow \u7C7B\u578B subagent **${w}**\u3002
|
|
2127
|
+
\u8BF7\u901A\u8FC7 \`workflow_run\` \u547D\u4EE4\u8C03\u5EA6\u5BF9\u5E94 workflow\u3002
|
|
2128
|
+
|
|
2129
|
+
<workflow_name>${w}</workflow_name>
|
|
2130
|
+
|
|
2131
|
+
## \u8C03\u5EA6\u76EE\u6807
|
|
2132
|
+
|
|
2133
|
+
- **Workflow \u540D\u79F0**: \`${w}\` (\u6743\u5A01\u6765\u6E90: \`<workflow_name>\` \u6807\u7B7E, \u4E0D\u8981\u4ECE\u4E0A\u4E0B\u6587\u731C\u6D4B)
|
|
2134
|
+
- **\u4EFB\u52A1\u63CF\u8FF0**: ${X}
|
|
2135
|
+
|
|
2136
|
+
## \u539F\u59CB\u7528\u6237\u8BF7\u6C42
|
|
2137
|
+
|
|
2138
|
+
${$}
|
|
2139
|
+
|
|
2140
|
+
## \u4F60\u7684\u884C\u52A8
|
|
2141
|
+
|
|
2142
|
+
1. \`workflow_get(${w})\` \u53D6 workflow \u5165\u53C2 schema
|
|
2143
|
+
2. \u4ECE"\u539F\u59CB\u7528\u6237\u8BF7\u6C42"\u63D0\u53D6\u7B26\u5408 schema \u7684 input \u5B57\u6BB5
|
|
2144
|
+
3. \`workflow_run(${w}, input)\` \u89E6\u53D1 workflow
|
|
2145
|
+
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2146
|
+
|
|
2147
|
+
\u4E0D\u8981\u505A\u5176\u4ED6\u5DE5\u4F5C\u3002\u53EA\u8D70 \`workflow_run\` \u8DEF\u5F84\u3002
|
|
2148
|
+
`}var VU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),W1=1800000,OU=1200000;class __{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(W){let Q=W instanceof Error?W.message:String(W);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${J}) failed (likely already terminal): ${Q}`),Y.push({runId:J,success:!1,error:Q})}}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(__.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${__.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),__.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??__.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=I_((_)=>VU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return __._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:W,existingSubSessionId:Q,triggerEventId:G}=_,q=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,H=this.getSessionComponent();if(!H)throw Error("SessionComponent not found");if(!await H.get(w))throw Error(`Parent session not found: ${w}`);let D;if(Q){let R=await H.get(Q);if(!R)throw Error(`Sub session not found for resume: ${Q}`);let b=R?.metadata?.created_by;if(b&&b!=="subagent")h.warn(`[BackgroundTaskManager] Session ${Q} was not created by a sub-agent (created_by=${b}); reusing anyway`);D=R;try{let F=R?.metadata??{};await H.update(Q,{metadata:{...F,reused_sub_session:!0,reused_at:Date.now()}})}catch(F){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:Q,error:F instanceof Error?F.message:String(F)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${Q} for task ${q}`)}else{let R={subagent_type:Y,created_by:"subagent",task_description:$},b=ew();if(b){if(b.messageId)R.messageId=b.messageId;let F=b.replyChannel;if(F?.messageId)R.larkMessageId=F.messageId;if(F?.chatId)R.chatId=F.chatId;if(F?.userId)R.larkUserId=F.userId;let T=F?.profile;if(T)R.larkProfile=T}if(G)R.triggerEventId=G;if(D=await H.create({title:`${$} (@${Y} subagent)`,parentSessionId:w,metadata:R}),!D)throw Error("Failed to create sub-session")}let O=fU(),z=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=${q}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let U=new l1;this.processRegistries.set(q,U);let V=Date.now(),M=`${Y}:bg_${q}`,f={id:q,runId:M,subSessionId:D.id,parentSessionId:w,description:$,subagentType:Y,status:"pending",createdAt:V,lastUpdatedAt:V,timeoutMs:J||W1,abortController:z,similarTaskIds:W,triggerEventId:G,replyChannel:O};this.tasks.set(q,f),this.abortControllers.set(q,z);let N={backgroundTaskId:q,subSessionId:D.id,parentSessionId:w,description:$,subagentType:Y,startedAt:V,timeoutMs:J||W1};return this.publishBackgroundEvent(c_.STARTED,N,w,G,O),this.executeTask(q,X,J,w).catch((R)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:q,error:R instanceof Error?R.message:String(R)})}),{taskId:q,subSessionId:D.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 W=$||W1,Q=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 H=this.processRegistries.get(_),B=await this.executeWithAbort(q,w,W,_,Q?.signal,Y.similarTaskIds,H,()=>Q?.abort(),Y.subagentType);if(Q?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let D=Date.now();Y.status="completed",Y.completedAt=D,Y.lastUpdatedAt=D,Y.result=B;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),H=__.parseAskUserErrorFromMessage(G),B=q.toLowerCase().includes("stopped")||q.toLowerCase().includes("aborted"),D=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(H){Y.status="awaiting-user",Y.error=H.rawErrorMessage,Y.pendingAskUserQuery=H.query;let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,subagentType:Y.subagentType,description:Y.description,query:H.query,sessionId:H.sessionId,nodeId:H.nodeId,nodeType:H.nodeType,agentSessionId:H.agentSessionId,error:H.rawErrorMessage,executionTimeMs:D,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:H.nodeId,queryPreview:H.query.substring(0,80)}),Y._preserveSubSessionOnExit=!0;return}if(B){Y.status="stopped";let z={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:X||Y.parentSessionId,status:"stopped",description:Y.description,error:q,executionTimeMs:D,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:D,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:D,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(H){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${Y.subSessionId}`,{error:H instanceof Error?H.message:String(H)})}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)},OU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,Y,J,W,Q,G){let q=_?.metadata??{},H=q.task_id,B=q.task_description||"",D=_.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=${D}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),M=await _U(z,{registry:V}),f=D4(z),N=M?.basePrompt||f?.promptOverride||"You are a subagent. Complete this task: {task_description}",R=M?.deniedTools||f?.deniedTools||[],b=M?.allowedTools||f?.allowedTools,F=N.replace(/{task_description}/g,B||"N/A");if(F+=`
|
|
2149
|
+
|
|
2150
|
+
---
|
|
2151
|
+
|
|
2152
|
+
# Session Info
|
|
2153
|
+
- task_id: ${H||"N/A"}
|
|
2154
|
+
- session_id: ${D}
|
|
2155
|
+
|
|
2156
|
+
---
|
|
2157
|
+
|
|
2158
|
+
## \u7528\u6237\u6307\u4EE4
|
|
2159
|
+
${w}
|
|
2160
|
+
|
|
2161
|
+
---
|
|
2162
|
+
|
|
2163
|
+
## \u6267\u884C\u89C4\u8303
|
|
2164
|
+
- \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
|
|
2165
|
+
- \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
|
|
2166
|
+
- \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
|
|
2167
|
+
- \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 y=this.env?.getComponent?.("task");if(y){let i=[];for(let v of J)try{let c=await y.getTask(v);if(!c){h.warn(`[delegate] Similar task #${v} not found, skipping`);continue}let D_=await y.listOperations({taskId:v,limit:10}),B_=`### Task #${c.id}: ${c.title}
|
|
2168
|
+
`;if(B_+=`- Status: ${c.status}
|
|
2169
|
+
`,c.description)B_+=`- Description: ${c.description}
|
|
2170
|
+
`;if(c.goals_and_expected_deliverables)B_+=`- Goals: ${c.goals_and_expected_deliverables}
|
|
2171
|
+
`;if(D_&&D_.length>0){B_+=`- Recent Operations:
|
|
2172
|
+
`;for(let Nw of D_)B_+=` - [${Nw.actionType}] ${Nw.actionTitle}: ${Nw.actionDescription||""}
|
|
2173
|
+
`}i.push(B_)}catch(c){h.warn(`[delegate] Failed to fetch similar task #${v}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)F+=`
|
|
2174
|
+
|
|
2175
|
+
---
|
|
2176
|
+
|
|
2177
|
+
## Similar Tasks Reference
|
|
2178
|
+
|
|
2179
|
+
The following similar tasks and their operation records can serve as reference:
|
|
2180
|
+
|
|
2181
|
+
`,F+=i.join(`
|
|
2182
|
+
`),F+=`
|
|
2183
|
+
|
|
2184
|
+
---
|
|
2185
|
+
|
|
2186
|
+
Use these as guidance to improve task execution efficiency.`}}catch(y){h.warn("[delegate] Failed to inject similar tasks reference",{error:y instanceof Error?y.message:String(y)})}if(!U)throw Error("AgentComponent not found");try{if(this.env){let y=qU(this.env),i=BU({registry:y,similarTaskIds:J??[],limit:5,maxChars:2000,maxDescriptionChars:240});if(!i.isEmpty)F+=`
|
|
2187
|
+
|
|
2188
|
+
---
|
|
2189
|
+
|
|
2190
|
+
${i.markdown}`}}catch(y){h.warn("[delegate] Failed to inject reuse candidate section",{error:y instanceof Error?y.message:String(y)})}let T=f?{...f,allowedTools:b}:b?{id:z,name:z,mode:"subagent",description:M?.description||"Custom agent",allowedTools:b,deniedTools:R}:void 0;UU(U,z,N,T,R);let C=V?.get(z)?.type==="workflow"?w:F;return new Promise((y,i)=>{let v=async()=>{try{await W?.killAll()}catch(U_){h.warn("[delegate] ProcessRegistry.killAll failed",{error:U_ instanceof Error?U_.message:String(U_)})}},c=!1,D_,B_,Nw=this.tasks.get(X);if(Nw?.runId)B_=Nw.runId;let _2=()=>{if(Y&&w2)try{Y.removeEventListener("abort",w2)}catch{}},w2;if(w2=()=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2();try{let U_=this.env?.getComponent?.("agent");if(U_?.abortRun&&B_)U_.abortRun(B_,"task_signal_abort")}catch{}v().catch(()=>{}).then(()=>{i(Error("Task execution stopped"))})},D_=setTimeout(()=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2();try{Q?.()}catch{}try{let U_=this.env?.getComponent?.("agent");if(U_?.abortRun&&B_)U_.abortRun(B_,"task_timeout")}catch{}v().catch(()=>{}).then(()=>{i(Error(`Task execution timeout after ${$}ms`))})},$),Y)Y.addEventListener("abort",w2);let v4=()=>this.env.handle_query?.(C,{sessionId:D,deniedTools:R.length>0?R:void 0,agentType:z,abort:Y,runId:B_});(W?A8(W,()=>J4(X,()=>v4())):J4(X,()=>v4()))?.then((U_)=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2(),y(U_)}).catch((U_)=>{if(c)return;if(c=!0,D_)clearTimeout(D_);_2(),i(U_)})})}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(W){h.warn("[BackgroundTaskManager] abortRun failed during stopTask",{taskId:_,runId:w.runId,error:W instanceof Error?W.message:String(W)})}w.completedAt=$,w.lastUpdatedAt=$;try{await this.processRegistries.get(_)?.killAll()}catch(W){h.warn("[delegate] stopTask killAll failed",{taskId:_,error:W instanceof Error?W.message:String(W)})}let{runIds:X,stopResults:Y}=await this.propagateStopToWorkflowRuns(_,"Task stopped by user"),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(c_.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(_)}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){h.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(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents killAll failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}try{await this.propagateStopToWorkflowRuns($,"force stop all")}catch(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents propagateStopToWorkflowRuns failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}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(W){h.warn(`[BackgroundTaskManager] forceStopAllAcrossParents mark stopped failed for ${$}: ${W instanceof Error?W.message:String(W)}`)}if(J&&Y){let W={backgroundTaskId:Y.id,subSessionId:Y.subSessionId,parentSessionId:Y.parentSessionId,status:"stopped",description:Y.description,error:"force stop all",executionTimeMs:Y.startedAt&&Y.completedAt?Y.completedAt-Y.startedAt:0,associatedTaskId:Y.associatedTaskId};this.publishBackgroundEvent(c_.STOPPED,W,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){h.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(),h.info("[BackgroundTaskManager] Disposed")}}m([u("task.background.attachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"attachWorkflowRun",null);m([u("task.background.detachWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"detachWorkflowRun",null);m([u("task.background.replaceWorkflowRun",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"replaceWorkflowRun",null);m([u("task.background.propagateStopToWorkflowRuns",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"propagateStopToWorkflowRuns",null);m([u("task.background.finalizeTask",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"finalizeTask",null);m([u("task.background.resolveEntryAgent",{recordParams:!0,recordResult:!0})],__.prototype,"resolveEntryAgent",null);m([u("task.background.createTask",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"createTask",null);m([u("task.background.executeTask",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"executeTask",null);m([u("task.background.startProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"startProgressReporter",null);m([u("task.background.stopProgressReporter",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"stopProgressReporter",null);m([u("delegate.executeWithAbort",{recordParams:!0,recordResult:!1,log:!0})],__.prototype,"executeWithAbort",null);m([u("task.background.stopAllForParent",{recordParams:!0,recordResult:!0,log:!0})],__.prototype,"stopAllForParent",null);m([u("task.background.forceStopAllAcrossParents",{recordParams:!1,recordResult:!0,log:!0})],__.prototype,"forceStopAllAcrossParents",null);function m5(_){return _.env?.getComponent?.("agent")?.getRegistry?.()}function l5(_){let w=_.env,X=_.backgroundTaskManager??new __(w),Y=m5(_);_._backgroundTaskManager=X;let J={name:"delegate_task",description:`Launch a new sub-agent to handle complex, multistep tasks autonomously.
|
|
2191
|
+
|
|
2192
|
+
Available agent types:
|
|
2193
|
+
${XU(Y)}
|
|
2194
|
+
|
|
2195
|
+
When using the delegate_task tool, you must specify a subagent_type parameter to select which agent type to use.
|
|
2196
|
+
|
|
2197
|
+
## When to use delegate_task:
|
|
2198
|
+
- When you need to perform complex, multi-step tasks that require independent execution
|
|
2199
|
+
- When you need to explore a codebase thoroughly (use "explore" subagent)
|
|
2200
|
+
- When you need to run long-running tasks without blocking the main agent
|
|
2201
|
+
|
|
2202
|
+
## How it works:
|
|
2203
|
+
This tool **always runs in background mode**. It returns immediately with:
|
|
2204
|
+
- **bgProcessId**: Internal background process ID (use with \`stop_task\` to cancel, different from Task #)
|
|
2205
|
+
- **subSessionId**: Sub-agent session ID (use with \`session_get\` to see full execution log, always retained)
|
|
2206
|
+
|
|
2207
|
+
**After delegating, just WAIT for the notification.** The background process will automatically notify you when:
|
|
2208
|
+
- \u2705 **completed** \u2014 with \`bgprocess:\` + \`Task #\` (if it created a task) + result summary
|
|
2209
|
+
- \u23F1\uFE0F **timeout** \u2014 with \`bgprocess:\` + \`Task #\` (if available)
|
|
2210
|
+
- \u274C **failed** \u2014 with \`bgprocess:\` + \`Task #\` + error details
|
|
2211
|
+
- \uD83D\uDED1 **stopped** \u2014 with \`bgprocess:\` + \`Task #\`
|
|
2212
|
+
|
|
2213
|
+
The sub-agent runs independently and creates its own tasks via \`task_create\`.
|
|
2214
|
+
No need to poll \u2014 just wait for the notification and use \`task_get\` with the Task # reported in it.
|
|
2215
|
+
|
|
2216
|
+
## Parameters:
|
|
2217
|
+
- **description**: A short (3-5 words) description of the task
|
|
2218
|
+
- **prompt**: The task for the agent to perform
|
|
2219
|
+
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2220
|
+
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2221
|
+
- **reason**: Brief reason for calling this tool (optional)
|
|
2222
|
+
- **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:x5,execute:async(W,Q)=>{let G=Date.now(),q=x5.parse(W),{description:H,prompt:B,subagent_type:D="general",timeout:O,reason:z,similar_task_ids:U}=q,V=Q.session_id||"default",M=q.triggerEventId??MU();if(M&&M!==q.triggerEventId)h.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${M}`);if(h.info(`[delegate_task] Called: description=${H}, subagent_type=${D}, triggerEventId=${M??"(none)"}`),M){let T=R8();if(T)try{if(!await T.getEventById(M))return{success:!1,output:"",error:`Unknown triggerEventId: ${M} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-G}}}catch(j){return{success:!1,output:"",error:`Failed to verify triggerEventId ${M}: ${j instanceof Error?j.message:String(j)}`,metadata:{execution_time_ms:Date.now()-G}}}else h.warn(`[delegate_task] triggerEventId=${M} supplied but no shared EventStore registered; skipping verification`)}let f=m5(_);if(!eB(D,f))return{success:!1,output:"",error:`Unknown subagent type: ${D}`,metadata:{execution_time_ms:Date.now()-G}};let N=_.getTagService(),R=B,b={prompt:R,subagentType:D,timeout:O,reason:z,tagService:N},F={component:{name:"task",version:"1.0.0"},data:b,metadata:{sessionId:V},phase:"before",hookPoint:$_.DELEGATE_BEFORE};return await E_.execute($_.DELEGATE_BEFORE,b,{sessionId:V}),R=b.prompt,await LU(X,V,H,R,b.subagentType,b.timeout,U,q.sub_session_id,M)}};return J.execute=I_(J.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),J}function AU(){let _=ew();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 MU=I_(AU,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function RU(){let _=ew()?.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 fU=I_(RU,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function LU(_,w,$,X,Y,J,W,Q,G){let q=Date.now();try{let H=Y,B=X,D,O=_.resolveEntryAgent(Y);if(O)D=Y,H=O,B=zU({workflowName:D,originalPrompt:X,description:$}),h.info(`[delegate_task] Routing workflow subagent '${Y}' \u2192 entry-agent '${O}'`);let{taskId:z,subSessionId:U}=await _.createTask({parentSessionId:w,description:$,prompt:B,subagentType:H,timeout:J,similarTaskIds:W,originalWorkflowName:D,existingSubSessionId:Q,triggerEventId:G});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${z}`,`\uD83D\uDCDD Description: ${$}`,`\uD83E\uDD16 Sub-agent: ${H}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(J||W1)/1000}s`,"",`Use stop_task with task_id="${z}" to cancel this task.`].join(`
|
|
2223
|
+
`),metadata:{execution_time_ms:Date.now()-q,sessionId:U,background:!0,status:"accepted",bgProcessId:z}}}catch(H){return{success:!1,output:"",error:H instanceof Error?H.message:String(H),metadata:{execution_time_ms:Date.now()-q}}}}var u5=A.object({task_id:A.string().describe("The ID of the background task to stop")}),FU=`Stop a running background task.
|
|
2224
|
+
|
|
2225
|
+
Use this tool to stop a background task that is currently running. This is useful when:
|
|
2226
|
+
- The user wants to cancel a long-running task
|
|
2227
|
+
- The task is taking too long and needs to be stopped
|
|
2228
|
+
- The user wants to change direction and doesn't need the task result anymore
|
|
2229
|
+
|
|
2230
|
+
When stopped, the task will be terminated immediately and you will receive a confirmation.
|
|
2231
|
+
|
|
2232
|
+
Parameters:
|
|
2233
|
+
- task_id: The ID of the background task to stop (obtained from the delegate_task response)`;function KU(_){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 c5(_){return{name:"stop_task",description:FU,parameters:u5,execute:async(w,$)=>{let X=Date.now(),Y=u5.parse(w),{task_id:J}=Y,W=await _.stopTask(J);if(W.success){let Q=W.task,G=Q.startedAt?Date.now()-Q.startedAt:Date.now()-Q.createdAt;return{success:!0,output:["\u2705 Task stopped successfully","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${Q.description}`,`\uD83D\uDD04 Status: ${Q.status} \u2192 stopped`,`\u23F1\uFE0F Elapsed Time: ${KU(G)}`,"",W.message].join(`
|
|
2234
|
+
`),metadata:{execution_time_ms:Date.now()-X,task_id:J,previous_status:Q.status}}}else{let Q=W.task,G;if(Q)G=["\u26A0\uFE0F Cannot stop task","",`\uD83D\uDCCB Task ID: ${J}`,`\uD83D\uDCDD Description: ${Q.description}`,`\uD83D\uDD04 Current Status: ${Q.status}`,"",W.message].join(`
|
|
2235
|
+
`);else G=["\u274C Task not found","",`\uD83D\uDCCB Task ID: ${J}`,"",W.message].join(`
|
|
2236
|
+
`);return{success:!1,output:G,error:W.message,metadata:{execution_time_ms:Date.now()-X,task_id:J}}}}}}var Rw={CREATED:"task.created",UPDATED:"task.updated",COMPLETED:"task.completed",DELETED:"task.deleted",OPERATION_ADDED:"task.operation_added",DELEGATED:"task.delegated"};import{execSync as EU}from"child_process";var d5="unknown",NU='{"type":"unknown"}';function bU(){return{task_id:A.number().describe("Task ID")}}function jU(_){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 U4(_){return A.preprocess(jU,A.object({...bU(),..._}))}var p5=A.object({title:A.string().describe("Task title"),description:A.string().optional().describe("Task description"),priority:A.enum(["low","medium","high"]).optional().describe("Task priority"),type:A.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:A.string().optional().describe("Goals and expected deliverables"),due_date:A.string().optional().describe("Due date (ISO format)"),tags:A.array(A.string()).optional().describe("Task tags (for search, stored in task.tags JSON field)"),project_path:A.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:A.union([A.number(),A.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
|
+
`+`\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
|
+
`+`**\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
|
+
`+`\u51B3\u7B56\u8DEF\u5F84\uFF08\u6309\u987A\u5E8F\u5339\u914D\uFF09\uFF1A
|
|
2240
|
+
`+` A. \u5F52\u5C5E\u5230\u73B0\u6709 longterm \u6839\uFF08\u5982\u300C[Longterm] X \u751F\u6001\u300D\uFF09\u2192 parent_task_id = \u8BE5\u6839 ID
|
|
2241
|
+
`+` 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
|
+
`+` C. \u65B0\u5EFA\u6839\u4EFB\u52A1 \u2192 \u7701\u7565 parent_task_id\uFF08\u8BA9\u6811\u6839 \u226410\uFF09
|
|
2243
|
+
`+`\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:A.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!`)}),i5=U4({include_operations:A.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.")}),n5=A.object({status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Filter by task type"),limit:A.number().optional().default(20),offset:A.number().optional().default(0),depth:A.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:A.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")}),r5=A.object({keywords:A.array(A.string()).describe("\u5173\u952E\u8BCD\u5217\u8868\uFF08AND \u903B\u8F91\uFF0C\u5339\u914D title/description/goals/tags/operations\uFF09"),limit:A.number().optional().default(20).describe("\u8FD4\u56DE\u6570\u91CF"),offset:A.number().optional().default(0).describe("\u504F\u79FB\u91CF"),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u7B5B\u9009"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u7B5B\u9009"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u7C7B\u578B\u7B5B\u9009"),exclude_task_id:A.number().optional().describe("\u6392\u9664\u7684 task ID"),depth:A.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:A.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")}),a5=U4({title:A.string().optional(),description:A.string().optional(),status:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional(),priority:A.enum(["low","medium","high"]).optional(),type:A.enum(["normal","cycle","longterm"]).optional().describe("Task type"),progress:A.number().min(0).max(100).optional(),current_status:A.string().optional(),goals_and_expected_deliverables:A.string().optional(),due_date:A.string().optional(),tags:A.array(A.string()).optional(),project_path:A.string().optional().describe("Project path, identifies which project this task belongs to"),context:A.string().optional().describe("Task context information for storing additional context"),parent_task_id:A.union([A.number(),A.null()]).optional().describe("Parent task ID (set to null to make it a root task)")}),o5=A.object({task_id:A.number().describe("Task ID")}),s5=U4({deliverable_storage_path:A.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")}),t5=A.object({task_ids:A.array(A.number()).describe("\u8981\u5F52\u6863\u7684\u4EFB\u52A1 ID \u5217\u8868"),reason:A.string().optional().describe("\u5F52\u6863\u539F\u56E0\uFF08\u53EF\u9009\uFF0C\u4F1A\u5199\u5165\u6BCF\u4E2A\u4EFB\u52A1\u7684 operation \u8BB0\u5F55\uFF09")}),e5=A.object({task_ids:A.array(A.number()).describe("\u8981\u5220\u9664\u7684\u4EFB\u52A1 ID \u5217\u8868")}),_X=A.object({depth:A.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:A.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:A.enum(["todo","active","completed","paused","cancelled","archived"]).optional().describe("\u6309\u72B6\u6001\u8FC7\u6EE4\uFF08\u4E0E task_list \u4E00\u81F4\uFF09\u3002"),priority:A.enum(["low","medium","high"]).optional().describe("\u6309\u4F18\u5148\u7EA7\u8FC7\u6EE4\u3002"),type:A.enum(["normal","cycle","longterm"]).optional().describe("\u6309\u4EFB\u52A1\u7C7B\u578B\u8FC7\u6EE4\u3002"),include_archived:A.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")});Jw();a();a();var SU=n("task-child-context"),PU=["commit","token","secret","password","api_key"];function B4(_){if(_===null||_===void 0)return _;if(Array.isArray(_))return _.map(B4);if(typeof _!=="object")return _;let w={};for(let[$,X]of Object.entries(_)){let Y=$.toLowerCase();if(PU.some((J)=>Y.includes(J)))continue;w[$]=B4(X)}return w}function ZU(_){let{parent:w,overrides:$={}}=_,X=$.contextInherit!==!1,Y=$.inheritTags===!0,J=$.projectPath??w.projectPath??"unknown",W={};if(w.contextJson&&w.contextJson.trim().length>0)try{let H=JSON.parse(w.contextJson);if(H&&typeof H==="object"&&!Array.isArray(H))W=H}catch(H){SU.debug(`[task-child-context] parent #${w.taskId} context is malformed JSON; continuing with empty inherited context (${H instanceof Error?H.message:String(H)})`),W={}}let Q={};if(X){if(W.worktree_path!==void 0&&$.worktreePath===void 0)Q.worktree_path=W.worktree_path;if(W.branch!==void 0&&$.branch===void 0)Q.branch=W.branch;if(W.parent_branch!==void 0)Q.parent_branch=W.parent_branch;if(W.type!==void 0)Q.type=W.type;if(W.prior_context&&typeof W.prior_context==="object"){let B=W.prior_context,D={};for(let[O,z]of Object.entries(B)){if(O.toLowerCase()==="commit")continue;D[O]=z}if(Object.keys(D).length>0)Q.prior_context=D}let H=new Set(["worktree_path","branch","parent_branch","type","prior_context","created_at"]);for(let[B,D]of Object.entries(W)){if(H.has(B))continue;Q[B]=D}}if($.worktreePath!==void 0)Q.worktree_path=$.worktreePath;if($.branch!==void 0)Q.branch=$.branch;let G=$.createdAt??new Date().toISOString();Q.created_at=G,Q.child_of=w.taskId;let q=B4(Q);return{project_path:J,context:JSON.stringify(q),inheritedTags:Y?w.tags??[]:[]}}var wX=n("task:tools:create");function CU(){try{let _=EU("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 x0(_){return{name:"task_create",description:`
|
|
2245
|
+
Create a new task for tracking work.
|
|
2246
|
+
|
|
2247
|
+
## \u26A0\uFE0F CALL task_tree(depth=1) BEFORE THIS TOOL
|
|
2248
|
+
|
|
2249
|
+
Before calling \`task_create\`, you **MUST** first call
|
|
2250
|
+
\`task_tree(depth=1)\` to inspect the existing task hierarchy.
|
|
2251
|
+
This is critical because:
|
|
2252
|
+
|
|
2253
|
+
1. Avoid duplicating root tasks (root tasks should stay \u2264 10).
|
|
2254
|
+
2. Find the right \`parent_task_id\` to attach under.
|
|
2255
|
+
3. Avoid creating stranded/orphan tasks.
|
|
2256
|
+
|
|
2257
|
+
Workflow:
|
|
2258
|
+
step 1: task_tree({depth: 1})
|
|
2259
|
+
step 2: read the tree, then decide per "Decision Tree" below
|
|
2260
|
+
step 3: task_create({...})
|
|
2261
|
+
|
|
2262
|
+
## Decision Tree \u2014 How to choose parent_task_id
|
|
2263
|
+
|
|
2264
|
+
Walk these paths in order:
|
|
2265
|
+
|
|
2266
|
+
**Path A \u2014 Attach under a longterm root.**
|
|
2267
|
+
The task belongs to a theme whose longterm root already exists
|
|
2268
|
+
(e.g. "[Longterm] X ecosystem"). Set \`parent_task_id\` to that
|
|
2269
|
+
root's id. This is the **preferred** path for incremental work
|
|
2270
|
+
inside an established theme.
|
|
2271
|
+
|
|
2272
|
+
**Path B \u2014 Attach under an existing topic cluster.**
|
|
2273
|
+
A non-longterm root already aggregates similar tasks and yours
|
|
2274
|
+
belongs in the same cluster. Set \`parent_task_id\` to that root.
|
|
2275
|
+
|
|
2276
|
+
**Path C \u2014 Create a new root.**
|
|
2277
|
+
Neither A nor B fits (cross-cutting work, or root count already
|
|
2278
|
+
\u2265 ~10). **Omit** \`parent_task_id\` (or pass \`null\`) and the
|
|
2279
|
+
task becomes a new root.
|
|
2280
|
+
|
|
2281
|
+
## Tree Hygiene Principles
|
|
2282
|
+
|
|
2283
|
+
Apply these when deciding parent_task_id:
|
|
2284
|
+
|
|
2285
|
+
- Root tasks \u2264 10 (keep tree width manageable)
|
|
2286
|
+
- Depth \u2264 5 (avoid deep nesting)
|
|
2287
|
+
- Same-theme tasks cluster under one parent
|
|
2288
|
+
- Long-tail/stranded tasks should be archived or merged
|
|
2289
|
+
|
|
2290
|
+
## \u26A0\uFE0F Spatial + Temporal Context (Task #2325)
|
|
2291
|
+
|
|
2292
|
+
A task MUST carry spatio-temporal context so it survives task-handoff
|
|
2293
|
+
across Agent sessions, worktrees and time. Two orthogonal axes:
|
|
2431
2294
|
|
|
2432
|
-
|
|
2433
|
-
|
|
2295
|
+
- **Space (project_path + worktree_path)**:
|
|
2296
|
+
- \`project_path\` (required): git repo root path (always the top-level repo)
|
|
2297
|
+
- \`worktree_path\` (in context): current worktree path if in a worktree
|
|
2298
|
+
- **Auto-detected by createTask** via \`git rev-parse --show-toplevel\`
|
|
2299
|
+
\u2014 you don't need to fill it manually (see "worktree_path detection
|
|
2300
|
+
logic" in the implementation).
|
|
2301
|
+
- You may **override** by passing it in \`context.worktree_path\`.
|
|
2434
2302
|
|
|
2435
|
-
|
|
2303
|
+
- **Time (context field)**:
|
|
2304
|
+
- \`created_at\` (in context): ISO 8601 timestamp **auto-injected**
|
|
2305
|
+
at creation time. Manual override is preserved if provided.
|
|
2306
|
+
- \`time_dimension\` (in context, optional): the task's "time anchor"
|
|
2307
|
+
\u2014 e.g. a release tag, sprint window or iteration id.
|
|
2308
|
+
- \`work_period\` (in context, optional): planned start/end dates
|
|
2309
|
+
if known.
|
|
2310
|
+
- \`prior_context\` (in context, optional): the previous task id
|
|
2311
|
+
/ commit hash this work continues from. Helps the next Agent
|
|
2312
|
+
pick up the trail via \`task_get\`.
|
|
2436
2313
|
|
|
2437
|
-
|
|
2314
|
+
Example context for code development task:
|
|
2438
2315
|
|
|
2439
|
-
|
|
2440
|
-
-
|
|
2316
|
+
\`\`\`json
|
|
2317
|
+
{"project_path": "<git-repo-root>",
|
|
2318
|
+
"worktree_path": "<git-repo-root>/.worktrees/<branch-name>",
|
|
2319
|
+
"branch": "feat/<branch-name>",
|
|
2320
|
+
"type": "feature",
|
|
2321
|
+
"parent_branch": "main",
|
|
2322
|
+
"created_at": "<ISO-8601-timestamp>",
|
|
2323
|
+
"prior_context": {"prev_task": "<task-id>", "commit": "<commit-hash>"}}
|
|
2324
|
+
\`\`\`
|
|
2441
2325
|
|
|
2442
|
-
##
|
|
2326
|
+
## IMPORTANT: Task Continuity Fields
|
|
2443
2327
|
|
|
2444
|
-
|
|
2328
|
+
This tool creates persistent task records that can be picked up by a
|
|
2329
|
+
Task Manager Agent to continue advancing unfinished work.
|
|
2445
2330
|
|
|
2446
|
-
|
|
2331
|
+
The following fields are critical for task context preservation:
|
|
2447
2332
|
|
|
2448
|
-
|
|
2449
|
-
|
|
2450
|
-
|
|
2451
|
-
4. \u628A output \u539F\u6837\u56DE\u7ED9 parent agent
|
|
2333
|
+
- project_path: The project root path where this task belongs.
|
|
2334
|
+
Used to locate the project space for this task.
|
|
2335
|
+
If unknown, use 'unknown'.
|
|
2452
2336
|
|
|
2453
|
-
|
|
2454
|
-
`}var gU=new Set(["strict-task-agent","code-review","bench-agent-host","workspace-analyzer","test-workflow-agent"]),DX=1800000,kU=1200000;class e{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 J=[];for(let Y of X){if(typeof this.workflowService?.stopRun!=="function"){h.warn(`[BackgroundTaskManager] workflowService not injected; cannot stop ${Y}`),J.push({runId:Y,success:!1,error:"workflowService not injected"});continue}try{await this.workflowService.stopRun(Y,w),J.push({runId:Y,success:!0})}catch(W){let q=W instanceof Error?W.message:String(W);h.warn(`[BackgroundTaskManager] workflowService.stopRun(${Y}) failed (likely already terminal): ${q}`),J.push({runId:Y,success:!1,error:q})}}return $.clear(),{runIds:X,stopResults:J}}finalizeTask(_,w){if(!_)return;this.stopProgressReporter(_),this.progressTimers.delete(_);let $=this.tasks.get(_);if($){if(this.tasks.delete(_),this.terminalTasks.size>=this.maxTerminalTasks){let Y=this.terminalTasks.keys().next().value;if(Y!==void 0)this.terminalTasks.delete(Y)}this.terminalTasks.set(_,$)}let X=this.abortControllers.get(_);if(X&&w!=="completed"){if(!X.signal.aborted)try{X.abort()}catch{}}this.abortControllers.delete(_),this.workflowRunRegistries.delete(_);let J=this.processRegistries.get(_);if(J&&J.size()>0)h.debug(`[BackgroundTaskManager] finalizeTask\u4FDD\u7559 processRegistry ${_} (residualPIDs=${J.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(e.detectWorkflowShortcutCompat(_))return h.info(`[BackgroundTaskManager] Compat rewrite: '${_}' \u2192 '${e.DEFAULT_WORKFLOW_ENTRY_AGENT}'`),e.DEFAULT_WORKFLOW_ENTRY_AGENT;let X=this.env?.getComponent?.("agent")?.getRegistry?.()?.get?.(_);if(!X||X.type!=="workflow")return;return X.entryAgent??e.DEFAULT_WORKFLOW_ENTRY_AGENT}catch(w){h.warn(`[BackgroundTaskManager] resolveEntryAgent failed for ${_}: ${w}`);return}}static _detectWorkflowShortcutWrapped=T_((_)=>gU.has(_),"delegate.detectWorkflowShortcut",{recordParams:!0,recordResult:!0,log:!0});static detectWorkflowShortcutCompat(_){return e._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,J){if(this.env?.pushEnvEvent)this.env.pushEnvEvent({type:_,payload:w,metadata:{source:"task.background",trigger_session_id:$,...X?{triggerEventId:X}:{},...J?{replyChannel:J}:{}}}),h.info(`[BackgroundTaskManager] Event published: ${_}`,{triggerEventId:X,replyChannelChatId:J?.chatId})}publishBackgroundEventWithTrigger(_,w,$,X,J){this.publishBackgroundEvent(_,w,$,X,J)}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),J=JSON.parse(X);return{query:J.query,sessionId:J.sessionId,nodeId:J.nodeId,nodeType:J.nodeType||"agent",agentSessionId:J.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:J,timeout:Y,similarTaskIds:W,existingSubSessionId:q,triggerEventId:G}=_,Q=`process_${Date.now()}_${Math.random().toString(36).slice(2,11)}`,H=this.getSessionComponent();if(!H)throw Error("SessionComponent not found");if(!await H.get(w))throw Error(`Parent session not found: ${w}`);let D;if(q){let K=await H.get(q);if(!K)throw Error(`Sub session not found for resume: ${q}`);let j=K?.metadata?.created_by;if(j&&j!=="subagent")h.warn(`[BackgroundTaskManager] Session ${q} was not created by a sub-agent (created_by=${j}); reusing anyway`);D=K;try{let N=K?.metadata??{};await H.update(q,{metadata:{...N,reused_sub_session:!0,reused_at:Date.now()}})}catch(N){h.warn("[BackgroundTaskManager] Failed to update reused session metadata",{existingSubSessionId:q,error:N instanceof Error?N.message:String(N)})}h.info(`[BackgroundTaskManager] Reusing sub session: ${q} for task ${Q}`)}else{let K={subagent_type:J,created_by:"subagent",task_description:$},j=uw();if(j){if(j.messageId)K.messageId=j.messageId;let N=j.replyChannel;if(N?.messageId)K.larkMessageId=N.messageId;if(N?.chatId)K.chatId=N.chatId;if(N?.userId)K.larkUserId=N.userId;let g=N?.profile;if(g)K.larkProfile=g}if(G)K.triggerEventId=G;if(D=await H.create({title:`${$} (@${J} subagent)`,parentSessionId:w,metadata:K}),!D)throw Error("Failed to create sub-session")}let z=xU(),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=${Q}\uFF09\u3002\u8BF7\u6E05\u7406 / \u91CD\u542F / \u8C03\u9AD8 maxProcessRegistries\u3002`)}let U=new n2;this.processRegistries.set(Q,U);let V=Date.now(),R=`${J}:bg_${Q}`,f={id:Q,runId:R,subSessionId:D.id,parentSessionId:w,description:$,subagentType:J,status:"pending",createdAt:V,lastUpdatedAt:V,abortController:A,similarTaskIds:W,triggerEventId:G,replyChannel:z};this.tasks.set(Q,f),this.abortControllers.set(Q,A);let S={backgroundTaskId:Q,subSessionId:D.id,parentSessionId:w,description:$,subagentType:J};return this.publishBackgroundEvent(l_.STARTED,S,w,G,z),this.executeTask(Q,X,Y,w).catch((K)=>{h.error("[BackgroundTaskManager] executeTask unhandled rejection",{taskId:Q,error:K instanceof Error?K.message:String(K)})}),{taskId:Q,subSessionId:D.id}}async executeTask(_,w,$,X){let J=this.tasks.get(_);if(!J){h.warn("[BackgroundTaskManager] executeTask: Task not found",{taskId:_});return}let Y=Date.now();J.status="running",J.startedAt=Y,J.lastUpdatedAt=Y;let W=$||DX,q=this.abortControllers.get(_);this.startProgressReporter(_,X||J.parentSessionId);try{let Q=await this.getSessionComponent().get(J.subSessionId);if(!Q)throw Error(`Sub session not found: ${J.subSessionId}`);let H=this.processRegistries.get(_),B=await this.executeWithAbort(Q,w,W,_,q?.signal,J.similarTaskIds,H,()=>q?.abort(),J.subagentType);if(q?.signal.aborted){h.info("[BackgroundTaskManager] Task was aborted",{taskId:_});return}let D=Date.now();J.status="completed",J.completedAt=D,J.lastUpdatedAt=D,J.result=B;let z=J.completedAt-J.startedAt;if(J.associatedTaskId=U0(),J.associatedTaskId===void 0)J.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(J.subSessionId);let A={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:X||J.parentSessionId,status:"completed",result:J.result,description:J.description,executionTimeMs:z,associatedTaskId:J.associatedTaskId};this.publishBackgroundEvent(l_.COMPLETED,A,X||J.parentSessionId,J.triggerEventId,J.replyChannel),h.info("[BackgroundTaskManager] Task completed successfully",{taskId:_,executionTimeMs:z})}catch(G){let Q=G instanceof Error?G.message:String(G),H=e.parseAskUserErrorFromMessage(G),B=Q.toLowerCase().includes("stopped")||Q.toLowerCase().includes("aborted"),D=J.startedAt?Date.now()-J.startedAt:0,z=Date.now();if(J.completedAt=z,J.lastUpdatedAt=z,J.associatedTaskId=U0(),J.associatedTaskId===void 0)J.associatedTaskId=await this.resolveAssociatedTaskIdBySubSession(J.subSessionId);if(H){J.status="awaiting-user",J.error=H.rawErrorMessage,J.pendingAskUserQuery=H.query;let A={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:X||J.parentSessionId,subagentType:J.subagentType,description:J.description,query:H.query,sessionId:H.sessionId,nodeId:H.nodeId,nodeType:H.nodeType,agentSessionId:H.agentSessionId,error:H.rawErrorMessage,executionTimeMs:D,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="${J.subagentType}", existingSubSessionId="${J.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:J.associatedTaskId};this.publishBackgroundEvent(l_.ASK_USER,A,X||J.parentSessionId,J.triggerEventId,J.replyChannel),h.info("[BackgroundTaskManager] Task awaiting user input (ask_user cascade)",{taskId:_,subSessionId:J.subSessionId,nodeId:H.nodeId,queryPreview:H.query.substring(0,80)}),J._preserveSubSessionOnExit=!0;return}if(B){J.status="stopped";let A={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:X||J.parentSessionId,status:"stopped",description:J.description,error:Q,executionTimeMs:D,associatedTaskId:J.associatedTaskId};this.publishBackgroundEvent(l_.STOPPED,A,X||J.parentSessionId,J.triggerEventId,J.replyChannel)}else if(Q.startsWith("Task execution timeout after")){J.status="timeout";let A={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:X||J.parentSessionId,status:"timeout",description:J.description,error:Q,executionTimeMs:D,associatedTaskId:J.associatedTaskId};this.publishBackgroundEvent(l_.TIMEOUT,A,X||J.parentSessionId,J.triggerEventId,J.replyChannel)}else{J.status="failed";let A={backgroundTaskId:J.id,subSessionId:J.subSessionId,parentSessionId:X||J.parentSessionId,status:"failed",error:Q,executionTimeMs:D,associatedTaskId:J.associatedTaskId};this.publishBackgroundEvent(l_.FAILED,A,X||J.parentSessionId,J.triggerEventId,J.replyChannel)}J.error=Q,h.error("[BackgroundTaskManager] Task execution error",{taskId:_,status:J.status,error:Q})}finally{this.finalizeTask(_,J.status);let G=J?._preserveSubSessionOnExit===!0,Q=this.getSessionComponent();if(!G&&Q?.endSessionCleanup&&J?.subSessionId)try{await Q.endSessionCleanup(J.subSessionId)}catch(H){h.warn(`[BackgroundTaskManager] endSessionCleanup failed for ${J.subSessionId}`,{error:H instanceof Error?H.message:String(H)})}else if(G)h.info(`[BackgroundTaskManager] Preserve sub session for ask_user resume: ${J.subSessionId}`)}}startProgressReporter(_,w){let $=setInterval(()=>{let X=this.tasks.get(_);if(!X||X.status!=="running"){this.stopProgressReporter(_);return}let J=U0();if(J!==void 0)X.associatedTaskId=J;X.lastUpdatedAt=Date.now();let Y={backgroundTaskId:_,subSessionId:X.subSessionId,parentSessionId:w,description:X.description,status:X.status,associatedTaskId:X.associatedTaskId};this.publishBackgroundEvent(l_.PROGRESS,Y,w,X.triggerEventId,X.replyChannel)},kU);this.progressTimers.set(_,$)}stopProgressReporter(_){let w=this.progressTimers.get(_);if(w)clearInterval(w),this.progressTimers.delete(_)}async executeWithAbort(_,w,$,X,J,Y,W,q,G){let Q=_?.metadata??{},H=Q.task_id,B=Q.task_description||"",D=_.id,z=Q.subagent_type,A=z||G||"general";if(!z&&!G)h.warn(`[delegate] subagent_type unresolved (no session metadata, no explicit value) \u2014 falling back to "general". sessionId=${D}`);let U=this.env?.getComponent?.("agent"),V=U?.getRegistry?.(),R=await OU(A,{registry:V}),f=A$(A),S=R?.basePrompt||f?.promptOverride||"You are a subagent. Complete this task: {task_description}",K=R?.deniedTools||f?.deniedTools||[],j=R?.allowedTools||f?.allowedTools,N=S.replace(/{task_description}/g,B||"N/A");if(N+=`
|
|
2337
|
+
- context: A JSON string containing time-space positioning information.
|
|
2338
|
+
This field is crucial for Agent task handoff.
|
|
2455
2339
|
|
|
2456
|
-
|
|
2340
|
+
**Required format**: Valid JSON string (parseable).
|
|
2457
2341
|
|
|
2458
|
-
|
|
2459
|
-
-
|
|
2460
|
-
-
|
|
2342
|
+
**Core fields**:
|
|
2343
|
+
- worktree_path: Git worktree path (for code development). Auto-detected.
|
|
2344
|
+
- branch: Current branch name
|
|
2345
|
+
- type: Work type classification (feature/bug/refactor/chore).
|
|
2346
|
+
\u26A0\uFE0F NOTE: This is the **context.type** (work classification), NOT the
|
|
2347
|
+
task's type field (normal/cycle/longterm). They are independent concepts.
|
|
2348
|
+
- created_at: ISO 8601 timestamp. Auto-injected if missing.
|
|
2461
2349
|
|
|
2462
|
-
|
|
2350
|
+
**Example for coding tasks**:
|
|
2351
|
+
{"worktree_path": "<worktree-path>", "branch": "<branch-name>", "type": "feature", "parent_branch": "main"}
|
|
2463
2352
|
|
|
2464
|
-
|
|
2465
|
-
|
|
2353
|
+
**Example for other tasks**:
|
|
2354
|
+
{"type": "general"}
|
|
2466
2355
|
|
|
2467
|
-
|
|
2356
|
+
If unable to fill in details, use at minimum:
|
|
2357
|
+
{"type": "unknown"}
|
|
2468
2358
|
|
|
2469
|
-
|
|
2470
|
-
- \u4F7F\u7528\u53EF\u7528\u5DE5\u5177\u5B8C\u6210\u4EFB\u52A1
|
|
2471
|
-
- \u8FD4\u56DE\u6E05\u6670\u7684\u4EFB\u52A1\u6267\u884C\u7ED3\u679C\u6458\u8981
|
|
2472
|
-
- \u9002\u65F6\u8C03\u7528 task_operation_create \u8BB0\u5F55\u8FDB\u5C55
|
|
2473
|
-
- \u5982\u679C\u4F60\u901A\u8FC7 task_create \u521B\u5EFA\u4E86\u4EFB\u52A1\uFF0C\u8BF7\u5728\u6700\u7EC8\u54CD\u5E94\u4E2D\u660E\u786E\u62A5\u544A task_id\uFF08\u4F8B\u5982\uFF1ATask #627\uFF09`,Y&&Y.length>0)try{let x=this.env?.getComponent?.("task");if(x){let i=[];for(let y of Y)try{let c=await x.getTask(y);if(!c){h.warn(`[delegate] Similar task #${y} not found, skipping`);continue}let H_=await x.listOperations({taskId:y,limit:10}),D_=`### Task #${c.id}: ${c.title}
|
|
2474
|
-
`;if(D_+=`- Status: ${c.status}
|
|
2475
|
-
`,c.description)D_+=`- Description: ${c.description}
|
|
2476
|
-
`;if(c.goals_and_expected_deliverables)D_+=`- Goals: ${c.goals_and_expected_deliverables}
|
|
2477
|
-
`;if(H_&&H_.length>0){D_+=`- Recent Operations:
|
|
2478
|
-
`;for(let Kw of H_)D_+=` - [${Kw.actionType}] ${Kw.actionTitle}: ${Kw.actionDescription||""}
|
|
2479
|
-
`}i.push(D_)}catch(c){h.warn(`[delegate] Failed to fetch similar task #${y}`,{error:c instanceof Error?c.message:String(c)})}if(i.length>0)N+=`
|
|
2359
|
+
**DO NOT leave this as plain text** - it must be valid JSON!
|
|
2480
2360
|
|
|
2481
|
-
|
|
2361
|
+
**Note**: malformed JSON (non-parseable) will be preserved as-is
|
|
2362
|
+
rather than rejected, to preserve backward compatibility. The
|
|
2363
|
+
auto-injection of \`created_at\` / \`worktree_path\` is best-effort.
|
|
2482
2364
|
|
|
2483
|
-
##
|
|
2365
|
+
## Task Binding Inheritance (Task #4023)
|
|
2484
2366
|
|
|
2485
|
-
|
|
2367
|
+
When this tool is called from inside a per-task group chat, the
|
|
2368
|
+
event-source handler resolves the chat\u2194task binding and injects the
|
|
2369
|
+
bound task id into \`EnvContext.parentTaskId\`. This tool reads that
|
|
2370
|
+
value and uses it as the default \`parent_task_id\`, so the LLM
|
|
2371
|
+
doesn't need to know the task tree to attach subtasks to the
|
|
2372
|
+
correct parent.
|
|
2486
2373
|
|
|
2487
|
-
|
|
2488
|
-
|
|
2374
|
+
Priority order (highest \u2192 lowest):
|
|
2375
|
+
1. Caller's explicit \`parent_task_id\` (always wins)
|
|
2376
|
+
2. \`EnvContext.parentTaskId\` injected from chat binding
|
|
2377
|
+
3. No parent (creates a root task, as before)
|
|
2489
2378
|
|
|
2490
|
-
|
|
2379
|
+
When the env-injected parent doesn't exist in the DB, the tool
|
|
2380
|
+
fails fast (does not silently create an orphan). When the
|
|
2381
|
+
env-injected value is 0 / negative / non-integer, it's treated as
|
|
2382
|
+
missing \u2014 only positive integers are honored.
|
|
2491
2383
|
|
|
2492
|
-
|
|
2384
|
+
`,parameters:p5,execute:async(w,$)=>{let X=p5.parse(w),Y=$.session_id||"unknown",J=CU(),W=X.context,Q=$1().parentTaskId,G=X.parent_task_id!==void 0&&X.parent_task_id!==null?X.parent_task_id:Q!==void 0&&Q!==null&&Number.isInteger(Q)&&Q>0?Q:void 0,q=X.project_path&&X.project_path.trim()!==""?X.project_path:void 0,H=q!==void 0&&q!==d5,B=H?q:void 0,D=X.tags,O;if(G!==void 0)try{let z=await _.getTask(G);if(z){let U=ZU({parent:{taskId:z.id,projectPath:z.project_path,contextJson:z.context??"",tags:z.tags},overrides:{projectPath:B,branch:void 0,worktreePath:void 0,inheritTags:X.tags===void 0,contextInherit:!0}});if(B===void 0)B=U.project_path;if(X.tags===void 0)D=U.inheritedTags;O=U.context}}catch(z){wX.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 M=JSON.parse(O);if(M&&typeof M==="object"&&!Array.isArray(M)){for(let[f,N]of Object.entries(M))if(V[f]===void 0)V[f]=N}}catch{}if(!V.created_at)V.created_at=new Date().toISOString();if(!V.worktree_path&&J)V.worktree_path=J;W=JSON.stringify(V)}catch{W=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:D,sessionId:Y,project_path:B??(H?q:d5),context:W});return v0(z.id),wX.info(`[createTask] Trace: Task #${z.id} created, currentTaskId=${z.id} set in EnvContext`),{success:!0,output:`Task created successfully: #${z.id} - ${z.title}`,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 m0(_){return{name:"task_get",description:"Get task details by ID. Optionally include operation records.",parameters:i5,execute:async(w,$)=>{let X=i5.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,W=J&&typeof J==="object"?{...J,operations:Y.operations}:Y;return{success:!0,output:JSON.stringify(W,null,2),metadata:{execution_time_ms:0}}}else{let Y=await _.getTask(X.task_id);if(!Y)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return{success:!0,output:JSON.stringify(Y,null,2),metadata:{execution_time_ms:0}}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}function u0(_){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
|
|
2385
|
+
`+"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:n5,execute:async(w,$)=>{let X=n5.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 l0(_){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.
|
|
2493
2386
|
|
|
2494
|
-
|
|
2387
|
+
Returns { tasks, total, limit, offset } so you can paginate large result sets.
|
|
2495
2388
|
|
|
2496
|
-
|
|
2389
|
+
If \`keywords\` is empty, returns no results.`,parameters:r5,execute:async(w,$)=>{let X=r5.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 z4(_){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.
|
|
2497
2390
|
|
|
2498
|
-
|
|
2499
|
-
${LU(J)}
|
|
2391
|
+
Use this when you need to quickly archive a group of completed, obsolete, or historical tasks (e.g., during task organization).
|
|
2500
2392
|
|
|
2501
|
-
|
|
2393
|
+
Returns summary of how many tasks were successfully archived and any errors encountered.`,parameters:t5,execute:async(w,$)=>{let X=t5.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 W=[],Q=0;for(let q of Y)try{if(await _.updateTask(q,{status:"archived"}))await _.createOperation({taskId:q,sessionId:J,actionType:"completed",actionTitle:"Batch archived",actionDescription:X.reason||"\u6279\u91CF\u5F52\u6863\uFF08\u4EFB\u52A1\u6574\u7406\uFF09"}),Q++,W.push({id:q,success:!0});else W.push({id:q,success:!1,error:"Task not found"})}catch(H){W.push({id:q,success:!1,error:H instanceof Error?H.message:String(H)})}return{success:!W.some((q)=>!q.success),output:JSON.stringify({archived_count:Q,total:Y.length,errors:W.filter((q)=>!q.success).map((q)=>({id:q.id,error:q.error})),results:W},null,2),metadata:{execution_time_ms:0}}}}}function V4(_){return{name:"task_batch_delete",description:`Batch delete multiple tasks at once. Deletes each task and all its operation records.
|
|
2502
2394
|
|
|
2503
|
-
|
|
2504
|
-
- When you need to perform complex, multi-step tasks that require independent execution
|
|
2505
|
-
- When you need to explore a codebase thoroughly (use "explore" subagent)
|
|
2506
|
-
- When you need to run long-running tasks without blocking the main agent
|
|
2395
|
+
Use this when you need to quickly remove a group of test, temporary, or otherwise worthless tasks (e.g., during task organization).
|
|
2507
2396
|
|
|
2508
|
-
|
|
2509
|
-
|
|
2510
|
-
- **bgProcessId**: Internal background process ID (use with \`stop_task\` to cancel, different from Task #)
|
|
2511
|
-
- **subSessionId**: Sub-agent session ID (use with \`session_get\` to see full execution log, always retained)
|
|
2397
|
+
Returns summary of how many tasks were successfully deleted and any errors encountered.`,parameters:e5,execute:async(w,$)=>{let Y=e5.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=[],W=0;for(let G of Y)try{if(await _.deleteTask(G))W++,J.push({id:G,success:!0});else J.push({id:G,success:!1,error:"Task not found"})}catch(q){J.push({id:G,success:!1,error:q instanceof Error?q.message:String(q)})}return{success:!J.some((G)=>!G.success),output:JSON.stringify({deleted_count:W,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}}}}}Jw();a();var TU=n("tool:update-task");async function IU(_,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 c0(_){return{name:"task_update",description:"Update an existing task's properties. Status and progress changes will create operation records.",parameters:a5,execute:async(w,$)=>{let X=a5.parse(w),Y=$.session_id||"unknown";try{if(X.parent_task_id!==void 0&&X.parent_task_id!==null){if(await IU(_,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 v0(J.id),TU.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 O4(_){return{name:"task_delete",description:"Delete a task and all its operation records.",parameters:o5,execute:async(w,$)=>{let X=o5.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}}}}}}Jw();a();var kU=n("task:tools:complete"),gU=`
|
|
2398
|
+
Mark a task as completed (progress=100, status=completed). Creates an operation record.
|
|
2512
2399
|
|
|
2513
|
-
**
|
|
2514
|
-
- \u2705 **completed** \u2014 with \`bgprocess:\` + \`Task #\` (if it created a task) + result summary
|
|
2515
|
-
- \u23F1\uFE0F **timeout** \u2014 with \`bgprocess:\` + \`Task #\` (if available)
|
|
2516
|
-
- \u274C **failed** \u2014 with \`bgprocess:\` + \`Task #\` + error details
|
|
2517
|
-
- \uD83D\uDED1 **stopped** \u2014 with \`bgprocess:\` + \`Task #\`
|
|
2400
|
+
**Before calling this tool**, you MUST:
|
|
2518
2401
|
|
|
2519
|
-
|
|
2520
|
-
|
|
2402
|
+
1. Read the task's \`goal\` (description) and \`delivery\` (goals_and_expected_deliverables) fields.
|
|
2403
|
+
- Use \`task_get(task_id=<id>)\` to fetch the full task record.
|
|
2404
|
+
2. **Validate** whether the goal and delivery match what you actually delivered.
|
|
2405
|
+
- If mismatch, either: (a) extend the task via \`task_update\`, or (b) honestly note the discrepancy in your final report.
|
|
2406
|
+
3. **Provide \`deliverable_storage_path\`** parameter with the deliverable's address:
|
|
2407
|
+
- Feishu doc URL (e.g., https://my.feishu.cn/docx/abc)
|
|
2408
|
+
- Local file path (e.g., /tmp/report.md)
|
|
2409
|
+
- Git branch or worktree path (e.g., feature/my-feature)
|
|
2410
|
+
- GitHub commit URL or PR URL
|
|
2411
|
+
- Cloud drive URL (e.g., https://my.feishu.cn/file/abc)
|
|
2412
|
+
- Or any other locator that points to where the work product lives
|
|
2521
2413
|
|
|
2522
|
-
|
|
2523
|
-
- **description**: A short (3-5 words) description of the task
|
|
2524
|
-
- **prompt**: The task for the agent to perform
|
|
2525
|
-
- **subagent_type**: The type of specialized agent to use (e.g., "general", "explore")
|
|
2526
|
-
- **timeout**: Task timeout in milliseconds (optional, default 30 minutes)
|
|
2527
|
-
- **reason**: Brief reason for calling this tool (optional)
|
|
2528
|
-
- **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:GX,execute:async(W,q)=>{let G=Date.now(),Q=GX.parse(W),{description:H,prompt:B,subagent_type:D="general",timeout:z,reason:A,similar_task_ids:U}=Q,V=q.session_id||"default",R=Q.triggerEventId??yU();if(R&&R!==Q.triggerEventId)h.info(`[delegate_task] triggerEventId auto-derived from EnvContext: ${R}`);if(h.info(`[delegate_task] Called: description=${H}, subagent_type=${D}, triggerEventId=${R??"(none)"}`),R){let g=d4();if(g)try{if(!await g.getEventById(R))return{success:!1,output:"",error:`Unknown triggerEventId: ${R} (not found in EventStore)`,metadata:{execution_time_ms:Date.now()-G}}}catch(E){return{success:!1,output:"",error:`Failed to verify triggerEventId ${R}: ${E instanceof Error?E.message:String(E)}`,metadata:{execution_time_ms:Date.now()-G}}}else h.warn(`[delegate_task] triggerEventId=${R} supplied but no shared EventStore registered; skipping verification`)}let f=QX(_);if(!RU(D,f))return{success:!1,output:"",error:`Unknown subagent type: ${D}`,metadata:{execution_time_ms:Date.now()-G}};let S=_.getTagService(),K=B,j={prompt:K,subagentType:D,timeout:z,reason:A,tagService:S},N={component:{name:"task",version:"1.0.0"},data:j,metadata:{sessionId:V},phase:"before",hookPoint:w_.DELEGATE_BEFORE};return await j_.execute(w_.DELEGATE_BEFORE,j,{sessionId:V}),K=j.prompt,await mU(X,V,H,K,j.subagentType,j.timeout,U,Q.sub_session_id,R)}};return Y.execute=T_(Y.execute,"delegate.execute",{recordParams:!0,recordResult:!1,recordError:!0}),Y}function hU(){let _=uw();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 yU=T_(hU,"delegate.deriveTriggerEventId",{recordParams:!1,recordResult:!0,recordError:!0});function vU(){let _=uw()?.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 xU=T_(vU,"delegate.captureReplyChannel",{recordParams:!1,recordResult:!0,recordError:!0});async function mU(_,w,$,X,J,Y,W,q,G){let Q=Date.now();try{let H=J,B=X,D,z=_.resolveEntryAgent(J);if(z)D=J,H=z,B=IU({workflowName:D,originalPrompt:X,description:$}),h.info(`[delegate_task] Routing workflow subagent '${J}' \u2192 entry-agent '${z}'`);let{taskId:A,subSessionId:U}=await _.createTask({parentSessionId:w,description:$,prompt:B,subagentType:H,timeout:Y,similarTaskIds:W,originalWorkflowName:D,existingSubSessionId:q,triggerEventId:G});return{success:!0,output:["\u2705 Background task accepted","",`\uD83D\uDCCB Process ID: ${A}`,`\uD83D\uDCDD Description: ${$}`,`\uD83E\uDD16 Sub-agent: ${H}${D?` (workflow: ${D})`:""}`,`\u23F1\uFE0F Timeout: ${(Y||DX)/1000}s`,"",`Use stop_task with task_id="${A}" to cancel this task.`].join(`
|
|
2529
|
-
`),metadata:{execution_time_ms:Date.now()-Q,sessionId:U,background:!0,status:"accepted",bgProcessId:A}}}catch(H){return{success:!1,output:"",error:H instanceof Error?H.message:String(H),metadata:{execution_time_ms:Date.now()-Q}}}}var HX=M.object({task_id:M.string().describe("The ID of the background task to stop")}),uU=`Stop a running background task.
|
|
2414
|
+
The \`deliverable_storage_path\` will be persisted to the task's \`context.deliverable_storage_path\` for future reference and traceability.
|
|
2530
2415
|
|
|
2531
|
-
|
|
2532
|
-
-
|
|
2533
|
-
-
|
|
2534
|
-
- The user wants to change direction and doesn't need the task result anymore
|
|
2416
|
+
**Restrictions**:
|
|
2417
|
+
- Cannot complete cycle-type tasks (they are periodic). Use \`task_update\` to reset progress instead.
|
|
2418
|
+
- Marks the task as 100% complete; use \`task_update\` to record partial progress first if needed.
|
|
2535
2419
|
|
|
2536
|
-
|
|
2420
|
+
**Backward compatibility**: \`deliverable_storage_path\` is optional. Existing callers that omit it continue to work as before.
|
|
2421
|
+
`.trim();function d0(_){return{name:"task_complete",description:gU,parameters:s5,execute:async(w,$)=>{let X=s5.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 W=await _.completeTask(X.task_id,Y,X.deliverable_storage_path);if(!W)return{success:!1,output:"",error:`Task not found: ${X.task_id}`,metadata:{execution_time_ms:0}};return v0(void 0),kU.info(`[completeTask] Trace: Task #${X.task_id} completed, deliverable=${X.deliverable_storage_path||"(none)"}, currentTaskId cleared from EnvContext`),{success:!0,output:X.deliverable_storage_path?`Task completed: #${W.id} - ${W.title}
|
|
2422
|
+
Deliverable (context + operation): ${X.deliverable_storage_path}`:`Task completed: #${W.id} - ${W.title}
|
|
2423
|
+
Deliverable: (no path provided)`,metadata:{execution_time_ms:0,task:W}}}catch(J){return{success:!1,output:"",error:J instanceof Error?J.message:String(J),metadata:{execution_time_ms:0}}}}}}function $X(_,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 XX(_,w){if(w<0)return _;if(w===0)return _.map(($)=>({...$,children:[]}));return _.map(($)=>({...$,children:XX($.children,w-1)}))}function YX(_){let w=0;for(let $ of _)w+=1+YX($.children);return w}function hU(_){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 W=$.get(J)||[];W.push(Y),$.set(J,W)}else X.push(Y)}for(let[Y,J]of $.entries()){let W=w.get(Y);J.sort($X),W.children=J.map((Q)=>w.get(Q.id))}return X.sort($X),X.map((Y)=>w.get(Y.id))}function p0(_){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
|
+
- total: count of ALL tasks in the returned tree (incl. descendants)
|
|
2425
|
+
- truncated: always false for now (no pagination cap on tree)
|
|
2426
|
+
- depth: the resolved depth value
|
|
2427
|
+
- parent_task_id: the root's id, or null for forest mode
|
|
2428
|
+
- 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:_X,execute:async(w,$)=>{let X=_X.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 q=await _.getTaskTree(X.parent_task_id,X.depth===-1?-1:Math.max(0,X.depth-1));Y=[G,...q]}}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 W=hU(Y);if(X.parent_task_id===void 0||X.parent_task_id===null)W=XX(W,X.depth);let Q=YX(W);return{success:!0,output:JSON.stringify({total:Q,truncated:!1,depth:X.depth,parent_task_id:J,nodes:W}),metadata:{execution_time_ms:0}}}catch(Y){return{success:!1,output:"",error:Y instanceof Error?Y.message:String(Y),metadata:{execution_time_ms:0}}}}}}var Q1=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),A4=100,M4=150,G1=5000,yU=1,q1=200,HX=A.string().min(A4,{message:`process_description \u592A\u77ED\uFF08\u5C11\u4E8E ${A4} \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(M4,{message:`process_description \u592A\u957F\uFF08\u8D85\u8FC7 ${M4} \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 ${A4}-${M4} \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"),DX=A.string().min(yU,{message:"milestone_title \u4E0D\u80FD\u4E3A\u7A7A"}).max(q1,{message:`milestone_title \u8D85\u8FC7 ${q1} \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"),BX=A.string().max(G1,{message:`milestone_description \u8D85\u8FC7 ${G1} \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"),vU=A.object({task_id:A.number().describe("Task ID"),milestone_type:Q1.optional(),milestone_title:DX.optional(),milestone_description:BX,process_description:HX.optional(),action_type:Q1.optional(),action_title:A.string().min(1).max(q1).optional(),action_description:A.string().max(G1).optional(),md_path:A.string().optional().describe("Path to detailed markdown documentation")}),JX=vU.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}}),WX=A.object({operation_id:A.number().describe("Operation ID")}),QX=A.object({task_id:A.number().describe("Task ID"),milestone_type:Q1.optional(),action_type:Q1.optional(),limit:A.number().optional().default(20),offset:A.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}}),xU=A.object({operation_id:A.number().describe("Operation ID"),milestone_title:DX.optional(),milestone_description:BX,process_description:HX.optional(),action_title:A.string().min(1).max(q1).optional(),action_description:A.string().max(G1).optional()}),GX=xU.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}}),qX=A.object({operation_id:A.number().describe("Operation ID")});function mU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function uU(_){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 i0(_){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-150 chars) captures HOW. Legacy action_* fields are accepted as deprecated aliases.",parameters:JX,execute:async(w,$)=>{let X;try{X=JX.parse(w)}catch(W){if(W instanceof W_)return{success:!1,output:"",error:mU(W),metadata:{execution_time_ms:0}};throw W}let Y=uU(X);if(!Y.ok)return{success:!1,output:"",error:Y.error,metadata:{execution_time_ms:0}};let J=$.session_id||"unknown";try{let W=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}),Q=`Operation created: #${W.id} for task #${W.taskId} [milestone=${W.milestoneType}] ${W.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)Q+=`
|
|
2537
2430
|
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
`);
|
|
2542
|
-
`);return{success:!1,output:G,error:W.message,metadata:{execution_time_ms:Date.now()-X,task_id:Y}}}}}}function zX(_,w,$){let X=w.toUpperCase();if(!_.startsWith(X))return;let J=$.replace(/-/g,"_").toUpperCase(),Y=_.slice(X.length);if(Y.startsWith("_"))Y=Y.slice(1);if(!Y)return;let W=Y.indexOf("_"),q;if(W===-1)q=Y;else{let Q=Y.slice(0,W),H=Y.slice(W+1);if(Q===J)q=H;else q=Y}if(!q)return;let G=q.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function VX(_,w){return{..._,execute:w}}var cU=()=>{},AX=r(()=>{cU(),B$(),_0()});AX();class M${_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(_,VX({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 dU={"task.storage.type":"sqlite","task.storage.dbPath":void 0},pU={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 iU=["completed","failed","cancelled","timeout"];a_();a();var r0=n("task:tag");class MX{store;constructor(_){this.store=_}async createTag(_){let w=await this.store.createTag(_);return r0.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)r0.debug(`[TagService] Deleted tag id=${_}`);return w}async addTagsToTask(_,w){await this.store.addTagsToTask(_,w),r0.debug(`[TagService] Added ${w.length} tags to task ${_}`)}async removeTagsFromTask(_,w){await this.store.removeTagsFromTask(_,w),r0.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(_),J=new Set(X.map((G)=>G.id)),Y=new Set($),W=$.filter((G)=>!J.has(G)),q=X.filter((G)=>!Y.has(G.id)).map((G)=>G.id);if(q.length>0)await this.store.removeTagsFromTask(_,q);if(W.length>0)await this.store.addTagsToTask(_,W);await this.store.updateTaskTags(_,w),r0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}z_();var J_=n("task"),rU="Deliverable: ";function nU(_){if(!_)return;return`${rU}${_}`}class fw extends M${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:J}=_,Y=X??"TASK";if(w.registerComponent(pU),$)w.registerSource({type:"file",relativePath:$,optional:!0,watch:!1});w.registerSource({type:"env",envPrefix:Y,priority:20,watch:!1}),await w.load("task");for(let W of Object.keys(process.env)){let q=zX(W,Y,"task");if(!q)continue;let G=process.env[W];if(G!==void 0)await w.set(q,G)}for(let[W,q]of Object.entries(dU))if(w.get(W)===void 0)await w.set(W,q);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",G1());if(J){let W=this.flattenConfig(J);for(let[q,G]of Object.entries(W))await w.set(q,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new MX(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 Dw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Dw,J_.info("[TaskComponent] Using SQLite storage (default)")}flattenConfig(_,w="task"){let $={};for(let[X,J]of Object.entries(_)){let Y=`${w}.${X}`;if(J&&typeof J==="object"&&!Array.isArray(J))Object.assign($,this.flattenConfig(J,Y));else $[Y]=J}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 e(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(W1(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(W1(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 _=[V0(this),A0(this),M0(this),f0(this),R0(this),x2(this),m2(this),O0(this),u2(this),F0(this)],w=[L0(this),d2(this),K0(this),p2(this),i2(this)],$=[BX(this),UX(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 j_.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(w_.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 J={task:X,sessionId:w,tagService:this.tagService};return await this.executeHook(w_.AFTER_CREATE,J),this.publishEvent(Uw.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{task:w,operations:$}}async updateTask(_,w){let $={id:_,options:{...w},tagService:this.tagService};await this.executeHook(w_.BEFORE_UPDATE,$);let X=await this.store.updateTask(_,$.options);if(X){let J={task:X,changes:w,tagService:this.tagService};if(await this.executeHook(w_.AFTER_UPDATE,J),this.publishEvent(Uw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&iU.includes(w.status)){let Y=Q1(),W={task:X,changes:w,terminalStatus:w.status,sessionId:Y.sessionId??"",tagService:this.tagService};await this.executeHook(w_.AFTER_COMPLETE,W),J_.info(`[TaskComponent] Task completed (AFTER_COMPLETE fired): ${_} -> ${w.status}`)}}return X}async deleteTask(_){let w={id:_};await this.executeHook(w_.BEFORE_DELETE,w);let $=await this.store.deleteTask(_),X={id:_,deleted:$};if(await this.executeHook(w_.AFTER_DELETE,X),$)this.publishEvent(Uw.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 J={status:"completed",progress:100};if($){let W={};if(X?.context)try{let q=JSON.parse(X.context);if(q&&typeof q==="object"&&!Array.isArray(q))W=q}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}W.deliverable_storage_path=$,J.context=JSON.stringify(W)}let Y=await this.updateTask(_,J);if(Y)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:nU($)}),this.publishEvent(Uw.COMPLETED,{task:Y,sessionId:w},w),J_.info(`[TaskComponent] Task completed: ${_}, deliverable=${$||"(none)"}`);return Y}async createOperation(_){let w={options:{..._}};await this.executeHook(w_.OPERATION_BEFORE_CREATE,w);let $=await this.store.createOperation(w.options),X=await this.store.getTask($.taskId),J={operation:$};return await this.executeHook(w_.OPERATION_AFTER_CREATE,J,{task:X,operation:$}),this.publishEvent(Uw.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){j_.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 $=j_.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 j_.count(_)}}m([u("task.component.executeHook",{recordParams:!0})],fw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],fw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],fw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],fw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],fw.prototype,"createOperation",null);var R$=M.enum(["todo","active","completed","paused","cancelled","archived"]),O$=M.enum(["low","medium","high"]),F$=M.enum(["normal","cycle","longterm"]),f$=M.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),aU=M.object({storage:M.object({type:M.enum(["memory","sqlite"]).default("sqlite"),dbPath:M.string().optional()}).default({})}).default({});var oU="Deliverable: ";function sU(_){if(!_)return;return`${oU}${_}`}var q2=1e6;class L${port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=tU(_);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:q2,offset:0,includeArchived:!0})).tasks}async createTask(_){let w=_.sessionId??this.defaultSessionId,$;if(_.parent_task_id!==void 0&&_.parent_task_id!==null){let J=await this.resolve(_.parent_task_id);if(!J)throw Error(`Parent task #${_.parent_task_id} not found.`);$=J.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:q2,offset:0});return{...w,operations:$}}async listTasks(_={}){let w=_.limit??20,$=_.offset??0,X=(await this.scanAllTasks()).map((J)=>this.toTask(J));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 Y=await this.resolve(w.parent_task_id);if(!Y)throw Error(`Parent task #${w.parent_task_id} not found.`);X=Y.id}let J=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 J?this.toTask(J):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 J={status:"completed",progress:100};if($)J.context=_z(X.context,$);let Y=await this.port.updateTask(X.nativeId,J);if(!Y)return null;let W=sU($);await this.createOperation({taskId:Y.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${Y.title}`,milestoneDescription:W??"Task completed",...$?{mdPath:$}:{}});let q=await this.resolve(X.nativeId);return this.toTask(q??Y)}async getTaskTree(_,w=-1){let $=await this.resolve(_);if(!$)return[];if(w===0)return[];let X=(await this.scanAllTasks()).map((Q)=>this.toTask(Q)),J=new Map;for(let Q of X){if(Q.parent_task_id===void 0)continue;let H=J.get(Q.parent_task_id)??[];H.push(Q),J.set(Q.parent_task_id,H)}let Y=[],W=new Set([$.id]),q=[$.id],G=0;while(q.length>0){if(w!==-1&&G>=w)break;let Q=[];for(let H of q)for(let B of J.get(H)??[]){if(W.has(B.id))continue;W.add(B.id),Y.push(B),Q.push(B.id)}q=Q,G++}return Y}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,J=(await this.scanAllTasks()).map((q)=>this.toTask(q));if(J=this.applyFilters(J,w),w.excludeTaskId!==void 0)J=J.filter((q)=>q.id!==w.excludeTaskId);let Y=_.map((q)=>q.toLowerCase()).filter((q)=>q.length>0),W=Y.length===0?J:J.filter((q)=>{let G=[q.title,q.description,q.goals_and_expected_deliverables,q.current_status,(q.tags??[]).join(" "),q.project_path].join(" ").toLowerCase();return Y.every((Q)=>G.includes(Q))});return{tasks:W.slice(X,X+$),total:W.length}}async createOperation(_){let w=await this.resolve(_.taskId);if(!w)throw Error(`Task not found: ${_.taskId}`);let $=_.milestoneType??_.actionType??"progress",X=_.milestoneTitle??_.actionTitle??"",J=_.milestoneDescription??_.actionDescription??"",Y=await this.port.createOperation({taskId:w.id,taskNativeId:w.nativeId,sessionId:_.sessionId??this.defaultSessionId,milestoneType:$,milestoneTitle:X,milestoneDescription:J,processDescription:_.processDescription??"",..._.mdPath?{mdPath:_.mdPath}:{}});return this.toOperation(Y)}async listOperations(_={}){let w=_.limit??100,$=_.offset??0,X=_.milestoneType??_.actionType;if(_.taskId===void 0)return[];let J=await this.resolve(_.taskId);if(!J)return[];let W=(await this.port.listOperations({taskNativeId:J.nativeId,limit:X?q2:w,offset:X?0:$})).operations.map((q)=>this.toOperation(q));if(X)W=W.filter((q)=>q.milestoneType===X),W=W.slice($,$+w);return W}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 J=(await this.port.listOperations({taskNativeId:$.nativeId,limit:q2})).operations.find((Y)=>Y.id===_);if(J)return this.toOperation(J)}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((J)=>J.status!=="archived");if(w.status!==void 0)$=$.filter((J)=>J.status===w.status);if(w.priority!==void 0)$=$.filter((J)=>J.priority===w.priority);if(w.type!==void 0)$=$.filter((J)=>J.type===w.type);if(w.parent_task_id!==void 0)$=$.filter((J)=>J.parent_task_id===w.parent_task_id);if(w.depth!==void 0&&w.depth>=0){let J=eU($,w.depth);$=$.filter((Y)=>J.has(Y.id))}return $}}function tU(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function eU(_,w){if(w<0)return new Set(_.map((W)=>W.id));let $=new Set(_.map((W)=>W.id)),X=new Map;for(let W of _){let q=W.parent_task_id;if(q===void 0||!$.has(q))continue;let G=X.get(q)??[];G.push(W),X.set(q,G)}let J=new Set,Y=_.filter((W)=>W.parent_task_id===void 0||!$.has(W.parent_task_id));for(let W of Y)J.add(W.id);for(let W=1;W<=w;W++){let q=[];for(let G of Y)for(let Q of X.get(G.id)??[]){if(J.has(Q.id))continue;J.add(Q.id),q.push(Q)}if(q.length===0)break;Y=q}return J}function _z(_,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 wz=1e6;function $z(_){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 n0(_,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 a0(_){let w=_.data??{},$=String(w.milestoneType??w.actionType??"progress"),X=String(w.milestoneTitle??w.actionTitle??""),J=String(w.milestoneDescription??w.actionDescription??""),Y=w.taskId??_.task_id,W=typeof Y==="number"?Y:typeof Y==="string"&&/^\d+$/.test(Y)?Number(Y):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:W,sessionId:String(w.sessionId??_.task_id??"unknown"),milestoneType:$,milestoneTitle:X,milestoneDescription:J,processDescription:String(w.processDescription??""),timestamp:_.created_at,...w.mdPath?{mdPath:String(w.mdPath)}:{},actionType:$,actionTitle:X,actionDescription:J}}function RX(_,w,$={}){let X=$.operationType??"roy.milestone",J=$.agent??"roy",Y=$.scanLimit??wz;async function W(){let Q=await _.listTasks({limit:Y});return new Map(Q.tasks.filter((H)=>typeof H.num==="number").map((H)=>[H.id,H.num]))}async function q(Q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(Q);return(await _.listTasks({limit:Y})).tasks.find((B)=>B.num===Q)??null}async function G(Q){let B=[...(await W()).entries()].find(([,D])=>D===Q);if(!B)throw Error(`parent task not found: ${Q}`);return B[0]}return{hidesArchivedByDefault:!1,async createTask(Q){let H=Q.parent_task_id!==void 0?await G(Q.parent_task_id):null,B={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}:{}},D=await _.createTask({title:Q.title,description:Q.description,priority:w.toStorePriority(Q.priority),owner:J,tags:w.toStoreTags(Q.tags),parent_id:H,session_id:Q.sessionId??"unknown",roy:B});return n0(D,w,Q.parent_task_id)},async getTask(Q){let H=await _.getTask(Q);if(!H)return null;let B=await W();return n0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async getTaskByNum(Q){let H=await q(Q);if(!H)return null;let B=await W();return n0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async listTasks(Q){let H=await _.listTasks({limit:Q?.limit??20,offset:Q?.offset??0}),B=await W();return{tasks:H.tasks.map((D)=>n0(D,w,D.parent_id?B.get(D.parent_id):void 0)),total:H.total}},async updateTask(Q,H){let B=$z(H),D=await _.updateTask(Q,{...H.title!==void 0?{title:H.title}:{},...H.description!==void 0?{description:H.description}:{},...H.status!==void 0?{status:w.toStoreStatus(H.status)}:{},...H.priority!==void 0?{priority:w.toStorePriority(H.priority)}:{},...H.tags!==void 0?{tags:w.toStoreTags(H.tags)}:{},...Object.keys(B).length>0?{roy:B}:{}});if(!D)return null;let z;if(H.parent_task_id!==void 0){let U=H.parent_task_id===null?null:await G(H.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(Q,U);z=H.parent_task_id===null?void 0:H.parent_task_id}let A=await _.getTask(Q)??D;if(z===void 0&&A.parent_id)z=(await W()).get(A.parent_id);return n0(A,w,z)},async deleteTask(Q){return await _.deleteTask(Q)},async createOperation(Q){let H=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 a0(H)},async listOperations(Q){let H=await _.listOperations({...Q?.taskNativeId?{task_id:Q.taskNativeId}:{},type:X,limit:Q?.limit??Y,offset:Q?.offset??0});return{operations:H.operations.map(a0),total:H.total}},async getOperationByNum(Q){if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(Q);return H?a0(H):null},async updateOperationByNum(Q,H){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let B=await _.getOperationByNum(Q);if(!B)return null;let D=a0(B),z=await _.updateOperation(Q,{data:{taskId:D.taskId,sessionId:H.sessionId??D.sessionId,milestoneType:H.milestoneType??D.milestoneType,milestoneTitle:H.milestoneTitle??D.milestoneTitle,milestoneDescription:H.milestoneDescription??D.milestoneDescription,processDescription:H.processDescription??D.processDescription,...H.mdPath??D.mdPath?{mdPath:H.mdPath??D.mdPath}:{}}});return z?a0(z):null},async deleteOperationByNum(Q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(Q)}}}var Xz="roy.milestone",Jz={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Yz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function OX(_){return Jz[_]??"pending"}function FX(_){return Yz[_]??"todo"}function fX(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function LX(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function KX(_){if(!_||_.length===0)return;return _.join(",")}function NX(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var Wz={toRoyStatus:(_)=>FX(_),toStoreStatus:(_)=>OX(_),toRoyPriority:(_)=>LX(_),toStorePriority:(_)=>fX(_),toRoyTags:(_)=>NX(_),toStoreTags:(_)=>KX(_)};function bX(_,w={}){return new L$(RX(_,Wz,{operationType:Xz,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var $O=R$.options,XO=O$.options,JO=F$.options,YO=f$.options;var EX=Symbol("Let zodToJsonSchema decide on which parser to use");var jX={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"},SX=(_)=>typeof _==="string"?{...jX,name:_}:{...jX,..._};var PX=(_)=>{let w=SX(_),$=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,J])=>[J._def,{def:J._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,J){_[w]=$,K$(_,w,X,J)}var G2=(_,w)=>{let $=0;for(;$<_.length&&$<w.length;$++)if(_[$]!==w[$])break;return[(_.length-$).toString(),...w.slice($)].join("/")};function o(_){if(_.target!=="openAi")return{};let w=[..._.basePath,_.definitionPath,_.openAiAnyTypeName];return _.flags.hasReferencedOpenAiAnyType=!0,{$ref:_.$refStrategy==="relative"?G2(w,_.currentPath):w.join("/")}}function ZX(_,w){let $={type:"array"};if(_.type?._def&&_.type?._def?.typeName!==F.ZodAny)$.items=I(_.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 CX(_,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 TX(){return{type:"boolean"}}function Q2(_,w){return I(_.type._def,w)}var IX=(_,w)=>{return I(_.innerType._def,w)};function N$(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((J,Y)=>N$(_,w,J))};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 qz(_,w)}}var qz=(_,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 gX(_,w){return{...I(_.innerType._def,w),default:_.defaultValue()}}function kX(_,w){return w.effectStrategy==="input"?I(_.schema._def,w):o(w)}function hX(_){return{type:"string",enum:Array.from(_.values)}}var Gz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function yX(_,w){let $=[I(_.left._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),I(_.right._def,{...w,currentPath:[...w.currentPath,"allOf","1"]})].filter((Y)=>!!Y),X=w.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,J=[];return $.forEach((Y)=>{if(Gz(Y)){if(J.push(...Y.allOf),Y.unevaluatedProperties===void 0)X=void 0}else{let W=Y;if("additionalProperties"in Y&&Y.additionalProperties===!1){let{additionalProperties:q,...G}=Y;W=G}else X=void 0;J.push(W)}}),J.length?{allOf:J,...X}:void 0}function vX(_,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 b$=void 0,E_={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(b$===void 0)b$=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return b$},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 H2(_,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":S_($,"email",X.message,w);break;case"format:idn-email":S_($,"idn-email",X.message,w);break;case"pattern:zod":G_($,E_.email,X.message,w);break}break;case"url":S_($,"uri",X.message,w);break;case"uuid":S_($,"uuid",X.message,w);break;case"regex":G_($,X.regex,X.message,w);break;case"cuid":G_($,E_.cuid,X.message,w);break;case"cuid2":G_($,E_.cuid2,X.message,w);break;case"startsWith":G_($,RegExp(`^${j$(X.value,w)}`),X.message,w);break;case"endsWith":G_($,RegExp(`${j$(X.value,w)}$`),X.message,w);break;case"datetime":S_($,"date-time",X.message,w);break;case"date":S_($,"date",X.message,w);break;case"time":S_($,"time",X.message,w);break;case"duration":S_($,"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":{G_($,RegExp(j$(X.value,w)),X.message,w);break}case"ip":{if(X.version!=="v6")S_($,"ipv4",X.message,w);if(X.version!=="v4")S_($,"ipv6",X.message,w);break}case"base64url":G_($,E_.base64url,X.message,w);break;case"jwt":G_($,E_.jwt,X.message,w);break;case"cidr":{if(X.version!=="v6")G_($,E_.ipv4Cidr,X.message,w);if(X.version!=="v4")G_($,E_.ipv6Cidr,X.message,w);break}case"emoji":G_($,E_.emoji(),X.message,w);break;case"ulid":{G_($,E_.ulid,X.message,w);break}case"base64":{switch(w.base64Strategy){case"format:binary":{S_($,"binary",X.message,w);break}case"contentEncoding:base64":{d($,"contentEncoding","base64",X.message,w);break}case"pattern:zod":{G_($,E_.base64,X.message,w);break}}break}case"nanoid":G_($,E_.nanoid,X.message,w);case"toLowerCase":case"toUpperCase":case"trim":break;default:((J)=>{})(X)}return $}function j$(_,w){return w.patternStrategy==="escape"?Hz(_):_}var Qz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Hz(_){let w="";for(let $=0;$<_.length;$++){if(!Qz.has(_[$]))w+="\\";w+=_[$]}return w}function S_(_,w,$,X){if(_.format||_.anyOf?.some((J)=>J.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 G_(_,w,$,X){if(_.pattern||_.allOf?.some((J)=>J.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:xX(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",xX(w,X),$,X)}function xX(_,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,J="",Y=!1,W=!1,q=!1;for(let G=0;G<X.length;G++){if(Y){J+=X[G],Y=!1;continue}if($.i){if(W){if(X[G].match(/[a-z]/)){if(q)J+=X[G],J+=`${X[G-2]}-${X[G]}`.toUpperCase(),q=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))J+=X[G],q=!0;else J+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){J+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){J+=`(^|(?<=[\r
|
|
2543
|
-
|
|
2544
|
-
]))
|
|
2431
|
+
`+G.join(`
|
|
2432
|
+
`);return{success:!0,output:Q,metadata:{execution_time_ms:0,operation_id:W.id,task_id:W.taskId,session_id:W.sessionId,deprecated_fields_used:X._deprecated_fields_used}}}catch(W){return{success:!1,output:"",error:W instanceof Error?W.message:String(W),metadata:{execution_time_ms:0}}}}}}function R4(_){return{name:"task_operation_get",description:"Get a single operation record by ID.",parameters:WX,execute:async(w,$)=>{let X=WX.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 n0(_){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:QX,execute:async(w,$)=>{let X=QX.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
|
+
|
|
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 lU(_){return`Invalid parameters: ${_.issues.map(($)=>`${$.path.join(".")||"<root>"}: ${$.message}`).join("; ")}`}function f4(_){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-150 chars).",parameters:GX,execute:async(w,$)=>{let X;try{X=GX.parse(w)}catch(Y){if(Y instanceof W_)return{success:!1,output:"",error:lU(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
|
+
|
|
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 L4(_){return{name:"task_operation_delete",description:"Delete an operation record.",parameters:qX,execute:async(w,$)=>{let X=qX.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 RX}from"path";function o(_){process.stderr.write(`${_}
|
|
2437
|
+
`)}var r0=()=>{},UX={};a_(UX,{runMigration:()=>cU});function cU(_){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 dU=r(()=>{Ww(),r0()}),zX={};a_(zX,{runMigration:()=>pU});function pU(_){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 iU=r(()=>{Ww(),r0()}),VX={};a_(VX,{runMigration:()=>nU});function nU(_){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 rU=r(()=>{Ww(),r0()}),OX={};a_(OX,{runMigration:()=>aU});function aU(_){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 AX){let W=$.has(Y),Q=$.has(J);if(W&&!Q)w.run(`ALTER TABLE task_operation RENAME COLUMN ${Y} TO ${J}`),o(`[Migration 004] Renamed ${Y} -> ${J}`);else if(Q)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 AX,oU=r(()=>{Ww(),r0(),AX=[{oldName:"action_type",newName:"milestone_type"},{oldName:"action_title",newName:"milestone_title"},{oldName:"action_description",newName:"milestone_description"}]}),MX={};a_(MX,{runMigration:()=>sU});function sU(_){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 tU=r(()=>{Ww(),r0()});function eU(){if(typeof Bun<"u"){let{Database:_}=w_("bun:sqlite");return _}try{let{DatabaseSync:_}=w_("node:sqlite");if(typeof _==="function")return _}catch{}return w_("better-sqlite3")}function w0(_){let w=eU();return _z(new w(_))}function _z(_){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 wz(){let _=process.env.HOME||process.env.USERPROFILE||"/tmp";return RX(_,".local","share")}function H1(){return RX(wz(),"roy-agent","tasks.db")}var fw,Lw,Ww=r(()=>{a(),V_(),fw=n("task:store"),Lw=class _{db=null;dbPath;initialized=!1;tasksCache=new Map;operationsCache=new Map;constructor(w){this.dbPath=w||H1()}async initialize(){if(this.initialized)return;if(this.dbPath!==":memory:"){let w=w_("fs"),X=w_("path").dirname(this.dbPath);if(!w.existsSync(X))w.mkdirSync(X,{recursive:!0})}if(this.db=w0(this.dbPath),this.db.run(`
|
|
2438
|
+
CREATE TABLE IF NOT EXISTS task (
|
|
2439
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2440
|
+
title TEXT NOT NULL,
|
|
2441
|
+
description TEXT DEFAULT '',
|
|
2442
|
+
status TEXT DEFAULT 'todo',
|
|
2443
|
+
priority TEXT DEFAULT 'medium',
|
|
2444
|
+
type TEXT DEFAULT 'normal',
|
|
2445
|
+
progress INTEGER DEFAULT 0,
|
|
2446
|
+
current_status TEXT DEFAULT '',
|
|
2447
|
+
goals_and_expected_deliverables TEXT DEFAULT '',
|
|
2448
|
+
parent_task_id INTEGER,
|
|
2449
|
+
created_at INTEGER NOT NULL,
|
|
2450
|
+
updated_at INTEGER NOT NULL,
|
|
2451
|
+
due_date TEXT,
|
|
2452
|
+
tags TEXT,
|
|
2453
|
+
project_path TEXT NOT NULL DEFAULT 'unknown',
|
|
2454
|
+
context TEXT NOT NULL DEFAULT '{}'
|
|
2455
|
+
)
|
|
2456
|
+
`),this.db.run(`
|
|
2457
|
+
CREATE TABLE IF NOT EXISTS task_operation (
|
|
2458
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2459
|
+
task_id INTEGER NOT NULL,
|
|
2460
|
+
session_id TEXT NOT NULL,
|
|
2461
|
+
milestone_type TEXT NOT NULL,
|
|
2462
|
+
milestone_title TEXT NOT NULL,
|
|
2463
|
+
milestone_description TEXT DEFAULT '',
|
|
2464
|
+
process_description TEXT NOT NULL DEFAULT '',
|
|
2465
|
+
timestamp INTEGER NOT NULL,
|
|
2466
|
+
md_path TEXT,
|
|
2467
|
+
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE
|
|
2468
|
+
)
|
|
2469
|
+
`),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_task_id ON task_operation(task_id)"),this.db.run("CREATE INDEX IF NOT EXISTS idx_task_operation_session_id ON task_operation(session_id)"),this.db.run(`
|
|
2470
|
+
CREATE TABLE IF NOT EXISTS task_tag (
|
|
2471
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
2472
|
+
name TEXT NOT NULL UNIQUE,
|
|
2473
|
+
created_at INTEGER NOT NULL,
|
|
2474
|
+
task_count INTEGER DEFAULT 0
|
|
2475
|
+
)
|
|
2476
|
+
`),this.db.run(`
|
|
2477
|
+
CREATE TABLE IF NOT EXISTS task_tag_relation (
|
|
2478
|
+
task_id INTEGER NOT NULL,
|
|
2479
|
+
tag_id INTEGER NOT NULL,
|
|
2480
|
+
created_at INTEGER NOT NULL,
|
|
2481
|
+
PRIMARY KEY (task_id, tag_id),
|
|
2482
|
+
FOREIGN KEY (task_id) REFERENCES task(id) ON DELETE CASCADE,
|
|
2483
|
+
FOREIGN KEY (tag_id) REFERENCES task_tag(id) ON DELETE CASCADE
|
|
2484
|
+
)
|
|
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}=(dU(),mw(UX));w(this.dbPath)}catch(w){fw.warn(`[Migration 001] Failed to run: ${w.message}`)}try{let{runMigration:w}=(iU(),mw(zX));w(this.dbPath)}catch(w){fw.warn(`[Migration 002] Failed to run: ${w.message}`)}try{let{runMigration:w}=(rU(),mw(VX));w(this.dbPath)}catch(w){fw.warn(`[Migration 003] Failed to run: ${w.message}`)}try{let{runMigration:w}=(oU(),mw(OX));w(this.dbPath)}catch(w){fw.warn(`[Migration 004] Failed to run: ${w.message}`)}try{let{runMigration:w}=(tU(),mw(MX));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
|
+
INSERT INTO task (title, description, priority, type, parent_task_id,
|
|
2487
|
+
goals_and_expected_deliverables, due_date, tags, status,
|
|
2488
|
+
current_status, created_at, updated_at, project_path, context)
|
|
2489
|
+
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}`,Q=this.db.prepare(J).get(...X)?.total??0,G=`SELECT * FROM task WHERE ${Y}`,q=[...X];if(G+=" ORDER BY updated_at DESC",w?.limit)G+=" LIMIT ?",q.push(w.limit);if(w?.offset)G+=" OFFSET ?",q.push(w.offset);return{tasks:this.db.prepare(G).all(...q).map((O)=>{let z=this.rowToTask(O);return this.tasksCache.set(z.id,z),z}),total:Q}}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 "),W=[];if($===0){let B=`SELECT * FROM task WHERE parent_task_id IS NULL AND ${J} ORDER BY updated_at DESC`,D=this.db.prepare(B).all(...Y);for(let O of D){let z=this.rowToTask(O);this.tasksCache.set(z.id,z),W.push(z)}}else{let D=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});W.push(...D);for(let O=1;O<=$;O++){if(D.length===0)break;let z=D.map((N)=>N.id),V=`SELECT * FROM task WHERE parent_task_id IN (${z.map(()=>"?").join(",")}) AND ${J} ORDER BY updated_at DESC`,f=this.db.prepare(V).all(...z,...Y).map((N)=>{let R=this.rowToTask(N);return this.tasksCache.set(R.id,R),R});W.push(...f),D=f}}let Q=W.length,G=w.offset??0,q=w.limit??Q;return{tasks:W.slice(G,G+q),total:Q}}async getTaskTree(w,$=-1){await this.initialize();let X=[],Y=[w],J=0;while(Y.length>0){if($!==-1&&J>=$)break;let W=Y.map(()=>"?").join(","),Q=this.db.prepare(`SELECT * FROM task WHERE parent_task_id IN (${W}) ORDER BY updated_at DESC`).all(...Y),G=[];for(let q of Q){let H=this.rowToTask(q);this.tasksCache.set(H.id,H),X.push(H),G.push(H.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(),Q=this.db.prepare(`
|
|
2491
|
+
INSERT INTO task_operation (task_id, session_id, milestone_type, milestone_title,
|
|
2492
|
+
milestone_description, process_description, timestamp, md_path)
|
|
2493
|
+
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(Q.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,W=[],Q=[];if(Y!==void 0)W.push("milestone_title = ?"),Q.push(Y);if(J!==void 0)W.push("milestone_description = ?"),Q.push(J);if($.processDescription!==void 0)W.push("process_description = ?"),Q.push($.processDescription);if(W.length===0)return X;return this.db.prepare(`UPDATE task_operation SET ${W.join(", ")} WHERE id = ?`).run(...Q,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((q)=>this.rowToOperation(q)))}let X=this.operationsCache.get($),Y=w.milestoneType??w.actionType;if(Y)X=X.filter((Q)=>Q.milestoneType===Y);let J=w.offset||0,W=w.limit||20;return X.slice(J,J+W)}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
|
+
INSERT INTO task_tag (name, created_at, task_count)
|
|
2496
|
+
VALUES (?, ?, 0)
|
|
2497
|
+
`).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((Q)=>this.rowToTag(Q))}async searchTags(w){await this.initialize();let $=`
|
|
2498
|
+
SELECT * FROM task_tag
|
|
2499
|
+
WHERE name LIKE ?
|
|
2500
|
+
ORDER BY task_count DESC
|
|
2501
|
+
LIMIT ?
|
|
2502
|
+
`;return this.db.prepare($).all(`%${w.query}%`,w.limit||20).map((J)=>this.rowToTag(J))}async deleteTag(w){return await this.initialize(),this.db.prepare("DELETE FROM task_tag WHERE id = ?").run(w).changes>0}async addTagsToTask(w,$){await this.initialize();let X=Date.now(),Y=this.db.prepare(`
|
|
2503
|
+
INSERT OR IGNORE INTO task_tag_relation (task_id, tag_id, created_at)
|
|
2504
|
+
VALUES (?, ?, ?)
|
|
2505
|
+
`);for(let J of $)Y.run(w,J,X),this.db.run(`
|
|
2506
|
+
UPDATE task_tag SET task_count = task_count + 1 WHERE id = ?
|
|
2507
|
+
`,J);await this.syncTaskTagsJson(w)}async removeTagsFromTask(w,$){await this.initialize();let X=this.db.prepare("DELETE FROM task_tag_relation WHERE task_id = ? AND tag_id = ?");for(let Y of $)X.run(w,Y),this.db.run(`
|
|
2508
|
+
UPDATE task_tag SET task_count = MAX(0, task_count - 1) WHERE id = ?
|
|
2509
|
+
`,Y);await this.syncTaskTagsJson(w)}async getTagsForTask(w){await this.initialize();let $=`
|
|
2510
|
+
SELECT t.* FROM task_tag t
|
|
2511
|
+
INNER JOIN task_tag_relation r ON t.id = r.tag_id
|
|
2512
|
+
WHERE r.task_id = ?
|
|
2513
|
+
ORDER BY t.name ASC
|
|
2514
|
+
`;return this.db.prepare($).all(w).map((J)=>this.rowToTag(J))}async getTaskIdsByTags(w){if(await this.initialize(),w.length===0)return[];let X=`
|
|
2515
|
+
SELECT DISTINCT r.task_id FROM task_tag_relation r
|
|
2516
|
+
INNER JOIN task_tag t ON r.tag_id = t.id
|
|
2517
|
+
WHERE t.name IN (${w.map(()=>"?").join(", ")})
|
|
2518
|
+
`;return this.db.prepare(X).all(...w).map((W)=>W.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 W=await this.getTagByName(J);if(!W)W=await this.createTag(J);Y.push(W.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:W,priority:Q,type:G,depth:q}=$,H=null;if(q!==void 0&&q>=0)H=await this.collectTaskIdsByDepth(q);let B=new Map,D="SELECT * FROM task WHERE 1=1",O=[];if(J)D+=" AND id != ?",O.push(J);if(W)D+=" AND status = ?",O.push(W);if(Q)D+=" AND priority = ?",O.push(Q);if(G)D+=" AND type = ?",O.push(G);if(!$?.include_archived&&$?.status!=="archived")D+=" AND status != 'archived'";let z=Math.max(X*5,200);D+=" ORDER BY updated_at DESC LIMIT ?",O.push(z);let U=this.db.prepare(D).all(...O);for(let b of U){let F=this.rowToTask(b),T=new Set,j=0;if(typeof F.title==="string"&&F.title){let C=F.title.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(F.tags&&Array.isArray(F.tags))for(let C of w){let y=C.toLowerCase();if(F.tags.some((i)=>i.toLowerCase().includes(y)))j+=2,T.add(C)}if(typeof F.description==="string"&&F.description){let C=F.description.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(typeof F.goals_and_expected_deliverables==="string"&&F.goals_and_expected_deliverables){let C=F.goals_and_expected_deliverables.toLowerCase();for(let y of w)if(C.includes(y.toLowerCase()))j++,T.add(y)}if(T.size===w.length)B.set(F.id,{task:F,matchCount:j})}let V=this.db.prepare("SELECT DISTINCT task_id FROM task_operation WHERE 1=1").all();for(let b of V){let T=new Set;for(let i of w){let v=`%${i}%`;if(this.db.prepare(`
|
|
2519
|
+
SELECT * FROM task_operation
|
|
2520
|
+
WHERE task_id = ?
|
|
2521
|
+
AND (milestone_title LIKE ? OR milestone_description LIKE ? OR process_description LIKE ?)
|
|
2522
|
+
LIMIT 10
|
|
2523
|
+
`).all(b.task_id,v,v,v).length>0)T.add(i)}if(T.size===0)continue;let j=this.db.prepare("SELECT * FROM task WHERE id = ?").get(b.task_id);if(!j)continue;let C=this.rowToTask(j);if(J&&C.id===J)continue;if(W&&C.status!==W)continue;if(Q&&C.priority!==Q)continue;if(G&&C.type!==G)continue;if(!$?.include_archived&&C.status==="archived")continue;let y=B.get(C.id);if(y)y.matchCount+=2;else{let i=new Set(T);if(typeof C.title==="string"&&C.title){let v=C.title.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.description==="string"&&C.description){let v=C.description.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(typeof C.goals_and_expected_deliverables==="string"&&C.goals_and_expected_deliverables){let v=C.goals_and_expected_deliverables.toLowerCase();for(let c of w)if(v.includes(c.toLowerCase()))i.add(c)}if(C.tags&&Array.isArray(C.tags)){for(let v of w)if(C.tags.some((c)=>c.toLowerCase().includes(v.toLowerCase())))i.add(v)}if(i.size===w.length)B.set(C.id,{task:C,matchCount:2})}}let M=Array.from(B.values()).sort((b,F)=>F.matchCount-b.matchCount);if(H!==null)M=M.filter((b)=>H.has(b.task.id));let f=M.length;return{tasks:M.slice(Y,Y+X).map((b)=>b.task),total:f}}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 W=Y.map(()=>"?").join(",");Y=this.db.prepare(`SELECT id FROM task WHERE parent_task_id IN (${W})`).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((q)=>q.id),W=`
|
|
2524
|
+
SELECT t.*, COUNT(r2.tag_id) as match_count
|
|
2525
|
+
FROM task t
|
|
2526
|
+
INNER JOIN task_tag_relation r ON t.id = r.task_id
|
|
2527
|
+
INNER JOIN task_tag_relation r2 ON t.id = r2.task_id
|
|
2528
|
+
WHERE r.tag_id IN (${Y.map(()=>"?").join(", ")})
|
|
2529
|
+
AND t.id != ?
|
|
2530
|
+
GROUP BY t.id
|
|
2531
|
+
ORDER BY match_count DESC, t.updated_at DESC
|
|
2532
|
+
LIMIT ?
|
|
2533
|
+
`;return this.db.prepare(W).all(...Y,w,$).map((q)=>this.rowToTask(q))}async searchTasks(w,$=20){await this.initialize();let X=`
|
|
2534
|
+
SELECT * FROM task
|
|
2535
|
+
WHERE title LIKE ? OR description LIKE ?
|
|
2536
|
+
ORDER BY updated_at DESC
|
|
2537
|
+
LIMIT ?
|
|
2538
|
+
`;return this.db.prepare(X).all(`%${w}%`,`%${w}%`,$).map((W)=>this.rowToTask(W))}async findTasksByContextValue(w,$=50){if(await this.initialize(),!w)return[];let X=`
|
|
2539
|
+
SELECT * FROM task
|
|
2540
|
+
WHERE context LIKE ?
|
|
2541
|
+
ORDER BY updated_at DESC
|
|
2542
|
+
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})],Lw.prototype,"rowToTask",null),m([u("task.searchTasksByKeywords",{recordParams:!0,recordResult:!0,log:!0})],Lw.prototype,"searchTasksByKeywords",null)});function fX(_,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 W=J.indexOf("_"),Q;if(W===-1)Q=J;else{let q=J.slice(0,W),H=J.slice(W+1);if(q===Y)Q=H;else Q=J}if(!Q)return;let G=Q.replace(/_/g,".");return`${$}.${G.toLowerCase()}`}function LX(_,w){return{..._,execute:w}}var $z=()=>{},FX=r(()=>{$z(),Q4(),_0()});FX();class F4{_status="created";_enabled=!0;env;hookManager;constructor(){this.hookManager=new Y1}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(_,LX({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 Xz={"task.storage.type":"sqlite","task.storage.dbPath":void 0},Yz={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 Jz=["completed","failed","cancelled","timeout"];Jw();a();var a0=n("task:tag");class KX{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($),W=$.filter((G)=>!Y.has(G)),Q=X.filter((G)=>!J.has(G.id)).map((G)=>G.id);if(Q.length>0)await this.store.removeTagsFromTask(_,Q);if(W.length>0)await this.store.addTagsToTask(_,W);await this.store.updateTaskTags(_,w),a0.info(`[TagService] Synced tags for task ${_}: ${w.join(", ")}`)}}V_();var J_=n("task"),Wz="Deliverable: ";function Qz(_){if(!_)return;return`${Wz}${_}`}class Fw extends F4{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(Yz),$)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 W of Object.keys(process.env)){let Q=fX(W,J,"task");if(!Q)continue;let G=process.env[W];if(G!==void 0)await w.set(Q,G)}for(let[W,Q]of Object.entries(Xz))if(w.get(W)===void 0)await w.set(W,Q);if(w.get("task.storage.dbPath")===void 0)await w.set("task.storage.dbPath",H1());if(Y){let W=this.flattenConfig(Y);for(let[Q,G]of Object.entries(W))await w.set(Q,G)}this.registerConfigWatcher(w),await this.initStore(),this.tagService=new KX(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 Lw($),J_.info(`[TaskComponent] Using SQLite storage: ${$||"default path"}`);else this.store=new Lw,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 __(this.env),this.toolComponent=this.env?.getComponent("tool"),this.toolComponent)await this.registerTools(),this.toolComponent.register(G2(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(G2(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),z4(this),V4(this),c0(this),O4(this),d0(this)],w=[i0(this),R4(this),n0(this),f4(this),L4(this)],$=[l5(this),c5(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(Rw.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:$}}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(Rw.UPDATED,{task:X,changes:w,sessionId:""},""),J_.info(`[TaskComponent] Task updated: ${_}`),w.status&&Jz.includes(w.status)){let J=$1(),W={task:X,changes:w,terminalStatus:w.status,sessionId:J.sessionId??"",tagService:this.tagService};await this.executeHook($_.AFTER_COMPLETE,W),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(Rw.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 W={};if(X?.context)try{let Q=JSON.parse(X.context);if(Q&&typeof Q==="object"&&!Array.isArray(Q))W=Q}catch{J_.warn(`[TaskComponent] Task #${_} context is not valid JSON, ignoring when merging deliverable`)}W.deliverable_storage_path=$,Y.context=JSON.stringify(W)}let J=await this.updateTask(_,Y);if(J)await this.createOperation({taskId:_,sessionId:w,milestoneType:"completed",milestoneTitle:"Task completed",milestoneDescription:Qz($)}),this.publishEvent(Rw.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(Rw.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})],Fw.prototype,"executeHook",null);m([u("task.component.createTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"createTask",null);m([u("task.component.updateTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"updateTask",null);m([u("task.component.completeTask",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"completeTask",null);m([u("task.component.createOperation",{recordParams:!0,recordResult:!0,log:!0})],Fw.prototype,"createOperation",null);var K4=A.enum(["todo","active","completed","paused","cancelled","archived"]),N4=A.enum(["low","medium","high"]),b4=A.enum(["normal","cycle","longterm"]),j4=A.enum(["create","progress","milestone","problem","solution","decision","review","completed","workflow_extracted"]),Gz=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 D1=1e6;class E4{port;options;constructor(_,w={}){this.port=_,this.options=w}get defaultSessionId(){return this.options.sessionId??"unknown"}async resolve(_){let w=Dz(_);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:D1,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:D1,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=Uz(X.context,$);let J=await this.port.updateTask(X.nativeId,Y);if(!J)return null;let W=Hz($);await this.createOperation({taskId:J.id,sessionId:w??this.defaultSessionId,milestoneType:"completed",milestoneTitle:`Completed: ${J.title}`,milestoneDescription:W??"Task completed",...$?{mdPath:$}:{}});let Q=await this.resolve(X.nativeId);return this.toTask(Q??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 H=Y.get(q.parent_task_id)??[];H.push(q),Y.set(q.parent_task_id,H)}let J=[],W=new Set([$.id]),Q=[$.id],G=0;while(Q.length>0){if(w!==-1&&G>=w)break;let q=[];for(let H of Q)for(let B of Y.get(H)??[]){if(W.has(B.id))continue;W.add(B.id),J.push(B),q.push(B.id)}Q=q,G++}return J}async searchTasksByKeywords(_,w={}){let $=w.limit??20,X=w.offset??0,Y=(await this.scanAllTasks()).map((Q)=>this.toTask(Q));if(Y=this.applyFilters(Y,w),w.excludeTaskId!==void 0)Y=Y.filter((Q)=>Q.id!==w.excludeTaskId);let J=_.map((Q)=>Q.toLowerCase()).filter((Q)=>Q.length>0),W=J.length===0?Y:Y.filter((Q)=>{let G=[Q.title,Q.description,Q.goals_and_expected_deliverables,Q.current_status,(Q.tags??[]).join(" "),Q.project_path].join(" ").toLowerCase();return J.every((q)=>G.includes(q))});return{tasks:W.slice(X,X+$),total:W.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 W=(await this.port.listOperations({taskNativeId:Y.nativeId,limit:X?D1:w,offset:X?0:$})).operations.map((Q)=>this.toOperation(Q));if(X)W=W.filter((Q)=>Q.milestoneType===X),W=W.slice($,$+w);return W}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:D1})).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=Bz($,w.depth);$=$.filter((J)=>Y.has(J.id))}return $}}function Dz(_){if(typeof _==="number")return Number.isFinite(_)?_:void 0;return/^\d+$/.test(_)?Number(_):void 0}function Bz(_,w){if(w<0)return new Set(_.map((W)=>W.id));let $=new Set(_.map((W)=>W.id)),X=new Map;for(let W of _){let Q=W.parent_task_id;if(Q===void 0||!$.has(Q))continue;let G=X.get(Q)??[];G.push(W),X.set(Q,G)}let Y=new Set,J=_.filter((W)=>W.parent_task_id===void 0||!$.has(W.parent_task_id));for(let W of J)Y.add(W.id);for(let W=1;W<=w;W++){let Q=[];for(let G of J)for(let q of X.get(G.id)??[]){if(Y.has(q.id))continue;Y.add(q.id),Q.push(q)}if(Q.length===0)break;J=Q}return Y}function Uz(_,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 zz=1e6;function Vz(_){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,W=typeof J==="number"?J:typeof J==="string"&&/^\d+$/.test(J)?Number(J):0;return{id:typeof _.num==="number"?_.num:0,nativeId:_.id,taskId:W,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 NX(_,w,$={}){let X=$.operationType??"roy.milestone",Y=$.agent??"roy",J=$.scanLimit??zz;async function W(){let q=await _.listTasks({limit:J});return new Map(q.tasks.filter((H)=>typeof H.num==="number").map((H)=>[H.id,H.num]))}async function Q(q){if(typeof _.getTaskByNum==="function")return await _.getTaskByNum(q);return(await _.listTasks({limit:J})).tasks.find((B)=>B.num===q)??null}async function G(q){let B=[...(await W()).entries()].find(([,D])=>D===q);if(!B)throw Error(`parent task not found: ${q}`);return B[0]}return{async createTask(q){let H=q.parent_task_id!==void 0?await G(q.parent_task_id):null,B={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}:{}},D=await _.createTask({title:q.title,description:q.description,priority:w.toStorePriority(q.priority),owner:Y,tags:w.toStoreTags(q.tags),parent_id:H,session_id:q.sessionId??"unknown",roy:B});return o0(D,w,q.parent_task_id)},async getTask(q){let H=await _.getTask(q);if(!H)return null;let B=await W();return o0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async getTaskByNum(q){let H=await Q(q);if(!H)return null;let B=await W();return o0(H,w,H.parent_id?B.get(H.parent_id):void 0)},async listTasks(q){let H=await _.listTasks({limit:q?.limit??20,offset:q?.offset??0}),B=await W();return{tasks:H.tasks.map((D)=>o0(D,w,D.parent_id?B.get(D.parent_id):void 0)),total:H.total}},async updateTask(q,H){let B=Vz(H),D=await _.updateTask(q,{...H.title!==void 0?{title:H.title}:{},...H.description!==void 0?{description:H.description}:{},...H.status!==void 0?{status:w.toStoreStatus(H.status)}:{},...H.priority!==void 0?{priority:w.toStorePriority(H.priority)}:{},...H.tags!==void 0?{tags:w.toStoreTags(H.tags)}:{},...Object.keys(B).length>0?{roy:B}:{}});if(!D)return null;let O;if(H.parent_task_id!==void 0){let U=H.parent_task_id===null?null:await G(H.parent_task_id);if(typeof _.setParentId==="function")await _.setParentId(q,U);O=H.parent_task_id===null?void 0:H.parent_task_id}let z=await _.getTask(q)??D;if(O===void 0&&z.parent_id)O=(await W()).get(z.parent_id);return o0(z,w,O)},async deleteTask(q){return await _.deleteTask(q)},async createOperation(q){let H=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(H)},async listOperations(q){let H=await _.listOperations({...q?.taskNativeId?{task_id:q.taskNativeId}:{},type:X,limit:q?.limit??J,offset:q?.offset??0});return{operations:H.operations.map(s0),total:H.total}},async getOperationByNum(q){if(typeof _.getOperationByNum!=="function")return null;let H=await _.getOperationByNum(q);return H?s0(H):null},async updateOperationByNum(q,H){if(typeof _.updateOperation!=="function")return null;if(typeof _.getOperationByNum!=="function")return null;let B=await _.getOperationByNum(q);if(!B)return null;let D=s0(B),O=await _.updateOperation(q,{data:{taskId:D.taskId,sessionId:H.sessionId??D.sessionId,milestoneType:H.milestoneType??D.milestoneType,milestoneTitle:H.milestoneTitle??D.milestoneTitle,milestoneDescription:H.milestoneDescription??D.milestoneDescription,processDescription:H.processDescription??D.processDescription,...H.mdPath??D.mdPath?{mdPath:H.mdPath??D.mdPath}:{}}});return O?s0(O):null},async deleteOperationByNum(q){if(typeof _.deleteOperation!=="function")return!1;return await _.deleteOperation(q)}}}var Oz="roy.milestone",Az={todo:"pending",active:"in_progress",completed:"done",cancelled:"cancelled",paused:"blocked",archived:"archived"},Mz={pending:"todo",in_progress:"active",done:"completed",cancelled:"cancelled",blocked:"paused",review:"active",archived:"archived"};function bX(_){return Az[_]??"pending"}function jX(_){return Mz[_]??"todo"}function EX(_){if(_==="high")return 1;if(_==="low")return 5;return 3}function SX(_){if(_===void 0)return"medium";if(_<=2)return"high";return _===3?"medium":"low"}function PX(_){if(!_||_.length===0)return;return _.join(",")}function ZX(_){if(!_)return[];return _.split(",").map((w)=>w.trim()).filter((w)=>w.length>0)}var Rz={toRoyStatus:(_)=>jX(_),toStoreStatus:(_)=>bX(_),toRoyPriority:(_)=>SX(_),toStorePriority:(_)=>EX(_),toRoyTags:(_)=>ZX(_),toStoreTags:(_)=>PX(_)};function CX(_,w={}){return new E4(NX(_,Rz,{operationType:Oz,agent:w.agent??"roy"}),{sessionId:w.sessionId})}var MR=K4.options,RR=N4.options,fR=b4.options,LR=j4.options;var IX=Symbol("Let zodToJsonSchema decide on which parser to use");var TX={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"},kX=(_)=>typeof _==="string"?{...TX,name:_}:{...TX,..._};var gX=(_)=>{let w=kX(_),$=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 S4(_,w,$,X){if(!X?.errorMessages)return;if($)_.errorMessage={..._.errorMessage,[w]:$}}function d(_,w,$,X,Y){_[w]=$,S4(_,w,X,Y)}var B1=(_,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"?B1(w,_.currentPath):w.join("/")}}function hX(_,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 yX(_,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 vX(){return{type:"boolean"}}function U1(_,w){return k(_.type._def,w)}var xX=(_,w)=>{return k(_.innerType._def,w)};function P4(_,w,$){let X=$??w.dateStrategy;if(Array.isArray(X))return{anyOf:X.map((Y,J)=>P4(_,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 fz(_,w)}}var fz=(_,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 mX(_,w){return{...k(_.innerType._def,w),default:_.defaultValue()}}function uX(_,w){return w.effectStrategy==="input"?k(_.schema._def,w):s(w)}function lX(_){return{type:"string",enum:Array.from(_.values)}}var Lz=(_)=>{if("type"in _&&_.type==="string")return!1;return"allOf"in _};function cX(_,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(Lz(J)){if(Y.push(...J.allOf),J.unevaluatedProperties===void 0)X=void 0}else{let W=J;if("additionalProperties"in J&&J.additionalProperties===!1){let{additionalProperties:Q,...G}=J;W=G}else X=void 0;Y.push(W)}}),Y.length?{allOf:Y,...X}:void 0}function dX(_,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 Z4=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(Z4===void 0)Z4=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return Z4},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 z1(_,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(`^${C4(X.value,w)}`),X.message,w);break;case"endsWith":q_($,RegExp(`${C4(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(C4(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 C4(_,w){return w.patternStrategy==="escape"?Kz(_):_}var Fz=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function Kz(_){let w="";for(let $=0;$<_.length;$++){if(!Fz.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:pX(w,X),...$&&X.errorMessages&&{errorMessage:{pattern:$}}})}else d(_,"pattern",pX(w,X),$,X)}function pX(_,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,W=!1,Q=!1;for(let G=0;G<X.length;G++){if(J){Y+=X[G],J=!1;continue}if($.i){if(W){if(X[G].match(/[a-z]/)){if(Q)Y+=X[G],Y+=`${X[G-2]}-${X[G]}`.toUpperCase(),Q=!1;else if(X[G+1]==="-"&&X[G+2]?.match(/[a-z]/))Y+=X[G],Q=!0;else Y+=`${X[G]}${X[G].toUpperCase()}`;continue}}else if(X[G].match(/[a-z]/)){Y+=`[${X[G]}${X[G].toUpperCase()}]`;continue}}if($.m){if(X[G]==="^"){Y+=`(^|(?<=[\r
|
|
2544
|
+
]))`;continue}else if(X[G]==="$"){Y+=`($|(?=[\r
|
|
2545
|
+
]))`;continue}}if($.s&&X[G]==="."){Y+=W?`${X[G]}\r
|
|
2545
2546
|
`:`[${X[G]}\r
|
|
2546
|
-
]`;continue}if(J+=X[G],X[G]==="\\")Y=!0;else if(W&&X[G]==="]")W=!1;else if(!W&&X[G]==="[")W=!0}try{new RegExp(J)}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 J}function D2(_,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,J)=>({...X,[J]:I(_.valueType._def,{...w,currentPath:[...w.currentPath,"properties",J]})??o(w)}),{}),additionalProperties:w.rejectedAdditionalProperties};let $={type:"object",additionalProperties:I(_.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,...J}=H2(_.keyType._def,w);return{...$,propertyNames:J}}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,...J}=Q2(_.keyType._def,w);return{...$,propertyNames:J}}return $}function mX(_,w){if(w.mapStrategy==="record")return D2(_,w);let $=I(_.keyType._def,{...w,currentPath:[...w.currentPath,"items","items","0"]})||o(w),X=I(_.valueType._def,{...w,currentPath:[...w.currentPath,"items","items","1"]})||o(w);return{type:"array",maxItems:125,items:{type:"array",items:[$,X],minItems:2,maxItems:2}}}function uX(_){let w=_.values,X=Object.keys(_.values).filter((Y)=>{return typeof w[w[Y]]!=="number"}).map((Y)=>w[Y]),J=Array.from(new Set(X.map((Y)=>typeof Y)));return{type:J.length===1?J[0]==="string"?"string":"number":["string","number"],enum:X}}function lX(_){return _.target==="openAi"?void 0:{not:o({..._,currentPath:[..._.currentPath,"not"]})}}function cX(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var o0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function pX(_,w){if(w.target==="openApi3")return dX(_,w);let $=_.options instanceof Map?Array.from(_.options.values()):_.options;if($.every((X)=>(X._def.typeName in o0)&&(!X._def.checks||!X._def.checks.length))){let X=$.reduce((J,Y)=>{let W=o0[Y._def.typeName];return W&&!J.includes(W)?[...J,W]:J},[]);return{type:X.length>1?X:X[0]}}else if($.every((X)=>X._def.typeName==="ZodLiteral"&&!X.description)){let X=$.reduce((J,Y)=>{let W=typeof Y._def.value;switch(W){case"string":case"number":case"boolean":return[...J,W];case"bigint":return[...J,"integer"];case"object":if(Y._def.value===null)return[...J,"null"];case"symbol":case"undefined":case"function":default:return J}},[]);if(X.length===$.length){let J=X.filter((Y,W,q)=>q.indexOf(Y)===W);return{type:J.length>1?J:J[0],enum:$.reduce((Y,W)=>{return Y.includes(W._def.value)?Y:[...Y,W._def.value]},[])}}}else if($.every((X)=>X._def.typeName==="ZodEnum"))return{type:"string",enum:$.reduce((X,J)=>[...X,...J._def.values.filter((Y)=>!X.includes(Y))],[])};return dX(_,w)}var dX=(_,w)=>{let $=(_.options instanceof Map?Array.from(_.options.values()):_.options).map((X,J)=>I(X._def,{...w,currentPath:[...w.currentPath,"anyOf",`${J}`]})).filter((X)=>!!X&&(!w.strictUnions||typeof X==="object"&&Object.keys(X).length>0));return $.length?{anyOf:$}:void 0};function iX(_,w){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(_.innerType._def.typeName)&&(!_.innerType._def.checks||!_.innerType._def.checks.length)){if(w.target==="openApi3")return{type:o0[_.innerType._def.typeName],nullable:!0};return{type:[o0[_.innerType._def.typeName],"null"]}}if(w.target==="openApi3"){let X=I(_.innerType._def,{...w,currentPath:[...w.currentPath]});if(X&&"$ref"in X)return{allOf:[X],nullable:!0};return X&&{...X,nullable:!0}}let $=I(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","0"]});return $&&{anyOf:[$,{type:"null"}]}}function rX(_,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 nX(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},J=[],Y=_.shape();for(let q in Y){let G=Y[q];if(G===void 0||G._def===void 0)continue;let Q=Bz(G);if(Q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();Q=!1}let H=I(G._def,{...w,currentPath:[...w.currentPath,"properties",q],propertyPath:[...w.currentPath,"properties",q]});if(H===void 0)continue;if(X.properties[q]=H,!Q)J.push(q)}if(J.length)X.required=J;let W=Dz(_,w);if(W!==void 0)X.additionalProperties=W;return X}function Dz(_,w){if(_.catchall._def.typeName!=="ZodNever")return I(_.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 Bz(_){try{return _.isOptional()}catch{return!0}}var aX=(_,w)=>{if(w.currentPath.toString()===w.propertyPath?.toString())return I(_.innerType._def,w);let $=I(_.innerType._def,{...w,currentPath:[...w.currentPath,"anyOf","1"]});return $?{anyOf:[{not:o(w)},$]}:o(w)};var oX=(_,w)=>{if(w.pipeStrategy==="input")return I(_.in._def,w);else if(w.pipeStrategy==="output")return I(_.out._def,w);let $=I(_.in._def,{...w,currentPath:[...w.currentPath,"allOf","0"]}),X=I(_.out._def,{...w,currentPath:[...w.currentPath,"allOf",$?"1":"0"]});return{allOf:[$,X].filter((J)=>J!==void 0)}};function sX(_,w){return I(_.type._def,w)}function tX(_,w){let X={type:"array",uniqueItems:!0,items:I(_.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 eX(_,w){if(_.rest)return{type:"array",minItems:_.items.length,items:_.items.map(($,X)=>I($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[]),additionalItems:I(_.rest._def,{...w,currentPath:[...w.currentPath,"additionalItems"]})};else return{type:"array",minItems:_.items.length,maxItems:_.items.length,items:_.items.map(($,X)=>I($._def,{...w,currentPath:[...w.currentPath,"items",`${X}`]})).reduce(($,X)=>X===void 0?$:[...$,X],[])}}function _9(_){return{not:o(_)}}function w9(_){return o(_)}var $9=(_,w)=>{return I(_.innerType._def,w)};var X9=(_,w,$)=>{switch(w){case F.ZodString:return H2(_,$);case F.ZodNumber:return rX(_,$);case F.ZodObject:return nX(_,$);case F.ZodBigInt:return CX(_,$);case F.ZodBoolean:return TX();case F.ZodDate:return N$(_,$);case F.ZodUndefined:return _9($);case F.ZodNull:return cX($);case F.ZodArray:return ZX(_,$);case F.ZodUnion:case F.ZodDiscriminatedUnion:return pX(_,$);case F.ZodIntersection:return yX(_,$);case F.ZodTuple:return eX(_,$);case F.ZodRecord:return D2(_,$);case F.ZodLiteral:return vX(_,$);case F.ZodEnum:return hX(_);case F.ZodNativeEnum:return uX(_);case F.ZodNullable:return iX(_,$);case F.ZodOptional:return aX(_,$);case F.ZodMap:return mX(_,$);case F.ZodSet:return tX(_,$);case F.ZodLazy:return()=>_.getter()._def;case F.ZodPromise:return sX(_,$);case F.ZodNaN:case F.ZodNever:return lX($);case F.ZodEffects:return kX(_,$);case F.ZodAny:return o($);case F.ZodUnknown:return w9($);case F.ZodDefault:return gX(_,$);case F.ZodBranded:return Q2(_,$);case F.ZodReadonly:return $9(_,$);case F.ZodCatch:return IX(_,$);case F.ZodPipeline:return oX(_,$);case F.ZodFunction:case F.ZodVoid:case F.ZodSymbol:return;default:return((X)=>{return})(w)}};function I(_,w,$=!1){let X=w.seen.get(_);if(w.override){let q=w.override?.(_,w,X,$);if(q!==EX)return q}if(X&&!$){let q=Uz(X,w);if(q!==void 0)return q}let J={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,J);let Y=X9(_,_.typeName,w),W=typeof Y==="function"?I(Y(),w):Y;if(W)zz(_,w,W);if(w.postProcess){let q=w.postProcess(W,_,w);return J.jsonSchema=W,q}return J.jsonSchema=W,W}var Uz=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:G2(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`),o(w);return w.$refStrategy==="seen"?o(w):void 0}}},zz=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var E$=(_,w)=>{let $=PX(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[Q,H])=>({...G,[Q]:I(H._def,{...$,currentPath:[...$.basePath,$.definitionPath,Q]},!0)??o($)}),{}):void 0,J=typeof w==="string"?w:w?.nameStrategy==="title"?void 0:w?.name,Y=I(_._def,J===void 0?$:{...$,currentPath:[...$.basePath,$.definitionPath,J]},!1)??o($),W=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(W!==void 0)Y.title=W;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 q=J===void 0?X?{...Y,[$.definitionPath]:X}:Y:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,J].join("/"),[$.definitionPath]:{...X,[J]:Y}};if($.target==="jsonSchema7")q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")q.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in q)||("oneOf"in q)||("allOf"in q)||("type"in q)&&Array.isArray(q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return q};var Vz=[V0,f0,A0,M0,R0,O0,F0,L0,K0];function Az(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=E$($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:J,...Y}=X;return Y}catch{return{}}}function J9(_,w={}){let $=bX(_,w);return Vz.map((X)=>{let J=X($);return{name:J.name,description:J.description,input:Az(J.parameters),options:{codemode:!1},execute:async(Y,W)=>{let q={session_id:W?.sessionID??w.sessionId??"unknown",workdir:W?.directory};try{let G=await J.execute(Y??{},q),Q=typeof G.output==="string"?G.output:JSON.stringify(G.output??"");return{content:G.success?Q:`ERROR: ${G.error??"unknown error"}`,metadata:{tool:J.name,ok:G.success}}}catch(G){return{content:`ERROR: ${G instanceof Error?G.message:String(G)}`,metadata:{tool:J.name,ok:!1}}}}}})}function Y9(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function W9(_,w){let $=w.enabled!==!1,X={enabled:$,agentId:null,toolNames:[],errors:[],disposers:[]};if(!$)return X;let J=_??{},Y=w.agent??$0;if(typeof J.agent?.transform==="function")try{let q=await J.agent.transform((G)=>{M2(G)});Y9(q,X.disposers),X.agentId=Y}catch(q){X.errors.push(`roy agent registration failed: ${S$(q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let W=[];try{W=J9(w.store,{agent:Y,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(q){return X.errors.push(`roy tool construction failed: ${S$(q)}`),X}if(typeof J.tool?.transform==="function")try{let q=await J.tool.transform((G)=>{for(let Q of W)G.add(Q)});Y9(q,X.disposers),X.toolNames=W.map((G)=>G.name)}catch(q){X.errors.push(`roy tool registration failed: ${S$(q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function S$(_){return _ instanceof Error?_.message:String(_)}import{join as C$}from"path";import{homedir as Nz}from"os";import{mkdirSync as bz}from"fs";import{Database as Mz}from"bun:sqlite";import{createHash as Rz,randomUUID as Oz}from"crypto";var Fz=`
|
|
2547
|
+
]`;continue}if(Y+=X[G],X[G]==="\\")J=!0;else if(W&&X[G]==="]")W=!1;else if(!W&&X[G]==="[")W=!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 V1(_,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}=z1(_.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}=U1(_.keyType._def,w);return{...$,propertyNames:Y}}return $}function iX(_,w){if(w.mapStrategy==="record")return V1(_,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 nX(_){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 rX(_){return _.target==="openAi"?void 0:{not:s({..._,currentPath:[..._.currentPath,"not"]})}}function aX(_){return _.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var t0={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function sX(_,w){if(w.target==="openApi3")return oX(_,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 W=t0[J._def.typeName];return W&&!Y.includes(W)?[...Y,W]: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 W=typeof J._def.value;switch(W){case"string":case"number":case"boolean":return[...Y,W];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,W,Q)=>Q.indexOf(J)===W);return{type:Y.length>1?Y:Y[0],enum:$.reduce((J,W)=>{return J.includes(W._def.value)?J:[...J,W._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 oX(_,w)}var oX=(_,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 tX(_,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 eX(_,w){let $={type:"number"};if(!_.checks)return $;for(let X of _.checks)switch(X.kind){case"int":$.type="integer",S4($,"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 _9(_,w){let $=w.target==="openAi",X={type:"object",properties:{}},Y=[],J=_.shape();for(let Q in J){let G=J[Q];if(G===void 0||G._def===void 0)continue;let q=bz(G);if(q&&$){if(G._def.typeName==="ZodOptional")G=G._def.innerType;if(!G.isNullable())G=G.nullable();q=!1}let H=k(G._def,{...w,currentPath:[...w.currentPath,"properties",Q],propertyPath:[...w.currentPath,"properties",Q]});if(H===void 0)continue;if(X.properties[Q]=H,!q)Y.push(Q)}if(Y.length)X.required=Y;let W=Nz(_,w);if(W!==void 0)X.additionalProperties=W;return X}function Nz(_,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 bz(_){try{return _.isOptional()}catch{return!0}}var w9=(_,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 $9=(_,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 X9(_,w){return k(_.type._def,w)}function Y9(_,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 J9(_,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 W9(_){return{not:s(_)}}function Q9(_){return s(_)}var G9=(_,w)=>{return k(_.innerType._def,w)};var q9=(_,w,$)=>{switch(w){case K.ZodString:return z1(_,$);case K.ZodNumber:return eX(_,$);case K.ZodObject:return _9(_,$);case K.ZodBigInt:return yX(_,$);case K.ZodBoolean:return vX();case K.ZodDate:return P4(_,$);case K.ZodUndefined:return W9($);case K.ZodNull:return aX($);case K.ZodArray:return hX(_,$);case K.ZodUnion:case K.ZodDiscriminatedUnion:return sX(_,$);case K.ZodIntersection:return cX(_,$);case K.ZodTuple:return J9(_,$);case K.ZodRecord:return V1(_,$);case K.ZodLiteral:return dX(_,$);case K.ZodEnum:return lX(_);case K.ZodNativeEnum:return nX(_);case K.ZodNullable:return tX(_,$);case K.ZodOptional:return w9(_,$);case K.ZodMap:return iX(_,$);case K.ZodSet:return Y9(_,$);case K.ZodLazy:return()=>_.getter()._def;case K.ZodPromise:return X9(_,$);case K.ZodNaN:case K.ZodNever:return rX($);case K.ZodEffects:return uX(_,$);case K.ZodAny:return s($);case K.ZodUnknown:return Q9($);case K.ZodDefault:return mX(_,$);case K.ZodBranded:return U1(_,$);case K.ZodReadonly:return G9(_,$);case K.ZodCatch:return xX(_,$);case K.ZodPipeline:return $9(_,$);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 Q=w.override?.(_,w,X,$);if(Q!==IX)return Q}if(X&&!$){let Q=jz(X,w);if(Q!==void 0)return Q}let Y={def:_,path:w.currentPath,jsonSchema:void 0};w.seen.set(_,Y);let J=q9(_,_.typeName,w),W=typeof J==="function"?k(J(),w):J;if(W)Ez(_,w,W);if(w.postProcess){let Q=w.postProcess(W,_,w);return Y.jsonSchema=W,Q}return Y.jsonSchema=W,W}var jz=(_,w)=>{switch(w.$refStrategy){case"root":return{$ref:_.path.join("/")};case"relative":return{$ref:B1(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}}},Ez=(_,w,$)=>{if(_.description){if($.description=_.description,w.markdownDescription)$.markdownDescription=_.description}return $};var T4=(_,w)=>{let $=gX(w),X=typeof w==="object"&&w.definitions?Object.entries(w.definitions).reduce((G,[q,H])=>({...G,[q]:k(H._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($),W=typeof w==="object"&&w.name!==void 0&&w.nameStrategy==="title"?w.name:void 0;if(W!==void 0)J.title=W;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 Q=Y===void 0?X?{...J,[$.definitionPath]:X}:J:{$ref:[...$.$refStrategy==="relative"?[]:$.basePath,$.definitionPath,Y].join("/"),[$.definitionPath]:{...X,[Y]:J}};if($.target==="jsonSchema7")Q.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="jsonSchema2019-09"||$.target==="openAi")Q.$schema="https://json-schema.org/draft/2019-09/schema#";if($.target==="openAi"&&(("anyOf"in Q)||("oneOf"in Q)||("allOf"in Q)||("type"in Q)&&Array.isArray(Q.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return Q};var Sz=[x0,p0,m0,u0,l0,c0,d0,i0,n0];function Pz(_){let w=_;if(!w)return{};let $=w.shape?w:w._def?.schema??w;try{let X=T4($,{target:"jsonSchema7",$refStrategy:"none",effectStrategy:"input"}),{$schema:Y,...J}=X;return J}catch{return{}}}function H9(_,w={}){let $=CX(_,w);return Sz.map((X)=>{let Y=X($);return{name:Y.name,description:Y.description,input:Pz(Y.parameters),options:{codemode:!1},execute:async(J,W)=>{let Q={session_id:W?.sessionID??w.sessionId??"unknown",workdir:W?.directory};try{let G=await Y.execute(J??{},Q),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 D9(_,w){let $=_?.dispose;if(typeof $==="function")w.push($)}async function B9(_,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 Q=await Y.agent.transform((G)=>{L1(G)});D9(Q,X.disposers),X.agentId=J}catch(Q){X.errors.push(`roy agent registration failed: ${I4(Q)}`)}else X.errors.push("ctx.agent.transform unavailable \u2014 roy agent not registered");let W=[];try{W=H9(w.store,{agent:J,...w.sessionId?{sessionId:w.sessionId}:{}})}catch(Q){return X.errors.push(`roy tool construction failed: ${I4(Q)}`),X}if(typeof Y.tool?.transform==="function")try{let Q=await Y.tool.transform((G)=>{for(let q of W)G.add(q)});D9(Q,X.disposers),X.toolNames=W.map((G)=>G.name)}catch(Q){X.errors.push(`roy tool registration failed: ${I4(Q)}`)}else X.errors.push("ctx.tool.transform unavailable \u2014 roy task tools not registered");return X}function I4(_){return _ instanceof Error?_.message:String(_)}import{join as h4}from"path";import{homedir as yz}from"os";import{mkdirSync as vz}from"fs";import{Database as Zz}from"bun:sqlite";import{createHash as Cz,randomUUID as Tz}from"crypto";var Iz=`
|
|
2547
2548
|
CREATE TABLE IF NOT EXISTS tasks (
|
|
2548
2549
|
id TEXT PRIMARY KEY,
|
|
2549
2550
|
title TEXT NOT NULL,
|
|
@@ -2598,13 +2599,13 @@ CREATE TABLE IF NOT EXISTS bounties (
|
|
|
2598
2599
|
done_at TEXT
|
|
2599
2600
|
);
|
|
2600
2601
|
CREATE INDEX IF NOT EXISTS bounties_status_idx ON bounties(status);
|
|
2601
|
-
`;function
|
|
2602
|
+
`;function Kw(){return new Date().toISOString()}function k4(){return Tz()}function kz(_){return Cz("sha256").update(_).digest("hex")}function U9(_){let w=JSON.stringify({id:_.id,type:_.type,data:_.data,prev_hash:_.prev_hash,created_at:_.created_at});return kz(w)}function g4(_){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:gz(_.roy),created_at:_.created_at,updated_at:_.updated_at}}function gz(_){if(_===null||_===void 0||_==="")return;try{let w=JSON.parse(_);if(w&&typeof w==="object"&&!Array.isArray(w))return w;return}catch{return}}function hz(_){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 z9(_){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 O1(_){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 A1{db;closedFlag=!1;constructor(_){this.db=_}static async create(_){let w=new Zz(_);return w.exec(Iz),hz(w),new A1(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 W=this.db.query("SELECT task_id FROM task_idempotency WHERE idempotency_key = ?").get(w);if(W){let Q=await this.getTask(W.task_id);if(Q)return Q}}let $=k4(),X=Kw(),Y=_.priority??3;if(this.db.query(`INSERT INTO tasks (id, title, description, status, priority, owner, tags,
|
|
2602
2603
|
parent_id, blocked_by, retry_of, retry_count, session_id, roy, created_at, updated_at)
|
|
2603
|
-
VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?, 0, ?, ?, ?, ?)`).run($,_.title,_.description??null,
|
|
2604
|
-
VALUES (?, ?, ?)`).run(w,$,X);await this.appendOperation({task_id:$,type:"task.created",data:{title:_.title,parent_id:_.parent_id??null}});let
|
|
2605
|
-
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),J
|
|
2606
|
-
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
|
|
2607
|
-
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
|
|
2604
|
+
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?g4(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?g4(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(Kw()),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 ")}`:"",W=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(g4),total:W}}async deleteTask(_){if(this.closedFlag)throw Error("store closed");return this.db.query("DELETE FROM tasks WHERE id = ?").run(_).changes>0}async setParentId(_,w){if(this.closedFlag)throw Error("store closed");this.db.query("UPDATE tasks SET parent_id = ?, updated_at = ? WHERE id = ?").run(w,Kw(),_)}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=k4(),Y=Kw(),J=U9({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)
|
|
2606
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`).run(X,_.task_id,_.type,JSON.stringify(_.data),Y,$,J);let W=this.db.query("SELECT last_insert_rowid() AS n").get().n;return{id:X,num:W,task_id:_.task_id,type:_.type,data:_.data,created_at:Y,prev_hash:$,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?z9(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 ")}`:"",W=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(z9),total:W}}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=U9({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=k4(),$=Kw();this.db.query(`INSERT INTO bounties (id, subject, body, from_, status, created_at)
|
|
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 O1(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 $=Kw();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 O1(X)}async completeBounty(_,w){if(this.closedFlag)throw Error("store closed");let $=Kw();if(this.db.query(`UPDATE bounties SET status = 'done', task_id = ?, done_at = ?
|
|
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 O1(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(O1)}}var xz=h4(yz(),".roy-task-plugin"),mz=h4(xz,"tasks.db");class $0{inner;constructor(_){this.inner=_}static async create(_){let w=_??mz;if(w!==":memory:")vz(h4(w,".."),{recursive:!0});let $=await A1.create(w);return new $0($)}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 h_ extends Error{status;body;constructor(_,w,$){super(w);this.status=_,this.body=$}}class y4{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(),W=null;try{W=J?JSON.parse(J):null}catch{W=J}if(!Y.ok)throw new h_(Y.status,`HTTP ${Y.status}`,W);return W}async createTask(_,w){let $=await this.request("POST","/tasks",{body:_,idempotencyKey:w});if(!$)throw new h_(500,"empty response from POST /tasks");return $}async getTask(_){try{return await this.request("GET",`/tasks/${encodeURIComponent(_)}`)}catch(w){if(w instanceof h_&&w.status===404)return null;throw w}}async updateTask(_,w){try{return await this.request("PATCH",`/tasks/${encodeURIComponent(_)}`,{body:w})}catch($){if($ instanceof h_&&$.status===404)return null;throw $}}async deleteTask(_){try{return await this.request("DELETE",`/tasks/${encodeURIComponent(_)}`),!0}catch(w){if(w instanceof h_&&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 h_(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 h_(500,"empty bounty response");return w}async claimBounty(_){try{return await this.request("POST","/bounties/claim",{body:{agent:_}})}catch(w){if(w instanceof h_&&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 h_&&$.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 e0{inner;constructor(_){this.inner=new y4(_)}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 wK(_={}){let w=_.persistence??"local",$;if(w==="remote"){if(!_.remoteUrl)throw Error("remoteUrl is required when persistence = 'remote' (e.g. http://localhost:7820)");$=new e0({baseUrl:_.remoteUrl,authToken:_.remoteAuthToken})}else $=await $0.create(_.localDbPath);let X={store:$,agent:_.agent??"opencode-default"};return{handlers:X2(X),store:$,async close(){await $.close()}}}var uz={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 e0({baseUrl:w.remoteUrl,authToken:w.remoteAuthToken})}else X=await $0.create(w.localDbPath);let Y={store:X,agent:w.agent??"opencode-default"},J=X2(Y),W=await B9(_,{store:X,enabled:w.royAgent!==!1,agent:"roy"}),Q=await _.agent.transform(async(q)=>{let B=q.get("build");if(!B)return;let D=String(B.system??""),O=`
|
|
2608
2609
|
|
|
2609
2610
|
# Roy Task Plugin (auto-injected by roy-task-plugin v2)
|
|
2610
2611
|
|
|
@@ -2619,7 +2620,7 @@ Mark progress on long tasks via \`task-update <id> --status <status>\`.
|
|
|
2619
2620
|
For task-first-class-citizen work (task tree, milestones, deliverables), switch
|
|
2620
2621
|
to the dedicated **\`roy\`** primary agent \u2014 it carries the full roy task
|
|
2621
2622
|
lifecycle as native tools.
|
|
2622
|
-
`;
|
|
2623
|
-
`)[0]?.trim()||`task-${Date.now()}`;await
|
|
2623
|
+
`;q.update("build",(z)=>{if(typeof z.system==="string"||z.system===void 0)z.system=D+O})}),G=await _.command.transform((q)=>{q.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(H)=>{let B=String(H?.prompt?.text??"").trim(),D=B.split(`
|
|
2624
|
+
`)[0]?.trim()||`task-${Date.now()}`;await J.session({type:"session.created",payload:{id:H?.sessionID??`cmd-${Date.now()}`,title:D,body:B,source:"command:task-create"}})}}),q.add({name:"task-list",description:"List tracked tasks. Filters: [--status <s>] [--owner <o>]",template:"task-list [--status <status>] [--owner <owner>]",execute:async()=>{}}),q.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 q of W.disposers)try{await q()}catch{}await Q.dispose(),await G.dispose(),await X.close()}}}},XK=uz;export{XK as default,wK as createRoyTaskPlugin,X2 as createHandlers,e0 as RemoteTaskStore,$0 as LocalTaskStore};
|
|
2624
2625
|
|
|
2625
|
-
//# debugId=
|
|
2626
|
+
//# debugId=6EB360EE2D0AAB7664756E2164756E21
|