adam-agent-server 0.1.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/LICENSE +21 -0
- package/README.md +424 -0
- package/dist/App-23CRAK2P.js +9 -0
- package/dist/adam-tools-MKUMZWCR.js +1 -0
- package/dist/approval-handler-SBFVVFGH.js +4 -0
- package/dist/channels-CNLMTKHM.js +1 -0
- package/dist/channels-VNG7U6UQ.js +1 -0
- package/dist/chunk-37OAKNKA.js +15 -0
- package/dist/chunk-3DAK2XWP.js +1 -0
- package/dist/chunk-3HM54J2N.js +1 -0
- package/dist/chunk-3OYRYMJW.js +11 -0
- package/dist/chunk-5AKFAMQL.js +29 -0
- package/dist/chunk-5BAD3NCT.js +1 -0
- package/dist/chunk-5GMYXCL3.js +1 -0
- package/dist/chunk-62PXAOD6.js +7 -0
- package/dist/chunk-B3CVXD44.js +104 -0
- package/dist/chunk-CV3ROBUM.js +1 -0
- package/dist/chunk-EJJDJY34.js +5 -0
- package/dist/chunk-F2IS5LWD.js +1 -0
- package/dist/chunk-FCV2DPZQ.js +1 -0
- package/dist/chunk-FUBKGVWI.js +8 -0
- package/dist/chunk-HMXDNPFE.js +5 -0
- package/dist/chunk-J5YZQQTS.js +3 -0
- package/dist/chunk-MMIO6BCA.js +10 -0
- package/dist/chunk-Q3N5LVPZ.js +5 -0
- package/dist/chunk-QOPUUA7O.js +1 -0
- package/dist/chunk-TGQYM4TH.js +6 -0
- package/dist/chunk-TYR3QUCL.js +23 -0
- package/dist/chunk-VURJZLM6.js +49 -0
- package/dist/chunk-W6JITSZF.js +569 -0
- package/dist/chunk-WGRTN6TX.js +1 -0
- package/dist/chunk-ZN5Q3YET.js +1 -0
- package/dist/cli.js +15 -0
- package/dist/config-42ZJPZDM.js +1 -0
- package/dist/db-ZDEA7EUY.js +1 -0
- package/dist/delivery-log-7DQ36UGP.js +1 -0
- package/dist/dist-CDWBOTZS.js +1 -0
- package/dist/engine-7VBPXTGK.js +1 -0
- package/dist/evolution-audit-MDA2ZVJW.js +1 -0
- package/dist/external-api-T7FFXVHL.js +1 -0
- package/dist/index.js +152 -0
- package/dist/logger-BEG4WFIM.js +1 -0
- package/dist/memories-BUNOVQVG.js +1 -0
- package/dist/onnxruntime_binding-6Q6HXASN.node +0 -0
- package/dist/onnxruntime_binding-EKZT2NRK.node +0 -0
- package/dist/onnxruntime_binding-P6S7V3CI.node +0 -0
- package/dist/onnxruntime_binding-PJNNIIUO.node +0 -0
- package/dist/onnxruntime_binding-UN6SPTQK.node +0 -0
- package/dist/role-presets-2X3VW75D.js +1 -0
- package/dist/roles-CMV5FMIA.js +1 -0
- package/dist/runtime-772O2XKZ.js +1 -0
- package/dist/server-bus-N5LCY73J.js +1 -0
- package/dist/session-manager-KO4CR3W6.js +1 -0
- package/dist/task-templates-AKQB7RRB.js +1 -0
- package/package.json +77 -0
- package/web/dist/assets/Card-BpwkRtmi.js +1 -0
- package/web/dist/assets/ChannelDetail-050qK78l.js +1 -0
- package/web/dist/assets/Channels-DA4gN6nU.js +12 -0
- package/web/dist/assets/Chat-LzhfKGQ5.js +1 -0
- package/web/dist/assets/Dashboard-Bh32YC_E.js +1 -0
- package/web/dist/assets/EmptyState-B08f3BH6.js +1 -0
- package/web/dist/assets/Evolution-BwsOuVbZ.js +3 -0
- package/web/dist/assets/GoalDetail-Zo16ZrYD.js +1 -0
- package/web/dist/assets/Goals-BmfVadFN.js +1 -0
- package/web/dist/assets/Logs-CYfQ9k_6.js +1 -0
- package/web/dist/assets/Memories-CgSb60RC.js +1 -0
- package/web/dist/assets/Plugins-DHgIfely.js +1 -0
- package/web/dist/assets/RoleDetail-CNJkMSuz.js +1 -0
- package/web/dist/assets/Roles-DGpN5Vm6.js +1 -0
- package/web/dist/assets/Settings-PjFyeX8n.js +1 -0
- package/web/dist/assets/Strategies-DBp2jYdi.js +1 -0
- package/web/dist/assets/Switch-yk5-dsti.js +1 -0
- package/web/dist/assets/Table-DWR4p9xA.js +1 -0
- package/web/dist/assets/TaskDetail-DMg-JAbC.js +2 -0
- package/web/dist/assets/Work-BYgMw2qj.js +1 -0
- package/web/dist/assets/dist-jv3vbjrx.js +1 -0
- package/web/dist/assets/format-DvtQjPZn.js +1 -0
- package/web/dist/assets/index-CWY8H-cU.js +52 -0
- package/web/dist/assets/index-OXMtvYRJ.css +2 -0
- package/web/dist/assets/rolldown-runtime-DF2fYuay.js +1 -0
- package/web/dist/assets/vendor-icons-DqHipOFA.js +1 -0
- package/web/dist/assets/vendor-react-C2hDj0vl.js +11 -0
- package/web/dist/assets/vendor-state-CRsbPXtF.js +1 -0
- package/web/dist/favicon.svg +1 -0
- package/web/dist/icons.svg +24 -0
- package/web/dist/index.html +19 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as LH,c as VH,d as L}from"./chunk-FCV2DPZQ.js";var eH=L(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.resolveBackendAndExecutionProviders=G.registerBackend=void 0;var X=new Map,m=[],jH=(t,H,_)=>{if(H&&typeof H.init=="function"&&typeof H.createInferenceSessionHandler=="function"){let a=X.get(t);if(a===void 0)X.set(t,{backend:H,priority:_});else{if(a.priority>_)return;if(a.priority===_&&a.backend!==H)throw new Error(`cannot register backend "${t}" using priority ${_}`)}if(_>=0){let e=m.indexOf(t);e!==-1&&m.splice(e,1);for(let i=0;i<m.length;i++)if(X.get(m[i]).priority<=_){m.splice(i,0,t);return}m.push(t)}return}throw new TypeError("not a valid backend")};G.registerBackend=jH;var qH=async t=>{let H=X.get(t);if(!H)return"backend not found.";if(H.initialized)return H.backend;if(H.aborted)return H.error;{let _=!!H.initPromise;try{return _||(H.initPromise=H.backend.init(t)),await H.initPromise,H.initialized=!0,H.backend}catch(a){return _||(H.error=`${a}`,H.aborted=!0),H.error}finally{delete H.initPromise}}},JH=async t=>{let H=t.executionProviders||[],_=H.map(E=>typeof E=="string"?E:E.name),a=_.length===0?m:_,e,i=[],n=new Set;for(let E of a){let r=await qH(E);typeof r=="string"?i.push({name:E,err:r}):(e||(e=r),e===r&&n.add(E))}if(!e)throw new Error(`no available backend found. ERR: ${i.map(E=>`[${E.name}] ${E.err}`).join(", ")}`);for(let{name:E,err:r}of i)_.includes(E)&&console.warn(`removing requested execution provider "${E}" from session options because it is not available: ${r}`);let $=H.filter(E=>n.has(typeof E=="string"?E:E.name));return[e,new Proxy(t,{get:(E,r)=>r==="executionProviders"?$:Reflect.get(E,r)})]};G.resolveBackendAndExecutionProviders=JH});var oH=L(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.registerBackend=void 0;var QH=eH();Object.defineProperty(F,"registerBackend",{enumerable:!0,get:function(){return QH.registerBackend}})});var pH=L(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.version=void 0;w.version="1.24.3"});var aH=L(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.env=void 0;var zH=pH(),AH="warning";K.env={wasm:{},webgl:{},webgpu:{},versions:{common:zH.version},set logLevel(t){if(t!==void 0){if(typeof t!="string"||["verbose","info","warning","error","fatal"].indexOf(t)===-1)throw new Error(`Unsupported logging level: ${t}`);AH=t}},get logLevel(){return AH}};Object.defineProperty(K.env,"logLevel",{enumerable:!0})});var lH=L(V=>{"use strict";Object.defineProperty(V,"__esModule",{value:!0});V.env=void 0;var YH=aH();V.env=YH.env});var TH=L(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.tensorToImageData=M.tensorToDataURL=void 0;var H_=(t,H)=>{let _=typeof document<"u"?document.createElement("canvas"):new OffscreenCanvas(1,1);_.width=t.dims[3],_.height=t.dims[2];let a=_.getContext("2d");if(a!=null){let e,i;H?.tensorLayout!==void 0&&H.tensorLayout==="NHWC"?(e=t.dims[2],i=t.dims[3]):(e=t.dims[3],i=t.dims[2]);let n=H?.format!==void 0?H.format:"RGB",$=H?.norm,E,r;$===void 0||$.mean===void 0?E=[255,255,255,255]:typeof $.mean=="number"?E=[$.mean,$.mean,$.mean,$.mean]:(E=[$.mean[0],$.mean[1],$.mean[2],0],$.mean[3]!==void 0&&(E[3]=$.mean[3])),$===void 0||$.bias===void 0?r=[0,0,0,0]:typeof $.bias=="number"?r=[$.bias,$.bias,$.bias,$.bias]:(r=[$.bias[0],$.bias[1],$.bias[2],0],$.bias[3]!==void 0&&(r[3]=$.bias[3]));let c=i*e,s=0,I=c,S=c*2,o=-1;n==="RGBA"?(s=0,I=c,S=c*2,o=c*3):n==="RGB"?(s=0,I=c,S=c*2):n==="RBG"&&(s=0,S=c,I=c*2);for(let D=0;D<i;D++)for(let B=0;B<e;B++){let N=(t.data[s++]-r[0])*E[0],C=(t.data[I++]-r[1])*E[1],d=(t.data[S++]-r[2])*E[2],Z=o===-1?255:(t.data[o++]-r[3])*E[3];a.fillStyle="rgba("+N+","+C+","+d+","+Z+")",a.fillRect(B,D,1,1)}if("toDataURL"in _)return _.toDataURL();throw new Error("toDataURL is not supported")}else throw new Error("Can not access image data")};M.tensorToDataURL=H_;var __=(t,H)=>{let _=typeof document<"u"?document.createElement("canvas").getContext("2d"):new OffscreenCanvas(1,1).getContext("2d"),a;if(_!=null){let e,i,n;H?.tensorLayout!==void 0&&H.tensorLayout==="NHWC"?(e=t.dims[2],i=t.dims[1],n=t.dims[3]):(e=t.dims[3],i=t.dims[2],n=t.dims[1]);let $=H!==void 0&&H.format!==void 0?H.format:"RGB",E=H?.norm,r,c;E===void 0||E.mean===void 0?r=[255,255,255,255]:typeof E.mean=="number"?r=[E.mean,E.mean,E.mean,E.mean]:(r=[E.mean[0],E.mean[1],E.mean[2],255],E.mean[3]!==void 0&&(r[3]=E.mean[3])),E===void 0||E.bias===void 0?c=[0,0,0,0]:typeof E.bias=="number"?c=[E.bias,E.bias,E.bias,E.bias]:(c=[E.bias[0],E.bias[1],E.bias[2],0],E.bias[3]!==void 0&&(c[3]=E.bias[3]));let s=i*e;if(H!==void 0&&(H.format!==void 0&&n===4&&H.format!=="RGBA"||n===3&&H.format!=="RGB"&&H.format!=="BGR"))throw new Error("Tensor format doesn't match input tensor dims");let I=4,S=0,o=1,D=2,B=3,N=0,C=s,d=s*2,Z=-1;$==="RGBA"?(N=0,C=s,d=s*2,Z=s*3):$==="RGB"?(N=0,C=s,d=s*2):$==="RBG"&&(N=0,d=s,C=s*2),a=_.createImageData(e,i);for(let y=0;y<i*e;S+=I,o+=I,D+=I,B+=I,y++)a.data[S]=(t.data[N++]-c[0])*r[0],a.data[o]=(t.data[C++]-c[1])*r[1],a.data[D]=(t.data[d++]-c[2])*r[2],a.data[B]=Z===-1?255:(t.data[Z++]-c[3])*r[3]}else throw new Error("Can not access image data");return a};M.tensorToImageData=__});var DH=L(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.tensorFromPinnedBuffer=p.tensorFromMLTensor=p.tensorFromGpuBuffer=p.tensorFromTexture=p.tensorFromImage=p.bufferToTensor=void 0;var g=j(),t_=(t,H)=>{if(t===void 0)throw new Error("Image buffer must be defined");if(H.height===void 0||H.width===void 0)throw new Error("Image height and width must be defined");if(H.tensorLayout==="NHWC")throw new Error("NHWC Tensor layout is not supported yet");let{height:_,width:a}=H,e=H.norm??{mean:255,bias:0},i,n;typeof e.mean=="number"?i=[e.mean,e.mean,e.mean,e.mean]:i=[e.mean[0],e.mean[1],e.mean[2],e.mean[3]??255],typeof e.bias=="number"?n=[e.bias,e.bias,e.bias,e.bias]:n=[e.bias[0],e.bias[1],e.bias[2],e.bias[3]??0];let $=H.format!==void 0?H.format:"RGBA",E=H.tensorFormat!==void 0&&H.tensorFormat!==void 0?H.tensorFormat:"RGB",r=_*a,c=E==="RGBA"?new Float32Array(r*4):new Float32Array(r*3),s=4,I=0,S=1,o=2,D=3,B=0,N=r,C=r*2,d=-1;$==="RGB"&&(s=3,I=0,S=1,o=2,D=-1),E==="RGBA"?d=r*3:E==="RBG"?(B=0,C=r,N=r*2):E==="BGR"&&(C=0,N=r,B=r*2);for(let y=0;y<r;y++,I+=s,o+=s,S+=s,D+=s)c[B++]=(t[I]+n[0])/i[0],c[N++]=(t[S]+n[1])/i[1],c[C++]=(t[o]+n[2])/i[2],d!==-1&&D!==-1&&(c[d++]=(t[D]+n[3])/i[3]);return E==="RGBA"?new g.Tensor("float32",c,[1,4,_,a]):new g.Tensor("float32",c,[1,3,_,a])};p.bufferToTensor=t_;var e_=async(t,H)=>{let _=typeof HTMLImageElement<"u"&&t instanceof HTMLImageElement,a=typeof ImageData<"u"&&t instanceof ImageData,e=typeof ImageBitmap<"u"&&t instanceof ImageBitmap,i=typeof t=="string",n,$=H??{},E=()=>{if(typeof document<"u")return document.createElement("canvas");if(typeof OffscreenCanvas<"u")return new OffscreenCanvas(1,1);throw new Error("Canvas is not supported")},r=c=>typeof HTMLCanvasElement<"u"&&c instanceof HTMLCanvasElement||c instanceof OffscreenCanvas?c.getContext("2d"):null;if(_){let c=E();c.width=t.width,c.height=t.height;let s=r(c);if(s!=null){let I=t.height,S=t.width;if(H!==void 0&&H.resizedHeight!==void 0&&H.resizedWidth!==void 0&&(I=H.resizedHeight,S=H.resizedWidth),H!==void 0){if($=H,H.tensorFormat!==void 0)throw new Error("Image input config format must be RGBA for HTMLImageElement");$.tensorFormat="RGBA",$.height=I,$.width=S}else $.tensorFormat="RGBA",$.height=I,$.width=S;s.drawImage(t,0,0),n=s.getImageData(0,0,S,I).data}else throw new Error("Can not access image data")}else if(a){let c,s;if(H!==void 0&&H.resizedWidth!==void 0&&H.resizedHeight!==void 0?(c=H.resizedHeight,s=H.resizedWidth):(c=t.height,s=t.width),H!==void 0&&($=H),$.format="RGBA",$.height=c,$.width=s,H!==void 0){let I=E();I.width=s,I.height=c;let S=r(I);if(S!=null)S.putImageData(t,0,0),n=S.getImageData(0,0,s,c).data;else throw new Error("Can not access image data")}else n=t.data}else if(e){if(H===void 0)throw new Error("Please provide image config with format for Imagebitmap");let c=E();c.width=t.width,c.height=t.height;let s=r(c);if(s!=null){let I=t.height,S=t.width;return s.drawImage(t,0,0,S,I),n=s.getImageData(0,0,S,I).data,$.height=I,$.width=S,(0,p.bufferToTensor)(n,$)}else throw new Error("Can not access image data")}else{if(i)return new Promise((c,s)=>{let I=E(),S=r(I);if(!t||!S)return s();let o=new Image;o.crossOrigin="Anonymous",o.src=t,o.onload=()=>{I.width=o.width,I.height=o.height,S.drawImage(o,0,0,I.width,I.height);let D=S.getImageData(0,0,I.width,I.height);$.height=I.height,$.width=I.width,c((0,p.bufferToTensor)(D.data,$))}});throw new Error("Input data provided is not supported - aborted tensor creation")}if(n!==void 0)return(0,p.bufferToTensor)(n,$);throw new Error("Input data provided is not supported - aborted tensor creation")};p.tensorFromImage=e_;var a_=(t,H)=>{let{width:_,height:a,download:e,dispose:i}=H,n=[1,a,_,4];return new g.Tensor({location:"texture",type:"float32",texture:t,dims:n,download:e,dispose:i})};p.tensorFromTexture=a_;var $_=(t,H)=>{let{dataType:_,dims:a,download:e,dispose:i}=H;return new g.Tensor({location:"gpu-buffer",type:_??"float32",gpuBuffer:t,dims:a,download:e,dispose:i})};p.tensorFromGpuBuffer=$_;var r_=(t,H)=>{let{dataType:_,dims:a,download:e,dispose:i}=H;return new g.Tensor({location:"ml-tensor",type:_??"float32",mlTensor:t,dims:a,download:e,dispose:i})};p.tensorFromMLTensor=r_;var E_=(t,H,_)=>new g.Tensor({location:"cpu-pinned",type:t,data:H,dims:_??[H.length]});p.tensorFromPinnedBuffer=E_});var BH=L(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.checkTypedArray=A.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=void 0;A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP=new Map([["float32",Float32Array],["uint8",Uint8Array],["int8",Int8Array],["uint16",Uint16Array],["int16",Int16Array],["int32",Int32Array],["bool",Uint8Array],["float64",Float64Array],["uint32",Uint32Array],["int4",Uint8Array],["uint4",Uint8Array]]);A.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP=new Map([[Float32Array,"float32"],[Uint8Array,"uint8"],[Int8Array,"int8"],[Uint16Array,"uint16"],[Int16Array,"int16"],[Int32Array,"int32"],[Float64Array,"float64"],[Uint32Array,"uint32"]]);var hH=!1,c_=()=>{if(!hH){hH=!0;let t=typeof BigInt64Array<"u"&&BigInt64Array.from,H=typeof BigUint64Array<"u"&&BigUint64Array.from,_=globalThis.Float16Array,a=typeof _<"u"&&_.from;t&&(A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("int64",BigInt64Array),A.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigInt64Array,"int64")),H&&(A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("uint64",BigUint64Array),A.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(BigUint64Array,"uint64")),a?(A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16",_),A.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.set(_,"float16")):A.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.set("float16",Uint16Array)}};A.checkTypedArray=c_});var NH=L(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.tensorReshape=O.calculateSize=void 0;var k=j(),i_=t=>{let H=1;for(let _=0;_<t.length;_++){let a=t[_];if(typeof a!="number"||!Number.isSafeInteger(a))throw new TypeError(`dims[${_}] must be an integer, got: ${a}`);if(a<0)throw new RangeError(`dims[${_}] must be a non-negative integer, got: ${a}`);H*=a}return H};O.calculateSize=i_;var s_=(t,H)=>{switch(t.location){case"cpu":return new k.Tensor(t.type,t.data,H);case"cpu-pinned":return new k.Tensor({location:"cpu-pinned",data:t.data,type:t.type,dims:H});case"texture":return new k.Tensor({location:"texture",texture:t.texture,type:t.type,dims:H});case"gpu-buffer":return new k.Tensor({location:"gpu-buffer",gpuBuffer:t.gpuBuffer,type:t.type,dims:H});case"ml-tensor":return new k.Tensor({location:"ml-tensor",mlTensor:t.mlTensor,type:t.type,dims:H});default:throw new Error(`tensorReshape: tensor location ${t.location} is not supported`)}};O.tensorReshape=s_});var j=L(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.Tensor=void 0;var CH=TH(),U=DH(),q=BH(),dH=NH(),$H=class{constructor(H,_,a){(0,q.checkTypedArray)();let e,i;if(typeof H=="object"&&"location"in H)switch(this.dataLocation=H.location,e=H.type,i=H.dims,H.location){case"cpu-pinned":{let $=q.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(e);if(!$)throw new TypeError(`unsupported type "${e}" to create tensor from pinned buffer`);if(!(H.data instanceof $))throw new TypeError(`buffer should be of type ${$.name}`);this.cpuData=H.data;break}case"texture":{if(e!=="float32")throw new TypeError(`unsupported type "${e}" to create tensor from texture`);this.gpuTextureData=H.texture,this.downloader=H.download,this.disposer=H.dispose;break}case"gpu-buffer":{if(e!=="float32"&&e!=="float16"&&e!=="int32"&&e!=="int64"&&e!=="uint32"&&e!=="uint8"&&e!=="bool"&&e!=="uint4"&&e!=="int4")throw new TypeError(`unsupported type "${e}" to create tensor from gpu buffer`);this.gpuBufferData=H.gpuBuffer,this.downloader=H.download,this.disposer=H.dispose;break}case"ml-tensor":{if(e!=="float32"&&e!=="float16"&&e!=="int32"&&e!=="int64"&&e!=="uint32"&&e!=="uint64"&&e!=="int8"&&e!=="uint8"&&e!=="bool"&&e!=="uint4"&&e!=="int4")throw new TypeError(`unsupported type "${e}" to create tensor from MLTensor`);this.mlTensorData=H.mlTensor,this.downloader=H.download,this.disposer=H.dispose;break}default:throw new Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let $,E;if(typeof H=="string")if(e=H,E=a,H==="string"){if(!Array.isArray(_))throw new TypeError("A string tensor's data must be a string array.");$=_}else{let r=q.NUMERIC_TENSOR_TYPE_TO_TYPEDARRAY_MAP.get(H);if(r===void 0)throw new TypeError(`Unsupported tensor type: ${H}.`);if(Array.isArray(_)){if(H==="float16"&&r===Uint16Array||H==="uint4"||H==="int4")throw new TypeError(`Creating a ${H} tensor from number array is not supported. Please use ${r.name} as data.`);H==="uint64"||H==="int64"?$=r.from(_,BigInt):$=r.from(_)}else if(_ instanceof r)$=_;else if(_ instanceof Uint8ClampedArray)if(H==="uint8")$=Uint8Array.from(_);else throw new TypeError("A Uint8ClampedArray tensor's data must be type of uint8");else if(H==="float16"&&_ instanceof Uint16Array&&r!==Uint16Array)$=new globalThis.Float16Array(_.buffer,_.byteOffset,_.length);else throw new TypeError(`A ${e} tensor's data must be type of ${r}`)}else if(E=_,Array.isArray(H)){if(H.length===0)throw new TypeError("Tensor type cannot be inferred from an empty array.");let r=typeof H[0];if(r==="string")e="string",$=H;else if(r==="boolean")e="bool",$=Uint8Array.from(H);else throw new TypeError(`Invalid element type of data array: ${r}.`)}else if(H instanceof Uint8ClampedArray)e="uint8",$=Uint8Array.from(H);else{let r=q.NUMERIC_TENSOR_TYPEDARRAY_TO_TYPE_MAP.get(H.constructor);if(r===void 0)throw new TypeError(`Unsupported type for tensor data: ${H.constructor}.`);e=r,$=H}if(E===void 0)E=[$.length];else if(!Array.isArray(E))throw new TypeError("A tensor's dims must be a number array");i=E,this.cpuData=$,this.dataLocation="cpu"}let n=(0,dH.calculateSize)(i);if(this.cpuData&&n!==this.cpuData.length&&!((e==="uint4"||e==="int4")&&Math.ceil(n/2)===this.cpuData.length))throw new Error(`Tensor's size(${n}) does not match data length(${this.cpuData.length}).`);this.type=e,this.dims=i,this.size=n}static async fromImage(H,_){return(0,U.tensorFromImage)(H,_)}static fromTexture(H,_){return(0,U.tensorFromTexture)(H,_)}static fromGpuBuffer(H,_){return(0,U.tensorFromGpuBuffer)(H,_)}static fromMLTensor(H,_){return(0,U.tensorFromMLTensor)(H,_)}static fromPinnedBuffer(H,_,a){return(0,U.tensorFromPinnedBuffer)(H,_,a)}toDataURL(H){return(0,CH.tensorToDataURL)(this,H)}toImageData(H){return(0,CH.tensorToImageData)(this,H)}get data(){if(this.ensureValid(),!this.cpuData)throw new Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw new Error("The data is not stored as a WebGL texture.");return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw new Error("The data is not stored as a WebGPU buffer.");return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw new Error("The data is not stored as a WebNN MLTensor.");return this.mlTensorData}async getData(H){switch(this.ensureValid(),this.dataLocation){case"cpu":case"cpu-pinned":return this.data;case"texture":case"gpu-buffer":case"ml-tensor":{if(!this.downloader)throw new Error("The current tensor is not created with a specified data downloader.");if(this.isDownloading)throw new Error("The current tensor is being downloaded.");try{this.isDownloading=!0;let _=await this.downloader();return this.downloader=void 0,this.dataLocation="cpu",this.cpuData=_,H&&this.disposer&&(this.disposer(),this.disposer=void 0),_}finally{this.isDownloading=!1}}default:throw new Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw new Error("The current tensor is being downloaded.");this.disposer&&(this.disposer(),this.disposer=void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation="none"}ensureValid(){if(this.dataLocation==="none")throw new Error("The tensor is disposed.")}reshape(H){if(this.ensureValid(),this.downloader||this.disposer)throw new Error("Cannot reshape a tensor that owns GPU resource.");return(0,dH.tensorReshape)(this,H)}};J.Tensor=$H});var rH=L(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.Tensor=void 0;var n_=j();Q.Tensor=n_.Tensor});var EH=L(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.TRACE_EVENT_END=h.TRACE_EVENT_BEGIN=h.TRACE_FUNC_END=h.TRACE_FUNC_BEGIN=h.TRACE=void 0;var l=aH(),I_=(t,H)=>{(typeof l.env.trace>"u"?!l.env.wasm.trace:!l.env.trace)||console.timeStamp(`${t}::ORT::${H}`)};h.TRACE=I_;var fH=(t,H)=>{let _=new Error().stack?.split(/\r\n|\r|\n/g)||[],a=!1;for(let e=0;e<_.length;e++){if(a&&!_[e].includes("TRACE_FUNC")){let i=`FUNC_${t}::${_[e].trim().split(" ")[1]}`;H&&(i+=`::${H}`),(0,h.TRACE)("CPU",i);return}_[e].includes("TRACE_FUNC")&&(a=!0)}},S_=t=>{(typeof l.env.trace>"u"?!l.env.wasm.trace:!l.env.trace)||fH("BEGIN",t)};h.TRACE_FUNC_BEGIN=S_;var L_=t=>{(typeof l.env.trace>"u"?!l.env.wasm.trace:!l.env.trace)||fH("END",t)};h.TRACE_FUNC_END=L_;var o_=t=>{(typeof l.env.trace>"u"?!l.env.wasm.trace:!l.env.trace)||console.time(`ORT::${t}`)};h.TRACE_EVENT_BEGIN=o_;var p_=t=>{(typeof l.env.trace>"u"?!l.env.wasm.trace:!l.env.trace)||console.timeEnd(`ORT::${t}`)};h.TRACE_EVENT_END=p_});var uH=L(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.InferenceSession=void 0;var A_=eH(),W=rH(),P=EH(),cH=class t{constructor(H){this.handler=H}async run(H,_,a){(0,P.TRACE_FUNC_BEGIN)(),(0,P.TRACE_EVENT_BEGIN)("InferenceSession.run");let e={},i={};if(typeof H!="object"||H===null||H instanceof W.Tensor||Array.isArray(H))throw new TypeError("'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.");let n=!0;if(typeof _=="object"){if(_===null)throw new TypeError("Unexpected argument[1]: cannot be null.");if(_ instanceof W.Tensor)throw new TypeError("'fetches' cannot be a Tensor");if(Array.isArray(_)){if(_.length===0)throw new TypeError("'fetches' cannot be an empty array.");n=!1;for(let r of _){if(typeof r!="string")throw new TypeError("'fetches' must be a string array or an object.");if(this.outputNames.indexOf(r)===-1)throw new RangeError(`'fetches' contains invalid output name: ${r}.`);e[r]=null}if(typeof a=="object"&&a!==null)i=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else{let r=!1,c=Object.getOwnPropertyNames(_);for(let s of this.outputNames)if(c.indexOf(s)!==-1){let I=_[s];(I===null||I instanceof W.Tensor)&&(r=!0,n=!1,e[s]=I)}if(r){if(typeof a=="object"&&a!==null)i=a;else if(typeof a<"u")throw new TypeError("'options' must be an object.")}else i=_}}else if(typeof _<"u")throw new TypeError("Unexpected argument[1]: must be 'fetches' or 'options'.");for(let r of this.inputNames)if(typeof H[r]>"u")throw new Error(`input '${r}' is missing in 'feeds'.`);if(n)for(let r of this.outputNames)e[r]=null;let $=await this.handler.run(H,e,i),E={};for(let r in $)if(Object.hasOwnProperty.call($,r)){let c=$[r];c instanceof W.Tensor?E[r]=c:E[r]=new W.Tensor(c.type,c.data,c.dims)}return(0,P.TRACE_EVENT_END)("InferenceSession.run"),(0,P.TRACE_FUNC_END)(),E}async release(){return this.handler.dispose()}static async create(H,_,a,e){(0,P.TRACE_FUNC_BEGIN)(),(0,P.TRACE_EVENT_BEGIN)("InferenceSession.create");let i,n={};if(typeof H=="string"){if(i=H,typeof _=="object"&&_!==null)n=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else if(H instanceof Uint8Array){if(i=H,typeof _=="object"&&_!==null)n=_;else if(typeof _<"u")throw new TypeError("'options' must be an object.")}else if(H instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&H instanceof SharedArrayBuffer){let c=H,s=0,I=H.byteLength;if(typeof _=="object"&&_!==null)n=_;else if(typeof _=="number"){if(s=_,!Number.isSafeInteger(s))throw new RangeError("'byteOffset' must be an integer.");if(s<0||s>=c.byteLength)throw new RangeError(`'byteOffset' is out of range [0, ${c.byteLength}).`);if(I=H.byteLength-s,typeof a=="number"){if(I=a,!Number.isSafeInteger(I))throw new RangeError("'byteLength' must be an integer.");if(I<=0||s+I>c.byteLength)throw new RangeError(`'byteLength' is out of range (0, ${c.byteLength-s}].`);if(typeof e=="object"&&e!==null)n=e;else if(typeof e<"u")throw new TypeError("'options' must be an object.")}else if(typeof a<"u")throw new TypeError("'byteLength' must be a number.")}else if(typeof _<"u")throw new TypeError("'options' must be an object.");i=new Uint8Array(c,s,I)}else throw new TypeError("Unexpected argument[0]: must be 'path' or 'buffer'.");let[$,E]=await(0,A_.resolveBackendAndExecutionProviders)(n),r=await $.createInferenceSessionHandler(i,E);return(0,P.TRACE_EVENT_END)("InferenceSession.create"),(0,P.TRACE_FUNC_END)(),new t(r)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}};z.InferenceSession=cH});var bH=L(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.InferenceSession=void 0;var l_=uH();Y.InferenceSession=l_.InferenceSession});var PH=L(xH=>{"use strict";Object.defineProperty(xH,"__esModule",{value:!0})});var RH=L(mH=>{"use strict";Object.defineProperty(mH,"__esModule",{value:!0})});var ZH=L(vH=>{"use strict";Object.defineProperty(vH,"__esModule",{value:!0})});var MH=L(GH=>{"use strict";Object.defineProperty(GH,"__esModule",{value:!0})});var HH=L(T=>{"use strict";var T_=T&&T.__createBinding||(Object.create?(function(t,H,_,a){a===void 0&&(a=_);var e=Object.getOwnPropertyDescriptor(H,_);(!e||("get"in e?!H.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return H[_]}}),Object.defineProperty(t,a,e)}):(function(t,H,_,a){a===void 0&&(a=_),t[a]=H[_]})),b=T&&T.__exportStar||function(t,H){for(var _ in t)_!=="default"&&!Object.prototype.hasOwnProperty.call(H,_)&&T_(H,t,_)};Object.defineProperty(T,"__esModule",{value:!0});b(oH(),T);b(lH(),T);b(bH(),T);b(rH(),T);b(PH(),T);b(RH(),T);b(EH(),T);b(ZH(),T);b(MH(),T)});var gH=L((Ht,D_)=>{D_.exports="./onnxruntime_binding-EKZT2NRK.node"});var OH=L((_t,h_)=>{h_.exports="./onnxruntime_binding-6Q6HXASN.node"});var yH=L((tt,B_)=>{B_.exports="./onnxruntime_binding-UN6SPTQK.node"});var KH=L((et,N_)=>{N_.exports="./onnxruntime_binding-PJNNIIUO.node"});var kH=L((at,C_)=>{C_.exports="./onnxruntime_binding-P6S7V3CI.node"});var d_,iH=VH(()=>{d_=LH({"../bin/napi-v6/darwin/arm64/onnxruntime_binding.node":()=>gH(),"../bin/napi-v6/linux/arm64/onnxruntime_binding.node":()=>OH(),"../bin/napi-v6/linux/x64/onnxruntime_binding.node":()=>yH(),"../bin/napi-v6/win32/arm64/onnxruntime_binding.node":()=>KH(),"../bin/napi-v6/win32/x64/onnxruntime_binding.node":()=>kH()})});var WH=L(R=>{"use strict";iH();Object.defineProperty(R,"__esModule",{value:!0});R.initOrt=R.binding=void 0;var _H=HH();R.binding=d_(`../bin/napi-v6/${process.platform}/${process.arch}/onnxruntime_binding.node`);var UH=!1,f_=()=>{if(!UH){UH=!0;let t=2;if(_H.env.logLevel)switch(_H.env.logLevel){case"verbose":t=0;break;case"info":t=1;break;case"warning":t=2;break;case"error":t=3;break;case"fatal":t=4;break;default:throw new Error(`Unsupported log level: ${_H.env.logLevel}`)}R.binding.initOrtOnce(t,_H.Tensor)}};R.initOrt=f_});var SH=L(u=>{"use strict";var u_=u&&u.__classPrivateFieldSet||function(t,H,_,a,e){if(a==="m")throw new TypeError("Private method is not writable");if(a==="a"&&!e)throw new TypeError("Private accessor was defined without a setter");if(typeof H=="function"?t!==H||!e:!H.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return a==="a"?e.call(t,_):e?e.value=_:H.set(t,_),_},v=u&&u.__classPrivateFieldGet||function(t,H,_,a){if(_==="a"&&!a)throw new TypeError("Private accessor was defined without a getter");if(typeof H=="function"?t!==H||!a:!H.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return _==="m"?a:_==="a"?a.call(t):a?a.value:H.get(t)},f;Object.defineProperty(u,"__esModule",{value:!0});u.listSupportedBackends=u.onnxruntimeBackend=void 0;var sH=WH(),b_=[void 0,"float32","uint8","int8","uint16","int16","int32","int64","string","bool","float16","float64","uint32","uint64",void 0,void 0,void 0,void 0,void 0,void 0,void 0,"uint4","int4"],nH=class{constructor(H,_){f.set(this,void 0),(0,sH.initOrt)(),u_(this,f,new sH.binding.InferenceSession,"f"),typeof H=="string"?v(this,f,"f").loadModel(H,_):v(this,f,"f").loadModel(H.buffer,H.byteOffset,H.byteLength,_),this.inputNames=[],this.outputNames=[],this.inputMetadata=[],this.outputMetadata=[];let a=e=>{let i=[],n=[];for(let $ of e)if(i.push($.name),!$.isTensor)n.push({name:$.name,isTensor:!1});else{let E=b_[$.type];if(E===void 0)throw new Error(`Unsupported data type: ${$.type}`);let r=[];for(let c=0;c<$.shape.length;++c){let s=$.shape[c];if(s===-1)r.push($.symbolicDimensions[c]);else if(s>=0)r.push(s);else throw new Error(`Invalid dimension: ${s}`)}n.push({name:$.name,isTensor:$.isTensor,type:E,shape:r})}return[i,n]};[this.inputNames,this.inputMetadata]=a(v(this,f,"f").inputMetadata),[this.outputNames,this.outputMetadata]=a(v(this,f,"f").outputMetadata)}async dispose(){v(this,f,"f").dispose()}startProfiling(){}endProfiling(){v(this,f,"f").endProfiling()}async run(H,_,a){return new Promise((e,i)=>{setImmediate(()=>{try{e(v(this,f,"f").run(H,_,a))}catch(n){i(n)}})})}};f=new WeakMap;var IH=class{async init(){return Promise.resolve()}async createInferenceSessionHandler(H,_){return new Promise((a,e)=>{setImmediate(()=>{try{a(new nH(H,_||{}))}catch(i){e(i)}})})}};u.onnxruntimeBackend=new IH;u.listSupportedBackends=sH.binding.listSupportedBackends});var XH=L(tH=>{"use strict";Object.defineProperty(tH,"__esModule",{value:!0});tH.version=void 0;tH.version="1.24.3"});var Z_=L(x=>{var x_=x&&x.__createBinding||(Object.create?(function(t,H,_,a){a===void 0&&(a=_);var e=Object.getOwnPropertyDescriptor(H,_);(!e||("get"in e?!H.__esModule:e.writable||e.configurable))&&(e={enumerable:!0,get:function(){return H[_]}}),Object.defineProperty(t,a,e)}):(function(t,H,_,a){a===void 0&&(a=_),t[a]=H[_]})),P_=x&&x.__exportStar||function(t,H){for(var _ in t)_!=="default"&&!Object.prototype.hasOwnProperty.call(H,_)&&x_(H,t,_)};Object.defineProperty(x,"__esModule",{value:!0});x.listSupportedBackends=void 0;P_(HH(),x);var m_=SH();Object.defineProperty(x,"listSupportedBackends",{enumerable:!0,get:function(){return m_.listSupportedBackends}});var FH=HH(),R_=XH(),wH=SH(),v_=(0,wH.listSupportedBackends)();for(let t of v_)(0,FH.registerBackend)(t.name,wH.onnxruntimeBackend,100);Object.defineProperty(FH.env.versions,"node",{value:R_.version,enumerable:!0})});export default Z_();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-J5YZQQTS.js";import"./chunk-3OYRYMJW.js";import"./chunk-Q3N5LVPZ.js";import"./chunk-HMXDNPFE.js";import"./chunk-MMIO6BCA.js";import"./chunk-WGRTN6TX.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as DeliveryEngine,c as getDeliveryEngine,d as initDeliveryEngine,b as isDeliveryMessage,e as stopDeliveryEngine};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e}from"./chunk-5AKFAMQL.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{a as createEvolutionAudit,e as generateDiff,d as getLatestRoleEvolution,b as listEvolutionAudit,c as listEvolutionAuditByRole};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a as i}from"./chunk-ZN5Q3YET.js";import"./chunk-F2IS5LWD.js";import{c as a}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";var c=a("agent");async function g(n){let e=p();if(e.length===0)return{scores:[],errors:[]};let s=[],r=[];for(let t of e)try{let o=await u(t);o!==null&&s.push({nodeId:n,score:o,source:t.name,fetchedAt:Date.now()})}catch(o){r.push(`External API "${t.name}" (${t.url}): ${o instanceof Error?o.message:String(o)}`),c.warn({endpoint:t.name,error:o},"External API fetch failed")}return{scores:s,errors:r}}async function u(n){let e=await fetch(n.url,{signal:AbortSignal.timeout(5e3),headers:{Accept:"application/json"}});if(!e.ok)throw new Error(`HTTP ${e.status} ${e.statusText}`);let s=await e.json(),r=l(s,n.scorePath);if(typeof r!="number"||isNaN(r))throw new Error(`Score at "${n.scorePath}" is not a number: ${JSON.stringify(r)}`);return Math.max(0,Math.min(1,r))}function l(n,e){let s=e.replace(/^\$\.?/,""),r=n;for(let t of s.split(".")){if(r==null||typeof r!="object")return;r=r[t]}return r}function p(){return i.externalApis??[]}export{g as collectExternalApiScores};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import{a as Js,b as Qs,d as Ys}from"./chunk-5GMYXCL3.js";import{A as Pt,B as Ns,C as Ls,D as qs,E as Bs,F as Us,G as Ws,H as He,J as Ct,a as gt,b as ft,c as rs,d as ns,e as as,f as os,g as is,h as wt,i as us,j as fe,k as ms,l as gs,m as fs,n as Ue,o as St,p as bs,q as vs,r as ks,s as re,t as Ge,u as Ts,v as ws,w as Os,x as Fs,y as Ms,z as js}from"./chunk-B3CVXD44.js";import{d as Zs,e as er}from"./chunk-J5YZQQTS.js";import{a as ae,b as A,c as $,d as N,e as Xt,f as Gs,g as ze,h as Vs,i as $s,j as Hs}from"./chunk-3OYRYMJW.js";import{h as Xs}from"./chunk-Q3N5LVPZ.js";import{b as Ss,d as Ve,f as ye}from"./chunk-EJJDJY34.js";import{b as ds,d as $e,e as Ps,f as H,g as Cs,h as _s,i as As,j as Se,k as Z,l as Es,p as xs,q as Ds}from"./chunk-QOPUUA7O.js";import{b as ls,c as ps}from"./chunk-HMXDNPFE.js";import{a as X,b as Tt,d as cs}from"./chunk-MMIO6BCA.js";import{a as g}from"./chunk-WGRTN6TX.js";import{e as ys,n as hs}from"./chunk-TYR3QUCL.js";import{b as zs,c as Ks}from"./chunk-5AKFAMQL.js";import{a as ss,b as tr,c as sr,d as rr}from"./chunk-VURJZLM6.js";import{a as We,b as U,c as Rs,d as we,g as Is}from"./chunk-TGQYM4TH.js";import{a as Jt,b as ge}from"./chunk-CV3ROBUM.js";import{a as Kt}from"./chunk-ZN5Q3YET.js";import{a as qe,b as pt,c as Qt,d as Y,e as Yt,f as ut}from"./chunk-5BAD3NCT.js";import"./chunk-37OAKNKA.js";import{a as se,b as Te,c as Rt,d as It,f as kt}from"./chunk-FUBKGVWI.js";import{a as Zt,b as es,c as on,e as yt,f as B,g as ht,h as bt,i as oe,j as vt,l as ie}from"./chunk-62PXAOD6.js";import{b as j,c as mt,d as ke}from"./chunk-W6JITSZF.js";import{b as zt,c as q,f as me}from"./chunk-F2IS5LWD.js";import{a as ts,c as E,d as Be}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";import{writeFileSync as sn,mkdirSync as rn,unlinkSync as Ea}from"fs";import{join as ot}from"path";me();import{readFileSync as dn,existsSync as cn}from"fs";import{resolve as _t}from"path";function nr(o=q){let e=[],t=[],s=process.env.ADAM_ENV_FILE;s&&t.push(_t(o,s)),t.push(_t(o,".env.local")),t.push(_t(o,".env"));for(let r of t){if(!cn(r))continue;ln(r)>0&&e.push(r)}return e}function ln(o){let t=dn(o,"utf-8").split(`
|
|
2
|
+
`),s=0;for(let r of t){let n=r.trim();if(!n||n.startsWith("#"))continue;n.startsWith("export ")&&(n=n.slice(7).trim());let a=n.indexOf("=");if(a===-1)continue;let i=n.slice(0,a).trim();if(!i)continue;let d=n.slice(a+1).trim();(d.startsWith('"')&&d.endsWith('"')||d.startsWith("'")&&d.endsWith("'"))&&(d=d.slice(1,-1)),d=d.replace(/\$\{(\w+)\}|\$(\w+)/g,(c,l,b)=>{let u=l??b;return process.env[u]??""}),(i.startsWith("ANTHROPIC_")||process.env[i]===void 0)&&(process.env[i]=d,s++)}return s}ke();ie();kt();import{existsSync as ar}from"fs";import pn from"path";import un from"fastify";import mn from"@fastify/cors";import gn from"@fastify/static";import fn from"@fastify/websocket";import yn from"@fastify/swagger";import hn from"@fastify/swagger-ui";import{timingSafeEqual as bn}from"crypto";function ir(o,e){let t=un({logger:!1});if(t.register(yn,{openapi:{info:{title:"Adam API",description:"Agent orchestration server built on Claude Agent SDK. Multi-agent system with parallel task execution, intelligent agent routing, self-evolving personas, and REST/WebSocket API.",version:"2.0.0"},servers:[{url:"http://localhost:7100"}],tags:[{name:"Tasks",description:"Task lifecycle management"},{name:"Roles",description:"Role CRUD and workspace management"},{name:"Skills",description:"Skill CRUD and permissions"},{name:"Memories",description:"Agent memory search and retrieval"},{name:"Goals",description:"Goal-driven task management"},{name:"Strategies",description:"Thompson Sampling strategy engine"},{name:"Templates",description:"Task template CRUD and triggers"},{name:"Webhooks",description:"External system integration"},{name:"Config",description:"Runtime configuration management"},{name:"Evolution",description:"Agent evolution audit log"},{name:"Health",description:"Server health checks"}],components:{securitySchemes:{apiKey:{type:"apiKey",in:"header",name:"x-api-key",description:"API key for webhook endpoints"}}}}}),t.register(hn,{routePrefix:"/docs"}),t.register(mn,{origin:!0}),t.register(fn,{options:{maxPayload:1024*1024*16}}),e){let r=Buffer.from(e);t.addHook("onRequest",async(n,a)=>{let i=n.url;if(i==="/healthz"||i==="/readyz"||i.startsWith("/docs")||i.startsWith("/ui"))return;let d=n.headers["x-api-key"];if(d&&or(d,r))return;let c=n.query,l=c.api_key||c["x-api-key"];if(!(l&&or(l,r)))return a.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"})})}let s=pn.join(ss,"web/dist");return ar(s)&&(t.register(gn,{root:s,prefix:"/ui/",wildcard:!1}),t.get("/ui",async(r,n)=>n.sendFile("index.html",s)),t.get("/ui/*",async(r,n)=>n.sendFile("index.html",s))),t.setErrorHandler((r,n,a)=>{if(r.validation){let d=r.validation.map(c=>{let l=c.instancePath||c.params?.missingProperty||"";return l?`${l}: ${c.message}`:c.message});return a.status(400).send({code:"VALIDATION_ERROR",message:d.join("; ")})}let i=r.statusCode??500;return a.status(i).send({code:"INTERNAL_ERROR",message:r.message})}),t.setNotFoundHandler((r,n)=>r.url.startsWith("/ui")&&ar(s)?n.sendFile("index.html",s):n.status(404).send({code:"NOT_FOUND",message:"Route not found"})),t}function or(o,e){try{let t=Buffer.from(o);return t.length!==e.length?!1:bn(t,e)}catch{return!1}}import{z as p}from"zod/v4";import{v4 as Pn}from"uuid";var vn=o=>({...o,nullable:!0}),S={type:"object",properties:{code:{type:"string"},message:{type:"string"}}},Rn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}},In={type:"object",additionalProperties:!0,properties:{type:{type:"string"},cron:{type:"string"},event:{type:"string"}}},dr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},trigger:In,steps:{type:"array",items:Rn},agentPreference:{type:"string"},config:{type:"object",additionalProperties:!0},tags:{type:"array",items:{type:"string"}},enabled:{type:"boolean"},createdAt:{type:"number"},updatedAt:{type:"number"}}},kn={type:"object",properties:{input:{type:"number"},output:{type:"number"}}},cr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},parentId:{type:"string"},status:{type:"string"},prompt:{type:"string"},originalPrompt:{type:"string"},config:{type:"object",additionalProperties:!0},result:{type:"string"},error:{type:"string"},sdkSessionId:{type:"string"},roleId:{type:"string"},templateId:{type:"string"},createdAt:{type:"number"},startedAt:{type:"number"},completedAt:{type:"number"},costUsd:{type:"number"},tokenUsage:kn,numTurns:{type:"number"},totalDurationMs:{type:"number"}}},Tn={type:"object",additionalProperties:!0,properties:{model:{type:"string"},effort:{type:"string"},maxTurns:{type:"number"}}},Ke={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},source:{type:"string"},traits:{type:"array",items:{type:"string"}},background:{type:"string"},preferences:Tn,learnedRules:{type:"array",items:{type:"string"}},memoryStreamId:{type:"string"},status:{type:"string"},createdAt:{type:"number"},lastActiveAt:{type:"number"},taskCount:{type:"number"},performanceScore:{type:"number"},role:{type:"string"},toolProfile:{type:"array",items:{type:"string"}},evaluationCriteria:{type:"object",additionalProperties:{type:"number"}},strategyPoolId:{type:"string"}}},lr={type:"object",additionalProperties:!0,properties:{id:{type:"string"},roleId:{type:"string"},type:{type:"string"},content:{type:"string"},keywords:{type:"array",items:{type:"string"}},importance:{type:"number"},sourceType:{type:"string"},sourceTaskId:{type:"string"},evidence:{type:"array",items:{type:"string"}},createdAt:{type:"number"},lastAccessed:{type:"number"},retrievedCount:{type:"number"},score:{type:"number"}}},wn={type:"object",additionalProperties:!0,properties:{id:{type:"string"},role:{type:"string"},taskType:{type:"string"},name:{type:"string"},promptTemplate:{type:"string"},alpha:{type:"number"},beta:{type:"number"},totalTrials:{type:"number"},avgReward:{type:"number"},toolProfile:{type:"array",items:{type:"string"}},createdAt:{type:"number"},updatedAt:{type:"number"}}},At={type:"object",additionalProperties:!0,properties:{id:{type:"string"},name:{type:"string"},description:{type:"string"},role:{type:"string"},metricType:{type:"string"},targetValue:{type:"number"},currentValue:{type:"number"},deadline:{type:"number"},budgetUsd:{type:"number"},status:{type:"string"},createdAt:{type:"number"},updatedAt:{type:"number"}}},Sn={type:"object",additionalProperties:!0,properties:{name:{type:"string"},displayName:{type:"string"},description:{type:"string"},tags:{type:"array",items:{type:"string"}},trigger:{type:"string"}}},R={templateCreated:{201:{type:"object",properties:{templateId:{type:"string"}}}},templateList:{200:{type:"object",properties:{templates:{type:"array",items:dr}}}},templateDetail:{200:{type:"object",properties:{template:dr}},404:S},templateUpdated:{200:{type:"object",properties:{templateId:{type:"string"}}},404:S},templateDeleted:{200:{type:"object",properties:{templateId:{type:"string"},deleted:{type:"boolean"}}},404:S},templateRun:{200:{type:"object",properties:{executionId:{type:"string"},status:{type:"string"}}},404:S},taskCreated:{201:{type:"object",properties:{taskId:{type:"string"}}},400:S},taskList:{200:{type:"object",properties:{tasks:{type:"array",items:cr}}}},taskDetail:{200:{type:"object",properties:{task:cr}},404:S},taskAction:{200:{type:"object",additionalProperties:!0,properties:{taskId:{type:"string"}}},400:S,404:S},approvalAction:{200:{type:"object",properties:{approvalId:{type:"string"},decision:{type:"string"}}},404:S},agentList:{200:{type:"object",properties:{roles:{type:"array",items:Ke}}}},agentDetail:{200:{type:"object",properties:{agent:Ke}},404:S},agentCreated:{201:{type:"object",properties:{agent:Ke}}},agentUpdated:{200:{type:"object",properties:{agent:Ke}},404:S},agentDeleted:{200:{type:"object",properties:{agentId:{type:"string"},deleted:{type:"boolean"}}},400:S,404:S},agentPersona:{200:{type:"object",properties:{persona:vn({type:"string"})}},404:S},memoryList:{200:{type:"object",properties:{memories:{type:"array",items:lr},count:{type:"number"}}},404:S},memoryQuery:{200:{type:"object",properties:{memories:{type:"array",items:lr},count:{type:"number"}}},404:S},strategyList:{200:{type:"object",properties:{strategies:{type:"array",items:wn}}}},strategyProbabilities:{200:{type:"object",additionalProperties:!0,properties:{role:{type:"string"},taskType:{type:"string"},stats:{type:"object",additionalProperties:!0},probabilities:{type:"object",additionalProperties:{type:"number"}}}}},goalList:{200:{type:"object",properties:{goals:{type:"array",items:At}}}},goalDetail:{200:{type:"object",properties:{goal:At}},404:S},goalCreated:{201:{type:"object",properties:{goal:At}},400:{...S,additionalProperties:!0,properties:{...S.properties,errors:{type:"array",items:{type:"string"}},warnings:{type:"array",items:{type:"string"}}}}},webhookTriggered:{202:{type:"object",properties:{code:{type:"string"},message:{type:"string"},executionId:{type:"string"},templateId:{type:"string"}}},401:S,404:S,409:S,500:S},webhookList:{200:{type:"object",properties:{webhooks:{type:"array",items:Sn},auth:{type:"string"}}}},configGet:{200:{type:"object",additionalProperties:!0,properties:{config:{type:"object",additionalProperties:{type:"object",additionalProperties:!0,properties:{value:{},mutable:{type:"boolean"}}}},mutable:{type:"array",items:{type:"string"}},restartRequired:{type:"array",items:{type:"string"}}}}},configPatch:{200:{type:"object",additionalProperties:!0,properties:{success:{type:"boolean"},updated:{type:"array",items:{type:"string"}},errors:{type:"array",items:{type:"string"}},message:{type:"string"}}}},healthz:{200:{type:"object",properties:{status:{type:"string"}}}},readyz:{200:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}},503:{type:"object",properties:{status:{type:"string"},checks:{type:"object",additionalProperties:{type:"boolean"}}}}}};var pr=p.union([p.object({type:p.literal("session"),sessionId:p.string()}),p.object({type:p.literal("channel"),channelId:p.string(),chatId:p.string().optional()})]),Cn=p.object({prompt:p.string().min(1,"prompt is required"),skillId:p.string().optional(),deliverTo:p.array(pr).optional(),reportTo:p.array(pr).optional(),config:p.object({allowedTools:p.array(p.string()).optional(),disallowedTools:p.array(p.string()).optional(),maxTurns:p.number().optional(),maxBudgetUsd:p.number().optional(),mcpServers:p.record(p.string(),p.unknown()).optional(),model:p.string().optional(),effort:p.enum(["low","medium","high","max"]).optional(),settingSources:p.array(p.string()).optional(),workspacePath:p.string().optional(),timeout:p.number().optional(),approvalRequired:p.array(p.string()).optional(),approvalTimeout:p.number().optional(),fileAccess:p.object({allowedPaths:p.array(p.string()),deniedPaths:p.array(p.string())}).optional(),env:p.record(p.string(),p.string()).optional(),plugins:p.array(p.string()).optional()}).optional()}),he=p.object({id:p.string().uuid()}),_n=["pending","queued","running","paused","completed","failed","cancelled"],An=p.object({status:p.enum(_n).optional(),skillId:p.string().optional(),limit:p.coerce.number().min(1).max(100).default(100),offset:p.coerce.number().min(0).default(0)});async function ur(o){let e=new is;o.post("/tasks",{schema:{tags:["Tasks"],summary:"Create a task",description:"Create a new task with a prompt and optional agent/config overrides. The task enters 'pending' status and is picked up by the scheduler.",body:{type:"object",required:["prompt"],properties:{prompt:{type:"string",minLength:1,description:"Task prompt"},skillId:{type:"string",description:"Optional agent to assign"},config:{type:"object",description:"Optional task configuration overrides",properties:{model:{type:"string"},maxTurns:{type:"integer"},maxBudgetUsd:{type:"number"},timeout:{type:"integer"},effort:{type:"string",enum:["low","medium","high","max"]}}}}},response:R.taskCreated}},async(n,a)=>{let i=Cn.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{prompt:d,skillId:c,config:l,deliverTo:b,reportTo:u}=i.data,y=ge(),w={timeout:l?.timeout??y.timeout,approvalRequired:l?.approvalRequired??y.approvalRequired,approvalTimeout:l?.approvalTimeout??y.approvalTimeout,fileAccess:l?.fileAccess??y.fileAccess,allowedTools:l?.allowedTools??y.allowedTools,disallowedTools:l?.disallowedTools??y.disallowedTools,maxTurns:l?.maxTurns??y.maxTurns,maxBudgetUsd:l?.maxBudgetUsd??y.maxBudgetUsd,mcpServers:l?.mcpServers,model:l?.model||y.model||void 0,effort:l?.effort??y.effort,settingSources:l?.settingSources??y.settingSources,workspacePath:l?.workspacePath,env:l?.env??y.env,claudeCodePath:y.claudeCodePath,plugins:l?.plugins},v={id:Pn(),status:"pending",prompt:d,roleId:c??void 0,config:w,deliverTo:b,reportTo:u,createdAt:Date.now()};return ae(v),g.emit({type:"task_created",taskId:v.id}),a.status(201).send({taskId:v.id})}),o.get("/tasks",{schema:{tags:["Tasks"],summary:"List tasks",description:"List tasks with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["pending","queued","running","paused","completed","failed","cancelled"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}},response:R.taskList}},async(n,a)=>{let i=An.safeParse(n.query);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let{status:d,skillId:c,limit:l,offset:b}=i.data;return{tasks:N(d,l,b,c)}}),o.get("/tasks/:id",{schema:{tags:["Tasks"],summary:"Get task by ID",description:"Retrieve a single task by its UUID.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskDetail}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=A(i.data.id);return d?{task:d}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"})}),o.post("/tasks/:id/cancel",{schema:{tags:["Tasks"],summary:"Cancel a task",description:"Cancel a running, queued, pending, or paused task. Returns 400 if the task is in a terminal state.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},response:R.taskAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=A(i.data.id);return d?d.status!=="running"&&d.status!=="queued"&&d.status!=="pending"&&d.status!=="paused"?a.status(400).send({code:"INVALID_STATE",message:`Cannot cancel task in status: ${d.status}`}):(e.cancelTask(d.id),{taskId:d.id,status:"cancelled"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"})});let t=p.object({taskIds:p.array(p.string()).min(1).max(500)});o.post("/tasks/batch-cancel",{schema:{tags:["Tasks"],summary:"Batch cancel tasks",description:"Cancel multiple tasks at once. Skips tasks that are already in terminal state. Returns count of cancelled tasks.",body:{type:"object",required:["taskIds"],properties:{taskIds:{type:"array",items:{type:"string"},minItems:1,maxItems:500}}}}},async(n,a)=>{let i=t.safeParse(n.body);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=new Set(["pending","queued","running","paused"]),c=0,l=[];for(let b of i.data.taskIds){let u=A(b);if(!u){l.push({taskId:b,reason:"not found"});continue}if(!d.has(u.status)){l.push({taskId:b,reason:`already ${u.status}`});continue}e.cancelTask(b),c++}return{cancelled:c,total:i.data.taskIds.length,errors:l.length>0?l:void 0}}),o.get("/tasks/:id/logs",{schema:{tags:["Tasks"],summary:"Get task step logs",description:"Returns execution step logs for a task (reasoning, tool calls, results).",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(n,a)=>{let i=A(n.params.id);if(!i)return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{limit:d=50,offset:c=0}=n.query;return{logs:ft(i.id,d,c)}});let s=p.object({approvalId:p.string().uuid(),reason:p.string().optional()});o.post("/tasks/:id/approve",{schema:{tags:["Tasks"],summary:"Approve a pending approval",description:"Approve a tool-use approval request for a paused task. The skill agent resumes execution with the approved tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=s.safeParse(n.body);return d.success?A(i.data.id)?e.resolveApproval(d.data.approvalId,"allow",d.data.reason)?{approvalId:d.data.approvalId,decision:"allow"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)})}),o.post("/tasks/:id/reject",{schema:{tags:["Tasks"],summary:"Reject a pending approval",description:"Reject a tool-use approval request for a paused task. The skill agent skips the denied tool call.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["approvalId"],properties:{approvalId:{type:"string",format:"uuid"},reason:{type:"string"}}},response:R.approvalAction}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=s.safeParse(n.body);return d.success?A(i.data.id)?e.resolveApproval(d.data.approvalId,"deny",d.data.reason)?{approvalId:d.data.approvalId,decision:"deny"}:a.status(404).send({code:"NOT_FOUND",message:"Approval not found or already resolved"}):a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)})});let r=p.object({planId:p.string(),decision:p.enum(["allow","deny"]),approvalType:p.enum(["once","permanent"]).optional(),reason:p.string().optional()});o.post("/tasks/:id/approve-plan",{schema:{tags:["Tasks"],summary:"Approve or deny an execution plan",description:"Respond to a plan approval request. Allow once (single task), allow permanent (create rule for similar tasks), or deny.",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",required:["planId","decision"],properties:{planId:{type:"string"},decision:{type:"string",enum:["allow","deny"]},approvalType:{type:"string",enum:["once","permanent"]},reason:{type:"string"}}}}},async(n,a)=>{let i=he.safeParse(n.params);if(!i.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)});let d=r.safeParse(n.body);if(!d.success)return a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(d.error)});if(!A(i.data.id))return a.status(404).send({code:"NOT_FOUND",message:"Task not found"});let{planId:l,decision:b,approvalType:u,reason:y}=d.data;return e.resolvePlanApproval(l,b,u,y)?{planId:l,decision:b,approvalType:u}:a.status(404).send({code:"NOT_FOUND",message:"Plan approval not found or already resolved"})}),o.get("/tasks/:id/plan",{schema:{tags:["Tasks"],summary:"Get execution plans for a task",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(n,a)=>{let i=he.safeParse(n.params);return i.success?A(i.data.id)?{plans:ns(i.data.id)}:a.status(404).send({code:"NOT_FOUND",message:"Task not found"}):a.status(400).send({code:"VALIDATION_ERROR",message:p.prettifyError(i.error)})})}ke();ie();async function mr(o,e){o.get("/healthz",{schema:{tags:["Health"],summary:"Health check",description:"Basic liveness probe. Returns 200 if the server process is running.",response:R.healthz}},async(t,s)=>({status:"ok"})),o.get("/readyz",{schema:{tags:["Health"],summary:"Readiness check",description:"Readiness probe that checks database, roles, config, embedding model, and task hub. Returns 503 if any check fails.",response:R.readyz}},async(t,s)=>{let r={database:!1,manager:!1,config:!1};try{j().prepare("SELECT 1").get(),r.database=!0}catch{r.database=!1}r.manager=!0,r.config=!!e.server;try{let a=oe(void 0,1,0);r.agents=a.length>0}catch{r.agents=!1}return r.embedding=ds(),r.taskHub=!0,Object.values(r).every(a=>a)?{status:"ready",checks:r}:s.status(503).send({status:"not_ready",checks:r})}),o.get("/stats",{schema:{tags:["Health"],summary:"Runtime statistics",description:"Returns execution pool status, active/pending task counts, and cost summary."}},async(t,s)=>{let n=Y().execution?.maxConcurrent??5,a=N("running"),i=N("pending");return{executionPool:{active:a.length,max:n,queued:i.length}}})}import{timingSafeEqual as fr}from"crypto";import{z as yr}from"zod/v4";var Et=class{connections=new Map;eventBuffers=new Map;eventIndices=new Map;addConnection(e,t){this.connections.has(e)||this.connections.set(e,new Set),this.connections.get(e).add(t);let s=this.getBufferedEvents(e);for(let r of s)t.readyState===1&&t.send(JSON.stringify(r));t.on("close",()=>{this.removeConnection(e,t)})}removeConnection(e,t){let s=this.connections.get(e);s&&(s.delete(t),s.size===0&&this.connections.delete(e))}broadcast(e,t){this.addToBuffer(e,t);let s=this.connections.get(e);if(!s||s.size===0)return;let r=JSON.stringify(t);for(let n of s)n.readyState===1&&n.send(r)}addToBuffer(e,t){let s=this.eventBuffers.get(e);s||(s=[],this.eventBuffers.set(e,s)),s.push(t),s.length>100&&s.shift(),this.eventIndices.set(e,t.index)}getBufferedEvents(e){return this.eventBuffers.get(e)??[]}getNextIndex(e){let s=(this.eventIndices.get(e)??0)+1;return this.eventIndices.set(e,s),s}},gr=new Et;var En=yr.object({id:yr.string().uuid()});async function hr(o,e){o.get("/tasks/:id/stream",{websocket:!0},(t,s)=>{if(e&&!xn(s,e)){t.close(4401,"Unauthorized");return}let r=En.safeParse(s.params);if(!r.success){t.close(1008,"Invalid task ID");return}let{id:n}=r.data;if(!A(n)){t.close(1008,"Task not found");return}gr.addConnection(n,t)})}function xn(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&fr(n,a))return!0}catch{}let s=o.query,r=s.api_key||s["x-api-key"];if(r)try{let n=Buffer.from(r),a=Buffer.from(e);if(n.length===a.length&&fr(n,a))return!0}catch{}return!1}import{timingSafeEqual as br}from"crypto";var Dn=E("ws"),Je=new Set;function vr(o,e){o.get("/events",{websocket:!0},(t,s)=>{if(e&&!On(s,e)){t.close(4401,"Unauthorized");return}Je.add(t),t.on("close",()=>{Je.delete(t)}),t.on("error",r=>{Dn.error({error:r},"WebSocket error"),Je.delete(t)})}),g.on("task_status_change",t=>{z(t)}),g.on("approval_request",t=>{z(t)}),g.on("stats_update",t=>{z(t)}),g.on("log_event",t=>{z(t)}),g.on("config_changed",t=>{z(t)}),g.on("plan_approval_request",t=>{(()=>{try{let r=cs(t.taskId);if(!r)return!1;let n=ls(r.sessionId);return n?n.source.type==="channel"&&!!n.source.channelId:!1}catch{return!1}})()||z(t)}),g.on("plan_approval_decision",t=>{z(t)}),g.on("task_created",t=>{z(t)}),g.on("execution_slot_change",t=>{z(t)}),g.on("execution_task_start",t=>{z(t)}),g.on("execution_task_end",t=>{z(t)})}function z(o){let e=JSON.stringify(o);for(let t of Je)t.readyState===1&&t.send(e)}function On(o,e){let t=o.headers["x-api-key"];if(t)try{let n=Buffer.from(t),a=Buffer.from(e);if(n.length===a.length&&br(n,a))return!0}catch{}let s=o.query,r=s.api_key||s["x-api-key"];if(r)try{let n=Buffer.from(r),a=Buffer.from(e);if(n.length===a.length&&br(n,a))return!0}catch{}return!1}ke();function Fn(o){return{id:o.id,sdkSessionId:o.sdk_session_id??void 0,userTaskSessionId:o.user_task_session_id??void 0,workspacePath:o.workspace_path??void 0,toolsFingerprint:o.tools_fingerprint??void 0,createdAt:o.created_at,lastActiveAt:o.last_active_at??void 0}}function xt(){let o=j(),e=o.prepare("SELECT * FROM server_state WHERE id = 1").get();if(e)return Fn(e);let t=Date.now();return o.prepare("INSERT INTO server_state (id, created_at) VALUES (1, ?)").run(t),{id:1,createdAt:t}}function Pe(o){let e=j(),t=[],s=[];"sdkSessionId"in o&&(t.push("sdk_session_id = ?"),s.push(o.sdkSessionId??null)),"userTaskSessionId"in o&&(t.push("user_task_session_id = ?"),s.push(o.userTaskSessionId??null)),"workspacePath"in o&&(t.push("workspace_path = ?"),s.push(o.workspacePath??null)),"lastActiveAt"in o&&(t.push("last_active_at = ?"),s.push(o.lastActiveAt??null)),"toolsFingerprint"in o&&(t.push("tools_fingerprint = ?"),s.push(o.toolsFingerprint??null)),t.length!==0&&(xt(),s.push(1),e.prepare(`UPDATE server_state SET ${t.join(", ")} WHERE id = ?`).run(...s))}function Dt(o){Pe({sdkSessionId:o,lastActiveAt:Date.now()})}function Rr(){Pe({sdkSessionId:void 0,lastActiveAt:Date.now()})}function Ir(o){Pe({workspacePath:o})}ie();kt();St();import{z as m}from"zod/v4";import{v4 as kr}from"uuid";import{rmSync as Mn,existsSync as Ot}from"fs";var Tr=m.object({model:m.string().optional(),effort:m.enum(["low","medium","high","max"]).optional(),maxTurns:m.number().optional()}),wr=m.object({path:m.string(),inheritPlugins:m.boolean().optional(),inheritMcp:m.boolean().optional(),inheritPermissions:m.boolean().optional()}),jn=m.object({name:m.string().min(1,"name is required"),cagPrompt:m.string().optional(),learnedRules:m.array(m.string()).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),evaluationCriteria:m.record(m.string(),m.number()).optional(),executionMode:m.enum(["isolated","inline"]).optional(),model:m.string().optional(),maxBudgetUsd:m.number().optional(),approvalRequired:m.array(m.string()).optional(),preferences:Tr.optional(),additionalDirectories:m.array(wr).optional(),allowedChannels:m.array(m.string()).optional(),inheritUserSettings:m.boolean().optional()}),Nn=m.object({name:m.string().min(1).optional(),cagPrompt:m.string().optional(),learnedRules:m.array(m.string()).optional(),status:m.enum(["active","inactive","retired"]).optional(),allowedTools:m.array(m.string()).optional(),disallowedTools:m.array(m.string()).optional(),evaluationCriteria:m.record(m.string(),m.number()).optional(),executionMode:m.enum(["isolated","inline"]).optional(),model:m.string().optional(),maxBudgetUsd:m.number().optional(),approvalRequired:m.array(m.string()).optional(),preferences:Tr.optional(),additionalDirectories:m.array(wr).optional(),allowedChannels:m.array(m.string()).nullable().optional(),inheritUserSettings:m.boolean().optional()}),Qe=m.object({id:m.string().min(1)}),Ln=m.object({status:m.enum(["active","inactive","retired"]).optional(),limit:m.coerce.number().min(1).max(100).default(100),offset:m.coerce.number().min(0).default(0)}),qn=m.object({path:m.string().min(1)});async function Sr(o){o.get("/roles",{schema:{tags:["Roles"],summary:"List all roles",description:"List all roles with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",enum:["active","inactive","retired"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(e,t)=>{let s=Ln.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let{status:r,limit:n,offset:a}=s.data;return{roles:oe(r,n,a).map(d=>({...d,workspacePath:se(d.name)}))}}),o.post("/roles",{schema:{tags:["Roles"],summary:"Create a role",description:"Create a new role with a name, CAG prompt, and optional preferences.",body:{type:"object",required:["name"],properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let s=jn.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let{name:r,cagPrompt:n,learnedRules:a,allowedTools:i,disallowedTools:d,evaluationCriteria:c,executionMode:l,model:b,maxBudgetUsd:u,approvalRequired:y,preferences:w,additionalDirectories:v,allowedChannels:W,inheritUserSettings:T}=s.data;if(ht(r))return t.status(409).send({code:"CONFLICT",message:`Role with name '${r}' already exists`});let Q={id:`role-${kr().slice(0,8)}`,name:r,cagPrompt:n??"",learnedRules:a??[],memoryStreamId:`mem-${kr().slice(0,8)}`,status:"active",preferences:w??{},allowedTools:i,disallowedTools:d,evaluationCriteria:c,executionMode:l,model:b,maxBudgetUsd:u,approvalRequired:y,additionalDirectories:v,allowedChannels:W,inheritUserSettings:T,createdAt:Date.now()};return yt(Q),Te(Q),t.status(201).send({role:Q})}),o.get("/roles/:id",{schema:{tags:["Roles"],summary:"Get role by ID",description:"Retrieve a single role with its project-scope plugins.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=B(s.data.id);if(!r)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=se(r.name),a=fe({scope:"project",projectPath:n});return{role:r,projectPlugins:a,workspacePath:n}}),o.patch("/roles/:id",{schema:{tags:["Roles"],summary:"Update a role",description:"Partially update a role's CAG prompt, learned rules, status, or preferences.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},cagPrompt:{type:"string"},learnedRules:{type:"array",items:{type:"string"}},status:{type:"string",enum:["active","inactive","retired"]},preferences:{type:"object",properties:{model:{type:"string"},effort:{type:"string",enum:["low","medium","high","max"]},maxTurns:{type:"number"}}}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=Nn.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(r.error)});if(!B(s.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let{allowedChannels:a,...i}=r.data,d={...i,updatedAt:Date.now()};if(a!==void 0&&(d.allowedChannels=a??void 0),bt(s.data.id,d),r.data.cagPrompt!==void 0||r.data.learnedRules!==void 0){let l=B(s.data.id);if(l){let b=se(l.name);Ot(b)&&Rt(b,l)}}let c=B(s.data.id);if(c&&(r.data.allowedTools!==void 0||r.data.disallowedTools!==void 0)){let l=se(c.name);Ot(l)&&It(c.id,c.allowedTools,l)}return{role:c}}),o.delete("/roles/:id",{schema:{tags:["Roles"],summary:"Delete a role",description:"Delete a role and its workspace.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=B(s.data.id);if(!r)return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let n=se(r.name);if(Ot(n))try{Mn(n,{recursive:!0,force:!0})}catch{}return vt(s.data.id),{roleId:s.data.id,deleted:!0}}),o.post("/roles/:id/scan-directory",{schema:{tags:["Roles"],summary:"Scan directory for plugin/permission configuration",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",required:["path"],properties:{path:{type:"string",minLength:1}}}}},async(e,t)=>{let s=Qe.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(s.error)});let r=qn.safeParse(e.body);if(!r.success)return t.status(400).send({code:"VALIDATION_ERROR",message:m.prettifyError(r.error)});if(!B(s.data.id))return t.status(404).send({code:"NOT_FOUND",message:"Role not found"});let a=Ue(r.data.path);return{path:r.data.path,enabledPlugins:a.enabledPlugins,mcpServers:a.mcpServers,allowedTools:a.allowedTools,disallowedTools:a.disallowedTools}})}me();import{z as Pr}from"zod/v4";import{readdirSync as Bn,existsSync as Un}from"fs";import{join as Ft,resolve as Cr,sep as Ar}from"path";import{homedir as Wn}from"os";var Gn=20,Vn=Pr.object({prefix:Pr.string()});function Er(o){return o.startsWith("~/")?Ft(Wn(),o.slice(2)):o}function _r(o){let e=Cr(o);for(let t of zt){let s=Er(t),r=Cr(s);if(e===r||e.startsWith(r+Ar))return!0}return!1}async function xr(o){o.get("/fs/suggest-dirs",{schema:{tags:["FS"],summary:"Suggest directory completions",description:"Return directory suggestions matching a given path prefix.",querystring:{type:"object",required:["prefix"],properties:{prefix:{type:"string"}}}}},async(e,t)=>{let s=Vn.safeParse(e.query);if(!s.success)return{suggestions:[]};let{prefix:r}=s.data;if(!r.startsWith("/")&&!r.startsWith("~/"))return{suggestions:[]};if(_r(r))return{suggestions:[]};let n=Er(r),a,i;if(r.endsWith("/"))a=n,i="";else{let v=Math.max(n.lastIndexOf("/"),n.lastIndexOf(Ar));if(v<0)return{suggestions:[]};a=n.slice(0,v+1),i=n.slice(v+1)}if(!Un(a))return{suggestions:[]};let d;try{d=Bn(a,{withFileTypes:!0}).filter(v=>v.isDirectory()).map(v=>v.name)}catch{return{suggestions:[]}}let c=i.toLowerCase(),l=d.filter(v=>v.toLowerCase().startsWith(c)),y=(i.startsWith(".")?l:l.filter(v=>!v.startsWith("."))).filter(v=>!_r(Ft(a,v)));return y.sort((v,W)=>v.localeCompare(W,void 0,{sensitivity:"base"})),{suggestions:y.slice(0,Gn).map(v=>Ft(a,v))}})}import{z as K}from"zod/v4";ie();var $n=K.object({roleId:K.string().min(1)}),Hn=K.object({roleId:K.string().min(1),prompt:K.string().min(1),topK:K.number().min(1).max(50).default(10)}),zn=K.object({limit:K.coerce.number().min(1).max(200).default(50),offset:K.coerce.number().min(0).default(0)});function Dr(o){return B(o)!==void 0}async function Or(o){o.get("/memories/:roleId",{schema:{tags:["Memories"],summary:"List role memories",description:"List all memories for a specific role with pagination. Embeddings are stripped from the response.",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}},response:R.memoryList}},async(e,t)=>{let s=$n.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:K.prettifyError(s.error)});let r=s.data.roleId;if(!Dr(r))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let n=zn.safeParse(e.query),{limit:a,offset:i}=n.success?n.data:{limit:50,offset:0},c=ys(r,a,i).map(({embedding:l,...b})=>b);return{memories:c,count:c.length}}),o.post("/memories/query",{schema:{tags:["Memories"],summary:"Query role memories",description:"Query a role's memories using hybrid search (FTS5 + vector similarity) with Smallville-style scoring (recency, importance, relevance).",body:{type:"object",required:["roleId","prompt"],properties:{roleId:{type:"string",minLength:1,description:"The role whose memories to query"},prompt:{type:"string",minLength:1,description:"The search query"},topK:{type:"integer",minimum:1,maximum:50,default:10,description:"Number of results to return"}}},response:R.memoryQuery}},async(e,t)=>{let s=Hn.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:K.prettifyError(s.error)});let{roleId:r,prompt:n,topK:a}=s.data;if(!Dr(r))return t.status(404).send({code:"NOT_FOUND",message:"Role or agent not found"});let d=(await bs(r,n,{topK:a})).map(({embedding:c,...l})=>l);return{memories:d,count:d.length}})}ie();import{v4 as be}from"uuid";import{CronExpressionParser as Jn}from"cron-parser";import{v4 as Kn}from"uuid";var Ce=E("scheduler"),Ye=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let s=ge(),r=e.config?.fileAccess,n={timeout:e.config?.timeout??s.timeout,approvalRequired:s.approvalRequired,approvalTimeout:s.approvalTimeout,fileAccess:{allowedPaths:[...s.fileAccess.allowedPaths,...r?.allowedPaths??[]],deniedPaths:[...s.fileAccess.deniedPaths,...r?.deniedPaths??[]]},plugins:e.config?.plugins,mcpServers:e.config?.mcpServers,model:e.config?.model??s.model,maxTurns:e.config?.maxTurns??s.maxTurns,maxBudgetUsd:e.config?.maxBudgetUsd??s.maxBudgetUsd,env:{...s.env,...e.config?.env},claudeCodePath:s.claudeCodePath},a={templateId:e.id,executionId:t,stepResults:new Map,config:n},i=this.sortSteps(e.steps);for(let d of i){try{await this.executeStep(d,a)}catch(l){Ce.error({stepId:d.id,error:l},"Workflow step failed");break}if(a.stepResults.get(d.id)?.status==="failed"){Ce.warn({stepId:d.id},"Workflow step failed, workflow aborted");break}}Ce.info({executionId:t,completedSteps:a.stepResults.size,totalSteps:i.length},"Workflow completed")}sortSteps(e){let t=new Set,s=[],r=new Map(e.map(a=>[a.id,a])),n=a=>{if(!t.has(a.id)){if(t.add(a.id),a.dependsOn)for(let i of a.dependsOn){let d=r.get(i);d&&n(d)}s.push(a)}};for(let a of e)n(a);return s}async executeStep(e,t){let s=this.resolveVariables(e.prompt,t.stepResults),r=Kn();ae({id:r,status:"pending",prompt:s,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId}),Ce.debug({stepId:e.id,taskId:r},"Created workflow step as task"),g.emit({type:"task_created",taskId:r});let n=await this.executeWithRetry(r,e.id),a=A(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:n==="completed"?"completed":"failed",result:a?.result,error:a?.error})}resolveVariables(e,t){return e.replace(/\{\{([^}]+)\.result\}\}/g,(s,r)=>t.get(r)?.result??`[no result from ${r}]`)}async executeWithRetry(e,t){let s=0;for(;s<this.maxRetries;){if(s++,await this.waitForTaskCompletion(e)==="completed")return"completed";if(s<this.maxRetries){let n=this.baseDelayMs*Math.pow(2,s-1);Ce.info({stepId:t,attempt:s,maxRetries:this.maxRetries,delayMs:n},"Workflow step failed, retrying"),await this.sleep(n)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(s=>{let r=Date.now(),n=()=>{if(Date.now()-r>t){s("failed");return}let a=A(e);if(!a){s("failed");return}if(a.status==="completed"){s("completed");return}if(a.status==="failed"||a.status==="cancelled"){s("failed");return}setTimeout(n,500)};n()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var O=E("scheduler"),Xe="ai-hourly-digest";function Qn(){if(U(Xe)){O.debug({templateId:Xe},"Built-in template already exists");return}let e={id:Xe,name:"AI Hourly Digest",description:"\u6BCF\u5C0F\u65F6\u641C\u7D22 AI \u524D\u6CBF\u6587\u7AE0\uFF0C\u603B\u7ED3\u540E\u4FDD\u5B58\u5230 Omnifocus",trigger:{type:"cron",cron:"0 * * * *"},enabled:!0,steps:[{id:"search_ai_news",prompt:`\u641C\u7D22\u8FC7\u53BB 24 \u5C0F\u65F6\u5185\u5173\u4E8E AI/\u4EBA\u5DE5\u667A\u80FD\u7684\u6700\u65B0\u524D\u6CBF\u6587\u7AE0\u3002
|
|
3
|
+
|
|
4
|
+
\u641C\u7D22\u6765\u6E90:
|
|
5
|
+
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
6
|
+
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
7
|
+
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
8
|
+
|
|
9
|
+
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
10
|
+
|
|
11
|
+
\u8F93\u51FA\u683C\u5F0F:
|
|
12
|
+
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
13
|
+
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
14
|
+
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
15
|
+
- \u6838\u5FC3\u4EF7\u503C\uFF1A[1-2 \u53E5\u8BDD\u8BF4\u660E\u4E3A\u4EC0\u4E48\u8FD9\u7BC7\u6587\u7AE0\u503C\u5F97\u770B]`},{id:"summarize_article",dependsOn:["search_ai_news"],prompt:`\u9605\u8BFB\u5E76\u603B\u7ED3\u8FD9\u7BC7\u6587\u7AE0\u3002
|
|
16
|
+
|
|
17
|
+
\u6587\u7AE0\u4FE1\u606F:
|
|
18
|
+
{{search_ai_news.result}}
|
|
19
|
+
|
|
20
|
+
\u8BF7:
|
|
21
|
+
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
22
|
+
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
23
|
+
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
24
|
+
|
|
25
|
+
\u603B\u7ED3\u7ED3\u6784:
|
|
26
|
+
## \u6838\u5FC3\u53D1\u73B0
|
|
27
|
+
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
28
|
+
|
|
29
|
+
## \u6280\u672F\u7EC6\u8282
|
|
30
|
+
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
31
|
+
|
|
32
|
+
## \u5F71\u54CD/\u610F\u4E49
|
|
33
|
+
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
34
|
+
|
|
35
|
+
## \u539F\u6587\u94FE\u63A5
|
|
36
|
+
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
37
|
+
|
|
38
|
+
\u603B\u7ED3\u5185\u5BB9:
|
|
39
|
+
{{summarize_article.result}}
|
|
40
|
+
|
|
41
|
+
\u63D0\u53D6\u6587\u7AE0\u6807\u9898\u548C\u5B8C\u6574\u603B\u7ED3\uFF0C\u7136\u540E\u6267\u884C\u4EE5\u4E0B\u547D\u4EE4\u6DFB\u52A0\u5230 Omnifocus Inbox\uFF1A
|
|
42
|
+
|
|
43
|
+
osascript /Users/norvyn/Code/Projects/Adam/scripts/add-to-omnifocus.applescript "[\u6587\u7AE0\u6807\u9898] AI \u524D\u6CBF\u901F\u9012" "[\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9]"
|
|
44
|
+
|
|
45
|
+
\u6CE8\u610F\uFF1A
|
|
46
|
+
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
47
|
+
- \u5C06 [\u5B8C\u6574\u603B\u7ED3\u5185\u5BB9] \u66FF\u6362\u4E3A\u5B8C\u6574\u7684\u603B\u7ED3\u6587\u672C\uFF08\u5305\u542B\u6838\u5FC3\u53D1\u73B0\u3001\u6280\u672F\u7EC6\u8282\u3001\u5F71\u54CD/\u610F\u4E49\u548C\u539F\u6587\u94FE\u63A5\uFF09
|
|
48
|
+
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
49
|
+
|
|
50
|
+
\u5B8C\u6210\u540E\u8F93\u51FA\uFF1A\u5DF2\u4FDD\u5B58\u5230 Omnifocus\uFF1A[\u4EFB\u52A1\u6807\u9898]`}],config:{timeout:300,fileAccess:{allowedPaths:["~/.adam/","/Users/norvyn/Code/Projects/Adam/scripts/"],deniedPaths:[]}},tags:["ai","digest","hourly","automation"],createdAt:Date.now()};We(e),O.info({templateId:Xe,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var Ze=class{cronJobs=new Map;workflowExecutor=new Ye;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,Qn();let e=we(!0),t=0;for(let s of e)s.trigger.type==="cron"&&s.trigger.cron&&(this.scheduleCronJob(s),t++);this.taskCompletionHandler=s=>{s.newStatus==="completed"&&this.checkEventTriggers(s.taskId).catch(r=>{O.error({taskId:s.taskId,error:r},"Event trigger check failed")})},g.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),O.info({cronCount:t},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=oe(void 0,1e3,0),t=0;for(let s of e)t+=hs(s.id);t>0&&O.info({totalCleaned:t},"Memory cleanup completed")}catch(e){O.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(g.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,O.info("Bree engine stopped")}scheduleCronJob(e){let t=`template-${e.id}`;this.cronJobs.has(t)&&(clearTimeout(this.cronJobs.get(t)),this.cronJobs.delete(t));let s;try{s=Jn.parse(e.trigger.cron)}catch{O.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let c=s.next().getTime()-Date.now();return Math.max(c,1e3)},n=()=>{this.executeCronTrigger(e.id).catch(c=>{O.error({templateId:e.id,error:c},"Cron trigger failed")});let d=setTimeout(n,r());this.cronJobs.set(t,d)},a=r(),i=setTimeout(n,a);this.cronJobs.set(t,i),O.debug({jobName:t,nextRun:new Date(Date.now()+a).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=U(e);!t||!t.enabled||(O.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,be()))}async scheduleJob(e){let t=U(e);t&&t.trigger.type==="cron"&&t.trigger.cron&&this.scheduleCronJob(t)}async unscheduleJob(e){let t=`template-${e}`,s=this.cronJobs.get(t);s&&(clearTimeout(s),this.cronJobs.delete(t))}async runNow(e){let t=U(e);if(!t)throw new Error(`Template ${e} not found`);let s=be();return this.executeWorkflow(t,s).catch(r=>{O.error({templateId:e,error:r},"Workflow execution failed")}),s}async checkEventTriggers(e){let t=A(e);if(!t)return;let s=we(!0),r=s.filter(n=>n.trigger.type==="event"&&n.trigger.event==="task_complete");for(let n of r)O.debug({templateName:n.name},"Event trigger matched"),await this.executeWorkflow(n,be());if(t.templateId){let n=s.filter(a=>a.trigger.type!=="event"||!a.trigger.event?!1:a.trigger.event===`template_complete:${t.templateId}`);for(let a of n)O.info({templateName:a.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(a,be())}}async executeWorkflow(e,t){if(O.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let s of e.goalIds){let r=re(s);if(!r){O.warn({goalId:s,templateId:e.id},"Goal reference not found, skipping");continue}let n=be();ks({id:n,name:r.name,description:r.description,roleId:r.roleId,metricType:r.metricType,targetValue:r.targetValue,currentValue:0,deadline:r.deadline,budgetUsd:r.budgetUsd,status:"active",createdAt:Date.now(),sourceSessionId:e.sourceSessionId,notifyTargets:e.notifyTargets});let a=be();ae({id:a,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:n,config:ge(),createdAt:Date.now(),templateId:e.id}),g.emit({type:"task_created",taskId:a}),O.info({templateId:e.id,sourceGoalId:s,newGoalId:n,taskId:a},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}};import{query as Zn}from"@anthropic-ai/claude-agent-sdk";import{v4 as ne}from"uuid";on();me();var Yn=new Set(["Read","Glob","Grep","LSP"]),Xn=new Set(["Edit","Write","NotebookEdit"]);function _e(o,e){return async(t,s,{agentID:r})=>{if(Yn.has(t))return{behavior:"allow",updatedInput:s};let n=o(r??"");if(Xn.has(t)){let a=Zt(t,s),i=q;if(a.length===0)return{behavior:"allow",updatedInput:s};let d={allowedPaths:n?.allowedPaths??[],deniedPaths:n?.deniedPaths??[]};for(let c of a){let l=es(c,i,d);if(!l.allowed)return{behavior:"deny",message:`Path denied: ${l.reason}. Try an alternative within allowed paths.`}}return{behavior:"allow",updatedInput:s}}if(n?.disallowedTools?.includes(t))return{behavior:"deny",message:`Tool ${t} is not allowed for this role.`};if(e&&n?.approvalRequired?.length){let a=t==="Bash"?s.command??"":`${t} ${JSON.stringify(s)}`;for(let i of n.approvalRequired)try{if(new RegExp(i).test(a))return await e(t,s,i,r)}catch{}}return{behavior:"allow",updatedInput:s}}}function Ae(o){return{SubagentStart:[{hooks:[async e=>{let t=o.roleId??e.agent_id;if(!t)return{};try{let s=await vs("role startup context",t,5);if(s)return{hookSpecificOutput:{hookEventName:"SubagentStart",additionalContext:s}}}catch{}return{}}]}],SubagentStop:[{hooks:[async e=>{let t=e.agent_id;if(!t||!o.currentTaskId)return{};try{let{createMemory:s}=await import("./memories-BUNOVQVG.js"),r=e.transcript;if(r&&r.length>100){let n=r.slice(0,500);s({id:`session-${Date.now()}`,roleId:o.roleId??t,type:"event",content:n,keywords:[],importance:3,sourceType:"task_complete",sourceTaskId:o.currentTaskId,createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0})}}catch{}return{}}]}],PostToolUse:[{hooks:[async e=>{if(!o.currentTaskId)return{};let t=e.tool_name,s=e.tool_input,r=e.tool_response,n=typeof r=="string"?r:JSON.stringify(r??"");try{gt({id:`step-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,taskId:o.currentTaskId,index:0,type:"tool_call",content:`${t}: ${JSON.stringify(s??{})} \u2192 ${n.slice(0,200)}`,toolName:t,toolInput:s,toolOutput:n,timestamp:Date.now()})}catch{}return{}}]}],PreCompact:[{hooks:[async e=>{let t=e.compact_summary;if(!t)return{};try{let{createMemory:s}=await import("./memories-BUNOVQVG.js");s({id:`compact-${Date.now()}`,roleId:o.roleId??"role-chat-manager",type:"thought",content:t.slice(0,500),keywords:["manager","decision","compaction"],importance:4,sourceType:"pre_compact",createdAt:Date.now(),lastAccessed:Date.now(),retrievedCount:0})}catch{}return{}}]}]}}function Mt(o){return`# ChatManager \u2014 User Interface Agent
|
|
51
|
+
|
|
52
|
+
You are the primary interface between the user and the goal-driven autonomous system.
|
|
53
|
+
You have access to a persistent conversation session and the adam-tools MCP server.
|
|
54
|
+
|
|
55
|
+
## Your Role
|
|
56
|
+
- You are an ORCHESTRATOR, not a worker. You manage goals, tasks, and templates via adam-tools MCP.
|
|
57
|
+
- Answer user questions directly when no tool calls are needed (e.g., "how many tasks are running?" \u2192 read state and answer)
|
|
58
|
+
- For ANY work request (search, analysis, writing, coding, weather lookup, etc.) \u2192 use dispatch_task to delegate to ExecutionPool
|
|
59
|
+
- You can read the codebase (Read, Grep) but you CANNOT search the web, run code, or edit files
|
|
60
|
+
- You do NOT have WebSearch, WebFetch, Bash, Edit, or Write tools \u2014 only dispatch_task and other adam-tools
|
|
61
|
+
- Keep task results in your conversation context so you can report them coherently
|
|
62
|
+
|
|
63
|
+
## Core Capabilities
|
|
64
|
+
Adam is a goal-driven autonomous AI task platform:
|
|
65
|
+
- **Task dispatch**: delegate work to specialized Role workers (web search, coding, analysis, browser automation, etc.)
|
|
66
|
+
- **Goal management**: SMART goals with budget, deadline, metric tracking; auto-decomposition
|
|
67
|
+
- **Role system**: multiple worker identities with different tools, learned rules, performance scoring
|
|
68
|
+
- **Scheduling**: cron recurring templates + one-shot delayed tasks
|
|
69
|
+
- **Channel messaging**: send/receive via connected platforms (WeChat, Telegram, etc.)
|
|
70
|
+
- **Memory**: per-Role searchable memory for cross-task context
|
|
71
|
+
- **Strategy evolution**: Thompson Sampling optimizes approaches over time
|
|
72
|
+
- **Plugin/MCP**: dynamically bind extensions and tool servers to roles
|
|
73
|
+
- **Monitor**: automatic quality scoring, retirement/reinstatement
|
|
74
|
+
- **Delivery**: event-driven result routing to channels/webhooks
|
|
75
|
+
|
|
76
|
+
When the user asks what you can do or asks for help, call **get_capabilities** to get a live snapshot of roles, channels, plugins, automations, and execution capacity, then answer based on the actual system state.
|
|
77
|
+
|
|
78
|
+
## Current Context
|
|
79
|
+
- Time: ${new Date(o.currentTime).toISOString()}
|
|
80
|
+
|
|
81
|
+
## Decision Principles
|
|
82
|
+
- Answer simple questions directly from state (no task needed)
|
|
83
|
+
- For ANY work request that needs external data (weather, news, web content, file operations, code execution): ALWAYS use dispatch_task. Do NOT tell the user "I can't do this" \u2014 dispatch_task delegates to workers that CAN do it.
|
|
84
|
+
- Never block waiting for task completion \u2014 respond immediately and update later
|
|
85
|
+
- When a task completes, the system will inject the result into your session context
|
|
86
|
+
- NEVER say "I don't have the ability to..." \u2014 use dispatch_task instead. The workers have WebSearch, WebFetch, Bash, and all standard tools.
|
|
87
|
+
- When a task completes and the user previously asked to send results to a channel \u2192 use send_to_channel(channelName, result) to deliver
|
|
88
|
+
- **Role selection**: Before dispatching, call list_roles to discover available roles and their capabilities (allowedTools). Pass the matching role's id as roleId to dispatch_task. Never dispatch without a roleId unless no role matches the task.
|
|
89
|
+
|
|
90
|
+
## Decision Patterns
|
|
91
|
+
- Simple task request \u2192 list_roles \u2192 pick best role \u2192 dispatch_task with roleId
|
|
92
|
+
- Complex multi-step request \u2192 create_goal \u2192 decompose_goal
|
|
93
|
+
- Recurring/scheduled request ("every day", "weekly", "\u6BCF\u5C0F\u65F6") \u2192 create_template with cron
|
|
94
|
+
- One-shot delayed request ("\u534A\u5C0F\u65F6\u540E", "in 30 minutes", "\u660E\u59293\u70B9") \u2192 schedule_task
|
|
95
|
+
- Check system capacity \u2192 get_system_status
|
|
96
|
+
- Send to channel \u2192 list_channels to find target \u2192 send_to_channel
|
|
97
|
+
- Deliver task output to a specific channel \u2192 pass deliverTo in dispatch_task or schedule_task (use list_channels to get channel info)
|
|
98
|
+
- Send status report to a different channel than output \u2192 pass reportTo (defaults to originating channel/session if omitted)
|
|
99
|
+
- Check goal/task progress \u2192 list_goals / read_task_status
|
|
100
|
+
- **Create new role**: When the user asks to create a role with specific capabilities (e.g., "\u80FD\u8BBF\u95EE\u7F51\u7EDC"), pass the required tools in allowedTools (e.g., ["WebSearch", "WebFetch"]). Without allowedTools, the role has no tool permissions and cannot execute tasks that need those tools.
|
|
101
|
+
|
|
102
|
+
## Conversation Coherence
|
|
103
|
+
When task completion notifications arrive, incorporate the results naturally into your conversation.
|
|
104
|
+
For example, if the user asked "run a report" and Task xyz completed, summarize the result for the user.
|
|
105
|
+
`}me();var F=E("chat-manager"),ea=q,Ee=class{sessionId;adamToolsInstance=null;running=!1;processing=!1;messageQueue=[];lastActivityAt=Date.now();consecutiveStaleCount=0;subscribed=!1;activeChatSessionId;activeChatSource;taskOriginMap=new Map;taskNotifyMap=new Map;constructor(e){this.sessionId=e}async start(){this.running||(this.running=!0,this.subscribeToEvents(),F.info("ChatManager started"))}stop(){this.running=!1,F.info("ChatManager stopped")}async handleMessage(e,t,s){return new Promise((r,n)=>{this.messageQueue.push({content:e,resolve:a=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,r(a)},reject:a=>{this.activeChatSessionId=void 0,this.activeChatSource=void 0,n(a)}}),this.activeChatSessionId=t,this.activeChatSource=s,this.processQueue()})}async processQueue(){if(this.processing||!this.running)return;let e=this.messageQueue.shift();if(e){this.processing=!0;try{let t=await this.runQuery(e.content);e.resolve(t)}catch(t){e.reject(t instanceof Error?t:new Error(String(t)))}finally{this.processing=!1,this.processQueue()}}}async runQuery(e){let t=Mt({currentTime:Date.now()});this.adamToolsInstance||(this.adamToolsInstance=Ct());let s=Ae({currentTaskId:void 0,roleId:"role-chat-manager"}),r=_e(d=>({disallowedTools:["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"]}));F.debug({hasApiKey:!!process.env.ANTHROPIC_API_KEY,hasResume:!!this.sessionId},"ChatManager SDK query starting");let n=["WebSearch","WebFetch","Bash","Edit","Write","NotebookEdit"],a=Zn({prompt:e,options:{cwd:ea,additionalDirectories:[process.cwd()],systemPrompt:t,resume:this.sessionId,maxTurns:50,maxBudgetUsd:5,disallowedTools:n,settingSources:["project"],mcpServers:{"adam-tools":this.adamToolsInstance},hooks:s,canUseTool:r,env:{...process.env,DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1",DISABLE_AUTO_COMPACT:"1",DISABLE_COMPACT:"1",ANTHROPIC_SMALL_FAST_MODEL:process.env.ANTHROPIC_MODEL??""},stderr:d=>{d.trim()&&F.debug({stderr:d.trim().slice(0,500)},"ChatManager SDK stderr")}}}),i="";for await(let d of a){let c=d;F.debug({eventType:c.type,subtype:c.subtype},"ChatManager SDK event"),this.lastActivityAt=Date.now(),this.consecutiveStaleCount=0,c.session_id&&typeof c.session_id=="string"&&(this.sessionId=c.session_id,Dt(this.sessionId)),c.type==="result"&&typeof c.result=="string"&&(i=c.result)}return i}subscribeToEvents(){this.subscribed||(this.subscribed=!0,g.on("task_created",e=>{this.activeChatSessionId&&this.activeChatSource&&($(e.taskId,{sourceSessionId:this.activeChatSessionId}),this.taskOriginMap.set(e.taskId,{chatSessionId:this.activeChatSessionId,source:this.activeChatSource,createdAt:Date.now()}),F.debug({taskId:e.taskId,chatSessionId:this.activeChatSessionId},"Tracked task origin for result delivery"));let t=A(e.taskId);if(t?.parentId){let s=this.taskOriginMap.get(t.parentId),r=s?void 0:A(t.parentId),n=s?.chatSessionId??r?.sourceSessionId;n&&($(e.taskId,{sourceSessionId:n}),s&&this.taskOriginMap.set(e.taskId,{...s}))}}),g.on("task_complete_event",e=>{this.handleTaskCompletion(e.taskId,e.result,e.error)}),setInterval(()=>{let e=Date.now()-864e5;for(let[t,s]of this.taskOriginMap)s.createdAt<e&&this.taskOriginMap.delete(t)},3600*1e3))}async handleTaskCompletion(e,t,s){let r=A(e),n=this.taskOriginMap.get(e);if(!n&&r?.sourceSessionId){let u=H(r.sourceSessionId);u&&(n={chatSessionId:u.id,source:u.source,createdAt:r.createdAt})}let a=r?.roleId?await this.getRoleName(r.roleId):void 0,i=a?`${a}`:e.slice(0,8),d=s?"\u274C":"\u2705",c=s?`\u4EFB\u52A1\u5931\u8D25: ${s.slice(0,200)}`:(t??"").slice(0,500),l=`${d} \u4EFB\u52A1\u5B8C\u6210 (${i})
|
|
106
|
+
|
|
107
|
+
${c}`;if(this.sessionId){let u=`[System notification] Task ${e} ${s?"failed":"completed"}. Result:
|
|
108
|
+
${(s??t??"").slice(0,500)}`;this.messageQueue.push({content:u,resolve:y=>{if(y&&y.trim()&&n){let w={id:ne(),sessionId:n.chatSessionId,role:"assistant",content:y,source:n.source,taskId:e,createdAt:Date.now()};X(w),g.emit({type:"chat_message",sessionId:n.chatSessionId,message:w}),Z(n.chatSessionId)}},reject:()=>{}}),this.processQueue()}if(n){let u={id:ne(),sessionId:n.chatSessionId,role:"assistant",content:l,source:n.source,taskId:e,createdAt:Date.now()};try{X(u),g.emit({type:"chat_message",sessionId:n.chatSessionId,message:u}),Z(n.chatSessionId),Se(n.chatSessionId),F.info({taskId:e,chatSessionId:n.chatSessionId,sourceType:n.source.type},"Task result delivered to chat session"),n.source.type==="channel"&&n.source.channelId&&n.source.chatId&&this.deliverToChannel(n.source.channelId,n.source.chatId,l)}catch(y){F.error({error:y,taskId:e},"Failed to deliver task result to chat session")}this.taskOriginMap.delete(e)}else F.debug({taskId:e},"Task completed but no chat session origin tracked (may be API-created or template-triggered)");let b=async(u,y)=>{try{let w=H(u);if(!w)return;X({id:ne(),sessionId:u,role:"assistant",content:y,source:w.source,taskId:e,createdAt:Date.now()}),Z(u),g.emit({type:"chat_message",sessionId:u,message:{id:ne(),sessionId:u,role:"assistant",content:y,source:w.source,createdAt:Date.now()}})}catch(w){F.error({error:w,taskId:e,targetSession:u},"Failed to deliver to session")}};if(r?.reportTo&&r.reportTo.length>0)for(let u of r.reportTo)u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,l):u.type==="session"&&u.sessionId&&await b(u.sessionId,l);else n?.source.type==="channel"&&n.source.channelId&&n.source.chatId&&this.deliverToChannel(n.source.channelId,n.source.chatId,l);if(r?.deliverTo&&r.deliverTo.length>0)for(let u of r.deliverTo){let y=s?`\u4EFB\u52A1\u5931\u8D25: ${(s??"").slice(0,200)}`:t??"";u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,y):u.type==="session"&&u.sessionId&&await b(u.sessionId,y)}if(!r?.deliverTo&&r?.notifyTargets&&r.notifyTargets.length>0)for(let u of r.notifyTargets)u.type==="channel"&&u.channelId&&u.chatId?this.deliverToChannel(u.channelId,u.chatId,l):u.type==="session"&&u.sessionId&&await b(u.sessionId,l);if(r?.parentId){let u=re(r.parentId);if(u){let y=Xt(r.parentId);if(y.every(v=>v.status==="completed"||v.status==="failed")){let v=y.some(te=>te.status==="failed"),W=v?"failed":"completed";Ge(r.parentId,{status:W,updatedAt:Date.now()}),F.info({goalId:r.parentId,goalName:u.name,finalStatus:W},"Goal completed");let T=`${v?"\u274C":"\u2705"} \u76EE\u6807\u5B8C\u6210: ${u.name}
|
|
109
|
+
|
|
110
|
+
${y.length} \u4E2A\u5B50\u4EFB\u52A1\u5168\u90E8\u5B8C\u6210`;await this.routeGoalNotification(u,T,r.parentId)}}}}async getRoleName(e){try{let{getRole:t}=await import("./roles-CMV5FMIA.js");return t(e)?.name}catch{return}}async deliverToChannel(e,t,s){if(!e||!t){F.warn({channelId:e,chatId:t},"Cannot deliver to channel: missing channelId or chatId");return}try{let{getChannelManager:r}=await import("./channels-CNLMTKHM.js"),n=r();n&&(await n.sendMessage(e,t,{content:s}),F.info({channelId:e,chatId:t.slice(0,12)},"Delivered notification to channel"))}catch(r){F.error({error:r,channelId:e,chatId:t.slice(0,12)},"Failed to deliver to channel")}}async routeGoalNotification(e,t,s){let r=e.deliverTo??e.notifyTargets??[],n=e.sourceSessionId;if(!(r.length===0&&!n)){for(let a of r)if(a.type==="session")try{let i=H(a.sessionId);i&&(X({id:ne(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}),Z(a.sessionId),g.emit({type:"chat_message",sessionId:a.sessionId,message:{id:ne(),sessionId:a.sessionId,role:"assistant",content:t,source:i.source,createdAt:Date.now()}}))}catch(i){F.error({error:i,goalId:s,targetSession:a.sessionId},"Failed to deliver Goal notification to session")}else a.type==="channel"&&await this.deliverToChannel(a.channelId,a.chatId??"",t);if(n&&!r.some(a=>a.type==="session"&&a.sessionId===n))try{let a=H(n);a&&(X({id:ne(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}),Z(n),g.emit({type:"chat_message",sessionId:n,message:{id:ne(),sessionId:n,role:"assistant",content:t,source:a.source,createdAt:Date.now()}}))}catch(a){F.error({error:a,goalId:s,sessionId:n},"Failed to deliver Goal notification to source session")}}}getLastActivityAt(){return this.lastActivityAt}getConsecutiveStaleCount(){return this.consecutiveStaleCount}isHealthy(){return this.running}async restartSession(){F.warn("Restarting ChatManager session (Watchdog triggered)"),this.consecutiveStaleCount++,this.sessionId=void 0,Dt(void 0)}};import{query as na}from"@anthropic-ai/claude-agent-sdk";import{v4 as aa}from"uuid";function jt(o){let e=o.roleName?`## Role Context
|
|
111
|
+
- Role: ${o.roleName}
|
|
112
|
+
${o.roleCagPrompt?`- CAG Prompt: ${o.roleCagPrompt.slice(0,200)}`:""}`:"",t=o.allowedTools&&o.allowedTools.length>0?`## Available Tools
|
|
113
|
+
You have access to: ${o.allowedTools.join(", ")}. Use them as needed to complete the task.`:"";return`# Execution Agent \u2014 Task Focus
|
|
114
|
+
|
|
115
|
+
You are executing a specific task assigned to you. Your job is to complete the work, not manage goals or strategies.
|
|
116
|
+
|
|
117
|
+
## Task
|
|
118
|
+
- Task ID: ${o.taskId}
|
|
119
|
+
- Prompt: ${o.prompt}
|
|
120
|
+
|
|
121
|
+
${e}
|
|
122
|
+
|
|
123
|
+
${t}
|
|
124
|
+
|
|
125
|
+
## Focus
|
|
126
|
+
- Focus entirely on completing the task
|
|
127
|
+
- Use the standard SDK tools to do the work
|
|
128
|
+
- Do NOT attempt strategic decisions \u2014 just execute
|
|
129
|
+
|
|
130
|
+
## Constraints
|
|
131
|
+
- You have standard SDK tools only (no adam-tools MCP)
|
|
132
|
+
- Stay within your assigned permissions and allowed paths
|
|
133
|
+
- Report completion with a clear result summary
|
|
134
|
+
- If WebSearch or WebFetch fails (network error, invalid params), report the failure honestly \u2014 do not fabricate data
|
|
135
|
+
- If a tool is unavailable, state it clearly in the result rather than guessing
|
|
136
|
+
`}ie();kt();me();ke();import{randomUUID as ta}from"crypto";function Mr(o,e,t){let r=j().prepare(`
|
|
137
|
+
INSERT INTO task_plugins (id, task_id, plugin_path, plugin_name, role_id, used_at)
|
|
138
|
+
VALUES (?, ?, ?, ?, ?, ?)
|
|
139
|
+
`),n=Date.now();for(let a of e){let i=a.split("/").pop()??a;r.run(ta(),o,a,i,t??null,n)}}function jr(o){return j().prepare(`
|
|
140
|
+
SELECT plugin_name as pluginName, COUNT(*) as usageCount
|
|
141
|
+
FROM task_plugins
|
|
142
|
+
WHERE role_id = ?
|
|
143
|
+
GROUP BY plugin_path
|
|
144
|
+
ORDER BY usageCount DESC
|
|
145
|
+
`).all(o)}function Nr(o=50){return j().prepare(`
|
|
146
|
+
SELECT plugin_path as pluginPath, plugin_name as pluginName, COUNT(*) as usageCount, MAX(used_at) as lastUsed
|
|
147
|
+
FROM task_plugins
|
|
148
|
+
GROUP BY plugin_path
|
|
149
|
+
ORDER BY usageCount DESC
|
|
150
|
+
LIMIT ?
|
|
151
|
+
`).all(o)}ie();import{createSdkMcpServer as sa,tool as Lr}from"@anthropic-ai/claude-agent-sdk";import{z as qr}from"zod";async function ra(o){let{listChannels:e}=await import("./channels-VNG7U6UQ.js"),t=e(),{listSessions:s}=await import("./session-manager-KO4CR3W6.js"),r=[...s("active"),...s("archived")],n=t.find(d=>d.name.toLowerCase().includes(o.toLowerCase()));if(!n)return null;let i=r.find(d=>d.source.type==="channel"&&d.source.channelId===n.id&&d.source.chatId)?.source.chatId??n.config?.userId??"";return{channelId:n.id,chatId:i}}function ve(o){return{content:[{type:"text",text:JSON.stringify(o)}]}}function Br(o){let e=o?B(o):void 0,t=[Lr("list_channels","List all available channels. Use this to discover what channels can be used with send_to_channel.",{},async()=>{let{listChannels:s}=await import("./channels-VNG7U6UQ.js"),r=s();return ve({channels:r.map(n=>({id:n.id,name:n.name,enabled:n.enabled,type:n.config?.type??"unknown"}))})}),Lr("send_to_channel","Send a message to a connected channel by name. This role can only send to channels in its allowedChannels list (if configured).",{channelName:qr.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:qr.string().describe("The message content to send")},async s=>{if(e?.allowedChannels!==void 0){if(e.allowedChannels.length===0)return ve({error:"This role is not allowed to send to any channels"});if(!e.allowedChannels.some(c=>c.toLowerCase()===s.channelName.toLowerCase()))return ve({error:`Channel "${s.channelName}" is not in the allowed channels list for this role`})}let r=await ra(s.channelName);if(!r)return ve({error:`Channel "${s.channelName}" not found or has no chatId available`});let{getChannelManager:n}=await import("./channels-CNLMTKHM.js"),a=n();if(!a)return ve({error:"ChannelManager not available"});let i=await a.sendMessage(r.channelId,r.chatId,{content:s.message});return ve({success:!!i,channelName:s.channelName})})];return sa({name:"execution-tools",version:"1.0.0",tools:t})}St();var J=E("execution"),xe=class{async execute(e,t){let s=Date.now(),r,n,a;$(e.id,{status:"running",startedAt:Date.now()}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:e.status,newStatus:"running"}),J.info({taskId:e.id,roleId:e.roleId},"ExecutionManager: starting task");try{let i=e.roleId?B(e.roleId):void 0,d=q;i&&(Te(i),d=se(i.name));let c={taskId:e.id,prompt:e.prompt,roleName:i?.name,roleCagPrompt:i?.cagPrompt,allowedTools:i?.allowedTools},l=jt(c),b=Ae({currentTaskId:e.id,roleId:e.roleId}),u=e.config.approvalTimeout??300,w=i?.preferences?.permissions,W=_e(P=>({allowedPaths:w?.allowedPaths,deniedPaths:w?.deniedPaths,disallowedTools:i?.disallowedTools,approvalRequired:i?.approvalRequired??e.config.approvalRequired}),async(P,x,V,Le)=>{let M=aa(),Gt=os(Le??e.roleId,e.prompt,"medium");if(Gt)return J.info({operationId:M,ruleId:Gt.id,taskId:e.id},"Auto-approved by permanent rule"),{behavior:"allow",updatedInput:x};let Vt={steps:[{index:0,description:`${P}: ${JSON.stringify(x).slice(0,300)}`,toolsNeeded:[P],expectedOutput:"",riskLevel:"medium"}],requiredPermissions:{},overallRisk:"medium"};return rs({id:M,taskId:e.id,roleId:Le??e.roleId,plan:Vt,status:"pending",createdAt:Date.now()}),g.emit({type:"plan_approval_request",taskId:e.id,planId:M,plan:Vt}),J.info({taskId:e.id,operationId:M,toolName:P,matchedPattern:V},"Privilege escalation: awaiting user decision"),new Promise(lt=>{let nn=setTimeout(()=>{Ht(),as(M,"denied"),J.warn({taskId:e.id,operationId:M},"Privilege escalation timed out, auto-denied"),lt({behavior:"deny",message:`Operation timed out after ${u}s. Auto-denied. Try a safer alternative that does not require approval.`})},u*1e3),$t=ue=>{if(ue.planId===M)if(Ht(),ue.decision==="allow")J.info({taskId:e.id,operationId:M,approvalType:ue.approvalType},"Operation authorized by user"),lt({behavior:"allow",updatedInput:x});else{let an=ue.reason?`Operation denied by user: ${ue.reason}. Try a safer alternative.`:"Operation denied by user. Try a safer alternative approach.";J.info({taskId:e.id,operationId:M,reason:ue.reason??"no reason given"},"Operation denied by user"),lt({behavior:"deny",message:an})}},Ht=()=>{clearTimeout(nn),g.off("plan_approval_decision",$t)};g.on("plan_approval_decision",$t)})}),T={...process.env,DISABLE_TELEMETRY:"1",DISABLE_ERROR_REPORTING:"1",CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC:"1",DISABLE_AUTOUPDATER:"1",DISABLE_AUTO_COMPACT:"1",DISABLE_COMPACT:"1"},te=e.config.maxBudgetUsd??5,Q=e.config.maxTurns??100,Me=Br(e.roleId??""),ce=i?.mcpServers??{},it=e.config.mcpServers??{},je={...ce,...it,"execution-tools":Me},f=[],G=i?.additionalDirectories??[];for(let P of G){let x=Ue(P.path);if(P.inheritPlugins||P.inheritMcp){let V=Object.entries(x.enabledPlugins).filter(([,M])=>M).map(([M])=>M),Le=gs(V);for(let[,M]of Le)f.includes(M)||f.push(M)}P.inheritPermissions}if(i){let P=fe({scope:"project",projectPath:d});for(let x of P)x.installPath&&!f.includes(x.installPath)&&f.push(x.installPath)}let le=[e.config.workspacePath??process.cwd(),...G.map(P=>P.path)].filter((P,x,V)=>V.indexOf(P)===x),Ie=na({prompt:e.prompt,options:{cwd:d,additionalDirectories:le,systemPrompt:l,maxTurns:Q,maxBudgetUsd:te,allowedTools:i?.allowedTools,model:i?.model,mcpServers:je,settingSources:i?.inheritUserSettings?["project","user"]:["project"],hooks:b,canUseTool:W,env:T,plugins:f.map(P=>({type:"local",path:P})),stderr:P=>{P.trim()&&J.debug({stderr:P.trim().slice(0,500)},"ExecutionManager SDK stderr")}}}),pe="",dt=0,Ne=()=>{J.warn({taskId:e.id},"ExecutionManager: abort signal received")};t&&t.addEventListener("abort",Ne);try{for await(let P of Ie){let x=P;if(J.debug({eventType:x.type,taskId:e.id},"ExecutionManager SDK event"),x.type==="result"&&typeof x.result=="string"&&(pe=x.result),x.type==="result"&&dt++,x.token_usage){let V=x.token_usage;V.input_tokens!==void 0&&V.output_tokens!==void 0&&(r={input:V.input_tokens,output:V.output_tokens}),V.cost_usd!==void 0&&(n=V.cost_usd)}}}finally{t&&t.removeEventListener("abort",Ne)}a=dt;let ct=Date.now()-s;return $(e.id,{status:"completed",result:pe,completedAt:Date.now(),costUsd:n,tokenUsage:r,numTurns:a,totalDurationMs:ct}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"completed"}),g.emit({type:"task_complete_event",taskId:e.id,result:pe}),f.length>0&&Mr(e.id,f,e.roleId),J.info({taskId:e.id,durationMs:ct,costUsd:n},"ExecutionManager: task completed"),{taskId:e.id,status:"completed",result:pe,costUsd:n,tokenUsage:r,numTurns:a,durationMs:ct}}catch(i){let d=i instanceof Error?i.message:String(i),c=Date.now()-s;return $(e.id,{status:"failed",error:d,completedAt:Date.now(),totalDurationMs:c}),g.emit({type:"task_status_change",taskId:e.id,oldStatus:"running",newStatus:"failed"}),g.emit({type:"task_complete_event",taskId:e.id,error:d}),J.error({taskId:e.id,error:i},"ExecutionManager: task failed"),{taskId:e.id,status:"failed",error:d,durationMs:c}}}};var de=E("execution-pool"),De=class{slots;running=!1;pollTimeoutId=null;executor;constructor(e,t){this.slots=Array.from({length:e},(s,r)=>({index:r,taskId:null,abortController:null})),this.executor=t??new xe}async start(){if(this.running)return;this.running=!0,g.on("task_created",s=>{this.onTaskCreated(s.taskId)}),g.on("task_status_change",s=>{s.newStatus==="pending"&&this.pickupPendingTasks()});let t=Y().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t),de.info({maxConcurrent:this.slots.length},"ExecutionPool started")}stop(){this.running=!1,this.pollTimeoutId&&(clearTimeout(this.pollTimeoutId),this.pollTimeoutId=null);for(let e of this.slots)e.abortController&&(e.abortController.abort(),e.taskId=null,e.abortController=null);de.info("ExecutionPool stopped")}poll=()=>{if(!this.running)return;this.pickupPendingTasks();let t=Y().execution?.pollIntervalMs??3e4;this.pollTimeoutId=setTimeout(this.poll,t)};async onTaskCreated(e){this.running&&await this.pickupPendingTasks()}async pickupPendingTasks(){if(!this.running)return;let e=this.slots.find(i=>i.taskId===null);if(!e){de.debug("No free slots available");return}let t=N("pending");if(t.length===0)return;let r=[...t].sort((i,d)=>i.createdAt-d.createdAt)[0];e.taskId=r.id,e.abortController=new AbortController;let n=e.index,a=r.id;de.info({slotIndex:n,taskId:a},"ExecutionPool: claimed slot for task"),this.emitSlotChange(),this.executeTask(r,n).catch(i=>{de.error({taskId:a,error:i},"ExecutionPool: executeTask failed unexpectedly")})}async executeTask(e,t){let s=this.slots[t];if(!s)return;let r="completed";try{g.emit({type:"execution_task_start",taskId:e.id,slotIndex:t});let n=await this.executor.execute(e,s.abortController?.signal);r=n.status,de.info({taskId:e.id,status:n.status,slotIndex:t},"ExecutionPool: task finished")}finally{s.taskId=null,s.abortController=null,g.emit({type:"execution_task_end",taskId:e.id,slotIndex:t,status:r}),this.emitSlotChange(),this.running&&this.pickupPendingTasks()}}emitSlotChange(){let e=this.slots.filter(s=>s.taskId!==null).length,t=N("pending");g.emit({type:"execution_slot_change",active:e,max:this.slots.length,queued:t.length})}getStatus(){let e=this.slots.filter(s=>s.taskId!==null).length,t=N("pending");return{active:e,max:this.slots.length,queued:t.length}}isHealthy(){return this.running}releaseSlot(e){let t=this.slots.find(s=>s.taskId===e);t&&(de.warn({taskId:e,slotIndex:t.index},"ExecutionPool: force-releasing slot"),t.abortController&&t.abortController.abort(),t.taskId=null,t.abortController=null,this.emitSlotChange(),this.running&&this.pickupPendingTasks())}};import{v4 as Nt}from"uuid";async function oa(o,e){if(!(await import("./config-42ZJPZDM.js").then(r=>r.getChatConfig())).autoTitle)return;let s=["Generate a very short title (max 50 characters) for a chat session that started with this message:",`"${e.slice(0,200)}"`,"Respond with only the title, no quotes or explanation."].join(`
|
|
152
|
+
`);try{let n=(await Os(s,"You are a concise title generator. Reply with only the title, max 50 characters.")).trim().slice(0,50);n.length>0&&ps(o,{title:n})}catch{}}var Lt=null;function Ur(o){Lt=o}async function et(o,e,t,s){let r;s&&(r=H(s)),r||(r=Ps(e)),r||(r=$e(e,t));let n=Nt(),a={id:n,sessionId:r.id,role:"user",content:o,source:e,createdAt:Date.now()};if(X(a),g.emit({type:"chat_message",sessionId:r.id,message:a}),r.messageCount===0&&oa(r.id,o),Z(r.id),Se(r.id),Lt){let i=r.id,d=r.source;(async()=>{try{let c=await Lt.handleMessage(o,i,e),l={id:Nt(),sessionId:i,role:"assistant",content:c,source:e,createdAt:Date.now()};X(l),g.emit({type:"chat_message",sessionId:i,message:l}),Z(i),Se(i),d.type==="channel"&&d.channelId&&d.chatId&&ia(d.channelId,d.chatId,c)}catch(c){(await import("./logger-BEG4WFIM.js")).getLogger("message-handler").error({error:c,sessionId:i},"ChatManager response failed");let b={id:Nt(),sessionId:i,role:"assistant",content:`\u26A0\uFE0F \u5904\u7406\u5931\u8D25: ${c instanceof Error?c.message:String(c)}`,source:e,createdAt:Date.now()};X(b),g.emit({type:"chat_message",sessionId:i,message:b}),Z(i)}})()}return{sessionId:r.id,messageId:n}}async function ia(o,e,t){try{let{getChannelManager:s}=await import("./channels-CNLMTKHM.js"),r=s();r&&await r.sendMessage(o,e,{content:t})}catch{}}import{z as h}from"zod/v4";import{v4 as da}from"uuid";var Wr=h.union([h.object({type:h.literal("session"),sessionId:h.string()}),h.object({type:h.literal("channel"),channelId:h.string(),chatId:h.string().optional()})]),ca=h.object({id:h.string(),prompt:h.string(),dependsOn:h.array(h.string()).optional(),outputAs:h.string().optional()}),la=h.object({type:h.enum(["cron","manual","event"]),cron:h.string().optional(),event:h.string().optional()}),qt=h.object({name:h.string().min(1),description:h.string().optional(),trigger:la,steps:h.array(ca).min(1),rolePreference:h.string().optional(),config:h.record(h.string(),h.unknown()).optional(),enabled:h.boolean().default(!0),goalIds:h.array(h.string()).optional(),notifyTargets:h.array(Wr).optional(),deliverTo:h.array(Wr).optional()}),Md=qt.transform(o=>({...o,notifyTargets:o.notifyTargets,deliverTo:o.deliverTo})),pa=qt.partial().transform(o=>({...o,notifyTargets:o.notifyTargets,deliverTo:o.deliverTo})),tt=h.object({id:h.string().min(1)});async function Gr(o,e){o.post("/task-templates",{schema:{tags:["Templates"],summary:"Create a task template",description:"Create a new task template with trigger (cron/manual/event) and execution steps. Cron-triggered templates are automatically scheduled.",body:{type:"object",required:["name","trigger","steps"],properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",required:["type"],properties:{type:{type:"string",enum:["cron","manual","event"]},cron:{type:"string",description:"Cron expression (required when type is cron)"},event:{type:"string",description:"Event name (required when type is event)"}}},steps:{type:"array",minItems:1,items:{type:"object",required:["id","prompt"],properties:{id:{type:"string"},prompt:{type:"string"},dependsOn:{type:"array",items:{type:"string"}},outputAs:{type:"string"}}}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean",default:!0},goalIds:{type:"array",items:{type:"string"}},notifyTargets:{type:"array",items:{type:"object"}}}},response:R.templateCreated}},async(t,s)=>{let r=qt.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n={id:da(),...r.data,createdAt:Date.now()};return We(n),n.enabled&&n.trigger.type==="cron"&&n.trigger.cron&&await e.scheduleJob(n.id),s.status(201).send({templateId:n.id})}),o.get("/task-templates",{schema:{tags:["Templates"],summary:"List task templates",description:"List all task templates, optionally filtering to enabled-only.",querystring:{type:"object",properties:{enabled:{type:"string",enum:["true","false"],description:"Filter to enabled templates only when 'true'"}}},response:R.templateList}},async t=>{let r=t.query.enabled==="true";return{templates:we(r)}}),o.get("/task-templates/:id",{schema:{tags:["Templates"],summary:"Get task template by ID",description:"Retrieve a single task template by its ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDetail}},async(t,s)=>{let r=tt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n=U(r.data.id);return n?{template:n}:s.status(404).send({code:"NOT_FOUND",message:"Template not found"})}),o.patch("/task-templates/:id",{schema:{tags:["Templates"],summary:"Update a task template",description:"Partially update a task template. Cron schedules are automatically rescheduled if the trigger changes.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},trigger:{type:"object",properties:{type:{type:"string",enum:["cron","manual","event"]},cron:{type:"string"},event:{type:"string"}}},steps:{type:"array",items:{type:"object"}},rolePreference:{type:"string"},config:{type:"object",additionalProperties:!0},enabled:{type:"boolean"},goalIds:{type:"array",items:{type:"string"}},notifyTargets:{type:"array",items:{type:"object"}},deliverTo:{type:"array",items:{type:"object"}}}},response:R.templateUpdated}},async(t,s)=>{let r=tt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)});let n=pa.safeParse(t.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(n.error)});if(!U(r.data.id))return s.status(404).send({code:"NOT_FOUND",message:"Template not found"});Rs(r.data.id,n.data),await e.unscheduleJob(r.data.id);let i=U(r.data.id);return i?.enabled&&i.trigger.type==="cron"&&i.trigger.cron&&await e.scheduleJob(i.id),{templateId:r.data.id}}),o.delete("/task-templates/:id",{schema:{tags:["Templates"],summary:"Delete a task template",description:"Delete a task template by ID. Cron jobs are automatically unscheduled.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateDeleted}},async(t,s)=>{let r=tt.safeParse(t.params);return r.success?U(r.data.id)?(await e.unscheduleJob(r.data.id),Is(r.data.id),{templateId:r.data.id,deleted:!0}):s.status(404).send({code:"NOT_FOUND",message:"Template not found"}):s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)})}),o.post("/task-templates/:id/run",{schema:{tags:["Templates"],summary:"Run a task template",description:"Manually trigger execution of a task template regardless of its trigger type.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.templateRun}},async(t,s)=>{let r=tt.safeParse(t.params);return r.success?U(r.data.id)?{executionId:await e.runNow(r.data.id),status:"started"}:s.status(404).send({code:"NOT_FOUND",message:"Template not found"}):s.status(400).send({code:"VALIDATION_ERROR",message:h.prettifyError(r.error)})})}import{z as C}from"zod/v4";St();var Bt=C.object({id:C.string().min(1)}),ua=C.object({scope:C.enum(["user","project"]).optional(),cwd:C.string().optional()}),ma=C.object({scope:C.enum(["user","project"]).optional(),cwd:C.string().optional()});async function Vr(o){o.get("/plugins",{schema:{tags:["Plugins"],summary:"List all installed plugins",querystring:{type:"object",properties:{scope:{type:"string",enum:["user","project","local"]}}}}},async t=>{let s=t.query,r=fe({scope:s.scope}),n=wt();return{plugins:r.map(a=>({...a,globalEnabled:n[a.id]??a.enabled}))}}),o.get("/plugins/:id",{schema:{tags:["Plugins"],summary:"Get plugin by ID",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});let n=ms(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Plugin not found"});let a=us(n.installPath),i=wt();return{plugin:{...n,globalEnabled:i[n.id]??n.enabled,manifest:a}}}),o.post("/plugins/:id/enable",{schema:{tags:["Plugins"],summary:"Enable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});try{return Us(r.data.id),{pluginId:r.data.id,enabled:!0}}catch(n){return s.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Enable failed"})}}),o.post("/plugins/:id/disable",{schema:{tags:["Plugins"],summary:"Disable a plugin globally",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(t,s)=>{let r=Bt.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)});try{return Ws(r.data.id),{pluginId:r.data.id,enabled:!1}}catch(n){return s.status(500).send({code:"CLI_ERROR",message:n instanceof Error?n.message:"Disable failed"})}}),o.get("/plugins/stats",{schema:{tags:["Plugins"],summary:"Get plugin usage statistics",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50}}}}},async t=>{let s=t.query;return{stats:Nr(s.limit??50)}});let e=C.object({roleId:C.string().min(1)});o.get("/plugins/stats/role/:roleId",{schema:{tags:["Plugins"],summary:"Get plugin usage by role",params:{type:"object",required:["roleId"],properties:{roleId:{type:"string"}}}}},async(t,s)=>{let r=e.safeParse(t.params);return r.success?{roleId:r.data.roleId,stats:jr(r.data.roleId)}:s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(r.error)})}),o.get("/plugins/marketplace",{schema:{tags:["Marketplace"],summary:"List available marketplace plugins"}},async(t,s)=>{if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found. Install Claude Code to use marketplace features."});try{let r=Ls();return{available:r.available,installed:r.installed}}catch(r){return s.status(500).send({code:"CLI_ERROR",message:r instanceof Error?r.message:"CLI command failed"})}}),o.get("/plugins/marketplaces",{schema:{tags:["Marketplace"],summary:"List known marketplace sources"}},async()=>({sources:fs()})),o.post("/plugins/install/:name",{schema:{tags:["Marketplace"],summary:"Install a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,s)=>{let n=C.object({name:C.string().min(1)}).safeParse(t.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(n.error)});let a=ua.safeParse(t.body??{});if(!a.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(a.error)});if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return qs(n.data.name,a.data.scope??"user",a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return s.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Install failed"})}}),o.post("/plugins/uninstall/:name",{schema:{tags:["Marketplace"],summary:"Uninstall a plugin",params:{type:"object",required:["name"],properties:{name:{type:"string"}}},body:{type:"object",properties:{scope:{type:"string",enum:["user","project"]},cwd:{type:"string"}}}}},async(t,s)=>{let n=C.object({name:C.string().min(1)}).safeParse(t.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(n.error)});let a=ma.safeParse(t.body??{});if(!a.success)return s.status(400).send({code:"VALIDATION_ERROR",message:C.prettifyError(a.error)});if(!He())return s.status(503).send({code:"CLI_NOT_AVAILABLE",message:"Claude Code CLI not found"});try{return Bs(n.data.name,a.data.scope,a.data.cwd),{success:!0,pluginId:n.data.name}}catch(i){return s.status(500).send({code:"CLI_ERROR",message:i instanceof Error?i.message:"Uninstall failed"})}})}import{z as Ut}from"zod/v4";var ga=Ut.object({name:Ut.string().min(1)}),fa="x-api-key";async function $r(o,e,t){o.post("/webhooks/:name",{schema:{tags:["Webhooks"],summary:"Trigger a webhook",description:"Trigger a task template execution by name or ID. Requires X-API-Key header if API key is configured.",security:[{apiKey:[]}],params:{type:"object",required:["name"],properties:{name:{type:"string",description:"Template name or ID"}}},response:R.webhookTriggered}},async(s,r)=>{if(t&&s.headers[fa]!==t)return r.status(401).send({code:"UNAUTHORIZED",message:"Invalid or missing API key"});let n=ga.safeParse(s.params);if(!n.success)return r.status(400).send({code:"VALIDATION_ERROR",message:Ut.prettifyError(n.error)});let{name:a}=n.data,i=U(a);if(!i){let{listTaskTemplates:d}=await import("./task-templates-AKQB7RRB.js");i=d(!1).find(l=>l.name===a||l.id===a)}if(!i)return r.status(404).send({code:"NOT_FOUND",message:`Template '${a}' not found`});if(!i.enabled)return r.status(409).send({code:"DISABLED",message:`Template '${a}' is disabled`});try{let d=await e.runNow(i.id);return r.status(202).send({code:"ACCEPTED",message:`Template '${i.name}' triggered`,executionId:d,templateId:i.id})}catch(d){let c=d instanceof Error?d.message:String(d);return r.status(500).send({code:"EXECUTION_ERROR",message:c})}}),o.get("/webhooks",{schema:{tags:["Webhooks"],summary:"List available webhooks",description:"List all enabled task templates that can be triggered via webhook, along with auth requirements.",response:R.webhookList}},async()=>{let{listTaskTemplates:s}=await import("./task-templates-AKQB7RRB.js");return{webhooks:s(!0).map(n=>({name:n.id,displayName:n.name,description:n.description,tags:n.tags,trigger:`POST /webhooks/${n.id}`})),auth:t?"X-API-Key header required":"No auth configured"}})}import{z as k}from"zod/v4";var ya=k.object({status:k.string().optional(),limit:k.coerce.number().min(1).max(100).default(20),offset:k.coerce.number().min(0).default(0)}),zr=k.union([k.object({type:k.literal("session"),sessionId:k.string()}),k.object({type:k.literal("channel"),channelId:k.string(),chatId:k.string().optional()})]),ha=k.object({input:k.string().min(1,"goal input is required"),notifyTargets:k.array(zr).optional()}),Hr=k.object({id:k.string().min(1)}),ba=k.object({name:k.string().min(1).optional(),description:k.string().optional(),status:k.enum(["active","paused","completed","failed"]).optional(),currentValue:k.number().optional(),budgetUsd:k.number().min(0).optional(),notifyTargets:k.array(zr).optional()});async function Kr(o){o.get("/goals",{schema:{tags:["Goals"],summary:"List goals",description:"List goals with optional status filter and pagination.",querystring:{type:"object",properties:{status:{type:"string",description:"Filter by goal status"},limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0}}},response:R.goalList}},async(e,t)=>{let s=ya.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let{status:r,limit:n,offset:a}=s.data;return{goals:Ts(r,n,a)}}),o.get("/goals/:id",{schema:{tags:["Goals"],summary:"Get goal by ID",description:"Retrieve a single goal by its ID, including metric tree and progress.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},response:R.goalDetail}},async(e,t)=>{let s=re(e.params.id);return s?{goal:s}:t.status(404).send({code:"NOT_FOUND",message:"Goal not found"})}),o.post("/goals",{schema:{tags:["Goals"],summary:"Create a goal",description:"Create a new goal from a natural language input. The input is parsed, validated, and a metric tree is built.",body:{type:"object",required:["input"],properties:{input:{type:"string",minLength:1,description:"Natural language goal description"},notifyTargets:{type:"array",items:{type:"object"},description:"Notification targets (session or channel)"}}},response:R.goalCreated}},async(e,t)=>{let s=ha.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let r=await Fs(s.data.input);if(!r.validationResult.isValid)return t.status(400).send({code:"INVALID_GOAL",errors:r.validationResult.errors,warnings:r.validationResult.warnings});let n=Ms(r.goalState,s.data.notifyTargets);return js(n.id,n.metricType),t.status(201).send({goal:n})}),o.patch("/goals/:id",{schema:{tags:["Goals"],summary:"Update a goal",description:"Partially update a goal's name, description, status, currentValue, or budgetUsd.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}},body:{type:"object",properties:{name:{type:"string",minLength:1},description:{type:"string"},status:{type:"string"},currentValue:{type:"number"},budgetUsd:{type:"number",minimum:0},notifyTargets:{type:"array",items:{type:"object"},description:"Notification targets (session or channel)"}}},response:R.goalDetail}},async(e,t)=>{let s=Hr.safeParse(e.params);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)});let r=ba.safeParse(e.body);return r.success?re(s.data.id)?(Ge(s.data.id,{...r.data,updatedAt:Date.now()}),{goal:re(s.data.id)}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(r.error)})}),o.delete("/goals/:id",{schema:{tags:["Goals"],summary:"Delete a goal",description:"Delete a goal by ID.",params:{type:"object",required:["id"],properties:{id:{type:"string"}}}}},async(e,t)=>{let s=Hr.safeParse(e.params);return s.success?re(s.data.id)?(ws(s.data.id),{goalId:s.data.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Goal not found"}):t.status(400).send({code:"VALIDATION_ERROR",message:k.prettifyError(s.error)})})}import{z as Oe}from"zod/v4";var va=Oe.object({role:Oe.enum(["engineer","analyst","content_creator","reviewer"]).optional(),taskType:Oe.string().optional(),limit:Oe.coerce.number().min(1).max(100).default(50)});async function Jr(o){o.get("/strategies",{schema:{tags:["Strategies"],summary:"List strategies",description:"List agent strategies with optional role/taskType filter. Returns evolutionary strategy entries used for agent routing.",querystring:{type:"object",properties:{role:{type:"string",enum:["engineer","analyst","content_creator","reviewer"]},taskType:{type:"string",description:"Filter by task type"},limit:{type:"integer",minimum:1,maximum:100,default:50}}},response:R.strategyList}},async(e,t)=>{let s=va.safeParse(e.query);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:Oe.prettifyError(s.error)});let{role:r,taskType:n,limit:a}=s.data,i;if(r&&n)i=Ns.getStrategies(r,n);else if(r)i=Pt(r);else{let d=["engineer","analyst","content_creator","reviewer"];i=[];for(let c of d)i.push(...Pt(c))}return{strategies:i.slice(0,a)}})}async function Qr(o){o.get("/config",{schema:{tags:["Config"],summary:"Get current configuration",description:"Returns the current server configuration with runtime-mutable vs restart-required indication for each setting.",response:R.configGet}},async(e,t)=>{let s=Y(),r=[...qe,...pt],n={};for(let a of r){let i=ut(s,a),d=qe.includes(a);n[a]={value:i,mutable:d}}return{config:n,mutable:[...qe],restartRequired:[...pt]}}),o.patch("/config",{schema:{tags:["Config"],summary:"Update runtime-mutable configuration",description:"Updates configuration values that can be changed at runtime. Restart-required settings are rejected but valid mutable changes are still applied (partial success).",response:R.configPatch}},async(e,t)=>{let s=e.body;if(!s||typeof s!="object")return t.status(400).send({success:!1,updated:[],errors:["Request body must be a JSON object with config key-value pairs"],message:"Validation error"});let r=Yt(s);if(r.updated.includes("logging.level")){let n=s["logging.level"];typeof n=="string"&&Be(n)}if(r.updated.length>0){let n=Y(),a=r.updated.map(i=>({path:i,value:ut(n,i)}));g.emit({type:"config_changed",changes:a})}return{success:r.errors.length===0,updated:r.updated,errors:r.errors,message:r.errors.length===0?`Updated ${r.updated.length} configuration value(s)`:`Updated ${r.updated.length} value(s); ${r.errors.length} rejected (restart required)`}})}async function Yr(o){o.get("/evolution-audit",{schema:{tags:["Evolution"],summary:"List evolution audit records",description:"Returns evolution audit log entries with optional role filter.",querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:100,default:20},offset:{type:"integer",minimum:0,default:0},roleId:{type:"string"}}}}},async(e,t)=>{let{limit:s=20,offset:r=0,roleId:n}=e.query;return n?Ks(n,s,r):zs(s,r)})}import{z as I}from"zod/v4";var Ra=["active","archived"],Ia=I.object({source:I.object({type:I.enum(["tui","web","api","channel"]),channelId:I.string().optional(),chatId:I.string().optional()}),roleId:I.string().optional()}),Fe=I.object({id:I.string().uuid()}),ka=I.object({status:I.enum(Ra).optional(),limit:I.coerce.number().min(1).max(100).default(100),offset:I.coerce.number().min(0).default(0)}),Ta=I.object({limit:I.coerce.number().min(1).max(200).default(50),offset:I.coerce.number().min(0).default(0)});async function Xr(o){o.post("/chat/sessions",{schema:{tags:["Chat"],summary:"Create a chat session",body:{type:"object",required:["source"],properties:{source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"}}}}},async(t,s)=>{let r=Ia.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{source:n,roleId:a}=r.data,i=$e(n,a);return s.status(201).send({session:i})}),o.get("/chat/sessions",{schema:{tags:["Chat"],summary:"List chat sessions",querystring:{type:"object",properties:{status:{type:"string",enum:["active","archived"]},limit:{type:"integer",minimum:1,maximum:100,default:100},offset:{type:"integer",minimum:0,default:0}}}}},async(t,s)=>{let r=ka.safeParse(t.query);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{status:n}=r.data;return{sessions:Es(n)}}),o.get("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Get chat session with messages",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=Tt(n.id);return{session:n,messages:a}}),o.post("/chat/sessions/:id/archive",{schema:{tags:["Chat"],summary:"Archive a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);return n?(Cs(n.id),{sessionId:n.id,status:"archived"}):s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.post("/chat/sessions/:id/restore",{schema:{tags:["Chat"],summary:"Restore an archived session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=_s(r.data.id);return n?{session:n}:s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.delete("/chat/sessions/:id",{schema:{tags:["Chat"],summary:"Delete a chat session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);return n?(As(n.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Session not found"})}),o.get("/chat/sessions/:id/messages",{schema:{tags:["Chat"],summary:"Get messages for a session",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},querystring:{type:"object",properties:{limit:{type:"integer",minimum:1,maximum:200,default:50},offset:{type:"integer",minimum:0,default:0}}}}},async(t,s)=>{let r=Fe.safeParse(t.params);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let n=H(r.data.id);if(!n)return s.status(404).send({code:"NOT_FOUND",message:"Session not found"});let a=Ta.safeParse(t.query),{limit:i=50,offset:d=0}=a.success?a.data:{};return{messages:Tt(n.id,i,d)}});let e=I.object({content:I.string().min(1,"content is required"),source:I.object({type:I.enum(["tui","web","api","channel"]),channelId:I.string().optional(),chatId:I.string().optional()}),roleId:I.string().optional(),sessionId:I.string().uuid().optional()});o.post("/chat/messages",{schema:{tags:["Chat"],summary:"Send a chat message",description:"Send a message. Creates a session if no active session exists for the source. Returns sessionId, messageId, and response.",body:{type:"object",required:["content","source"],properties:{content:{type:"string",minLength:1},source:{type:"object",required:["type"],properties:{type:{type:"string",enum:["tui","web","api","channel"]},channelId:{type:"string"},chatId:{type:"string"}}},roleId:{type:"string"},sessionId:{type:"string"}}}}},async(t,s)=>{let r=e.safeParse(t.body);if(!r.success)return s.status(400).send({code:"VALIDATION_ERROR",message:I.prettifyError(r.error)});let{content:n,source:a,roleId:i,sessionId:d}=r.data,c=await et(n,a,i,d);return s.status(201).send(c)})}var wa=E("ws"),st=new Set,rt=[],Sa=50;function Pa(o){rt.push(o),rt.length>Sa&&rt.shift()}function Re(o){Pa(o);let e=JSON.stringify(o);for(let t of st)t.readyState===1&&t.send(e)}function Zr(o){o.get("/chat/stream",{websocket:!0},(e,t)=>{st.add(e);for(let s of rt)e.readyState===1&&e.send(JSON.stringify(s));e.on("close",()=>{st.delete(e)}),e.on("error",s=>{wa.error({error:s},"Chat WebSocket error"),st.delete(e)})}),g.on("session_created",e=>Re(e)),g.on("session_archived",e=>Re(e)),g.on("session_restored",e=>Re(e)),g.on("session_deleted",e=>Re(e)),g.on("chat_message",e=>Re(e)),g.on("task_complete_event",e=>Re(e))}var L=E("channels"),nt=class{adapters=new Map;rateLimits=new Map;healthInterval;rateLimitPerMinute;constructor(e){this.rateLimitPerMinute=e?.rateLimitPerMinute??60}async addChannel(e,t){this.adapters.set(e.id,t),t.onMessage(s=>{this.handleInbound(e.id,s)}),e.enabled&&await this.connectChannel(e.id)}async removeChannel(e){let t=this.adapters.get(e);if(t){try{await t.disconnect()}catch(s){L.error({channelId:e,error:s},"Error disconnecting channel")}this.adapters.delete(e),this.rateLimits.delete(e)}}async connectChannel(e){let t=this.adapters.get(e);if(!t)throw new Error(`No adapter registered for channel ${e}`);try{ye(e,"connecting"),await t.connect(),ye(e,"connected"),L.info({channelId:e,platform:t.platform},"Channel connected")}catch(s){throw ye(e,"error"),L.error({channelId:e,error:s},"Failed to connect channel"),s}}async disconnectChannel(e){let t=this.adapters.get(e);if(t)try{await t.disconnect(),ye(e,"disconnected"),L.info({channelId:e},"Channel disconnected")}catch(s){L.error({channelId:e,error:s},"Error disconnecting channel")}}getChannelStatus(e){let t=this.adapters.get(e);return t?t.getStatus():"disconnected"}getChannelStatuses(){let e=new Map;for(let[t,s]of this.adapters)e.set(t,s.getStatus());return e}hasAdapter(e){return this.adapters.has(e)}async sendMessage(e,t,s){let r=this.adapters.get(e);if(!r)return L.warn({channelId:e},"No adapter for outbound message"),null;if(!this.checkRateLimit(e))return L.warn({channelId:e},"Rate limit exceeded, dropping outbound message"),null;try{return await r.sendMessage(t,s)}catch(n){return L.error({channelId:e,chatId:t,error:n},"Failed to send outbound message"),null}}checkRateLimit(e){let t=Date.now(),s=this.rateLimits.get(e);return!s||t-s.windowStart>=6e4?(this.rateLimits.set(e,{count:1,windowStart:t}),!0):s.count>=this.rateLimitPerMinute?!1:(s.count++,!0)}async handleInbound(e,t){if(t.source==="system"){L.debug({channelId:e},"Skipping system message (anti-loop)");return}try{let{isDeliveryMessage:r}=await import("./engine-7VBPXTGK.js"),n=t.channelMessageId??t.raw?.MsgId??"";if(n&&r(String(n))){L.debug({channelId:e,messageId:n},"Skipping delivery-sent message (anti-loop)");return}}catch{}if(!this.checkRateLimit(e)){L.warn({channelId:e,senderId:t.senderId},"Rate limit exceeded for inbound message");return}try{let{handleInboundForApproval:r}=await import("./approval-handler-SBFVVFGH.js");if(await r(e,t.chatId,t.content)){L.debug({channelId:e,chatId:t.chatId},"Inbound message consumed as approval reply");return}}catch{}let s=Ss(e);if(s?.allowedChatIds&&!s.allowedChatIds.includes(t.chatId)){L.debug({channelId:e,chatId:t.chatId},"Chat not in allowlist, ignoring");return}try{let r=await et(t.content,{type:"channel",channelId:e,chatId:t.chatId},s?.linkedRoleId);L.info({channelId:e,chatId:t.chatId,sessionId:r.sessionId},"Inbound message routed to session")}catch(r){L.error({channelId:e,chatId:t.chatId,error:r},"Failed to route inbound message")}}startHealthMonitor(e=3e4){this.stopHealthMonitor(),this.healthInterval=setInterval(()=>{this.checkHealth()},e)}stopHealthMonitor(){this.healthInterval&&(clearInterval(this.healthInterval),this.healthInterval=void 0)}checkHealth(){for(let[e,t]of this.adapters){let s=t.getStatus();try{ye(e,s)}catch{}}}async startAll(){let e=Ve(!0);for(let t of e){let s=this.adapters.get(t.id);if(s&&s.getStatus()!=="connected")try{await this.connectChannel(t.id)}catch{}}this.startHealthMonitor()}async stopAll(){this.stopHealthMonitor();for(let e of this.adapters.keys())await this.disconnectChannel(e);this.adapters.clear(),this.rateLimits.clear()}_getAdapterCount(){return this.adapters.size}_getRateLimitEntry(e){return this.rateLimits.get(e)}};ke();var ee=E("watchdog"),at=null;function en(o,e,t,s){if(!o.enabled){ee.info("Watchdog disabled");return}let r=o.intervalMinutes*6e4;ee.info({intervalMinutes:o.intervalMinutes},"Watchdog started"),at=setInterval(()=>{Ca(o,e,t,s)},r)}function tn(){at&&(clearInterval(at),at=null,ee.info("Watchdog stopped"))}function Ca(o,e,t,s){let{rules:r}=o;if(r.managerHealthCheck.enabled){let n=r.managerHealthCheck.staleDurationMinutes*6e4,a=e.getLastActivityAt();if(Date.now()-a>n){let i=`ChatManager session stale (no activity for ${r.managerHealthCheck.staleDurationMinutes} min)`;if(ee.warn(i),r.managerHealthCheck.action==="restart"){let d=e.getConsecutiveStaleCount()>0;e.restartSession(),d&&(ee.fatal("ChatManager unrecoverable after session restart \u2014 exiting for supervisor restart"),process.exit(1))}else r.managerHealthCheck.action==="notify"&&s(i)}}if(!t.isHealthy()){let n="ExecutionPool is not healthy (stopped unexpectedly)";ee.warn(n),s(n)}if(r.staleTasks.enabled){let n=r.staleTasks.maxPendingMinutes*6e4,i=N("pending").filter(d=>Date.now()-d.createdAt>n);if(i.length>0){let d=`${i.length} stale task(s) pending > ${r.staleTasks.maxPendingMinutes} min`;ee.warn({count:i.length},d),r.staleTasks.action==="notify"&&s(d)}}if(r.staleRunningTasks?.enabled){let n=r.staleRunningTasks.maxRunningMinutes*6e4,i=N("running").filter(d=>{if(!d.startedAt||Date.now()-d.startedAt<n)return!1;try{let u=j().prepare("SELECT MAX(timestamp) as latest FROM step_logs WHERE task_id = ?").get(d.id)?.latest??d.startedAt;return Date.now()-u>n}catch{return!0}});if(i.length>0){let d=`${i.length} task(s) running with no activity for > ${r.staleRunningTasks.maxRunningMinutes} min \u2014 marking as failed`;ee.warn({count:i.length,taskIds:i.map(c=>c.id)},d);for(let c of i)$(c.id,{status:"failed",error:`Watchdog timeout: no activity for > ${r.staleRunningTasks.maxRunningMinutes} min`,completedAt:Date.now()}),g.emit({type:"task_status_change",taskId:c.id,oldStatus:"running",newStatus:"failed"}),t.releaseSlot(c.id);s(d)}}if(r.dbMaintenance.enabled)try{let a=j().pragma("wal_checkpoint(PASSIVE)");ee.debug({walSize:a},"WAL checkpoint")}catch(n){ee.error({error:n},"DB health check failed")}}import{z as D}from"zod";import{v4 as _a}from"uuid";var Aa=D.object({eventType:D.enum(["task_complete","task_error","plan_approval_request","*"]),matchCriteria:D.object({templateId:D.string().optional(),skillId:D.string().optional(),skillRole:D.string().optional(),promptPattern:D.string().optional(),taskStatus:D.string().optional()}).optional().default({}),target:D.object({type:D.enum(["channel","webhook"]),channelId:D.string().optional(),chatId:D.string().optional(),webhookUrl:D.string().optional()}),formatTemplate:D.string().optional(),maxPerMinute:D.number().int().min(1).max(60).optional().default(5),skipOriginChannel:D.boolean().optional().default(!0),enabled:D.boolean().optional().default(!0)});async function Wt(o){o.get("/delivery-rules",async(e,t)=>Vs()),o.post("/delivery-rules",async(e,t)=>{let s=Aa.safeParse(e.body);if(!s.success)return t.status(400).send({code:"VALIDATION_ERROR",message:D.prettifyError(s.error)});let r=s.data,n={id:_a(),eventType:r.eventType,matchCriteria:r.matchCriteria,target:r.target,formatTemplate:r.formatTemplate,maxPerMinute:r.maxPerMinute,skipOriginChannel:r.skipOriginChannel,enabled:r.enabled,createdAt:Date.now()};return Gs(n),t.status(201).send(n)}),o.put("/delivery-rules/:id",async(e,t)=>{if(!ze(e.params.id))return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let r=e.body;return $s(e.params.id,r),{id:e.params.id,updated:!0}}),o.delete("/delivery-rules/:id",async(e,t)=>ze(e.params.id)?(Hs(e.params.id),{id:e.params.id,deleted:!0}):t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"})),o.get("/delivery-rules/:id/log",async(e,t)=>Xs(e.params.id)),o.post("/delivery-rules/:id/test",async(e,t)=>{let s=ze(e.params.id);if(!s)return t.status(404).send({code:"NOT_FOUND",message:"Delivery rule not found"});let{getDeliveryEngine:r}=await import("./engine-7VBPXTGK.js"),n=r();if(!n)return t.status(503).send({code:"ENGINE_NOT_READY",message:"DeliveryEngine not initialized"});let a=`[TEST] Delivery rule test at ${new Date().toISOString()}`,{createDeliveryLog:i}=await import("./delivery-log-7DQ36UGP.js"),{v4:d}=await import("uuid"),{TTL_MS:c}=await import("./delivery-log-7DQ36UGP.js"),l={id:d(),ruleId:s.id,status:"pending",target:s.target,content:a,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+c};i(l);try{return await n.attemptDeliveryPublic(l,s),{id:l.id,ruleId:s.id,status:"sent",content:a}}catch(b){let u=b instanceof Error?b.message:String(b);return t.status(500).send({code:"DELIVERY_FAILED",message:u,logId:l.id})}})}me();var _=E("adam");function xa(o){let e={...o};if(e.defaults&&typeof e.defaults=="object"){let t={...e.defaults};if(t.env&&typeof t.env=="object"){let s={...t.env};for(let r of Object.keys(s))s[r]&&(s[r]=s[r].slice(0,4)+"****");t.env=s}e.defaults=t}if(e.server&&typeof e.server=="object"){let t={...e.server};t.apiKey&&typeof t.apiKey=="string"&&(t.apiKey=t.apiKey.slice(0,4)+"****"),e.server=t}return e}async function Da(){sr();let o=rr();o.length>0&&console.log(`[adam] Migrated to ~/.adam/: ${o.join(", ")}`);let e=nr();_.info("Starting Adam Agent Server"),e.length>0&&_.info({files:e},"Loaded env files");let t=Jt();Qt(t),t.logging?.level&&Be(t.logging.level),_.info({config:xa(t)},"Config loaded"),process.env.ANTHROPIC_API_KEY||_.warn("ANTHROPIC_API_KEY not set \u2014 Manager LLM queries will fail"),process.env.ANTHROPIC_BASE_URL&&_.info({url:process.env.ANTHROPIC_BASE_URL},"Using custom API base URL");let s=t.defaults?.claudeCodePath;try{if(!s){let{createRequire:le}=await import("module"),{dirname:Ie,join:pe}=await import("path"),Ne=le(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");s=pe(Ie(Ne),"cli.js")}let{execSync:f}=await import("child_process"),G=f(`"${s}" --version`,{timeout:5e3,encoding:"utf-8"}).trim();_.info({path:s,version:G},"Claude Code CLI detected")}catch(f){let G=f;G.code==="ENOENT"?_.warn({path:s},"Claude Code CLI not found. Task execution will fail. Install: npm i -g @anthropic-ai/claude-code"):_.warn({path:s,error:(G.stderr?.trim()||String(f)).slice(0,200)},"Claude Code CLI check failed")}let n=j().prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();_.info({tables:n.map(f=>f.name).join(", ")},"Database initialized");let a=xt(),{getToolsFingerprint:i}=await import("./adam-tools-MKUMZWCR.js"),d=i(),c=a.sdkSessionId;if(c&&a.toolsFingerprint!==d&&(_.info({old:a.toolsFingerprint?.slice(0,40),new:d.slice(0,40)},"MCP tools changed \u2014 invalidating old SDK session"),Rr(),c=void 0),Pe({toolsFingerprint:d}),c){let f=process.cwd();a.workspacePath&&a.workspacePath!==f&&(_.warn({serverCwd:f,saved:a.workspacePath},"Workspace mismatch"),_.warn("SDK session may not resume correctly due to cwd mismatch")),_.info({sessionId:c.slice(0,8)},"Recovering manager SDK session")}else _.info("No previous manager SDK session found, starting fresh");a.userTaskSessionId&&_.info({sessionId:a.userTaskSessionId.slice(0,8)},"Recovering user task session"),Ir(process.cwd());let{initializeDefaultRoles:l}=await import("./role-presets-2X3VW75D.js"),b=l();_.info({count:b.length},"Roles initialized");let y=Y().execution??{maxConcurrent:3,maxBudgetPerTaskUsd:5,pollIntervalMs:3e4},w=new Ee(c),v=new De(y.maxConcurrent);Ur(w),await w.start(),await v.start();let W=N("running");if(W.length>0){_.warn({count:W.length},"Found orphaned running tasks from previous session \u2014 marking as failed");for(let f of W)$(f.id,{status:"failed",error:"Server restarted while task was running",completedAt:Date.now()})}let T=ir(t,t.server.apiKey);await T.register(f=>ur(f)),await T.register(f=>mr(f,t)),await T.register(f=>hr(f,t.server.apiKey)),await T.register(Sr),await T.register(Or),await T.register(Kr),await T.register(Jr);let te=new Ze;await te.start(),tr(),await T.register(f=>Gr(f,te)),await T.register(Vr),await T.register(f=>$r(f,te,process.env.ADAM_WEBHOOK_API_KEY)),await T.register(Qr),await T.register(Yr),await T.register(Xr);let Q=new nt;Qs(Q),await T.register(Ys),await T.register(Zr),await T.register(f=>vr(f,t.server.apiKey)),await T.register(xr),await T.register(Wt),xs(),Zs(),Q.startHealthMonitor();try{let f=Ve();for(let G of f)if(G.platform==="wechat"){let le=G.config;if(le.botToken){let Ie=new Js(G.id,le);Q.addChannel(G,Ie)}}}catch(f){_.error({error:f},"Failed to register WeChat adapters at startup")}let{host:Me,port:ce}=t.server;await T.listen({host:Me,port:ce}),_.info({host:Me,port:ce},"Server listening");let it=t.watchdog??Kt.watchdog;en(it,w,v,f=>{_.warn({alert:f},"Watchdog alert")}),ts(f=>{g.emit({type:"log_event",timestamp:f.time??Date.now(),level:f.level??"info",component:f.component??"adam",msg:f.msg??""})}),rn(q,{recursive:!0}),rn(ot(q,"logs"),{recursive:!0}),sn(ot(q,"adam.port"),String(ce)),t.server.apiKey&&sn(ot(q,"adam.key"),t.server.apiKey,{mode:384}),process.send?.({type:"ready",port:ce});let je=async()=>{_.info("Shutting down"),tn(),Ds(),er(),await Q.stopAll(),w.stop(),v.stop(),await te.stop(),await T.close(),mt();try{Ea(ot(q,"adam.key"))}catch{}process.exit(0)};process.on("SIGINT",()=>{je()}),process.on("SIGTERM",()=>{je()})}Da().catch(o=>{_.fatal(o,"Fatal error"),process.exit(1)});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{g as getComponentFilter,e as getLogLevel,c as getLogger,b as logger,a as onLogEvent,f as setComponentFilter,d as setLogLevel};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i,j,k,l,m,n,o}from"./chunk-TYR3QUCL.js";import"./chunk-62PXAOD6.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{m as DEFAULT_HYBRID_CONFIG,i as DEFAULT_SCORING_WEIGHTS,j as calculateRecency,k as calculateSmallvilleScore,n as cleanupMemories,d as countMemoriesByRole,a as createMemory,h as deleteMemory,b as getMemory,l as getRoleScoringWeights,e as listMemoriesByRole,g as searchByBM25,f as searchByVector,o as searchHybrid,c as updateMemoryRetrievalCount};
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b}from"./chunk-37OAKNKA.js";import"./chunk-FUBKGVWI.js";import"./chunk-62PXAOD6.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as CHAT_MANAGER_ROLE_ID,b as initializeDefaultRoles};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{d as a,e as b,f as c,g as d,h as e,i as f,j as g,l as h}from"./chunk-62PXAOD6.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";h();export{b as createRole,g as deleteRole,c as getRole,d as getRoleByName,f as listRoles,e as updateRole,a as validateAdditionalDirectories};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g,h}from"./chunk-5BAD3NCT.js";import"./chunk-FCV2DPZQ.js";export{a as MUTABLE_PATHS,b as RESTART_REQUIRED_PATHS,f as getNestedValue,d as getRuntimeConfig,c as initRuntimeConfig,g as isMutablePath,h as isRestartRequiredPath,e as updateMutableConfig};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a}from"./chunk-WGRTN6TX.js";import"./chunk-FCV2DPZQ.js";export{a as serverBus};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{c as a,d as b,e as c,f as d,g as e,h as f,i as g,j as h,k as i,l as j,m as k,n as l,o as m,p as n,q as o,r as p}from"./chunk-QOPUUA7O.js";import"./chunk-HMXDNPFE.js";import"./chunk-MMIO6BCA.js";import"./chunk-WGRTN6TX.js";import"./chunk-TYR3QUCL.js";import"./chunk-CV3ROBUM.js";import"./chunk-ZN5Q3YET.js";import"./chunk-5BAD3NCT.js";import"./chunk-62PXAOD6.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{p as _resetForTest,e as archiveSession,b as createSession,g as deleteSession,c as getActiveSession,d as getSession,m as getTimeoutPollerInterval,i as incrementMessageCount,n as initSessionManager,j as listSessions,f as restoreSession,o as shutdownSessionManager,k as startTimeoutPoller,l as stopTimeoutPoller,h as touchSession,a as warmCache};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{a,b,c,d,e,f,g}from"./chunk-TGQYM4TH.js";import"./chunk-W6JITSZF.js";import"./chunk-F2IS5LWD.js";import"./chunk-FCV2DPZQ.js";export{a as createTaskTemplate,g as deleteTaskTemplate,f as disableTaskTemplate,e as enableTaskTemplate,b as getTaskTemplate,d as listTaskTemplates,c as updateTaskTemplate};
|