adam-agent-server 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{adam-tools-RTCTINZI.js → adam-tools-BB7WQGVT.js} +1 -1
- package/dist/{approval-handler-SSKO2IGC.js → approval-handler-HK7GQPHU.js} +1 -1
- package/dist/{bree-engine-SQMSKGAP.js → bree-engine-25VACELK.js} +1 -1
- package/dist/{channels-WFZAONF3.js → channels-JEBBMFUQ.js} +1 -1
- package/dist/chunk-BREBCBG4.js +49 -0
- package/dist/chunk-D6WM2OQS.js +86 -0
- package/dist/{chunk-KMMC7BEF.js → chunk-DWMMWYLD.js} +1 -1
- package/dist/chunk-NXTTKAQX.js +3 -0
- package/dist/chunk-URW2DJQF.js +1 -0
- package/dist/{engine-6SFURLSL.js → engine-3PNNEZNK.js} +1 -1
- package/dist/index.js +13 -13
- package/dist/{outbound-gateway-UCB57NPJ.js → outbound-gateway-DZTXBUTP.js} +1 -1
- package/package.json +2 -1
- package/dist/chunk-2EP27EGS.js +0 -1
- package/dist/chunk-BQE7XAMQ.js +0 -86
- package/dist/chunk-DT2LX4XI.js +0 -49
- package/dist/chunk-LBLERTM4.js +0 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-NXTTKAQX.js";import"./chunk-PQ7KPALO.js";import"./chunk-FDWW245P.js";import"./chunk-L7JP7DUO.js";import"./chunk-PCSZW2PE.js";import"./chunk-SFUS33SO.js";import"./chunk-3DAK2XWP.js";import"./chunk-FCV2DPZQ.js";export{a as OutboundGateway,b as getOutboundGateway,c as isRecentlySent};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "adam-agent-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Goal-driven AI agent orchestration server with Role+Skill model, real-time streaming, and multi-channel delivery",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
"@fastify/websocket": "^11.0.0",
|
|
27
27
|
"better-sqlite3": "^11.0.0",
|
|
28
28
|
"bree": "^9.2.9",
|
|
29
|
+
"discord.js": "^14.16.0",
|
|
29
30
|
"chalk": "^5.0.0",
|
|
30
31
|
"commander": "^13.0.0",
|
|
31
32
|
"cron-parser": "^5.5.0",
|
package/dist/chunk-2EP27EGS.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{f as ne}from"./chunk-742NWPTQ.js";import{a as re,b,c as z,d as ie,e as se}from"./chunk-PQ7KPALO.js";import{c as f}from"./chunk-3DAK2XWP.js";import{z as c}from"zod/v4";import{v4 as Ut}from"uuid";import{randomUUID as ue}from"crypto";import We from"crypto";var oe="1.0.0",S="";function qe(e){let t=e.split(".").map(r=>parseInt(r,10)),i=t[0]??0,s=t[1]??0,n=t[2]??0;return(i&255)<<16|(s&255)<<8|n&255}var V=qe(oe),je=35e3,ae=15e3,ze=1e4;function P(){return{channel_version:oe}}function Ve(e){return e.endsWith("/")?e:`${e}/`}function Qe(){let e=We.randomBytes(4).readUInt32BE(0);return Buffer.from(String(e),"utf-8").toString("base64")}function Ge(e){let t={"Content-Type":"application/json",AuthorizationType:"ilink_bot_token","Content-Length":String(Buffer.byteLength(e.body,"utf-8")),"X-WECHAT-UIN":Qe(),"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};return e.token?.trim()&&(t.Authorization=`Bearer ${e.token.trim()}`),e.routeTag&&(t.SKRouteTag=e.routeTag),t}async function A(e){let t=Ve(e.baseUrl),i=new URL(e.endpoint,t),s=Ge({token:e.token,routeTag:e.routeTag,body:e.body}),n=new AbortController,r=setTimeout(()=>n.abort(),e.timeoutMs);try{let o=await fetch(i.toString(),{method:"POST",headers:s,body:e.body,signal:n.signal});clearTimeout(r);let a=await o.text();if(!o.ok)throw new Error(`${e.label} ${o.status}: ${a}`);return a}catch(o){throw clearTimeout(r),o}}async function de(e){let t=e.timeoutMs??je;try{let i=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getupdates",body:JSON.stringify({get_updates_buf:e.get_updates_buf??"",base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:t,label:"getUpdates"});return JSON.parse(i)}catch(i){if(i instanceof Error&&i.name==="AbortError")return{ret:0,msgs:[],get_updates_buf:e.get_updates_buf};throw i}}async function v(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendmessage",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"sendMessage"})}async function ce(e){await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/sendtyping",body:JSON.stringify({...e.body,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ze,label:"sendTyping"})}async function le(e){let t=await A({baseUrl:e.baseUrl,endpoint:"ilink/bot/getuploadurl",body:JSON.stringify({filekey:e.filekey,media_type:e.media_type,to_user_id:e.to_user_id,rawsize:e.rawsize,rawfilemd5:e.rawfilemd5,filesize:e.filesize,thumb_rawsize:e.thumb_rawsize,thumb_rawfilemd5:e.thumb_rawfilemd5,thumb_filesize:e.thumb_filesize,no_need_thumb:e.no_need_thumb,aeskey:e.aeskey,base_info:P()}),token:e.token,routeTag:e.routeTag,timeoutMs:e.timeoutMs??ae,label:"getUploadUrl"});return JSON.parse(t)}var Ke=5*6e4,He=35e3,ge="3",y=new Map;function Q(e){return Date.now()-e.startedAt<Ke}function Xe(){for(let[e,t]of y)Q(t)||y.delete(e)}async function pe(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_bot_qrcode?bot_type=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S};i&&(r.SKRouteTag=i);let o=await fetch(n.toString(),{headers:r});if(!o.ok){let a=await o.text().catch(()=>"(unreadable)");throw new Error(`Failed to fetch QR code: ${o.status} ${o.statusText} body=${a}`)}return await o.json()}async function Je(e,t,i){let s=e.endsWith("/")?e:`${e}/`,n=new URL(`ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(t)}`,s),r={"iLink-App-Id":S,"iLink-App-ClientVersion":String(V)};i&&(r.SKRouteTag=i);let o=new AbortController,a=setTimeout(()=>o.abort(),He);try{let d=await fetch(n.toString(),{headers:r,signal:o.signal});clearTimeout(a);let l=await d.text();if(!d.ok)throw new Error(`Failed to poll QR status: ${d.status} ${d.statusText}`);return JSON.parse(l)}catch(d){if(clearTimeout(a),d instanceof Error&&d.name==="AbortError")return{status:"wait"};throw d}}async function me(e){let t=e.accountId||ue();Xe();let i=y.get(t);if(!e.force&&i&&Q(i)&&i.qrcodeUrl)return{qrcodeUrl:i.qrcodeUrl,message:"QR code ready. Scan with WeChat.",sessionKey:t};if(!e.apiBaseUrl)return{message:"No baseUrl configured for this WeChat channel.",sessionKey:t};try{let s=e.botType||ge,n=await pe(e.apiBaseUrl,s,e.routeTag),r={sessionKey:t,id:ue(),qrcode:n.qrcode,qrcodeUrl:n.qrcode_img_content,startedAt:Date.now()};return y.set(t,r),{qrcodeUrl:n.qrcode_img_content,message:"Scan the QR code with WeChat to connect.",sessionKey:t}}catch(s){return{message:`Failed to start login: ${String(s)}`,sessionKey:t}}}var Ye=3;async function fe(e){let t=y.get(e.sessionKey);if(!t)return{connected:!1,message:"No active login session. Start QR login first."};if(!Q(t))return y.delete(e.sessionKey),{connected:!1,message:"QR code expired. Please start again."};let i=Math.max(e.timeoutMs??48e4,1e3),s=Date.now()+i,n=1;for(;Date.now()<s;){try{let r=await Je(e.apiBaseUrl,t.qrcode,e.routeTag);switch(t.status=r.status,r.status){case"wait":break;case"scaned":break;case"expired":{if(n++,n>Ye)return y.delete(e.sessionKey),{connected:!1,message:"Login timeout: QR expired multiple times."};try{let o=e.botType||ge,a=await pe(e.apiBaseUrl,o,e.routeTag);t.qrcode=a.qrcode,t.qrcodeUrl=a.qrcode_img_content,t.startedAt=Date.now()}catch(o){return y.delete(e.sessionKey),{connected:!1,message:`QR refresh failed: ${String(o)}`}}break}case"confirmed":return r.ilink_bot_id?(y.delete(e.sessionKey),{connected:!0,botToken:r.bot_token,accountId:r.ilink_bot_id,baseUrl:r.baseurl,userId:r.ilink_user_id,message:"Connected to WeChat successfully!"}):(y.delete(e.sessionKey),{connected:!1,message:"Login failed: server did not return bot ID."})}}catch(r){return y.delete(e.sessionKey),{connected:!1,message:`Login failed: ${String(r)}`}}await new Promise(r=>setTimeout(r,1e3))}return y.delete(e.sessionKey),{connected:!1,message:"Login timeout. Please try again."}}import k,{promises as Y}from"fs";import C from"path";import{homedir as Z}from"os";var O={IMAGE:1,VIDEO:2,FILE:3,VOICE:4},F={NONE:0,USER:1,BOT:2},m={NONE:0,TEXT:1,IMAGE:2,VOICE:3,FILE:4,VIDEO:5},N={NEW:0,GENERATING:1,FINISH:2},ye={TYPING:1,CANCEL:2};var Ze=f("channels"),G=-14,$=3600*1e3,R=new Map;function he(e){let t=Date.now()+$;R.set(e,t),Ze.info({channelId:e},`Session paused until ${new Date(t).toISOString()} (${$/1e3}s)`)}function L(e){let t=R.get(e);return t===void 0?!1:Date.now()>=t?(R.delete(e),!1):!0}function be(e){let t=R.get(e);if(t===void 0)return 0;let i=t-Date.now();return i<=0?(R.delete(e),0):i}function _e(e){R.delete(e)}import Ee from"fs";import Se from"path";import{homedir as at}from"os";import{createCipheriv as et,createDecipheriv as tt}from"crypto";function we(e,t){let i=et("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function xe(e,t){let i=tt("aes-128-ecb",t,null);return Buffer.concat([i.update(e),i.final()])}function Ie(e){return Math.ceil((e+1)/16)*16}function K(e,t){return`${t}/download?encrypted_query_param=${encodeURIComponent(e)}`}function Te(e){return`${e.cdnBaseUrl}/upload?encrypted_query_param=${encodeURIComponent(e.uploadParam)}&filekey=${encodeURIComponent(e.filekey)}`}var Wt=f("channels");function nt(e){let t=Buffer.from(e,"base64");if(t.length===16)return t;if(t.length===32&&/^[0-9a-fA-F]{32}$/.test(t.toString("ascii")))return Buffer.from(t.toString("ascii"),"hex");throw new Error(`aes_key must decode to 16 raw bytes or 32-char hex, got ${t.length} bytes`)}async function Ue(e){let t=await fetch(e);if(!t.ok)throw new Error(`CDN download ${t.status} ${t.statusText}`);return Buffer.from(await t.arrayBuffer())}async function M(e){let{encryptQueryParam:t,aesKeyBase64:i,cdnBaseUrl:s,fullUrl:n}=e,r=nt(i),o=n?.trim()||(t?K(t,s):null);if(!o)throw new Error("CDN download: need full_url or encrypt_query_param");let a=await Ue(o);return xe(a,r)}async function ke(e){let{encryptQueryParam:t,cdnBaseUrl:i,fullUrl:s}=e,n=s?.trim()||(t?K(t,i):null);if(!n)throw new Error("CDN download: need full_url or encrypt_query_param");return Ue(n)}var B=f("channels"),Re=24e3;function rt(e,t){let i=e.byteLength,s=44+i,n=Buffer.allocUnsafe(s),r=0;return n.write("RIFF",r),r+=4,n.writeUInt32LE(s-8,r),r+=4,n.write("WAVE",r),r+=4,n.write("fmt ",r),r+=4,n.writeUInt32LE(16,r),r+=4,n.writeUInt16LE(1,r),r+=2,n.writeUInt16LE(1,r),r+=2,n.writeUInt32LE(t,r),r+=4,n.writeUInt32LE(t*2,r),r+=4,n.writeUInt16LE(2,r),r+=2,n.writeUInt16LE(16,r),r+=2,n.write("data",r),r+=4,n.writeUInt32LE(i,r),r+=4,Buffer.from(e.buffer,e.byteOffset,e.byteLength).copy(n,r),n}async function Ce(e){try{let{decode:t}=await import("silk-wasm");B.debug(`silkToWav: decoding ${e.length} bytes of SILK`);let i=await t(e,Re);B.debug(`silkToWav: decoded duration=${i.duration}ms pcmBytes=${i.data.byteLength}`);let s=rt(i.data,Re);return B.debug(`silkToWav: WAV size=${s.length}`),s}catch(t){return B.warn(`silkToWav: transcode failed, will use raw silk err=${String(t)}`),null}}import it from"path";var st={".pdf":"application/pdf",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".txt":"text/plain",".csv":"text/csv",".zip":"application/zip",".tar":"application/x-tar",".gz":"application/gzip",".mp3":"audio/mpeg",".ogg":"audio/ogg",".wav":"audio/wav",".mp4":"video/mp4",".mov":"video/quicktime",".webm":"video/webm",".mkv":"video/x-matroska",".avi":"video/x-msvideo",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".bmp":"image/bmp"},ot={"image/jpeg":".jpg","image/jpg":".jpg","image/png":".png","image/gif":".gif","image/webp":".webp","image/bmp":".bmp","video/mp4":".mp4","video/quicktime":".mov","video/webm":".webm","video/x-matroska":".mkv","video/x-msvideo":".avi","audio/mpeg":".mp3","audio/ogg":".ogg","audio/wav":".wav","application/pdf":".pdf","application/zip":".zip","application/x-tar":".tar","application/gzip":".gz","text/plain":".txt","text/csv":".csv"};function D(e){let t=it.extname(e).toLowerCase();return st[t]??"application/octet-stream"}function Me(e){let t=e.split(";")[0].trim().toLowerCase();return ot[t]??".bin"}var U=f("channels"),Pe=100*1024*1024;function dt(e){return Me(e)??".bin"}async function E(e,t,i,s,n=Pe,r){if(e.length>n)throw new Error(`Media too large: ${e.length} bytes exceeds ${n} bytes`);let o=Se.join(at(),".adam","wechat","media",s,i);await Ee.promises.mkdir(o,{recursive:!0});let a;if(r&&/^[a-zA-Z0-9._-]+$/.test(r))a=r;else{let l=t?dt(t):".bin",u=Date.now(),p=Math.random().toString(36).slice(2,7);a=`${u}-${p}${l}`}let d=Se.join(o,a);return await Ee.promises.writeFile(d,e),U.debug(`saveMedia: saved ${e.length} bytes to ${d}`),d}async function Ae(e,t){let{cdnBaseUrl:i,channelId:s}=t;if(e.type===m.IMAGE){let n=e.image_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url)return null;let r=n.aeskey?Buffer.from(n.aeskey,"hex").toString("base64"):n.media?.aes_key;try{let o=r?await M({encryptQueryParam:n.media?.encrypt_query_param,aesKeyBase64:r,cdnBaseUrl:i,fullUrl:n.media?.full_url}):await ke({encryptQueryParam:n.media?.encrypt_query_param,cdnBaseUrl:i,fullUrl:n.media?.full_url});return{path:await E(o,"image/png","inbound",s),mimeType:"image/png",type:"image"}}catch(o){return U.error({channelId:s},`Image download/decrypt failed: ${String(o)}`),null}}if(e.type===m.VOICE){let n=e.voice_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=await Ce(r);if(o){let a=await E(o,"audio/wav","inbound",s);return U.debug(`Voice: saved WAV to ${a}`),{path:a,mimeType:"audio/wav",type:"audio"}}else{let a=await E(r,"audio/silk","inbound",s);return U.debug(`Voice: silk transcode unavailable, saved raw SILK to ${a}`),{path:a,mimeType:"audio/silk",type:"audio"}}}catch(r){return U.error({channelId:s},`Voice download/transcode failed: ${String(r)}`),null}}if(e.type===m.FILE){let n=e.file_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url}),o=D(n.file_name??"file.bin");return{path:await E(r,o,"inbound",s,Pe,n.file_name),mimeType:o,type:"file"}}catch(r){return U.error({channelId:s},`File download failed: ${String(r)}`),null}}if(e.type===m.VIDEO){let n=e.video_item;if(!n?.media?.encrypt_query_param&&!n?.media?.full_url||!n?.media?.aes_key)return null;try{let r=await M({encryptQueryParam:n.media.encrypt_query_param,aesKeyBase64:n.media.aes_key,cdnBaseUrl:i,fullUrl:n.media.full_url});return{path:await E(r,"video/mp4","inbound",s),mimeType:"video/mp4",type:"video"}}catch(r){return U.error({channelId:s},`Video download failed: ${String(r)}`),null}}return null}import ut from"path";import H from"crypto";import ct from"fs/promises";var I=f("channels"),W=3;async function lt(e){let{buf:t,uploadFullUrl:i,uploadParam:s,filekey:n,cdnBaseUrl:r,label:o,aeskey:a}=e,d=we(t,a),l=i?.trim(),u;if(l)u=l;else if(s)u=Te({cdnBaseUrl:r,uploadParam:s,filekey:n});else throw new Error(`${o}: CDN upload URL missing (need upload_full_url or upload_param)`);I.debug(`${o}: CDN POST url=${u} ciphertextSize=${d.length}`);let p,_;for(let h=1;h<=W;h++)try{let g=await fetch(u,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:new Uint8Array(d)});if(g.status>=400&&g.status<500){let x=g.headers.get("x-error-message")??await g.text();throw I.error(`${o}: CDN client error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload client error ${g.status}: ${x}`)}if(g.status!==200){let x=g.headers.get("x-error-message")??`status ${g.status}`;throw I.error(`${o}: CDN server error attempt=${h} status=${g.status} errMsg=${x}`),new Error(`CDN upload server error: ${x}`)}if(p=g.headers.get("x-encrypted-param")??void 0,!p)throw I.error(`${o}: CDN response missing x-encrypted-param header attempt=${h}`),new Error("CDN upload response missing x-encrypted-param header");I.debug(`${o}: CDN upload success attempt=${h}`);break}catch(g){if(_=g,g instanceof Error&&g.message.includes("client error"))throw g;h<W?I.warn(`${o}: attempt ${h} failed, retrying... err=${String(g)}`):I.error(`${o}: all ${W} attempts failed err=${String(g)}`)}if(!p)throw _ instanceof Error?_:new Error(`CDN upload failed after ${W} attempts`);return{downloadParam:p}}async function X(e){let{filePath:t,toUserId:i,opts:s,cdnBaseUrl:n,mediaType:r,label:o}=e,a=await ct.readFile(t),d=a.length,l=H.createHash("md5").update(a).digest("hex"),u=Ie(d),p=H.randomBytes(16).toString("hex"),_=H.randomBytes(16);I.debug(`${o}: file=${t} rawsize=${d} filesize=${u} md5=${l} filekey=${p}`);let h=await le({...s,filekey:p,media_type:r,to_user_id:i,rawsize:d,rawfilemd5:l,filesize:u,no_need_thumb:!0,aeskey:_.toString("hex")}),g=h.upload_full_url?.trim(),x=h.upload_param;if(!g&&!x)throw new Error(`${o}: getUploadUrl returned no upload URL (need upload_full_url or upload_param)`);let{downloadParam:De}=await lt({buf:a,uploadFullUrl:g||void 0,uploadParam:x??void 0,filekey:p,cdnBaseUrl:n,aeskey:_,label:`${o}[orig filekey=${p}]`});return{filekey:p,downloadEncryptedQueryParam:De,aeskey:_.toString("hex"),fileSize:d,fileSizeCiphertext:u}}async function ve(e){return X({...e,mediaType:O.IMAGE,label:"uploadImageToWeixin"})}async function Oe(e){return X({...e,mediaType:O.VIDEO,label:"uploadVideoToWeixin"})}async function Fe(e){return X({...e,mediaType:O.FILE,label:"uploadFileAttachmentToWeixin"})}var q=f("channels");function gt(){return`adam-wechat-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function pt(e){let t=e;return t=t.replace(/```[^\n]*\n?([\s\S]*?)```/g,(i,s)=>s.trim()),t=t.replace(/!\[[^\]]*\]\([^)]*\)/g,""),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/^\|[\s:|-]+\|$/gm,""),t=t.replace(/^\|(.+)\|$/gm,(i,s)=>s.split("|").map(n=>n.trim()).join(" ")),t}async function J(e){let{to:t,text:i,mediaItem:s,opts:n,label:r}=e,o=[],a=pt(i);a&&o.push({type:m.TEXT,text_item:{text:a}}),o.push(s);let d="";for(let l of o){d=gt();let u={msg:{from_user_id:"",to_user_id:t,client_id:d,message_type:F.BOT,message_state:N.FINISH,item_list:[l],context_token:n.contextToken}};await v({baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag,body:u})}return q.debug(`${r}: sent to=${t} messageId=${d}`),{messageId:d}}async function mt(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.IMAGE,image_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},mid_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendImageMessage"})}async function ft(e){let{to:t,text:i,uploaded:s,opts:n}=e,r={type:m.VIDEO,video_item:{media:{encrypt_query_param:s.downloadEncryptedQueryParam,aes_key:Buffer.from(s.aeskey).toString("base64"),encrypt_type:1},video_size:s.fileSizeCiphertext}};return J({to:t,text:i,mediaItem:r,opts:n,label:"sendVideoMessage"})}async function yt(e){let{to:t,text:i,fileName:s,uploaded:n,opts:r}=e,o={type:m.FILE,file_item:{media:{encrypt_query_param:n.downloadEncryptedQueryParam,aes_key:Buffer.from(n.aeskey).toString("base64"),encrypt_type:1},file_name:s,len:String(n.fileSize)}};return J({to:t,text:i,mediaItem:o,opts:r,label:"sendFileMessage"})}async function Ne(e){let{filePath:t,to:i,text:s,opts:n,cdnBaseUrl:r}=e,o=D(t),a={baseUrl:n.baseUrl,token:n.token,routeTag:n.routeTag};if(o.startsWith("video/")){q.debug(`sendWeixinMediaFile: uploading video filePath=${t} to=${i}`);let u=await Oe({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return ft({to:i,text:s,uploaded:u,opts:n})}if(o.startsWith("image/")){q.debug(`sendWeixinMediaFile: uploading image filePath=${t} to=${i}`);let u=await ve({filePath:t,toUserId:i,opts:a,cdnBaseUrl:r});return mt({to:i,text:s,uploaded:u,opts:n})}let d=ut.basename(t);q.debug(`sendWeixinMediaFile: uploading file attachment filePath=${t} name=${d} to=${i}`);let l=await Fe({filePath:t,fileName:d,toUserId:i,opts:a,cdnBaseUrl:r});return yt({to:i,text:s,fileName:d,uploaded:l,opts:n})}var w=f("channels"),ee=new Map;function Le(e){return C.join(Z(),".adam","wechat",`${e}.context-tokens.json`)}function ht(e){let t=Le(e);try{let i=k.readFileSync(t,"utf-8"),s=JSON.parse(i);for(let[n,r]of Object.entries(s))typeof r=="string"&&r&&ee.set(`${e}:${n}`,r);w.debug({channelId:e,count:Object.keys(s).length},"Restored context tokens from disk")}catch{}}function bt(e,t,i){let s=Le(e);try{let n={};try{let o=k.readFileSync(s,"utf-8");n=JSON.parse(o)}catch{}n[t]=i;let r=C.dirname(s);k.mkdirSync(r,{recursive:!0}),k.writeFileSync(s,JSON.stringify(n),"utf-8")}catch(n){w.warn({channelId:e,userId:t},`Failed to persist context token: ${String(n)}`)}}function _t(e,t,i){ee.set(`${e}:${t}`,i),bt(e,t,i)}function $e(e,t){return ee.get(`${e}:${t}`)}function Be(e){return C.join(Z(),".adam","wechat",`${e}.sync`)}function wt(e){try{return k.readFileSync(Be(e),"utf-8")}catch{return""}}function xt(e,t){let i=Be(e);k.mkdirSync(C.dirname(i),{recursive:!0}),k.writeFileSync(i,t,"utf-8")}var It=0;function Tt(){return`adam-wechat-${Date.now()}-${++It}`}var j=class{platform="wechat";id;config;status="disconnected";messageHandler=null;pollAbort=null;getUpdatesBuf="";constructor(t,i){if(this.id=t,!i.baseUrl)throw new Error("WeChat adapter requires baseUrl");this.config=i}async connect(){if(!this.config.botToken)throw new Error("WeChat adapter requires botToken. Complete QR login first.");this.status="connecting",this.getUpdatesBuf=wt(this.id),ht(this.id),this.pollAbort=new AbortController,this.status="connected",w.info({channelId:this.id},"WeChat adapter connected, starting long-poll"),this.startLongPoll()}async disconnect(){this.pollAbort&&(this.pollAbort.abort(),this.pollAbort=null),this.status="disconnected",w.info({channelId:this.id},"WeChat adapter disconnected")}getStatus(){return this.status==="connected"&&L(this.id)?"error":this.status}async sendMessage(t,i){if(L(this.id)){let o=Math.ceil(be(this.id)/6e4);throw new Error(`WeChat session paused, ${o} min remaining. Re-scan QR to reconnect.`)}let s=Tt(),n=$e(this.id,t),r=this.config.cdnBaseUrl??this.config.baseUrl;if(i.mediaUrl)try{let o=await fetch(i.mediaUrl);if(!o.ok)throw new Error(`Failed to fetch media: ${o.status}`);let a=Buffer.from(await o.arrayBuffer()),d=C.join(Z(),".adam","wechat","media","outbound-tmp");await Y.mkdir(d,{recursive:!0});let l=this.getExtensionFromMediaType(i.mediaType),u=C.join(d,`${Date.now()}-${Math.random().toString(36).slice(2,7)}${l}`);await Y.writeFile(u,a);let p=await Ne({filePath:u,to:t,text:i.content??"",opts:{baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,contextToken:n},cdnBaseUrl:r});return await Y.unlink(u).catch(()=>{}),p.messageId}catch(o){throw w.error({channelId:this.id},`sendMessage media handling failed: ${String(o)}`),o}return await v({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{msg:{from_user_id:"",to_user_id:t,client_id:s,message_type:F.BOT,message_state:N.FINISH,item_list:i.content?[{type:m.TEXT,text_item:{text:i.content}}]:void 0,context_token:n}}}),s}onMessage(t){this.messageHandler=t}async sendTypingIndicator(t){if(L(this.id))return;let i=$e(this.id,t);try{await ce({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,body:{ilink_user_id:t,status:ye.TYPING}})}catch{}}updateConfig(t){Object.assign(this.config,t)}async startLongPoll(){let t=this.pollAbort?.signal,i=0,s=3,n=3e4,r=2e3;for(;!t?.aborted;)try{let o=await de({baseUrl:this.config.baseUrl,token:this.config.botToken,routeTag:this.config.routeTag,get_updates_buf:this.getUpdatesBuf});if(o.ret===G||o.errcode===G){he(this.id),this.status="error",w.error({channelId:this.id},"Session expired (errcode=-14), pausing for 1 hour"),await this.sleep($,t),_e(this.id),this.status="connected";continue}if(o.ret!==void 0&&o.ret!==0||o.errcode!==void 0&&o.errcode!==0){i++,w.error({channelId:this.id,ret:o.ret,errcode:o.errcode},"getUpdates API error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t);continue}i=0,o.get_updates_buf&&(this.getUpdatesBuf=o.get_updates_buf,xt(this.id,o.get_updates_buf));for(let d of o.msgs??[])await this.processInbound(d)}catch(o){if(t?.aborted)return;i++,w.error({channelId:this.id,error:o},"getUpdates error"),i>=s?(i=0,await this.sleep(n,t)):await this.sleep(r,t)}}async processInbound(t){if(!this.messageHandler)return;t.context_token&&t.from_user_id&&_t(this.id,t.from_user_id??"",t.context_token);let i="",s,n=[];for(let a of t.item_list??[])a.type===m.TEXT&&a.text_item?.text&&(i+=a.text_item.text),a.type===m.IMAGE&&(s="image",n.push(a)),a.type===m.VOICE&&(s="audio",n.push(a),a.voice_item?.text&&!i&&(i=a.voice_item.text)),a.type===m.FILE&&(s="file",n.push(a)),a.type===m.VIDEO&&(s="video",n.push(a));if(!i&&!s)return;let r;if(n.length>0){let a=this.config.cdnBaseUrl??this.config.baseUrl;try{let d=await Ae(n[0],{cdnBaseUrl:a,channelId:this.id});d&&(r=d.path,s=d.type)}catch(d){w.error({channelId:this.id},`Media download failed: ${String(d)}`)}}let o={channelId:this.id,platform:"wechat",chatId:t.from_user_id??"",senderId:t.from_user_id??"",content:i,mediaType:s,mediaPath:r,isGroup:!1,timestamp:t.create_time_ms??Date.now(),raw:t};this.messageHandler(o)}getExtensionFromMediaType(t){switch(t){case"image":return".png";case"video":return".mp4";case"audio":return".mp3";default:return".bin"}}sleep(t,i){return new Promise((s,n)=>{let r=setTimeout(s,t);i?.addEventListener("abort",()=>{clearTimeout(r),n(new Error("aborted"))},{once:!0})})}};var T=c.object({id:c.string().uuid()}),kt=c.object({name:c.string().min(1,"name is required"),platform:c.string().min(1,"platform is required"),config:c.record(c.string(),c.unknown()),enabled:c.boolean().optional().default(!0),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),Rt=c.object({name:c.string().min(1).optional(),enabled:c.boolean().optional(),config:c.record(c.string(),c.unknown()).optional(),linkedRoleId:c.string().optional(),allowedChatIds:c.array(c.string()).optional()}),te;function On(e){te=e}function Fn(){return te}async function Nn(e){let t=te;e.get("/channels",{schema:{tags:["Channels"],summary:"List channels",querystring:{type:"object",properties:{enabled:{type:"boolean"}}}}},async(i,s)=>({channels:ie(i.query.enabled)})),e.post("/channels",{schema:{tags:["Channels"],summary:"Create a channel",body:{type:"object",required:["name","platform","config"],properties:{name:{type:"string",minLength:1},platform:{type:"string",minLength:1},config:{type:"object"},enabled:{type:"boolean"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=kt.safeParse(i.body);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let{name:r,platform:o,config:a,enabled:d,linkedRoleId:l,allowedChatIds:u}=n.data,p={id:Ut(),name:r,platform:o,enabled:d,status:"disconnected",config:a,linkedRoleId:l,allowedChatIds:u,createdAt:Date.now(),messageCount:0};return re(p),s.status(201).send({channel:p})}),e.get("/channels/:id",{schema:{tags:["Channels"],summary:"Get channel by ID",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?{channel:r}:s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.patch("/channels/:id",{schema:{tags:["Channels"],summary:"Update channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{name:{type:"string"},enabled:{type:"boolean"},config:{type:"object"},linkedRoleId:{type:"string"},allowedChatIds:{type:"array",items:{type:"string"}}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let o=Rt.safeParse(i.body);return o.success?(z(r.id,o.data),{channel:b(r.id)}):s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(o.error)})}),e.delete("/channels/:id",{schema:{tags:["Channels"],summary:"Delete channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);return r?(se(r.id),s.status(204).send()):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.post("/channels/:id/connect",{schema:{tags:["Channels"],summary:"Connect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(!t.hasAdapter(r.id))return s.status(400).send({code:"NO_ADAPTER",message:"No adapter registered for this channel. Install the appropriate adapter first."});try{return await t.connectChannel(r.id),{channelId:r.id,status:"connected"}}catch(o){return s.status(500).send({code:"CONNECT_FAILED",message:String(o)})}}),e.post("/channels/:id/disconnect",{schema:{tags:["Channels"],summary:"Disconnect channel",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});if(!t)return s.status(501).send({code:"NOT_IMPLEMENTED",message:"Channel manager not initialized"});let r=b(n.data.id);return r?(await t.disconnectChannel(r.id),{channelId:r.id,status:"disconnected"}):s.status(404).send({code:"NOT_FOUND",message:"Channel not found"})}),e.get("/channels/:id/messages",{schema:{tags:["Channels"],summary:"Get channel message history",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(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});let{limit:o=50,offset:a=0}=i.query;return{messages:ne(r.id,o,a)}}),e.post("/channels/:id/wechat/qr-start",{schema:{tags:["WeChat"],summary:"Start WeChat QR login",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config;return await me({apiBaseUrl:o.baseUrl,routeTag:o.routeTag})}),e.post("/channels/:id/wechat/qr-wait",{schema:{tags:["WeChat"],summary:"Wait for WeChat QR scan",params:{type:"object",required:["id"],properties:{id:{type:"string",format:"uuid"}}},body:{type:"object",properties:{sessionKey:{type:"string"},timeoutMs:{type:"number"}}}}},async(i,s)=>{let n=T.safeParse(i.params);if(!n.success)return s.status(400).send({code:"VALIDATION_ERROR",message:c.prettifyError(n.error)});let r=b(n.data.id);if(!r)return s.status(404).send({code:"NOT_FOUND",message:"Channel not found"});if(r.platform!=="wechat")return s.status(400).send({code:"INVALID_PLATFORM",message:"Channel is not a WeChat channel"});let o=r.config,{sessionKey:a,timeoutMs:d}=i.body??{},l=await fe({sessionKey:a??"",apiBaseUrl:o.baseUrl,timeoutMs:d??12e4,routeTag:o.routeTag});if(l.connected&&l.botToken){let u={...o,botToken:l.botToken,accountId:l.accountId,baseUrl:l.baseUrl??o.baseUrl,userId:l.userId};if(z(r.id,{config:u}),t){let p=new j(r.id,u),_=b(r.id);_&&await t.addChannel(_,p)}}return{connected:l.connected,accountId:l.accountId,message:l.message}})}export{j as a,On as b,Fn as c,Nn as d};
|
package/dist/chunk-BQE7XAMQ.js
DELETED
|
@@ -1,86 +0,0 @@
|
|
|
1
|
-
import{a as ue}from"./chunk-5JLMSNIW.js";import{b as Ge,c as Se,e as Ve}from"./chunk-IXF3XBGX.js";import{b as ae}from"./chunk-AXMXXUPO.js";import{a as tt,c as Me,e as rt}from"./chunk-KICPHTI2.js";import{j as _e}from"./chunk-FUGJMHY4.js";import{d as Re}from"./chunk-PQ7KPALO.js";import{a as Ke}from"./chunk-2GXYBWLS.js";import{a as Be}from"./chunk-WZOMGJSY.js";import{a as ce,b as _,c as de,d as Ze,e as et}from"./chunk-WXN3PSVX.js";import{a as se,b as v,c as F,d as A}from"./chunk-L7426WNY.js";import{a as ke}from"./chunk-L7JP7DUO.js";import{a as We,b as Te,c as Je,g as qe,j as He}from"./chunk-HAWA62R2.js";import{a as Ye,b as B,c as ze,f as Qe,g as Xe}from"./chunk-VF6GJGD6.js";import{d as k,g as je}from"./chunk-FYDFMYUP.js";import{a as Fe,b as le,e as Ie,f as V}from"./chunk-U36NBCR3.js";import{e as $e,f as T,h as U,i as G,j as Oe,k as we,l as ie}from"./chunk-XNWZZYAV.js";import{b,d as oe}from"./chunk-PCSZW2PE.js";import{c as I,d as Ue}from"./chunk-3DAK2XWP.js";import{c as Dt,e as At,f as x}from"./chunk-FCV2DPZQ.js";var wt={};At(wt,{getGlobalEnabledState:()=>z,getInstalledPlugin:()=>Le,getPluginManifest:()=>Q,listInstalledPlugins:()=>C,listMarketplaceSources:()=>Ce,resolvePluginPaths:()=>Ee,scanDirectoryConfig:()=>X});import{existsSync as E,readFileSync as K,readdirSync as yt}from"fs";import{join as y}from"path";import vt from"os";function j(e){try{if(!E(e))return null;let t=K(e,"utf-8");return JSON.parse(t)}catch{return null}}function z(){return j(Xt())?.enabledPlugins??{}}function Q(e){let t=e;function r(n,o){let s={};try{if(!E(n))return s;let l=K(n,"utf-8").replace(/^```yaml\r?\n/,"").replace(/^```\r?\n/,"");for(let u of o){let d=new RegExp(`^${u}:\\s*(.+)$`,"m"),p=l.match(d);p&&(s[u]=p[1].trim())}}catch{}return s}try{let n={name:"",skills:[],agents:[],mcpServers:[],hooks:[],lspServers:[]},o=y(t,".claude-plugin","plugin.json");if(E(o))try{let d=JSON.parse(K(o,"utf-8"));n.name=d.name??"",n.version=d.version,n.description=d.description,Array.isArray(d.lspServers)&&(n.lspServers=d.lspServers),Array.isArray(d.mcpServers)&&(n.mcpServers=d.mcpServers),Array.isArray(d.hooks)&&(n.hooks=d.hooks)}catch{}let s=y(t,"skills");if(E(s)){let d=yt(s,{withFileTypes:!0});for(let p of d){if(!p.isDirectory()&&!p.isSymbolicLink())continue;let g=y(s,p.name,"SKILL.md"),f=r(g,["name","description"]);f.name&&n.skills.push({name:f.name,description:f.description??""})}}let i=y(t,"agents");if(E(i)){let d=yt(i,{withFileTypes:!0});for(let p of d){if(!p.isFile()||!p.name.endsWith(".md"))continue;let g=r(y(i,p.name),["name","description"]);g.name&&n.agents.push({name:g.name,description:g.description??""})}}let l=y(t,".mcp.json");if(E(l))try{let d=JSON.parse(K(l,"utf-8"));d.mcpServers&&typeof d.mcpServers=="object"&&(n.mcpServers=Object.keys(d.mcpServers))}catch{}let u=y(t,"hooks","hooks.json");if(E(u))try{let d=JSON.parse(K(u,"utf-8"));Array.isArray(d)&&(n.hooks=d.map(p=>typeof p=="object"&&p!==null&&"event"in p?String(p.event):String(p)))}catch{}return n}catch{return null}}function C(e){let t=j(xe());if(!t?.plugins)return[];let r=z(),n=[];for(let[o,s]of Object.entries(t.plugins))if(!(!Array.isArray(s)||s.length===0))for(let i of s){let l=i.scope??"user";e?.scope&&l!==e.scope||e?.projectPath&&i.projectPath!==e.projectPath||n.push({id:o,name:o.split("@")[0],version:i.version??"",scope:l,projectPath:i.projectPath,installPath:i.installPath??y(Y(),o),enabled:r[o]??i.enabled??!0,installedAt:i.installedAt??"",lastUpdated:i.lastUpdated??""})}return n}function Le(e){let t=j(xe());if(!t?.plugins?.[e])return null;let r=t.plugins[e];if(!Array.isArray(r)||r.length===0)return null;let n=r[0],o=z();return{id:e,name:e.split("@")[0],version:n.version??"",scope:n.scope??"user",projectPath:n.projectPath,installPath:n.installPath??y(Y(),e),enabled:o[e]??n.enabled??!0,installedAt:n.installedAt??"",lastUpdated:n.lastUpdated??""}}function Ee(e){let t=j(xe()),r=new Map;for(let n of e){let o=t?.plugins?.[n];Array.isArray(o)&&o.length>0&&r.set(n,o[0].installPath??y(Y(),n))}return r}function Ce(){return j(Qt())?.marketplaces??[]}function X(e){let t=y(e,".claude","settings.json"),r=j(t);return{enabledPlugins:r?.enabledPlugins??{},mcpServers:r?.mcpServers??{},allowedTools:r?.allowedTools??[],disallowedTools:r?.disallowedTools??[]}}var Y,xe,Qt,Xt,ye=Dt(()=>{"use strict";Y=()=>y(vt.homedir(),".claude","plugins"),xe=()=>y(Y(),"installed_plugins.json"),Qt=()=>y(Y(),"known_marketplaces.json"),Xt=()=>y(vt.homedir(),".claude","settings.json")});import{createSdkMcpServer as cr,tool as m}from"@anthropic-ai/claude-agent-sdk";import{z as a}from"zod";ie();V();import{v4 as J}from"uuid";oe();function Nt(e){return{id:e.id,goalId:e.goal_id,level:e.level,parentId:e.parent_id??void 0,name:e.name,description:e.description??void 0,weight:e.weight,calibrationFactor:e.calibration_factor,createdAt:e.created_at}}function W(e){b().prepare(`
|
|
2
|
-
INSERT INTO metric_tree (id, goal_id, level, parent_id, name, description,
|
|
3
|
-
weight, calibration_factor, created_at)
|
|
4
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
5
|
-
`).run(e.id,e.goalId,e.level,e.parentId??null,e.name,e.description??null,e.weight,e.calibrationFactor,e.createdAt)}function nt(e){return b().prepare("SELECT * FROM metric_tree WHERE goal_id = ? ORDER BY level, created_at").all(e).map(Nt)}var jt=I("goal-manager");async function un(e){let t;try{let n=JSON.parse(e);t={name:n.name??"",description:n.description,metric:n.metric??"",targetValue:n.targetValue??0,currentValue:n.currentValue??0,deadline:n.deadline??0,budget:n.budget??0,roleId:n.roleId??"engineer",status:"active"}}catch{t=await $t(e)}let r=Ot(t);return{goalState:t,validationResult:r,rawInput:e}}async function $t(e){let t=`Extract SMART goal fields from this natural language input.
|
|
6
|
-
|
|
7
|
-
Input: "${e}"
|
|
8
|
-
|
|
9
|
-
Respond ONLY with a JSON object:
|
|
10
|
-
{
|
|
11
|
-
"name": "short goal name (max 100 chars)",
|
|
12
|
-
"description": "detailed description of what the goal aims to achieve",
|
|
13
|
-
"metric": "measurable metric name (e.g. completion, reports_written, accuracy_score)",
|
|
14
|
-
"targetValue": <number, the target to reach>,
|
|
15
|
-
"deadline_days": <number, days from now to complete>,
|
|
16
|
-
"budget": <number, estimated budget in USD>,
|
|
17
|
-
"role": "<best matching role: engineer | analyst | content_creator | reviewer>"
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
Rules:
|
|
21
|
-
- name: concise, actionable title
|
|
22
|
-
- metric: quantifiable measure of success; use "completion" if the goal is binary (done/not done)
|
|
23
|
-
- targetValue: realistic target for the metric; use 1 for binary goals
|
|
24
|
-
- deadline_days: reasonable timeframe; default 7 if unclear
|
|
25
|
-
- budget: estimated cost in USD; default 5 if unclear
|
|
26
|
-
- role: match to the nature of work (research=analyst, writing=content_creator, coding=engineer, review=reviewer)`;try{let n=(await ue(t,"You extract structured SMART goal fields from natural language. Reply with only valid JSON.")).match(/\{[\s\S]*\}/);if(n){let o=JSON.parse(n[0]),s=o.deadline_days??7;return{name:(o.name??e.slice(0,100)).slice(0,100),description:o.description??e,metric:o.metric??"completion",targetValue:o.targetValue??1,currentValue:0,deadline:Date.now()+s*24*60*60*1e3,budget:o.budget??5,roleId:o.roleId??"engineer",status:"active"}}}catch(r){jt.warn({error:r},"LLM goal parsing failed, using fallback")}return{name:e.trim().slice(0,100),description:e.trim(),metric:"completion",targetValue:1,currentValue:0,deadline:Date.now()+10080*60*1e3,budget:5,roleId:"engineer",status:"active"}}function Ot(e){let t=[],r=[];return(!e.name||e.name.trim().length===0)&&t.push("S: name must be non-empty"),(!e.description||e.description.trim().length===0)&&t.push("S: description must be non-empty"),(!e.metric||e.metric.trim().length===0)&&t.push("M: metric must be specified"),e.targetValue<=0&&t.push("A: targetValue must be > 0"),(!e.roleId||e.roleId.trim().length===0)&&t.push("R: roleId must be non-empty"),e.deadline<=Date.now()&&t.push("T: deadline must be in the future"),e.budget<=0&&r.push("budget is zero or negative; goal will have no spending limit"),{isValid:t.length===0,errors:t,warnings:r}}function pn(e,t,r){let n=J(),o=Date.now(),s={id:n,name:e.name,description:e.description,roleId:e.roleId,metricType:e.metric,targetValue:e.targetValue,currentValue:e.currentValue,deadline:e.deadline,budgetUsd:e.budget,status:e.status,createdAt:o,deliverTo:t,reportTo:r};return ce(s),s}function ot(e,t){let r=Date.now(),n=[],o={id:J(),goalId:e,level:"L0",name:`${t}_goal_progress`,description:`Goal-level ${t} progress (monthly)`,weight:1,calibrationFactor:1,createdAt:r};n.push(o),W(o);let s={id:J(),goalId:e,level:"L1",parentId:o.id,name:`${t}_weekly_trend`,description:`Weekly trend for ${t}`,weight:.8,calibrationFactor:1,createdAt:r};n.push(s),W(s);let i={id:J(),goalId:e,level:"L2",parentId:s.id,name:`${t}_daily_process`,description:`Daily process metric for ${t}`,weight:.6,calibrationFactor:1,createdAt:r};n.push(i),W(i);let l={id:J(),goalId:e,level:"L3",parentId:i.id,name:`${t}_per_task`,description:`Per-task instant metric for ${t}`,weight:.4,calibrationFactor:1,createdAt:r};return n.push(l),W(l),n}var pe=class{static collect(t,r){let n=v(t);if(!n)return this.emptyMetrics(t,r);let o=ae(t,500,0),s=n.completedAt&&n.startedAt?n.completedAt-n.startedAt:0,i=new Set,l=0,u=0;for(let p of o)p.type==="tool_call"&&p.toolName&&i.add(p.toolName),p.type==="error"&&l++,p.type==="approval_request"&&u++;let d={taskId:t,goalId:r,timestamp:Date.now(),durationMs:s,costUsd:n.costUsd??0,turns:n.numTurns??0,toolCount:i.size,errorCount:l,approvalCount:u,rawScore:0,isComplete:n.status==="completed"};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(t){let n=1-Math.min(t.durationMs/6e5,1),s=1-Math.min(t.costUsd/5,1),l=1-Math.min(t.turns/50,1),u;t.toolCount>=3&&t.toolCount<=15?u=1:t.toolCount<3?u=t.toolCount/3:u=Math.max(0,1-(t.toolCount-15)/15);let d=t.errorCount===0?1:Math.max(0,1-t.errorCount*.2),p=Math.min(1,.5+t.approvalCount*.25);return .3*n+.2*s+.2*l+.1*u+.15*d+.05*p}static cache=new Map;static persist(t){this.cache.set(t.taskId,t)}static getCached(t){return this.cache.get(t)}static clearCache(){this.cache.clear()}static emptyMetrics(t,r){return{taskId:t,goalId:r,timestamp:Date.now(),durationMs:0,costUsd:0,turns:0,toolCount:0,errorCount:0,approvalCount:0,rawScore:0,isComplete:!1}}};oe();function Ft(e){return{id:e.id,strategyId:e.strategy_id,goalId:e.goal_id,taskId:e.task_id??void 0,reward:e.reward??void 0,metricL2Score:e.metric_l2_score??void 0,metricL3Score:e.metric_l3_score??void 0,context:e.context??void 0,completedAt:e.completed_at}}function st(e){b().prepare(`
|
|
27
|
-
INSERT INTO trials (id, strategy_id, goal_id, task_id, reward,
|
|
28
|
-
metric_l2_score, metric_l3_score, context, completed_at)
|
|
29
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
30
|
-
`).run(e.id,e.strategyId,e.goalId,e.taskId??null,e.reward??null,e.metricL2Score??null,e.metricL3Score??null,e.context??null,e.completedAt)}function at(e,t=100){return b().prepare("SELECT * FROM trials WHERE goal_id = ? ORDER BY completed_at DESC LIMIT ?").all(e,t).map(Ft)}var me=class{static collect(t){let r=_(t);if(!r)return this.emptyMetrics(t);let n=Date.now(),o=r.targetValue>0?Math.min(r.currentValue/r.targetValue,1):0,s=Math.max(0,(r.deadline-n)/(1e3*60*60*24)),i=this.calculateBudgetSpent(t),l=r.budgetUsd>0?Math.max(0,1-i/r.budgetUsd):1,u=this.calculateExpectedCompletion(r),d={goalId:t,metricType:r.metricType,targetValue:r.targetValue,currentValue:r.currentValue,progressPct:o,deadlineRemainingDays:s,budgetRemainingPct:l,expectedCompletionPct:u,rawScore:0};return d.rawScore=this.computeRawScore(d),d}static computeRawScore(t){let r=Math.min(t.progressPct,1),n;t.expectedCompletionPct>=1?n=1:t.expectedCompletionPct>=.8?n=.5+(t.expectedCompletionPct-.8)*2.5:n=t.expectedCompletionPct*.625;let o=t.budgetRemainingPct;return .5*r+.3*n+.2*o}static calculateExpectedCompletion(t){let r=Date.now(),n=t.deadline-t.createdAt,o=r-t.createdAt;if(n<=0)return 0;let s=o/n;if(s<.1)return .5;let i=t.targetValue>0?t.currentValue/t.targetValue:0;return s>0?i/s:0}static calculateBudgetSpent(t){let r=at(t,1e3),n=0,o=new Set;for(let s of r)if(s.taskId&&!o.has(s.taskId)){o.add(s.taskId);let i=v(s.taskId);i?.costUsd&&(n+=i.costUsd)}return n}static emptyMetrics(t){return{goalId:t,metricType:"",targetValue:0,currentValue:0,progressPct:0,deadlineRemainingDays:0,budgetRemainingPct:0,expectedCompletionPct:0,rawScore:0}}};var Ut=I("agent"),q=class{static cache=new Map;static CACHE_TTL=1440*60*1e3;static async callClaude(t){let o=(await ue(t,'You are an AI quality evaluator. Respond with JSON: {"score": 0-1, "confidence": 0-1, "reasoning": "..."}')).match(/\{[\s\S]*\}/);if(!o)throw new Error("Failed to parse LLM Judge response as JSON");let s=JSON.parse(o[0]);return{score:Math.max(0,Math.min(1,s.score??0)),confidence:Math.max(.3,Math.min(.95,s.confidence??.5)),reasoning:s.reasoning??"No reasoning provided"}}static async evaluate(t,r){let n=`${t}:${r}`,o=this.cache.get(n);if(o&&Date.now()-o.evaluatedAt<this.CACHE_TTL)return o;let s=v(t);if(!s){let g={taskId:t,criteria:r,score:0,confidence:.3,reasoning:"Task not found",evaluatedAt:Date.now()};return this.cache.set(n,g),g}let i=this.getPromptTemplate(s.prompt??"",s.result??s.error??"",r),l,u,d;try{let g=await this.callClaude(i);l=g.score,u=g.confidence,d=g.reasoning}catch(g){Ut.warn({error:g,taskId:t},"LLM Judge Claude API call failed, using heuristic fallback"),s.status==="failed"?(l=.1,u=.6,d=`Task failed: ${s.error??"unknown error"} (heuristic fallback)`):s.status==="completed"&&s.result?(l=.7,u=.5,d="Task completed with result (heuristic fallback due to API error)"):s.status==="completed"?(l=.5,u=.4,d="Task completed without explicit result (heuristic fallback)"):(l=.3,u=.3,d=`Task in status: ${s.status} (heuristic fallback)`)}let p={taskId:t,criteria:r,score:l,confidence:u,reasoning:d,evaluatedAt:Date.now()};return this.cache.set(n,p),p}static shouldUseObjective(t){let r=v(t);return r?r.status==="completed"&&r.costUsd!==void 0&&r.numTurns!==void 0:!1}static clearCache(){this.cache.clear()}static getPromptTemplate(t,r,n){return`You are an expert evaluator. Evaluate the following task result against these criteria:
|
|
31
|
-
|
|
32
|
-
Task: ${t}
|
|
33
|
-
Result: ${r}
|
|
34
|
-
Criteria: ${n}
|
|
35
|
-
|
|
36
|
-
Provide:
|
|
37
|
-
1. Score (0-1): How well did the task meet the criteria?
|
|
38
|
-
2. Confidence (0-1): How confident are you in this evaluation?
|
|
39
|
-
3. Reasoning: Brief explanation of your scoring
|
|
40
|
-
|
|
41
|
-
Respond in JSON: {"score": number, "confidence": number, "reasoning": "string"}`}};var Gt={L0:.2,L1:.15,L2:.35,L3:.3},ge=class e{goalId;nodes;children;constructor(t,r){this.goalId=t,this.nodes=new Map(r.map(n=>[n.id,n])),this.children=new Map;for(let n of r){let o=n.parentId,s=this.children.get(o)??[];s.push(n),this.children.set(o,s)}this.validateAcyclicity()}validateAcyclicity(){for(let t of this.nodes.values()){if(t.parentId&&!this.nodes.has(t.parentId))continue;let r=new Set,n=t.id;for(;n;){if(r.has(n))throw new Error(`Cycle detected in metric tree at node ${n}`);r.add(n),n=this.nodes.get(n)?.parentId}}}static buildFromGoal(t){let r=nt(t);return new e(t,r)}static fromNodes(t,r){return new e(t,r)}queryPath(t){let r=[];for(let n of this.nodes.values())n.level===t&&r.push(n);return r.sort((n,o)=>o.weight-n.weight)}aggregateScores(t,r){let n=this.queryPath(t);if(n.length===0)return 0;let o=0,s=0;for(let i of n){let l=r.get(i.id)??0,u=i.weight*i.calibrationFactor;o+=l*u,s+=u}return s>0?o/s:0}getWeightedScore(t){let r=0;for(let[n,o]of Object.entries(Gt)){let s=this.aggregateScores(n,t);r+=s*o}return Math.max(0,Math.min(1,r))}getNodeCount(){return this.nodes.size}getChildren(t){return this.children.get(t)??[]}};var An=I("agent");function fe(e,t){let r=Date.now(),n=ge.buildFromGoal(e),o=new Map,s=me.collect(e);for(let u of n.queryPath("L0"))o.set(u.id,s.rawScore);let i=Vt(n);if(t){let u=pe.collect(t,e);if(u.isComplete){for(let p of n.queryPath("L3"))o.set(p.id,u.rawScore);let d=n.getNodeCount()>0?n.getWeightedScore(o):Math.max(0,Math.min(1,u.rawScore*.65+s.rawScore*.35));return{goalId:e,taskId:t,reward:d,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:u.rawScore},calibrationFactors:i,source:"objective",confidence:.9,computedAt:r}}}if(t&&!q.shouldUseObjective(t)){let d=q.evaluate(t,"general_quality"),p=s.rawScore*.5+.5*.5;return{goalId:e,taskId:t,reward:s.rawScore,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0,llmJudge:.5},calibrationFactors:i,source:"llm_judge",confidence:.4,computedAt:r}}let l=n.getNodeCount()>0?n.getWeightedScore(o):s.rawScore;return{goalId:e,reward:l,breakdown:{L0:s.rawScore,L1:0,L2:0,L3:0},calibrationFactors:i,source:"fallback",confidence:.3,computedAt:r}}function Vt(e){let t={L0:1,L1:1,L2:1,L3:1};for(let r of["L0","L1","L2","L3"]){let n=e.queryPath(r);n.length>0&&(t[r]=n[0].calibrationFactor)}return t}import{v4 as ut}from"uuid";oe();function he(e){return{id:e.id,roleId:e.role_id,taskType:e.task_type,name:e.name,promptTemplate:e.prompt_template,alpha:e.alpha,beta:e.beta,totalTrials:e.total_trials,avgReward:e.avg_reward??void 0,createdAt:e.created_at,updatedAt:e.updated_at??void 0}}function it(e){b().prepare(`
|
|
42
|
-
INSERT INTO strategies (id, role_id, task_type, name, prompt_template,
|
|
43
|
-
alpha, beta, total_trials, avg_reward, created_at, updated_at)
|
|
44
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
45
|
-
`).run(e.id,e.roleId,e.taskType,e.name,e.promptTemplate,e.alpha,e.beta,e.totalTrials,e.avgReward??null,e.createdAt,e.updatedAt??null)}function lt(e){let r=b().prepare("SELECT * FROM strategies WHERE id = ?").get(e);return r?he(r):void 0}function $n(e=100){return b().prepare("SELECT * FROM strategies ORDER BY created_at LIMIT ?").all(e).map(he)}function ct(e){return b().prepare("SELECT * FROM strategies WHERE role_id = ? ORDER BY created_at").all(e).map(he)}function L(e,t){return b().prepare("SELECT * FROM strategies WHERE role_id = ? AND task_type = ? ORDER BY created_at").all(e,t).map(he)}function dt(e,t){b().prepare(`
|
|
46
|
-
UPDATE strategies
|
|
47
|
-
SET alpha = alpha + ?,
|
|
48
|
-
beta = beta + ?,
|
|
49
|
-
total_trials = total_trials + 1,
|
|
50
|
-
avg_reward = CASE
|
|
51
|
-
WHEN total_trials = 0 THEN ?
|
|
52
|
-
ELSE (avg_reward * total_trials + ?) / (total_trials + 1)
|
|
53
|
-
END,
|
|
54
|
-
updated_at = ?
|
|
55
|
-
WHERE id = ?
|
|
56
|
-
`).run(t,1-t,t,t,Date.now(),e)}var H=class{static sampleBeta(t,r){let n=this.sampleGamma(t,1),o=this.sampleGamma(r,1);return n/(n+o)}static sampleGamma(t,r){if(t<1)return this.sampleGamma(t+1,r)*Math.pow(Math.random(),1/t);let n=t-1/3,o=1/Math.sqrt(9*n);for(;;){let s,i;do s=this.randn(),i=1+o*s;while(i<=0);i=i*i*i;let l=Math.random();if(l<1-.0331*s*s*s*s||Math.log(l)<.5*s*s+n*(1-i+Math.log(i)))return n*i/r}}static randn(){let t=Math.random(),r=Math.random();return Math.sqrt(-2*Math.log(t))*Math.cos(2*Math.PI*r)}static sample(t){if(t.length===0)return null;let r=null,n=-1;for(let o of t){let s=this.sampleBeta(o.alpha,o.beta);s>n&&(n=s,r=o)}return r}static getProbabilities(t,r=1e4){let n=new Map;for(let s=0;s<r;s++){let i=this.sample(t);i&&n.set(i.id,(n.get(i.id)||0)+1)}let o=new Map;for(let[s,i]of n)o.set(s,i/r);return o}};var Bt=5,Pe=20,pt=.5,S=class{static selectStrategy(t,r){let n=L(t,r);return H.sample(n)}static recordTrial(t,r,n,o,s,i,l){dt(t,o),st({id:ut(),strategyId:t,goalId:r,taskId:n,reward:o,metricL2Score:s,metricL3Score:i,context:l,completedAt:Date.now()})}static getStrategies(t,r){return L(t,r)}static getStrategyById(t){return lt(t)}static getPopulationStats(t,r){let n=L(t,r);if(n.length===0)return{count:0,avgTrials:0,avgReward:0,minTrials:0,maxTrials:0};let s=n.reduce((u,d)=>u+d.totalTrials,0)/n.length,i=n.filter(u=>u.avgReward!==void 0).map(u=>u.avgReward),l=i.length>0?i.reduce((u,d)=>u+d,0)/i.length:0;return{count:n.length,avgTrials:s,avgReward:l,minTrials:Math.min(...n.map(u=>u.totalTrials)),maxTrials:Math.max(...n.map(u=>u.totalTrials))}}static shouldEvolve(t,r){let n=this.getPopulationStats(t,r);return n.count<Bt?!0:n.count<Pe&&n.maxTrials>0}static addStrategy(t,r,n,o){if(L(t,r).length>=Pe)throw new Error(`Strategy population at maximum (${Pe}) for ${t}/${r}`);let i={id:`strat-${ut().slice(0,8)}`,roleId:t,taskType:r,name:n,promptTemplate:o,alpha:pt,beta:pt,totalTrials:0,createdAt:Date.now()};return it(i),i}static getTopStrategies(t,r,n=3){let s=L(t,r).filter(i=>i.totalTrials>0);return s.sort((i,l)=>(l.avgReward??0)-(i.avgReward??0)),s.slice(0,n)}static getSamplingProbabilities(t,r){let n=L(t,r);return H.getProbabilities(n)}static evaluateAndRecord(t,r,n,o,s,i){let l=fe(r,n);return this.recordTrial(t,r,n,l.reward,o,s,i),l.reward}};var Wt=3,Jt=2,be=class{static async generateVariants(t,r,n=Wt,o=Jt){let s=S.getTopStrategies(t,r,n);if(s.length===0){let l=`baseline-${r}-v1`;return S.addStrategy(t,r,l,this.generateBaselinePrompt(t,r)),[l]}let i=[];for(let l=0;l<o;l++){let u=s[0].totalTrials+l+1,d=`${r}-evolved-v${u}`,p=s[0].promptTemplate,g=this.mutateTemplate(p);S.addStrategy(t,r,d,g),i.push(d)}return i}static generateBaselinePrompt(t,r){return`You are a ${t} agent specializing in ${r}.
|
|
57
|
-
|
|
58
|
-
## Core Focus
|
|
59
|
-
Complete tasks with high quality.
|
|
60
|
-
|
|
61
|
-
## Approach
|
|
62
|
-
1. Understand the task requirements thoroughly
|
|
63
|
-
2. Plan your approach before executing
|
|
64
|
-
3. Execute systematically, checking your work
|
|
65
|
-
4. Verify completion against requirements`}static mutateTemplate(t){let r=[this.addProcessEmphasis(),this.addQualityFocus(),this.addVerificationStep()],n=r[Math.floor(Math.random()*r.length)];return`${t}
|
|
66
|
-
|
|
67
|
-
## Evolution
|
|
68
|
-
${n}`}static addProcessEmphasis(){let t=["Break down complex tasks into smaller steps","Iterate on solutions, testing each component","Document your reasoning at each step"];return`**Process:** ${t[Math.floor(Math.random()*t.length)]}`}static addQualityFocus(){let t=["Double-check all outputs before completing","Consider edge cases and error conditions","Optimize for correctness over speed"];return`**Quality:** ${t[Math.floor(Math.random()*t.length)]}`}static addVerificationStep(){return"**Verification:** After completing, verify your work meets all requirements."}static async generateWithLLM(t,r,n){return{promptTemplate:this.generateBaselinePrompt(t,r),rationale:"Generated baseline - LLM integration in Phase 5"}}};import{tool as N}from"@anthropic-ai/claude-agent-sdk";import{z as h}from"zod";import{v4 as qt}from"uuid";function M(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}var Ht={query:h.string().describe("Search query for memory retrieval"),roleId:h.string().optional().describe("Role ID to scope search (omit for cross-role)"),topK:h.number().optional().describe("Max results to return (default 5)")},Kt={query:h.string().describe("Search query for memory retrieval"),topK:h.number().optional().describe("Max results to return (default 5)")},Yt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),roleId:h.string().describe("Role ID to save memory under"),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},zt={id:h.string().optional().describe("Memory ID to update. Omit to create new."),content:h.string().describe("Memory content text"),type:h.enum(["event","thought","reflection"]).optional().describe("Memory type (default: thought)"),keywords:h.array(h.string()).optional().describe("Keywords for BM25 search"),importance:h.number().min(1).max(5).optional().describe("Importance 1-5 (default: 3)"),tier:h.enum(["working","episodic","semantic"]).optional().describe("Memory tier (default: episodic)")},mt={id:h.string().describe("Memory ID to delete")};async function gt(e,t){let r=e??t.roleId,n=t.topK??5,o=await Ke(r,t.query,{topK:n});return M({results:o.map(s=>({id:s.id,type:s.type,content:s.content,keywords:s.keywords,importance:s.importance,score:s.score}))})}async function ft(e,t){let r=e??t.roleId;if(!r)return M({error:"roleId is required"});let n,o=!0;try{n=await Be(t.content)}catch{o=!1}if(t.id){if(!Te(t.id))return M({error:`Memory ${t.id} not found`});let u=Je(t.id,{content:t.content,embedding:n,keywords:t.keywords,importance:t.importance,type:t.type});return M({id:t.id,action:"updated",success:u,embeddingUpdated:o})}let s=`mem-${qt().slice(0,8)}`,i=Date.now();return We({id:s,roleId:r,type:t.type??"thought",content:t.content,embedding:n,keywords:t.keywords??[],importance:t.importance??3,sourceType:"manual",createdAt:i,lastAccessed:i,retrievedCount:0,tier:t.tier??"episodic"}),M({id:s,action:"created",success:!0,embeddingUpdated:o})}async function ht(e,t){if(e){let r=Te(t.id);if(!r)return M({error:`Memory ${t.id} not found`});if(r.roleId!==e)return M({error:`Memory ${t.id} does not belong to this role`})}return He(t.id),M({id:t.id,deleted:!0})}function bt(e){return e?[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Kt,async t=>gt(e,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",zt,async t=>ft(e,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(e,t))]:[N("search_memories","Search agent memory using hybrid vector + keyword search. Returns scored memories ranked by relevance, recency, and importance.",Ht,async t=>gt(void 0,t)),N("save_memory","Create a new memory or update an existing one. Provide 'id' to update, omit to create. Embedding is auto-generated from content.",Yt,async t=>ft(void 0,t)),N("delete_memory","Delete a memory by ID.",mt,async t=>ht(void 0,t))]}import{v4 as w}from"uuid";ye();import{spawnSync as It}from"child_process";import{createRequire as Zt}from"module";import{dirname as er,join as St}from"path";import{openSync as tr,readFileSync as rr,unlinkSync as nr}from"fs";var or=3e4,kt=12e4;function Tt(){let t=Zt(import.meta.url).resolve("@anthropic-ai/claude-agent-sdk");return St(er(t),"cli.js")}function Z(e,t){let r=Tt(),n=t?.timeout??or;if(t?.json){let s=St("/tmp",`adam-cli-stdout-${process.pid}-${Date.now()}.txt`),i=tr(s,"w");try{let l=It("node",[r,...e],{cwd:t.cwd,timeout:n,stdio:["ignore",i,"pipe"],encoding:"utf-8"});if(l.status!==0)throw new Error(l.stderr?.trim()||`CLI exited with status ${l.status}`);return rr(s,"utf-8")}finally{try{nr(s)}catch{}}}let o=It("node",[r,...e],{cwd:t?.cwd,timeout:n,encoding:"utf-8"});if(o.status!==0)throw new Error(o.stderr?.trim()||`CLI exited with status ${o.status}`);return o.stdout}function Rt(){let e=Z(["plugin","list","--available","--json"],{json:!0});return JSON.parse(e)}function De(e,t="user",r){return Z(["plugin","install",e,"--scope",t],{cwd:r,timeout:kt})}function Ae(e,t,r){return Z(["plugin","uninstall",e],{cwd:r,timeout:kt})}function _t(e,t){return Z(["plugin","enable",e])}function Mt(e,t){return Z(["plugin","disable",e])}function co(){try{return!!Tt()}catch{return!1}}ye();V();var ar={Read:{category:"File",label:"read"},Write:{category:"File",label:"write"},Edit:{category:"File",label:"edit"},Glob:{category:"Search",label:"find files"},Grep:{category:"Search",label:"search content"},Bash:{category:"Execution",label:"shell commands"},WebSearch:{category:"Web",label:"web search"},WebFetch:{category:"Web",label:"fetch pages"},NotebookEdit:{category:"Execution",label:"Jupyter notebooks"}};function ee(e,t){let r=e.allowedTools??[];if(r.length===0)return"No tool permissions";let n=new Map,o=[];for(let d of r){let p=ar[d];if(p){let g=n.get(p.category)??[];g.push(p.label),n.set(p.category,g)}else o.push(d)}let s=[];for(let[d,p]of n)s.push(`${d} (${p.join(", ")})`);o.length>0&&s.push(o.join(", "));let i=s.join(" \xB7 "),l=Object.keys(e.mcpServers??{});l.length>0&&(i+=` \xB7 MCP: ${l.join(", ")}`);let u=e.additionalDirectories??[];if(u.length>0&&(i+=` \xB7 Dirs: ${u.map(d=>d.path).join(", ")}`),t&&t.plugins.length>0){let d=t.plugins.map(p=>{let g=[];return p.skills.length>0&&g.push(`skills: ${p.skills.map(f=>f.name).join(", ")}`),p.agents.length>0&&g.push(`agents: ${p.agents.map(f=>f.name).join(", ")}`),g.length>0?`${p.name} (${g.join("; ")})`:p.name});i+=` \xB7 Plugins: ${d.join(", ")}`}return i}function ir(e){let t=[],r=e.additionalDirectories??[];for(let n of r){if(!n.inheritPlugins&&!n.inheritMcp)continue;let o=X(n.path),s=Object.entries(o.enabledPlugins).filter(([,l])=>l).map(([l])=>l),i=Ee(s);for(let[,l]of i)t.includes(l)||t.push(l)}try{let n=Fe(e.name),o=C({scope:"project",projectPath:n});for(let s of o)s.installPath&&!t.includes(s.installPath)&&t.push(s.installPath)}catch{}return t}function Ne(e){let t=ir(e),r=[];for(let n of t){let o=Q(n);o&&r.push({name:o.name||n.split("/").pop()||"unknown",description:o.description,skills:o.skills,agents:o.agents,mcpServers:o.mcpServers,hooks:o.hooks})}return{plugins:r}}oe();function lr(e){return{id:e.id,roleId:e.role_id??void 0,taskPattern:e.task_pattern,maxRiskLevel:e.max_risk_level,createdAt:e.created_at,createdByTaskId:e.created_by_task_id??void 0}}var Pt={low:1,medium:2,high:3};function xt(e){b().prepare(`
|
|
69
|
-
INSERT INTO approval_rules (id, role_id, task_pattern, max_risk_level, created_at, created_by_task_id)
|
|
70
|
-
VALUES (?, ?, ?, ?, ?, ?)
|
|
71
|
-
`).run(e.id,e.roleId??null,e.taskPattern,e.maxRiskLevel,e.createdAt,e.createdByTaskId??null)}function fo(e,t,r){let o=b().prepare("SELECT * FROM approval_rules ORDER BY created_at DESC").all();for(let s of o)if(!(s.role_id&&s.role_id!==e)&&!(Pt[r]>Pt[s.max_risk_level]))try{if(new RegExp(s.task_pattern,"i").test(t))return lr(s)}catch{}}import*as Lt from"crypto";var te=I("api"),re=class{cancelTask(t){let r=v(t);r&&(F(t,{status:"cancelled",completedAt:Date.now()}),ke.emit({type:"task_status_change",taskId:t,oldStatus:r.status,newStatus:"cancelled"}),te.debug({taskId:t,oldStatus:r.status},"Task cancelled"))}resolveApproval(t,r,n){return te.debug({approvalId:t,action:r,reason:n},"Approval resolved (no-op in Pure C)"),!0}resolvePlanApproval(t,r,n,o){let s=Ge(t);if(!s)return te.warn({planId:t},"Plan not found or already resolved"),!1;let i=v(s.taskId);return i?(Ve(t,r==="allow"?"approved":"denied",n),r==="allow"&&n==="permanent"&&xt({id:Lt.randomUUID(),roleId:s.roleId,taskPattern:i.prompt.slice(0,100).replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),maxRiskLevel:s.plan.overallRisk,createdAt:Date.now(),createdByTaskId:i.id}),ke.emit({type:"plan_approval_decision",taskId:i.id,planId:t,decision:r,approvalType:n,reason:o}),te.debug({planId:t,decision:r,approvalType:n},"Plan approval resolved"),!0):(te.warn({planId:t},"Task not found for plan"),!1)}};var ve=I("manager");function c(e){return{content:[{type:"text",text:JSON.stringify(e)}]}}async function P(e){let{listChannels:t}=await import("./channels-VEUBY2NZ.js"),r=t(),{listSessions:n}=await import("./session-manager-45LFTPBA.js"),o=[...n("active"),...n("archived")],s=[];for(let i of e)if(i.type==="session"&&i.sessionId)s.push({type:"session",sessionId:i.sessionId});else if(i.type==="channel"){let l=i.channelId,u=i.chatId;if(!l&&i.channelName){let d=r.find(p=>p.name.toLowerCase().includes(i.channelName.toLowerCase()));d&&(l=d.id)}if(l&&!u){let d=o.find(p=>p.source.type==="channel"&&p.source.channelId===l&&p.source.chatId);d?.source.chatId?u=d.source.chatId:u=r.find(g=>g.id===l)?.config?.userId}l&&u?s.push({type:"channel",channelId:l,chatId:u}):ve.warn({channelName:i.channelName,channelId:l,chatId:u},"Could not resolve channel notify target")}return s}async function dr(e){let{listRoles:t}=await import("./roles-SG2YAR64.js"),r=t(void 0,100,0);for(let n of r)if(n.name.toLowerCase().includes(e.toLowerCase()))return n.id}var ur={goalId:a.string()},pr={goalId:a.string(),status:a.string().optional(),currentValue:a.number().optional(),budgetUsd:a.number().optional(),notes:a.string().optional()},mr={goalId:a.string(),goalDescription:a.string(),maxSubtasks:a.number().optional()},D=a.union([a.object({type:a.literal("session"),sessionId:a.string()}),a.object({type:a.literal("channel"),channelName:a.string()}),a.object({type:a.literal("channel"),channelId:a.string(),chatId:a.string().optional()})]),gr={prompt:a.string(),roleId:a.string().describe("Role ID. Call list_roles first to find the best role for the task."),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text). E.g., send result to a specific channel."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary). Defaults to the originating channel/session."),toolOverrides:a.object({allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional()}).optional()},fr={taskId:a.string(),goalId:a.string().optional(),strategyId:a.string().optional()},hr={roleId:a.string(),taskType:a.string(),name:a.string().optional()},br={status:a.string().optional(),limit:a.number().optional()},yr={taskId:a.string(),roleId:a.string()},vr={taskId:a.string().optional(),status:a.string().optional(),limit:a.number().optional()},wr={roleId:a.string(),allowedPaths:a.array(a.string()).optional(),deniedPaths:a.array(a.string()).optional(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional(),allowedChannels:a.array(a.string()).optional(),inheritUserSettings:a.boolean().optional().describe("Enable/disable inheriting user-level settings (global plugins, MCP servers). Default: false (isolated).")},Ir={roleId:a.string().optional(),limit:a.number().optional()},Sr={name:a.string(),cagPrompt:a.string(),traits:a.array(a.string()).optional(),allowedTools:a.array(a.string()).optional(),disallowedTools:a.array(a.string()).optional(),additionalDirectories:a.array(a.object({path:a.string(),inheritPlugins:a.boolean().optional(),inheritMcp:a.boolean().optional(),inheritPermissions:a.boolean().optional()})).optional()},kr={roleId:a.string(),reason:a.string().optional()},Tr={name:a.string(),description:a.string().optional(),roleId:a.string().optional(),metric:a.string().optional(),targetValue:a.number().optional(),deadline:a.number().optional(),budgetUsd:a.number().optional(),deliverTo:a.array(D).optional().describe("Where to deliver goal completion notifications.")},Rr={name:a.string(),description:a.string().optional(),triggerType:a.enum(["cron","event"]),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),prompt:a.string(),roleId:a.string().optional(),enabled:a.boolean().optional(),goalIds:a.array(a.string()).optional(),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary).")},_r={status:a.enum(["active","retired","probation"]).optional(),limit:a.number().optional()},Mr={enabled:a.boolean().optional()},Pr={},xr={},Lr={prompt:a.string().describe("The task prompt to execute after the delay"),delayMinutes:a.number().optional().describe("Minutes from now to execute (e.g., 30 for 'half an hour later')"),runAt:a.string().optional().describe("ISO 8601 timestamp to execute at (e.g., '2026-04-01T15:00:00+08:00')"),roleId:a.string().describe("Role ID to assign the task to. Call list_roles first."),deliverTo:a.array(D).optional().describe("Where to deliver the task output (result full text)."),reportTo:a.array(D).optional().describe("Where to send status reports (completion summary).")},Er={roleId:a.string().optional().describe("If provided, shows which plugins are installed in that role's workspace.")},Cr={roleId:a.string().describe("Role ID to install the plugin under (project-scope)."),pluginId:a.string().describe("Plugin ID (e.g. 'github@anthropic'). Use list_available_plugins to discover available plugins.")},Dr={roleId:a.string().describe("Role ID to uninstall the plugin from."),pluginId:a.string().describe("Plugin ID to uninstall.")},Ar={roleId:a.string().describe("Role ID to bind the MCP server to."),mcpName:a.string().describe("Name for this MCP server (e.g., 'github', 'filesystem')."),mcpConfig:a.record(a.string(),a.unknown()).describe("MCP server configuration object.")},Nr={roleId:a.string().describe("Role ID to unbind the MCP server from."),mcpName:a.string().describe("Name of the MCP server to remove.")},jr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},$r={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Or={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Fr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Ur={},Gr={},Vr={pluginId:a.string().describe("Plugin ID (e.g., 'github@anthropic').")},Br={roleId:a.string().describe("Role ID to associate scanned plugins with."),path:a.string().describe("Directory path to scan for .claude/settings.json.")},Wr={taskId:a.string().describe("Task ID to cancel.")},Jr={taskId:a.string().describe("Task ID to get logs for."),limit:a.number().optional().describe("Max log entries (default 20).")},qr={roleId:a.string().describe("Role ID to delete.")},Hr={},Kr={updates:a.record(a.string(),a.unknown()).describe("Config key-value pairs to update. Example: { 'defaults.maxTurns': 50, 'logging.level': 'debug' }")},Yr={roleId:a.string().describe("Role ID to list memories for."),limit:a.number().optional().describe("Max results (default 20).")},zr={templateId:a.string().describe("Template ID to update."),name:a.string().optional(),enabled:a.boolean().optional(),prompt:a.string().optional(),triggerCron:a.string().optional(),triggerEvent:a.string().optional(),roleId:a.string().optional()},Qr={templateId:a.string().describe("Template ID to delete.")},Xr={templateId:a.string().describe("Template ID to run immediately.")},Zr={enabled:a.boolean().optional().describe("Filter by enabled status.")},en={eventType:a.string().describe("Event type that triggers this rule (e.g., 'task_complete')."),channelId:a.string().describe("Channel ID to deliver to."),format:a.string().optional().describe("Format template (e.g., 'summary', 'full'). Default: 'summary'."),matchCriteria:a.record(a.string(),a.unknown()).optional().describe("JSON match criteria for event fields."),enabled:a.boolean().optional().describe("Enable this rule immediately (default true).")},tn={ruleId:a.string().describe("Delivery rule ID to delete.")},rn={roleId:a.string().optional().describe("Role ID to filter strategies by.")},Et=[m("read_goal_state","Read a single goal's detailed state: progress percentage, time remaining, budget spent, and current value. Use this for deep-dive on one goal; use list_goals for an overview of all goals.",ur,async e=>{let t=_(e.goalId);if(!t)return c({error:"Goal not found"});let r=Date.now(),n=t.targetValue>0?t.currentValue/t.targetValue:0;return c({id:t.id,name:t.name,description:t.description,roleId:t.roleId,metricType:t.metricType,targetValue:t.targetValue,currentValue:t.currentValue,deadline:t.deadline,budgetUsd:t.budgetUsd,status:t.status,progress:n,timeRemainingMs:Math.max(0,t.deadline-r),budgetRemainingUsd:t.budgetUsd})}),m("update_goal_state","Update a goal's status, current value, or budget.",pr,async e=>{let t={};return e.status&&(t.status=e.status),e.currentValue!==void 0&&(t.currentValue=e.currentValue),e.budgetUsd!==void 0&&(t.budgetUsd=e.budgetUsd),Object.keys(t).length>0&&(t.updatedAt=Date.now(),de(e.goalId,t)),c({success:!0})}),m("decompose_goal","Decompose a goal into actionable subtasks using LLM reasoning.",mr,async e=>{let t=k(),r=Math.min(e.maxSubtasks??5,10);try{let{query:o}=await import("@anthropic-ai/claude-agent-sdk"),s=`Decompose this goal into ${r} actionable subtasks.
|
|
72
|
-
|
|
73
|
-
Goal: ${e.goalDescription}
|
|
74
|
-
|
|
75
|
-
Respond ONLY with a JSON array. Each item: {"description": "...", "prompt": "detailed task instruction", "complexity": "low|medium|high", "role": "engineer|analyst|content_creator|reviewer"}
|
|
76
|
-
|
|
77
|
-
Rules:
|
|
78
|
-
- Each subtask must be independently executable
|
|
79
|
-
- Order from foundational to dependent
|
|
80
|
-
- Be specific about what each subtask should accomplish
|
|
81
|
-
- For each subtask, specify the best role from: 'engineer', 'analyst', 'content_creator', 'reviewer'. Match role to the nature of the work.`,i=o({prompt:s,options:{cwd:process.cwd(),maxTurns:1,maxBudgetUsd:.02}}),l="";for await(let d of i){let p=d;p.type==="result"&&typeof p.result=="string"&&(l=p.result)}let u=l.match(/\[[\s\S]*\]/);if(u){let d=JSON.parse(u[0]),p=[];for(let g=0;g<Math.min(d.length,r);g++){let f=d[g],ne=`subtask-${w().slice(0,8)}`,$=f.role,O=$?await dr($):void 0;se({id:ne,status:"pending",prompt:f.prompt,parentId:e.goalId,roleId:O,config:t.defaults,createdAt:Date.now()}),p.push({id:ne,description:f.description,prompt:f.prompt,dependencies:g>0?[p[g-1].id]:[],estimatedComplexity:f.complexity??"medium",role:$})}if(p.length>0)return c({subtasks:p})}}catch(o){ve.error({error:o},"LLM decomposition failed, using fallback")}let n=[];for(let o=0;o<r;o++){let s=`subtask-${w().slice(0,8)}`,i=`Subtask ${o+1} of goal: ${e.goalDescription.slice(0,100)}`,l=`${e.goalDescription}
|
|
82
|
-
|
|
83
|
-
Subtask ${o+1}/${r}`;se({id:s,status:"pending",prompt:l,parentId:e.goalId,config:t.defaults,createdAt:Date.now()}),n.push({id:s,description:i,prompt:l,dependencies:o>0?[n[o-1].id]:[],estimatedComplexity:"medium"})}return c({subtasks:n})}),m("dispatch_task","Create and immediately dispatch a task to the execution pool. roleId is required \u2014 call list_roles first to find the best role. The assigned role determines which tools the worker can use. Pass deliverTo (result delivery) and/or reportTo (status reports) to route output when the task completes.",gr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let O=G("active",20,0).filter(R=>R.source!=="system").map(R=>({id:R.id,name:R.name,allowedTools:R.allowedTools??[],capabilitySummary:ee(R)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:O})}let r=w(),n=k(),o=e.prompt.toLowerCase(),s={coding:["code","implement","fix","debug","refactor","build"],analysis:["analyze","data","report","statistics","investigate"],content:["write","translate","summarize","content","draft"],review:["review","check","audit","evaluate","assess"],admin:["config","permission","deploy","manage"]},i="general";for(let[O,R]of Object.entries(s))if(R.some(Ct=>o.includes(Ct))){i=O;break}let l,u=e.prompt,d=S.selectStrategy(e.roleId,i);d?.promptTemplate&&(u=`${d.promptTemplate}
|
|
84
|
-
|
|
85
|
-
## Task
|
|
86
|
-
${e.prompt}`,l=d.id);let p=[...n.defaults.allowedTools];e.toolOverrides?.allowedTools&&(p=[...e.toolOverrides.allowedTools]);let g={...n.defaults,allowedTools:p,disallowedTools:e.toolOverrides?.disallowedTools??n.defaults.disallowedTools},f=e.deliverTo?await P(e.deliverTo):void 0,ne=e.reportTo?await P(e.reportTo):void 0;se({id:r,status:"pending",prompt:u,roleId:e.roleId,deliverTo:f,reportTo:ne,config:g,createdAt:Date.now()});let{serverBus:$}=await import("./server-bus-GEGVMSCA.js");return $.emit({type:"task_created",taskId:r}),c({taskId:r,roleId:e.roleId,strategyId:l})}),m("evaluate_result","Evaluate a completed task's result and record a trial for Thompson Sampling.",fr,async e=>{let{goalId:t,taskId:r,strategyId:n}=e,o=fe(t??"",r);return n&&t&&S.recordTrial(n,t,r,o.reward,o.breakdown.L2||void 0,o.breakdown.L3||void 0,"Evaluated via adam-tools"),c({reward:o.reward,metricL2Score:o.breakdown.L2||void 0,metricL3Score:o.breakdown.L3||void 0,source:o.source,reasoning:`Evaluated via ${o.source} with confidence ${o.confidence.toFixed(2)}`})}),m("create_strategy","Create a new strategy variant for a role/taskType using LLM evolution.",hr,async e=>{let{roleId:t,taskType:r}=e;await be.generateVariants(t,r,3,1);let n=S.getStrategies(t,r),o=n[n.length-1];return c(o?{id:o.id,name:o.name,promptTemplate:o.promptTemplate}:{error:`Failed to create strategy for ${t}/${r}`})}),m("list_goals","List all goals with progress percentage, budget, deadline, and time remaining. Goal statuses: active (in progress), paused, completed, failed. Use this to check current goal status before making decisions.",br,async e=>{let t=e.status;return c(Ze(t,e.limit??10,0))}),m("delete_goal","Delete a goal by ID.",{goalId:a.string()},async e=>_(e.goalId)?(et(e.goalId),c({success:!0,goalId:e.goalId})):c({error:"Goal not found"})),m("pause_goal","Pause an active goal.",{goalId:a.string()},async e=>_(e.goalId)?(de(e.goalId,{status:"paused",updatedAt:Date.now()}),c({success:!0,goalId:e.goalId,status:"paused"})):c({error:"Goal not found"})),m("assign_role","Assign a role to a pending task.",yr,async e=>{let{taskId:t,roleId:r}=e;if(!v(t))return c({error:`Task not found: ${t}`});let o=T(r);return o?(F(t,{roleId:r}),ve.debug({taskId:t,roleId:r,roleName:o.name},"Role assigned to task"),c({success:!0,taskId:t,roleId:r})):c({error:`Role not found: ${r}`})}),...bt(),m("read_task_status","Read a single task's details (prompt, status, result, roleId) by ID, or list all tasks filtered by status (pending, running, completed, failed). Use this to check task progress and results.",vr,async e=>{if(e.taskId){let r=v(e.taskId);return c(r??{error:"Task not found"})}let t=e.status;return c(A(t,e.limit??100,0))}),m("modify_role_permissions","Update a role's RBAC permissions (paths, tools).",wr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={};if(e.allowedTools&&(r.allowedTools=e.allowedTools),e.disallowedTools&&(r.disallowedTools=e.disallowedTools),e.additionalDirectories!==void 0&&(r.additionalDirectories=e.additionalDirectories),e.allowedChannels!==void 0&&(r.allowedChannels=e.allowedChannels),"inheritUserSettings"in e&&(r.inheritUserSettings=e.inheritUserSettings),e.allowedPaths||e.deniedPaths){let n=t.preferences??{},o=n.permissions??{};r.preferences={...n,permissions:{...o,allowedPaths:e.allowedPaths??o.allowedPaths,deniedPaths:e.deniedPaths??o.deniedPaths}}}return U(e.roleId,r),c({success:!0})}),m("view_audit_log","View the evolution audit log for role changes.",Ir,async e=>{let{listEvolutionAudit:t}=await import("./evolution-audit-B7WKMOVR.js"),r=t(e.limit??50);return c({entries:r})}),m("list_roles","List all roles with their capabilities including bound plugins (skills/agents). Use this to discover available roles before dispatching tasks.",_r,async e=>{let r=G(e.status,e.limit??50,0).map(n=>{let o=Ne(n);return{id:n.id,name:n.name,status:n.status,allowedTools:n.allowedTools??[],disallowedTools:n.disallowedTools??[],additionalDirectories:n.additionalDirectories??[],cagPrompt:n.cagPrompt.slice(0,500)+(n.cagPrompt.length>500?"...":""),capabilitySummary:ee(n,o),plugins:o.plugins.map(s=>({name:s.name,skills:s.skills.map(i=>i.name),agents:s.agents.map(i=>i.name)}))}});return c({roles:r})}),m("create_role","Create a new role with a name, CAG prompt, and optional tool permissions.",Sr,async e=>{let t=`role-${w().slice(0,8)}`,r={id:t,name:e.name,cagPrompt:e.cagPrompt,learnedRules:[],memoryStreamId:`mem-${w().slice(0,8)}`,status:"active",preferences:{},createdAt:Date.now(),allowedTools:e.allowedTools,disallowedTools:e.disallowedTools,additionalDirectories:e.additionalDirectories};return $e(r),le(r),c({roleId:t,name:e.name,allowedTools:e.allowedTools,additionalDirectories:e.additionalDirectories??[]})}),m("retire_role","Retire a role (marks as retired, stops receiving tasks).",kr,async e=>T(e.roleId)?(U(e.roleId,{status:"retired"}),ve.info({roleId:e.roleId,reason:e.reason},"Role retired"),c({success:!0})):c({error:`Role not found: ${e.roleId}`})),m("create_goal","Create a new goal with optional budget, deadline, and metric tracking.",Tr,async e=>{let t=w(),r=Date.now(),n=r+10080*60*1e3,o={id:t,name:e.name,description:e.description,roleId:e.roleId??"engineer",metricType:e.metric??"completion",targetValue:e.targetValue??1,currentValue:0,deadline:e.deadline??n,budgetUsd:e.budgetUsd??5,status:"active",createdAt:r,deliverTo:e.deliverTo?await P(e.deliverTo):void 0};ce(o),ot(t,o.metricType);let s=_(t);return c({goalId:s.id,name:s.name,status:s.status})}),m("create_template","Create a recurring scheduled task using cron expressions (e.g., 'every hour', 'daily at 9am', 'weekly'). For one-shot delayed tasks ('in 30 minutes', 'tomorrow at 3pm'), use schedule_task instead.",Rr,async e=>{let{createTaskTemplate:t}=await import("./task-templates-7LSQ6OST.js"),r=w(),n=w(),o=e.deliverTo?await P(e.deliverTo):void 0,s=e.reportTo?await P(e.reportTo):void 0,i={id:r,name:e.name,description:e.description,trigger:{type:e.triggerType,cron:e.triggerCron,event:e.triggerEvent},steps:[{id:n,prompt:e.prompt}],rolePreference:e.roleId,enabled:e.enabled??!0,createdAt:Date.now(),goalIds:e.goalIds,deliverTo:o,reportTo:s};return t(i),c({templateId:r,name:i.name,trigger:i.trigger})}),m("list_templates","List task templates (automations). Use this to check existing scheduled/recurring tasks before creating new ones.",{enabled:a.boolean().optional().describe("Filter by enabled status. Omit to list all."),limit:a.number().optional().describe("Max results (default 50)")},async e=>{let{listTaskTemplates:t}=await import("./task-templates-7LSQ6OST.js"),r=t(e.enabled,e.limit??50,0);return c(r.map(n=>({id:n.id,name:n.name,description:n.description,trigger:n.trigger,enabled:n.enabled,rolePreference:n.rolePreference,deliverTo:n.deliverTo,createdAt:n.createdAt})))}),m("send_to_channel","Send a message to a connected channel by name. Use this to deliver task results or notifications to a specific channel (e.g., WeChat on iPad).",{channelName:a.string().describe("The channel name, e.g., 'WeChat on iPad'"),message:a.string().describe("The message content to send")},async e=>{let t=await P([{type:"channel",channelName:e.channelName}]);if(t.length===0)return c({error:`Channel "${e.channelName}" not found or no chatId available`});let r=t[0];if(r.type!=="channel")return c({error:"Resolved target is not a channel"});let{getOutboundGateway:n}=await import("./outbound-gateway-UCB57NPJ.js"),s=await n().send({channelId:r.channelId,chatId:r.chatId,content:e.message,messageType:"deliver"});return c({success:s.success,channelName:e.channelName})}),m("list_channels","List all connected channels with their platform, status, and chatId for message delivery. Use this to discover available channels before sending messages or setting up notifications.",Mr,async e=>{let t=Re(e.enabled),r=[..._e("active"),..._e("archived")],n=t.map(o=>{let s,i=r.find(l=>l.source.type==="channel"&&l.source.channelId===o.id&&l.source.chatId);return i?.source.chatId?s=i.source.chatId:s=o.config?.userId,{id:o.id,name:o.name,platform:o.platform,status:o.status,chatId:s}});return c({channels:n})}),m("get_system_status","Get current system status: execution pool capacity (active/max/queued slots), running task count, and system health. Use this to check if the system has capacity before dispatching tasks.",Pr,async()=>{let e=k(),t=A("running"),r=A("pending");return c({executionPool:{active:t.length,max:e.execution?.maxConcurrent??5,queued:r.length},timestamp:new Date().toISOString()})}),m("schedule_task","Schedule a one-shot delayed task. roleId is required \u2014 call list_roles first. Use this when the user wants something done later (e.g., '\u534A\u5C0F\u65F6\u540E', 'in 30 minutes', 'tomorrow at 3pm'). For recurring schedules ('every day', 'weekly'), use create_template instead.",Lr,async e=>{let t=T(e.roleId);if(!t||t.status!=="active"){let g=G("active",20,0).filter(f=>f.source!=="system").map(f=>({id:f.id,name:f.name,allowedTools:f.allowedTools??[],capabilitySummary:ee(f)}));return c({error:`Role not found or not active: ${e.roleId}. Pick a roleId from the list below.`,availableRoles:g})}let r=Date.now(),n;if(e.delayMinutes!==void 0&&e.runAt!==void 0)return c({error:"Provide exactly one of delayMinutes or runAt, not both"});if(e.delayMinutes!==void 0)n=r+e.delayMinutes*60*1e3;else if(e.runAt!==void 0){if(n=new Date(e.runAt).getTime(),isNaN(n))return c({error:"Invalid ISO 8601 timestamp in runAt"})}else return c({error:"Provide either delayMinutes or runAt"});if(n<=r)return c({error:"Scheduled time must be in the future"});let o=10080*60*1e3;if(n-r>o)return c({error:"Schedule exceeds maximum of 7 days"});let s=w(),i=new Date(n).toISOString(),l=e.deliverTo?await P(e.deliverTo):void 0,u=e.reportTo?await P(e.reportTo):void 0;Ye({id:s,name:e.prompt.slice(0,80),description:`One-shot scheduled task: ${e.prompt.slice(0,200)}`,trigger:{type:"once",runAt:i},steps:[{id:"main",prompt:e.prompt}],rolePreference:e.roleId,config:{...k().defaults},tags:["scheduled","once"],enabled:!0,createdAt:r,deliverTo:l,reportTo:u});let{getBreeEngine:d}=await import("./bree-engine-SQMSKGAP.js"),p=d();return p&&p.scheduleOnceJob(s),c({templateId:s,executeAt:i,prompt:e.prompt})}),m("cancel_scheduled_task","Cancel a previously scheduled one-shot task by its template ID. The task will not execute.",{templateId:a.string().describe("The template ID returned by schedule_task")},async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});if(t.trigger.type!=="once")return c({error:"This is not a one-shot scheduled task. Use disable_template for recurring automations."});Qe(e.templateId);let{getBreeEngine:r}=await import("./bree-engine-SQMSKGAP.js"),n=r();return n&&await n.unscheduleJob(e.templateId),c({cancelled:!0,templateId:e.templateId})}),m("list_available_plugins","List all installed plugins with their scope and global enabled state. If roleId is provided, shows which plugins are installed in that role's workspace.",Er,async e=>{let t=z(),r=C(),n=e.roleId?(()=>{let{getRoleWorkspacePath:o}=(V(),x(Ie)),{getRole:s}=(ie(),x(we)),{listInstalledPlugins:i}=(ye(),x(wt)),l=s(e.roleId);if(!l)return[];let u=o(l.name);return i({scope:"project",projectPath:u}).map(d=>d.id)})():[];return c({plugins:r.map(o=>({id:o.id,name:o.name,scope:o.scope,projectPath:o.projectPath,enabled:o.enabled,globalEnabled:t[o.id]??o.enabled,isInstalledInRole:n.includes(o.id),description:o.version?`v${o.version}`:void 0}))})}),m("install_plugin_for_role","Install a plugin into a role's workspace (project-scope). The plugin will be available when that role executes tasks.",Cr,async e=>{let{getRole:t}=(ie(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return De(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId,scope:"project",cwd:o})}catch(s){return c({error:`Failed to install plugin: ${s}`})}}),m("uninstall_plugin_from_role","Uninstall a plugin from a role's workspace.",Dr,async e=>{let{getRole:t}=(ie(),x(we)),{getRoleWorkspacePath:r}=(V(),x(Ie)),n=t(e.roleId);if(!n)return c({error:`Role not found: ${e.roleId}`});let o=r(n.name);try{return Ae(e.pluginId,"project",o),c({success:!0,roleId:e.roleId,pluginId:e.pluginId})}catch(s){return c({error:`Failed to uninstall plugin: ${s}`})}}),m("bind_mcp_to_role","Bind an MCP server configuration to a role. The MCP server will be available to the role during task execution.",Ar,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let n={...t.mcpServers??{},[e.mcpName]:e.mcpConfig};try{return U(e.roleId,{mcpServers:n}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName,mcpServers:n})}catch(o){return c({error:`Failed to bind MCP server: ${o}`})}}),m("unbind_mcp_from_role","Remove an MCP server binding from a role.",Nr,async e=>{let t=T(e.roleId);if(!t)return c({error:`Role not found: ${e.roleId}`});let r={...t.mcpServers??{}};if(!(e.mcpName in r))return c({error:`MCP server "${e.mcpName}" not bound to this role`});delete r[e.mcpName];try{return U(e.roleId,{mcpServers:r}),le(t),c({success:!0,roleId:e.roleId,mcpName:e.mcpName})}catch(n){return c({error:`Failed to unbind MCP server: ${n}`})}}),m("get_capabilities","Get a comprehensive overview of Adam's current capabilities: available roles and their tools, connected channels, installed plugins, active automations, and execution capacity. Call this when the user asks what you can do, or asks for help.",xr,async()=>{let{listTaskTemplates:e}=await import("./task-templates-7LSQ6OST.js"),t=k(),r=G(void 0,100,0),n=Re(),o=e(!0,100,0),s=A("running"),i=A("pending");return c({roles:{description:"Specialized worker identities \u2014 each has its own tools, MCP servers, plugins (skills/agents), and learned rules",active:r.filter(l=>l.status==="active"&&l.source!=="system").map(l=>{let u=Ne(l);return{name:l.name,tools:l.allowedTools??[],mcpServers:Object.keys(l.mcpServers??{}),channels:l.allowedChannels??[],capabilitySummary:ee(l,u),plugins:u.plugins.map(d=>({name:d.name,skills:d.skills.map(p=>p.name),agents:d.agents.map(p=>p.name)}))}}),retired:r.filter(l=>l.status==="retired").length,probation:r.filter(l=>l.status==="probation").length},channels:{description:"Send/receive messages via connected platforms",connected:n.filter(l=>l.enabled).map(l=>({name:l.name,platform:l.platform,status:l.status}))},plugins:{description:"Extensions that add capabilities to roles",installed:C().filter(l=>l.enabled).map(l=>({name:l.name,scope:l.scope,description:l.version?`v${l.version}`:void 0}))},automations:{description:"Recurring cron tasks and event-triggered templates",active:o.map(l=>({name:l.name,trigger:l.trigger}))},execution:{description:"Parallel task execution pool",maxConcurrent:t.execution?.maxConcurrent??5,running:s.length,queued:i.length},coreFeatures:["Goal management \u2014 SMART goals with budget/deadline/metric, auto-decomposition into subtasks","Memory \u2014 per-Role vector + keyword searchable memory across tasks","Strategy evolution \u2014 Thompson Sampling optimizes task approaches over time","Monitor \u2014 automatic quality scoring, role retirement/reinstatement","Delivery engine \u2014 event-driven result routing to channels/webhooks","Schedule \u2014 cron recurring templates + one-shot delayed tasks"]})}),m("enable_plugin","Enable a globally installed plugin (makes it available to all roles).",jr,async e=>{try{return _t(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to enable plugin: ${t}`})}}),m("disable_plugin","Disable a globally installed plugin (removes it from all roles).",$r,async e=>{try{return Mt(e.pluginId),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to disable plugin: ${t}`})}}),m("install_plugin_for_user","Install a plugin globally for the current user (user-scope).",Or,async e=>{try{return De(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId,scope:"user"})}catch(t){return c({error:`Failed to install plugin: ${t}`})}}),m("uninstall_plugin_for_user","Uninstall a globally installed plugin from the current user.",Fr,async e=>{try{return Ae(e.pluginId,"user"),c({success:!0,pluginId:e.pluginId})}catch(t){return c({error:`Failed to uninstall plugin: ${t}`})}}),m("browse_marketplace","Browse all available plugins from configured marketplaces (shows installed and available).",Ur,async()=>{try{let e=Rt(),t=C();return c({available:e,installed:t})}catch(e){return c({error:`Failed to browse marketplace: ${e}`})}}),m("list_marketplace_sources","List configured plugin marketplace sources.",Gr,async()=>{let e=Ce();return c({sources:e})}),m("get_plugin_detail","Get detailed manifest for an installed plugin (skills, agents, MCP servers, hooks).",Vr,async e=>{let t=Le(e.pluginId);if(!t)return c({error:`Plugin not found: ${e.pluginId}`});let r=Q(t.installPath);return c({id:t.id,name:t.name,version:t.version,scope:t.scope,projectPath:t.projectPath,enabled:t.enabled,manifest:r})}),m("scan_directory","Scan a directory for .claude/settings.json and return its plugin/MCP configuration.",Br,async e=>{let{getRole:t}=await import("./roles-SG2YAR64.js");if(!t(e.roleId))return c({error:`Role not found: ${e.roleId}`});try{let n=X(e.path);return c({roleId:e.roleId,path:e.path,config:n})}catch(n){return c({error:`Failed to scan directory: ${n}`})}}),m("cancel_task","Cancel a running or pending task by setting its status to 'cancelled'. Emits a task_status_change event.",Wr,async e=>{let t=v(e.taskId);if(!t)return c({error:`Task not found: ${e.taskId}`});let r=t.status;F(e.taskId,{status:"cancelled"});let{serverBus:n}=await import("./server-bus-GEGVMSCA.js");return n.emit({type:"task_status_change",taskId:e.taskId,oldStatus:r,newStatus:"cancelled"}),c({success:!0,taskId:e.taskId,status:"cancelled"})}),m("view_task_logs","Retrieve step-by-step execution logs for a task.",Jr,async e=>{let t=ae(e.taskId,e.limit??20);return c({taskId:e.taskId,count:t.length,logs:t})}),m("delete_role","Delete a role by ID. This removes the role and its workspace.",qr,async e=>T(e.roleId)?(Oe(e.roleId),c({success:!0,roleId:e.roleId})):c({error:`Role not found: ${e.roleId}`})),m("view_config","Get the current runtime configuration (mutable fields and restart-required fields).",Hr,async()=>{let{MUTABLE_PATHS:e,RESTART_REQUIRED_PATHS:t}=await import("./runtime-6UTYEONR.js"),r=k(),n={};try{let l=k().server?.port??7100,u=await fetch(`http://127.0.0.1:${l}/config`);u.ok&&(n=await u.json())}catch{}let o=[...e,...t],s=[...t],i={};for(let l of o){let u=l.split("."),d=r;for(let p of u)if(d&&typeof d=="object")d=d[p];else{d=void 0;break}i[l]={value:d,mutable:!t.includes(l)}}return c({config:i,mutable:[...e],restartRequired:[...t]})}),m("update_config","Update mutable runtime configuration fields. Returns partial-success: some fields may update while others return errors.",Kr,async e=>{let{isRestartRequiredPath:t}=await import("./runtime-6UTYEONR.js"),{setConfigValue:r}=await import("./config-WHXCZCI4.js"),n=je(e.updates,r);if(e.updates["logging.level"]&&Ue(e.updates["logging.level"]),n.updated.length>0){let{serverBus:o}=await import("./server-bus-GEGVMSCA.js");o.emit({type:"config_changed",changes:n.updated.map(s=>({path:s,value:e.updates[s]}))})}return c(n)}),m("list_memories","List memories stored under a specific role.",Yr,async e=>{let t=qe(e.roleId,e.limit??20);return c({roleId:e.roleId,count:t.length,memories:t})}),m("update_template","Update a task template's fields (name, prompt, cron, enabled, etc.).",zr,async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});let r={};if(e.name!==void 0&&(r.name=e.name),e.enabled!==void 0&&(r.enabled=e.enabled),e.prompt!==void 0){let n=t.steps?.length?[...t.steps]:[];n.length===0?n.push({id:w(),prompt:e.prompt}):n[0]={...n[0],prompt:e.prompt},r.steps=n}return(e.triggerCron!==void 0||e.triggerEvent!==void 0)&&(r.trigger={type:e.triggerEvent?"event":"cron",cron:e.triggerCron,event:e.triggerEvent}),e.roleId!==void 0&&(r.rolePreference=e.roleId),ze(e.templateId,r),c({success:!0,templateId:e.templateId,updated:Object.keys(r)})}),m("delete_template","Delete a task template by ID.",Qr,async e=>B(e.templateId)?(Xe(e.templateId),c({success:!0,templateId:e.templateId})):c({error:`Template not found: ${e.templateId}`})),m("run_template","Trigger a template immediately (runs the webhook endpoint for its name).",Xr,async e=>{let t=B(e.templateId);if(!t)return c({error:`Template not found: ${e.templateId}`});try{let r=k().server?.port??7100,n=await fetch(`http://127.0.0.1:${r}/webhooks/${t.name}`,{method:"POST"}),o=await n.json();return n.ok?c({success:!0,templateId:e.templateId,templateName:t.name,response:o}):c({error:`Webhook failed: ${o.code??n.status} \u2014 ${o.message??""}`})}catch(r){return c({error:`Failed to trigger template: ${r}`})}}),m("list_delivery_rules","List delivery rules, optionally filtered by enabled status.",Zr,async e=>{let t=Me(e.enabled);return c({count:t.length,rules:t})}),m("create_delivery_rule","Create a new delivery rule for event-driven result routing.",en,async e=>{let t=w(),r={id:t,eventType:e.eventType,matchCriteria:e.matchCriteria??{},target:{type:"channel",channelId:e.channelId},formatTemplate:e.format,maxPerMinute:10,skipOriginChannel:!1,enabled:e.enabled??!0,createdAt:Date.now()};return tt(r),c({success:!0,ruleId:t,rule:r})}),m("delete_delivery_rule","Delete a delivery rule by ID.",tn,async e=>Me().find(n=>n.id===e.ruleId)?(rt(e.ruleId),c({success:!0,ruleId:e.ruleId})):c({error:`Delivery rule not found: ${e.ruleId}`})),m("list_strategies","List Thompson Sampling strategy populations for a role, or all strategies if roleId omitted.",rn,async e=>{let t;if(e.roleId)t=ct(e.roleId);else{let{getDb:r}=await import("./db-PNZ3UJOE.js");t=r().prepare("SELECT * FROM strategies ORDER BY created_at").all().map(o=>({id:o.id,roleId:o.role_id,name:o.name,taskType:o.task_type,createdAt:o.created_at,updatedAt:o.updated_at??void 0,promptTemplate:o.prompt_template??"",alpha:o.alpha,beta:o.beta,totalTrials:o.trials,avgReward:o.total_reward&&o.trials>0?o.total_reward/o.trials:void 0,enabled:o.enabled===1}))}return c({roleId:e.roleId??null,count:t.length,strategies:t})}),m("authorize_task_operation","Authorize a pending privilege escalation for a task. The paused operation will proceed.",{taskId:a.string(),operationId:a.string().optional().describe("ID of the specific operation. If omitted, authorizes the most recent pending operation."),scope:a.enum(["once","permanent"]).default("once").describe("'once' = this operation only. 'permanent' = auto-authorize matching patterns in the future.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"allow",e.scope),c({success:!0,operationId:r.id,decision:"allow",scope:e.scope})):c({error:"No pending operation found for this task"})}),m("deny_task_operation","Deny a pending privilege escalation for a task. The paused operation will be rejected.",{taskId:a.string(),operationId:a.string().optional(),reason:a.string().optional().describe("Reason for denial, provided to the executor as feedback.")},async e=>{let t=Se(e.taskId),r=e.operationId?t.find(o=>o.id===e.operationId):t.find(o=>o.status==="pending");return r?(new re().resolvePlanApproval(r.id,"deny","once",e.reason),c({success:!0,operationId:r.id,decision:"deny"})):c({error:"No pending operation found for this task"})})];function Yo(){return Et.map(e=>e.name).sort().join(",")}function zo(){return cr({name:"adam-tools",version:"1.0.0",tools:Et})}export{fo as a,re as b,z as c,Q as d,C as e,Le as f,Ce as g,X as h,ye as i,un as j,pn as k,ot as l,$n as m,ct as n,S as o,bt as p,Rt as q,De as r,Ae as s,_t as t,Mt as u,co as v,ir as w,Yo as x,zo as y};
|
package/dist/chunk-DT2LX4XI.js
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
import{a as A,b as P}from"./chunk-WXN3PSVX.js";import{a as T,b as p}from"./chunk-L7426WNY.js";import{a as u}from"./chunk-L7JP7DUO.js";import{p as x}from"./chunk-HAWA62R2.js";import{a as I,b as l,d as y,f as C}from"./chunk-VF6GJGD6.js";import{d as h}from"./chunk-T25NLVMY.js";import{i as b,l as J}from"./chunk-XNWZZYAV.js";import{c as k}from"./chunk-3DAK2XWP.js";J();import{v4 as d}from"uuid";import{CronExpressionParser as D}from"cron-parser";import{v4 as M}from"uuid";var m=k("scheduler"),w=class{maxRetries=3;baseDelayMs=1e3;async execute(e,t){let s=h(),r=e.config?.fileAccess,i={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},o={templateId:e.id,executionId:t,stepResults:new Map,config:i},a=this.sortSteps(e.steps);for(let c of a){try{await this.executeStep(c,o)}catch(_){m.error({stepId:c.id,error:_},"Workflow step failed");break}if(o.stepResults.get(c.id)?.status==="failed"){m.warn({stepId:c.id},"Workflow step failed, workflow aborted");break}}m.info({executionId:t,completedSteps:o.stepResults.size,totalSteps:a.length},"Workflow completed")}sortSteps(e){let t=new Set,s=[],r=new Map(e.map(o=>[o.id,o])),i=o=>{if(!t.has(o.id)){if(t.add(o.id),o.dependsOn)for(let a of o.dependsOn){let c=r.get(a);c&&i(c)}s.push(o)}};for(let o of e)i(o);return s}async executeStep(e,t){let s=this.resolveVariables(e.prompt,t.stepResults),r=M();T({id:r,status:"pending",prompt:s,config:t.config,createdAt:Date.now(),parentId:t.executionId,templateId:t.templateId}),m.debug({stepId:e.id,taskId:r},"Created workflow step as task"),u.emit({type:"task_created",taskId:r});let i=await this.executeWithRetry(r,e.id),o=p(r);t.stepResults.set(e.id,{stepId:e.id,taskId:r,status:i==="completed"?"completed":"failed",result:o?.result,error:o?.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 i=this.baseDelayMs*Math.pow(2,s-1);m.info({stepId:t,attempt:s,maxRetries:this.maxRetries,delayMs:i},"Workflow step failed, retrying"),await this.sleep(i)}}return"failed"}waitForTaskCompletion(e,t=6e5){return new Promise(s=>{let r=Date.now(),i=()=>{if(Date.now()-r>t){s("failed");return}let o=p(e);if(!o){s("failed");return}if(o.status==="completed"){s("completed");return}if(o.status==="failed"||o.status==="cancelled"){s("failed");return}setTimeout(i,500)};i()})}sleep(e){return new Promise(t=>setTimeout(t,e))}};var n=k("scheduler"),v="ai-hourly-digest";function O(){if(l(v)){n.debug({templateId:v},"Built-in template already exists");return}let e={id:v,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
|
|
2
|
-
|
|
3
|
-
\u641C\u7D22\u6765\u6E90:
|
|
4
|
-
1. Hacker News AI \u677F\u5757 (https://news.ycombinator.com/front?day=1)
|
|
5
|
-
2. ArXiv cs.AI \u6700\u65B0\u8BBA\u6587 (https://arxiv.org/list/cs.AI/recent)
|
|
6
|
-
3. Reddit r/MachineLearning \u70ED\u95E8\u5E16\u5B50
|
|
7
|
-
|
|
8
|
-
\u627E\u51FA\u4E00\u7BC7\u6700\u6709\u4EF7\u503C\u3001\u6700\u6709\u6280\u672F\u6DF1\u5EA6\u7684\u6587\u7AE0\u3002
|
|
9
|
-
|
|
10
|
-
\u8F93\u51FA\u683C\u5F0F:
|
|
11
|
-
- \u6807\u9898\uFF1A[\u6587\u7AE0\u6807\u9898]
|
|
12
|
-
- \u6765\u6E90\uFF1A[\u7F51\u7AD9/\u5E73\u53F0\u540D\u79F0]
|
|
13
|
-
- \u94FE\u63A5\uFF1A[\u5B8C\u6574 URL]
|
|
14
|
-
- \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
|
|
15
|
-
|
|
16
|
-
\u6587\u7AE0\u4FE1\u606F:
|
|
17
|
-
{{search_ai_news.result}}
|
|
18
|
-
|
|
19
|
-
\u8BF7:
|
|
20
|
-
1. \u7528 WebFetch \u83B7\u53D6\u6587\u7AE0\u5B8C\u6574\u5185\u5BB9
|
|
21
|
-
2. \u63D0\u53D6\u6838\u5FC3\u89C2\u70B9\u548C\u6280\u672F\u7EC6\u8282
|
|
22
|
-
3. \u7528\u4E2D\u6587\u5199\u51FA 300-500 \u5B57\u7684\u603B\u7ED3
|
|
23
|
-
|
|
24
|
-
\u603B\u7ED3\u7ED3\u6784:
|
|
25
|
-
## \u6838\u5FC3\u53D1\u73B0
|
|
26
|
-
[\u6587\u7AE0\u6700\u91CD\u8981\u7684\u53D1\u73B0/\u521B\u65B0\u70B9]
|
|
27
|
-
|
|
28
|
-
## \u6280\u672F\u7EC6\u8282
|
|
29
|
-
[\u5173\u952E\u7684\u6280\u672F\u65B9\u6CD5/\u5B9E\u73B0\u7EC6\u8282]
|
|
30
|
-
|
|
31
|
-
## \u5F71\u54CD/\u610F\u4E49
|
|
32
|
-
[\u8FD9\u9879\u5DE5\u4F5C\u7684\u610F\u4E49\u6216\u5BF9\u884C\u4E1A\u7684\u5F71\u54CD]
|
|
33
|
-
|
|
34
|
-
## \u539F\u6587\u94FE\u63A5
|
|
35
|
-
[\u6587\u7AE0 URL]`},{id:"save_to_omnifocus",dependsOn:["summarize_article"],prompt:`\u5C06\u6587\u7AE0\u603B\u7ED3\u4FDD\u5B58\u5230 Omnifocus\u3002
|
|
36
|
-
|
|
37
|
-
\u603B\u7ED3\u5185\u5BB9:
|
|
38
|
-
{{summarize_article.result}}
|
|
39
|
-
|
|
40
|
-
\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
|
|
41
|
-
|
|
42
|
-
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]"
|
|
43
|
-
|
|
44
|
-
\u6CE8\u610F\uFF1A
|
|
45
|
-
- \u5C06 [\u6587\u7AE0\u6807\u9898] \u66FF\u6362\u4E3A\u5B9E\u9645\u6807\u9898
|
|
46
|
-
- \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
|
|
47
|
-
- \u603B\u7ED3\u5185\u5BB9\u4F7F\u7528\u6362\u884C\u7B26\u5206\u9694\u5404\u90E8\u5206
|
|
48
|
-
|
|
49
|
-
\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()};I(e),n.info({templateId:v,cron:"0 * * * *"},"Registered built-in AI Hourly Digest template")}var R=class{cronJobs=new Map;workflowExecutor=new w;started=!1;taskCompletionHandler=null;async start(){if(this.started)return;this.started=!0,O();let e=y(!0),t=0;for(let r of e)r.trigger.type==="cron"&&r.trigger.cron&&(this.scheduleCronJob(r),t++);let s=0;for(let r of e)r.trigger.type==="once"&&r.trigger.runAt&&(this.scheduleOnceJob(r.id),s++);this.taskCompletionHandler=r=>{r.newStatus==="completed"&&this.checkEventTriggers(r.taskId).catch(i=>{n.error({taskId:r.taskId,error:i},"Event trigger check failed")})},u.on("task_status_change",this.taskCompletionHandler),this.cronJobs.set("memory-cleanup",setInterval(()=>{this.runMemoryCleanup()},36e5)),n.info({cronCount:t,onceCount:s},"Bree engine started with cron jobs + memory cleanup")}runMemoryCleanup(){try{let e=b(void 0,1e3,0),t=0;for(let s of e)t+=x(s.id);t>0&&n.info({totalCleaned:t},"Memory cleanup completed")}catch(e){n.warn({error:e},"Memory cleanup failed")}}async stop(){for(let[,e]of this.cronJobs)clearTimeout(e),clearInterval(e);this.cronJobs.clear(),this.taskCompletionHandler&&(u.off("task_status_change",this.taskCompletionHandler),this.taskCompletionHandler=null),this.started=!1,n.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=D.parse(e.trigger.cron)}catch{n.warn({templateId:e.id,cron:e.trigger.cron},"Invalid cron expression");return}let r=()=>{let f=s.next().getTime()-Date.now();return Math.max(f,1e3)},i=()=>{this.executeCronTrigger(e.id).catch(f=>{n.error({templateId:e.id,error:f},"Cron trigger failed")});let c=setTimeout(i,r());this.cronJobs.set(t,c)},o=r(),a=setTimeout(i,o);this.cronJobs.set(t,a),n.debug({jobName:t,nextRun:new Date(Date.now()+o).toISOString()},"Scheduled cron job")}async executeCronTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Cron triggered"),await this.executeWorkflow(t,d()))}async scheduleJob(e){let t=l(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=l(e);if(!t)throw new Error(`Template ${e} not found`);let s=d();return this.executeWorkflow(t,s).catch(r=>{n.error({templateId:e,error:r},"Workflow execution failed")}),s}async checkEventTriggers(e){let t=p(e);if(!t)return;let s=y(!0),r=s.filter(i=>i.trigger.type==="event"&&i.trigger.event==="task_complete");for(let i of r)n.debug({templateName:i.name},"Event trigger matched"),await this.executeWorkflow(i,d());if(t.templateId){let i=s.filter(o=>o.trigger.type!=="event"||!o.trigger.event?!1:o.trigger.event===`template_complete:${t.templateId}`);for(let o of i)n.info({templateName:o.name,sourceTemplateId:t.templateId},"Template complete trigger matched"),await this.executeWorkflow(o,d())}}async executeWorkflow(e,t){if(n.info({templateName:e.name,executionId:t},"Executing workflow"),e.goalIds&&e.goalIds.length>0){for(let s of e.goalIds){let r=P(s);if(!r){n.warn({goalId:s,templateId:e.id},"Goal reference not found, skipping");continue}let i=d();A({id:i,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,deliverTo:e.deliverTo,reportTo:e.reportTo});let o=d();T({id:o,status:"pending",prompt:`Decompose and execute goal: ${r.name}. ${r.description??""}`,parentId:i,config:h(),createdAt:Date.now(),templateId:e.id}),u.emit({type:"task_created",taskId:o}),n.info({templateId:e.id,sourceGoalId:s,newGoalId:i,taskId:o},"Goal reference triggered, dispatched decomposition task")}return}await this.workflowExecutor.execute(e,t)}scheduleOnceJob(e){let t=l(e);if(!t||!t.enabled||t.trigger.type!=="once")return;let r=(t.trigger.runAt?new Date(t.trigger.runAt).getTime():0)-Date.now();if(r<=0){n.info({templateId:e,runAt:t.trigger.runAt},"Once-shot template past due, executing immediately"),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")});return}let i=`template-${e}`;this.cronJobs.has(i)&&clearTimeout(this.cronJobs.get(i));let o=setTimeout(()=>{this.cronJobs.delete(i),this.executeOnceTrigger(e).catch(a=>{n.error({templateId:e,error:a},"Once trigger execution failed")})},r);this.cronJobs.set(i,o),n.info({templateId:e,runAt:t.trigger.runAt,delayMs:r},"Scheduled once-shot job")}async executeOnceTrigger(e){let t=l(e);!t||!t.enabled||(n.info({templateName:t.name},"Once-shot triggered"),await this.executeWorkflow(t,d()),C(e),n.info({templateId:e},"Once-shot template auto-disabled after execution"))}},S=null;function Y(){return S}function Z(g){S=g}export{R as a,Y as b,Z as c};
|
package/dist/chunk-LBLERTM4.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{b as M}from"./chunk-PQ7KPALO.js";import{b as k,c as h,d as w}from"./chunk-FDWW245P.js";import{a as p}from"./chunk-L7JP7DUO.js";import{c as b}from"./chunk-3DAK2XWP.js";function $(n,c,s){switch(c){case"wechat":return D(n);case"telegram":return n;case"slack":return R(n);case"webhook":return JSON.stringify({result:n,taskId:s,timestamp:new Date().toISOString()});default:return D(n)}}function D(n){return n.replace(/^#{1,6}\s+/gm,"").replace(/\*\*(.+?)\*\*/g,"$1").replace(/\*(.+?)\*/g,"$1").replace(/__(.+?)__/g,"$1").replace(/_(.+?)_/g,"$1").replace(/`([^`]+)`/g,"$1").replace(/```[\s\S]*?```/g,c=>c.replace(/```\w*\n?/g,"").trim()).replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/!\[([^\]]*)\]\([^)]+\)/g,"$1").replace(/\n{3,}/g,`
|
|
2
|
-
|
|
3
|
-
`).trim()}function R(n){return n.replace(/\*\*(.+?)\*\*/g,"*$1*").replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>")}import{v4 as O}from"uuid";var C=b("adam"),I=class{_dedupCache=new Map;_rateLimitWindows=new Map;_recentlySentIds=new Set;isRecentlySent(c){return this._recentlySentIds.has(c)}async send(c){let{taskId:s,channelId:a,chatId:l,content:y,messageType:d,platform:x,webhookUrl:m,replyMarkup:S}=c,T=d!=="reply"&&!!s,r;if(T){r=`${s}:${a??"none"}:${l??"none"}:${d}`;let t=this._dedupCache.get(r);if(t&&Date.now()-t.timestamp<300*1e3)return C.debug({dedupKey:r},"Dedup hit, returning cached log entry"),{success:!0,logEntryId:t.logEntryId}}if(a){let t=Date.now(),i=6e4,o=this._rateLimitWindows.get(a);o||(o=[],this._rateLimitWindows.set(a,o));let u=t-i;for(;o.length>0&&o[0]<u;)o.shift();if(o.length>=60){let f=O();return C.warn({channelId:a,count:o.length},"Rate limited, not sending"),{success:!1,logEntryId:f,error:"rate_limited"}}o.push(t)}let E=x??(a?M(a)?.platform:void 0)??"unknown",v=m?y:$(y,E,s),e=O(),g={id:e,ruleId:void 0,taskId:s??void 0,status:"pending",target:a&&l?{type:"channel",channelId:a,chatId:l}:m?{type:"webhook",webhookUrl:m}:{type:"channel",channelId:a??"",chatId:l??""},content:v,attempts:0,createdAt:Date.now(),expiresAt:Date.now()+1440*60*1e3,source:"direct",messageType:d};k(g),r&&this._dedupCache.set(r,{logEntryId:e,timestamp:Date.now()});try{if(m){let t=await fetch(m,{method:"POST",body:JSON.stringify({result:y,taskId:s,timestamp:new Date().toISOString()}),signal:AbortSignal.timeout(1e4)});if(t.ok)return w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:s,target:g.target,status:"delivered",messageType:d}),{success:!0,logEntryId:e};{let i=`Webhook returned ${t.status}`;return h(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:s,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}else if(a&&l){let{getChannelManager:t}=await import("./channels-WFZAONF3.js"),i=t();if(!i){let f="ChannelManager not available";return h(e,"failed",f),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:s,target:g.target,status:"failed",error:f,messageType:d}),{success:!1,logEntryId:e,error:f}}let o={content:v,...S?{replyMarkup:S}:{}},u=await i.sendMessage(a,l,o);return u&&(this._recentlySentIds.add(u),setTimeout(()=>this._recentlySentIds.delete(u),300*1e3)),w(e),p.emit({type:"delivery_status_change",logEntryId:e,taskId:s,target:g.target,status:"delivered",messageType:d}),{success:!0,messageId:u??void 0,logEntryId:e}}else{let t="No channelId/chatId or webhookUrl provided";return h(e,"failed",t),r&&this._dedupCache.delete(r),{success:!1,logEntryId:e,error:t}}}catch(t){let i=t instanceof Error?t.message:String(t);return h(e,"failed",i),r&&this._dedupCache.delete(r),p.emit({type:"delivery_status_change",logEntryId:e,taskId:s,target:g.target,status:"failed",error:i,messageType:d}),{success:!1,logEntryId:e,error:i}}}},_=null;function L(){return _||(_=new I),_}function J(n){return L().isRecentlySent(n)}export{I as a,L as b,J as c};
|